diff --git a/desktop/internal/core/client.go b/desktop/internal/core/client.go index c40e2d3b2..260995d90 100644 --- a/desktop/internal/core/client.go +++ b/desktop/internal/core/client.go @@ -34,6 +34,9 @@ type requestEnvelope struct { GitExecution *gitExecution `json:"gitExecution,omitempty"` // Origin is the user action the request belongs to, nil for none (see Origin). Origin *requestOrigin `json:"origin,omitempty"` + // RemoteWorkspace is the host folder the request's workspace paths stand for, nil for a + // local request (WithRemoteWorkspace). + RemoteWorkspace *remoteWorkspace `json:"remoteWorkspace,omitempty"` } // gitExecution is the part of a request's Git policy the client sets (GitExecutionOptions in @@ -113,14 +116,19 @@ func (c *Client) execute(ctx context.Context, command string, payload, result an if payload == nil { payload = struct{}{} } + remote, binding, session, err := remoteWorkspaceRequest(ctx, command) + if err != nil { + return nil, err + } operationID := fmt.Sprintf("desktop-%d", nextCoreOperation.Add(1)) execution := gitExecutionOf(ctx, command) request, err := json.Marshal(requestEnvelope{ - OperationID: operationID, - Command: command, - Payload: payload, - GitExecution: execution, - Origin: requestOriginOf(ctx), + OperationID: operationID, + Command: command, + Payload: payload, + GitExecution: execution, + Origin: requestOriginOf(ctx), + RemoteWorkspace: remote, }) if err != nil { return nil, &Error{ @@ -146,12 +154,16 @@ func (c *Client) execute(ctx context.Context, command string, payload, result an observer = gitAuthenticationObserver(gitAuthenticationOf(ctx, command), returned, observer) } if observer == nil { - return nil, decodeResponse(ctx, command, call(ctx, operationID, request), result) + err = decodeResponse(ctx, command, call(ctx, operationID, request), result) + remoteWorkspaceAnswered(binding, session, err) + return nil, err } stop := watchCancellation(ctx, operationID) defer stop() response, observationErr := executeJSONWithEvents(request, observer) - return observationErr, decodeResponse(ctx, command, response, result) + err = decodeResponse(ctx, command, response, result) + remoteWorkspaceAnswered(binding, session, err) + return observationErr, err } // call sends one encoded request while a watcher forwards cancellation of ctx to the kernel. diff --git a/desktop/internal/core/errors.go b/desktop/internal/core/errors.go index 6da878e48..6bb752765 100644 --- a/desktop/internal/core/errors.go +++ b/desktop/internal/core/errors.go @@ -68,6 +68,10 @@ const ( CodeTimedOut ErrorCode = "timed_out" // CodeConnectionClosed means a long-lived connection named by the request is closed. CodeConnectionClosed ErrorCode = "connection_closed" + // CodeRemoteServerInvalid means the remote server build for the host's platform could not be + // read, or its SHA-256 is not the one the application's manifest names; nothing was sent to + // the host. + CodeRemoteServerInvalid ErrorCode = "remote_server_invalid" // CodeUnknown means the failure fits no more specific category. CodeUnknown ErrorCode = "unknown" ) diff --git a/desktop/internal/core/remote.go b/desktop/internal/core/remote.go index 04011af8a..8a9898bba 100644 --- a/desktop/internal/core/remote.go +++ b/desktop/internal/core/remote.go @@ -248,23 +248,10 @@ type RemoteProbeResult struct { // cancelled at once. Core bounds a probe, answers included, to five minutes. The probe changes // nothing, so an observation failure is reported only when the request itself succeeded. func (c *Client) RemoteProbe(ctx context.Context, connection SSHConnection) (RemoteProbeResult, error) { - prompt, _ := ctx.Value(gitAuthenticationKey{}).(func(GitAuthChallenge)) - if prompt == nil { - prompt = func(challenge GitAuthChallenge) { - // The answer must not wait on the request's goroutine, which delivers the event. - go func() { _, _ = c.RemoteAuthRespond(context.Background(), challenge.RequestID, nil) }() - } - } - returned := make(chan struct{}) - defer close(returned) - observer := gitAuthenticationObserver(func(challenge GitAuthChallenge) { - challenge.Remote = true - prompt(challenge) - }, returned, nil) var result RemoteProbeResult - observationErr, err := c.ExecuteWithEvents(ctx, "remote.probe", struct { + observationErr, err := c.executeRemoteWithPrompts(ctx, "remote.probe", struct { Connection SSHConnection `json:"connection"` - }{connection}, &result, observer) + }{connection}, &result) if err != nil { return RemoteProbeResult{}, err } diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go new file mode 100644 index 000000000..377b90d9b --- /dev/null +++ b/desktop/internal/core/remote_session.go @@ -0,0 +1,323 @@ +package core + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync/atomic" +) + +// Remote development sessions: the connections Core keeps open to a host after remote.connect, +// the requests that address one by its session id, and the remote workspace a context binds its +// requests to (design R0, S16, S17). Core owns the OpenSSH process tree of each session and ends +// it on remote.disconnect, remote.closeAll or its own exit. + +// RemoteServerBuild is one remote server build the application ships: the Rust target it runs +// on, the absolute path of the read-only file, and the SHA-256 the application's manifest names +// for it. Core checks the bytes it sends against SHA256, never against a hash of the file. +type RemoteServerBuild struct { + Target string `json:"target"` + Path string `json:"path"` + SHA256 string `json:"sha256"` +} + +// RemoteConnectRequest opens a session to the host of Connection, installing the server build +// for the host's platform when the host does not already run that exact build. +type RemoteConnectRequest struct { + Connection SSHConnection `json:"connection"` + // Servers are the builds the application ships; Core picks the one for the host. + Servers []RemoteServerBuild `json:"servers"` + // ServerVersion is the version of the shipped builds. + ServerVersion string `json:"serverVersion"` + // InstallRoot is where the host keeps installed servers; empty is $HOME/.lithe-server. + InstallRoot string `json:"installRoot,omitempty"` +} + +// RemoteSession is a session remote.connect opened. +type RemoteSession struct { + // ID names the session in every later request. + ID string `json:"id"` + // Uploaded says whether this connection sent the server to the host. + Uploaded bool `json:"uploaded"` + // HostName is the host's own name, for display. + HostName string `json:"hostName"` + // UserName is the account the server runs as, empty when unknown. + UserName string `json:"userName"` + // HomeDirectory is that account's home directory, empty when unknown. + HomeDirectory string `json:"homeDirectory"` +} + +// RemoteConnectResult is the outcome of remote.connect. Session is set only when Status is +// RemoteProbeConnected; the other statuses mean the same as for a probe. +type RemoteConnectResult struct { + Status RemoteProbeStatus `json:"status"` + Session *RemoteSession `json:"session"` + Host *RemoteProbedHost `json:"host"` + // Diagnostics is the redacted end of OpenSSH's standard error. It is upstream text, shown + // as it is, and may still name the host, so it is never logged. + Diagnostics string `json:"diagnostics"` +} + +// RemoteConnect opens a session as request asks. Questions OpenSSH asks reach the prompt +// WithGitAuthentication put in ctx, as for RemoteProbe. Core bounds an attempt, answers +// included, to five minutes. Failures are CodeInvalidRequest before OpenSSH starts, +// CodeRuntimeMissing without ssh, CodeRemoteServerInvalid when the build cannot be read or +// differs from its SHA-256, and the context's error when ctx ends. A session whose events could +// not all be observed is closed again and the observation failure returned: the user may not +// have seen every question it asked. +func (c *Client) RemoteConnect(ctx context.Context, request RemoteConnectRequest) (RemoteConnectResult, error) { + request.Servers = nonNil(request.Servers) + var result RemoteConnectResult + observationErr, err := c.executeRemoteWithPrompts(ctx, "remote.connect", request, &result) + if err != nil { + return RemoteConnectResult{}, err + } + if observationErr != nil { + if result.Session != nil { + _, _ = c.RemoteDisconnect(context.Background(), result.Session.ID) + } + return RemoteConnectResult{}, observationErr + } + return result, nil +} + +// 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. +func (c *Client) executeRemoteWithPrompts(ctx context.Context, command string, payload, result any) (observationErr, err error) { + prompt, _ := ctx.Value(gitAuthenticationKey{}).(func(GitAuthChallenge)) + if prompt == nil { + prompt = func(challenge GitAuthChallenge) { + // The answer must not wait on the request's goroutine, which delivers the event. + go func() { _, _ = c.RemoteAuthRespond(context.Background(), challenge.RequestID, nil) }() + } + } + returned := make(chan struct{}) + defer close(returned) + observer := gitAuthenticationObserver(func(challenge GitAuthChallenge) { + challenge.Remote = true + prompt(challenge) + }, returned, nil) + return c.ExecuteWithEvents(ctx, command, payload, result, observer) +} + +// RemoteDisconnect ends the session sessionID and its OpenSSH process tree. closed is false when +// Core no longer knew the session. +func (c *Client) RemoteDisconnect(ctx context.Context, sessionID string) (closed bool, err error) { + var result struct { + Closed bool `json:"closed"` + } + err = c.Execute(ctx, "remote.disconnect", struct { + SessionID string `json:"sessionId"` + }{sessionID}, &result) + return result.Closed, err +} + +// RemoteCloseAll ends every session Core keeps open and returns how many it closed. The +// application calls it once, while quitting: exiting without it can leave OpenSSH and the remote +// server running. Afterwards Core refuses every remote.connect of the process with +// CodeCancelled, so closing a window or a project must use RemoteDisconnect instead. +func (c *Client) RemoteCloseAll(ctx context.Context) (closed int, err error) { + var result struct { + Closed int `json:"closed"` + } + err = c.Execute(ctx, "remote.closeAll", nil, &result) + return result.Closed, err +} + +// RemoteFileKind is the kind of a host entry itself; links are never followed. +type RemoteFileKind string + +const ( + RemoteFileKindFile RemoteFileKind = "file" + RemoteFileKindDirectory RemoteFileKind = "directory" + RemoteFileKindSymlink RemoteFileKind = "symlink" + // RemoteFileKindOther is a socket, a device or a FIFO. + RemoteFileKindOther RemoteFileKind = "other" +) + +// RemoteFileMetadata is the metadata of a host path itself. +type RemoteFileMetadata struct { + Kind RemoteFileKind `json:"kind"` + // Size is in bytes; for a link, the length of its target text. + Size uint64 `json:"size"` + // ModifiedMs is milliseconds since the Unix epoch, nil when the host did not report it. + ModifiedMs *int64 `json:"modifiedMs"` + // Readonly is true when no write permission bit is set. + Readonly bool `json:"readonly"` + // Mode is the permission bits. + Mode uint32 `json:"mode"` + // SymlinkTarget is a link's target as stored, when it is valid UTF-8. + SymlinkTarget string `json:"symlinkTarget,omitempty"` + // SymlinkTargetKind is the kind of what a link resolves to; empty for a dangling link. + SymlinkTargetKind RemoteFileKind `json:"symlinkTargetKind,omitempty"` +} + +// IsDirectory reports whether the entry is a directory or a link that resolves to one. +func (m RemoteFileMetadata) IsDirectory() bool { + return m.Kind == RemoteFileKindDirectory || + (m.Kind == RemoteFileKindSymlink && m.SymlinkTargetKind == RemoteFileKindDirectory) +} + +// RemoteDirectoryEntry is one entry of a host directory. +type RemoteDirectoryEntry struct { + Name string `json:"name"` + Metadata RemoteFileMetadata `json:"metadata"` +} + +// RemoteDirectory is a host directory's listing. +type RemoteDirectory struct { + // Entries are sorted by the byte order of Name. + Entries []RemoteDirectoryEntry `json:"entries"` + // SkippedNonUTF8 counts the entries whose names are not UTF-8; the protocol cannot name them. + SkippedNonUTF8 uint32 `json:"skippedNonUtf8"` +} + +// RemoteReadDir lists the absolute host directory path over the session sessionID. A broken or +// unknown session fails with CodeConnectionClosed, a missing path with CodeWorkspaceNotFound +// and a denied one with CodePermissionDenied. +func (c *Client) RemoteReadDir(ctx context.Context, sessionID, path string) (RemoteDirectory, error) { + var result RemoteDirectory + err := c.Execute(ctx, "remote.readDir", struct { + SessionID string `json:"sessionId"` + Path string `json:"path"` + }{sessionID, path}, &result) + return result, err +} + +// RemoteHostRequest performs the finite host method with params over the session sessionID and +// decodes its result into result, which may be nil. Core accepts the filesystem, environment +// and port queries, server.state and the controls of existing processes and terminals; a +// method that would create a resource is CodeInvalidRequest. A broken or unknown session fails +// with CodeConnectionClosed. +func (c *Client) RemoteHostRequest(ctx context.Context, sessionID, method string, params, result any) error { + if params == nil { + params = struct{}{} + } + return c.Execute(ctx, "remote.hostRequest", struct { + SessionID string `json:"sessionId"` + Method string `json:"method"` + Params any `json:"params"` + }{sessionID, method, params}, result) +} + +// RemoteServerState asks the server of sessionID what still runs; the connection's heartbeat +// uses it, since it is the cheapest request that reaches the server. +func (c *Client) RemoteServerState(ctx context.Context, sessionID string) error { + var ignored json.RawMessage + return c.RemoteHostRequest(ctx, sessionID, "server.state", nil, &ignored) +} + +// RemoteWorkspace binds the requests of a context (WithRemoteWorkspace) to a folder on a +// connected host. LocalRoot is the placeholder the window shows as the project's root and +// RemoteRoot the host folder it stands for; Core translates every schema-owned path between +// them and never reads or writes the placeholder. The session is swapped as the connection is +// lost and opened again, and is safe to change from any goroutine. +type RemoteWorkspace struct { + localRoot string + remoteRoot string + session atomic.Pointer[string] + lost func(sessionID string) +} + +// NewRemoteWorkspace returns a binding of localRoot to the host folder remoteRoot with no +// session yet. lost, when not nil, runs on the request's goroutine the first time a request of +// the current session fails with CodeConnectionClosed; the session is then already detached. +func NewRemoteWorkspace(localRoot, remoteRoot string, lost func(sessionID string)) *RemoteWorkspace { + return &RemoteWorkspace{localRoot: localRoot, remoteRoot: remoteRoot, lost: lost} +} + +// LocalRoot is the placeholder folder of the binding. +func (w *RemoteWorkspace) LocalRoot() string { return w.localRoot } + +// RemoteRoot is the host folder of the binding. +func (w *RemoteWorkspace) RemoteRoot() string { return w.remoteRoot } + +// Attach makes sessionID the session the binding's requests go over. +func (w *RemoteWorkspace) Attach(sessionID string) { w.session.Store(&sessionID) } + +// Detach leaves the binding without a session and returns the one it had, empty for none. +func (w *RemoteWorkspace) Detach() string { + if previous := w.session.Swap(nil); previous != nil { + return *previous + } + return "" +} + +// SessionID is the session the binding's requests go over, empty while it has none. +func (w *RemoteWorkspace) SessionID() string { + if current := w.session.Load(); current != nil { + return *current + } + return "" +} + +type remoteWorkspaceKey struct{} + +// WithRemoteWorkspace returns a context whose requests run on the host of binding. Every +// request of the context carries the binding except the remote.* commands, which name their +// session themselves; Core refuses a command that has no remote adapter with +// CodeNotSupported, so nothing of the context falls back to the local placeholder. While the +// binding has no session a request fails at once with CodeConnectionClosed and Core never sees +// it. +func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context.Context { + if binding == nil { + return ctx + } + return context.WithValue(ctx, remoteWorkspaceKey{}, binding) +} + +// RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context. +func RemoteWorkspaceOf(ctx context.Context) *RemoteWorkspace { + binding, _ := ctx.Value(remoteWorkspaceKey{}).(*RemoteWorkspace) + return binding +} + +// remoteWorkspace is the request's remote workspace on the wire (Workspace in the Rust +// protocol). +type remoteWorkspace struct { + SessionID string `json:"sessionId"` + LocalRoot string `json:"localRoot"` + RemoteRoot string `json:"remoteRoot"` +} + +// remoteWorkspaceRequest is what a request of ctx sends as its remote workspace: nil for a +// local context and for a remote.* command, the binding's session and roots otherwise. session +// is the pointer the request read, so a later loss detaches only that session. +func remoteWorkspaceRequest(ctx context.Context, command string) (wire *remoteWorkspace, binding *RemoteWorkspace, session *string, err error) { + binding = RemoteWorkspaceOf(ctx) + if binding == nil || isRemoteSessionCommand(command) { + return nil, nil, nil, nil + } + session = binding.session.Load() + if session == nil { + return nil, nil, nil, &Error{ + Command: command, + Code: CodeConnectionClosed, + Message: "the remote workspace is not connected", + } + } + return &remoteWorkspace{SessionID: *session, LocalRoot: binding.localRoot, RemoteRoot: binding.remoteRoot}, binding, session, nil +} + +// isRemoteSessionCommand reports whether command addresses a session by its id rather than +// through the request's remote workspace. +func isRemoteSessionCommand(command string) bool { + return strings.HasPrefix(command, "remote.") +} + +// remoteWorkspaceAnswered detaches session from binding when the request failed because its +// connection closed, and tells the binding's owner once. +func remoteWorkspaceAnswered(binding *RemoteWorkspace, session *string, err error) { + if binding == nil || session == nil { + return + } + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + return + } + if binding.session.CompareAndSwap(session, nil) && binding.lost != nil { + binding.lost(*session) + } +} diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go new file mode 100644 index 000000000..2d75820a9 --- /dev/null +++ b/desktop/internal/core/remote_session_test.go @@ -0,0 +1,200 @@ +package core + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "strings" + "sync/atomic" + "testing" +) + +// shippedTargets are the server builds the application ships; the paths do not exist, so a host +// that has a build reads none and Core sends nothing. +var shippedTargets = []RemoteServerBuild{ + {Target: "x86_64-unknown-linux-musl", Path: "/nonexistent/lithe-remote-server-x86_64", SHA256: strings.Repeat("a", 64)}, + {Target: "aarch64-unknown-linux-musl", Path: "/nonexistent/lithe-remote-server-aarch64", SHA256: strings.Repeat("b", 64)}, +} + +// A request of a remote workspace context carries the binding's session and roots, a remote.* +// command never does, and a binding without a session fails before Core sees the request. +func TestRemoteWorkspaceRequestsCarryTheBindingExceptSessionCommands(t *testing.T) { + binding := NewRemoteWorkspace("/cache/remote/1/abc/repo", "/srv/repo", nil) + ctx := WithRemoteWorkspace(context.Background(), binding) + + if wire, _, _, err := remoteWorkspaceRequest(context.Background(), "file.read"); wire != nil || err != nil { + t.Fatalf("a local context sent %+v, %v", wire, err) + } + _, _, _, err := remoteWorkspaceRequest(ctx, "file.read") + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("a binding without a session = %v, want connection_closed", err) + } + + binding.Attach("session-7") + wire, owner, session, err := remoteWorkspaceRequest(ctx, "file.read") + if err != nil || owner != binding || session == nil || *session != "session-7" { + t.Fatalf("request = %+v, %v, %v", wire, session, err) + } + encoded, err := json.Marshal(requestEnvelope{Command: "file.read", Payload: struct{}{}, RemoteWorkspace: wire}) + if err != nil { + t.Fatal(err) + } + if want := `"remoteWorkspace":{"sessionId":"session-7","localRoot":"/cache/remote/1/abc/repo","remoteRoot":"/srv/repo"}`; !strings.Contains(string(encoded), want) { + t.Fatalf("envelope = %s, want it to contain %s", encoded, want) + } + for _, command := range []string{"remote.readDir", "remote.disconnect", "remote.hostRequest"} { + if wire, _, _, err := remoteWorkspaceRequest(ctx, command); wire != nil || err != nil { + t.Errorf("%s sent %+v, %v", command, wire, err) + } + } + if got := binding.Detach(); got != "session-7" || binding.SessionID() != "" { + t.Fatalf("Detach = %q, then SessionID = %q", got, binding.SessionID()) + } +} + +// With the real kernel: a command without a remote adapter is refused instead of reading the +// placeholder, and a command with one over a session Core does not know reports the loss once +// and detaches the binding, so the next request fails without reaching Core. +func TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding(t *testing.T) { + client := NewClient() + var lost atomic.Int32 + var lostSession atomic.Pointer[string] + binding := NewRemoteWorkspace(t.TempDir(), "/srv/repo", func(sessionID string) { + lost.Add(1) + lostSession.Store(&sessionID) + }) + binding.Attach("no-such-session") + ctx := WithRemoteWorkspace(testContext(t), binding) + + err := client.Execute(ctx, "core.ping", nil, nil) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeNotSupported { + t.Fatalf("core.ping in a remote workspace = %v, want not_supported", err) + } + if lost.Load() != 0 || binding.SessionID() != "no-such-session" { + t.Fatal("a refused command detached the session") + } + + _, err = client.ListDirectories(ctx, binding.LocalRoot(), []string{""}) + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("listing over an unknown session = %v, want connection_closed", err) + } + if lost.Load() != 1 || lostSession.Load() == nil || *lostSession.Load() != "no-such-session" || binding.SessionID() != "" { + t.Fatalf("lost %d times, binding session %q", lost.Load(), binding.SessionID()) + } + _, err = client.ListDirectories(ctx, binding.LocalRoot(), []string{""}) + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed || lost.Load() != 1 { + t.Fatalf("after the loss = %v and lost %d times, want a local connection_closed", err, lost.Load()) + } +} + +// The session commands answer for a session Core does not know: nothing to close, and a broken +// connection for a listing or a host request. +func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) { + client := NewClient() + ctx := testContext(t) + closed, err := client.RemoteDisconnect(ctx, "no-such-session") + if err != nil || closed { + t.Fatalf("disconnect = %v, %v, want nothing closed", closed, err) + } + var coreErr *Error + if _, err := client.RemoteReadDir(ctx, "no-such-session", "/"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("readDir = %v, want connection_closed", err) + } + if err := client.RemoteServerState(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("server.state = %v, want connection_closed", err) + } +} + +// Closing every session ends the process's remote development: Core then refuses to connect. +// It runs in a child process, since the refusal lasts as long as the process. +func TestRemoteCloseAllRefusesLaterConnections(t *testing.T) { + if os.Getenv("LITHE_TEST_REMOTE_CLOSE_ALL") == "1" { + client := NewClient() + ctx := testContext(t) + if closed, err := client.RemoteCloseAll(ctx); err != nil || closed != 0 { + t.Fatalf("closeAll = %d, %v, want nothing to close", closed, err) + } + _, err := client.RemoteConnect(ctx, RemoteConnectRequest{ + Connection: SSHConnection{Host: "devbox"}, + Servers: shippedTargets, + ServerVersion: "0.0.0-test", + }) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeCancelled { + t.Fatalf("connect after closeAll = %v, want cancelled", err) + } + return + } + child := exec.CommandContext(testContext(t), os.Args[0], "-test.run=^TestRemoteCloseAllRefusesLaterConnections$", "-test.count=1") + child.Env = append(os.Environ(), "LITHE_TEST_REMOTE_CLOSE_ALL=1") + if output, err := child.CombinedOutput(); err != nil { + t.Fatalf("child: %v\n%s", err, output) + } +} + +// Connecting relays the password question like a probe. A host without a shipped build is +// unsupportedPlatform and gets nothing; a host with one fails with remote_server_invalid, since +// the shipped file cannot be read, and is sent nothing either. +func TestRemoteConnectAsksThroughTheHostAndSendsNoUnreadableBuild(t *testing.T) { + standInSSH(t) + client := NewClient() + var asked atomic.Int32 + prompt := func(challenge GitAuthChallenge) { + asked.Add(1) + go func() { + _, _ = client.RemoteAuthRespond(context.Background(), challenge.RequestID, answerText("s3cret")) + }() + } + connection := SSHConnection{Host: "devbox", User: "dev"} + var probe RemoteProbeResult + var probeErr error + finishesWithin(t, "probe", testDeadline, func() { + probe, probeErr = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), connection) + }) + if probeErr != nil || probe.Host == nil { + t.Fatalf("probe = %+v, %v", probe, probeErr) + } + var result RemoteConnectResult + var err error + finishesWithin(t, "connect", testDeadline, func() { + result, err = client.RemoteConnect(WithGitAuthentication(testContext(t), prompt), RemoteConnectRequest{ + Connection: connection, + Servers: shippedTargets, + ServerVersion: "0.0.0-test", + }) + }) + if asked.Load() < 2 { + t.Fatalf("asked %d times, want the probe's and the connection's password questions; connect = %+v, %v", asked.Load(), result, err) + } + shipped := false + for _, build := range shippedTargets { + shipped = shipped || build.Target == probe.Host.ServerTarget + } + if !shipped { + if err != nil || result.Status != RemoteProbeUnsupportedPlatform || result.Session != nil { + t.Fatalf("connect = %+v, %v, want unsupportedPlatform without a session", result, err) + } + return + } + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeRemoteServerInvalid || strings.Contains(coreErr.Details, "/nonexistent") { + t.Fatalf("connect = %+v, %v, want remote_server_invalid without the path", result, err) + } +} + +// A malformed build is refused before OpenSSH starts. +func TestRemoteConnectRefusesAMalformedBuildBeforeConnecting(t *testing.T) { + _, err := NewClient().RemoteConnect(testContext(t), RemoteConnectRequest{ + Connection: SSHConnection{Host: "devbox"}, + Servers: []RemoteServerBuild{{Target: "x86_64-unknown-linux-musl", Path: "/nonexistent", SHA256: "not-hex"}}, + ServerVersion: "0.0.0-test", + }) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeInvalidRequest { + t.Fatalf("connect = %v, want invalid_request", err) + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index e734bdfc8..0e6d8c61c 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1575,6 +1575,26 @@ 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.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}", + "desktop.remote.browse.denied": "The host account is not allowed to open this folder.", + "desktop.remote.browse.empty": "This folder has no subfolders.", + "desktop.remote.browse.folders": "Folders", + "desktop.remote.browse.lost": "The connection to the host closed. Connect again to choose a folder.", + "desktop.remote.browse.notFound": "The folder does not exist on the host.", + "desktop.remote.browse.open": "Open", + "desktop.remote.browse.openFailed": "Cannot open the folder: {reason}", + "desktop.remote.browse.opening": "Opening…", + "desktop.remote.browse.path": "Folder path", + "desktop.remote.browse.pathInvalid": "Enter an absolute path of the host, such as /home/user/project or ~/project.", + "desktop.remote.browse.pathPlaceholder": "/home/user/project or ~/project", + "desktop.remote.browse.readFailed": "Cannot list the folder: {reason}", + "desktop.remote.browse.recent": "Recent Folders", + "desktop.remote.browse.refresh": "Refresh", + "desktop.remote.browse.skipped": "Entries not listed because they could not be read: {count}", + "desktop.remote.browse.target": "Opens {path}", + "desktop.remote.browse.up": "Parent Folder", "desktop.remote.cancel": "Cancel", "desktop.remote.choose": "Choose File…", "desktop.remote.chooseFailed": "Cannot open the file picker: {reason}", @@ -1589,6 +1609,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.color.yellow": "Yellow", "desktop.remote.colorHelp": "Marks the connection in the list, for example to tell production from test hosts. Kept on this computer only.", "desktop.remote.conflict": "The saved connections changed elsewhere and were read again. Save once more.", + "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.connecting": "Connecting… OpenSSH may ask for a password or to confirm the host key.", "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}”?", @@ -1657,6 +1681,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.saved": "Saved Connections", "desktop.remote.saving": "Saving…", "desktop.remote.settings": "Connection Settings", + "desktop.remote.status.connected": "SSH: {name}", + "desktop.remote.status.disconnect": "Disconnect and Close", + "desktop.remote.status.disconnected": "SSH: {name} · Disconnected", + "desktop.remote.status.label": "Remote Connection", + "desktop.remote.status.latency": "SSH: {name} · {ms} ms", + "desktop.remote.status.reconnect": "Reconnect", + "desktop.remote.status.reconnecting": "SSH: {name} · Reconnecting…", + "desktop.remote.status.unresponsive": "SSH: {name} · Not responding", "desktop.remote.stop": "Stop", "desktop.remote.storageHelp": "Kept on this computer in {path}. Passwords and the contents of private keys are never saved.", "desktop.remote.test": "Test Connection", @@ -1670,6 +1702,9 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.user": "User", "desktop.remote.userPlaceholder": "Auto (SSH config, otherwise your local user name)", "desktop.remote.via": "via {jump}", + "desktop.remote.workspace.banner": "This is a remote workspace. The Project tool window lists the host's files; editing, terminals, search, Git and running do not work here yet.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. The Project tool window lists the host's files.", + "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "desktop.remoteAuth.failed": "Cannot pass the answer to SSH: {reason}", "desktop.remoteAuth.refused": "SSH did not take the answer: it may be at most 8192 bytes and may not contain a line break. The question was cancelled.", "desktop.remoteAuth.secretHint": "The answer goes only to this SSH connection. Lithe does not keep it.", @@ -5008,6 +5043,26 @@ 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.browse.anchorUnusable": "无法准备代表远程工作区的本地文件夹:{path}", + "desktop.remote.browse.back": "返回", + "desktop.remote.browse.connected": "已连接到 {name}", + "desktop.remote.browse.denied": "主机账户无权打开此文件夹。", + "desktop.remote.browse.empty": "此文件夹没有子文件夹。", + "desktop.remote.browse.folders": "文件夹", + "desktop.remote.browse.lost": "与主机的连接已断开。请重新连接后再选择文件夹。", + "desktop.remote.browse.notFound": "主机上不存在此文件夹。", + "desktop.remote.browse.open": "打开", + "desktop.remote.browse.openFailed": "无法打开文件夹:{reason}", + "desktop.remote.browse.opening": "正在打开…", + "desktop.remote.browse.path": "文件夹路径", + "desktop.remote.browse.pathInvalid": "请输入主机上的绝对路径,例如 /home/user/project 或 ~/project。", + "desktop.remote.browse.pathPlaceholder": "/home/user/project 或 ~/project", + "desktop.remote.browse.readFailed": "无法列出文件夹:{reason}", + "desktop.remote.browse.recent": "最近的文件夹", + "desktop.remote.browse.refresh": "刷新", + "desktop.remote.browse.skipped": "有 {count} 个条目无法读取,未列出。", + "desktop.remote.browse.target": "将打开 {path}", + "desktop.remote.browse.up": "上级文件夹", "desktop.remote.cancel": "取消", "desktop.remote.choose": "选择文件…", "desktop.remote.chooseFailed": "无法打开文件选择器:{reason}", @@ -5022,6 +5077,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.color.yellow": "黄色", "desktop.remote.colorHelp": "在列表中标记这个连接,例如区分生产和测试主机。只保存在本机。", "desktop.remote.conflict": "已保存的连接在别处被修改过,已重新读取,请再保存一次。", + "desktop.remote.connect": "连接", + "desktop.remote.connect.notBundled": "此版本的 Lithe 未包含适用于该主机的远端服务,无法打开主机上的文件夹。", + "desktop.remote.connect.serverInvalid": "远端服务未通过完整性校验,没有启动。请重新安装 Lithe 后再试。", + "desktop.remote.connecting": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", "desktop.remote.damaged": "无法读取 {path} 里保存的连接。修复或删除这个文件之前不能保存。", "desktop.remote.delete": "删除", "desktop.remote.deleteConfirm": "删除“{name}”?", @@ -5090,6 +5149,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.saved": "已保存的连接", "desktop.remote.saving": "正在保存…", "desktop.remote.settings": "连接设置", + "desktop.remote.status.connected": "SSH: {name}", + "desktop.remote.status.disconnect": "断开并关闭", + "desktop.remote.status.disconnected": "SSH: {name} · 已断开", + "desktop.remote.status.label": "远程连接", + "desktop.remote.status.latency": "SSH: {name} · {ms} 毫秒", + "desktop.remote.status.reconnect": "重新连接", + "desktop.remote.status.reconnecting": "SSH: {name} · 正在重新连接…", + "desktop.remote.status.unresponsive": "SSH: {name} · 无响应", "desktop.remote.stop": "停止", "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", "desktop.remote.test": "测试连接", @@ -5103,6 +5170,9 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.user": "用户名", "desktop.remote.userPlaceholder": "自动(SSH 配置,否则本机用户名)", "desktop.remote.via": "经 {jump}", + "desktop.remote.workspace.banner": "这是远程工作区。项目工具窗口可以浏览主机上的文件;编辑、终端、搜索、Git 和运行暂不可用。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,项目工具窗口可以浏览主机上的文件。", + "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}", "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", "desktop.remoteAuth.secretHint": "回答只交给这次 SSH 连接,Lithe 不会保存。", diff --git a/desktop/internal/remoteplaceholder/remoteplaceholder.go b/desktop/internal/remoteplaceholder/remoteplaceholder.go new file mode 100644 index 000000000..094d0f6a8 --- /dev/null +++ b/desktop/internal/remoteplaceholder/remoteplaceholder.go @@ -0,0 +1,136 @@ +// Package remoteplaceholder gives a remote workspace its local root: the path that names the +// workspace in Core's requests and in the window, and that the local file system can never open, +// list or create (#2231). +// +// Core reads and writes below a remote workspace's local root on the host, and refuses every +// command that has no remote adapter instead of touching the local path. The client still calls the +// operating system with project paths in places that do not go through Core. Every placeholder +// therefore lies below the anchor, a regular read-only file in the user's cache directory, and not +// below a directory. A local call fails with ENOTDIR (ERROR_PATH_NOT_FOUND on Windows) instead of +// reading or creating a local folder that only looks like the project: os.MkdirAll, os.Create and +// os.ReadDir below a file all fail. Core maps a host path outside the workspace to a sibling of the +// local root (.lithe-remote-host), which lies below the anchor too. +// +// The anchor holds no data and is never deleted. It is created on first use and checked on every +// use: a directory, a link or any other kind of file at its path is refused, since a local folder +// below it could be created. +package remoteplaceholder + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + "unicode" +) + +// AnchorName is the anchor's file name in the client's cache directory. +const AnchorName = "remote-workspaces" + +// ErrAnchorUnusable means something other than a regular file is at the anchor's path, so a local +// folder could be created below it; no placeholder is given out until it is removed. +var ErrAnchorUnusable = errors.New("remoteplaceholder: the anchor is not a regular file") + +// DefaultAnchor is the anchor of the client: Lithe/remote-workspaces in the user's cache directory. +func DefaultAnchor() (string, error) { + base, err := os.UserCacheDir() + if err != nil { + return "", fmt.Errorf("remoteplaceholder: locate the cache directory: %w", err) + } + return filepath.Join(base, "Lithe", AnchorName), nil +} + +// Ensure makes sure the anchor is a regular file, creating an empty read-only one when nothing is +// at its path. A link, a directory or any other kind of file there fails with ErrAnchorUnusable +// and is left as it is. +func Ensure(anchor string) error { + info, err := os.Lstat(anchor) + if errors.Is(err, fs.ErrNotExist) { + if err := os.MkdirAll(filepath.Dir(anchor), 0o700); err != nil { + return fmt.Errorf("remoteplaceholder: create the cache directory: %w", err) + } + file, err := os.OpenFile(anchor, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o444) + if err == nil { + return file.Close() + } + if !errors.Is(err, fs.ErrExist) { + return fmt.Errorf("remoteplaceholder: create the anchor: %w", err) + } + // Another process created it first: check what it created. + info, err = os.Lstat(anchor) + } + if err != nil { + return fmt.Errorf("remoteplaceholder: inspect the anchor: %w", err) + } + if !info.Mode().IsRegular() { + return ErrAnchorUnusable + } + return nil +} + +// Root is the local root of the remote workspace whose host folder is remoteRoot, reached over the +// saved connection connectionID: anchor//. The key tells apart the same folder over two +// connections and two folders of one name; the name is the folder's own, made safe for every local +// file system, so the window and the tree show it. Opening the same folder over the same +// connection again gives the same root, which is how the window finds it already open. +func Root(anchor, connectionID, remoteRoot string) string { + sum := sha256.Sum256([]byte(connectionID + "\x00" + remoteRoot)) + return filepath.Join(anchor, hex.EncodeToString(sum[:8]), localName(remoteRoot)) +} + +// maxNameRunes bounds the local name, which only labels the root. +const maxNameRunes = 64 + +// localName is the final element of the POSIX path remoteRoot as a file name every local file +// system accepts: "root" for the host's root, letters, digits and "._-" kept, every other +// character replaced by "_". +func localName(remoteRoot string) string { + base := path.Base(path.Clean("/" + strings.TrimLeft(remoteRoot, "/"))) + if base == "/" { + return "root" + } + var name strings.Builder + count := 0 + for _, r := range base { + if count == maxNameRunes { + break + } + count++ + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '.' || r == '_' || r == '-' { + name.WriteRune(r) + continue + } + name.WriteByte('_') + } + // Windows drops trailing dots, and "." and ".." are no names at all. + text := strings.TrimRight(name.String(), ".") + if text == "" { + return "folder" + } + if reservedOnWindows(text) { + return "_" + text + } + return text +} + +// reservedOnWindows says whether name, before any extension, is a device name Windows reserves in +// every directory. +func reservedOnWindows(name string) bool { + stem := strings.ToUpper(name) + if dot := strings.IndexByte(stem, '.'); dot >= 0 { + stem = stem[:dot] + } + switch stem { + case "CON", "PRN", "AUX", "NUL": + return true + } + if len(stem) == 4 && (strings.HasPrefix(stem, "COM") || strings.HasPrefix(stem, "LPT")) { + return stem[3] >= '0' && stem[3] <= '9' + } + return false +} diff --git a/desktop/internal/remoteplaceholder/remoteplaceholder_test.go b/desktop/internal/remoteplaceholder/remoteplaceholder_test.go new file mode 100644 index 000000000..fc98b7e40 --- /dev/null +++ b/desktop/internal/remoteplaceholder/remoteplaceholder_test.go @@ -0,0 +1,106 @@ +package remoteplaceholder + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// Ensure creates an empty read-only anchor, keeps it on the next call, and a placeholder below it +// can be neither listed, created nor written by the local file system. +func TestPlaceholdersCannotBeUsedLocally(t *testing.T) { + anchor := filepath.Join(t.TempDir(), "cache", AnchorName) + if err := Ensure(anchor); err != nil { + t.Fatalf("create the anchor: %v", err) + } + info, err := os.Lstat(anchor) + if err != nil || !info.Mode().IsRegular() || info.Size() != 0 { + t.Fatalf("anchor = %v, %v, want an empty regular file", info, err) + } + if runtime.GOOS != "windows" && info.Mode().Perm()&0o222 != 0 { + t.Fatalf("anchor mode = %v, want read-only", info.Mode().Perm()) + } + if err := Ensure(anchor); err != nil { + t.Fatalf("an existing anchor: %v", err) + } + + root := Root(anchor, "connection-1", "/home/dev/repo") + if _, err := os.ReadDir(root); err == nil { + t.Fatal("listed a placeholder") + } + if err := os.MkdirAll(filepath.Join(root, "src"), 0o755); err == nil { + t.Fatal("created a folder below a placeholder") + } + if err := os.WriteFile(filepath.Join(root, "main.go"), []byte("package main"), 0o644); err == nil { + t.Fatal("wrote a file below a placeholder") + } + host := root + ".lithe-remote-host" + if err := os.MkdirAll(host, 0o755); err == nil { + t.Fatal("created the host-path sibling of a placeholder") + } + if entries, err := os.ReadDir(filepath.Dir(anchor)); err != nil || len(entries) != 1 { + t.Fatalf("cache directory has %d entries, %v; want only the anchor", len(entries), err) + } +} + +// Anything but a regular file at the anchor's path is refused and left there. +func TestEnsureRefusesAnAnchorThatIsNoRegularFile(t *testing.T) { + directory := filepath.Join(t.TempDir(), AnchorName) + if err := os.Mkdir(directory, 0o700); err != nil { + t.Fatal(err) + } + if err := Ensure(directory); !errors.Is(err, ErrAnchorUnusable) { + t.Fatalf("a directory = %v, want ErrAnchorUnusable", err) + } + if info, err := os.Lstat(directory); err != nil || !info.IsDir() { + t.Fatal("the directory was not left as it was") + } + + if runtime.GOOS == "windows" { + // Creating a link needs a privilege the Windows runner may not grant. + return + } + link := filepath.Join(t.TempDir(), AnchorName) + if err := os.Symlink(directory, link); err != nil { + t.Fatal(err) + } + if err := Ensure(link); !errors.Is(err, ErrAnchorUnusable) { + t.Fatalf("a link to a directory = %v, want ErrAnchorUnusable", err) + } +} + +// A root is the same for the same folder over the same connection, different otherwise, and its +// name is the folder's name in a form every local file system accepts. +func TestRootNamesTheFolderAndTellsWorkspacesApart(t *testing.T) { + anchor := filepath.Join(string(filepath.Separator)+"cache", AnchorName) + root := Root(anchor, "c1", "/srv/repo") + if root != Root(anchor, "c1", "/srv/repo") { + t.Fatal("the same workspace has two roots") + } + if filepath.Dir(filepath.Dir(root)) != anchor || filepath.Base(root) != "repo" { + t.Fatalf("root = %s, want anchor//repo", root) + } + for _, other := range []string{Root(anchor, "c2", "/srv/repo"), Root(anchor, "c1", "/opt/repo")} { + if other == root { + t.Fatalf("two workspaces share the root %s", root) + } + } + for remote, want := range map[string]string{ + "/": "root", + "/home/dev/": "dev", + "/home/项目": "项目", + "/srv/a:b|c": "a_b_c", + "/srv/name.": "name", + "/srv/...": "folder", + "/srv/con": "_con", + "/srv/COM1.txt": "_COM1.txt", + "/srv/" + strings.Repeat("x", 80): strings.Repeat("x", maxNameRunes), + } { + if got := filepath.Base(Root(anchor, "c1", remote)); got != want { + t.Errorf("name of %q = %q, want %q", remote, got, want) + } + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 11c9d746f..4764307c4 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -40,6 +40,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/projectgen" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/1lck/Lithe-IDEA/desktop/internal/wslpath" @@ -212,6 +213,11 @@ type Kernel interface { EditRemoteConnections(ctx context.Context, document *string, edit core.RemoteConnectionEdit) (core.RemoteConnectionsPublication, error) RemoteProbe(ctx context.Context, connection core.SSHConnection) (core.RemoteProbeResult, error) RemoteAuthRespond(ctx context.Context, requestID string, answer *string) (bool, error) + RemoteConnect(ctx context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) + RemoteDisconnect(ctx context.Context, sessionID string) (bool, error) + RemoteCloseAll(ctx context.Context) (int, error) + RemoteReadDir(ctx context.Context, sessionID, path string) (core.RemoteDirectory, error) + RemoteServerState(ctx context.Context, sessionID string) error GitCreateTag(ctx context.Context, root, name, revision, message string) error GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error) GitRebaseStart(ctx context.Context, root string, preview core.RebasePreview, steps []core.RebaseStep) (*core.RebaseSession, error) @@ -481,6 +487,9 @@ type project struct { indexing projectIndexing // name is the folder's name, shown in the title bar. name string + // remote is set when the project's folder is on an SSH host (remote_workspace.go); root is + // then the workspace's local placeholder, which the local file system cannot open. + remote *remoteProject // ctx ends when the project closes, which stops its kernel calls. ctx context.Context cancel context.CancelFunc @@ -772,6 +781,12 @@ type App struct { clone cloneState // remote is the Remote Development window (remote.go). remote remoteState + // remoteBundle, remoteAnchor and remoteAfter replace the server builds a connection sends, + // the anchor of the remote workspaces' placeholders and the timers of their heartbeats and + // reconnections (remote_workspace.go); tests set them. + remoteBundle func() (remoteserver.Bundle, error) + remoteAnchor func() (string, error) + remoteAfter func(time.Duration, func()) func() bool // gitAuth holds the questions of the Git operations the user started (git_auth.go). gitAuth gitAuthState newProject newProjectState @@ -1128,6 +1143,15 @@ func (a *App) Run() error { session.plugins.Runs.StopAll() } } + if a.kernel != nil { + // Every tab shares the kernel: this ends the remote sessions no closed project ended, + // such as one the Remote Development window had open, and refuses new ones. + ctx, cancel := context.WithTimeout(context.Background(), remoteCloseAllTimeout) + if _, err := a.kernel.RemoteCloseAll(ctx); err != nil { + a.backgroundFailed("remote_close_all", remoteLogError(err)) + } + cancel() + } if a.logs != nil { a.logs.Wait() } @@ -1706,6 +1730,7 @@ func (a *App) finishCloseProject(p *project, after func()) { } a.cancelPrompts() a.ideAPIDisable(p) + a.closeRemoteWorkspace(p) p.cancel() a.closePluginPages() a.closePreviewPages() diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index 899db4647..f4fbfa3d7 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -511,13 +511,14 @@ func (a *App) hiddenToolWindowRow(c ui.C, i int) (ui.Box, bool) { return row, row.Clicked() } -// statusBar is the strip across the bottom of the workbench: the navigation path of the item the -// user is on at the leading end (status_path_view.go), and at the trailing end the readouts the -// user can arrange. +// statusBar is the strip across the bottom of the workbench: the connection of a remote workspace +// (remote_status_view.go) and the navigation path of the item the user is on at the leading end +// (status_path_view.go), and at the trailing end the readouts the user can arrange. func (a *App) statusBar(c ui.C) { clicked := -1 ui.Row(c).FillWidth().Height(statusBarHeight).Shrink(0).Background(a.chromeFill()). Items(ui.Center).PadX(chromeEdge).Children(func() { + a.remoteStatus(c) a.statusPathView(c) zone := ui.Row(c).Items(ui.Center).Gap(chromeStatusGap).Children(func() { for _, i := range a.chrome.items[zoneStatus] { @@ -642,6 +643,10 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { a.menuDivider(c) a.menuTitle(c, a.text.Title.OpenProjects) openRow := a.welcome.row(a.project.root, len(a.recent)) + if r := a.project.remote; r != nil { + // The placeholder names no folder of this computer, so the row shows the host's. + openRow.name, openRow.path = a.project.name, r.remoteLocation() + } current, closing = a.projectMenuRow(c.Part("current"), openRow, a.project.git.branch(), true, false) a.menuDivider(c) diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index f5ff851b5..d7b4ea2a8 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -270,7 +270,7 @@ func (a *App) syntaxRegistry() *syntax.Registry { // group. The file is read and its language's grammar loaded away from the window thread; a // file that cannot be read, is binary or is too large is not opened and the banner says why. func (a *App) openFile(p *project, path string) { - if path == "" { + if path == "" || a.refuseRemote(p, "open_file") { return } path = filepath.Clean(path) @@ -880,6 +880,14 @@ func (a *App) removeDocument(p *project, d *document) { // saveProjectDocuments drains writes and verifies each current document before closing. func (a *App) saveProjectDocuments(p *project, done func(bool)) { + if p.remote != nil && len(p.docs.list) == 0 { + // A remote workspace opens no file yet (openFile refuses it), so there is nothing to save. + // Core's save batch is a pure reducer with no remote adapter, and a request of the + // project's context carries the remote binding, which Core refuses; asking would keep the + // workspace from closing. A remote workspace with documents still asks, and fails loudly. + done(true) + return + } a.saveProjectPass(p, make(map[int]int), done) } diff --git a/desktop/internal/workbench/editor_session.go b/desktop/internal/workbench/editor_session.go index 739dd7d34..68420f760 100644 --- a/desktop/internal/workbench/editor_session.go +++ b/desktop/internal/workbench/editor_session.go @@ -77,8 +77,11 @@ type editorRestoreItem struct { // saveEditorSession records the editor of p for the next time the project opens. A project // with no file open forgets its session. +// +// A remote workspace has no session: its files do not open in the editor yet, and its root is a +// placeholder that names no folder of this computer. func (a *App) saveEditorSession(p *project) { - if p.standalone { + if p.standalone || p.remote != nil { return } all := map[string]savedEditorSession{} diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index 64a464256..51bb05a90 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -4,6 +4,7 @@ import ( "strconv" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" @@ -420,6 +421,11 @@ func (a *App) terminalToolBody(c ui.C, p *project) { body.Items(ui.Center).PadX(shellContentPad).Children(func() { ui.Paragraph(c, a.text.Terminal.NoTerminals, 3).Grow(1).TextCenter().Color(a.colors.Subtle) }) + case p.remote != nil: + // A terminal of a remote workspace would be a shell of this computer, so none is opened. + body.Items(ui.Center).PadX(shellContentPad).Children(func() { + ui.Paragraph(c, i18n.Shared(a.language(), "desktop.remote.workspace.localOnly"), 3).Grow(1).TextCenter().Color(a.colors.Subtle) + }) case !u.autoFailed: c.After(func() { if t := a.newTerminal(p, ""); t != nil { diff --git a/desktop/internal/workbench/filetree_menu.go b/desktop/internal/workbench/filetree_menu.go index bddd1f9a6..5f8f6a8fc 100644 --- a/desktop/internal/workbench/filetree_menu.go +++ b/desktop/internal/workbench/filetree_menu.go @@ -55,10 +55,17 @@ type treePrompt struct { // from anywhere on it too. A row of a folder or the root can make files and folders; any row // but the root can be renamed or deleted. The Git items appear only for a file the last status // lists as changed. +// +// A row of a remote workspace has the items that do not touch the folder: copying its host path +// and refreshing the tree. Its rows are neither dragged nor dropped on. func (a *App) projectTreeMenu(c ui.C, p *project, row gfx.ID, n *treeNode, target ui.Box) { language := a.language() root := n == p.tree.root target.LabelFor(row) + if p.remote != nil { + a.remoteTreeMenu(c, p, n, target) + return + } if !root { p.tree.rememberRow(row, n) target.DragSource(&a.dnd.tree) @@ -205,6 +212,23 @@ func (a *App) projectTreeMenu(c ui.C, p *project, row gfx.ID, n *treeNode, targe }) } +// remoteTreeMenu declares the context menu of row n of the remote workspace p. +func (a *App) remoteTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { + language := a.language() + ui.ContextMenu(c, target, func(menu *ui.MenuItems) { + menu.WidthRange(200, 280) + full := filepath.Join(p.root, filepath.FromSlash(n.path)) + a.copyPathMenu(c, menu, full, n != p.tree.root, "workspace.tree") + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.files.refresh")).Clicked() { + c.After(func() { + a.performed("workspace.tree.refresh", surfaceContextMenu) + a.refreshProjectTree(p) + }) + } + }) +} + // revealLabel is the menu label that shows a path in the platform's file manager. func revealLabel(language i18n.Language) string { if runtime.GOOS == "windows" { @@ -248,10 +272,12 @@ func (a *App) copyPathMenu(c ui.C, menu *ui.MenuItems, full string, relative boo } // copyTreePath copies a path to the clipboard, relative to the project when relative is set. +// The absolute path of a remote workspace's file is its path on the host. func (a *App) copyTreePath(full string, relative bool) { text := full - if relative { - if p := a.project; p != nil { + if p := a.project; p != nil { + text = p.remoteHostPath(full) + if relative { if rel, err := filepath.Rel(p.root, full); err == nil { text = filepath.ToSlash(rel) } diff --git a/desktop/internal/workbench/filetree_watch.go b/desktop/internal/workbench/filetree_watch.go index 6baec9c5e..eb2f9048b 100644 --- a/desktop/internal/workbench/filetree_watch.go +++ b/desktop/internal/workbench/filetree_watch.go @@ -17,6 +17,11 @@ import ( const treeWatchLimit = 128 func (a *App) watchTreeNode(p *project, n *treeNode) { + if p.remote != nil { + // A remote workspace's folder is on the host; the local watch would only fail on its + // placeholder. The tree is read again when the connection comes back. + return + } if treeUsesRecursiveWatch() { if !p.tree.recursiveWatch { p.tree.recursiveWatch = true diff --git a/desktop/internal/workbench/remote.go b/desktop/internal/workbench/remote.go index 9b95600eb..94df1ed1e 100644 --- a/desktop/internal/workbench/remote.go +++ b/desktop/internal/workbench/remote.go @@ -65,6 +65,10 @@ type remoteState struct { // probe is the running test, nil when none runs; result is the last one's outcome. probe *remoteProbe result *remoteProbeOutcome + // connect is the running connection to the selected host, nil when none runs; its failure is + // shown as result. browser chooses the host folder to open over the session it opened. + connect *remoteProbe + browser *remoteBrowser // probed is what the last test of each connection found, by the connection as Core stores // it, so that a saved connection's overview shows its host again after the form was saved // or the window reopened. It lives in memory while the app runs, outlives the window and @@ -141,11 +145,13 @@ func (a *App) openRemote(surface actionSurface) { a.loadRemote(remoteLoadSelectFirst, "") } -// closeRemote closes the window, stopping a running test. What was typed and not saved is -// dropped. +// closeRemote closes the window, stopping a running test or connection and ending the session a +// folder was being chosen over. What was typed and not saved is dropped. func (a *App) closeRemote() { r := &a.remote r.stopProbe() + r.stopConnect() + a.leaveRemoteBrowser() r.generation++ r.open, r.saving, r.loading = false, false, false r.form = remoteForm{} @@ -340,9 +346,10 @@ func (r *remoteState) probedOutcome(connection core.SSHConnection) *remoteProbeO return r.probed[remoteStored(connection)] } -// resetEditing drops the last test, its errors and the delete question. +// resetEditing drops the last test or connection, its errors and the delete question. func (r *remoteState) resetEditing() { r.stopProbe() + r.stopConnect() r.result, r.err, r.fieldErr, r.confirmDelete = nil, "", remoteFieldRefusal{}, false } diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go new file mode 100644 index 000000000..fb3c0c274 --- /dev/null +++ b/desktop/internal/workbench/remote_browse.go @@ -0,0 +1,389 @@ +package workbench + +import ( + "cmp" + "context" + "errors" + "path" + "slices" + "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/remoteconn" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" + "github.com/vivaui/viva/ui" +) + +// Connect in the Remote Development window opens a session to the selected saved connection's +// host, sending it the server build the client carries for the host's platform, then lists the +// host's folders so the user picks the one to open (#2231, R0). The session is the window's while +// the folder is chosen: Back, closing the window and quitting end it. Opening the folder hands it +// to the workspace (remote_workspace.go) and remembers the folder with the connection. +// +// Only a saved connection connects, as saved: the workspace connects again with the same, and +// the folder it remembers belongs to the entry. OpenSSH's questions are asked in the +// authentication dialog, as a test asks them. + +// remoteBrowser chooses the host folder to open over a session the window connected. +type remoteBrowser struct { + session core.RemoteSession + entryID string + name string + connection core.SSHConnection + // recent are the connection's recent folders, latest first. + recent []string + recentList ui.ListState + // path is what the path field holds. dir is the folder listed last, or tried last when it + // could not be listed; folders are its subfolders' names, links to folders among them. + path ui.Field + dir string + folders []string + // skipped counts the entries whose names the host could not send. + skipped uint32 + list ui.ListState + loading bool + // listing counts the listings, so that only the latest applies. + listing uint64 + // readErr is why dir could not be listed; err why the folder could not be opened. + readErr string + opening bool + err string +} + +// stopConnect cancels a running connection; a session it opens anyway is ended when it returns. +func (r *remoteState) stopConnect() { + if r.connect != nil { + r.connect.cancel() + r.connect = nil + } +} + +// connectable says whether Connect may start for the selected connection: it is saved, the form +// shows it as saved, and nothing else runs. +func (r *remoteState) connectable() bool { + return r.open && r.browser == nil && r.connect == nil && r.probe == nil && !r.saving && + 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() { + r := &a.remote + if !r.connectable() { + return + } + entry := *r.entry(r.selected) + r.result, r.err, r.fieldErr, r.confirmDelete = nil, "", remoteFieldRefusal{}, false + a.performed("remote.connect", surfaceButton) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), remoteProbeTimeout) + attempt := &remoteProbe{cancel: cancel} + r.connect = attempt + generation, kernel := r.generation, a.kernel + a.background(nil, 0, func(context.Context) func(*App) { + defer cancel() + result, err := a.connectRemoteHost(a.gitAuthentication(ctx), kernel, entry.Connection) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.connect != attempt { + if result.Session != nil { + a.releaseRemoteSession(result.Session.ID) + } + // log-exempt: 用户取消:连接已停止、换了连接或窗口已关闭,已打开的会话随即结束。 + return + } + r.connect = nil + if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { + a.browseRemote(entry, *result.Session) + return + } + if result.Session != nil { + a.releaseRemoteSession(result.Session.ID) + } + if field, reason, ok := core.RemoteConnectionFieldError(err); ok { + a.operationRejected("remote_connect", "field_refused") + r.err = remoteRefusalText(a.language(), remoteFieldRefusal{field: field, reason: reason}) + return + } + a.operationFailed("remote_connect", remoteConnectFailure(result, err)) + r.result = remoteConnectOutcome(result, err) + } + }) +} + +// stopRemoteConnect stops the running connection. +func (a *App) stopRemoteConnect() { + r := &a.remote + if r.connect == nil { + return + } + a.performed("remote.connect.stop", surfaceButton) + r.stopConnect() +} + +// remoteConnectFailureText is the window's text for a connection that could not start for a +// reason of this computer: the client carries no server build, or the one installed in the cache +// changed. "" for any other error, which the test's texts cover. +func remoteConnectFailureText(language i18n.Language, err error) string { + var coreErr *core.Error + switch { + case errors.Is(err, remoteserver.ErrNotBundled): + return i18n.Shared(language, "desktop.remote.connect.notBundled") + case errors.Is(err, remoteserver.ErrMismatch), + errors.As(err, &coreErr) && coreErr.Code == core.CodeRemoteServerInvalid: + return i18n.Shared(language, "desktop.remote.connect.serverInvalid") + } + return "" +} + +// browseRemote starts choosing the folder to open over session, in the account's home directory. +func (a *App) browseRemote(entry core.SavedRemoteConnection, session core.RemoteSession) { + r := &a.remote + r.browser = &remoteBrowser{session: session, entryID: entry.ID, name: entry.Name, connection: entry.Connection, recent: entry.RecentFolders} + start := session.HomeDirectory + if !path.IsAbs(start) { + start = "/" + } + a.listRemoteFolder(path.Clean(start)) +} + +// leaveRemoteBrowser stops choosing a folder and ends its session. +func (a *App) leaveRemoteBrowser() { + r := &a.remote + if b := r.browser; b != nil { + r.browser = nil + a.releaseRemoteSession(b.session.ID) + } +} + +// backFromRemoteBrowser is Back: the session ends and the form shows again. +func (a *App) backFromRemoteBrowser() { + if a.remote.browser == nil { + return + } + a.performed("remote.browse.back", surfaceButton) + a.leaveRemoteBrowser() +} + +// listRemoteFolder lists the host folder dir, an absolute clean POSIX path, in the browser. +func (a *App) listRemoteFolder(dir string) { + r := &a.remote + b := r.browser + if b == nil || b.opening { + return + } + b.listing++ + b.loading, b.readErr, b.err, b.dir = true, "", "", dir + b.path.SetText(dir) + listing, generation, kernel, session := b.listing, r.generation, a.kernel, b.session.ID + a.background(nil, remoteReadDirTimeout, func(ctx context.Context) func(*App) { + directory, err := kernel.RemoteReadDir(ctx, session, dir) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.browser != b || b.listing != listing { + // log-exempt: 用户取消:已换了文件夹、返回或关闭窗口,不再应用列出结果。 + return + } + b.loading, b.folders, b.skipped, b.list = false, nil, 0, ui.ListState{} + if err != nil { + a.operationFailed("remote_read_dir", remoteLogError(err)) + if remoteConnectionClosed(err) { + // The session is gone: choosing over it cannot go on. + a.leaveRemoteBrowser() + r.err = i18n.Shared(a.language(), "desktop.remote.browse.lost") + return + } + b.readErr = remoteReadDirFailureText(a.language(), err) + return + } + b.folders, b.skipped = remoteFolders(directory), directory.SkippedNonUTF8 + } + }) +} + +// remoteFolders are the names of directory's folders and links to folders, hidden ones last. +func remoteFolders(directory core.RemoteDirectory) []string { + var folders []string + for _, entry := range directory.Entries { + if entry.Metadata.IsDirectory() { + folders = append(folders, entry.Name) + } + } + slices.SortStableFunc(folders, func(x, y string) int { + hiddenX, hiddenY := strings.HasPrefix(x, "."), strings.HasPrefix(y, ".") + if hiddenX != hiddenY { + if hiddenX { + return 1 + } + return -1 + } + return cmp.Compare(strings.ToLower(x), strings.ToLower(y)) + }) + return folders +} + +// remoteReadDirFailureText says why a host folder could not be listed. +func remoteReadDirFailureText(language i18n.Language, err error) string { + var coreErr *core.Error + if errors.As(err, &coreErr) { + switch coreErr.Code { + case core.CodeWorkspaceNotFound: + return i18n.Shared(language, "desktop.remote.browse.notFound") + case core.CodePermissionDenied: + return i18n.Shared(language, "desktop.remote.browse.denied") + case core.CodeInvalidRequest: + return i18n.Shared(language, "desktop.remote.browse.pathInvalid") + } + } + return i18n.SharedFormat(language, "desktop.remote.browse.readFailed", map[string]string{"reason": remoteLogError(err).Error()}) +} + +// remoteFolderPath is text, typed in the path field, as the absolute clean host path to list: a +// leading ~ is the account's home directory. ok is false for a relative path, and for ~ when the +// host did not report the home directory. +func remoteFolderPath(text, home string) (dir string, ok bool) { + text = strings.TrimSpace(text) + if text == "~" || strings.HasPrefix(text, "~/") { + if !path.IsAbs(home) { + return "", false + } + text = home + text[1:] + } + if !path.IsAbs(text) || strings.ContainsRune(text, 0) { + return "", false + } + return path.Clean(text), true +} + +// goRemoteFolder lists the folder typed in the path field. +func (a *App) goRemoteFolder() { + b := a.remote.browser + if b == nil || b.opening { + return + } + dir, ok := remoteFolderPath(b.path.Text(), b.session.HomeDirectory) + if !ok { + a.operationRejected("remote_read_dir", "path_not_absolute") + b.readErr = i18n.Shared(a.language(), "desktop.remote.browse.pathInvalid") + return + } + a.performed("remote.browse.go", surfaceButton) + a.listRemoteFolder(dir) +} + +// upRemoteFolder lists the parent of the folder shown. +func (a *App) upRemoteFolder() { + b := a.remote.browser + if b == nil || b.dir == "" || b.dir == "/" { + return + } + a.performed("remote.browse.up", surfaceButton) + a.listRemoteFolder(path.Dir(b.dir)) +} + +// target is the folder Open opens: the selected subfolder, or the folder shown. +func (b *remoteBrowser) target() string { + if at := b.list.Selected(); at >= 0 && at < len(b.folders) { + return path.Join(b.dir, b.folders[at]) + } + return b.dir +} + +// openable says whether Open may open the target now. +func (b *remoteBrowser) openable() bool { + return !b.loading && !b.opening && b.readErr == "" && b.dir != "" +} + +// openRemoteFolder opens the target as a remote workspace: it makes sure the placeholders' anchor +// 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() { + r := &a.remote + b := r.browser + if !r.open || b == nil || !b.openable() { + return + } + a.performed("remote.workspace.open", surfaceButton) + b.opening, b.err = true, "" + dir, entryID := b.target(), 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() + if err == nil { + err = remoteplaceholder.Ensure(anchor) + } + var rememberErr error + if err == nil { + // The folder is remembered even when the workspace then fails to open, as the editor + // remembers a project it opened. + 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}}) + } + } + return func(a *App) { + if rememberErr != nil { + // Opening does not depend on it: the folder is only missing from the recent list. + a.backgroundFailed("remote_remember_folder", documentLogError(rememberErr)) + } + r := &a.remote + if !r.open || r.generation != generation || r.browser != b { + // log-exempt: 用户取消:窗口已关闭或已返回,会话已随之结束。 + return + } + b.opening = false + if err != nil { + a.operationFailed("remote_workspace_open", documentLogError(err)) + if errors.Is(err, remoteplaceholder.ErrAnchorUnusable) { + b.err = i18n.SharedFormat(a.language(), "desktop.remote.browse.anchorUnusable", map[string]string{"path": anchor}) + } else { + b.err = i18n.SharedFormat(a.language(), "desktop.remote.browse.openFailed", map[string]string{"reason": documentLogError(err).Error()}) + } + return + } + target := remoteTarget{ + connectionID: b.entryID, name: b.name, connection: b.connection, session: b.session, + remoteRoot: dir, root: remoteplaceholder.Root(anchor, b.entryID, dir), + } + // The session is the workspace's from here on. + r.browser = nil + a.closeRemote() + a.openRemoteWorkspace(target) + } + }) +} + +// openRemoteWorkspace shows target: the tab that has the folder open over the same connection, +// which takes the session when it has lost its own; this workbench when it has no project; a new +// tab otherwise. +func (a *App) openRemoteWorkspace(target remoteTarget) { + if open := a.sessions.showing(target.root); open != nil { + a.sessions.activate(open) + p := open.project + if r := p.remote; r != nil && !r.closed && r.session == "" && r.reconnecting == nil { + r.stopRemoteTimer() + open.attachRemote(p, target.session.ID) + open.refreshRemoteTree(p) + return + } + a.releaseRemoteSession(target.session.ID) + return + } + if a.project == nil || a.sessions == nil { + a.openRemoteProject(target) + return + } + a.sessions.openRemoteTab(a, target) +} + +// remoteSkippedText says how many entries of the folder shown have names the host could not send, +// "" when none. +func remoteSkippedText(language i18n.Language, skipped uint32) string { + if skipped == 0 { + return "" + } + return i18n.SharedFormat(language, "desktop.remote.browse.skipped", map[string]string{"count": strconv.FormatUint(uint64(skipped), 10)}) +} diff --git a/desktop/internal/workbench/remote_browse_view.go b/desktop/internal/workbench/remote_browse_view.go new file mode 100644 index 000000000..cdf71237e --- /dev/null +++ b/desktop/internal/workbench/remote_browse_view.go @@ -0,0 +1,167 @@ +package workbench + +import ( + "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 folder browser of remote_browse.go in the Remote Development window. + +const ( + // remoteRecentWidth is the width of the connection's recent folders beside the folder list. + remoteRecentWidth = 260 + // remoteFolderRowHeight is the height of a folder's row. + remoteFolderRowHeight = 26 +) + +// remoteBrowserView declares the browser: the connection, the path of the folder shown with the +// button to its parent, the connection's recent folders and the folder's subfolders. A click +// selects a subfolder for Open; a double click or Enter lists it. +func (a *App) remoteBrowserView(c ui.C, b *remoteBrowser) { + language := a.language() + k := c.Part("browser") + ui.Column(k).Fill().Pad(16).Gap(10).Children(func() { + ui.Row(k.Part("connected")).FillWidth().Gap(8).Items(ui.Center).Children(func() { + ui.Icon(k, icons.Server).Size(16, 16).Shrink(0).Color(a.colors.Success) + ui.Text(k, i18n.SharedFormat(language, "desktop.remote.browse.connected", map[string]string{"name": b.name})).Weight(gfx.WeightSemibold).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(k, remoteAddress(b.connection)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + }) + pathLabel := i18n.Shared(language, "desktop.remote.browse.path") + ui.Row(k.Part("path")).FillWidth().Gap(6).Items(ui.Center).Children(func() { + if a.gitIconButton(k.Part("up"), i18n.Shared(language, "desktop.remote.browse.up"), icons.ArrowUp, false, b.opening || b.dir == "/" || b.dir == "") { + c.After(a.upRemoteFolder) + } + if ui.TextField(k.Part("field"), &b.path, pathLabel, i18n.Shared(language, "desktop.remote.browse.pathPlaceholder")).Grow(1).MinWidth(0).Disabled(b.opening).Submitted() { + c.After(a.goRemoteFolder) + } + if a.gitIconButton(k.Part("refresh"), i18n.Shared(language, "desktop.remote.browse.refresh"), icons.RefreshCw, false, b.opening || b.loading || b.dir == "") { + c.After(func() { + if b := a.remote.browser; b != nil { + a.performed("remote.browse.refresh", surfaceButton) + a.listRemoteFolder(b.dir) + } + }) + } + }) + if b.readErr != "" { + a.remoteNotice(k.Part("read"), icons.CircleAlert, a.theme.Danger, b.readErr) + } + if b.err != "" { + a.remoteNotice(k.Part("error"), icons.CircleX, a.theme.Danger, b.err) + } + ui.Row(k.Part("lists")).FillWidth().Grow(1).Shrink(1).MinHeight(0).Gap(0). + Border(1, a.colors.Line).Radius(a.theme.Metrics.RadiusItem()).Children(func() { + if len(b.recent) > 0 { + a.remoteRecentFolders(k.Part("recent"), b) + ui.Column(k).Width(1).FillHeight().Shrink(0).Background(a.colors.Line) + } + a.remoteFolderList(k.Part("folders"), b) + }) + if text := remoteSkippedText(language, b.skipped); text != "" { + ui.Paragraph(k.Part("skipped"), text, 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + } + }) +} + +// remoteRecentFolders declares the folders opened over the connection before; choosing one lists +// it. +func (a *App) remoteRecentFolders(c ui.C, b *remoteBrowser) { + title := i18n.Shared(a.language(), "desktop.remote.browse.recent") + ui.Column(c).Width(remoteRecentWidth).FillHeight().Shrink(0).Children(func() { + ui.Row(c.Part("header")).FillWidth().Height(panelHeaderHeight).Shrink(0).Items(ui.Center).PadX(10).Children(func() { + ui.Text(c, title).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Ellipsis() + }) + b.recentList.Label = func(row int) string { + if row < 0 || row >= len(b.recent) { + return "" + } + return b.recent[row] + } + ui.List(c.Part("rows"), &b.recentList, len(b.recent), func(row ui.ListRow) { + folder := b.recent[row.Index] + rc := row.C + row.Element.Height(remoteFolderRowHeight).PadX(10).Gap(8).Items(ui.Center).Hover(ui.Look{}.Background(a.colors.Hover)) + row.Element.Children(func() { + ui.Icon(rc, icons.Clock).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(rc, folder).Ellipsis().Shrink(1).MinWidth(0) + }) + }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(title) + if b.recentList.Changed() { + if at := b.recentList.Selected(); at >= 0 && at < len(b.recent) && !b.opening { + folder := b.recent[at] + c.After(func() { + if dir, ok := remoteFolderPath(folder, ""); ok { + a.performed("remote.browse.recent", surfaceButton) + a.listRemoteFolder(dir) + } + }) + } + } + }) +} + +// remoteFolderList declares the subfolders of the folder shown. +func (a *App) remoteFolderList(c ui.C, b *remoteBrowser) { + language := a.language() + title := i18n.Shared(language, "desktop.remote.browse.folders") + ui.Column(c).Grow(1).Shrink(1).MinWidth(0).FillHeight().Children(func() { + if b.loading || len(b.folders) == 0 { + text := i18n.Shared(language, "desktop.remote.browse.empty") + switch { + case b.loading: + text = i18n.Shared(language, "native.loading") + case b.readErr != "": + text = "" + } + ui.Row(c.Part("empty")).FillWidth().Pad(10).Children(func() { + ui.Paragraph(c, text, 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + }) + return + } + b.list.Label = func(row int) string { + if row < 0 || row >= len(b.folders) { + return "" + } + return b.folders[row] + } + ui.List(c.Part("rows"), &b.list, len(b.folders), func(row ui.ListRow) { + name := b.folders[row.Index] + rc := row.C + row.Element.Height(remoteFolderRowHeight).PadX(10).Gap(8).Items(ui.Center).Hover(ui.Look{}.Background(a.colors.Hover)) + row.Element.Children(func() { + ui.Icon(rc, icons.Folder).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(rc, name).Ellipsis().Shrink(1).MinWidth(0) + }) + }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(title) + if at, ok := b.list.Submitted(); ok && at >= 0 && at < len(b.folders) && !b.opening { + dir := b.dir + "/" + b.folders[at] + c.After(func() { + if dir, ok := remoteFolderPath(dir, ""); ok { + a.performed("remote.browse.enter", surfaceButton) + a.listRemoteFolder(dir) + } + }) + } + }) +} + +// remoteBrowserFooter declares the folder Open opens, Back and Open. +func (a *App) remoteBrowserFooter(c ui.C, b *remoteBrowser) { + language := a.language() + if target := b.target(); target != "" { + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.browse.target", map[string]string{"path": target})).Ellipsis().Shrink(1).MinWidth(0).Color(a.colors.Subtle) + } + ui.Spacer(c) + if ui.Button(c.Part("back"), i18n.Shared(language, "desktop.remote.browse.back")).Outline().Disabled(b.opening).Clicked() { + c.After(a.backFromRemoteBrowser) + } + label := i18n.Shared(language, "desktop.remote.browse.open") + if b.opening { + label = i18n.Shared(language, "desktop.remote.browse.opening") + } + if ui.Button(c.Part("open"), label).Disabled(!b.openable()).Clicked() { + c.After(a.openRemoteFolder) + } +} diff --git a/desktop/internal/workbench/remote_status_view.go b/desktop/internal/workbench/remote_status_view.go new file mode 100644 index 000000000..04687c610 --- /dev/null +++ b/desktop/internal/workbench/remote_status_view.go @@ -0,0 +1,122 @@ +package workbench + +import ( + "strconv" + + "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 status bar's item of a remote workspace (remote_workspace.go): the +// connection and how it is doing, as the button that opens the connection's menu. It sits at the +// leading end of the status bar, as the remote indicator of VS Code and of JetBrains Gateway does. + +// remoteStatusText is the item's text for r: the connection's name, with the round trip of the +// last heartbeat while connected or with how the connection is doing otherwise. +func remoteStatusText(language i18n.Language, r *remoteProject) string { + switch r.link { + case remoteUnresponsive: + return i18n.SharedFormat(language, "desktop.remote.status.unresponsive", map[string]string{"name": r.name}) + case remoteReconnecting: + return i18n.SharedFormat(language, "desktop.remote.status.reconnecting", map[string]string{"name": r.name}) + case remoteDisconnected: + return i18n.SharedFormat(language, "desktop.remote.status.disconnected", map[string]string{"name": r.name}) + } + if r.latency <= 0 { + return i18n.SharedFormat(language, "desktop.remote.status.connected", map[string]string{"name": r.name}) + } + ms := strconv.FormatInt(max(r.latency.Milliseconds(), 1), 10) + return i18n.SharedFormat(language, "desktop.remote.status.latency", map[string]string{"name": r.name, "ms": ms}) +} + +// remoteStatusLook is the icon of the item and its colour for r's link. +func (a *App) remoteStatusLook(r *remoteProject) (gfx.Icon, gfx.Color) { + switch r.link { + case remoteUnresponsive: + return icons.CircleAlert, a.colors.Warning + case remoteReconnecting: + return icons.LoaderCircle, a.colors.Subtle + case remoteDisconnected: + return icons.CircleX, a.theme.Danger + } + return icons.Server, a.colors.Success +} + +// remoteStatus declares the item of the open remote workspace, and nothing for a local project. +func (a *App) remoteStatus(c ui.C) { + p := a.project + if p == nil || p.remote == nil { + return + } + r := p.remote + language := a.language() + text := remoteStatusText(language, r) + icon, color := a.remoteStatusLook(r) + k := c.Part("remote") + button := ui.Row(k).Height(chromeStatusItem).Shrink(0).Items(ui.Center).Gap(chromeGap).PadX(chromeStatusPad). + Radius(a.theme.Metrics.RadiusItem()). + HitWith(ui.ID(k), i18n.Shared(language, "desktop.remote.status.label"), gfx.HitOptions{ + Role: gfx.RoleButton, + Cursor: gfx.PointerCursorHand, + Value: text, + Expandable: true, + Expanded: r.menuOpen, + }) + if r.menuOpen { + button = button.Background(a.colors.Active) + } else { + button = button.Hover(ui.Look{}.Background(a.colors.Hover)) + } + button.Children(func() { + ui.Icon(k, icon).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(color) + a.chromeStatusLabel(k, text) + ui.Icon(k, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Subtle) + }) + if button.Clicked() && !r.menuOpen { + r.menuOpen = true + } + a.remoteStatusMenu(k, p, button) +} + +// remoteStatusMenu declares the open menu of the connection above anchor: the host folder, why +// connecting again failed, Reconnect while there is no session, Disconnect, which closes the +// workspace, and the Remote Development window. +func (a *App) remoteStatusMenu(c ui.C, p *project, anchor ui.Box) { + r := p.remote + if !r.menuOpen { + return + } + language := a.language() + ui.Menu(c, anchor, &r.menuOpen, func(menu *ui.MenuItems) { + menu.Above() + // Wide enough for why connecting again failed, which the menu shows on one line. + menu.WidthRange(240, 560) + menu.Label(r.remoteLocation()) + if r.failure != nil && r.link == remoteDisconnected { + if text := remoteFailureText(language, r.failure); text != "" { + menu.Item(text).Icon(icons.CircleX).Disabled(true) + } + } + if r.session == "" && r.reconnecting == nil { + if menu.Item(i18n.Shared(language, "desktop.remote.status.reconnect")).Icon(icons.RefreshCw).Clicked() { + c.After(func() { a.reconnectRemoteByUser(surfaceMenu) }) + } + } + if menu.Item(i18n.Shared(language, "desktop.remote.status.disconnect")).Icon(icons.X).Clicked() { + c.After(func() { + a.performed("remote.workspace.disconnect", surfaceMenu) + a.post(func(a *App) { + if a.project == p { + a.closeProject() + } + }) + }) + } + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.remote.menuItem")).Icon(icons.Server).Clicked() { + c.After(func() { a.openRemote(surfaceMenu) }) + } + }) +} diff --git a/desktop/internal/workbench/remote_view.go b/desktop/internal/workbench/remote_view.go index a20dbdcc2..3944d8fb2 100644 --- a/desktop/internal/workbench/remote_view.go +++ b/desktop/internal/workbench/remote_view.go @@ -48,12 +48,20 @@ func (a *App) remoteView(c ui.C) { 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 { @@ -249,7 +257,7 @@ func (a *App) remoteDetail(c ui.C) { } // remoteOverview declares a saved connection: its mark, name, group and address with Edit, what -// the last test found about the host, and its settings. +// 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 @@ -280,7 +288,7 @@ func (a *App) remoteOverview(c ui.C, language i18n.Language, entry core.SavedRem } }) }) - if ui.Button(c.Part("edit"), i18n.Shared(language, "desktop.remote.edit")).Icon(icons.Pencil).Outline().Disabled(r.saving).Clicked() { + 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) } }) @@ -294,6 +302,8 @@ func (a *App) remoteOverview(c ui.C, language i18n.Language, entry core.SavedRem 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: @@ -570,35 +580,23 @@ func (a *App) remoteFormResult(c ui.C, language i18n.Language) { func (a *App) remoteOutcome(c ui.C, language i18n.Language, outcome *remoteProbeOutcome) { ui.Column(c).FillWidth().Gap(8).Children(func() { if outcome.err != nil { - text := i18n.SharedFormat(language, "desktop.remote.probe.error", map[string]string{"reason": outcome.err.Error()}) - var coreErr *core.Error - if errors.As(outcome.err, &coreErr) && coreErr.Code == core.CodeRuntimeMissing { - text = i18n.Shared(language, "desktop.remote.probe.noSSH") - } - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, text) + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, remoteFailureText(language, outcome)) return } result := outcome.result host := result.Host - var system, machine string - if host != nil { - system, machine = host.System, host.Machine - } switch result.Status { case core.RemoteProbeConnected: + 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, - i18n.SharedFormat(language, "desktop.remote.probe.unsupported", map[string]string{"system": system, "machine": machine})) - case core.RemoteProbeAuthenticationFailed: - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.authenticationFailed")) - case core.RemoteProbeHostKeyRejected: - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.hostKeyRejected")) - case core.RemoteProbeUnreachable: - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.unreachable")) + a.remoteNotice(c.Part("status"), icons.CircleAlert, a.colors.Warning, remoteFailureText(language, outcome)) default: - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.failed")) + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, remoteFailureText(language, outcome)) } if host != nil { a.remoteHostDetails(c.Part("details"), language, *host) @@ -610,6 +608,40 @@ func (a *App) remoteOutcome(c ui.C, language i18n.Language, outcome *remoteProbe }) } +// 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. +func remoteFailureText(language i18n.Language, outcome *remoteProbeOutcome) string { + if err := outcome.err; err != nil { + if own := remoteConnectFailureText(language, err); own != "" { + return own + } + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeRuntimeMissing { + return i18n.Shared(language, "desktop.remote.probe.noSSH") + } + return i18n.SharedFormat(language, "desktop.remote.probe.error", map[string]string{"reason": remoteLogError(err).Error()}) + } + result := outcome.result + switch result.Status { + case core.RemoteProbeConnected: + return "" + case core.RemoteProbeUnsupportedPlatform: + var system, machine string + if host := result.Host; host != nil { + system, machine = host.System, host.Machine + } + return i18n.SharedFormat(language, "desktop.remote.probe.unsupported", map[string]string{"system": system, "machine": machine}) + case core.RemoteProbeAuthenticationFailed: + return i18n.Shared(language, "desktop.remote.probe.authenticationFailed") + case core.RemoteProbeHostKeyRejected: + return i18n.Shared(language, "desktop.remote.probe.hostKeyRejected") + case core.RemoteProbeUnreachable: + return i18n.Shared(language, "desktop.remote.probe.unreachable") + } + 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 @@ -648,8 +680,9 @@ func (a *App) remoteHostDetails(c ui.C, language i18n.Language, host core.Remote } // remoteFooter declares the footer. The overview has Delete, or the question whether to delete, -// then Test Connection and Close; the form has Test Connection, then Cancel (Close while nothing -// is saved to go back to) and Save. +// 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() @@ -670,10 +703,23 @@ func (a *App) remoteFooter(c ui.C) { c.After(func() { r.confirmDelete = true }) } ui.Spacer(c) - a.remoteTestButton(c, language) + 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) diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go new file mode 100644 index 000000000..5c5aa6dce --- /dev/null +++ b/desktop/internal/workbench/remote_workspace.go @@ -0,0 +1,487 @@ +package workbench + +import ( + "context" + "errors" + "path" + "path/filepath" + "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/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" +) + +// A remote workspace is a project whose folder is on an SSH host (#2231, R0). Its root is a +// placeholder below a read-only file of the user's cache directory (remoteplaceholder), and its +// context carries a core.RemoteWorkspace binding: every Core request of the project runs on the +// host or is refused with not_supported, and a local call with a path of the project fails +// instead of touching a local folder that only looks like it. +// +// The workspace opens over a session the Remote Development window connected, and keeps it alive: +// a heartbeat asks the server's state, a failed request of the binding reports the connection +// lost, and the window then connects again on its own a few times, pausing longer each time. +// OpenSSH's questions are cancelled during those attempts, which must not ask the user anything +// they did not start; a host that needs a password then ends disconnected, and Reconnect in the +// status bar asks. Closing the project ends its session, and quitting ends every session Core +// keeps (App.Run). +// +// In this stage the workspace lists its folder in the Project tool window. The features that +// still read the project through the local file system (the editor, terminals, Git, the watch +// of the folder, language servers, run configurations and plugins) are not started for it and +// say so, until each moves to the host (R0, step 3). The workspace stays in safe mode: nothing of +// the host's project runs on this computer. + +const ( + // remoteHeartbeatInterval is the pause between two heartbeats of a connected workspace. + remoteHeartbeatInterval = 15 * time.Second + // remoteHeartbeatTimeout bounds one heartbeat. A server that does not answer in time is shown + // unresponsive; remoteHeartbeatMisses in a row end the session and connect again. + remoteHeartbeatTimeout = 10 * time.Second + remoteHeartbeatMisses = 3 + // remoteReconnectAttempts bounds the attempts to connect again after the connection was lost. + // The pause before the next attempt doubles from remoteReconnectFirstPause up to + // remoteReconnectMaxPause. + remoteReconnectAttempts = 6 + remoteReconnectFirstPause = time.Second + remoteReconnectMaxPause = 30 * time.Second + // remoteDisconnectTimeout bounds ending one session; remoteCloseAllTimeout bounds ending every + // session while the application quits. + remoteDisconnectTimeout = 10 * time.Second + remoteCloseAllTimeout = 10 * time.Second + // remoteReadDirTimeout bounds listing one host folder in the folder browser. + remoteReadDirTimeout = 30 * time.Second +) + +// remoteLink is how the workspace's connection is doing, as the status bar shows it. +type remoteLink int + +const ( + // remoteConnected: the last heartbeat was answered. + remoteConnected remoteLink = iota + // remoteUnresponsive: the session is open, but the last heartbeat went unanswered. + remoteUnresponsive + // remoteReconnecting: the session was lost and a new one is being opened. + remoteReconnecting + // remoteDisconnected: the session was lost and connecting again failed or gave up; Reconnect + // tries again. + remoteDisconnected +) + +// remoteProject is the remote side of a project (project.remote). +type remoteProject struct { + // binding carries the session and the two roots in every Core request of the project. + binding *core.RemoteWorkspace + // connectionID, name and connection are the saved connection the workspace was opened over, + // as it was when the workspace opened; connecting again uses the same. + connectionID string + name string + connection core.SSHConnection + // session is the session the binding is attached to, "" while there is none. + session string + // home is the host account's home directory, "" when the host did not report it. + home string + link remoteLink + latency time.Duration + // misses counts the heartbeats in a row that went unanswered. + misses int + // stopTimer stops the pending heartbeat or reconnection; timer tells its callback apart from + // one a later schedule replaced. + stopTimer func() bool + timer uint64 + beating bool + // attempt counts the attempts of the current reconnection; reconnecting is the running one. + attempt int + reconnecting *remoteProbe + // failure is why connecting again failed, nil while it has not. + failure *remoteProbeOutcome + // menuOpen is the status bar's menu of the connection. + menuOpen bool + // closed is set once the project closes; nothing of the workspace runs afterwards. + closed bool +} + +// remoteTarget is a host folder to open as a workspace over a connected session. +type remoteTarget struct { + connectionID string + name string + connection core.SSHConnection + session core.RemoteSession + // remoteRoot is the host folder, an absolute POSIX path; root is its local placeholder. + remoteRoot string + root string +} + +// errRemoteSessionClosed is what the binding's loss reports: a request of the workspace found +// its connection closed. +var errRemoteSessionClosed = &core.Error{Code: core.CodeConnectionClosed, Message: "the connection to the host closed"} + +// remoteLogError is err as the log keeps it. Core's message of a remote failure may name the host +// or a host path, so only its command and code are kept; any other error loses its paths. +func remoteLogError(err error) error { + var coreErr *core.Error + if errors.As(err, &coreErr) { + return &core.Error{Command: coreErr.Command, Code: coreErr.Code, Message: "remote request failed"} + } + return documentLogError(err) +} + +// remoteConnectionClosed reports whether err says the session's connection is gone. +func remoteConnectionClosed(err error) bool { + var coreErr *core.Error + return errors.As(err, &coreErr) && coreErr.Code == core.CodeConnectionClosed +} + +// remoteHostPath is the host path of full, a path below the project's root; the root itself is +// the host folder. A path outside the root, and every path of a local project, is returned as +// it is. +func (p *project) remoteHostPath(full string) string { + if p.remote == nil { + return full + } + rel, err := filepath.Rel(p.root, full) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return full + } + root := p.remote.binding.RemoteRoot() + if rel == "." { + return root + } + return path.Join(root, filepath.ToSlash(rel)) +} + +// remoteLocation is the workspace as the user names it: the connection's name and the host +// folder. +func (r *remoteProject) remoteLocation() string { + return r.name + ":" + r.binding.RemoteRoot() +} + +// remoteServerBundle is the server builds a connection sends: the ones the client carries, +// installed below the user's cache directory. It runs off the window thread. +func (a *App) remoteServerBundle() (remoteserver.Bundle, error) { + if a.remoteBundle != nil { + return a.remoteBundle() + } + dir, err := remoteserver.DefaultDir() + if err != nil { + return remoteserver.Bundle{}, err + } + return remoteserver.Resolve(dir) +} + +// remotePlaceholderAnchor is the anchor below which the workspaces' placeholders lie. It runs off +// the window thread. +func (a *App) remotePlaceholderAnchor() (string, error) { + if a.remoteAnchor != nil { + return a.remoteAnchor() + } + return remoteplaceholder.DefaultAnchor() +} + +// connectRemoteHost opens a session to the host of connection with the server builds the client +// carries. It runs off the window thread. +func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, connection core.SSHConnection) (core.RemoteConnectResult, error) { + bundle, err := a.remoteServerBundle() + if err != nil { + return core.RemoteConnectResult{}, err + } + servers := make([]core.RemoteServerBuild, len(bundle.Builds)) + for i, build := range bundle.Builds { + servers[i] = core.RemoteServerBuild{Target: build.Target, Path: build.Path, SHA256: build.SHA256} + } + return kernel.RemoteConnect(ctx, core.RemoteConnectRequest{Connection: connection, Servers: servers, ServerVersion: bundle.Version}) +} + +// remoteConnectOutcome is a connection's result as the window shows a test's. +func remoteConnectOutcome(result core.RemoteConnectResult, err error) *remoteProbeOutcome { + return &remoteProbeOutcome{result: core.RemoteProbeResult{Status: result.Status, Host: result.Host, Diagnostics: result.Diagnostics}, err: err} +} + +// remoteConnectFailure is the error the log keeps for a connection that failed: err, or Core's +// fixed status when the connection was refused. +func remoteConnectFailure(result core.RemoteConnectResult, err error) error { + if err != nil { + return remoteLogError(err) + } + return errors.New("remote connect: " + string(result.Status)) +} + +// releaseRemoteSession ends the session id in the background; a session Core no longer knows is +// already gone. +func (a *App) releaseRemoteSession(id string) { + if id == "" { + return + } + kernel := a.kernel + a.background(nil, remoteDisconnectTimeout, func(ctx context.Context) func(*App) { + _, err := kernel.RemoteDisconnect(ctx, id) + if err == nil { + return nil + } + return func(a *App) { a.backgroundFailed("remote_disconnect", remoteLogError(err)) } + }) +} + +// remoteAfterFunc runs f on its own goroutine after d and returns what stops it. +func (a *App) remoteAfterFunc(d time.Duration, f func()) func() bool { + if a.remoteAfter != nil { + return a.remoteAfter(d, f) + } + return time.AfterFunc(d, f).Stop +} + +// scheduleRemote runs then on the window thread after d, replacing the pending heartbeat or +// reconnection. It does not run once the project closed or another schedule replaced it. +func (a *App) scheduleRemote(p *project, d time.Duration, then func(*App, *project)) { + r := p.remote + r.stopRemoteTimer() + token := r.timer + r.stopTimer = a.remoteAfterFunc(d, func() { + a.post(func(a *App) { + if a.project != p || r.closed || r.timer != token { + return + } + r.stopTimer = nil + then(a, p) + }) + }) +} + +// stopRemoteTimer stops the pending heartbeat or reconnection; a callback already queued finds +// its token outdated. +func (r *remoteProject) stopRemoteTimer() { + if r.stopTimer != nil { + r.stopTimer() + r.stopTimer = nil + } + r.timer++ +} + +// attachRemote makes session the workspace's session and starts its heartbeat. +func (a *App) attachRemote(p *project, session string) { + r := p.remote + r.session, r.link, r.attempt, r.misses, r.failure = session, remoteConnected, 0, 0, nil + r.binding.Attach(session) + a.beatRemote(p) +} + +// beatRemote asks the server of the workspace's session what still runs, and schedules the next +// heartbeat. An answer shows the connection alive with its round trip; a closed connection is +// lost; remoteHeartbeatMisses unanswered heartbeats in a row end the session as lost. +func (a *App) beatRemote(p *project) { + r := p.remote + if r == nil || r.closed || r.beating || r.session == "" { + return + } + r.beating = true + session, kernel := r.session, a.kernel + a.background(p, remoteHeartbeatTimeout, func(ctx context.Context) func(*App) { + started := time.Now() + err := kernel.RemoteServerState(ctx, session) + latency := time.Since(started) + return func(a *App) { + r.beating = false + if r.closed || r.session != session { + // log-exempt: 用户取消:工作区已关闭,或会话已被新会话取代,旧心跳的结果不再适用。 + return + } + switch { + case err == nil: + r.link, r.latency, r.misses = remoteConnected, latency, 0 + a.scheduleRemote(p, remoteHeartbeatInterval, (*App).beatRemote) + case remoteConnectionClosed(err): + a.loseRemote(p, session, err) + default: + r.misses++ + if r.misses == 1 { + a.backgroundFailed("remote_heartbeat", remoteLogError(err)) + } + if r.misses >= remoteHeartbeatMisses { + a.loseRemote(p, session, err) + return + } + r.link = remoteUnresponsive + a.scheduleRemote(p, remoteHeartbeatInterval, (*App).beatRemote) + } + } + }) +} + +// loseRemote handles the loss of session: the binding is left without one, Core ends what is left +// of it, and connecting again starts. +func (a *App) loseRemote(p *project, session string, err error) { + r := p.remote + if r == nil || r.closed || session == "" || r.session != session { + // log-exempt: 同一次失败已经记录过:这个会话的丢失已记录并处理过(remote_session_lost),或工作区已关闭。 + return + } + a.backgroundFailed("remote_session_lost", remoteLogError(err)) + r.session, r.misses = "", 0 + r.binding.Detach() + r.stopRemoteTimer() + a.releaseRemoteSession(session) + r.attempt = 0 + a.reconnectRemote(p, false) +} + +// reconnectRemote opens a new session over the workspace's connection. userStarted is Reconnect +// in the status bar: it starts the attempts afresh, asks OpenSSH's questions in the window and +// does not try again on its own. An automatic attempt cancels every question and, while the host +// is unreachable, tries again after a pause up to remoteReconnectAttempts times. +func (a *App) reconnectRemote(p *project, userStarted bool) { + r := p.remote + if r == nil || r.closed || r.reconnecting != nil || r.session != "" { + return + } + if userStarted { + r.attempt = 0 + } + r.attempt++ + r.stopRemoteTimer() + r.link, r.failure = remoteReconnecting, nil + ctx, cancel := context.WithTimeout(a.operationContext(p.ctx), remoteProbeTimeout) + if userStarted { + ctx = a.gitAuthentication(ctx) + } + attempt := &remoteProbe{cancel: cancel} + r.reconnecting = attempt + kernel, connection := a.kernel, r.connection + a.background(nil, 0, func(context.Context) func(*App) { + defer cancel() + result, err := a.connectRemoteHost(ctx, kernel, connection) + return func(a *App) { + if a.project != p || r.closed || r.reconnecting != attempt { + if result.Session != nil { + a.releaseRemoteSession(result.Session.ID) + } + // log-exempt: 用户取消:工作区已关闭或这次重连已被取代,新会话随即结束。 + return + } + r.reconnecting = nil + if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { + a.attachRemote(p, result.Session.ID) + a.refreshRemoteTree(p) + return + } + if result.Session != nil { + a.releaseRemoteSession(result.Session.ID) + } + r.failure = remoteConnectOutcome(result, err) + if !userStarted && r.attempt < remoteReconnectAttempts && remoteRetryable(result.Status, err) { + r.link = remoteReconnecting + a.scheduleRemote(p, remoteReconnectPause(r.attempt), func(a *App, p *project) { a.reconnectRemote(p, false) }) + // log-exempt: 同一次失败已经记录过:导致重连的连接丢失已记录(remote_session_lost),最后一次尝试的结果另记 remote_reconnect。 + return + } + if userStarted { + a.operationFailed("remote_reconnect", remoteConnectFailure(result, err)) + } else { + a.backgroundFailed("remote_reconnect", remoteConnectFailure(result, err)) + } + r.link = remoteDisconnected + } + }) +} + +// remoteRetryable reports whether an automatic reconnection that ended with status or err may +// succeed when tried again: the host could not be reached, or the connection broke or timed out. +// A refused login, an unknown host key or a missing server build needs the user. +func remoteRetryable(status core.RemoteProbeStatus, err error) bool { + if err != nil { + return remoteConnectionClosed(err) || errors.Is(err, context.DeadlineExceeded) + } + return status == core.RemoteProbeUnreachable +} + +// remoteReconnectPause is the pause after the failed attempt-th attempt. +func remoteReconnectPause(attempt int) time.Duration { + pause := remoteReconnectFirstPause + for i := 1; i < attempt && pause < remoteReconnectMaxPause; i++ { + pause *= 2 + } + return min(pause, remoteReconnectMaxPause) +} + +// refreshRemoteTree reads the Project tool window's listings again over the new session: the root +// when it could not be listed, otherwise the folders shown open. +func (a *App) refreshRemoteTree(p *project) { + if p.tree.failed != "" { + a.retryProjectTree(p) + return + } + a.resyncTreeListings(p) +} + +// reconnectRemoteByUser is Reconnect in the status bar. +func (a *App) reconnectRemoteByUser(surface actionSurface) { + p := a.project + if p == nil || p.remote == nil || p.remote.session != "" || p.remote.reconnecting != nil { + return + } + a.performed("remote.workspace.reconnect", surface) + a.reconnectRemote(p, true) +} + +// closeRemoteWorkspace ends the workspace's session while its project closes; nothing of the +// workspace runs afterwards. +func (a *App) closeRemoteWorkspace(p *project) { + r := p.remote + if r == nil || r.closed { + return + } + r.closed = true + r.stopRemoteTimer() + if r.reconnecting != nil { + r.reconnecting.cancel() + r.reconnecting = nil + } + r.binding.Detach() + a.releaseRemoteSession(r.session) + r.session, r.menuOpen = "", false +} + +// refuseRemote reports whether p is a remote workspace. When it is, a feature that runs only on +// this computer refuses: the refusal is logged with operation and a notification says the +// feature does not work in a remote workspace yet. +func (a *App) refuseRemote(p *project, operation string) bool { + if p == nil || p.remote == nil { + return false + } + a.operationRejected(operation, "remote_workspace") + a.notifyInfo(i18n.Shared(a.language(), "desktop.remote.workspace.localOnly")) + return true +} + +// openRemoteProject opens target as this workbench's project, which must have none: the window +// opens the folder in a new tab otherwise (windowSessions.openRemoteTab). The workspace takes +// target's session; when it cannot open, the session is ended. +func (a *App) openRemoteProject(target remoteTarget) { + if a.project != nil || a.closingProject { + a.releaseRemoteSession(target.session.ID) + return + } + name := path.Base(target.remoteRoot) + p := &project{root: target.root, name: name, commit: newCommitState()} + r := &remoteProject{connectionID: target.connectionID, name: target.name, connection: target.connection, home: target.session.HomeDirectory} + p.remote = r + r.binding = core.NewRemoteWorkspace(target.root, target.remoteRoot, func(session string) { + // A request of the workspace found the connection closed, on the request's goroutine. + a.post(func(a *App) { + if a.project == p { + a.loseRemote(p, session, errRemoteSessionClosed) + } + }) + }) + // The host's project never runs on this computer, so the workspace stays in safe mode. + ctx := core.WithRemoteWorkspace(core.WithProjectCodeAllowed(context.Background(), p.trust.allowed), r.binding) + p.ctx, p.cancel = context.WithCancel(ctx) + a.searchView.reset() + a.term = terminalUI{} + a.project = p + a.notice = "" + a.logView.reset() + a.worktreeView.reset() + a.attachRemote(p, target.session.ID) +} diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go new file mode 100644 index 000000000..ecab2e0cc --- /dev/null +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -0,0 +1,533 @@ +package workbench + +import ( + "context" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" +) + +// The host the tests connect to: its account's home directory and the folders below it. +const ( + remoteTestHost = "build.example" + remoteTestHome = "/home/dev" +) + +// remoteTestFolders are the host's folders the folder browser lists. +var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ + remoteTestHome: { + {Name: ".cache", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindDirectory}}, + {Name: "linked", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindSymlink, SymlinkTargetKind: core.RemoteFileKindDirectory}}, + {Name: "notes.txt", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindFile}}, + {Name: "project", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindDirectory}}, + }, + remoteTestHome + "/project": { + {Name: "README.md", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindFile}}, + {Name: "src", Metadata: core.RemoteFileMetadata{Kind: core.RemoteFileKindDirectory}}, + }, +} + +// remoteHostKernel stands in for a host over SSH: it opens numbered sessions, lists +// remoteTestFolders, answers heartbeats as the test says and lists the workspace's tree only +// for a request that carries the workspace's session. Everything else is the real Core. +type remoteHostKernel struct { + *testKernel + mu sync.Mutex + // refuse is the status the next connections end with; "" connects. + refuse core.RemoteProbeStatus + // state is the heartbeat's answer; once, when set, is the next heartbeat's alone. + state error + once error + connects int + servers [][]core.RemoteServerBuild + beats int + closed []string + // listings are the sessions the Project tool window's listings carried, "" for none. + listings []string +} + +func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.connects++ + k.servers = append(k.servers, request.Servers) + if request.Connection.Host != remoteTestHost { + return core.RemoteConnectResult{Status: core.RemoteProbeUnreachable}, nil + } + if k.refuse != "" { + return core.RemoteConnectResult{Status: k.refuse}, nil + } + session := &core.RemoteSession{ID: "session-" + strconv.Itoa(k.connects), HostName: "devbox", UserName: "dev", HomeDirectory: remoteTestHome} + return core.RemoteConnectResult{Status: core.RemoteProbeConnected, Session: session}, nil +} + +func (k *remoteHostKernel) RemoteReadDir(_ context.Context, _ string, dir string) (core.RemoteDirectory, error) { + entries, ok := remoteTestFolders[dir] + if !ok { + return core.RemoteDirectory{}, &core.Error{Command: "remote.readDir", Code: core.CodeWorkspaceNotFound, Message: "no such folder: " + dir} + } + return core.RemoteDirectory{Entries: entries, SkippedNonUTF8: 1}, nil +} + +func (k *remoteHostKernel) RemoteServerState(context.Context, string) error { + k.mu.Lock() + defer k.mu.Unlock() + k.beats++ + if err := k.once; err != nil { + k.once = nil + return err + } + return k.state +} + +func (k *remoteHostKernel) RemoteDisconnect(_ context.Context, id string) (bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.closed = append(k.closed, id) + return true, nil +} + +func (k *remoteHostKernel) ListDirectories(ctx context.Context, _ string, paths []string) ([]core.DirectoryListing, error) { + session := "" + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + session = binding.SessionID() + } + k.mu.Lock() + k.listings = append(k.listings, session) + k.mu.Unlock() + if session == "" { + return nil, &core.Error{Command: "workspace.listDirectories", Code: core.CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + listings := make([]core.DirectoryListing, 0, len(paths)) + for _, dir := range paths { + listing := core.DirectoryListing{Path: dir} + if dir == "" { + listing.Children = []core.WorkspaceNode{ + {Path: "src", Name: "src", IsDirectory: true}, + {Path: "README.md", Name: "README.md"}, + } + } + listings = append(listings, listing) + } + return listings, nil +} + +// set changes how the host answers. +func (k *remoteHostKernel) set(change func(k *remoteHostKernel)) { + k.mu.Lock() + defer k.mu.Unlock() + change(k) +} + +// count reads one of the host's counters. +func (k *remoteHostKernel) count(read func(k *remoteHostKernel) int) int { + k.mu.Lock() + defer k.mu.Unlock() + return read(k) +} + +// remoteTimers keeps the heartbeats and reconnections a workspace schedules, so a test runs each +// when it chooses instead of waiting for it. +type remoteTimers struct { + mu sync.Mutex + pending []*remoteTimer +} + +type remoteTimer struct { + after time.Duration + run func() + stopped bool +} + +func (s *remoteTimers) start(d time.Duration, f func()) func() bool { + s.mu.Lock() + defer s.mu.Unlock() + timer := &remoteTimer{after: d, run: f} + s.pending = append(s.pending, timer) + return func() bool { + s.mu.Lock() + defer s.mu.Unlock() + stopped := !timer.stopped + timer.stopped = true + return stopped + } +} + +// take is the one timer still pending, which no longer is; a workspace has at most one. +func (s *remoteTimers) take(t *testing.T) *remoteTimer { + t.Helper() + s.mu.Lock() + defer s.mu.Unlock() + var live []*remoteTimer + for _, timer := range s.pending { + if !timer.stopped { + live = append(live, timer) + } + } + s.pending = nil + if len(live) != 1 { + t.Fatalf("%d timers pending, want one", len(live)) + } + live[0].stopped = true + return live[0] +} + +// fire runs the pending timer, applies the heartbeat or the attempt it starts, and says how long +// the workspace had asked to wait. +func (h *harness) fire(t *testing.T, timers *remoteTimers) time.Duration { + t.Helper() + timer := timers.take(t) + timer.run() + // The timer posts to the window, which starts the heartbeat or the attempt; the next pass + // applies its result, which may start an attempt to connect again or the new session's first + // heartbeat, applied by the last pass. + h.settle() + h.settle() + h.settle() + return timer.after +} + +// countFailures counts the logged failures of operation, of the user's actions and of the +// window's own work alike. +func countFailures(logger *treeRecordingLog, operation string) int { + logger.mu.Lock() + defer logger.mu.Unlock() + n := 0 + for _, event := range logger.events { + if (event.Event == operationFailedEvent || event.Event == backgroundFailedEvent) && event.Fields["operation"] == operation { + n++ + } + } + return n +} + +// remoteWorkspaceHarness is an English window with one saved connection to remoteTestHost and the +// Remote Development window open on it, whose host is k and whose timers are timers'. +func remoteWorkspaceHarness(t *testing.T) (*harness, *remoteHostKernel, *remoteTimers, *treeRecordingLog) { + t.Helper() + k := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarnessWithLanguages(t, k, []string{"en-US"}) + logger := &treeRecordingLog{} + h.app.logSink = logger + timers := &remoteTimers{} + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + h.app.remoteBundle = func() (remoteserver.Bundle, error) { + return remoteserver.Bundle{Version: "0.0.0-test", Builds: []remoteserver.Build{{ + Target: "x86_64-unknown-linux-musl", Path: "/bundle/lithe-server", SHA256: strings.Repeat("0", 64), + }}}, nil + } + h.app.remoteAnchor = func() (string, error) { return anchor, nil } + h.app.remoteAfter = timers.start + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + r := &h.app.remote + r.form.host.SetText(remoteTestHost) + r.form.user.SetText("dev") + h.redraw() + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.save")) + h.settle() + if r.entry(r.selected) == nil || r.dirty() { + t.Fatal("the connection was not saved and selected") + } + return h, k, timers, logger +} + +// clickFront clicks the front-most control named label: the Remote Development window and the +// status bar's menu are declared over the welcome page and the workbench, whose controls share +// names such as Open with theirs. +func (h *harness) clickFront(label string) { + h.t.Helper() + h.click(center(h.frontLabeled(label))) +} + +// 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.await("the home folder's listing", func() bool { + b := h.app.remote.browser + return b != nil && !b.loading + }) + h.settle() + return h.app.remote.browser +} + +// openRemoteTestProject connects, chooses the project folder and opens it, and waits for the +// Project tool window's listing. +func (h *harness) openRemoteTestProject(t *testing.T) *project { + t.Helper() + return h.openBrowsedProject(t, h.connectAndBrowse(t)) +} + +// openBrowsedProject chooses the project folder in b, opens it and waits for the Project tool +// window's listing. +func (h *harness) openBrowsedProject(t *testing.T, b *remoteBrowser) *project { + t.Helper() + h.clickFront("project") + h.settle() + if got := b.target(); got != remoteTestHome+"/project" { + t.Fatalf("Open would open %q, want the selected folder", got) + } + if !h.shows(i18n.SharedFormat(h.app.language(), "desktop.remote.browse.target", map[string]string{"path": remoteTestHome + "/project"})) { + t.Fatal("the footer does not show the folder Open opens") + } + h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.browse.open")) + h.await("the workspace's tree and first heartbeat", func() bool { + p := h.app.project + return p != nil && p.remote != nil && !p.remote.beating && p.tree.root != nil && p.tree.root.listed && !p.tree.reading + }) + h.settle() + return h.app.project +} + +// Connect lists the host account's home folder, its folders and links to folders with hidden ones +// last, and Open opens the selected one as a remote workspace: its root is a placeholder of the +// cache directory, its title names the connection, the status bar shows the connection, and the +// folder is remembered with the connection. Neither the host nor its paths are logged. +func TestRemoteWorkspaceOpensTheChosenFolder(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + b := h.connectAndBrowse(t) + if got, want := b.folders, []string{"linked", "project", ".cache"}; !slices.Equal(got, want) { + t.Fatalf("listed %q, want %q", got, want) + } + if !h.shows(i18n.SharedFormat(lang, "desktop.remote.browse.connected", map[string]string{"name": remoteTestHost})) || + !h.showsWrapped(remoteSkippedText(lang, 1)) || h.shows("notes.txt") { + t.Fatal("the browser does not show the connection with the home folder's subfolders") + } + if servers := k.servers[0]; len(servers) != 1 || servers[0].Path != "/bundle/lithe-server" { + t.Fatalf("connected with %+v, want the client's server builds", servers) + } + + p := h.openBrowsedProject(t, b) + r := p.remote + if h.app.remote.open || r == nil || r.session != "session-1" { + t.Fatalf("window open = %v, remote = %+v: the workspace did not take the session", h.app.remote.open, r) + } + entry := savedRemoteConnections(t, h)[0] + anchor, _ := h.app.remoteAnchor() + if want := remoteplaceholder.Root(anchor, entry.ID, remoteTestHome+"/project"); p.root != want { + t.Fatalf("root %q, want the placeholder %q", p.root, want) + } + if !slices.Equal(entry.RecentFolders, []string{remoteTestHome + "/project"}) { + t.Fatalf("remembered %q, want the opened folder", entry.RecentFolders) + } + if got, want := h.app.projectDisplayName(p), "project [SSH: "+remoteTestHost+"]"; got != want { + t.Fatalf("title %q, want %q", got, want) + } + if !h.shows("README.md") || !h.shows(remoteStatusText(lang, r)) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.banner")) { + t.Fatal("the workspace does not show its tree, its connection and what works in it") + } + if got := k.listings; len(got) == 0 || slices.Contains(got, "") { + t.Fatalf("listings carried sessions %q, want the workspace's on every one", got) + } + if k.beats == 0 || r.link != remoteConnected { + t.Fatalf("beats = %d, link = %v: the heartbeat did not start", k.beats, r.link) + } + 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"} + if got := remoteActions(logger); !slices.Equal(got, want) { + t.Fatalf("performed %q, want %q", got, want) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// What still runs on this computer refuses in a remote workspace and says so: opening a file, a +// terminal, trusting the folder and every tool window but the project's and the notifications'. +// Copying a path copies the host's. +func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { + h, _, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + localOnly := i18n.Shared(lang, "desktop.remote.workspace.localOnly") + + h.app.openFile(p, filepath.Join(p.root, "README.md")) + if h.app.newTerminalWith(p, terminalOptions{}) != nil { + t.Fatal("a terminal started in the remote workspace") + } + asked := false + h.app.askToTrustProject(p, func() { asked = true }) + h.settle() + if asked || p.trust.asking || p.selectedDocument(p.terms.bench.FocusedGroup) != nil { + t.Fatal("the workspace opened a file or asked to be trusted") + } + for _, operation := range []string{"open_file", "open_terminal", "project_trust"} { + if !rejected(logger, operation, "remote_workspace") { + t.Fatalf("%s was not logged as refused", operation) + } + } + if list := h.app.notifications.list; len(list) == 0 || list[0].text != localOnly { + t.Fatal("the refusal was not notified") + } + + h.app.openToolWindow(itemGit) + h.redraw() + if !h.showsWrapped(localOnly) { + t.Fatal("the Git tool window does not say it does not work here") + } + + // Search Everywhere does not search the host's files yet: it offers only actions, as for a + // file opened on its own, and Tab does not switch to another scope. + h.app.openEverywhere(p) + h.app.everywhereView.scope = 0 + h.redraw() + if p.everywhere.scope != everywhereScopeActions { + t.Fatal("Search Everywhere searches the remote workspace's files") + } + h.app.closeEverywhere(p) + + var copied []string + saved := treeCopyText + treeCopyText = func(text string) error { + copied = append(copied, text) + return nil + } + t.Cleanup(func() { treeCopyText = saved }) + h.app.copyTreePath(filepath.Join(p.root, "src", "main.go"), false) + h.app.copyTreePath(p.root, false) + h.app.copyTreePath(filepath.Join(p.root, "src", "main.go"), true) + if want := []string{remoteTestHome + "/project/src/main.go", remoteTestHome + "/project", "src/main.go"}; !slices.Equal(copied, want) { + t.Fatalf("copied %q, want %q", copied, want) + } +} + +// Unanswered heartbeats show the connection not responding; the third ends the session, and the +// workspace connects again on its own, pausing longer each time, until it gives up and shows it +// disconnected. Reconnect in the status bar's menu then connects and lists the tree again over the +// new session, and Disconnect and Close ends the session and closes the workspace. +func TestRemoteWorkspaceReconnectsAfterMissedHeartbeats(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + r := p.remote + + k.set(func(k *remoteHostKernel) { k.state = context.DeadlineExceeded }) + for miss := 1; miss < remoteHeartbeatMisses; miss++ { + if d := h.fire(t, timers); d != remoteHeartbeatInterval { + t.Fatalf("heartbeat after %v, want %v", d, remoteHeartbeatInterval) + } + if r.link != remoteUnresponsive || r.session != "session-1" || !h.shows(remoteStatusText(lang, r)) { + t.Fatalf("after %d misses: link %v, session %q", miss, r.link, r.session) + } + } + k.set(func(k *remoteHostKernel) { k.refuse = core.RemoteProbeUnreachable }) + h.fire(t, timers) + if r.session != "" || r.link != remoteReconnecting || !slices.Contains(k.closed, "session-1") { + t.Fatalf("after the last miss: session %q, link %v, closed %q", r.session, r.link, k.closed) + } + var pauses []time.Duration + for r.link == remoteReconnecting { + pauses = append(pauses, h.fire(t, timers)) + } + if want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second}; !slices.Equal(pauses, want) { + t.Fatalf("paused %v before connecting again, want %v", pauses, want) + } + if got := k.count(func(k *remoteHostKernel) int { return k.connects }); got != 1+remoteReconnectAttempts { + t.Fatalf("connected %d times, want the first and %d attempts", got, remoteReconnectAttempts) + } + if r.link != remoteDisconnected || !h.shows(remoteStatusText(lang, r)) { + t.Fatalf("link %v after the last attempt, want disconnected", r.link) + } + + k.set(func(k *remoteHostKernel) { k.refuse, k.state = "", nil }) + listed := k.count(func(k *remoteHostKernel) int { return len(k.listings) }) + h.clickFront(i18n.Shared(lang, "desktop.remote.status.label")) + h.settle() + if !h.shows(r.remoteLocation()) || !h.shows(i18n.Shared(lang, "desktop.remote.probe.unreachable")) { + t.Fatal("the menu does not show the workspace and why connecting again failed") + } + h.clickFront(i18n.Shared(lang, "desktop.remote.status.reconnect")) + h.await("the new session", func() bool { return r.session != "" && !r.beating && !p.tree.reading }) + h.settle() + if r.link != remoteConnected || r.failure != nil || k.count(func(k *remoteHostKernel) int { return len(k.listings) }) == listed { + t.Fatalf("link %v, failure %+v: Reconnect did not connect and list the tree again", r.link, r.failure) + } + session := r.session + + h.clickFront(i18n.Shared(lang, "desktop.remote.status.label")) + h.settle() + h.clickFront(i18n.Shared(lang, "desktop.remote.status.disconnect")) + h.await("the workspace to close", func() bool { return h.app.project == nil }) + h.settle() + if !slices.Contains(k.closed, session) { + t.Fatalf("closed %q, want the workspace's session %q", k.closed, session) + } + // The first miss, the lost session and the attempt that gave up are logged once each; the + // misses after the first and the attempts before the last are the same failure. + for _, operation := range []string{"remote_heartbeat", "remote_session_lost", "remote_reconnect"} { + if got := countFailures(logger, operation); got != 1 { + t.Fatalf("%s logged %d times, want once", operation, got) + } + } + want := []string{"remote.workspace.reconnect", "remote.workspace.disconnect"} + if got := remoteActions(logger); !slices.Equal(got[len(got)-2:], want) { + t.Fatalf("performed %q, want it to end with %q", got, want) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A heartbeat that finds the connection closed ends the session at once, and the workspace +// connects again on its own over a new session. +func TestRemoteWorkspaceReconnectsWhenTheConnectionCloses(t *testing.T) { + h, k, timers, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + r := p.remote + k.set(func(k *remoteHostKernel) { + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fire(t, timers) + h.await("the new session", func() bool { return r.session == "session-2" && !r.beating && !p.tree.reading }) + if r.link != remoteConnected || !slices.Contains(k.closed, "session-1") { + t.Fatalf("link %v, closed %q: the lost session was not replaced", r.link, k.closed) + } +} + +// Back ends the browser's session and shows the form again; a folder that does not exist says so +// in the browser and keeps Open disabled. +func TestRemoteBrowserBackEndsTheSession(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + b := h.connectAndBrowse(t) + b.path.SetText("~/missing") + h.app.goRemoteFolder() + h.await("the missing folder", func() bool { return !b.loading }) + h.settle() + if b.dir != remoteTestHome+"/missing" || b.openable() || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.browse.notFound")) { + t.Fatalf("dir %q, openable %v: the missing folder is not reported", b.dir, b.openable()) + } + b.path.SetText("relative/path") + h.app.goRemoteFolder() + h.settle() + if !rejected(logger, "remote_read_dir", "path_not_absolute") { + t.Fatal("a relative path was not refused") + } + + h.clickFront(i18n.Shared(lang, "desktop.remote.browse.back")) + h.settle() + h.settle() + 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")) { + t.Fatal("Back does not show the form again") + } + if event := loggedAny(t, logger, remoteTestHome); event != "" { + t.Fatalf("logged a host path: %s", event) + } +} diff --git a/desktop/internal/workbench/remote_workspace_visual_test.go b/desktop/internal/workbench/remote_workspace_visual_test.go new file mode 100644 index 000000000..fbf2c51fd --- /dev/null +++ b/desktop/internal/workbench/remote_workspace_visual_test.go @@ -0,0 +1,106 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualRemoteWorkspace captures a remote workspace being opened: the host's home folder in +// the Remote Development window with a folder chosen, the workspace it opened with its notice and +// status bar item, and the status bar's menu of the connection. +func TestVisualRemoteWorkspace(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language, suffix string }{ + {"light", "en-US", "light-en-US"}, + {"dark", "zh-Hans", "dark-zh-CN"}, + } { + t.Run(look.suffix, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + shot := func(scene string) { + t.Helper() + // The scenes set the window's state directly, which does not ask for a frame. + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "remote-workspace-"+scene+"-"+look.suffix+".png")); err != nil { + t.Fatal(err) + } + } + timers := &remoteTimers{} + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + h.app.remoteBundle = func() (remoteserver.Bundle, error) { + return remoteserver.Bundle{Version: "0.0.0-visual", Builds: []remoteserver.Build{{ + Target: "x86_64-unknown-linux-musl", Path: "/bundle/lithe-server", SHA256: strings.Repeat("0", 64), + }}}, nil + } + h.app.remoteAnchor = func() (string, error) { return anchor, nil } + h.app.remoteAfter = timers.start + h.app.openRemote(surfaceMenu) + h.settleChain() + r := &h.app.remote + r.selectNew() + r.form.name.SetText("Build box") + r.form.host.SetText(remoteTestHost) + r.form.user.SetText("dev") + h.app.saveRemote() + h.settleChain() + if r.err != "" || r.fieldErr.field != "" { + t.Fatalf("saving the connection: %q %+v", r.err, r.fieldErr) + } + + b := h.connectAndBrowse(t) + h.clickFront("project") + h.settleChain() + if b.target() != remoteTestHome+"/project" { + t.Fatal("the project folder was not chosen") + } + shot("browse") + + h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.browse.open")) + h.await("the remote workspace's tree", func() bool { + p := h.app.project + return p != nil && p.remote != nil && !p.remote.beating && p.tree.root != nil && p.tree.root.listed && !p.tree.reading + }) + shot("opened") + + h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.status.label")) + h.settleChain() + if !h.app.project.remote.menuOpen { + t.Fatal("the connection's menu did not open") + } + shot("menu") + h.app.project.remote.menuOpen = false + }) + } +} diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index 2dad4c959..597bfe050 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -146,8 +146,15 @@ func (a *App) startProjectSearchWatch(p *project) { if p.everywhere.watchAttached { p.everywhere.watchReady, p.everywhere.watchAvailable = false, false } - a.tasks.running.Add(1) wake := func() { a.post(func(a *App) { a.drainProjectSearchWatch(p, slot) }) } + if p.remote != nil { + // A remote workspace's folder is on the host, which the local watch cannot observe: the + // search runs without a watch, as where none is available. + slot.finish(nil, nil) + wake() + return + } + a.tasks.running.Add(1) go func() { defer a.tasks.running.Done() watch, err := app.WatchTree(p.root, nil, wake) diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index 5843950e2..e4d1e0514 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -151,6 +151,13 @@ type everywhereSearch struct { pending []string } +// everywhereActionsOnly reports whether Search Everywhere offers only actions in p: a file +// opened on its own has no folder to search, and a remote workspace does not search the host's +// files yet (its results could not be opened either). +func (p *project) everywhereActionsOnly() bool { + return p.standalone || p.remote != nil +} + func (a *App) openEverywhere(p *project) { if a.everywhereView.open { a.focusEverywhere(p) @@ -158,7 +165,7 @@ func (a *App) openEverywhere(p *project) { } a.everywhereView.open = true a.everywhereView.scope = 0 - if p.standalone { + if p.everywhereActionsOnly() { a.everywhereView.scope = everywhereScopeActions } a.everywhereView.query.SetText("") @@ -211,7 +218,7 @@ func (a *App) closeEverywhere(p *project) { func (a *App) updateEverywhere(p *project, query string, scope int) { v, s := &a.everywhereView, &p.everywhere - if p.standalone { + if p.everywhereActionsOnly() { scope = everywhereScopeActions } options := v.options(scope) diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index 53ba6a0cc..3a18fb4aa 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -34,7 +34,7 @@ func (a *App) everywherePopup(c ui.C) { } s := &p.everywhere scope := v.effectiveScope() - if p.standalone { + if p.everywhereActionsOnly() { scope = everywhereScopeActions } a.updateEverywhere(p, v.query.Text(), scope) @@ -60,7 +60,7 @@ func (a *App) everywherePopup(c ui.C) { Width: width, Offset: 1, Align: ui.Start, KeepOpenOnAnchor: true, }, &v.open, func() { ui.Column(c).FillWidth().Height(height).Gap(8).Children(func() { - if p.standalone { + if p.everywhereActionsOnly() { ui.Text(c, i18n.Shared(language, "desktop.everywhere.actions")).Bold() } else { a.everywhereScopes(c, p, language) @@ -553,7 +553,7 @@ func (a *App) everywhereKey(p *project, event gfx.KeyEvent) gfx.EventResult { } } v := &a.everywhereView - if !p.standalone && event.Key == gfx.KeyTab && (event.Modifiers == 0 || event.Modifiers == gfx.ModifierShift) { + if !p.everywhereActionsOnly() && event.Key == gfx.KeyTab && (event.Modifiers == 0 || event.Modifiers == gfx.ModifierShift) { step := 1 if event.Modifiers == gfx.ModifierShift { step = -1 @@ -565,7 +565,7 @@ func (a *App) everywhereKey(p *project, event gfx.KeyEvent) gfx.EventResult { if event.Modifiers != 0 { return gfx.EventResult{} } - if p.standalone || v.effectiveScope() == everywhereScopeActions { + if p.everywhereActionsOnly() || v.effectiveScope() == everywhereScopeActions { switch event.Key { case gfx.KeyUp: v.actionSelected = max(0, v.actionSelected-1) diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 89f8b972f..389812783 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -169,6 +169,12 @@ func (a *App) toolBody(c ui.C, tool item, p *project) { body.Children(func() { a.toolPlaceholder(c) }) return } + if p.remote != nil && tool.id != itemProject && tool.id != itemNotifications { + // A remote workspace lists the host's files; every other tool window reads or runs + // the project on this computer, so it says it does not work there yet. + body.Children(func() { a.safeModePanel(c, p, "") }) + return + } body.Clip().Children(func() { switch tool.id { case itemGit: @@ -318,6 +324,13 @@ func (a *App) toolTabsWith(c ui.C, selected int, labels []string, choose func(in }) } +// emptyEditorHint is a command an empty editor shows with its shortcuts. +type emptyEditorHint struct { + label string + // command is the keymap command whose fixed gesture and bindings are shown. + command string +} + // editorArea declares the editor area. Once a terminal has been dragged into it, or a file // opened, it is the groups of tabs those are in (see editorGroups). Until then there is no // editor, so it shows what an empty one shows: the commands that open something and where to @@ -337,14 +350,26 @@ func (a *App) editorArea(c ui.C) { }) return } - hints := [...]struct { - label string - // command is the keymap command whose fixed gesture and bindings are shown. - command string - }{ + hints := [...]emptyEditorHint{ {a.text.Editor.SearchEverywhere, "search.everywhere"}, {a.text.Editor.FindInFiles, "search.files"}, } + if p := a.project; p != nil && p.remote != nil { + // A remote workspace opens no file yet, so the notice that says what works in it stands + // over the empty editor. Find in Files does not search the host yet, and Search Everywhere + // offers only actions there (project.everywhereActionsOnly). + ui.Column(c.Part("remote")).Fill().Children(func() { + a.safeModeNotice(c.Part("safeMode"), p) + a.emptyEditorHints(c, hints[:1]) + }) + return + } + a.emptyEditorHints(c, hints[:]) +} + +// emptyEditorHints declares an empty editor: the commands that find something to open, with +// their shortcuts. +func (a *App) emptyEditorHints(c ui.C, hints []emptyEditorHint) { editor := ui.Column(c).Fill().Clip().Center().Pad(shellContentPad).Background(a.colors.Editor).Radius(workbenchPanelRadius).Children(func() { ui.Column(c).FillWidth().MaxWidth(shellHintWidth).Children(func() { // Labels end and shortcuts start at one line down the middle, so the two read as diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index 71dc05c3d..4d3204e15 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -384,6 +384,9 @@ type terminalOptions struct { // newTerminalWith is newTerminal with the options of a plugin terminal. func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { + if a.refuseRemote(p, "open_terminal") { + return nil + } shell := options.shell if shell == "" && options.plugin == nil { shell = a.settings.TerminalShell diff --git a/desktop/internal/workbench/window_sessions.go b/desktop/internal/workbench/window_sessions.go index fba499721..45cab524a 100644 --- a/desktop/internal/workbench/window_sessions.go +++ b/desktop/internal/workbench/window_sessions.go @@ -250,6 +250,20 @@ func (s *windowSessions) openTab(path string) { a.openProjectHere(path) } +// openRemoteTab opens the remote workspace target in a new workbench of the window, in a tab after +// the others, and shows it. from is the workbench whose Remote Development window connected it: +// every tab shares the kernel, so the new tab takes over the session from opened, and what tests +// replaced in from. +func (s *windowSessions) openRemoteTab(from *App, target remoteTarget) { + a := New(s.options) + a.remoteBundle, a.remoteAnchor, a.remoteAfter = from.remoteBundle, from.remoteAnchor, from.remoteAfter + s.list = append(s.list, a) + s.activate(a) + a.reloadPluginLanguages() + a.loadGitHubAccount() + a.openRemoteProject(target) +} + // leave takes workbench a out of the strip once its project has closed, when the window has // other tabs. The tab beside it is then shown. The last workbench stays and shows the welcome // screen. diff --git a/desktop/internal/workbench/window_title.go b/desktop/internal/workbench/window_title.go index 0f90b2aab..ab0f5fe6f 100644 --- a/desktop/internal/workbench/window_title.go +++ b/desktop/internal/workbench/window_title.go @@ -4,6 +4,8 @@ import ( "path/filepath" "runtime" "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) // The system title of the window names what it shows, so the task switcher, the taskbar @@ -40,9 +42,13 @@ func (a *App) windowTitle() string { // projectDisplayName is the name the taskbar and Alt+Tab show for p: its folder's name, or // that name under the folder above it when another open tab shows a project of the same name, -// so two checkouts of one repository do not look alike. +// so two checkouts of one repository do not look alike. A remote workspace's name says the +// connection it is on, as "folder [SSH: connection]". func (a *App) projectDisplayName(p *project) string { name := p.name + if r := p.remote; r != nil { + return i18n.SharedFormat(a.language(), "desktop.remote.workspace.title", map[string]string{"folder": name, "connection": r.name}) + } if !a.projectNameShared(p) { return name } diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index f38609103..ab826c906 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -169,7 +169,7 @@ func (a *App) requireProjectTrust(p *project, proceed func()) { // askToTrustProject asks to trust the open project p in safe mode, from the notice above the // editor or before an action that runs project code; then, when set, it runs proceed. func (a *App) askToTrustProject(p *project, proceed func()) { - if p.trust.asking { + if p.trust.asking || a.refuseRemote(p, "project_trust") { return } p.trust.asking = true @@ -276,17 +276,25 @@ func (a *App) skipUntrustedModel(instance *buildInstance) { // safeModePanel declares what a tool window shows in safe mode in place of what it would read by // running project code: message, and the button that asks to trust the project. +// +// A remote workspace stays in safe mode, since the host's project never runs on this computer: +// its panel says the feature does not work there yet and has no button. func (a *App) safeModePanel(c ui.C, p *project, message string) { + remote := p.remote != nil + if remote { + message = i18n.Shared(a.language(), "desktop.remote.workspace.localOnly") + } ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Subtle) - if ui.Button(c.Key("trust"), i18n.Shared(a.language(), "desktop.trust.bannerLink")).Ghost().Disabled(p.trust.asking).Clicked() { + if !remote && ui.Button(c.Key("trust"), i18n.Shared(a.language(), "desktop.trust.bannerLink")).Ghost().Disabled(p.trust.asking).Clicked() { c.After(func() { a.askToTrustProject(p, nil) }) } }) } // safeModeNotice declares the notice above the editor of a project in safe mode, with the link -// that asks to trust it, as IDEA's editor notification does. +// that asks to trust it, as IDEA's editor notification does. A remote workspace's notice says +// what works in it and has no link: it is not trusted on this computer. func (a *App) safeModeNotice(c ui.C, p *project) { background, border, foreground := gfx.RGB24(0xFFF6E9), gfx.RGB24(0xF4CD9A), gfx.RGB24(0x000000) if a.colors.Dark { @@ -297,8 +305,12 @@ func (a *App) safeModeNotice(c ui.C, p *project) { ui.Row(c.Part("top")).FillWidth().Height(1).Shrink(0).Background(border) ui.Row(c).FillWidth().Gap(conflictGap).PadX(conflictPadX).PadY(conflictPadY).Items(ui.Center).Children(func() { ui.Icon(c, icons.BannerWarning).Size(conflictIcon, conflictIcon).Shrink(0).Color(gfx.RGB24(0xFFFFFF)) - ui.Paragraph(c, i18n.Shared(language, "desktop.trust.banner"), conflictMaxRows).FontSize(13).Color(foreground).Grow(1).Shrink(1) - if ui.Button(c.Key("trust"), i18n.Shared(language, "desktop.trust.bannerLink")).Link().Disabled(p.trust.asking).Clicked() { + text := i18n.Shared(language, "desktop.trust.banner") + if p.remote != nil { + text = i18n.Shared(language, "desktop.remote.workspace.banner") + } + ui.Paragraph(c, text, conflictMaxRows).FontSize(13).Color(foreground).Grow(1).Shrink(1) + if p.remote == nil && ui.Button(c.Key("trust"), i18n.Shared(language, "desktop.trust.bannerLink")).Link().Disabled(p.trust.asking).Clicked() { c.After(func() { a.askToTrustProject(p, nil) }) } }) diff --git a/docs/assets/remote-connections/README.md b/docs/assets/remote-connections/README.md index aa95d7167..85d0a493a 100644 --- a/docs/assets/remote-connections/README.md +++ b/docs/assets/remote-connections/README.md @@ -3,7 +3,7 @@ 来自生产 Viva Page 的无头渲染。连接列表由真实 Core 写入测试临时偏好目录,颜色、分组和分组顺序都由 Core 保存和给出;“测试连接”的结果由测试替换的内核直接返回固定的主机信息,不启动 OpenSSH,密码询问由测试直接放入提问队列。截图里的主机、用户和路径都是虚构的。截图覆盖深色与浅色主题、中文与英文界面,用于确认: - 左侧列表按 Core 给出的分组列出连接,分组标题带数量,没有分组的连接排在最后的“未分组”下;每个连接左侧是它的颜色条; -- 选中已保存的连接时右侧显示概览:颜色图标、名称、分组标签、地址和跳板机,“主机信息”显示这次运行中最近一次测试得到的系统、CPU、内存和磁盘,“连接设置”逐项列出设置,未填写的项显示它的回退规则,例如“自动(SSH 配置,否则 22)”; +- 选中已保存的连接时右侧显示概览:颜色图标、名称、分组标签、地址和跳板机,“主机信息”显示这次运行中最近一次测试得到的系统、CPU、内存和磁盘,“连接设置”逐项列出设置,未填写的项显示它的回退规则,例如“自动(SSH 配置,否则 22)”;底部是“删除”“测试连接”“关闭”和“连接”,连接后的文件夹选择见 `docs/assets/remote-workspace`; - 点“编辑”后右侧换成表单:名称与颜色、主机与端口、用户名、身份验证与私钥、分组各占一行,高级选项折叠在下方; - 新建连接时可以选“新建分组…”并在旁边输入分组名;主机字段填了 `user@host` 时,Core 拒绝的原因显示在主机字段下方,没有写入列表; - OpenSSH 询问密码时,窗口上方弹出“SSH 身份验证”,提示原文照搬,输入框为密码框,说明答案只交给这次连接、不会保存。 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 905b2388e..12d3a54d3 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 035cbfa85..50be006b8 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 33d0ade83..292cfda6a 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 5630a59c0..66c7485ef 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-workspace/README.md b/docs/assets/remote-workspace/README.md new file mode 100644 index 000000000..260273410 --- /dev/null +++ b/docs/assets/remote-workspace/README.md @@ -0,0 +1,18 @@ +# 远程工作区(#2231)无头测试截图 + +来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表和心跳也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- 连接后“远程开发”窗口改为主机的文件夹选择:顶部是连接名和 `用户@主机`,路径框可以输入 `~` 或 `/` 开头的路径,无法读取的条目在列表下方说明数量,底部显示将打开的主机路径; +- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明远程工作区暂时只能浏览文件夹,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; +- 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”。 + +截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 + +| 场景 | 浅色英文 | 深色中文 | +| --- | --- | --- | +| 选择主机文件夹 | [浅色英文](remote-workspace-browse-light-en-US.png) | [深色中文](remote-workspace-browse-dark-zh-CN.png) | +| 打开的远程工作区 | [浅色英文](remote-workspace-opened-light-en-US.png) | [深色中文](remote-workspace-opened-dark-zh-CN.png) | +| 状态栏连接菜单 | [浅色英文](remote-workspace-menu-light-en-US.png) | [深色中文](remote-workspace-menu-dark-zh-CN.png) | + +复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/remote-workspace"`,在 `desktop/` 下通过 +`../scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualRemoteWorkspace$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png new file mode 100644 index 000000000..99f4185d6 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png new file mode 100644 index 000000000..2bfc8e4ce Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png new file mode 100644 index 000000000..1b7a6f6d1 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-menu-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-menu-light-en-US.png new file mode 100644 index 000000000..fdf5ce1cb Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-menu-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-opened-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-opened-dark-zh-CN.png new file mode 100644 index 000000000..ae4ba79ac Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-opened-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-opened-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-opened-light-en-US.png new file mode 100644 index 000000000..1429dcffa Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-opened-light-en-US.png differ diff --git a/docs/ci-builds.md b/docs/ci-builds.md index a3753ecea..3acb1fd63 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -91,7 +91,9 @@ Viva 的 Core 源码检出、Cargo 目标目录和暂存静态库位于当前工 `winapi-import-libraries=mingw-system`。这避免 cgo 依赖 Cargo 私有路径中的 `libwinapi_*` 归档;不增加下载、缓存目录或运行期资源。能否把这些构建状态复制到另一个工作树,见下文 `.artifacts/desktop/` 一段。Core 仓库恢复的 `scripts/rust-core/verify-rust-core-comments.sh` 先用固定词法器检查真实注释,再检查 Rustdoc;调用方应沿用本工作树的 `CARGO_TARGET_DIR`。独立 Core 检出未提供该变量时,输出只进入该检出的 `.artifacts/rust-core-checks/`(桌面默认检出内为 `.artifacts/desktop/lithe-core-rust/source/.artifacts/rust-core-checks/`)。词法器二进制、Cargo 状态与 Rustdoc 受 Core 修订、helper Cargo.lock、目标、编译器及环境约束,随 Core 构建状态一起处理;只在构建/验证阶段生成,不进入安装包,不影响签名或增量更新。 Viva 的 IDE API 辅助程序 `lithe-mcp` 由 `scripts/desktop/build-desktop-core.sh` 在同一固定 Core 检出上以 `features=mcp` 编到暂存目录的 `bin/`。`package-desktop.sh` 在 `viva package` 前把它复制成 `desktop/internal/idehelp/lithe-mcp.bin`,以 `lithe_bundled_helper` 构建标签嵌入客户端二进制,打包结束或失败时删除该生成文件;文件被 Git 忽略,不跨工作树复制。运行期客户端把嵌入的字节原子安装到应用数据目录的 `ide-host/bin/` 再启动,安装包本身不增加可执行文件、不被写入,也不改变签名或增量更新基线;开发运行由 `desktop-go.sh` 用暂存目录里的辅助程序通过 `LITHE_IDE_HELPER` 提供,不读取安装目录。 -远端工作区服务 `lithe-remote-server`(#2231)也嵌入客户端二进制:`package-desktop.sh` 在 `viva package` 前取得一个暂存目录(CI 通过 `LITHE_REMOTE_SERVER_STAGE` 给出可复用工作流已经冒烟测试过的产物,用 `--require-pinned` 校验;本地打包运行 `build-remote-server.sh` 重新编译,不要求固定提交),用 `verify-remote-server-artifacts.mjs` 校验后,再逐个核对体积和 SHA-256,复制成 `desktop/internal/remoteserver/<目标>.bin` 和 `remote-server-manifest.json`,以 `lithe_bundled_remote_server` 构建标签嵌入;校验后字节有变化就停止打包。这些生成文件被 Git 忽略,打包开始前先删掉上一次中断留下的旧文件,打包结束或失败时再删除,不跨工作树复制。运行期由 `remoteserver.Install` 在连接远程主机时(连接流程在 #2231 后续阶段接上)把与清单哈希一致的字节原子安装到用户缓存目录 `/Lithe/remote-server/<目标>/lithe-remote-server`(目录 0700、文件 0600,字节相同就复用),再交给 Core 上传到远程主机;它不执行这个文件,不写安装目录,安装包里也不多出文件,签名和增量更新基线不受影响。删除该缓存目录是安全的,下次连接会重新安装。开发运行由 `desktop-go.sh` 在 `.artifacts/desktop/remote-server/` 有清单时导出 `LITHE_REMOTE_SERVER_STAGE`,客户端直接读取暂存目录并按清单校验,不复制;打包版只用嵌入的字节,忽略该变量。 +远端工作区服务 `lithe-remote-server`(#2231)也嵌入客户端二进制:`package-desktop.sh` 在 `viva package` 前取得一个暂存目录(CI 通过 `LITHE_REMOTE_SERVER_STAGE` 给出可复用工作流已经冒烟测试过的产物,用 `--require-pinned` 校验;本地打包运行 `build-remote-server.sh` 重新编译,不要求固定提交),用 `verify-remote-server-artifacts.mjs` 校验后,再逐个核对体积和 SHA-256,复制成 `desktop/internal/remoteserver/<目标>.bin` 和 `remote-server-manifest.json`,以 `lithe_bundled_remote_server` 构建标签嵌入;校验后字节有变化就停止打包。这些生成文件被 Git 忽略,打包开始前先删掉上一次中断留下的旧文件,打包结束或失败时再删除,不跨工作树复制。运行期由 `remoteserver.Install` 在远程开发窗口连接主机时把与清单哈希一致的字节原子安装到用户缓存目录 `/Lithe/remote-server/<目标>/lithe-remote-server`(目录 0700、文件 0600,字节相同就复用),再交给 Core 上传到远程主机;它不执行这个文件,不写安装目录,安装包里也不多出文件,签名和增量更新基线不受影响。删除该缓存目录是安全的,下次连接会重新安装。开发运行由 `desktop-go.sh` 在 `.artifacts/desktop/remote-server/` 有清单时导出 `LITHE_REMOTE_SERVER_STAGE`,客户端直接读取暂存目录并按清单校验,不复制;打包版只用嵌入的字节,忽略该变量。 + +打开的远程工作区以本机占位目录作为项目根(`desktop/internal/remoteplaceholder`)。所有占位目录都在锚点文件 `/Lithe/remote-workspaces` 之下:它是一个空的只读普通文件(0444,所在目录 0700),第一次打开远程工作区时创建,之后每次使用都检查它仍是普通文件,是目录、链接或其他类型就拒绝打开。占位目录因此永远无法在本机列出或创建,没走 Core 的本机文件调用会以 ENOTDIR(Windows 上为 ERROR_PATH_NOT_FOUND)失败,不会读写一个看起来像项目的本机文件夹。锚点不含数据、不随工作区关闭删除;手动删除是安全的,下次打开会重新创建。它属于用户缓存目录,不在任何检出或安装目录里,不跨工作树复制,也不影响签名和增量更新基线。 `viva package` 的链接参数是固定的,不能用 `-X` 注入构建信息,所以 `package-desktop.sh` 每次打包都生成 `desktop/internal/buildinfo/package_info.go`,以 `lithe_package_info` 构建标签编进客户端。文件记录更新渠道(`--stable` 为正式版,`--autobuild` 为 AutoBuild,本地包为空,不会自我更新)、构建时间(`LITHE_BUILD_TIME`,缺省为打包时刻)、提交(`LITHE_BUILD_COMMIT`,缺省为 `git HEAD`),以及验证更新源签名的公钥(`LITHE_UPDATE_PUBLIC_KEYS`,逗号分隔,只含公钥)。打包结束或失败时删除这个文件;它被 Git 忽略,不跨工作树复制。它只改变可执行文件本身,安装包里不会多出文件,签名和增量更新基线也不受影响。 打包和更新源签名用的 `viva` 命令由 `scripts/desktop/build-viva-tool.sh` 按 `desktop/go.mod` 的 `replace` 从 Viva fork 编译,放在当前工作树的 `.artifacts/desktop/tools/viva-<模块版本>/`;`replace` 指向本地目录时没有版本,放在 `viva-local/` 并每次重新编译。目录名只固定 Viva 源码,不记录 Go 工具链和主机平台;随 `.artifacts/desktop/` 一起复制时,必须满足下文的前提(含相同的 Go 工具链和主机平台),否则删掉该目录,由脚本在本工作树重新编译。它只在打包(`package-desktop.sh`)和签名更新源(`publish-update-feed.sh`)时使用,不进入安装包,不影响签名或增量更新基线。 diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 582ab0db8..7084e7913 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -628,6 +628,289 @@ "reason": "string" } }, + { + "id": "desktop.remote.connect", + "description": "Remote Development window: button that connects to the saved connection and lists the host's folders", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.connecting", + "description": "Remote Development window: notice while connecting to open a folder of the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.connect.notBundled", + "description": "Remote Development window: notice when this build of Lithe carries no remote server for the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.connect.serverInvalid", + "description": "Remote Development window: notice when the remote server failed its integrity check", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.connected", + "description": "Remote Development window, folder browser after connecting: heading with the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.browse.path", + "description": "Remote Development window, folder browser after connecting: accessible label of the path field of the folder shown", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.pathPlaceholder", + "description": "Remote Development window, folder browser after connecting: placeholder of the path field; Enter lists the folder typed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.up", + "description": "Remote Development window, folder browser after connecting: accessible label and tooltip of the button that lists the parent folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.refresh", + "description": "Remote Development window, folder browser after connecting: accessible label and tooltip of the button that lists the folder again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.recent", + "description": "Remote Development window, folder browser after connecting: heading of the folders opened over this connection before", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.folders", + "description": "Remote Development window, folder browser after connecting: accessible label of the list of subfolders", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.empty", + "description": "Remote Development window, folder browser after connecting: shown in place of the list when the folder has no subfolders", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.target", + "description": "Remote Development window, folder browser after connecting: footer text naming the host folder Open opens", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remote.browse.back", + "description": "Remote Development window, folder browser after connecting: button that returns to the connection's form and ends the session", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.open", + "description": "Remote Development window, folder browser after connecting: button that opens the chosen folder as a remote workspace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.opening", + "description": "Remote Development window, folder browser after connecting: the Open button while the folder opens", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.lost", + "description": "Remote Development window: notice on the form when the connection closed while browsing", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.notFound", + "description": "Remote Development window, folder browser after connecting: notice when the folder does not exist on the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.denied", + "description": "Remote Development window, folder browser after connecting: notice when the host account may not list the folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.pathInvalid", + "description": "Remote Development window, folder browser after connecting: notice when the path typed is not an absolute path of the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.browse.readFailed", + "description": "Remote Development window, folder browser after connecting: notice when the folder could not be listed; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.browse.anchorUnusable", + "description": "Remote Development window, folder browser after connecting: notice when the local folder that stands for remote workspaces cannot be prepared; path is that folder", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remote.browse.openFailed", + "description": "Remote Development window, folder browser after connecting: notice when the folder could not be opened; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.browse.skipped", + "description": "Remote Development window, folder browser after connecting: note under the list when entries could not be read; count is their number", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "integer" + } + }, + { + "id": "desktop.remote.status.label", + "description": "Status bar item of a remote workspace: accessible label of the button that opens the connection's menu", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.status.connected", + "description": "Status bar item of a remote workspace: text while connected, before the first round trip is known", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.status.latency", + "description": "Status bar item of a remote workspace: text while connected with the round trip of the last heartbeat in milliseconds", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "ms": "integer" + } + }, + { + "id": "desktop.remote.status.unresponsive", + "description": "Status bar item of a remote workspace: text when the last heartbeat went unanswered", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.status.reconnecting", + "description": "Status bar item of a remote workspace: text while connecting again after the connection was lost", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.status.disconnected", + "description": "Status bar item of a remote workspace: text when the connection was lost and connecting again failed", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.status.reconnect", + "description": "Status bar item of a remote workspace: menu item that connects again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.status.disconnect", + "description": "Status bar item of a remote workspace: menu item that ends the session and closes the workspace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.workspace.title", + "description": "Window title and task switcher name of a remote workspace", + "platforms": [ + "desktop" + ], + "parameters": { + "folder": "string", + "connection": "string" + } + }, + { + "id": "desktop.remote.workspace.banner", + "description": "Notice above the editor of a remote workspace: what works in it so far", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.workspace.localOnly", + "description": "Notification and tool window text when a feature does not work in a remote workspace yet", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.remote.edit", "description": "Remote Development window: button that turns the selected connection's overview into its form", @@ -893,7 +1176,42 @@ "desktop.remote.groupPlaceholder": "Group name", "desktop.remote.ungrouped": "Ungrouped", "desktop.remote.error.groupTooLong": "Too long: at most 64 characters.", - "desktop.remote.error.groupInvalid": "A group name cannot contain line breaks, tabs or other control characters." + "desktop.remote.error.groupInvalid": "A group name cannot contain line breaks, tabs or other control characters.", + "desktop.remote.connect": "Connect", + "desktop.remote.connecting": "Connecting… OpenSSH may ask for a password or to confirm the host key.", + "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.browse.connected": "Connected to {name}", + "desktop.remote.browse.path": "Folder path", + "desktop.remote.browse.pathPlaceholder": "/home/user/project or ~/project", + "desktop.remote.browse.up": "Parent Folder", + "desktop.remote.browse.refresh": "Refresh", + "desktop.remote.browse.recent": "Recent Folders", + "desktop.remote.browse.folders": "Folders", + "desktop.remote.browse.empty": "This folder has no subfolders.", + "desktop.remote.browse.target": "Opens {path}", + "desktop.remote.browse.back": "Back", + "desktop.remote.browse.open": "Open", + "desktop.remote.browse.opening": "Opening…", + "desktop.remote.browse.lost": "The connection to the host closed. Connect again to choose a folder.", + "desktop.remote.browse.notFound": "The folder does not exist on the host.", + "desktop.remote.browse.denied": "The host account is not allowed to open this folder.", + "desktop.remote.browse.pathInvalid": "Enter an absolute path of the host, such as /home/user/project or ~/project.", + "desktop.remote.browse.readFailed": "Cannot list the folder: {reason}", + "desktop.remote.browse.anchorUnusable": "Cannot prepare the local folder that stands for remote workspaces: {path}", + "desktop.remote.browse.openFailed": "Cannot open the folder: {reason}", + "desktop.remote.browse.skipped": "Entries not listed because they could not be read: {count}", + "desktop.remote.status.label": "Remote Connection", + "desktop.remote.status.connected": "SSH: {name}", + "desktop.remote.status.latency": "SSH: {name} · {ms} ms", + "desktop.remote.status.unresponsive": "SSH: {name} · Not responding", + "desktop.remote.status.reconnecting": "SSH: {name} · Reconnecting…", + "desktop.remote.status.disconnected": "SSH: {name} · Disconnected", + "desktop.remote.status.reconnect": "Reconnect", + "desktop.remote.status.disconnect": "Disconnect and Close", + "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", + "desktop.remote.workspace.banner": "This is a remote workspace. The Project tool window lists the host's files; editing, terminals, search, Git and running do not work here yet.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. The Project tool window lists the host's files." }, "zh-CN": { "desktop.remote.title": "远程开发", @@ -1001,7 +1319,42 @@ "desktop.remote.groupPlaceholder": "分组名称", "desktop.remote.ungrouped": "未分组", "desktop.remote.error.groupTooLong": "太长:最多 64 个字符。", - "desktop.remote.error.groupInvalid": "分组名不能包含换行、制表符等控制字符。" + "desktop.remote.error.groupInvalid": "分组名不能包含换行、制表符等控制字符。", + "desktop.remote.connect": "连接", + "desktop.remote.connecting": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", + "desktop.remote.connect.notBundled": "此版本的 Lithe 未包含适用于该主机的远端服务,无法打开主机上的文件夹。", + "desktop.remote.connect.serverInvalid": "远端服务未通过完整性校验,没有启动。请重新安装 Lithe 后再试。", + "desktop.remote.browse.connected": "已连接到 {name}", + "desktop.remote.browse.path": "文件夹路径", + "desktop.remote.browse.pathPlaceholder": "/home/user/project 或 ~/project", + "desktop.remote.browse.up": "上级文件夹", + "desktop.remote.browse.refresh": "刷新", + "desktop.remote.browse.recent": "最近的文件夹", + "desktop.remote.browse.folders": "文件夹", + "desktop.remote.browse.empty": "此文件夹没有子文件夹。", + "desktop.remote.browse.target": "将打开 {path}", + "desktop.remote.browse.back": "返回", + "desktop.remote.browse.open": "打开", + "desktop.remote.browse.opening": "正在打开…", + "desktop.remote.browse.lost": "与主机的连接已断开。请重新连接后再选择文件夹。", + "desktop.remote.browse.notFound": "主机上不存在此文件夹。", + "desktop.remote.browse.denied": "主机账户无权打开此文件夹。", + "desktop.remote.browse.pathInvalid": "请输入主机上的绝对路径,例如 /home/user/project 或 ~/project。", + "desktop.remote.browse.readFailed": "无法列出文件夹:{reason}", + "desktop.remote.browse.anchorUnusable": "无法准备代表远程工作区的本地文件夹:{path}", + "desktop.remote.browse.openFailed": "无法打开文件夹:{reason}", + "desktop.remote.browse.skipped": "有 {count} 个条目无法读取,未列出。", + "desktop.remote.status.label": "远程连接", + "desktop.remote.status.connected": "SSH: {name}", + "desktop.remote.status.latency": "SSH: {name} · {ms} 毫秒", + "desktop.remote.status.unresponsive": "SSH: {name} · 无响应", + "desktop.remote.status.reconnecting": "SSH: {name} · 正在重新连接…", + "desktop.remote.status.disconnected": "SSH: {name} · 已断开", + "desktop.remote.status.reconnect": "重新连接", + "desktop.remote.status.disconnect": "断开并关闭", + "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", + "desktop.remote.workspace.banner": "这是远程工作区。项目工具窗口可以浏览主机上的文件;编辑、终端、搜索、Git 和运行暂不可用。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,项目工具窗口可以浏览主机上的文件。" } } } diff --git a/shared/platform-feature-matrix/features/remote-connections.json b/shared/platform-feature-matrix/features/remote-connections.json index 5b4338c12..8bf39d66e 100644 --- a/shared/platform-feature-matrix/features/remote-connections.json +++ b/shared/platform-feature-matrix/features/remote-connections.json @@ -31,5 +31,5 @@ }, "owner": "Remote", "verification": "从欢迎页的“远程开发”按钮和标题栏项目菜单打开“远程开发”:新建连接只填主机,保存后列表以主机名命名并选中这一行,右侧显示概览;点“编辑”进入表单,改名称和端口后保存,回到概览且列表与偏好目录 remote/connections.json 同步;编辑中点“取消”回到原连接、不写文件;删除先在底部确认。选颜色并选“新建分组…”输入分组名后保存,左侧出现带数量的分组标题和颜色条,未分组的连接排在最后的“未分组”下,第二个连接可从下拉框选同一分组(大小写不同视为同一分组)。概览的“连接设置”逐项列出设置,未填的项显示回退规则(例如“自动(SSH 配置,否则 22)”);测试成功后概览的“主机信息”显示本次运行最近一次测试的结果,关闭再打开窗口仍在,未测试的连接显示提示。主机填 user@host、端口填非数字、分组超过 64 个字符时,错误显示在对应字段下且不写文件。对一台 Linux SSH 主机分别用 SSH Agent、私钥文件和密码测试连接:密码和带口令私钥的询问出现在窗口中,输入以圆点显示,取消或关闭窗口立即停止测试且不再追问;成功后显示系统、架构、CPU、内存和主目录磁盘。首次连接时 OpenSSH 确认主机指纹的询问同样出现在窗口中,由用户回答,Lithe 不替用户接受;拒绝指纹或指纹已改变时测试失败并说明原因。日志只有 remote.connections.open、remote.connection.new/select/edit/edit.cancel/save/remove/test/test.stop 和 remote.authentication.answer/cancel 等动作,不含主机、用户名、私钥路径、分组名、询问原文或答案。", - "notes": "Viva:连接列表的格式和字段规则在 Core(remote.connections、remote.editConnections),桌面端只读写偏好目录里的 remote/connections.json,按读取时的字节原子写回 Core 返回的文档,文件被改过时不覆盖;测试连接由 Core 运行 PATH 中的 OpenSSH,SSH 询问经 SSH_ASKPASS 指向 lithe 可执行文件的助手模式回到窗口,和 Git 认证共用同一个提问队列。Lithe 只把私钥路径交给 OpenSSH,不读取私钥内容,也不接受粘贴的私钥。macOS 用无头截图和真实 Core 的单元测试覆盖;Windows 上 OpenSSH 调用 GUI 子系统助手读取答案仍待实机验证。打开远程项目、文件夹选择和远端服务部署见 remote-development-workspace,仍未实现。 2026-11-21(#2231 窗口重设计):颜色(六种固定色或无)和分组随连接保存在 Core 的 connections.json(Lithe-IDEA/Lithe-core-rust#152),分组顺序由 Core 的 sections 给出(按首次使用的顺序,未分组在最后),桌面端只展示;概览的“主机信息”只保存在本次运行的内存里,不写文件。连接、打开文件夹、搜索、从 Motty 或 SSH 配置导入、ssh -G 实际生效值和最近一次测试时间尚未实现。自动化:TestRemoteConnectionsColorAndGroup、TestRemoteCancelGoesBackToTheSavedConnection、TestRemoteOverviewShowsTheTestedHost 与 TestVisualRemoteConnections。" + "notes": "Viva:连接列表的格式和字段规则在 Core(remote.connections、remote.editConnections),桌面端只读写偏好目录里的 remote/connections.json,按读取时的字节原子写回 Core 返回的文档,文件被改过时不覆盖;测试连接由 Core 运行 PATH 中的 OpenSSH,SSH 询问经 SSH_ASKPASS 指向 lithe 可执行文件的助手模式回到窗口,和 Git 认证共用同一个提问队列。Lithe 只把私钥路径交给 OpenSSH,不读取私钥内容,也不接受粘贴的私钥。macOS 用无头截图和真实 Core 的单元测试覆盖;Windows 上 OpenSSH 调用 GUI 子系统助手读取答案仍待实机验证。连接后选择主机文件夹并打开远程工作区见 remote-workspace。 2026-11-21(#2231 窗口重设计):颜色(六种固定色或无)和分组随连接保存在 Core 的 connections.json(Lithe-IDEA/Lithe-core-rust#152),分组顺序由 Core 的 sections 给出(按首次使用的顺序,未分组在最后),桌面端只展示;概览的“主机信息”只保存在本次运行的内存里,不写文件。搜索、从 Motty 或 SSH 配置导入、ssh -G 实际生效值和最近一次测试时间尚未实现。自动化:TestRemoteConnectionsColorAndGroup、TestRemoteCancelGoesBackToTheSavedConnection、TestRemoteOverviewShowsTheTestedHost 与 TestVisualRemoteConnections。" } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 15bd5f4e7..6f382941e 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -4,21 +4,34 @@ "group": "远程开发", "capability": "远程连接与远程路径工作区", "macos": { - "implementationStatus": "missing", - "verificationStatus": "not-applicable", + "implementationStatus": "partial", + "verificationStatus": "pending", "evidence": [ - "docs/viva-migration.md" + "desktop/internal/core/remote_session.go", + "desktop/internal/core/remote_session_test.go", + "desktop/internal/remoteplaceholder/remoteplaceholder.go", + "desktop/internal/workbench/remote_browse.go", + "desktop/internal/workbench/remote_browse_view.go", + "desktop/internal/workbench/remote_workspace.go", + "desktop/internal/workbench/remote_status_view.go", + "desktop/internal/workbench/remote_workspace_test.go", + "desktop/internal/workbench/remote_workspace_visual_test.go" ] }, "windows": { - "implementationStatus": "missing", - "verificationStatus": "not-applicable", + "implementationStatus": "partial", + "verificationStatus": "pending", "evidence": [ - "docs/viva-migration.md" + "desktop/internal/core/remote_session.go", + "desktop/internal/remoteplaceholder/remoteplaceholder.go", + "desktop/internal/workbench/remote_browse.go", + "desktop/internal/workbench/remote_browse_view.go", + "desktop/internal/workbench/remote_workspace.go", + "desktop/internal/workbench/remote_status_view.go" ] }, "owner": "Remote", - "verification": "Windows 验证连接、密码提示、远程路径、断线和重连;macOS 从欢迎页远程开发入口连接 Linux SSH 主机,验证文件树、编辑保存冲突、断线通知与重连。macOS 路由与断线 fixture 已有自动测试,真实 SSH 流程仍待验收;完整远程开发进度见 remote-development-workspace。 文件树新建、目录、复制、重命名与主机废纸篓已接入,14 项 Swift 路由/监听 fixture 通过;真实 SSH 验证外部创建、编辑、移动、删除、溢出重扫和 watcher 取消后无资源残留。 构建与插件接入进度同步至 remote-development-workspace;本行保持 partial/pending,不能以本机 fixture 替代真实 SSH 验收。 通用资源启动在读取请求时预留身份,启动期间的关闭由创建者保留最终清理责任;验证清理早于注册、工作线程饱和、失败启动、无效关闭参数,以及不同资源独立性;区分常驻会话断线保留、非驻留断线清理和会话关闭/空闲到期后的迟到资源清理。RemotePluginLaunchPreparerTests 使用真实声明覆盖目标架构、远端状态目录、缺失资源、准备中重连和取消清理;本机 fixture 不替代 SSH/Linux 验收。语言和工具专属集成由各插件负责,不在本能力范围。 会话拥有完整插件快照:验证分配回复丢失后按原身份释放、重复释放不接管已有目录、跨会话隔离、父目录权限与链接拒绝、删除失败(包括等待创建者清理)保留原身份供重试、普通断线清理、常驻断线保留及关闭/空闲到期回收;服务端强杀后的回收仍未实现。上传验证同文件并发 BUSY、不同文件独立提交,以及取消/到期不等待文件锁。Agent 后续单独处理,本轮不扩展。 常驻服务并发启动按身份先取得有界.start文件锁,重新检查socket后才创建daemon;锁覆盖至socket就绪,关闭描述符释放,inode保留。验证互斥、立即期限、释放后可重取,以及竞争连接收到server.shutdown确认后daemon不重新启动。macOS真实进程回归与Linux/macOS编译检查分别记录,Linux运行结果以CI为准。 macOS 远程文件树通过 Core 的按需目录列表应用可见性、自然排序与嵌套工作树规则;断线时不回退读取本机占位目录。Swift 路由与真实协议主机 fixture 已覆盖,真实 SSH 产品验收仍 pending。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区暂时只能浏览文件夹,打开文件、终端、Git、搜索监听和信任项目都被拒绝并提示,不回退到本机;查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试和 TestVisualRemoteWorkspace 无头截图;真实 SSH 主机上的整机验收、Windows 实机(Core 主机路径问题见 #2264)仍待完成。远程文件编辑保存、监听、终端、Git 与端口转发见 remote-development-workspace。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -55,5 +68,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:未找到远程连接、远程路径工作区、断线与重连处理的实现;desktop/ 中没有 SSH 连接或远程文件树后端。" + "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。macOS 由单元测试与无头截图覆盖;Windows 上 Core 按本机规则校验主机路径(#2264),推测远程请求全部被拒绝,未实机验证。" }