diff --git a/desktop/internal/core/remote_terminal.go b/desktop/internal/core/remote_terminal.go new file mode 100644 index 0000000000..71ed1e1ee0 --- /dev/null +++ b/desktop/internal/core/remote_terminal.go @@ -0,0 +1,194 @@ +package core + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "unicode/utf8" +) + +// RemoteTerminalOpen is how a host terminal starts. +type RemoteTerminalOpen struct { + // Argv is the program and its arguments; empty runs the user's login shell as a login + // shell, which reads the same profile files as an SSH login. + Argv []string `json:"argv,omitempty"` + // Cwd is the absolute host working directory; empty starts in the user's home. + Cwd string `json:"cwd,omitempty"` + // Env adds variables to the server's environment. TERM is xterm-256color unless Env sets + // it. + Env map[string]string `json:"env,omitempty"` + // Columns and Rows are the size in character cells; both must be at least 1. + Columns uint16 `json:"columns"` + Rows uint16 `json:"rows"` + // Label is what server.state reports for the terminal, so the window that closes the + // session can name what still runs. Nil reports none. + Label *RemoteResourceLabel `json:"label,omitempty"` +} + +// RemoteResourceLabel names a host resource in server.state. +type RemoteResourceLabel struct { + // Kind is the client's category, such as "terminal"; at most 64 characters. + Kind string `json:"kind"` + // Name is shown to the user; at most 256 characters, and NewRemoteResourceLabel cuts a + // longer one. + Name string `json:"name"` +} + +// Core's limits on a resource label, in characters. +const ( + remoteLabelKindChars = 64 + remoteLabelNameChars = 256 +) + +// NewRemoteResourceLabel is a label of kind and name cut to the lengths Core accepts, so a +// long tab title cannot fail the request. +func NewRemoteResourceLabel(kind, name string) *RemoteResourceLabel { + return &RemoteResourceLabel{Kind: cutRunes(kind, remoteLabelKindChars), Name: cutRunes(name, remoteLabelNameChars)} +} + +// cutRunes is text cut to at most limit characters. +func cutRunes(text string, limit int) string { + if utf8.RuneCountInString(text) <= limit { + return text + } + return string([]rune(text)[:limit]) +} + +// RemoteTerminalEvents receive a host terminal's events. Both run on the request's goroutine +// and must return at once: they must not wait for a UI thread or for the terminal's input. +// Core holds 1024 undelivered events per terminal and ends the terminal, and with it the +// request, when a subscriber stops reading. +type RemoteTerminalEvents struct { + // Started is called once, before any output, with the id terminal.write, terminal.resize + // and terminal.close take. + Started func(terminalID uint64) + // Output receives the bytes the program wrote, in order. Output owns data. + Output func(data []byte) +} + +// RemoteTerminalExit is how a host terminal's program ended: ExitCode when it exited, Signal +// when a signal ended it. +type RemoteTerminalExit struct { + ExitCode *int `json:"exitCode"` + Signal *int `json:"signal"` +} + +// remoteTerminalEvent is one remote event of remote.runTerminal. +type remoteTerminalEvent struct { + Type string `json:"type"` + Event string `json:"event"` + Params struct { + TerminalID uint64 `json:"terminalId"` + Data string `json:"data"` + } `json:"params"` +} + +// errRemoteTerminalEvent is an event of remote.runTerminal the client cannot read. +var errRemoteTerminalEvent = errors.New("core: unreadable remote terminal event") + +// RemoteRunTerminal runs a terminal on the host of sessionID until its program exits, and +// returns how it ended. It blocks the calling goroutine for the terminal's whole life, so run +// it off the UI thread. Ending ctx closes the terminal: Core sends terminal.close, which hangs +// the program up and kills it two seconds later, and returns the context's error. A broken or +// unknown session fails with CodeConnectionClosed, and a program that cannot start with +// CodeProcessFailed. An event the client cannot read ends the terminal too and is returned as +// the error, since its output would be incomplete. +func (c *Client) RemoteRunTerminal(ctx context.Context, sessionID string, open RemoteTerminalOpen, events RemoteTerminalEvents) (RemoteTerminalExit, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + var unreadable error + observer := func(raw json.RawMessage) { + if unreadable != nil { + return + } + if err := deliverRemoteTerminalEvent(raw, events); err != nil { + // Cancelling ends the terminal rather than letting it run unseen. + unreadable = err + cancel() + } + } + var exit RemoteTerminalExit + observationErr, err := c.ExecuteWithEvents(ctx, "remote.runTerminal", struct { + SessionID string `json:"sessionId"` + Params RemoteTerminalOpen `json:"params"` + }{sessionID, open}, &exit, observer) + switch { + case unreadable != nil: + return RemoteTerminalExit{}, unreadable + case err != nil: + return RemoteTerminalExit{}, err + case observationErr != nil: + return RemoteTerminalExit{}, observationErr + } + return exit, nil +} + +// deliverRemoteTerminalEvent hands one event of remote.runTerminal to events. Events of other +// kinds are not the terminal's and are ignored. +func deliverRemoteTerminalEvent(raw json.RawMessage, events RemoteTerminalEvents) error { + if !bytes.Contains(raw, []byte(`"remote"`)) { + return nil + } + var event remoteTerminalEvent + if err := json.Unmarshal(raw, &event); err != nil || event.Type != "remote" { + return nil + } + switch event.Event { + case "terminal.started": + if events.Started != nil { + events.Started(event.Params.TerminalID) + } + case "terminal.output": + data, err := base64.StdEncoding.DecodeString(event.Params.Data) + if err != nil { + return errRemoteTerminalEvent + } + if events.Output != nil && len(data) > 0 { + events.Output(data) + } + } + return nil +} + +// RemoteTerminalWrite types data into the host terminal terminalID of sessionID. busy is true +// when the program has not read what it was given before and the host refused data without +// taking any of it: sending the same bytes again later is safe. A terminal that already ended +// fails with CodeProcessFailed, a broken or unknown session with CodeConnectionClosed. +func (c *Client) RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (busy bool, err error) { + err = c.RemoteHostRequest(ctx, sessionID, "terminal.write", struct { + TerminalID uint64 `json:"terminalId"` + Data string `json:"data"` + }{terminalID, base64.StdEncoding.EncodeToString(data)}, nil) + if remoteHostCode(err) == "BUSY" { + return true, nil + } + return false, err +} + +// RemoteTerminalResize tells the host terminal terminalID of sessionID its size in cells; both +// must be at least 1. +func (c *Client) RemoteTerminalResize(ctx context.Context, sessionID string, terminalID uint64, columns, rows uint16) error { + return c.RemoteHostRequest(ctx, sessionID, "terminal.resize", struct { + TerminalID uint64 `json:"terminalId"` + Columns uint16 `json:"columns"` + Rows uint16 `json:"rows"` + }{terminalID, columns, rows}, nil) +} + +// remoteHostCode is the host protocol's code of a host method that failed, such as "BUSY" or +// "UNKNOWN_RESOURCE"; empty when err is not one. Core reports it in the error's details. +func remoteHostCode(err error) string { + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Details == "" { + return "" + } + var details struct { + RemoteCode string `json:"remoteCode"` + } + if json.Unmarshal([]byte(coreErr.Details), &details) != nil { + return "" + } + return details.RemoteCode +} diff --git a/desktop/internal/core/remote_terminal_test.go b/desktop/internal/core/remote_terminal_test.go new file mode 100644 index 0000000000..ce2c77c97e --- /dev/null +++ b/desktop/internal/core/remote_terminal_test.go @@ -0,0 +1,91 @@ +package core + +import ( + "encoding/json" + "errors" + "strconv" + "strings" + "testing" + "unicode/utf8" +) + +// The terminal's events reach their callbacks in order: started with its id, output decoded, +// an empty output dropped, and events that are not the terminal's ignored. Output that is not +// base64 is an error, since what the terminal shows would be incomplete. +func TestRemoteTerminalEventsReachTheirCallbacks(t *testing.T) { + var got []string + events := RemoteTerminalEvents{ + Started: func(id uint64) { got = append(got, "started "+strconv.FormatUint(id, 10)) }, + Output: func(data []byte) { got = append(got, "output "+string(data)) }, + } + for _, raw := range []string{ + `{"type":"progress","message":"remote"}`, + `{"type":"remote","event":"terminal.started","params":{"terminalId":7}}`, + `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":"aGk="}}`, + `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":""}}`, + `{"type":"remote","event":"terminal.exit","params":{"terminalId":7,"exitCode":0}}`, + `{"type":"remote","event":"watch.changed","params":{}}`, + } { + if err := deliverRemoteTerminalEvent(json.RawMessage(raw), events); err != nil { + t.Fatalf("event %s: %v", raw, err) + } + } + if want := []string{"started 7", "output hi"}; strings.Join(got, "|") != strings.Join(want, "|") { + t.Fatalf("delivered %q, want %q", got, want) + } + bad := `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":"not base64!"}}` + if err := deliverRemoteTerminalEvent(json.RawMessage(bad), events); !errors.Is(err, errRemoteTerminalEvent) { + t.Fatalf("unreadable output = %v, want errRemoteTerminalEvent", err) + } +} + +// The host protocol's code is read from a Core error's details; anything else has none. +func TestRemoteHostCodeReadsTheDetails(t *testing.T) { + busy := &Error{Command: "remote.hostRequest", Code: CodeProcessFailed, Details: `{"remoteCode":"BUSY"}`} + if got := remoteHostCode(busy); got != "BUSY" { + t.Fatalf("code = %q, want BUSY", got) + } + for _, err := range []error{ + nil, + errors.New("plain"), + &Error{Code: CodeProcessFailed}, + &Error{Code: CodeProcessFailed, Details: "not json"}, + &Error{Code: CodeProcessFailed, Details: `{"other":"BUSY"}`}, + } { + if got := remoteHostCode(err); got != "" { + t.Errorf("code of %v = %q, want none", err, got) + } + } +} + +// A label longer than Core accepts is cut by characters, not bytes. +func TestNewRemoteResourceLabelCutsToCoreLimits(t *testing.T) { + label := NewRemoteResourceLabel(strings.Repeat("k", 70), strings.Repeat("终", 300)) + if utf8.RuneCountInString(label.Kind) != remoteLabelKindChars || utf8.RuneCountInString(label.Name) != remoteLabelNameChars || !utf8.ValidString(label.Name) { + t.Fatalf("label kind %d, name %d characters", utf8.RuneCountInString(label.Kind), utf8.RuneCountInString(label.Name)) + } + if short := NewRemoteResourceLabel("terminal", "devbox"); short.Kind != "terminal" || short.Name != "devbox" { + t.Fatalf("short label = %+v", short) + } +} + +// With the real kernel, a terminal, its input and its size over a session Core does not know +// fail with connection_closed, and the run never reports a start. +func TestRemoteTerminalOfAnUnknownSession(t *testing.T) { + client := NewClient() + ctx := testContext(t) + started := false + _, err := client.RemoteRunTerminal(ctx, "no-such-session", RemoteTerminalOpen{Columns: 80, Rows: 24}, RemoteTerminalEvents{ + Started: func(uint64) { started = true }, + }) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed || started { + t.Fatalf("runTerminal = %v, started %v, want connection_closed", err, started) + } + if busy, err := client.RemoteTerminalWrite(ctx, "no-such-session", 1, []byte("x")); busy || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("write = %v, %v, want connection_closed", busy, err) + } + if err := client.RemoteTerminalResize(ctx, "no-such-session", 1, 80, 24); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("resize = %v, want connection_closed", err) + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index db56e89b6b..acb7884f9a 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1697,6 +1697,9 @@ var sharedCatalogs = map[string]map[string]string{ "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.terminal.dropOutside": "Only files of this remote workspace can be dropped on its terminal. Files of this computer are not on the host.", + "desktop.remote.terminal.notConnected": "the workspace is not connected to the host. Wait for it to connect again, or click Reconnect in the status bar.", + "desktop.remote.terminal.tabNumber": "{name} ({number})", "desktop.remote.test": "Test Connection", "desktop.remote.testing": "Connecting… OpenSSH may ask for a password or to confirm the host key.", "desktop.remote.timeout": "Connect Timeout (s)", @@ -1708,8 +1711,8 @@ 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. Its files open, edit and save on the host; terminals, search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files.", + "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit and save on the host, and terminals run on the host; search, Git and running do not work here yet.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "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.", @@ -5171,6 +5174,9 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.status.unresponsive": "SSH: {name} · 无响应", "desktop.remote.stop": "停止", "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", + "desktop.remote.terminal.dropOutside": "只能把这个远程工作区里的文件拖到它的终端,本机的文件不在主机上。", + "desktop.remote.terminal.notConnected": "工作区未连接到主机。请等待重新连接,或点击状态栏中的“重新连接”。", + "desktop.remote.terminal.tabNumber": "{name} ({number})", "desktop.remote.test": "测试连接", "desktop.remote.testing": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", "desktop.remote.timeout": "连接超时(秒)", @@ -5182,8 +5188,8 @@ 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.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存,终端在主机上运行;搜索、Git 和运行暂不可用。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件,也可以在主机上运行终端。", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}", "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", diff --git a/desktop/internal/termview/open_test.go b/desktop/internal/termview/open_test.go new file mode 100644 index 0000000000..8a6b15b1d0 --- /dev/null +++ b/desktop/internal/termview/open_test.go @@ -0,0 +1,58 @@ +package termview + +import ( + "errors" + "strings" + "testing" +) + +// A program Config.Open starts elsewhere is given the screen's size and nothing of the local +// shell's start: its output is shown and what is typed is written to it. A failure to open is +// shown with its reason, logged and ends the view, and Enter opens the program again. +func TestOpenStartsTheProgramElsewhere(t *testing.T) { + var sizes [][2]int + refusal := errors.New("the host is not connected") + refuse := true + shell := &fakeShell{done: make(chan struct{}), output: []byte("host$ ")} + var failures []Failure + view := New(Config{ + Shell: "ignored", Dir: "/ignored", + Messages: Messages{ + SessionEnded: "ended", + SessionEndedStatus: func(int) string { return "ended with status" }, + RestartHint: "press enter", + StartFailed: func(reason string) string { return "could not start: " + reason }, + }, + Failed: func(f Failure) { failures = append(failures, f) }, + Open: func(cols, rows int) (Shell, error) { + sizes = append(sizes, [2]int{cols, rows}) + if refuse { + refuse = false + return nil, refusal + } + return shell, nil + }, + }) + view.ensureStarted() + cols, rows := view.screen.Size() + if len(sizes) != 1 || sizes[0] != [2]int{cols, rows} { + t.Fatalf("opened with %v, want the screen's %dx%d", sizes, cols, rows) + } + if !view.Ended() || !strings.Contains(view.RetainedText(1<<16), "could not start: the host is not connected") { + t.Fatalf("a failed open shows %q and ended = %v", view.RetainedText(1<<16), view.Ended()) + } + if len(failures) != 1 || failures[0].Event != eventStartFailed || !errors.Is(failures[0].Err, refusal) { + t.Fatalf("failures = %+v, want the start failure", failures) + } + + if !view.Restart() { + t.Fatal("Enter did not open the program again") + } + view.Pump() + if len(sizes) != 2 || view.Ended() || !strings.Contains(view.RetainedText(1<<16), "host$") { + t.Fatalf("opened %d times; the view shows %q", len(sizes), view.RetainedText(1<<16)) + } + if !view.SendLine("ls") || !strings.Contains(string(shell.input), "ls") { + t.Fatalf("the program was given %q", shell.input) + } +} diff --git a/desktop/internal/termview/session.go b/desktop/internal/termview/session.go index 40cf0a51ff..0f1315c4d8 100644 --- a/desktop/internal/termview/session.go +++ b/desktop/internal/termview/session.go @@ -49,7 +49,7 @@ func (v *View) start() { // hold. cols, rows := v.screen.Size() args := v.cfg.Args - if args == nil { + if args == nil && v.cfg.Open == nil { args = localshell.ArgsFor(v.cfg.Shell) } // The user's own shell, started without arguments of its own, reports its prompts and its @@ -58,9 +58,10 @@ func (v *View) start() { // a program that prints the same sequences, a shell nested in this one, or what the // shell before a restart left half written cannot pass for this shell's prompt. A // program started with arguments is left as it is, and so is the user's shell when the - // settings turned the integration off: without a token it starts plain. + // settings turned the integration off: without a token it starts plain. A program that + // Config.Open starts elsewhere is not one localshell can integrate, so it starts plain. token := "" - if args == nil && !v.options.PlainShell { + if args == nil && !v.options.PlainShell && v.cfg.Open == nil { token = rand.Text() } v.screen.SetPromptToken(token) diff --git a/desktop/internal/termview/view.go b/desktop/internal/termview/view.go index 37dbbc11dc..2ebe3ee733 100644 --- a/desktop/internal/termview/view.go +++ b/desktop/internal/termview/view.go @@ -176,13 +176,24 @@ type Config struct { // OpenLink opens a link the user Command- (Control- off macOS) clicked. Nil leaves // links inert. OpenLink func(target string) - // start opens a shell; nil uses localshell.Start. It runs off the window thread when - // Notify is set (see View.start). Tests replace it. + // Open starts the program somewhere other than this machine, such as on the host of a + // remote workspace, in a grid of cols by rows cells. The view then gives it Args as they + // are, leaves Shell, Dir, Env and Unset to Open, and starts it plain, without the prompt + // integration of localshell.Config.PromptToken. Open runs off the window thread when + // Notify is set and may block until the program runs; the Shell it returns must keep + // every promise of Shell. Nil starts a local shell. + Open func(cols, rows int) (Shell, error) + // start opens a shell; nil uses localshell.Start, or Open when it is set. It runs off the + // window thread when Notify is set (see View.start). Tests replace it. start func(localshell.Config) (shell, error) } -// shell is the part of *localshell.Shell the view uses, so tests can stand in for it. -type shell interface { +// shell is the name the view uses for Shell. +type shell = Shell + +// Shell is the part of *localshell.Shell the view uses, so tests and Config.Open can stand +// in for it. +type Shell interface { // Drain appends the output received since the last call to dst. It never blocks. Drain(dst []byte) []byte // Write queues input for the shell and reports whether it was accepted: false once the @@ -329,6 +340,10 @@ func nextOwner() uint32 { // New makes a terminal view. Its shell starts at the first paint, once the grid's size is // known. func New(cfg Config) *View { + if cfg.start == nil && cfg.Open != nil { + openElsewhere := cfg.Open + cfg.start = func(config localshell.Config) (shell, error) { return openElsewhere(config.Cols, config.Rows) } + } if cfg.start == nil { cfg.start = func(config localshell.Config) (shell, error) { opened, err := localshell.Start(config) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 7826a34eea..bb22a5f9fd 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -221,6 +221,9 @@ type Kernel interface { RemoteReadFile(ctx context.Context, sessionID, path string) ([]byte, core.RemoteFileVersion, error) RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error) RemoteServerState(ctx context.Context, sessionID string) error + RemoteRunTerminal(ctx context.Context, sessionID string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error) + RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error) + RemoteTerminalResize(ctx context.Context, sessionID string, terminalID uint64, columns, rows uint16) 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) diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 8d9d4321d9..139ecedb40 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -123,7 +123,7 @@ func (a *App) commands() []command { command := text add("terminal.runSelection", t.GroupTerminal, i18n.Shared(a.language(), "desktop.terminal.runSelection"), "", true, func() { if term := a.newTerminal(p, ""); term != nil { - a.openTerminals(p) + a.openToolWindow(itemTerminal) a.sendTerminalCommand(term, command) } }) diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index 51bb05a90b..cc5e6fa7ba 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -4,7 +4,6 @@ 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" @@ -394,7 +393,11 @@ func (a *App) terminalTabs(c ui.C) { Tooltip(a.text.Terminal.NewTab).Clicked() { c.After(func() { a.openToolTerminal("") }) } - a.shellMenuButton(c) + // The shell menu lists this computer's programs; a remote workspace's terminal runs + // the host's login shell. + if a.project == nil || a.project.remote == nil { + a.shellMenuButton(c) + } }) ui.Spacer(c) }) @@ -421,11 +424,6 @@ 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/remote_terminal.go b/desktop/internal/workbench/remote_terminal.go new file mode 100644 index 0000000000..f3ff681c72 --- /dev/null +++ b/desktop/internal/workbench/remote_terminal.go @@ -0,0 +1,537 @@ +package workbench + +import ( + "context" + "errors" + "maps" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/shellkind" + "github.com/1lck/Lithe-IDEA/desktop/internal/termview" +) + +// A terminal of a remote workspace runs on the host (#2231, R0, step 3): its program is the host +// account's login shell, started by the server in the host folder the terminal was opened in, +// and the terminal view draws what Core relays (remote.runTerminal). Nothing of it runs on this +// computer. The shell menu's programs are this computer's, so a remote workspace offers none of +// them, and a picture pasted into the terminal would be saved on this computer, so it is not +// offered either. A plugin's terminal still runs only in a local project. +// +// The terminal lives as long as its request. Closing the tab ends the request, and Core then hangs +// the program up and kills it soon after; a lost connection ends it too, and the workspace +// connects again (loseRemote). Enter starts a new shell once the workspace is connected again. + +const ( + // remoteTerminalOutputLimit bounds the output a host terminal holds for its view. The view + // takes everything at each frame; only a window that stops drawing lets output pile up, and + // the oldest is then dropped rather than stalling Core's event stream, which would end the + // terminal (core.RemoteTerminalEvents). + remoteTerminalOutputLimit = 8 << 20 + // remoteTerminalInputLimit bounds what was typed and not yet taken by the host, as + // localshell bounds its backlog. + remoteTerminalInputLimit = 4 << 20 + // remoteTerminalWriteChunk is the most one terminal.write sends. + remoteTerminalWriteChunk = 32 << 10 + // remoteTerminalRequestTimeout bounds one write or resize. + remoteTerminalRequestTimeout = 10 * time.Second + // The pause after the host refused input it could not take yet doubles from + // remoteTerminalBusyFirstPause up to remoteTerminalBusyMaxPause. + remoteTerminalBusyFirstPause = 10 * time.Millisecond + remoteTerminalBusyMaxPause = 250 * time.Millisecond + // remoteSIGHUP and remoteSIGKILL are the Linux signals that end a host program Core closes. + remoteSIGHUP = 1 + remoteSIGKILL = 9 +) + +var ( + // errRemoteTerminalOutputDropped is logged once for a terminal whose view stopped taking + // its output long enough that the oldest of it was dropped. + errRemoteTerminalOutputDropped = errors.New("remote terminal: output dropped while the view did not read it") + // errRemoteTerminalInputDropped is logged once for a terminal whose host refused input. + errRemoteTerminalInputDropped = errors.New("remote terminal: input dropped") +) + +// remoteTerminalStartError is why a host terminal did not start. Error is the reason the +// terminal shows; the cause is what the log keeps of it (remoteLogError). +type remoteTerminalStartError struct { + reason string + cause error +} + +func (e *remoteTerminalStartError) Error() string { return e.reason } +func (e *remoteTerminalStartError) Unwrap() error { return e.cause } + +// remoteExitStatus is a host program's end that was not a clean exit, as termview reads it. +type remoteExitStatus int + +func (s remoteExitStatus) Error() string { + return "remote terminal: program ended with status " + strconv.Itoa(int(s)) +} + +// ExitStatus is the status the terminal reports: the exit code, or 128 plus the signal that +// ended the program, as a shell reports one. +func (s remoteExitStatus) ExitStatus() int { return int(s) } + +// remoteTerminalHost is what a host terminal needs of the workbench, taken on the window thread +// when the terminal is made: every method runs off it. +type remoteTerminalHost struct { + kernel Kernel + binding *core.RemoteWorkspace + // ctx ends with the terminal's tab; each start's request runs under a child of it. + ctx context.Context + open core.RemoteTerminalOpen + notify func() + // notConnected is the reason shown when the workspace has no session. + notConnected string + // lost tells the window the session's connection closed; failed logs a failure. + lost func(session string, err error) + failed func(operation string, err error) +} + +// start runs the host terminal in a grid of cols by rows cells and returns once the host +// started it, or why it could not. It blocks, so termview runs it off the window thread. +func (h remoteTerminalHost) start(cols, rows int) (termview.Shell, error) { + session := h.binding.SessionID() + if session == "" { + return nil, &remoteTerminalStartError{reason: h.notConnected, cause: errRemoteSessionClosed} + } + ctx, cancel := context.WithCancel(h.ctx) + s := &remoteShell{ + host: h, + session: session, + ctx: ctx, + cancel: cancel, + wake: make(chan struct{}, 1), + started: make(chan struct{}), + done: make(chan struct{}), + } + open := h.open + open.Env = maps.Clone(h.open.Env) + open.Columns, open.Rows = remoteCells(cols), remoteCells(rows) + go s.run(open) + select { + case <-s.started: + case <-s.done: + if !s.hasStarted() { + cancel() + return nil, h.startError(s.err) + } + // It started and ended at once; the view shows its output and its end. + } + go s.send() + return s, nil +} + +// startError is the failure to start a host terminal as the terminal shows it. +func (h remoteTerminalHost) startError(err error) error { + if remoteConnectionClosed(err) { + return &remoteTerminalStartError{reason: h.notConnected, cause: err} + } + reason := err.Error() + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Message != "" { + // Core's message is the server's diagnostic, which the terminal shows as it is. + reason = coreErr.Message + } + return &remoteTerminalStartError{reason: reason, cause: err} +} + +// remoteCells is a grid dimension as a host terminal takes it: at least 1, at most 65535. +func remoteCells(n int) uint16 { + return uint16(min(max(n, 1), 1<<16-1)) +} + +// remoteShell is a host terminal as termview drives it: a termview.Shell whose program runs on +// the workspace's host. +type remoteShell struct { + host remoteTerminalHost + session string + // ctx is the start's request; cancel ends it. + ctx context.Context + cancel context.CancelFunc + // started is closed when the host started the program, done when the request returned. + started chan struct{} + startedOnce sync.Once + done chan struct{} + // wake tells the sender there is input or a size to send. + wake chan struct{} + + mu sync.Mutex + terminal uint64 + output []byte + dropped bool + input []byte + // cols and rows are the size to send once resized is set. + cols, rows uint16 + resized bool + inputLost bool + ended bool + // err is why the program ended, set before done is closed. + err error +} + +// run is the start's request: it returns when the program ends or the terminal closes. +func (s *remoteShell) run(open core.RemoteTerminalOpen) { + exit, err := s.host.kernel.RemoteRunTerminal(s.ctx, s.session, open, core.RemoteTerminalEvents{ + Started: func(terminalID uint64) { + s.startedOnce.Do(func() { + s.mu.Lock() + s.terminal = terminalID + s.mu.Unlock() + close(s.started) + }) + }, + Output: s.received, + }) + end := s.endError(exit, err) + s.mu.Lock() + s.ended, s.input, s.err = true, nil, end + s.mu.Unlock() + close(s.done) + s.host.notify() +} + +// endError is why the program ended as termview reads it: nil for a clean exit and for a +// terminal that was closed, an ExitStatus for any other exit, and the request's error +// otherwise. A closed connection is reported to the window, which connects again; another +// failure of a terminal that ran is logged here, while one that kept it from starting is the +// view's to show and log. +func (s *remoteShell) endError(exit core.RemoteTerminalExit, err error) error { + closing := s.ctx.Err() != nil + switch { + case err != nil && closing: + return nil + case err != nil: + if remoteConnectionClosed(err) { + s.host.lost(s.session, err) + } else if s.hasStarted() { + s.host.failed("remote_terminal", err) + } + return err + case exit.ExitCode != nil && *exit.ExitCode != 0: + return remoteExitStatus(*exit.ExitCode) + case exit.Signal != nil: + if closing && (*exit.Signal == remoteSIGHUP || *exit.Signal == remoteSIGKILL) { + return nil + } + return remoteExitStatus(128 + *exit.Signal) + } + return nil +} + +// hasStarted reports whether the host started the program. +func (s *remoteShell) hasStarted() bool { + select { + case <-s.started: + return true + default: + return false + } +} + +// received keeps output for the view. It runs on the request's goroutine and never waits. +func (s *remoteShell) received(data []byte) { + s.mu.Lock() + s.output = append(s.output, data...) + dropped := false + if over := len(s.output) - remoteTerminalOutputLimit; over > 0 { + s.output = s.output[:copy(s.output, s.output[over:])] + dropped, s.dropped = !s.dropped, true + } + s.mu.Unlock() + if dropped { + s.host.failed("remote_terminal_output", errRemoteTerminalOutputDropped) + } + s.host.notify() +} + +// Drain appends the output received since the last call to dst. +func (s *remoteShell) Drain(dst []byte) []byte { + s.mu.Lock() + defer s.mu.Unlock() + dst = append(dst, s.output...) + s.output = s.output[:0] + if cap(s.output) > remoteTerminalWriteChunk { + s.output = nil // do not keep a flood's buffer + } + return dst +} + +// Write queues input for the host and reports whether it was taken: false once the program +// ended or while remoteTerminalInputLimit of earlier input waits. +func (s *remoteShell) Write(p []byte) bool { + if len(p) == 0 { + return true + } + s.mu.Lock() + ok := !s.ended && len(s.input)+len(p) <= remoteTerminalInputLimit + if ok { + s.input = append(s.input, p...) + } + s.mu.Unlock() + if ok { + s.signal() + } + return ok +} + +// Resize sends the host the terminal's size; a size sent later replaces one not sent yet. +func (s *remoteShell) Resize(cols, rows int) { + s.mu.Lock() + s.cols, s.rows, s.resized = remoteCells(cols), remoteCells(rows), true + s.mu.Unlock() + s.signal() +} + +func (s *remoteShell) signal() { + select { + case s.wake <- struct{}{}: + default: + } +} + +func (s *remoteShell) Done() <-chan struct{} { return s.done } + +// Err says why the program ended, once Done is closed. +func (s *remoteShell) Err() error { + s.mu.Lock() + defer s.mu.Unlock() + return s.err +} + +// Busy is false: the server does not report what the host shell runs. +func (s *remoteShell) Busy() bool { return false } + +// Kind is Unknown: the host's login shell is not known by name. +func (s *remoteShell) Kind() shellkind.Kind { return shellkind.Unknown } + +// Close ends the request, and Core closes the host terminal. +func (s *remoteShell) Close() { s.cancel() } + +// send delivers the size and the input to the host, in the order they were given, until the +// terminal ends. A host that cannot take input yet takes it again after a pause; input the host +// refused for another reason is dropped, as a pty drops what is typed into a program that ended. +func (s *remoteShell) send() { + for { + select { + case <-s.done: + return + case <-s.wake: + } + for s.sendNext() { + } + } +} + +// sendNext sends the pending size, or else the next chunk of input, and reports whether it +// sent anything. +func (s *remoteShell) sendNext() bool { + s.mu.Lock() + terminal, ended := s.terminal, s.ended + resize, cols, rows := s.resized, s.cols, s.rows + s.resized = false + var chunk []byte + if !resize { + chunk = append(chunk, s.input[:min(len(s.input), remoteTerminalWriteChunk)]...) + } + s.mu.Unlock() + if ended || (!resize && len(chunk) == 0) { + return false + } + if resize { + err := s.request(func(ctx context.Context) error { + return s.host.kernel.RemoteTerminalResize(ctx, s.session, terminal, cols, rows) + }) + s.refused(err, false) + return true + } + pause := remoteTerminalBusyFirstPause + for { + var busy bool + err := s.request(func(ctx context.Context) error { + var err error + busy, err = s.host.kernel.RemoteTerminalWrite(ctx, s.session, terminal, chunk) + return err + }) + if err == nil && busy { + if !s.wait(pause) { + return false + } + pause = min(2*pause, remoteTerminalBusyMaxPause) + continue + } + s.mu.Lock() + if err == nil { + s.input = s.input[:copy(s.input, s.input[len(chunk):])] + } else { + s.input = nil + } + s.mu.Unlock() + s.refused(err, true) + return true + } +} + +// request runs one host request of the terminal, bounded by remoteTerminalRequestTimeout. +func (s *remoteShell) request(do func(context.Context) error) error { + ctx, cancel := context.WithTimeout(s.ctx, remoteTerminalRequestTimeout) + defer cancel() + return do(ctx) +} + +// refused handles a write or a resize the host did not take. A closed connection is the +// window's to handle; a terminal that ended or closed reports its end itself; anything else is +// logged once. +func (s *remoteShell) refused(err error, input bool) { + if err == nil || s.ctx.Err() != nil { + return + } + if remoteConnectionClosed(err) { + s.host.lost(s.session, err) + return + } + select { + case <-s.done: + return + default: + } + s.mu.Lock() + first := !s.inputLost + s.inputLost = true + s.mu.Unlock() + if first { + operation := "remote_terminal_resize" + if input { + operation = "remote_terminal_input" + } + s.host.failed(operation, errors.Join(errRemoteTerminalInputDropped, err)) + } +} + +// wait pauses for d and reports false when the terminal ended or closed meanwhile. +func (s *remoteShell) wait(d time.Duration) bool { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-timer.C: + return true + case <-s.done: + return false + case <-s.ctx.Done(): + return false + } +} + +// remoteTerminalConfig makes config start terminal t of the remote workspace p on the host, in +// dir, with env added to the server's environment. It returns what cancels the terminal's +// requests when its tab closes. +func (a *App) remoteTerminalConfig(p *project, t *terminal, config *termview.Config, dir string, env []string) context.CancelFunc { + r := p.remote + ctx, cancel := context.WithCancel(p.ctx) + host := remoteTerminalHost{ + kernel: a.kernel, + binding: r.binding, + ctx: ctx, + open: core.RemoteTerminalOpen{ + Cwd: p.remoteTerminalDir(dir), + Env: environmentMap(env), + Label: core.NewRemoteResourceLabel("terminal", a.terminalTitle(t)), + }, + notify: a.invalidator.Invalidate, + notConnected: i18n.Shared(a.language(), "desktop.remote.terminal.notConnected"), + lost: func(session string, err error) { + a.post(func(a *App) { + if a.project == p { + a.loseRemote(p, session, err) + } + }) + }, + failed: func(operation string, err error) { a.backgroundFailedIn(ctx, operation, remoteLogError(err)) }, + } + config.Open = host.start + config.Shell, config.Args, config.Unset = "", nil, nil + // A picture pasted into the terminal would be saved on this computer, where the host's + // shell cannot read it. + config.PasteImage = nil + // The reason a host terminal did not start may name a host path, which the log does not + // keep. + failed := config.Failed + config.Failed = func(f termview.Failure) { + if f.Err != nil { + f.Err = remoteLogError(f.Err) + } + failed(f) + } + return cancel +} + +// remoteTerminalDir is the host folder a terminal of the remote workspace p opened in dir starts +// in: dir's host path, or the workspace's host folder when dir is not in the project. +func (p *project) remoteTerminalDir(dir string) string { + if host, ok := p.remoteHostPathWithin(dir); ok { + return host + } + return p.remote.binding.RemoteRoot() +} + +// remoteHostPathWithin is the host path of full when full is the remote workspace's root or a +// path below it; ok is false for any other path, which names nothing on the host. +func (p *project) remoteHostPathWithin(full string) (string, bool) { + if p.remote == nil || full == "" { + return "", false + } + rel, err := filepath.Rel(p.root, full) + if err != nil || filepath.IsAbs(rel) || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + return p.remoteHostPath(full), true +} + +// environmentMap is env, a list of NAME=value, as a map; a later entry replaces an earlier one. +func environmentMap(env []string) map[string]string { + if len(env) == 0 { + return nil + } + m := make(map[string]string, len(env)) + for _, entry := range env { + if name, value, ok := strings.Cut(entry, "="); ok && name != "" { + m[name] = value + } + } + return m +} + +// remoteTerminalTitle is the tab title of the number-th terminal of a remote workspace whose +// connection is named name: the name alone for the first, then the name with its number. +func remoteTerminalTitle(language i18n.Language, name string, number int) string { + if number <= 1 { + return name + } + return i18n.SharedFormat(language, "desktop.remote.terminal.tabNumber", map[string]string{"name": name, "number": strconv.Itoa(number)}) +} + +// pasteRemoteTerminalPaths pastes the host paths of paths into terminal t of the remote +// workspace p, quoted for a POSIX shell. A path outside the project names nothing on the host and +// is left out; nothing is pasted when none is left. +func (a *App) pasteRemoteTerminalPaths(p *project, t *terminal, paths []string) { + quoted := make([]string, 0, len(paths)) + for _, full := range paths { + if host, ok := p.remoteHostPathWithin(full); ok { + quoted = append(quoted, quoteShellPath(shellkind.POSIX, host)) + } + } + if len(quoted) == 0 { + a.operationRejected("terminal_drop_path", "remote_workspace") + a.notifyInfo(i18n.Shared(a.language(), "desktop.remote.terminal.dropOutside")) + return + } + if t.view.Paste(strings.Join(quoted, " ") + " ") { + a.focusTerminal(t.id) + } +} diff --git a/desktop/internal/workbench/remote_terminal_test.go b/desktop/internal/workbench/remote_terminal_test.go new file mode 100644 index 0000000000..936ec6a5a6 --- /dev/null +++ b/desktop/internal/workbench/remote_terminal_test.go @@ -0,0 +1,617 @@ +package workbench + +import ( + "context" + "errors" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// remoteHostTerminals stands in for the host's terminals (remote.runTerminal): a terminal starts +// at once and prints the prompt remoteHostPrompt, echoes what is typed, and runs until the test +// ends it or its request ends. +type remoteHostTerminals struct { + mu sync.Mutex + runs []*remoteHostRun + // busy is how many writes the host refuses as BUSY before it takes input again. + busy int + // refuse, when set, fails the next terminal before it starts. + refuse error + // resizes are the sizes the host was told, as "columns x rows"; writes are the lengths of + // the writes it took. + resizes []string + writes []int + // changed is signalled after each change, for tests that do not run a window. + changed chan struct{} +} + +// remoteHostPrompt is what a host terminal prints when it starts. +const remoteHostPrompt = "host$" + +// remoteHostRun is one terminal the host ran. +type remoteHostRun struct { + session string + open core.RemoteTerminalOpen + // typed is the input the host took, under remoteHostTerminals.mu. + typed []byte + echo chan []byte + end chan remoteHostEnd + // ended is closed when the request returned. + ended chan struct{} +} + +// remoteHostEnd is how the test ends a host terminal. +type remoteHostEnd struct { + exit core.RemoteTerminalExit + err error +} + +func (k *remoteHostKernel) RemoteRunTerminal(ctx context.Context, session string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error) { + h := &k.terminals + h.mu.Lock() + if err := h.refuse; err != nil { + h.refuse = nil + h.mu.Unlock() + return core.RemoteTerminalExit{}, err + } + run := &remoteHostRun{session: session, open: open, echo: make(chan []byte, 64), end: make(chan remoteHostEnd, 1), ended: make(chan struct{})} + h.runs = append(h.runs, run) + id := uint64(len(h.runs)) + h.mu.Unlock() + defer func() { + close(run.ended) + h.signal() + }() + events.Started(id) + events.Output([]byte(remoteHostPrompt + " ")) + h.signal() + for { + select { + case data := <-run.echo: + events.Output(data) + case end := <-run.end: + return end.exit, end.err + case <-ctx.Done(): + // Core closes the terminal and answers with the context's error. + return core.RemoteTerminalExit{}, ctx.Err() + } + } +} + +func (k *remoteHostKernel) RemoteTerminalWrite(_ context.Context, session string, terminal uint64, data []byte) (bool, error) { + h := &k.terminals + h.mu.Lock() + run, err := h.find(session, terminal) + busy := err == nil && h.busy > 0 + switch { + case busy: + h.busy-- + case err == nil: + run.typed = append(run.typed, data...) + h.writes = append(h.writes, len(data)) + } + h.mu.Unlock() + h.signal() + if err != nil || busy { + return busy, err + } + select { + case run.echo <- append([]byte(nil), data...): + case <-run.ended: + } + return false, nil +} + +func (k *remoteHostKernel) RemoteTerminalResize(_ context.Context, session string, terminal uint64, columns, rows uint16) error { + h := &k.terminals + h.mu.Lock() + _, err := h.find(session, terminal) + if err == nil { + h.resizes = append(h.resizes, strconv.Itoa(int(columns))+"x"+strconv.Itoa(int(rows))) + } + h.mu.Unlock() + h.signal() + return err +} + +// find is the running terminal of session numbered terminal, or the error the host answers a +// request for it with. +func (h *remoteHostTerminals) find(session string, terminal uint64) (*remoteHostRun, error) { + if terminal == 0 || terminal > uint64(len(h.runs)) || h.runs[terminal-1].session != session { + return nil, &core.Error{Command: "remote.hostRequest", Code: core.CodeConnectionClosed, Message: "no such session"} + } + run := h.runs[terminal-1] + select { + case <-run.ended: + return nil, &core.Error{Command: "remote.hostRequest", Code: core.CodeProcessFailed, Message: "the terminal ended", Details: `{"remoteCode":"UNKNOWN_RESOURCE"}`} + default: + return run, nil + } +} + +func (h *remoteHostTerminals) signal() { + select { + case h.changes() <- struct{}{}: + default: + } +} + +func (h *remoteHostTerminals) changes() chan struct{} { + h.mu.Lock() + defer h.mu.Unlock() + if h.changed == nil { + h.changed = make(chan struct{}, 1) + } + return h.changed +} + +// set changes how the host's terminals answer. +func (h *remoteHostTerminals) set(change func(h *remoteHostTerminals)) { + h.mu.Lock() + defer h.mu.Unlock() + change(h) +} + +// started is every terminal the host ran. +func (h *remoteHostTerminals) started() []*remoteHostRun { + h.mu.Lock() + defer h.mu.Unlock() + return slices.Clone(h.runs) +} + +// typedInto is the input the host took for run. +func (h *remoteHostTerminals) typedInto(run *remoteHostRun) string { + h.mu.Lock() + defer h.mu.Unlock() + return string(run.typed) +} + +// read is something of the host's terminals read under their lock. +func (h *remoteHostTerminals) read(read func(h *remoteHostTerminals) bool) bool { + h.mu.Lock() + defer h.mu.Unlock() + return read(h) +} + +// await waits for condition, which the host's terminals make true, without a window. +func (h *remoteHostTerminals) await(t *testing.T, what string, condition func() bool) { + t.Helper() + deadline := time.NewTimer(8 * time.Second) + defer deadline.Stop() + for !condition() { + select { + case <-h.changes(): + case <-deadline.C: + t.Fatalf("timed out waiting for %s", what) + } + } +} + +// openRemoteTerminal shows the Terminal tool window of the remote workspace p, which opens a +// terminal on the host, and waits for the host's prompt. +func (h *harness) openRemoteTerminal(t *testing.T, k *remoteHostKernel, p *project) (*terminal, *remoteHostRun) { + t.Helper() + before := len(k.terminals.started()) + h.clickTerminalButton() + h.await("a terminal to start on the host", func() bool { return len(k.terminals.started()) > before && len(p.terms.list) > 0 }) + term := p.terms.list[len(p.terms.list)-1] + h.awaitTerminal(term, remoteHostPrompt) + return term, k.terminals.started()[before] +} + +// clickTerminalButton opens the Terminal tool window by its button, as a person does: the click +// shows the window, and the window's first paint starts the terminal the workspace opened with. +func (h *harness) clickTerminalButton() { + h.t.Helper() + if !h.app.chrome.isOpen(catalogIndex[itemTerminal]) { + h.click(center(h.button(itemTerminal))) + } + h.settle() +} + +// awaitTerminal waits for term to show text, spaces aside, since a long line wraps in the grid. +func (h *harness) awaitTerminal(term *terminal, text string) { + h.t.Helper() + want := strings.Join(strings.Fields(text), "") + h.await("the terminal's text", func() bool { + term.view.Pump() + return strings.Contains(strings.Join(strings.Fields(term.view.RetainedText(1<<16)), ""), want) + }) +} + +// showsControl reports whether a control named label is shown. +func (h *harness) showsControl(label string) bool { + for _, hit := range h.driver.Snapshot().Hits { + if hit.Label == label && !hit.IsLabel { + return true + } + } + return false +} + +// The Terminal tool window of a remote workspace runs the host account's login shell in the host +// folder: the request carries the workspace's session, Lithe's own variables and a label of the +// connection's name, and the tab is named after the connection. What is typed reaches the host in +// order, also after the host asked to wait, and the size goes with it. There is no menu of this +// computer's shells, closing the tab ends the host terminal without anything failing, and +// neither the host nor its paths are logged. +func TestRemoteWorkspaceTerminalRunsOnTheHost(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + if len(p.terms.list) != 1 || len(k.terminals.started()) != 0 { + t.Fatalf("the workspace opened with %d terminals, %d running before they were shown", len(p.terms.list), len(k.terminals.started())) + } + term, run := h.openRemoteTerminal(t, k, p) + + if run.session != p.remote.session || run.open.Cwd != remoteTestHome+"/project" || len(run.open.Argv) != 0 { + t.Fatalf("the terminal ran in session %v, argv %d, cwd matched %v", run.session == p.remote.session, len(run.open.Argv), run.open.Cwd == remoteTestHome+"/project") + } + if run.open.Env["TERM_PROGRAM"] != "Lithe" || run.open.Columns == 0 || run.open.Rows == 0 { + t.Fatalf("the terminal started with env %v and %dx%d cells", slices.Sorted(mapKeys(run.open.Env)), run.open.Columns, run.open.Rows) + } + if label := run.open.Label; label == nil || label.Kind != "terminal" || label.Name != remoteTestHost { + t.Fatal("the host terminal is not labelled with the connection's name") + } + if got := h.app.terminalTitle(term); got != remoteTestHost { + t.Fatal("the tab is not named after the connection") + } + h.redraw() + if h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.localOnly")) || h.showsControl(h.app.text.Terminal.ShellMenu) { + t.Fatal("the Terminal tool window says it does not work here or offers this computer's shells") + } + + k.terminals.set(func(h *remoteHostTerminals) { h.busy = 2 }) + if !term.view.SendLine("echo hi") { + t.Fatal("the terminal did not take the line") + } + h.awaitTerminal(term, remoteHostPrompt+" echo hi") + if got := k.terminals.typedInto(run); got != "echo hi\r" { + t.Fatalf("the host took %q", got) + } + if k.terminals.read(func(h *remoteHostTerminals) bool { return h.busy != 0 }) { + t.Fatal("the input was not offered again after the host asked to wait") + } + + second := h.app.newTerminalWith(p, terminalOptions{activate: true}) + if second == nil || h.app.terminalTitle(second) != remoteTestHost+" (2)" { + t.Fatal("the second terminal is not numbered after the connection's name") + } + h.app.closeTerminal(p, term.id) + h.await("the host terminal to end", func() bool { + select { + case <-run.ended: + return true + default: + return false + } + }) + h.settle() + if p.remote.session == "" || countFailures(logger, "remote_terminal") != 0 || countFailures(logger, "remote_session_lost") != 0 { + t.Fatal("closing the tab failed or ended the session") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A host terminal whose connection closes ends, and the workspace connects again. While it has no +// session, Enter says the workspace is not connected; once it is connected again, Enter starts a +// new shell on the new session. +func TestRemoteWorkspaceTerminalEndsWithTheConnection(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + term, run := h.openRemoteTerminal(t, k, p) + + k.set(func(k *remoteHostKernel) { k.refuse = core.RemoteProbeUnreachable }) + run.end <- remoteHostEnd{err: &core.Error{Command: "remote.runTerminal", Code: core.CodeConnectionClosed, Message: "connection to " + remoteTestHost + " closed"}} + h.await("the workspace to lose its session", func() bool { return p.remote.session == "" && p.remote.reconnecting == nil }) + h.awaitTerminal(term, h.app.text.Terminal.SessionEnded) + if countFailures(logger, "remote_session_lost") != 1 || countFailures(logger, "remote_terminal") != 0 { + t.Fatal("the lost connection was not logged once as the session's") + } + + if !term.view.Restart() { + t.Fatal("Enter did not start the terminal again") + } + h.awaitTerminal(term, i18n.Shared(lang, "desktop.remote.terminal.notConnected")) + if len(k.terminals.started()) != 1 { + t.Fatal("a terminal started without a session") + } + + k.set(func(k *remoteHostKernel) { k.refuse = "" }) + h.fire(t, timers) + if p.remote.session == "" || p.remote.session == run.session { + t.Fatal("the workspace did not connect again") + } + if !term.view.Restart() { + t.Fatal("Enter did not start the terminal again") + } + h.await("a terminal on the new session", func() bool { return len(k.terminals.started()) == 2 }) + if again := k.terminals.started()[1]; again.session != p.remote.session { + t.Fatal("the new terminal did not run on the new session") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A host terminal that cannot start shows Core's reason, and what is logged keeps only the +// command and its code. +func TestRemoteWorkspaceTerminalShowsWhyItDidNotStart(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + reason := "cannot change to " + remoteTestHome + "/project: no such directory" + k.terminals.set(func(h *remoteHostTerminals) { + h.refuse = &core.Error{Command: "remote.runTerminal", Code: core.CodeProcessFailed, Message: reason} + }) + h.clickTerminalButton() + h.await("a terminal tab", func() bool { return len(p.terms.list) == 1 }) + h.awaitTerminal(p.terms.list[0], reason) + if len(k.terminals.started()) != 0 || p.remote.session == "" { + t.Fatal("a refused terminal ran or ended the session") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// Paths dropped on a host terminal are pasted as the host's, quoted for a POSIX shell; a path of +// this computer outside the workspace is left out, and a drop of only such paths pastes nothing +// and says why. +func TestRemoteWorkspaceTerminalTakesTheHostPathsOfDroppedFiles(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + term, run := h.openRemoteTerminal(t, k, p) + outside := filepath.Join(t.TempDir(), "local.txt") + + h.app.pasteTerminalPaths(term, []string{filepath.Join(p.root, "src", "it's.go"), outside, p.root}) + want := "'" + remoteTestHome + `/project/src/it'\''s.go' '` + remoteTestHome + "/project' " + h.await("the host paths to reach the host", func() bool { return k.terminals.typedInto(run) == want }) + + h.app.pasteTerminalPaths(term, []string{outside}) + h.settle() + if k.terminals.typedInto(run) != want { + t.Fatal("a path of this computer was pasted into the host terminal") + } + if !rejected(logger, "terminal_drop_path", "remote_workspace") { + t.Fatal("the refused drop was not logged") + } + if !slices.ContainsFunc(h.app.notifications.list, func(n *notification) bool { + return n.text == i18n.Shared(lang, "desktop.remote.terminal.dropOutside") + }) { + t.Fatal("the refused drop was not notified") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// remoteTestShell starts a host terminal of k over a binding attached to session-1, outside a +// window: lost and failed record what the window would be told. +func remoteTestShell(t *testing.T, k *remoteHostKernel) (*remoteShell, *remoteShellReports) { + t.Helper() + binding := core.NewRemoteWorkspace(filepath.Join(t.TempDir(), "project"), remoteTestHome+"/project", nil) + binding.Attach("session-1") + ctx, cancel := context.WithCancel(context.Background()) + reports := &remoteShellReports{} + host := remoteTerminalHost{ + kernel: k, + binding: binding, + ctx: ctx, + open: core.RemoteTerminalOpen{Cwd: remoteTestHome + "/project"}, + notify: func() {}, + lost: func(session string, err error) { + reports.mu.Lock() + defer reports.mu.Unlock() + reports.lost = append(reports.lost, session) + }, + failed: func(operation string, err error) { + reports.mu.Lock() + defer reports.mu.Unlock() + reports.failed = append(reports.failed, operation) + }, + } + shell, err := host.start(80, 24) + if err != nil { + cancel() + t.Fatalf("start: %v", err) + } + s := shell.(*remoteShell) + t.Cleanup(func() { + cancel() + deadline := time.NewTimer(8 * time.Second) + defer deadline.Stop() + select { + case <-s.Done(): + case <-deadline.C: + t.Error("the host terminal did not end with its request") + } + }) + return s, reports +} + +// remoteTestShellAlone is a host terminal with no request behind it, whose input and output a +// test drives by hand; failed records what it logged. +func remoteTestShellAlone(reports *remoteShellReports) *remoteShell { + return &remoteShell{ + host: remoteTerminalHost{ + notify: func() {}, + failed: func(operation string, err error) { + reports.mu.Lock() + defer reports.mu.Unlock() + reports.failed = append(reports.failed, operation) + }, + }, + wake: make(chan struct{}, 1), + } +} + +// remoteShellReports are what a host terminal told the window. +type remoteShellReports struct { + mu sync.Mutex + lost []string + failed []string +} + +func (r *remoteShellReports) snapshot() (lost, failed []string) { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.lost), slices.Clone(r.failed) +} + +// The sender gives the host the size before input typed after it, and the input in order, in +// chunks no larger than one write takes, also after the host asked it to wait. +func TestRemoteShellSendsTheSizeAndChunkedInputInOrder(t *testing.T) { + k := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + s, reports := remoteTestShell(t, k) + run := k.terminals.started()[0] + + k.terminals.set(func(h *remoteHostTerminals) { h.busy = 1 }) + s.Resize(120, 40) + big := strings.Repeat("x", remoteTerminalWriteChunk+10) + if !s.Write([]byte(big)) || !s.Write([]byte("tail")) { + t.Fatal("the terminal did not take the input") + } + k.terminals.await(t, "the input to reach the host", func() bool { return k.terminals.typedInto(run) == big+"tail" }) + // The size was pending whenever input was, and the sender sends a pending size first, so + // the host had it before the first chunk. + if !k.terminals.read(func(h *remoteHostTerminals) bool { + return slices.Equal(h.resizes, []string{"120x40"}) && len(h.writes) >= 2 && slices.Max(h.writes) <= remoteTerminalWriteChunk && h.busy == 0 + }) { + t.Fatal("the host was not told the size once, or was given more than a chunk in a write") + } + if lost, failed := reports.snapshot(); len(lost) != 0 || len(failed) != 0 { + t.Fatalf("lost %d, failed %q", len(lost), failed) + } +} + +// A terminal holds at most remoteTerminalInputLimit of input the host has not taken: more is +// refused while that much waits, and nothing is taken once the program ended. +func TestRemoteShellBoundsTheInputItHolds(t *testing.T) { + s := remoteTestShellAlone(&remoteShellReports{}) + if !s.Write(make([]byte, remoteTerminalInputLimit-1)) || !s.Write([]byte("x")) { + t.Fatal("the terminal refused input within its limit") + } + if s.Write([]byte("y")) { + t.Fatal("a terminal holding the most input it may took more") + } + s.mu.Lock() + s.input, s.ended = nil, true + s.mu.Unlock() + if s.Write([]byte("z")) { + t.Fatal("a terminal whose program ended took input") + } +} + +// Output the view does not read is bounded: the oldest is dropped and that is logged once. +func TestRemoteShellDropsTheOldestOutputPastItsLimit(t *testing.T) { + reports := &remoteShellReports{} + s := remoteTestShellAlone(reports) + s.received([]byte(strings.Repeat("a", remoteTerminalOutputLimit))) + s.received([]byte("bc")) + s.received([]byte("d")) + got := s.Drain(nil) + if len(got) != remoteTerminalOutputLimit || !strings.HasSuffix(string(got), "bcd") { + t.Fatalf("kept %d bytes", len(got)) + } + if _, failed := reports.snapshot(); !slices.Equal(failed, []string{"remote_terminal_output"}) { + t.Fatalf("failed %q, want the dropped output once", failed) + } +} + +// How a host terminal ended is what the view reads: an exit code or 128 plus the signal as the +// status, a hang-up of a terminal being closed as no failure, a closed connection told to the +// window, and another failure logged when the program ran and left to the view when it did not. +func TestRemoteShellReportsHowTheProgramEnded(t *testing.T) { + code := func(n int) *int { return &n } + closed := &core.Error{Command: "remote.runTerminal", Code: core.CodeConnectionClosed} + broken := &core.Error{Command: "remote.runTerminal", Code: core.CodeProcessFailed} + for _, c := range []struct { + name string + exit core.RemoteTerminalExit + err error + closing bool + status int // -1: no status; 0: a clean end + lost bool + failed bool + // unstarted is a request that ended before the host started the program. + unstarted bool + }{ + {name: "clean exit", exit: core.RemoteTerminalExit{ExitCode: code(0)}}, + {name: "exit code", exit: core.RemoteTerminalExit{ExitCode: code(3)}, status: 3}, + {name: "signal", exit: core.RemoteTerminalExit{Signal: code(15)}, status: 143}, + {name: "hang-up while closing", exit: core.RemoteTerminalExit{Signal: code(remoteSIGHUP)}, closing: true}, + {name: "kill while closing", exit: core.RemoteTerminalExit{Signal: code(remoteSIGKILL)}, closing: true}, + {name: "hang-up", exit: core.RemoteTerminalExit{Signal: code(remoteSIGHUP)}, status: 129}, + {name: "cancelled", err: context.Canceled, closing: true}, + {name: "connection closed", err: closed, status: -1, lost: true}, + {name: "failure", err: broken, status: -1, failed: true}, + // The view shows and logs why the program did not start. + {name: "failure before the start", err: broken, status: -1, unstarted: true}, + {name: "connection closed before the start", err: closed, status: -1, lost: true, unstarted: true}, + } { + t.Run(c.name, func(t *testing.T) { + var lost, failed bool + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if c.closing { + cancel() + } + s := &remoteShell{ + host: remoteTerminalHost{ + lost: func(string, error) { lost = true }, + failed: func(string, error) { failed = true }, + }, + ctx: ctx, + started: make(chan struct{}), + } + if !c.unstarted { + close(s.started) + } + err := s.endError(c.exit, c.err) + var exit interface{ ExitStatus() int } + switch { + case c.status == 0 && err != nil: + t.Fatalf("err = %v, want a clean end", err) + case c.status > 0 && (!errors.As(err, &exit) || exit.ExitStatus() != c.status): + t.Fatalf("err = %v, want status %d", err, c.status) + case c.status < 0 && (err == nil || errors.As(err, &exit)): + t.Fatalf("err = %v, want the request's error", err) + } + if lost != c.lost || failed != c.failed { + t.Fatalf("lost %v, failed %v", lost, failed) + } + }) + } +} + +// A host terminal of a workspace without a session does not reach the host and says why. +func TestRemoteShellWithoutASessionSaysTheWorkspaceIsNotConnected(t *testing.T) { + k := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + host := remoteTerminalHost{kernel: k, binding: core.NewRemoteWorkspace(t.TempDir(), remoteTestHome, nil), ctx: context.Background(), notConnected: "not connected"} + _, err := host.start(80, 24) + if err == nil || err.Error() != "not connected" || !errors.Is(err, errRemoteSessionClosed) || len(k.terminals.started()) != 0 { + t.Fatalf("start = %v, ran %d", err, len(k.terminals.started())) + } +} + +func mapKeys(m map[string]string) func(func(string) bool) { + return func(yield func(string) bool) { + for key := range m { + if !yield(key) { + return + } + } + } +} diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index dc3f587587..9eb81064ab 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -26,10 +26,11 @@ import ( // 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, and the editor opens, -// saves and compares the host's files (remote_documents.go). The features that still read the -// project through the local file system (terminals, the watch of the folder, search, local -// history, language servers, run configurations and plugins) are not started for it, or say so, +// In this stage the workspace lists its folder in the Project tool window, the editor opens, +// saves and compares the host's files (remote_documents.go), and its terminals run the host's +// login shell on the host (remote_terminal.go). The features that still read the project through +// the local file system (the watch of the folder, search, local history, language servers, run +// configurations and plugins, a plugin's terminal among them) are not started for it, or 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, so Git stays off as it does in an untrusted project. @@ -466,7 +467,8 @@ func (a *App) openRemoteProject(target remoteTarget) { 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{} + // Its first terminal runs on the host once it is shown, over the session attached below. + a.openTerminals(p) a.project = p a.notice = "" a.logView.reset() diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 227722147b..093f72b247 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -63,6 +63,8 @@ type remoteHostKernel struct { fileErr, writeErr error // fileSessions are the sessions the requests for host files went over. fileSessions []string + // terminals are the host's terminals (remote_terminal_test.go). + terminals remoteHostTerminals } func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) { @@ -357,8 +359,9 @@ func TestRemoteWorkspaceOpensTheChosenFolder(t *testing.T) { } // What still runs on this computer refuses in a remote workspace and says so: opening a file -// outside the host folder or in a viewer, a terminal, local history, trusting the folder and -// every tool window but the project's and the notifications'. Copying a path copies the host's. +// outside the host folder or in a viewer, a plugin's terminal, local history, trusting the folder +// and every tool window but the project's, the terminal's and the notifications'. Copying a path +// copies the host's. func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { h, _, _, logger := remoteWorkspaceHarness(t) lang := h.app.language() @@ -369,8 +372,8 @@ func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { h.app.openFile(p, filepath.Join(p.root, "logo.png")) h.app.openFile(p, filepath.Join(filepath.Dir(p.root), "elsewhere.txt")) h.app.openLocalHistory(p, filepath.Join(p.root, "README.md")) - if h.app.newTerminalWith(p, terminalOptions{}) != nil { - t.Fatal("a terminal started in the remote workspace") + if h.app.newTerminalWith(p, terminalOptions{plugin: &pluginTerminal{}}) != nil { + t.Fatal("a plugin's terminal started in the remote workspace") } asked := false h.app.askToTrustProject(p, func() { asked = true }) diff --git a/desktop/internal/workbench/remote_workspace_visual_test.go b/desktop/internal/workbench/remote_workspace_visual_test.go index d1ea574f53..6725b80a92 100644 --- a/desktop/internal/workbench/remote_workspace_visual_test.go +++ b/desktop/internal/workbench/remote_workspace_visual_test.go @@ -19,8 +19,8 @@ import ( // 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, the status bar's menu of the connection, a host file open in the editor and -// the conflict a save over a change made on the host shows. +// status bar item, the status bar's menu of the connection, a host file open in the editor, the +// conflict a save over a change made on the host shows, and a terminal running on the host. func TestVisualRemoteWorkspace(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") if out == "" { @@ -120,6 +120,22 @@ func TestVisualRemoteWorkspace(t *testing.T) { t.Fatal("the save over the host's change did not show the conflict") } shot("conflict") + // Loading the host's version resolves the conflict, and clearing the notifications takes + // down the refused save's toast, so the next scene shows the file as it is on the host. + h.app.loadDocumentDisk(p, d) + awaitDocumentState(t, h, func() bool { return !d.resolvingConflict }) + h.app.clearNotifications() + + // The Terminal tool window runs the host's login shell in the host folder, in a tab + // named after the connection. + term, run := h.openRemoteTerminal(t, kernel, p) + run.echo <- []byte("uname -sm\r\nLinux x86_64\r\n" + remoteHostPrompt + " ") + h.awaitTerminal(term, "Linux x86_64") + // The pointer leaves the button it clicked, whose tooltip would cover the terminal. + if err := h.driver.Move(800, 300); err != nil { + t.Fatal(err) + } + shot("terminal") }) } } diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 389812783c..581a2c6ec8 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -169,9 +169,10 @@ 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. + if p.remote != nil && tool.id != itemProject && tool.id != itemNotifications && tool.id != itemTerminal { + // A remote workspace lists the host's files and runs its terminals on the host; 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 } diff --git a/desktop/internal/workbench/terminal_commands_test.go b/desktop/internal/workbench/terminal_commands_test.go new file mode 100644 index 0000000000..7aa4d62d3d --- /dev/null +++ b/desktop/internal/workbench/terminal_commands_test.go @@ -0,0 +1,65 @@ +package workbench + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Running the editor's selection in the terminal opens one more terminal, selected in the +// Terminal tool window, and runs the selection there; the terminal that was open stays in the +// list, so its shell is still the window's to close. +func TestRunSelectionRunsInANewShownTerminal(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("uses /bin/sh") + } + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + root := t.TempDir() + path := filepath.Join(root, "run.sh") + // The output differs from the typed line, so the shell has run it when it shows. + if err := os.WriteFile(path, []byte("printf 'LITHE_%s\\n' RAN\n"), 0o600); err != nil { + t.Fatal(err) + } + h.open(root) + h.app.settings.TerminalShell = "/bin/sh" + p := h.app.project + if len(p.terms.list) != 1 { + t.Fatalf("the project opened with %d terminals, want 1", len(p.terms.list)) + } + first := p.terms.list[0] + h.app.openFile(p, path) + h.await("the file", func() bool { + d := h.app.selectedEditorDocument() + return d != nil && d.path == path + }) + d := h.app.selectedEditorDocument() + d.view.SetSelection(0, d.view.TextSnapshot().Len()) + var run func() + for _, cmd := range h.app.commands() { + if cmd.id == "terminal.runSelection" { + run = cmd.run + } + } + if run == nil { + t.Fatal("Run Selection is not offered for a selection") + } + run() + h.settle() + + if len(p.terms.list) != 2 || p.terms.list[0] != first { + t.Fatalf("after Run Selection the project has %d terminals, first kept %v", len(p.terms.list), p.terms.list[0] == first) + } + term := p.terms.list[1] + if p.terms.selected(toolGroup) != term || !h.app.chrome.isOpen(catalogIndex[itemTerminal]) { + t.Fatal("the terminal the selection runs in is not shown") + } + awaitStateWithin(t, h, 5*time.Second, "the selection's output", func() bool { + term.view.Pump() + return strings.Contains(term.view.RetainedText(1<<16), "LITHE_RAN") + }) +} diff --git a/desktop/internal/workbench/terminal_drop.go b/desktop/internal/workbench/terminal_drop.go index e296022cff..8396e4f0cc 100644 --- a/desktop/internal/workbench/terminal_drop.go +++ b/desktop/internal/workbench/terminal_drop.go @@ -63,8 +63,13 @@ func (a *App) terminalFileDrop(event gfx.FileDropEvent) (gfx.EventResult, bool) return gfx.EventResult{}, true } -// pasteTerminalPaths pastes paths, quoted for the terminal's shell, followed by a space. +// pasteTerminalPaths pastes paths, quoted for the terminal's shell, followed by a space. A +// terminal of a remote workspace is given their host paths (pasteRemoteTerminalPaths). func (a *App) pasteTerminalPaths(t *terminal, paths []string) { + if p := a.project; p != nil && p.remote != nil && t.host != "" { + a.pasteRemoteTerminalPaths(p, t, paths) + return + } program := t.shell if program == "" { program = loginShellProgram() diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index 4d3204e15b..e7966cf739 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -54,6 +54,10 @@ type terminal struct { find terminalFind // title replaces "Local (n)" on the tab; a plugin terminal sets it. title string + // host is the connection's name when the terminal runs on a remote workspace's host, and + // names the tab instead of "Local"; closeHost then ends the terminal's host requests. + host string + closeHost context.CancelFunc // plugin is set when a plugin backend owns the terminal. plugin *pluginTerminal // scripts are the command scripts written for commands too long for the shell's line; they are @@ -271,6 +275,7 @@ func (a *App) closeTerminals(p *project) { return } for _, t := range p.terms.list { + t.endHost() a.awaitShellEnd(t.view.Close()) t.removeCommandScripts() a.finishPluginTerminal(t, "closed", nil) @@ -382,15 +387,21 @@ type terminalOptions struct { plugin *pluginTerminal } -// newTerminalWith is newTerminal with the options of a plugin terminal. +// newTerminalWith is newTerminal with the options of a plugin terminal. A terminal of a remote +// workspace runs the host's login shell on the host (remote_terminal.go); a plugin's terminal +// would run on this computer, so a remote workspace refuses it. func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { - if a.refuseRemote(p, "open_terminal") { + if options.plugin != nil && a.refuseRemote(p, "open_terminal") { return nil } shell := options.shell if shell == "" && options.plugin == nil { shell = a.settings.TerminalShell } + if p.remote != nil { + // The shell menu's programs and the Terminal setting name programs of this computer. + shell = "" + } set := &p.terms state := set.bench if state.Group(toolGroup) == nil { @@ -423,6 +434,10 @@ func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { if options.plugin != nil { config.Exited = func(status *int) { a.pluginTerminalExited(p, t, status) } } + if p.remote != nil { + t.host = p.remote.name + t.closeHost = a.remoteTerminalConfig(p, t, &config, dir, config.Env) + } t.view = termview.New(config) // A terminal can start before its first paint (Start below), and the switches decide how // its shell starts. @@ -467,6 +482,7 @@ func (a *App) closeTerminal(p *project, id int) { if !a.reduceTerminals(p, set.bench, core.CloseEditor(group, member, emptyPolicy(group), core.SelectAdjacent)) { return } + t.endHost() a.awaitShellEnd(t.view.Close()) t.removeCommandScripts() a.finishPluginTerminal(t, "closed", nil) @@ -539,5 +555,16 @@ func (a *App) terminalTitle(t *terminal) string { if t.title != "" { return t.title } + if t.host != "" { + return remoteTerminalTitle(a.language(), t.host, t.number) + } return a.text.Terminal.Tab(t.number) } + +// endHost ends the host requests of a terminal of a remote workspace, so that one still +// starting gives up at once; a local terminal has none. +func (t *terminal) endHost() { + if t.closeHost != nil { + t.closeHost() + } +} diff --git a/docs/assets/remote-workspace/README.md b/docs/assets/remote-workspace/README.md index a7841896f0..a879319b51 100644 --- a/docs/assets/remote-workspace/README.md +++ b/docs/assets/remote-workspace/README.md @@ -1,12 +1,13 @@ # 远程工作区(#2231)无头测试截图 -来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳和主机上的 `README.md` 也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: +来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳、主机上的 `README.md` 和终端的输出也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: - 连接后“远程开发”窗口改为主机的文件夹选择:顶部是连接名和 `用户@主机`,路径框可以输入 `~` 或 `/` 开头的路径,无法读取的条目在列表下方说明数量,底部显示将打开的主机路径; -- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑和保存,终端、搜索、Git 和运行暂不可用,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; +- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑和保存,终端在主机上运行,搜索、Git 和运行暂不可用,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; - 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”; - 在项目树打开 `README.md`:编辑器显示主机上的内容,Markdown 预览照常; -- 主机上的文件被别人改过后再保存:保存被拒绝,通知说明文件在外部被修改,编辑器上方出现“保留编辑器版本 / 加载磁盘版本”,主机上的内容不被覆盖。 +- 主机上的文件被别人改过后再保存:保存被拒绝,通知说明文件在外部被修改,编辑器上方出现“保留编辑器版本 / 加载磁盘版本”,主机上的内容不被覆盖; +- 打开终端工具窗口:终端在主机的文件夹里运行主机的登录 shell,标签页以连接名命名,没有本机 Shell 选择菜单;截图里的命令输出由测试内核返回。 截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 @@ -17,6 +18,7 @@ | 状态栏连接菜单 | [浅色英文](remote-workspace-menu-light-en-US.png) | [深色中文](remote-workspace-menu-dark-zh-CN.png) | | 打开主机上的文件 | [浅色英文](remote-workspace-file-light-en-US.png) | [深色中文](remote-workspace-file-dark-zh-CN.png) | | 保存时主机上的文件已被修改 | [浅色英文](remote-workspace-conflict-light-en-US.png) | [深色中文](remote-workspace-conflict-dark-zh-CN.png) | +| 主机上的终端 | [浅色英文](remote-workspace-terminal-light-en-US.png) | [深色中文](remote-workspace-terminal-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-conflict-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-conflict-dark-zh-CN.png index 47c49c2626..7e48bfa7db 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-conflict-dark-zh-CN.png and b/docs/assets/remote-workspace/remote-workspace-conflict-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-conflict-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-conflict-light-en-US.png index 2a1b011bee..61f7ddde7c 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-conflict-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-conflict-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-file-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-file-dark-zh-CN.png index a62e5f5045..4d8869b7f4 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-file-dark-zh-CN.png and b/docs/assets/remote-workspace/remote-workspace-file-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-file-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-file-light-en-US.png index 881031f395..cef7661f0a 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-file-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-file-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 index 00a56cc83d..ea1f83e5f2 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png 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 index 0dea2b96e4..e457965464 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-menu-light-en-US.png 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 index 80ec2daa6a..f0a735db74 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-opened-dark-zh-CN.png 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 index 448e778b6a..2d3e895275 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-opened-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-opened-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-terminal-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-terminal-dark-zh-CN.png new file mode 100644 index 0000000000..8458f14eb8 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-terminal-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-terminal-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-terminal-light-en-US.png new file mode 100644 index 0000000000..03d80b5c21 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-terminal-light-en-US.png differ diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 7944e1bb3a..da4f0f1018 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -956,6 +956,31 @@ "limit": "string" } }, + { + "id": "desktop.remote.terminal.notConnected", + "description": "Terminal of a remote workspace: why its shell could not start while the workspace has no connection to the host; shown after 'Could not start the shell:'", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.terminal.tabNumber", + "description": "Terminal tab of a remote workspace after the first: the connection's name and the terminal's number", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "number": "string" + } + }, + { + "id": "desktop.remote.terminal.dropOutside", + "description": "Notification when files dropped on a remote workspace's terminal are not in the workspace, so they are not on the host", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.remote.edit", "description": "Remote Development window: button that turns the selected connection's overview into its form", @@ -1255,14 +1280,17 @@ "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. Its files open, edit and save on the host; terminals, search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files.", + "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit and save on the host, and terminals run on the host; search, Git and running do not work here yet.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", "desktop.remote.document.disconnected": "the remote workspace is not connected; try again once it reconnects", "desktop.remote.document.timedOut": "the host did not answer in time", "desktop.remote.document.notFound": "the file no longer exists on the host", "desktop.remote.document.permissionDenied": "the host account has no permission to access it", "desktop.remote.document.failed": "the host could not read or write it", - "desktop.remote.document.tooLargeToSave": "This file exceeds the {limit} the host takes in one save. Your edits remain open." + "desktop.remote.document.tooLargeToSave": "This file exceeds the {limit} the host takes in one save. Your edits remain open.", + "desktop.remote.terminal.notConnected": "the workspace is not connected to the host. Wait for it to connect again, or click Reconnect in the status bar.", + "desktop.remote.terminal.tabNumber": "{name} ({number})", + "desktop.remote.terminal.dropOutside": "Only files of this remote workspace can be dropped on its terminal. Files of this computer are not on the host." }, "zh-CN": { "desktop.remote.title": "远程开发", @@ -1404,14 +1432,17 @@ "desktop.remote.status.reconnect": "重新连接", "desktop.remote.status.disconnect": "断开并关闭", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", - "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存;终端、搜索、Git 和运行暂不可用。", - "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件。", + "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存,终端在主机上运行;搜索、Git 和运行暂不可用。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件,也可以在主机上运行终端。", "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试", "desktop.remote.document.timedOut": "主机没有及时响应", "desktop.remote.document.notFound": "主机上已没有这个文件", "desktop.remote.document.permissionDenied": "主机账户没有访问这个文件的权限", "desktop.remote.document.failed": "主机无法读取或写入这个文件", - "desktop.remote.document.tooLargeToSave": "文件超过主机单次保存上限 {limit},编辑内容仍保留。" + "desktop.remote.document.tooLargeToSave": "文件超过主机单次保存上限 {limit},编辑内容仍保留。", + "desktop.remote.terminal.notConnected": "工作区未连接到主机。请等待重新连接,或点击状态栏中的“重新连接”。", + "desktop.remote.terminal.tabNumber": "{name} ({number})", + "desktop.remote.terminal.dropOutside": "只能把这个远程工作区里的文件拖到它的终端,本机的文件不在主机上。" } } } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 59a9bc020f..987593e582 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -2,13 +2,15 @@ "id": "remote-workspace", "area": "工作区", "group": "远程开发", - "capability": "远程连接、远程路径工作区与主机文件编辑", + "capability": "远程连接、远程路径工作区、主机文件编辑与主机终端", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", "evidence": [ "desktop/internal/core/remote_session.go", "desktop/internal/core/remote_session_test.go", + "desktop/internal/core/remote_terminal.go", + "desktop/internal/core/remote_terminal_test.go", "desktop/internal/remoteplaceholder/remoteplaceholder.go", "desktop/internal/workbench/remote_browse.go", "desktop/internal/workbench/remote_browse_view.go", @@ -16,7 +18,10 @@ "desktop/internal/workbench/remote_workspace.go", "desktop/internal/workbench/remote_status_view.go", "desktop/internal/workbench/remote_documents_test.go", + "desktop/internal/workbench/remote_terminal.go", + "desktop/internal/termview/open_test.go", "desktop/internal/workbench/remote_workspace_test.go", + "desktop/internal/workbench/remote_terminal_test.go", "desktop/internal/workbench/remote_workspace_visual_test.go" ] }, @@ -26,16 +31,19 @@ "evidence": [ "desktop/internal/core/remote_session.go", "desktop/internal/core/remote_session_test.go", + "desktop/internal/core/remote_terminal.go", + "desktop/internal/core/remote_terminal_test.go", "desktop/internal/remoteplaceholder/remoteplaceholder.go", "desktop/internal/workbench/remote_browse.go", "desktop/internal/workbench/remote_browse_view.go", "desktop/internal/workbench/remote_documents.go", "desktop/internal/workbench/remote_workspace.go", - "desktop/internal/workbench/remote_status_view.go" + "desktop/internal/workbench/remote_status_view.go", + "desktop/internal/workbench/remote_terminal.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区里主机文件可以打开、编辑和保存,终端、搜索、Git 和运行暂不可用。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史、终端、Git 和信任项目都被拒绝并提示,不回退到本机;查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_documents_test.go 的 2 个测试和 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收仍待完成。主机文件的外部修改监听、终端、Git、搜索与端口转发见 remote-development-workspace。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区里主机文件可以打开、编辑和保存,终端在主机上运行,搜索、Git 和运行暂不可用。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史、插件终端、Git 和信任项目都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、internal/core 的 TestRemoteTerminal* 与 termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放)仍待完成。主机文件的外部修改监听、Git、搜索与端口转发见 remote-development-workspace。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -72,5 +80,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。" + "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。" }