diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index 377b90d9b..f3e973b33 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -186,6 +186,69 @@ func (c *Client) RemoteReadDir(ctx context.Context, sessionID, path string) (Rem return result, err } +// RemoteStat is the metadata of the absolute host path itself over the session sessionID; a +// link is described, not followed. It fails like RemoteReadDir. +func (c *Client) RemoteStat(ctx context.Context, sessionID, path string) (RemoteFileMetadata, error) { + var result RemoteFileMetadata + err := c.RemoteHostRequest(ctx, sessionID, "fs.stat", struct { + Path string `json:"path"` + }{path}, &result) + return result, err +} + +// RemoteFileVersion identifies the content of a host file as it was read or saved; a guarded +// write is refused when the file no longer has it. +type RemoteFileVersion struct { + Size uint64 `json:"size"` + // ModifiedMs is milliseconds since the Unix epoch, nil when the host did not report it. + ModifiedMs *int64 `json:"modifiedMs"` +} + +// RemoteReadFile reads the whole host file path over the session sessionID and returns its +// bytes and the version they were read at. A file larger than Core opens for editing fails with +// CodeNotSupported; otherwise it fails like RemoteReadDir. path must name a regular file or a +// link to one: the host server opens the path before it checks what it is, so the caller checks +// with RemoteStat first. +func (c *Client) RemoteReadFile(ctx context.Context, sessionID, path string) ([]byte, RemoteFileVersion, error) { + var result struct { + Data []byte `json:"data"` + RemoteFileVersion + } + err := c.Execute(ctx, "remote.readFile", struct { + SessionID string `json:"sessionId"` + Path string `json:"path"` + }{sessionID, path}, &result) + if err != nil { + return nil, RemoteFileVersion{}, err + } + return result.Data, result.RemoteFileVersion, nil +} + +// RemoteWriteFile replaces the host file path over the session sessionID with data, atomically +// through a temporary sibling and through a link. With expected, a file that no longer has that +// version is left alone; without it, the file must not exist yet. saved is false for either +// refusal, and the version is the saved content's otherwise. Content larger than the host +// accepts in one request fails with CodeProcessFailed. +func (c *Client) RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *RemoteFileVersion) (version RemoteFileVersion, saved bool, err error) { + var result struct { + Status string `json:"status"` + RemoteFileVersion + } + err = c.Execute(ctx, "remote.writeFile", struct { + SessionID string `json:"sessionId"` + Path string `json:"path"` + Data []byte `json:"data"` + Expected *RemoteFileVersion `json:"expected,omitempty"` + }{sessionID, path, data, expected}, &result) + if err != nil { + return RemoteFileVersion{}, false, err + } + if result.Status != "saved" { + return RemoteFileVersion{}, false, nil + } + return result.RemoteFileVersion, true, nil +} + // RemoteHostRequest performs the finite host method with params over the session sessionID and // decodes its result into result, which may be nil. Core accepts the filesystem, environment // and port queries, server.state and the controls of existing processes and terminals; a @@ -257,10 +320,10 @@ type remoteWorkspaceKey struct{} // WithRemoteWorkspace returns a context whose requests run on the host of binding. Every // request of the context carries the binding except the remote.* commands, which name their -// session themselves; Core refuses a command that has no remote adapter with -// CodeNotSupported, so nothing of the context falls back to the local placeholder. While the -// binding has no session a request fails at once with CodeConnectionClosed and Core never sees -// it. +// session themselves, and the payload-only commands (payloadOnlyCommands); Core refuses a +// command that has no remote adapter with CodeNotSupported, so nothing of the context falls +// back to the local placeholder. While the binding has no session a request fails at once with +// CodeConnectionClosed and Core never sees it. func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context.Context { if binding == nil { return ctx @@ -268,6 +331,29 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context. return context.WithValue(ctx, remoteWorkspaceKey{}, binding) } +// payloadOnlyCommands are the commands an open document sends that compute only from their +// payload: Core's handler reads no file, starts no process and names no workspace path, so the +// answer is the same on any computer. They go without the remote workspace, which Core would +// refuse for want of an adapter, and keep working while the host is disconnected, so the user +// can still type, decode the bytes the host returned and plan the save that will then fail. +// +// Add a command here only after reading its Core handler; a command that touches the workspace +// sent without the binding would read the empty placeholder instead of the host. +var payloadOnlyCommands = map[string]bool{ + "document.lifecycle": true, + "document.planSaveBatch": true, + "document.reduceSaveBatch": true, + "editor.lineEdit": true, + "editor.navigationHistory.reduce": true, + "editor.parseNavigationInput": true, + "editor.recent.reduce": true, + "editor.recovery.decide": true, + "languages.matchFirstLine": true, + "markdown.outline": true, + "text.decode": true, + "text.encode": true, +} + // RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context. func RemoteWorkspaceOf(ctx context.Context) *RemoteWorkspace { binding, _ := ctx.Value(remoteWorkspaceKey{}).(*RemoteWorkspace) @@ -283,11 +369,12 @@ type remoteWorkspace struct { } // remoteWorkspaceRequest is what a request of ctx sends as its remote workspace: nil for a -// local context and for a remote.* command, the binding's session and roots otherwise. session -// is the pointer the request read, so a later loss detaches only that session. +// local context, a remote.* command and a payload-only command, the binding's session and roots +// otherwise. session is the pointer the request read, so a later loss detaches only that +// session. func remoteWorkspaceRequest(ctx context.Context, command string) (wire *remoteWorkspace, binding *RemoteWorkspace, session *string, err error) { binding = RemoteWorkspaceOf(ctx) - if binding == nil || isRemoteSessionCommand(command) { + if binding == nil || isRemoteSessionCommand(command) || payloadOnlyCommands[command] { return nil, nil, nil, nil } session = binding.session.Load() diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index 2d75820a9..d71be2d36 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -107,6 +107,39 @@ func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) { if err := client.RemoteServerState(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { t.Fatalf("server.state = %v, want connection_closed", err) } + if _, err := client.RemoteStat(ctx, "no-such-session", "/srv/repo/README.md"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("fs.stat = %v, want connection_closed", err) + } + if _, _, err := client.RemoteReadFile(ctx, "no-such-session", "/srv/repo/README.md"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("readFile = %v, want connection_closed", err) + } + modified := int64(1) + if _, saved, err := client.RemoteWriteFile(ctx, "no-such-session", "/srv/repo/README.md", []byte("text"), &RemoteFileVersion{Size: 4, ModifiedMs: &modified}); saved || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("writeFile = %v, %v, want connection_closed", saved, err) + } +} + +// A context without its remote workspace sends requests that compute from their payload as +// local ones, and leaves a local context as it was. +// A payload-only command of a remote workspace goes as a local request, connected or not, so +// typing and decoding keep working while the host is away; a command that reads the workspace +// still needs the session. +func TestPayloadOnlyCommandsSendNoRemoteWorkspace(t *testing.T) { + binding := NewRemoteWorkspace("/cache/remote/1/abc/repo", "/srv/repo", nil) + ctx := WithRemoteWorkspace(context.Background(), binding) + for _, attached := range []bool{false, true} { + if attached { + binding.Attach("session-7") + } + for command := range payloadOnlyCommands { + if wire, owner, session, err := remoteWorkspaceRequest(ctx, command); wire != nil || owner != nil || session != nil || err != nil { + t.Fatalf("%s (attached %v) = %+v, %v, %v, %v, want a local request", command, attached, wire, owner, session, err) + } + } + } + if wire, _, _, err := remoteWorkspaceRequest(ctx, "file.read"); wire == nil || err != nil { + t.Fatalf("file.read = %+v, %v, want the binding", wire, err) + } } // Closing every session ends the process's remote development: Core then refuses to connect. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 0e6d8c61c..db56e89b6 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1618,6 +1618,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.deleteConfirm": "Delete “{name}”?", "desktop.remote.deleteFailed": "Cannot delete the connection: {reason}", "desktop.remote.diagnostics": "OpenSSH Output", + "desktop.remote.document.disconnected": "the remote workspace is not connected; try again once it reconnects", + "desktop.remote.document.failed": "the host could not read or write it", + "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.timedOut": "the host did not answer in time", + "desktop.remote.document.tooLargeToSave": "This file exceeds the {limit} the host takes in one save. Your edits remain open.", "desktop.remote.edit": "Edit", "desktop.remote.empty": "No saved connections yet. Fill in the form and save it.", "desktop.remote.error.duplicate": "Another saved connection already uses this.", @@ -1702,8 +1708,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. The Project tool window lists the host's files; editing, terminals, search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. The Project tool window lists the host's files.", + "desktop.remote.workspace.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.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.", @@ -5086,6 +5092,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.deleteConfirm": "删除“{name}”?", "desktop.remote.deleteFailed": "无法删除连接:{reason}", "desktop.remote.diagnostics": "OpenSSH 输出", + "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试", + "desktop.remote.document.failed": "主机无法读取或写入这个文件", + "desktop.remote.document.notFound": "主机上已没有这个文件", + "desktop.remote.document.permissionDenied": "主机账户没有访问这个文件的权限", + "desktop.remote.document.timedOut": "主机没有及时响应", + "desktop.remote.document.tooLargeToSave": "文件超过主机单次保存上限 {limit},编辑内容仍保留。", "desktop.remote.edit": "编辑", "desktop.remote.empty": "还没有保存的连接。填写右侧表单后保存。", "desktop.remote.error.duplicate": "另一个已保存的连接已在使用这个值。", @@ -5170,8 +5182,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/workbench/app.go b/desktop/internal/workbench/app.go index 4764307c4..7826a34ee 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -217,6 +217,9 @@ type Kernel interface { RemoteDisconnect(ctx context.Context, sessionID string) (bool, error) RemoteCloseAll(ctx context.Context) (int, error) RemoteReadDir(ctx context.Context, sessionID, path string) (core.RemoteDirectory, error) + RemoteStat(ctx context.Context, sessionID, path string) (core.RemoteFileMetadata, error) + 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 GitCreateTag(ctx context.Context, root, name, revision, message string) error GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error) diff --git a/desktop/internal/workbench/document_conflict.go b/desktop/internal/workbench/document_conflict.go index 5f9a9f633..10452f1c7 100644 --- a/desktop/internal/workbench/document_conflict.go +++ b/desktop/internal/workbench/document_conflict.go @@ -112,7 +112,7 @@ func (a *App) loadDocumentDisk(p *project, d *document) { } d.resolvingConflict = true revision, generation := d.view.Revision(), d.conflictGeneration - read := a.documentReader + read, raw := a.documentTextOf(p), a.documentRawOf(p) kernel, _ := a.kernel.(editorKernel) encoding, hasBOM, coded := d.encoding, d.hasBOM, d.needsCodec() // The view's text is unchanged until the apply below, which checks the revision: the content @@ -123,9 +123,9 @@ func (a *App) loadDocumentDisk(p *project, d *document) { var data []byte var err error if coded { - data, err = readRawDocument(d.path) + data, err = raw(ctx, d.path) } else { - data, err = read(d.path) + data, err = read(ctx, d.path) } observed = data var content editorview.Content diff --git a/desktop/internal/workbench/document_observation.go b/desktop/internal/workbench/document_observation.go index 0f5a32d0f..60f8911be 100644 --- a/desktop/internal/workbench/document_observation.go +++ b/desktop/internal/workbench/document_observation.go @@ -197,36 +197,30 @@ func (a *App) scheduleDocumentChecks(p *project) { p.docs.checking++ baseline := d.view.SavedSnapshot() missing := d.recreateMissing - read := a.documentReader + read, raw := a.documentTextOf(p), a.documentRawOf(p) maximum := int64(a.searchPreferences.MaximumFileBytes) - if baseline.Len() > 16<<20 { - read = func(path string) ([]byte, error) { - data, err := documentio.ReadFileLimit(path, maximum) - if err != nil { - return nil, err - } - kind, err := core.ClassifyDocumentText(data) - if kind == core.DocumentInvalidUTF8 { - return nil, errUnsupportedEncoding - } - if kind == core.DocumentBinary { - return nil, errNotText - } - return data, err + if baseline.Len() > 16<<20 && p.remote == nil { + // A host file opens up to remoteDocumentReadLimit, so only a local one is this large. + read = func(_ context.Context, path string) ([]byte, error) { + return classifiedDocument(documentio.ReadFileLimit(path, maximum)) } } kernel, _ := a.kernel.(editorKernel) encoding, hasBOM, disk := d.encoding, d.hasBOM, d.diskBytes a.background(p, 0, func(ctx context.Context) func(*App) { - data, err := read(d.path) - // The baseline is compared in place: copying it would double the memory a check - // needs for a large document. - same := func() bool { return baseline.EqualBytes(data) } + var data []byte + var err error + var same func() bool if disk != nil { // The file is not plain UTF-8: it is compared as bytes and decoded as it was - // opened. Its bytes may even be invalid UTF-8, which the reader refuses. - data, err = readRawDocument(d.path) + // opened. Its bytes may even be invalid UTF-8, which the text reader refuses. + data, err = raw(ctx, d.path) same = func() bool { return bytes.Equal(data, disk) } + } else { + data, err = read(ctx, d.path) + // The baseline is compared in place: copying it would double the memory a check + // needs for a large document. + same = func() bool { return baseline.EqualBytes(data) } } changed := err == nil && (missing || !same()) var content editorview.Content @@ -289,6 +283,13 @@ func (a *App) applyDocumentCheck(p *project, d *document, baseline rope.Rope, co d.checkPending = true return } + if errors.Is(err, errRemoteDisconnected) { + // The host is checked again once the connection opens (reconnectRemote); a close waits + // for that, as it does for a check that failed. + d.checkFailed = true + // log-exempt: 同一次失败已经记录过:连接丢失已记录为 remote_session_lost,状态栏显示重连。 + return + } if err != nil && !errors.Is(err, os.ErrNotExist) { d.checkFailed = true a.emit(documentFailedLevel, documentEventOpenFailed, documentOpenFields(err)) diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index d7b4ea2a8..1256ef044 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -270,7 +270,7 @@ func (a *App) syntaxRegistry() *syntax.Registry { // group. The file is read and its language's grammar loaded away from the window thread; a // file that cannot be read, is binary or is too large is not opened and the banner says why. func (a *App) openFile(p *project, path string) { - if path == "" || a.refuseRemote(p, "open_file") { + if path == "" { return } path = filepath.Clean(path) @@ -278,6 +278,16 @@ func (a *App) openFile(p *project, path string) { a.selectDocument(p, d.id) return } + if p.remote != nil { + // A remote workspace edits the files of its host folder; the viewers still read this + // computer's files. + if _, ok := remoteHostPathBelow(p.root, p.remote.binding.RemoteRoot(), path); !ok && a.refuseRemote(p, "open_file") { + return + } + if _, ok := viewerKindOf(path); ok && a.refuseRemote(p, "open_viewer") { + return + } + } if kind, ok := viewerKindOf(path); ok && !p.standalone { a.openViewer(p, path, kind) return @@ -293,8 +303,12 @@ func (a *App) openFile(p *project, path string) { name := filepath.Base(path) kernel, _ := a.kernel.(editorKernel) budget := int64(a.searchPreferences.MaxFileBytes) + bytesOf := a.documentBytesOf(p) + remote := p.remote != nil a.background(p, 0, func(ctx context.Context) func(*App) { - read, err := readDocumentEncodedLimit(ctx, kernel, path, budget) + // A host file is read over the session (remote_documents.go); decoding, recovery and the + // language are payload-only Core commands, so they need no connection. + read, err := readDocumentEncodedLimit(ctx, kernel, bytesOf, path, budget) restored := a.prepareRecoveredDocument(ctx, p, path, read.text, err) if restored.found && restored.missing { err = nil @@ -322,8 +336,9 @@ func (a *App) openFile(p *project, path string) { location := p.docs.locations[path] delete(p.docs.locations, path) defer a.openFinished(p, path, err) - if errors.Is(err, errNotText) && !p.standalone { - // A binary file opens in the hex viewer rather than not at all. + if errors.Is(err, errNotText) && !p.standalone && !remote { + // A binary file opens in the hex viewer rather than not at all. The viewer reads + // this computer's files, so a remote workspace says the file is not text instead. a.openViewer(p, path, viewerHex) return } @@ -343,8 +358,9 @@ func (a *App) openFile(p *project, path string) { } // A plugin that serves this language starts its server the first time a // file of it is opened, not when the project opens: a workspace of Go - // files must not pay for a Java server. - if languageID != "" { + // files must not pay for a Java server. A remote workspace runs none on this + // computer, which would read the placeholder. + if languageID != "" && !remote { a.startPluginServer(languageID) } if d := p.docs.byPath(path); d != nil { @@ -402,7 +418,13 @@ func (a *App) openFileAtPosition(p *project, path string, line, column int) { // readDocument reads an editor file and asks Core to classify its complete // contents, refusing binary controls or bytes that cannot be edited as UTF-8. func readDocument(path string) ([]byte, error) { - data, err := documentio.ReadFile(path) + return classifiedDocument(documentio.ReadFile(path)) +} + +// classifiedDocument is data, the complete contents of a file read with err, when Core +// classifies it as editor text: binary controls and bytes that cannot be edited as UTF-8 are +// refused. +func classifiedDocument(data []byte, err error) ([]byte, error) { if err != nil { return nil, err } @@ -467,6 +489,12 @@ func documentOpenReason(err error) string { return "not_regular" case errors.Is(err, documentio.ErrSymbolicLink): return "symbolic_link" + case errors.Is(err, errRemoteDisconnected): + return "remote_disconnected" + case errors.Is(err, errRemoteTimedOut): + return "remote_timed_out" + case errors.Is(err, errRemoteFileFailed): + return "remote_failed" case errors.Is(err, fs.ErrNotExist): return "not_found" case errors.Is(err, fs.ErrPermission): @@ -490,6 +518,9 @@ func (a *App) documentReason(err error) string { case errors.Is(err, documentio.ErrSymbolicLink): return i18n.Shared(a.language(), "document.fileAccess.openTheTargetFileDirectlySymbolicLinkEditingIsNotSupportedByThisFileAdapter") } + if reason, ok := a.remoteDocumentReason(err); ok { + return reason + } var pathErr *os.PathError if errors.As(err, &pathErr) { return pathErr.Err.Error() @@ -536,7 +567,9 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. a.refreshGitGutter(p, d) a.refreshInlineBlame(p, d) p.docs.group = group - if !virtual { + if !virtual && p.remote == nil { + // The host's folder is not watched yet; a remote document is checked when it is saved, + // before it closes and after the connection opens again (remote_documents.go). a.watchDocument(p, d) } a.focusDocument(id) @@ -653,11 +686,18 @@ func (a *App) saveDocumentMode(p *project, id int, auto bool) { consent := d.linkConsent d.linkConsent = nil d.saving = true + remote := a.remoteDocuments(p) a.background(p, 0, func(ctx context.Context) func(*App) { var err error bytesOut := data if bytesOut, err = a.encodeForSave(ctx, d, data); err == nil { switch { + case remote != nil && missing: + err = remote.create(ctx, path, bytesOut) + case remote != nil: + // The host replaces the file as its own, so a remote save never asks about + // hard links. + err = remote.save(ctx, path, bytesOut, expected) case missing: err = create(path, bytesOut) case consent != nil: @@ -880,14 +920,6 @@ func (a *App) removeDocument(p *project, d *document) { // saveProjectDocuments drains writes and verifies each current document before closing. func (a *App) saveProjectDocuments(p *project, done func(bool)) { - if p.remote != nil && len(p.docs.list) == 0 { - // A remote workspace opens no file yet (openFile refuses it), so there is nothing to save. - // Core's save batch is a pure reducer with no remote adapter, and a request of the - // project's context carries the remote binding, which Core refuses; asking would keep the - // workspace from closing. A remote workspace with documents still asks, and fails loudly. - done(true) - return - } a.saveProjectPass(p, make(map[int]int), done) } @@ -909,6 +941,8 @@ func (a *App) saveProjectPass(p *project, verified map[int]int, done func(bool)) for _, d := range p.docs.list { documents = append(documents, core.SaveBatchDocument{ID: documentMember(d.id), Dirty: !d.scratch && (d.dirty() || d.conflicted), ContentSynchronized: !d.view.IsComposing()}) } + // The save batch is planned from the documents' states alone, so it goes without a remote + // workspace's binding, which Core refuses for a request with no remote adapter. ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) plan, err := a.kernel.PlanDocumentSaveBatch(ctx, documents) cancel() diff --git a/desktop/internal/workbench/documents_tabless.go b/desktop/internal/workbench/documents_tabless.go index cbc730b18..f1ab25447 100644 --- a/desktop/internal/workbench/documents_tabless.go +++ b/desktop/internal/workbench/documents_tabless.go @@ -41,8 +41,9 @@ func (a *App) openTablessDocument(p *project, path string) { p.docs.opening[path] = true registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) + bytesOf := a.documentBytesOf(p) a.background(p, 0, func(ctx context.Context) func(*App) { - file := a.readTablessFile(ctx, kernel, registry, path) + file := a.readTablessFile(ctx, kernel, bytesOf, registry, path) return func(a *App) { delete(p.docs.opening, path) // A file that is not text, or that cannot be read, has no document; its Diff stays read only. @@ -63,14 +64,14 @@ type tablessFile struct { err error } -// readTablessFile reads path and prepares its text and grammar; it runs on a worker. -func (a *App) readTablessFile(ctx context.Context, kernel editorKernel, registry *syntax.Registry, path string) tablessFile { - read, err := readDocumentEncoded(ctx, kernel, path) - file := tablessFile{read: read, err: err} +// readTablessFile reads path with read and prepares its text and grammar; it runs on a worker. +func (a *App) readTablessFile(ctx context.Context, kernel editorKernel, read documentBytes, registry *syntax.Registry, path string) tablessFile { + text, err := readDocumentEncoded(ctx, kernel, read, path) + file := tablessFile{read: text, err: err} if err != nil { return file } - file.content = editorview.Prepare(read.text) + file.content = editorview.Prepare(text.text) file.languageID, file.grammar = a.resolveDocumentLanguage(ctx, registry, path, file.content.Snapshot()) return file } diff --git a/desktop/internal/workbench/editor_actions.go b/desktop/internal/workbench/editor_actions.go index 8d3bbba9b..fec2decf3 100644 --- a/desktop/internal/workbench/editor_actions.go +++ b/desktop/internal/workbench/editor_actions.go @@ -103,7 +103,9 @@ func (a *App) clearEditorActions(d *document) { // collectEditorActions asks the plugins for the actions of the document's current text. An answer // that arrives after the text changed is dropped, since its ranges no longer name the document. func (a *App) collectEditorActions(p *project, d *document) { - if a.plugins == nil || d.virtual || d.path == "" { + // The plugins of a remote workspace do not run yet (#2231): its documents name placeholder + // paths, which have nothing on this computer. + if a.plugins == nil || d.virtual || d.path == "" || p.remote != nil { return } data, _ := d.view.Text() diff --git a/desktop/internal/workbench/encoding.go b/desktop/internal/workbench/encoding.go index 9dc569899..49ff00cd0 100644 --- a/desktop/internal/workbench/encoding.go +++ b/desktop/internal/workbench/encoding.go @@ -6,7 +6,6 @@ import ( "errors" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/encodingname" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -48,25 +47,22 @@ type documentRead struct { disk []byte } -// readDocumentEncoded reads the file at path as the editor opens it. Plain UTF-8 reads as -// before; a file with a UTF-8 byte order mark, UTF-16 or a legacy encoding is detected and -// decoded by Core. A file Core cannot decode is refused for the reason readDocument gave. -func readDocumentEncoded(ctx context.Context, kernel editorKernel, path string) (documentRead, error) { - return readDocumentEncodedLimit(ctx, kernel, path, 16<<20) +// readDocumentEncoded reads the file at path through read as the editor opens it, up to the +// editor's default limit. +func readDocumentEncoded(ctx context.Context, kernel editorKernel, read documentBytes, path string) (documentRead, error) { + return readDocumentEncodedLimit(ctx, kernel, read, path, 16<<20) } -func readDocumentEncodedLimit(ctx context.Context, kernel editorKernel, path string, limit int64) (documentRead, error) { - data, err := documentio.ReadFileLimit(path, limit) - if err == nil { - kind, classifyErr := core.ClassifyDocumentText(data) - err = classifyErr - if kind == core.DocumentInvalidUTF8 { - err = errUnsupportedEncoding - } - if kind == core.DocumentBinary { - err = errNotText - } +// readDocumentEncodedLimit reads up to limit bytes of the file at path through read as the +// editor opens it. Plain UTF-8 reads as it is; a file with a UTF-8 byte order mark, UTF-16 or a +// legacy encoding is detected and decoded by Core. A file Core cannot decode is refused for the +// reason classifiedDocument gave. +func readDocumentEncodedLimit(ctx context.Context, kernel editorKernel, read documentBytes, path string, limit int64) (documentRead, error) { + raw, err := read(ctx, path, limit) + if err != nil { + return documentRead{}, err } + data, err := classifiedDocument(raw, nil) if err == nil && !bytes.HasPrefix(data, utf8BOM) { return documentRead{text: data}, nil } @@ -76,13 +72,6 @@ func readDocumentEncodedLimit(ctx context.Context, kernel editorKernel, path str if kernel == nil { return documentRead{}, err } - raw := data - if err != nil { - var readErr error - if raw, readErr = documentio.ReadFileLimit(path, limit); readErr != nil { - return documentRead{}, err - } - } decoded, decodeErr := kernel.DecodeFileBytes(ctx, raw, "") if decodeErr != nil { if err != nil { @@ -97,10 +86,10 @@ func readDocumentEncodedLimit(ctx context.Context, kernel editorKernel, path str // all of it: the window shows replacement characters for the bytes it lost. var errLossyDecode = errors.New("the file has bytes the chosen encoding cannot decode") -// readDocumentAs reads the file at path decoded as encoding, which is the reopen path: a wrong -// choice shows replacement characters and Lossy says so. -func readDocumentAs(ctx context.Context, kernel editorKernel, path, encoding string) (documentRead, bool, error) { - raw, err := documentio.ReadFile(path) +// readDocumentAs reads the file at path through read decoded as encoding, which is the reopen +// path: a wrong choice shows replacement characters and Lossy says so. +func readDocumentAs(ctx context.Context, kernel editorKernel, read documentBytes, path, encoding string) (documentRead, bool, error) { + raw, err := read(ctx, path, 16<<20) if err != nil { return documentRead{}, false, err } @@ -108,11 +97,11 @@ func readDocumentAs(ctx context.Context, kernel editorKernel, path, encoding str if err != nil { return documentRead{}, false, err } - read := documentRead{text: []byte(decoded.Text), encoding: decoded.Encoding, hasBOM: decoded.HasBOM, disk: raw} + opened := documentRead{text: []byte(decoded.Text), encoding: decoded.Encoding, hasBOM: decoded.HasBOM, disk: raw} if decoded.Encoding == "utf-8" && !decoded.HasBOM { - read.encoding, read.disk = "", nil + opened.encoding, opened.disk = "", nil } - return read, decoded.Lossy, nil + return opened, decoded.Lossy, nil } // expectedDiskBytes is what the file must still hold for a guarded save. @@ -179,8 +168,9 @@ func (a *App) reopenWithEncoding(p *project, d *document, encoding string) { // Unchanged until the apply below, which checks the revision: the content is measured // against this text on the worker. base := d.view.TextSnapshot() + bytesOf := a.documentBytesOf(p) a.background(p, 0, func(ctx context.Context) func(*App) { - read, lossy, err := readDocumentAs(ctx, kernel, d.path, encoding) + read, lossy, err := readDocumentAs(ctx, kernel, bytesOf, d.path, encoding) var content editorview.Content if err == nil { content = editorview.PrepareAgainst(base, read.text) @@ -269,9 +259,9 @@ func (d *document) revertEncodingChoice() { d.previousEncoding, d.encodingChanged = nil, false } -// readRawDocument reads a file's bytes without judging them as text, for a document whose -// file is compared and decoded through Core. -func readRawDocument(path string) ([]byte, error) { return documentio.ReadFileLimit(path, 64<<20) } +// rawDocumentLimit bounds the bytes of a file read without judging them as text, for a document +// whose file is compared and decoded through Core (documentRawOf). +const rawDocumentLimit = 64 << 20 // decodeExternal is the editor text of bytes read from the file of a document: the bytes // themselves for plain UTF-8, or Core's decoding in the encoding the document was opened with. diff --git a/desktop/internal/workbench/local_history.go b/desktop/internal/workbench/local_history.go index 68d3e1e1e..c33e51d2a 100644 --- a/desktop/internal/workbench/local_history.go +++ b/desktop/internal/workbench/local_history.go @@ -106,7 +106,9 @@ func (a *App) renamedLocalHistory(p *project, oldPath, newPath string, before [] // when it is asked for. func (a *App) localHistoryJob(p *project, work func(ctx context.Context, kernel localHistoryKernel, root, storage string, policy core.HistoryPolicy) error) { kernel, ok := a.kernel.(localHistoryKernel) - if !ok || p == nil || p.standalone { + // Core keys local history by the project's real folder on this computer, which a remote + // workspace's placeholder is not, so a remote workspace keeps none yet (#2231). + if !ok || p == nil || p.standalone || p.remote != nil { return } root, policy := p.root, a.settings.LocalHistory.Policy() @@ -188,7 +190,8 @@ type localHistoryState struct { // openLocalHistory shows the snapshots of the file at path. func (a *App) openLocalHistory(p *project, path string) { kernel, ok := a.kernel.(localHistoryKernel) - if !ok || p == nil || p.standalone { + // A remote workspace keeps no local history yet (localHistoryJob), so there is none to show. + if !ok || p == nil || p.standalone || a.refuseRemote(p, "local_history") { return } rel, inside := projectRelative(p.root, path) diff --git a/desktop/internal/workbench/logevents_test.go b/desktop/internal/workbench/logevents_test.go index 96c16bc7b..54e01dcdd 100644 --- a/desktop/internal/workbench/logevents_test.go +++ b/desktop/internal/workbench/logevents_test.go @@ -33,7 +33,12 @@ func TestLogEventsMatchCatalog(t *testing.T) { {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&fs.PathError{Op: "open", Path: "a.txt", Err: fs.ErrNotExist})}, {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&fs.PathError{Op: "open", Path: "a.txt", Err: fs.ErrPermission})}, {documentFailedLevel, documentEventOpenFailed, documentOpenFields(failure)}, + {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&remoteFileError{reason: errRemoteDisconnected})}, + {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&remoteFileError{reason: errRemoteTimedOut, cause: context.DeadlineExceeded})}, + {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&remoteFileError{reason: fs.ErrPermission, cause: remoteLogError(&core.Error{Command: "remote.stat", Code: core.CodePermissionDenied, Message: "/home/dev/a.txt"})})}, + {documentFailedLevel, documentEventOpenFailed, documentOpenFields(&remoteFileError{reason: errRemoteFileFailed, cause: errRemoteOutsideFolder})}, {documentFailedLevel, documentEventSaveFailed, documentSaveFields(3, 0, failure)}, + {documentFailedLevel, documentEventSaveFailed, documentSaveFields(4, 2, &remoteFileError{reason: errRemoteSaveTooLarge, cause: remoteLogError(&core.Error{Command: "remote.writeFile", Code: core.CodeProcessFailed, Details: `{"remoteCode":"TOO_LARGE"}`})})}, {core.LevelWarn, "editor.document.watch_failed", map[string]any{"stage": "create"}}, {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "document_external_change", "reason": "disk_conflict"}}, {documentFailedLevel, documentEventSaveFailed, documentSaveFields(12, 41, failure)}, diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index df715632e..c7101b881 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -123,7 +123,8 @@ func (a *App) documentEdited(p *project, d *document, edit editorview.Edit) { // document; edits that arrive meanwhile stay queued. func (a *App) startDocumentSync(p *project, d *document) { s := &d.sync - if s.running || a.plugins == nil || a.project != p { + // A remote workspace starts no language server (#2231): its documents name placeholder paths. + if s.running || a.plugins == nil || a.project != p || p.remote != nil { return } server, pluginID := a.documentSyncServer(d) diff --git a/desktop/internal/workbench/remote_documents.go b/desktop/internal/workbench/remote_documents.go new file mode 100644 index 000000000..2b6ca00f7 --- /dev/null +++ b/desktop/internal/workbench/remote_documents.go @@ -0,0 +1,341 @@ +package workbench + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io/fs" + "path" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// The editor of a remote workspace reads and writes its files on the host (#2231, R0 step 3). +// A document keeps the placeholder path the Project tool window shows; each read and write +// translates it to the host path below the workspace's folder and goes over the workspace's +// current session. Nothing is read from or written to the placeholder, and a path outside the +// workspace's folder is refused. +// +// A read asks the host what the path is first (remote.stat), because the host server opens a path +// before it checks what it is, and a named pipe would block it. Like a local file, a link, a +// folder, a pipe, a socket or a device does not open as text. A save keeps the promise of the +// local guarded write that a file someone else changed is never overwritten: it reads the file +// again, compares its bytes with the ones the editor last read or wrote, and replaces it only +// while the file still has the version that read returned. A file that no longer exists is a +// conflict, and saving one the user chose to recreate writes only while it is still missing. +// The host replaces a file through a temporary sibling, which leaves its other hard links with +// the old bytes. +// +// Core decodes, encodes, recovers and names the language of a file without reading it: those +// are payload-only commands, which the Core client sends without the workspace's binding, so +// they also work while the host is away. Until the host watches the workspace (the next step of +// R0), a change on the host is found when a document is saved, before it closes and after the +// connection opens again. A host file opens up to remoteDocumentReadLimit, Core's limit, and +// saves up to remoteDocumentWriteLimit, the most the host takes in one request. Unsaved edits are +// drafts on this computer under the placeholder path, which is the same each time the folder +// opens. +// Core's message of a failure may name a host path, so the log keeps only its command and code. + +const ( + // remoteDocumentReadLimit is the largest host file the editor opens: Core reads no more in + // one request. + remoteDocumentReadLimit = 16 << 20 + // remoteDocumentWriteLimit is the largest file the editor saves on the host: the host takes + // no more in one request. + remoteDocumentWriteLimit = 8 << 20 + // remoteDocumentTimeout bounds one read or write of a host file, which may cross a slow link. + remoteDocumentTimeout = 2 * time.Minute +) + +// These errors explain why a host file could not be read or written, besides the reasons a +// local file has. +var ( + // errRemoteDisconnected: the workspace has no session, or the request found its connection + // closed. + errRemoteDisconnected = errors.New("the remote workspace is not connected") + // errRemoteTimedOut: the host did not answer in time. + errRemoteTimedOut = errors.New("the host did not answer in time") + // errRemoteFileFailed: the host could not read or write the file for another reason. + errRemoteFileFailed = errors.New("the host could not read or write the file") + // errRemoteOutsideFolder is the cause of a refused path outside the workspace's folder. + errRemoteOutsideFolder = errors.New("the path is outside the remote workspace's folder") + // errRemoteSaveTooLarge: the file is larger than the host takes in one save + // (remoteDocumentWriteLimit), which is less than a local file saves. + errRemoteSaveTooLarge = errors.New("the file is larger than the host takes in one save") +) + +// remoteFileError is a failed read or write of a host file. reason is what the editor tells the +// user and matches with errors.Is; cause is the failure as the log keeps it, nil when there is +// nothing more to say. +type remoteFileError struct { + reason error + cause error +} + +func (e *remoteFileError) Error() string { return e.reason.Error() } + +func (e *remoteFileError) Unwrap() []error { + if e.cause == nil { + return []error{e.reason} + } + return []error{e.reason, e.cause} +} + +// documentBytes reads up to limit bytes of the file of a document at path, which is the +// placeholder path in a remote workspace. A file larger than limit is errTooLarge. +type documentBytes func(ctx context.Context, path string, limit int64) ([]byte, error) + +// localDocumentBytes reads a document's file on this computer. +func localDocumentBytes(_ context.Context, path string, limit int64) ([]byte, error) { + return documentio.ReadFileLimit(path, limit) +} + +// documentBytesOf is where the documents of p are read from: the host of a remote workspace, or +// this computer. It runs on the window thread; what it returns runs on any. +func (a *App) documentBytesOf(p *project) documentBytes { + if r := a.remoteDocuments(p); r != nil { + return r.read + } + return localDocumentBytes +} + +// documentTextOf is how a check of the documents of p reads a file as editor text: a.documentReader +// on this computer, which tests replace, or the host's bytes classified the same way. It runs on +// the window thread; what it returns runs on any. +func (a *App) documentTextOf(p *project) func(context.Context, string) ([]byte, error) { + if r := a.remoteDocuments(p); r != nil { + return func(ctx context.Context, path string) ([]byte, error) { + return classifiedDocument(r.read(ctx, path, remoteDocumentReadLimit)) + } + } + read := a.documentReader + return func(_ context.Context, path string) ([]byte, error) { return read(path) } +} + +// documentRawOf is how a check of the documents of p reads the bytes of a file that is not plain +// UTF-8. It runs on the window thread; what it returns runs on any. +func (a *App) documentRawOf(p *project) func(context.Context, string) ([]byte, error) { + read := a.documentBytesOf(p) + return func(ctx context.Context, path string) ([]byte, error) { return read(ctx, path, rawDocumentLimit) } +} + +// remoteDocuments reads and writes the files of a remote workspace's documents on its host. +type remoteDocuments struct { + kernel Kernel + binding *core.RemoteWorkspace + // lost reports that a request found the connection of a session closed. Core reports only + // the requests that carry the binding, and these name their session themselves. + lost func(session string) +} + +// remoteDocuments is how the documents of p reach its host, nil for a local project. +func (a *App) remoteDocuments(p *project) *remoteDocuments { + if p == nil || p.remote == nil { + return nil + } + return &remoteDocuments{kernel: a.kernel, binding: p.remote.binding, lost: a.remoteSessionLost(p)} +} + +// read returns the bytes of the host file of local, a path below the workspace's placeholder. +// A file larger than limit, or than Core reads, is errTooLarge. +func (r *remoteDocuments) read(ctx context.Context, local string, limit int64) ([]byte, error) { + host, session, err := r.target(local) + if err != nil { + return nil, err + } + data, _, err := r.readHost(ctx, session, host, limit) + return data, err +} + +// save replaces the host file of local with data while it still holds expected, the bytes the +// editor last read or wrote. A file that changed or no longer exists is documentio.ErrConflict, +// and so is one that changes between the comparison and the write. +func (r *remoteDocuments) save(ctx context.Context, local string, data, expected []byte) error { + if len(data) > remoteDocumentWriteLimit { + return &remoteFileError{reason: errRemoteSaveTooLarge} + } + host, session, err := r.target(local) + if err != nil { + return err + } + current, version, err := r.readHost(ctx, session, host, remoteDocumentReadLimit) + switch { + case errors.Is(err, fs.ErrNotExist), errors.Is(err, errTooLarge): + // The expected bytes were read, so a file too large to read holds others. + return documentio.ErrConflict + case err != nil: + return err + case !bytes.Equal(current, expected): + return documentio.ErrConflict + } + return r.write(ctx, session, host, data, &version) +} + +// create writes data as the host file of local, which must not exist: one that exists again is +// documentio.ErrConflict. +func (r *remoteDocuments) create(ctx context.Context, local string, data []byte) error { + if len(data) > remoteDocumentWriteLimit { + return &remoteFileError{reason: errRemoteSaveTooLarge} + } + host, session, err := r.target(local) + if err != nil { + return err + } + return r.write(ctx, session, host, data, nil) +} + +// target is the host path of local and the session to reach it over. +func (r *remoteDocuments) target(local string) (host, session string, err error) { + host, ok := remoteHostPathBelow(r.binding.LocalRoot(), r.binding.RemoteRoot(), local) + if !ok { + return "", "", &remoteFileError{reason: errRemoteFileFailed, cause: errRemoteOutsideFolder} + } + if session = r.binding.SessionID(); session == "" { + return "", "", &remoteFileError{reason: errRemoteDisconnected} + } + return host, session, nil +} + +// readHost reads the host file host over session and returns the version its bytes were read at. +func (r *remoteDocuments) readHost(ctx context.Context, session, host string, limit int64) ([]byte, core.RemoteFileVersion, error) { + limit = min(limit, remoteDocumentReadLimit) + ctx, cancel := context.WithTimeout(ctx, remoteDocumentTimeout) + defer cancel() + metadata, err := r.kernel.RemoteStat(ctx, session, host) + if err != nil { + return nil, core.RemoteFileVersion{}, r.failed(session, err) + } + switch { + case metadata.Kind == core.RemoteFileKindSymlink: + return nil, core.RemoteFileVersion{}, documentio.ErrSymbolicLink + case metadata.Kind != core.RemoteFileKindFile: + return nil, core.RemoteFileVersion{}, documentio.ErrNotRegular + case limit < 0 || metadata.Size > uint64(limit): + return nil, core.RemoteFileVersion{}, errTooLarge + } + data, version, err := r.kernel.RemoteReadFile(ctx, session, host) + if err != nil { + return nil, core.RemoteFileVersion{}, r.failed(session, err) + } + if int64(len(data)) > limit { + // The file grew after it was described. + return nil, core.RemoteFileVersion{}, errTooLarge + } + return data, version, nil +} + +// write replaces the host file host with data over session while it has expected, or creates it +// while it does not exist when expected is nil. +func (r *remoteDocuments) write(ctx context.Context, session, host string, data []byte, expected *core.RemoteFileVersion) error { + ctx, cancel := context.WithTimeout(ctx, remoteDocumentTimeout) + defer cancel() + _, saved, err := r.kernel.RemoteWriteFile(ctx, session, host, data, expected) + if err != nil { + if failure := r.failed(session, err); !errors.Is(failure, errTooLarge) { + return failure + } + // The host refused this many bytes: the save says so with the host's limit, not with + // the open's reason or a local file's limit. + return &remoteFileError{reason: errRemoteSaveTooLarge, cause: remoteLogError(err)} + } + if !saved { + return documentio.ErrConflict + } + return nil +} + +// failed is err, a failed request over session, as the editor handles it. A closed connection is +// reported lost, so the workspace connects again. +func (r *remoteDocuments) failed(session string, err error) error { + var coreErr *core.Error + if !errors.As(err, &coreErr) { + if errors.Is(err, context.DeadlineExceeded) { + return &remoteFileError{reason: errRemoteTimedOut, cause: err} + } + return &remoteFileError{reason: errRemoteFileFailed, cause: documentLogError(err)} + } + reason := errRemoteFileFailed + switch coreErr.Code { + case core.CodeConnectionClosed: + if r.lost != nil { + r.lost(session) + } + reason = errRemoteDisconnected + case core.CodeWorkspaceNotFound: + reason = fs.ErrNotExist + case core.CodePermissionDenied: + reason = fs.ErrPermission + case core.CodeTimedOut: + reason = errRemoteTimedOut + case core.CodeCancelled: + reason = context.Canceled + case core.CodeNotSupported: + if coreErr.Command == "remote.readFile" { + // Core reads no larger file in one request. + reason = errTooLarge + } + case core.CodeProcessFailed: + if remoteFailureCode(coreErr) == "TOO_LARGE" { + reason = errTooLarge + } + } + return &remoteFileError{reason: reason, cause: remoteLogError(err)} +} + +// remoteFailureCode is the host's own code of a failed request, "" when Core gave none. +func remoteFailureCode(err *core.Error) string { + var details struct { + RemoteCode string `json:"remoteCode"` + } + if json.Unmarshal([]byte(err.Details), &details) != nil { + return "" + } + return details.RemoteCode +} + +// remoteHostPathBelow is the host path of full in the host folder remoteRoot, which localRoot +// stands for; the root itself is the host folder. ok is false for a path outside localRoot. +func remoteHostPathBelow(localRoot, remoteRoot, full string) (string, bool) { + rel, err := filepath.Rel(localRoot, full) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + if rel == "." { + return remoteRoot, true + } + return path.Join(remoteRoot, filepath.ToSlash(rel)), true +} + +// remoteDocumentReason is the words for err when a host file could not be read or written for a +// reason only a remote workspace has, or that the system would name in a local one. ok is false +// for the editor's own reasons, which read the same for both. +func (a *App) remoteDocumentReason(err error) (string, bool) { + var remoteErr *remoteFileError + if !errors.As(err, &remoteErr) { + return "", false + } + lang := a.language() + switch { + case errors.Is(remoteErr.reason, errRemoteDisconnected): + return i18n.Shared(lang, "desktop.remote.document.disconnected"), true + case errors.Is(remoteErr.reason, errRemoteTimedOut): + return i18n.Shared(lang, "desktop.remote.document.timedOut"), true + case errors.Is(remoteErr.reason, fs.ErrNotExist): + return i18n.Shared(lang, "desktop.remote.document.notFound"), true + case errors.Is(remoteErr.reason, fs.ErrPermission): + return i18n.Shared(lang, "desktop.remote.document.permissionDenied"), true + case errors.Is(remoteErr.reason, errTooLarge): + return a.text.Editor.TooLarge, true + case errors.Is(remoteErr.reason, errRemoteSaveTooLarge): + limit := strconv.Itoa(remoteDocumentWriteLimit>>20) + " MiB" + return i18n.SharedFormat(lang, "desktop.remote.document.tooLargeToSave", map[string]string{"limit": limit}), true + } + return i18n.Shared(lang, "desktop.remote.document.failed"), true +} diff --git a/desktop/internal/workbench/remote_documents_test.go b/desktop/internal/workbench/remote_documents_test.go new file mode 100644 index 000000000..62b345545 --- /dev/null +++ b/desktop/internal/workbench/remote_documents_test.go @@ -0,0 +1,255 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" +) + +// remoteTestReadme is the host file the Project tool window lists as README.md. +const remoteTestReadme = remoteTestHome + "/project/README.md" + +// takeFileError is the failure the next request for a host file ends with, once; nil lets it +// through. The lock is held. +func (k *remoteHostKernel) takeFileError(session string) error { + k.fileSessions = append(k.fileSessions, session) + err := k.fileErr + k.fileErr = nil + return err +} + +func (k *remoteHostKernel) RemoteStat(_ context.Context, session, path string) (core.RemoteFileMetadata, error) { + k.mu.Lock() + defer k.mu.Unlock() + if err := k.takeFileError(session); err != nil { + return core.RemoteFileMetadata{}, err + } + if kind, ok := k.kinds[path]; ok { + return core.RemoteFileMetadata{Kind: kind}, nil + } + data, ok := k.files[path] + if !ok { + return core.RemoteFileMetadata{}, &core.Error{Command: "remote.stat", Code: core.CodeWorkspaceNotFound, Message: "no such file: " + path} + } + return core.RemoteFileMetadata{Kind: core.RemoteFileKindFile, Size: uint64(len(data))}, nil +} + +func (k *remoteHostKernel) RemoteReadFile(_ context.Context, session, path string) ([]byte, core.RemoteFileVersion, error) { + k.mu.Lock() + defer k.mu.Unlock() + if err := k.takeFileError(session); err != nil { + return nil, core.RemoteFileVersion{}, err + } + data, ok := k.files[path] + if !ok { + return nil, core.RemoteFileVersion{}, &core.Error{Command: "remote.readFile", Code: core.CodeWorkspaceNotFound, Message: "no such file: " + path} + } + return slices.Clone(data), k.versionLocked(path), nil +} + +// RemoteWriteFile writes while the file has the expected version, or creates it while it does +// not exist, as the host server does. +func (k *remoteHostKernel) RemoteWriteFile(_ context.Context, session, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + if err := k.takeFileError(session); err != nil { + return core.RemoteFileVersion{}, false, err + } + if err := k.writeErr; err != nil { + k.writeErr = nil + return core.RemoteFileVersion{}, false, err + } + current, exists := k.files[path] + switch { + case expected == nil && exists, + expected != nil && (!exists || expected.Size != uint64(len(current)) || expected.ModifiedMs == nil || *expected.ModifiedMs != k.modified[path]): + return core.RemoteFileVersion{}, false, nil + } + k.writeLocked(path, data) + return k.versionLocked(path), true, nil +} + +// versionLocked is the version of the host file path. The lock is held. +func (k *remoteHostKernel) versionLocked(path string) core.RemoteFileVersion { + modified := k.modified[path] + return core.RemoteFileVersion{Size: uint64(len(k.files[path])), ModifiedMs: &modified} +} + +// writeLocked replaces the host file path with data and moves its modification time on. The +// lock is held. +func (k *remoteHostKernel) writeLocked(path string, data []byte) { + if k.files == nil { + k.files, k.modified = make(map[string][]byte), make(map[string]int64) + } + k.files[path] = slices.Clone(data) + k.modified[path]++ +} + +// put changes the host file path as someone on the host does. +func (k *remoteHostKernel) put(path, text string) { + k.set(func(k *remoteHostKernel) { k.writeLocked(path, []byte(text)) }) +} + +// file is the text of the host file path, and whether it exists. +func (k *remoteHostKernel) file(path string) (string, bool) { + k.mu.Lock() + defer k.mu.Unlock() + data, ok := k.files[path] + return string(data), ok +} + +// openRemoteFile opens the file name of p's folder and waits for its read to finish; the +// document is nil when the file did not open. +func (h *harness) openRemoteFile(t *testing.T, p *project, name string) *document { + t.Helper() + path := filepath.Join(p.root, name) + h.app.openFile(p, path) + awaitDocumentState(t, h, func() bool { _, opening := p.docs.opening[path]; return !opening }) + h.settle() + return p.docs.byPath(path) +} + +// typeAtCaret types text into d at its caret. +func typeAtCaret(t *testing.T, d *document, text string) { + t.Helper() + input := d.view.TextInput(app.TextInputContext{ID: d.hit}) + if _, err := input.OnEvent(app.TextEvent{Kind: app.TextInsert, Text: text}); err != nil { + t.Fatal(err) + } +} + +// saveAndWait saves d and waits for the save and the checks it schedules to finish. +func (h *harness) saveAndWait(t *testing.T, p *project, d *document) { + t.Helper() + h.app.saveDocument(p, d.id) + awaitDocumentState(t, h, func() bool { return !d.saving && !d.checking && !d.checkPending }) + h.settle() +} + +// notified reports that a notification says text. +func (h *harness) notified(text string) bool { + return slices.ContainsFunc(h.app.notifications.list, func(n *notification) bool { return n.text == text }) +} + +// The editor of a remote workspace opens, saves and compares the host's files over the +// workspace's session, and nothing is read from or written to the placeholder. A save over a file +// changed on the host is refused and shows the conflict, and loading the host's version resolves +// it. Neither the host nor its paths are logged. +func TestRemoteWorkspaceEditsTheHostsFiles(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.put(remoteTestReadme, "# Project\n") + p := h.openRemoteTestProject(t) + + d := h.openRemoteFile(t, p, "README.md") + if d == nil { + t.Fatalf("README.md did not open; notifications %+v", h.app.notifications.list) + } + if text, _ := d.view.Text(); string(text) != "# Project\n" { + t.Fatalf("opened %q, want the host's text", text) + } + typeAtCaret(t, d, "local ") + h.saveAndWait(t, p, d) + if got, _ := k.file(remoteTestReadme); got != "local # Project\n" || d.dirty() { + t.Fatalf("host file %q, dirty %v: the save did not reach the host", got, d.dirty()) + } + if _, err := os.Lstat(d.path); err == nil { + t.Fatal("the save wrote the file below the placeholder") + } + if sessions := k.fileSessions; len(sessions) == 0 || slices.ContainsFunc(sessions, func(s string) bool { return s != "session-1" }) { + t.Fatalf("the host's files went over sessions %q, want the workspace's", sessions) + } + + k.put(remoteTestReadme, "changed on the host\n") + typeAtCaret(t, d, "more ") + h.saveAndWait(t, p, d) + if got, _ := k.file(remoteTestReadme); got != "changed on the host\n" { + t.Fatalf("host file %q: the save overwrote a change made on the host", got) + } + if !d.conflicted || !h.notified(h.app.text.Editor.SaveFailed("README.md", i18n.Shared(lang, "editor.externalConflict"))) { + t.Fatal("the refused save did not show the conflict") + } + h.app.loadDocumentDisk(p, d) + awaitDocumentState(t, h, func() bool { return !d.resolvingConflict }) + h.settle() + if text, _ := d.view.Text(); string(text) != "changed on the host\n" || d.conflicted || d.dirty() { + t.Fatalf("text %q, conflicted %v: loading the host's version did not resolve the conflict", text, d.conflicted) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A host file that cannot be read or saved says why in the user's words: it is missing, not a +// regular file, not permitted, larger than the host takes, or the connection closed. A closed +// connection connects again on its own and then compares the documents with the host, so a change +// made on the host meanwhile shows as a conflict. The log keeps only the command and the code. +func TestRemoteDocumentFailuresSayWhy(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.put(remoteTestReadme, "# Project\n") + k.set(func(k *remoteHostKernel) { + k.kinds = map[string]core.RemoteFileKind{remoteTestHome + "/project/pipe": core.RemoteFileKindOther} + }) + p := h.openRemoteTestProject(t) + r := p.remote + editor := h.app.text.Editor + + if h.openRemoteFile(t, p, "missing.txt") != nil || !h.notified(editor.OpenFailed("missing.txt", i18n.Shared(lang, "desktop.remote.document.notFound"))) { + t.Fatal("a missing host file did not say it is gone") + } + if h.openRemoteFile(t, p, "pipe") != nil || !h.notified(editor.OpenFailed("pipe", h.app.documentReason(documentio.ErrNotRegular))) { + t.Fatal("a host path that is not a regular file opened") + } + k.set(func(k *remoteHostKernel) { + k.fileErr = &core.Error{Command: "remote.stat", Code: core.CodePermissionDenied, Message: "permission denied: " + remoteTestReadme} + }) + if h.openRemoteFile(t, p, "README.md") != nil || !h.notified(editor.OpenFailed("README.md", i18n.Shared(lang, "desktop.remote.document.permissionDenied"))) { + t.Fatal("a file the host account may not read did not say so") + } + + d := h.openRemoteFile(t, p, "README.md") + if d == nil { + t.Fatal("README.md did not open") + } + typeAtCaret(t, d, "local ") + k.set(func(k *remoteHostKernel) { + k.writeErr = &core.Error{Command: "remote.writeFile", Code: core.CodeProcessFailed, Message: "too large", Details: `{"remoteCode":"TOO_LARGE"}`} + }) + h.saveAndWait(t, p, d) + tooLarge := i18n.SharedFormat(lang, "desktop.remote.document.tooLargeToSave", map[string]string{"limit": "8 MiB"}) + if !d.dirty() || !h.notified(editor.SaveFailed("README.md", tooLarge)) { + t.Fatal("a save the host refused as too large did not say so with the host's limit") + } + + // The connection closes during the next save, and the file changes on the host before the + // workspace connects again. + k.put(remoteTestReadme, "changed on the host\n") + k.set(func(k *remoteHostKernel) { + k.fileErr = &core.Error{Command: "remote.stat", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.app.saveDocument(p, d.id) + h.await("the new session and the check after it", func() bool { + return r.session == "session-2" && !r.beating && !d.saving && !d.checking && !d.checkPending + }) + h.settle() + if !h.notified(editor.SaveFailed("README.md", i18n.Shared(lang, "desktop.remote.document.disconnected"))) { + t.Fatal("the save that found the connection closed did not say so") + } + if got, _ := k.file(remoteTestReadme); got != "changed on the host\n" || !d.conflicted || !d.dirty() { + t.Fatalf("host file %q, conflicted %v: the check after reconnecting did not find the host's change", got, d.conflicted) + } + if got := countFailures(logger, "remote_session_lost"); got != 1 { + t.Fatalf("remote_session_lost logged %d times, want once", got) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 5c5aa6dce..dc3f58758 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -4,8 +4,6 @@ import ( "context" "errors" "path" - "path/filepath" - "strings" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -28,11 +26,12 @@ 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. The features that -// still read the project through the local file system (the editor, terminals, Git, the watch -// of the folder, language servers, run configurations and plugins) are not started for it and -// say so, until each moves to the host (R0, step 3). The workspace stays in safe mode: nothing of -// the host's project runs on this computer. +// 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, +// 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. const ( // remoteHeartbeatInterval is the pause between two heartbeats of a connected workspace. @@ -141,15 +140,10 @@ func (p *project) remoteHostPath(full string) string { if p.remote == nil { return full } - rel, err := filepath.Rel(p.root, full) - if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - return full - } - root := p.remote.binding.RemoteRoot() - if rel == "." { - return root + if host, ok := remoteHostPathBelow(p.root, p.remote.binding.RemoteRoot(), full); ok { + return host } - return path.Join(root, filepath.ToSlash(rel)) + return full } // remoteLocation is the workspace as the user names it: the connection's name and the host @@ -363,6 +357,7 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { a.attachRemote(p, result.Session.ID) a.refreshRemoteTree(p) + a.recheckRemoteDocuments(p) return } if result.Session != nil { @@ -466,14 +461,7 @@ func (a *App) openRemoteProject(target remoteTarget) { p := &project{root: target.root, name: name, commit: newCommitState()} r := &remoteProject{connectionID: target.connectionID, name: target.name, connection: target.connection, home: target.session.HomeDirectory} p.remote = r - r.binding = core.NewRemoteWorkspace(target.root, target.remoteRoot, func(session string) { - // A request of the workspace found the connection closed, on the request's goroutine. - a.post(func(a *App) { - if a.project == p { - a.loseRemote(p, session, errRemoteSessionClosed) - } - }) - }) + r.binding = core.NewRemoteWorkspace(target.root, target.remoteRoot, a.remoteSessionLost(p)) // The host's project never runs on this computer, so the workspace stays in safe mode. ctx := core.WithRemoteWorkspace(core.WithProjectCodeAllowed(context.Background(), p.trust.allowed), r.binding) p.ctx, p.cancel = context.WithCancel(ctx) @@ -484,4 +472,31 @@ func (a *App) openRemoteProject(target remoteTarget) { a.logView.reset() a.worktreeView.reset() a.attachRemote(p, target.session.ID) + // Unsaved edits of the folder's files are drafts on this computer; they open over the host's + // files as a local project's do. + a.restoreCheckpoints(p) +} + +// remoteSessionLost is how a request of p reports, on its own goroutine, that it found the +// connection of session closed: the window thread then handles the loss. +func (a *App) remoteSessionLost(p *project) func(session string) { + return func(session string) { + a.post(func(a *App) { + if a.project == p { + a.loseRemote(p, session, errRemoteSessionClosed) + } + }) + } +} + +// recheckRemoteDocuments compares every document of p with its host file once a new session +// opened: a change made on the host meanwhile is then found as any external change is, and a +// close that waited on a check that found the host away goes on. +func (a *App) recheckRemoteDocuments(p *project) { + for _, d := range p.docs.list { + if !d.virtual { + d.checkPending = true + } + } + a.scheduleDocumentChecks(p) } diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index ecab2e0cc..227722147 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -37,8 +37,9 @@ var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ } // remoteHostKernel stands in for a host over SSH: it opens numbered sessions, lists -// remoteTestFolders, answers heartbeats as the test says and lists the workspace's tree only -// for a request that carries the workspace's session. Everything else is the real Core. +// remoteTestFolders, answers heartbeats as the test says, lists the workspace's tree only for a +// request that carries the workspace's session and keeps the files of files +// (remote_documents_test.go). Everything else is the real Core. type remoteHostKernel struct { *testKernel mu sync.Mutex @@ -53,6 +54,15 @@ type remoteHostKernel struct { closed []string // listings are the sessions the Project tool window's listings carried, "" for none. listings []string + // files are the host's files by host path, and modified the time each was last written. + files map[string][]byte + modified map[string]int64 + // kinds are the host paths that are not regular files. + kinds map[string]core.RemoteFileKind + // fileErr fails the next request for a host file, once; writeErr fails the next write, once. + fileErr, writeErr error + // fileSessions are the sessions the requests for host files went over. + fileSessions []string } func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) { @@ -346,26 +356,29 @@ func TestRemoteWorkspaceOpensTheChosenFolder(t *testing.T) { } } -// What still runs on this computer refuses in a remote workspace and says so: opening a file, a -// terminal, trusting the folder and every tool window but the project's and the notifications'. -// Copying a path copies the host's. +// 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. func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { h, _, _, logger := remoteWorkspaceHarness(t) lang := h.app.language() p := h.openRemoteTestProject(t) localOnly := i18n.Shared(lang, "desktop.remote.workspace.localOnly") - h.app.openFile(p, filepath.Join(p.root, "README.md")) + // The viewers and a file outside the folder would read this computer's files. + 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") } asked := false h.app.askToTrustProject(p, func() { asked = true }) h.settle() - if asked || p.trust.asking || p.selectedDocument(p.terms.bench.FocusedGroup) != nil { + if asked || p.trust.asking || p.selectedDocument(p.terms.bench.FocusedGroup) != nil || len(p.docs.opening) != 0 { t.Fatal("the workspace opened a file or asked to be trusted") } - for _, operation := range []string{"open_file", "open_terminal", "project_trust"} { + for _, operation := range []string{"open_viewer", "open_file", "local_history", "open_terminal", "project_trust"} { if !rejected(logger, operation, "remote_workspace") { t.Fatalf("%s was not logged as refused", operation) } diff --git a/desktop/internal/workbench/remote_workspace_visual_test.go b/desktop/internal/workbench/remote_workspace_visual_test.go index fbf2c51fd..d1ea574f5 100644 --- a/desktop/internal/workbench/remote_workspace_visual_test.go +++ b/desktop/internal/workbench/remote_workspace_visual_test.go @@ -19,7 +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, and the status bar's menu of the connection. +// 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. func TestVisualRemoteWorkspace(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") if out == "" { @@ -101,6 +102,24 @@ func TestVisualRemoteWorkspace(t *testing.T) { } shot("menu") h.app.project.remote.menuOpen = false + h.settleChain() + + // The host's README opens in the editor, and a save over a change made on the host + // meanwhile is refused and shows the conflict. + p := h.app.project + kernel.put(remoteTestReadme, "# Project\n\nBuilt and run on the host.\n") + d := h.openRemoteFile(t, p, "README.md") + if d == nil { + t.Fatal("README.md did not open") + } + shot("file") + kernel.put(remoteTestReadme, "# Project\n\nChanged on the host.\n") + typeAtCaret(t, d, "Edited here. ") + h.saveAndWait(t, p, d) + if !d.conflicted { + t.Fatal("the save over the host's change did not show the conflict") + } + shot("conflict") }) } } diff --git a/desktop/internal/workbench/source_preview.go b/desktop/internal/workbench/source_preview.go index 24500de32..a4edfc5a8 100644 --- a/desktop/internal/workbench/source_preview.go +++ b/desktop/internal/workbench/source_preview.go @@ -183,11 +183,12 @@ func (a *App) showSourcePreview(p *project, sp *sourcePreview, path string, line registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) budget := int64(a.searchPreferences.MaxFileBytes) + bytesOf := a.documentBytesOf(p) a.background(p, 0, func(ctx context.Context) func(*App) { data, err := openText, error(nil) if !open { var read documentRead - read, err = readDocumentEncodedLimit(ctx, kernel, path, budget) + read, err = readDocumentEncodedLimit(ctx, kernel, bytesOf, path, budget) data = read.text } var content editorview.Content @@ -224,8 +225,9 @@ func (a *App) showEditablePreview(p *project, sp *sourcePreview, path string, li generation := sp.generation registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) + bytesOf := a.documentBytesOf(p) a.background(p, 0, func(ctx context.Context) func(*App) { - file := a.readTablessFile(ctx, kernel, registry, path) + file := a.readTablessFile(ctx, kernel, bytesOf, registry, path) return func(a *App) { if sp.generation != generation || a.project != p || !alive(a) { return diff --git a/docs/assets/remote-workspace/README.md b/docs/assets/remote-workspace/README.md index 260273410..a7841896f 100644 --- a/docs/assets/remote-workspace/README.md +++ b/docs/assets/remote-workspace/README.md @@ -1,10 +1,12 @@ # 远程工作区(#2231)无头测试截图 -来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表和心跳也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: +来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳和主机上的 `README.md` 也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: - 连接后“远程开发”窗口改为主机的文件夹选择:顶部是连接名和 `用户@主机`,路径框可以输入 `~` 或 `/` 开头的路径,无法读取的条目在列表下方说明数量,底部显示将打开的主机路径; -- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明远程工作区暂时只能浏览文件夹,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; -- 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”。 +- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑和保存,终端、搜索、Git 和运行暂不可用,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; +- 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”; +- 在项目树打开 `README.md`:编辑器显示主机上的内容,Markdown 预览照常; +- 主机上的文件被别人改过后再保存:保存被拒绝,通知说明文件在外部被修改,编辑器上方出现“保留编辑器版本 / 加载磁盘版本”,主机上的内容不被覆盖。 截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 @@ -13,6 +15,8 @@ | 选择主机文件夹 | [浅色英文](remote-workspace-browse-light-en-US.png) | [深色中文](remote-workspace-browse-dark-zh-CN.png) | | 打开的远程工作区 | [浅色英文](remote-workspace-opened-light-en-US.png) | [深色中文](remote-workspace-opened-dark-zh-CN.png) | | 状态栏连接菜单 | [浅色英文](remote-workspace-menu-light-en-US.png) | [深色中文](remote-workspace-menu-dark-zh-CN.png) | +| 打开主机上的文件 | [浅色英文](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) | 复验:从仓库根目录设置绝对路径 `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 new file mode 100644 index 000000000..47c49c262 Binary files /dev/null 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 new file mode 100644 index 000000000..2a1b011be Binary files /dev/null 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 new file mode 100644 index 000000000..a62e5f504 Binary files /dev/null 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 new file mode 100644 index 000000000..881031f39 Binary files /dev/null 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 1b7a6f6d1..00a56cc83 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 fdf5ce1cb..0dea2b96e 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 ae4ba79ac..80ec2daa6 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 1429dcffa..448e778b6 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/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 7084e7913..7944e1bb3 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -911,6 +911,51 @@ "desktop" ] }, + { + "id": "desktop.remote.document.disconnected", + "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: the workspace has no connection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.document.timedOut", + "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: the host did not answer in time", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.document.notFound", + "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: the file is gone on the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.document.permissionDenied", + "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: the SSH account may not access it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.document.failed", + "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: any other failure of the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.document.tooLargeToSave", + "description": "Reason a file of a remote workspace could not be saved, after “Could not save {name}: ”: larger than the host takes in one save; limit is a size such as 8 MiB", + "platforms": [ + "desktop" + ], + "parameters": { + "limit": "string" + } + }, { "id": "desktop.remote.edit", "description": "Remote Development window: button that turns the selected connection's overview into its form", @@ -1210,8 +1255,14 @@ "desktop.remote.status.reconnect": "Reconnect", "desktop.remote.status.disconnect": "Disconnect and Close", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", - "desktop.remote.workspace.banner": "This is a remote workspace. The Project tool window lists the host's files; editing, terminals, search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. The Project tool window lists the host's files." + "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.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." }, "zh-CN": { "desktop.remote.title": "远程开发", @@ -1353,8 +1404,14 @@ "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},编辑内容仍保留。" } } } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index b3f17db7d..59a9bc020 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -2,7 +2,7 @@ "id": "remote-workspace", "area": "工作区", "group": "远程开发", - "capability": "远程连接与远程路径工作区", + "capability": "远程连接、远程路径工作区与主机文件编辑", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -12,8 +12,10 @@ "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_documents_test.go", "desktop/internal/workbench/remote_workspace_test.go", "desktop/internal/workbench/remote_workspace_visual_test.go" ] @@ -27,12 +29,13 @@ "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" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区暂时只能浏览文件夹,打开文件、终端、Git、搜索监听和信任项目都被拒绝并提示,不回退到本机;查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试和 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收仍待完成。远程文件编辑保存、监听、终端、Git 与端口转发见 remote-development-workspace。", + "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。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -69,5 +72,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。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)。" }