diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index d6f889580..62b842146 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -305,6 +305,16 @@ func (c *Client) RemoteWriteFile(ctx context.Context, sessionID, path string, da return result.RemoteFileVersion, true, nil } +// RemoteCreateDirectory creates the host folder path over the session sessionID with its missing +// parents; a folder already there is left as it is. RemoteWriteFile creates no parent, so a file +// whose folder may be missing is written after it. +func (c *Client) RemoteCreateDirectory(ctx context.Context, sessionID, path string) error { + return c.RemoteHostRequest(ctx, sessionID, "fs.createDir", struct { + Path string `json:"path"` + Recursive bool `json:"recursive"` + }{path, 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 @@ -395,7 +405,8 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context. // that will then fail. workspace.filterChanges drops the host watch's changes in folders Core // hides, by name alone; workspace.searchPresentation groups search results by the paths it is // sent, and workspace.replaceText replaces in the text it is sent, which Replace All read from -// the host. +// the host. editor.find searches the text of the editor or the diff side it is sent, and +// github.parseRemote reads the GitHub repository out of the remote URL the host's Git answered. // // 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. @@ -403,11 +414,13 @@ var payloadOnlyCommands = map[string]bool{ "document.lifecycle": true, "document.planSaveBatch": true, "document.reduceSaveBatch": true, + "editor.find": true, "editor.lineEdit": true, "editor.navigationHistory.reduce": true, "editor.parseNavigationInput": true, "editor.recent.reduce": true, "editor.recovery.decide": true, + "github.parseRemote": true, "languages.matchFirstLine": true, "markdown.outline": true, "text.decode": true, diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 2b9c017d4..86120e7de 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1862,8 +1862,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.userPlaceholder": "Auto (SSH config, otherwise your local user name)", "desktop.remote.via": "via {jump}", "desktop.remote.viaHosts": "via {hosts}", - "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit, save and are searched on the host, and terminals run on the host; 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, save and search the host's files and run terminals on the host.", + "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit, save and are searched on the host, and terminals and Git run on the host; running, debugging and language servers do not work here yet.", + "desktop.remote.workspace.gitAbove": "This folder is inside a Git repository that starts in a folder above it on the host. Open the repository's top folder to use Git in a remote workspace.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit, save and search the host's files, run terminals and use Git on the host.", + "desktop.remote.workspace.safeBanner": "This remote workspace is in safe mode: you can browse, edit, save and search its files on the host. Trust the folder to use Git.", "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.", @@ -5494,8 +5496,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.userPlaceholder": "自动(SSH 配置,否则本机用户名)", "desktop.remote.via": "经 {jump}", "desktop.remote.viaHosts": "经由 {hosts}", - "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑、保存和搜索,终端在主机上运行;Git 和运行暂不可用。", - "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端。", + "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑、保存和搜索,终端和 Git 在主机上运行;运行、调试和语言服务器暂不可用。", + "desktop.remote.workspace.gitAbove": "此文件夹位于主机上更上层文件夹开始的 Git 仓库中。请打开仓库的顶层文件夹,以便在远程工作区中使用 Git。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端和使用 Git。", + "desktop.remote.workspace.safeBanner": "此远程工作区处于安全模式:可以浏览、编辑、保存和搜索主机上的文件。信任此文件夹后即可使用 Git。", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}", "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", diff --git a/desktop/internal/remoteplaceholder/remoteplaceholder.go b/desktop/internal/remoteplaceholder/remoteplaceholder.go index 094d0f6a8..1b6d1d9bb 100644 --- a/desktop/internal/remoteplaceholder/remoteplaceholder.go +++ b/desktop/internal/remoteplaceholder/remoteplaceholder.go @@ -134,3 +134,59 @@ func reservedOnWindows(name string) bool { } return false } + +// HostSuffix is added to a local root to name the sibling Core maps every host path outside the +// workspace to: .lithe-remote-host/. +const HostSuffix = ".lithe-remote-host" + +// HostPath is the host path local stands for, as Core maps it, in the workspace whose local root +// is root and whose host folder is remoteRoot: a path below root is the same path below +// remoteRoot, and a path below root's sibling (HostSuffix) is the host path it names. ok is false +// for any other path. +func HostPath(root, remoteRoot, local string) (string, bool) { + if suffix, ok := below(root+HostSuffix, local); ok { + return path.Join("/", suffix), true + } + if suffix, ok := below(root, local); ok { + return path.Join(remoteRoot, suffix), true + } + return "", false +} + +// LocalPath is the path that stands for host, an absolute host path, in the same workspace: the +// inverse of HostPath. ok is false for a path that is not absolute, and on Windows for one with a +// name holding "\", which would name another path there. +func LocalPath(root, remoteRoot, host string) (string, bool) { + if !path.IsAbs(host) { + return "", false + } + host = path.Clean(host) + remote := path.Clean(remoteRoot) + if host == remote { + return root, true + } + base, suffix := root+HostSuffix, strings.TrimPrefix(host, "/") + if rest, ok := strings.CutPrefix(host, strings.TrimSuffix(remote, "/")+"/"); ok { + base, suffix = root, rest + } + if suffix == "" { + return base, true + } + if filepath.Separator != '/' && strings.ContainsRune(suffix, filepath.Separator) { + return "", false + } + return filepath.Join(base, filepath.FromSlash(suffix)), true +} + +// below is the slash-separated path of full below dir, "" for dir itself; ok is false for a path +// outside dir. +func below(dir, full string) (string, bool) { + rel, err := filepath.Rel(dir, full) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + if rel == "." { + return "", true + } + return filepath.ToSlash(rel), true +} diff --git a/desktop/internal/remoteplaceholder/remoteplaceholder_test.go b/desktop/internal/remoteplaceholder/remoteplaceholder_test.go index fc98b7e40..5cc751d02 100644 --- a/desktop/internal/remoteplaceholder/remoteplaceholder_test.go +++ b/desktop/internal/remoteplaceholder/remoteplaceholder_test.go @@ -104,3 +104,38 @@ func TestRootNamesTheFolderAndTellsWorkspacesApart(t *testing.T) { } } } + +// HostPath and LocalPath map the workspace's own paths below the root and every other host path +// below the root's sibling, as Core does, and each undoes the other. +func TestHostAndLocalPathsMapBothWays(t *testing.T) { + anchor := filepath.Join(string(filepath.Separator)+"cache", AnchorName) + root := Root(anchor, "c1", "/srv/repo") + sibling := root + HostSuffix + for _, tc := range []struct{ host, local string }{ + {"/srv/repo", root}, + {"/srv/repo/.git/HEAD", filepath.Join(root, ".git", "HEAD")}, + {"/srv/main/.git/worktrees/repo", filepath.Join(sibling, "srv", "main", ".git", "worktrees", "repo")}, + {"/srv/repository/x", filepath.Join(sibling, "srv", "repository", "x")}, + {"/", sibling}, + } { + local, ok := LocalPath(root, "/srv/repo", tc.host) + if !ok || local != tc.local { + t.Errorf("LocalPath(%q) = %q, %v; want %q", tc.host, local, ok, tc.local) + } + host, ok := HostPath(root, "/srv/repo", tc.local) + if !ok || host != tc.host { + t.Errorf("HostPath(%q) = %q, %v; want %q", tc.local, host, ok, tc.host) + } + } + if local, ok := LocalPath(Root(anchor, "c1", "/"), "/", "/etc/hosts"); !ok || local != filepath.Join(Root(anchor, "c1", "/"), "etc", "hosts") { + t.Errorf("LocalPath below the host's root = %q, %v", local, ok) + } + if _, ok := LocalPath(root, "/srv/repo", "relative/path"); ok { + t.Error("mapped a relative host path") + } + for _, local := range []string{filepath.Dir(root), filepath.Join(filepath.Dir(root), "other"), root + "x"} { + if host, ok := HostPath(root, "/srv/repo", local); ok { + t.Errorf("HostPath(%q) = %q; want no host path", local, host) + } + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f067abe4a..8111ac13a 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -220,6 +220,7 @@ type Kernel interface { 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) + RemoteCreateDirectory(ctx context.Context, sessionID, path string) error RemoteServerState(ctx context.Context, sessionID string) error SearchRemoteConnections(ctx context.Context, document *string, query string) (core.RemoteConnectionsState, error) RemoteParseAddress(ctx context.Context, text string) (core.RemoteAddress, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 544f64d85..aba2fbbca 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -250,8 +250,12 @@ func (b *buildState) active() bool { return b.operation != nil || len(b.running) // runs; otherwise it stops the one that runs and starts the new one once it ended, so the two // never share a port or files. A start that is asked again while one waits replaces it. // -// In safe mode the user is first asked to trust the project, since a run runs its code. +// In safe mode the user is first asked to trust the project, since a run runs its code. A +// remote workspace's project runs on its host, which a run does not reach yet. func (a *App) startRun(p *project, key string, start func(*App, *project)) { + if a.refuseRemote(p, "run_start") { + return + } if p.safeMode() { a.askToTrustProject(p, func() { a.startRun(p, key, start) }) return @@ -778,6 +782,11 @@ func (a *App) loadBuildSystems(p *project) { if p == nil || p.build.loading { return } + if p.remote != nil { + // log-exempt: 远程工作区的构建工具要在主机上运行,现在还不支持:本机的占位文件夹里没有项目,不探测构建系统; + // 构建、运行和测试窗口显示只在本机可用的说明,按下运行时 refuseRemote 记录并提示。 + return + } if a.plugins == nil || a.plugins.Backend == nil { p.build.loaded = true p.build.failed = a.text.Build.PluginsUnavailable @@ -1330,7 +1339,11 @@ func buildTaskSelection(instance *buildInstance, task *pluginservice.BuildTaskDe // so a tool call can report them, and the Build window keeps its notification and ignores them. func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userArguments []string) (*buildOperation, error) { // A task runs the build tool on the project: in safe mode the user is asked to trust it - // first, and the task starts once trusted. The caller, such as the IDE API, is refused. + // first, and the task starts once trusted. The caller, such as the IDE API, is refused. A + // remote workspace's build tool runs on its host, which a task does not reach yet. + if a.refuseRemote(p, "build_task") { + return nil, refuseBuild(refusalNotReady, "the workspace is remote") + } if p.safeMode() { a.askToTrustProject(p, func() { _, _ = a.runBuildTask(p, projectID, targetID, taskID, userArguments) }) return nil, refuseBuild(refusalNotReady, "the workspace is not trusted") diff --git a/desktop/internal/workbench/commit_view.go b/desktop/internal/workbench/commit_view.go index 473494006..b868307c6 100644 --- a/desktop/internal/workbench/commit_view.go +++ b/desktop/internal/workbench/commit_view.go @@ -127,6 +127,8 @@ func (a *App) drawCommitStatus(c ui.C, p *project) bool { switch { case p.git.safeMode: a.safeModePanel(c, p, i18n.Shared(a.language(), "desktop.trust.gitSafeMode")) + case p.git.remoteAbove: + a.gitEmpty(c, i18n.Shared(a.language(), "desktop.remote.workspace.gitAbove")) case !p.git.loaded: a.gitEmpty(c, g.Loading) case p.git.err != nil: diff --git a/desktop/internal/workbench/git.go b/desktop/internal/workbench/git.go index 6039abd85..1d58d5a78 100644 --- a/desktop/internal/workbench/git.go +++ b/desktop/internal/workbench/git.go @@ -19,7 +19,11 @@ type gitState struct { // safeMode is set, with loaded, when the status was not read because the project is in safe // mode: Core runs no Git there (#2208), and the Git views offer to trust the project. safeMode bool - status core.GitStatus + // remoteAbove is set, with loaded, when a remote workspace's folder lies inside a repository + // that starts above it on the host, which a remote workspace does not show yet + // (remoteRepositoryAbove). + remoteAbove bool + status core.GitStatus err error // tree is the same answer indexed for the project tree, which colors the rows of the // changed paths. It is rebuilt whenever the status is replaced. @@ -58,10 +62,13 @@ func (a *App) readGit(p *project, policy func(context.Context) context.Context) return func(a *App) { wasRepo := p.git.isRepository() g := gitState{loaded: true, status: status, err: err} - if core.IsGitUntrustedWorkspace(err) { + switch { + case core.IsGitUntrustedWorkspace(err): // The trust was withdrawn while the read was on its way: Core ran no Git, and the // views show safe mode rather than a failure. g = gitState{loaded: true, safeMode: true} + case err == nil && remoteRepositoryAbove(p, status): + g = gitState{loaded: true, remoteAbove: true} } if !a.setGit(p, g, generation) { return @@ -70,6 +77,10 @@ func (a *App) readGit(p *project, policy func(context.Context) context.Context) a.backgroundFailed("git_status_safe_mode", err) return } + if g.remoteAbove { + // log-exempt: 预期的缺失:远程工作区的文件夹在更上层的仓库里,Git 视图说明原因,不是失败。 + return + } if err != nil { a.operationFailed("git_status", err) a.notifyError(a.text.Git.Failed(err.Error())) diff --git a/desktop/internal/workbench/git_exclude.go b/desktop/internal/workbench/git_exclude.go index 516eeb0dc..8e16d69aa 100644 --- a/desktop/internal/workbench/git_exclude.go +++ b/desktop/internal/workbench/git_exclude.go @@ -37,7 +37,8 @@ func excludeLocallyPattern(rel string) string { } // excludeLocally adds the change's pattern to the repository's info/exclude and reads the status -// again. +// again. A remote workspace's repository is on its host, where the file is written +// (remoteDocuments.appendInfoExclude). func (a *App) excludeLocally(p *project, change core.GitChange) { kernel, ok := a.kernel.(gitObserveKernel) if !ok { @@ -46,24 +47,50 @@ func (a *App) excludeLocally(p *project, change core.GitChange) { a.performed("git.excludeLocally", surfaceContextMenu) root := p.git.repositoryRoot(p.root) pattern := excludeLocallyPattern(change.Path) + host := a.remoteDocuments(p) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { watch, found, err := kernel.GitWatchContextOf(ctx, root) if err == nil && !found { err = errors.New("not a Git repository") } - if err == nil { + if err == nil && host != nil { + err = host.appendInfoExclude(ctx, watch.GitCommonDirectory, pattern) + } else if err == nil { err = appendInfoExclude(watch.GitCommonDirectory, pattern) } return func(a *App) { if err != nil { - a.notifyError(i18n.SharedFormat(a.language(), "desktop.git.excludeFailed", map[string]string{"reason": reviewReason(err)})) - a.operationFailed("git_exclude", err) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.git.excludeFailed", map[string]string{"reason": a.excludeFailureReason(err)})) + a.operationFailed("git_exclude", p.logError(documentLogError(err))) } a.reloadGit(p) } }) } +// excludeFailureReason is the words for a failed exclusion: a remote workspace's own reasons, such +// as a lost connection, or the error itself. +func (a *App) excludeFailureReason(err error) string { + if reason, ok := a.remoteDocumentReason(err); ok { + return reason + } + return reviewReason(err) +} + +// infoExcludeAddition is the text that adds pattern to an info/exclude that holds existing; ok is +// false when the file already has that line. +func infoExcludeAddition(existing []byte, pattern string) (addition string, ok bool) { + for _, line := range strings.Split(string(existing), "\n") { + if line == pattern { + return "", false + } + } + if len(existing) > 0 && !strings.HasSuffix(string(existing), "\n") { + return "\n" + pattern + "\n", true + } + return pattern + "\n", true +} + // appendInfoExclude appends pattern to commonDir/info/exclude unless the file already has that // line. The file is created with its directory when missing. func appendInfoExclude(commonDir, pattern string) error { @@ -76,20 +103,15 @@ func appendInfoExclude(commonDir, pattern string) error { if err != nil && !os.IsNotExist(err) { return err } - for _, line := range strings.Split(string(existing), "\n") { - if line == pattern { - return nil - } - } - prefix := "" - if len(existing) > 0 && !strings.HasSuffix(string(existing), "\n") { - prefix = "\n" + addition, ok := infoExcludeAddition(existing, pattern) + if !ok { + return nil } out, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644) if err != nil { return err } - if _, err := out.WriteString(prefix + pattern + "\n"); err != nil { + if _, err := out.WriteString(addition); err != nil { out.Close() return err } diff --git a/desktop/internal/workbench/git_observation.go b/desktop/internal/workbench/git_observation.go index 300cb4c59..3dbfc9c1f 100644 --- a/desktop/internal/workbench/git_observation.go +++ b/desktop/internal/workbench/git_observation.go @@ -44,14 +44,23 @@ type gitObservation struct { // revision counts the changes that can move history (commits, refs, HEAD or config), so // a consumer such as the inline blame refreshes on it and not on index writes. revision int + // remote are a remote workspace's host watches of its metadata folders, in place of watches + // (remote_git.go). + remote map[string]*remoteGitWatch } // startGitObservation resolves the metadata roots of the project in the background and // installs their watches. The first answer rescans the status once. Finding the roots runs Git, -// so a project in safe mode is observed once it is trusted (applyProjectTrust). +// so a project in safe mode is observed once it is trusted (applyProjectTrust). A remote +// workspace's Git runs on its host, which watches the metadata too, so it is observed while it +// has a session (remote_git.go). func (a *App) startGitObservation(p *project) { kernel, ok := a.kernel.(gitObserveKernel) - if !ok || p.safeMode() || p.observe.metadata != nil || p.observe.watches != nil { + if !ok || p.safeMode() || p.observe.metadata != nil || p.observe.watches != nil || p.observe.remote != nil { + return + } + remote := p.remote != nil + if remote && (p.remote.closed || p.remote.session == "") { return } p.observe.gen++ @@ -59,7 +68,9 @@ func (a *App) startGitObservation(p *project) { a.background(p, gitTimeout, func(ctx context.Context) func(*App) { watch, found, err := kernel.GitWatchContextOf(core.AutomaticRefresh(ctx), root) var dirs []string - if found && err == nil { + if remote && found && err == nil { + dirs = remoteGitDirectories(watch) + } else if found && err == nil { dirs = []string{watch.GitDirectory} if watch.GitCommonDirectory != watch.GitDirectory { dirs = append(dirs, watch.GitCommonDirectory) @@ -77,7 +88,7 @@ func (a *App) startGitObservation(p *project) { return } if err != nil { - a.backgroundFailed("git_metadata_watch", documentLogError(err)) + a.backgroundFailed("git_metadata_watch", p.logError(documentLogError(err))) return } if !found { @@ -89,9 +100,13 @@ func (a *App) startGitObservation(p *project) { GitCommonDirectory: watch.GitCommonDirectory, WorkspaceRoot: p.root, } - o.watches = make(map[string]*documentWatch, len(dirs)) - for _, dir := range dirs { - a.startGitWatch(p, dir) + if remote { + a.startRemoteGitWatches(p, dirs) + } else { + o.watches = make(map[string]*documentWatch, len(dirs)) + for _, dir := range dirs { + a.startGitWatch(p, dir) + } } o.full = true a.scheduleGitObservation(p) @@ -253,6 +268,7 @@ func (a *App) closeGitObservation(p *project) { for _, slot := range o.watches { slot.close() } + stopRemoteGitWatches(p) o.gen++ o.watches, o.metadata, o.paths, o.full = nil, nil, nil, false } diff --git a/desktop/internal/workbench/gitlog_view.go b/desktop/internal/workbench/gitlog_view.go index d4854b31e..03a8d8054 100644 --- a/desktop/internal/workbench/gitlog_view.go +++ b/desktop/internal/workbench/gitlog_view.go @@ -858,6 +858,9 @@ func (a *App) drawLogList(c ui.C, p *project) { case p.git.safeMode: a.safeModePanel(c, p, i18n.Shared(a.language(), "desktop.trust.gitSafeMode")) return + case p.git.remoteAbove: + a.gitEmpty(c, i18n.Shared(a.language(), "desktop.remote.workspace.gitAbove")) + return case !p.git.loaded || l.loading && len(l.commits) == 0: a.gitEmpty(c, g.Loading) return diff --git a/desktop/internal/workbench/gitreview.go b/desktop/internal/workbench/gitreview.go index 483cdd503..35a6f8213 100644 --- a/desktop/internal/workbench/gitreview.go +++ b/desktop/internal/workbench/gitreview.go @@ -103,7 +103,7 @@ type blameState struct { } // openBlame opens the annotations of a tracked file of the project, with the text read from -// the saved file. +// the saved file: on this computer, or on the host of a remote workspace. func (a *App) openBlame(p *project, relative string) { kernel, ok := a.reviewKernel() if !ok { @@ -113,12 +113,16 @@ func (a *App) openBlame(p *project, relative string) { *b = blameState{open: true, loading: true, gen: b.gen + 1, path: relative, list: b.list} gen, root := b.gen, p.git.repositoryRoot(p.root) disk := filepath.Join(root, filepath.FromSlash(relative)) + readText := readBlameText + if host := a.remoteDocuments(p); host != nil { + readText = func(ctx context.Context, file string) ([]string, error) { return remoteBlameText(ctx, host, file) } + } a.performed("git.blame.open", surfaceContextMenu) a.background(p, reviewTimeout, func(ctx context.Context) func(*App) { lines, err := kernel.GitBlame(ctx, root, relative) var text []string if err == nil { - text, err = readBlameText(disk) + text, err = readText(ctx, disk) } return func(a *App) { b := &p.review.blame @@ -127,8 +131,12 @@ func (a *App) openBlame(p *project, relative string) { } b.loading = false if err != nil { - b.err = i18n.SharedFormat(a.language(), "desktop.gitReview.blameFailed", map[string]string{"reason": reviewReason(err)}) - a.operationFailed("git_blame", err) + reason, ok := a.remoteDocumentReason(err) + if !ok { + reason = reviewReason(err) + } + b.err = i18n.SharedFormat(a.language(), "desktop.gitReview.blameFailed", map[string]string{"reason": reason}) + a.operationFailed("git_blame", p.logError(documentLogError(err))) return } b.lines, b.text = lines, text @@ -137,7 +145,7 @@ func (a *App) openBlame(p *project, relative string) { } // readBlameText reads the lines of the saved file the blame refers to, bounded in size. -func readBlameText(file string) ([]string, error) { +func readBlameText(_ context.Context, file string) ([]string, error) { f, err := os.Open(file) if err != nil { return nil, err @@ -148,7 +156,28 @@ func readBlameText(file string) ([]string, error) { if err != nil && n == 0 { return nil, nil } - return strings.Split(strings.TrimSuffix(string(data[:n]), "\n"), "\n"), nil + return blameTextLines(data[:n]), nil +} + +// remoteBlameText is readBlameText on the host of a remote workspace. A file larger than the +// limit shows the annotations without its text, since the host sends a file whole or not at all. +func remoteBlameText(ctx context.Context, host *remoteDocuments, file string) ([]string, error) { + data, err := host.read(ctx, file, blameFileLimit) + switch { + case errors.Is(err, errTooLarge): + // log-exempt: 预期的缺失:文件超过注解读取上限,注解照常显示,只是没有行内容。 + return nil, nil + case err != nil: + return nil, err + case len(data) == 0: + return nil, nil + } + return blameTextLines(data), nil +} + +// blameTextLines splits the text of a blamed file into its lines. +func blameTextLines(data []byte) []string { + return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n") } // blameDate is the date a blame line was authored on, in the viewer's time zone. diff --git a/desktop/internal/workbench/gitworktree.go b/desktop/internal/workbench/gitworktree.go index 881a8bdf9..5fe582999 100644 --- a/desktop/internal/workbench/gitworktree.go +++ b/desktop/internal/workbench/gitworktree.go @@ -780,8 +780,12 @@ func (a *App) repairWorktrees(p *project) { }, nil, func(a *App) { a.notifySuccess(a.text.Worktrees.Repaired) }) } -// revealWorktree shows the checkout at path in the system's file browser. +// revealWorktree shows the checkout at path in the system's file browser. A remote workspace's +// checkouts are on the host, so it refuses there. func (a *App) revealWorktree(path string) { + if a.refuseRemote(a.project, "git_worktree_reveal") { + return + } a.performed("git.worktree.reveal", surfaceButton) a.background(nil, 0, func(context.Context) func(*App) { err := app.RevealPath(path) @@ -794,9 +798,13 @@ func (a *App) revealWorktree(path string) { }) } -// copyWorktreePath puts the path of a checkout on the clipboard. +// copyWorktreePath puts the path of a checkout on the clipboard: in a remote workspace, its path +// on the host. func (a *App) copyWorktreePath(path string) { a.performed("git.worktree.copyPath", surfaceButton) + if p := a.project; p != nil { + path = p.remoteHostPath(path) + } if err := app.SetClipboardText(path); err != nil { a.operationFailed("clipboard_copy", err) a.notifyError(a.text.Worktrees.Failed(err.Error())) @@ -814,6 +822,11 @@ func (a *App) showWorktrees() { // openWorktree opens the checkout at path as the window's project. func (a *App) openWorktree(path string) { + // A remote workspace's checkout opens over a session of its own, which this window does not + // start yet; its placeholder would open as an empty local folder. + if a.refuseRemote(a.project, "git_worktree_open") { + return + } a.performed("git.worktree.open", surfaceButton) // The worktree menu offers This Window and New Window itself. a.openProjectThisWindow(path) @@ -822,6 +835,10 @@ func (a *App) openWorktree(path string) { // beginCreateWorktree opens the dialog that creates a worktree and reads the references it // can start from. func (a *App) beginCreateWorktree(p *project) { + // The dialog chooses the new checkout's folder on this computer. + if a.refuseRemote(p, "git_worktree_create") { + return + } a.performed("git.worktree.create", surfaceButton) w := &p.worktrees cr := &w.create diff --git a/desktop/internal/workbench/gitworktree_view.go b/desktop/internal/workbench/gitworktree_view.go index b6ee2f103..3524e7fe1 100644 --- a/desktop/internal/workbench/gitworktree_view.go +++ b/desktop/internal/workbench/gitworktree_view.go @@ -78,7 +78,7 @@ func (a *App) drawWorktreeList(c ui.C, p *project) ui.Box { return ui.Column(c).FillHeight().Background(a.colors.Panel).Clip().Children(func() { ui.Row(c).Height(logToolbarHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(6).Children(func() { ui.TextField(c, &v.search, t.Search, t.Search).Grow(1).MinWidth(0) - if a.gitIconButton(c, t.New, icons.Plus, false, w.busy || !w.loaded) { + if a.gitIconButton(c, t.New, icons.Plus, false, w.busy || !w.loaded || p.remote != nil) { c.After(func() { a.beginCreateWorktree(p) }) } if a.gitIconButton(c, t.Refresh, icons.RefreshCw, false, w.loading) { @@ -197,6 +197,9 @@ func (a *App) worktreeRowMenu(row ui.ListRow, p *project, w core.GitWorktree) { } ui.ContextMenu(c, row.Element, func(menu *ui.MenuItems) { ws, t := &p.worktrees, &a.text.Worktrees + // A remote workspace's worktrees are host folders: this window neither opens them nor shows + // them in the file browser yet. + remote := p.remote != nil menu.WidthRange(180, 260) item := func(label string, disabled bool, action string, run func()) { if menu.Item(label).Disabled(disabled).Clicked() { @@ -206,9 +209,9 @@ func (a *App) worktreeRowMenu(row ui.ListRow, p *project, w core.GitWorktree) { }) } } - item(t.OpenCurrent, w.IsCurrent || w.IsPrunable || w.IsBare, "git.worktree.open", func() { a.openWorktree(w.Path) }) - item(i18n.Shared(a.language(), "desktop.worktree.openNewWindow"), w.IsPrunable || w.IsBare, "git.worktree.openNewWindow", func() { a.openWorktreeInNewWindow(w.Path) }) - item(t.Reveal, w.IsPrunable, "git.worktree.reveal", func() { a.revealWorktree(w.Path) }) + item(t.OpenCurrent, remote || w.IsCurrent || w.IsPrunable || w.IsBare, "git.worktree.open", func() { a.openWorktree(w.Path) }) + item(i18n.Shared(a.language(), "desktop.worktree.openNewWindow"), remote || w.IsPrunable || w.IsBare, "git.worktree.openNewWindow", func() { a.openWorktreeInNewWindow(w.Path) }) + item(t.Reveal, remote || w.IsPrunable, "git.worktree.reveal", func() { a.revealWorktree(w.Path) }) item(t.CopyPath, false, "git.worktree.copyPath", func() { a.copyWorktreePath(w.Path) }) menu.Separator() lock := t.Lock @@ -374,6 +377,7 @@ func (a *App) drawWorktreeOverview(c ui.C, p *project, w core.GitWorktree) { // used is named by the reason, which its hover hint shows. func (a *App) drawWorktreeActions(c ui.C, p *project, w core.GitWorktree) { ws, t := &p.worktrees, &a.text.Worktrees + remote := p.remote != nil action := func(label, blocked string, icon gfx.Icon, disabled bool, run func()) { if blocked != "" { label = blocked @@ -382,9 +386,9 @@ func (a *App) drawWorktreeActions(c ui.C, p *project, w core.GitWorktree) { c.After(run) } } - action(t.OpenCurrent, "", icons.FolderOpen, w.IsCurrent || w.IsPrunable || w.IsBare, func() { a.openWorktree(w.Path) }) - action(i18n.Shared(a.language(), "desktop.worktree.openNewWindow"), "", icons.FolderOpen, w.IsPrunable || w.IsBare, func() { a.openWorktreeInNewWindow(w.Path) }) - action(t.Reveal, "", icons.Folder, w.IsPrunable, func() { a.revealWorktree(w.Path) }) + action(t.OpenCurrent, "", icons.FolderOpen, remote || w.IsCurrent || w.IsPrunable || w.IsBare, func() { a.openWorktree(w.Path) }) + action(i18n.Shared(a.language(), "desktop.worktree.openNewWindow"), "", icons.FolderOpen, remote || w.IsPrunable || w.IsBare, func() { a.openWorktreeInNewWindow(w.Path) }) + action(t.Reveal, "", icons.Folder, remote || w.IsPrunable, func() { a.revealWorktree(w.Path) }) action(t.CopyPath, "", icons.Copy, false, func() { a.copyWorktreePath(w.Path) }) lockLabel, lockIcon := t.Lock, icons.Lock if w.IsLocked { diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index 17be21179..ce2309465 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -194,6 +194,11 @@ func (a *App) requestPluginServer(languageID string, providersChanged bool) { if a.plugins == nil || languageID == "" { return } + if a.project != nil && a.project.remote != nil { + // log-exempt: 远程工作区的语言服务器要在主机上运行,现在还不支持;在本机启动只会读到空的占位文件夹, + // 信任远程文件夹后也不在本机运行任何项目代码。 + return + } a.pluginServerMu.Lock() if a.pluginServers == nil { a.pluginServers = make(map[string]*pluginServer) diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go index 48380b8c6..53debbdf6 100644 --- a/desktop/internal/workbench/remote_browse.go +++ b/desktop/internal/workbench/remote_browse.go @@ -393,9 +393,10 @@ func (a *App) openRemoteFolder() { a.openRemoteFolderAt(b.target()) } -// openRemoteFolderNow opens dir once its trust is decided (remote_trust.go). It also marks the -// connection as connected now, for the list's "2 hours ago". -func (a *App) openRemoteFolderNow(dir string) { +// openRemoteFolderNow opens dir once its trust is decided (remote_trust.go), trusted when trusted +// is set and in safe mode otherwise. It also marks the connection as connected now, for the +// list's "2 hours ago". +func (a *App) openRemoteFolderNow(dir string, trusted bool) { r := &a.remote b := r.browser if !r.open || b == nil { @@ -445,7 +446,7 @@ func (a *App) openRemoteFolderNow(dir string) { } target := remoteTarget{ connectionID: b.entryID, name: b.name, connection: b.connection, session: b.session, - remoteRoot: dir, root: remoteplaceholder.Root(anchor, b.entryID, dir), + remoteRoot: dir, root: remoteplaceholder.Root(anchor, b.entryID, dir), trusted: trusted, } // The session is the workspace's from here on. r.browser = nil @@ -456,8 +457,8 @@ func (a *App) openRemoteFolderNow(dir string) { } // openRemoteWorkspace shows target: the tab that has the folder open over the same connection, -// which takes the session when it has lost its own; this workbench when it has no project; a new -// tab otherwise. +// which takes the session when it has lost its own and the trust the user just decided for the +// folder; this workbench when it has no project; a new tab otherwise. func (a *App) openRemoteWorkspace(target remoteTarget) { if open := a.sessions.showing(target.root); open != nil { a.sessions.activate(open) @@ -466,9 +467,10 @@ func (a *App) openRemoteWorkspace(target remoteTarget) { r.stopRemoteTimer() open.attachRemote(p, target.session.ID) open.refreshRemoteTree(p) - return + } else { + a.releaseRemoteSession(target.session.ID) } - a.releaseRemoteSession(target.session.ID) + open.applyProjectTrust(p, target.trusted) return } if a.project == nil || a.sessions == nil { diff --git a/desktop/internal/workbench/remote_git.go b/desktop/internal/workbench/remote_git.go new file mode 100644 index 000000000..687f71dff --- /dev/null +++ b/desktop/internal/workbench/remote_git.go @@ -0,0 +1,263 @@ +package workbench + +import ( + "context" + "errors" + "io/fs" + "path" + "path/filepath" + "strings" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" +) + +// A trusted remote workspace runs Git on its host: Core runs every git.* request of the project +// there (core.RemoteWorkspace), so the status, the commit, the diffs, the log, the blame, stashes +// and shelves read and change the host's repository, and the paths Core answers name the +// workspace's placeholder (remoteplaceholder). What the window itself reads or writes of the +// repository goes to the host too: the blamed file's text and the info/exclude a file is excluded +// in. In safe mode Git stays off, as in a local project. +// +// The window learns of a change to the repository's metadata, made by a terminal or anything else +// on the host, from the host: next to the watch of the folder (remote_watch.go), the same server +// watches the repository's git directory, and the common directory when it lies elsewhere +// (remote.runWatch, recursive and with no folder left out). The changes it sends go to the same +// classification as a local project's (git_observation.go), which Core makes by path alone. The +// watches run over the session and stop when it is lost or the project closes; a new session, and +// trust, start them again. + +// remoteGitWatch is one host watch of a remote workspace's Git metadata folder +// (gitObservation.remote). +type remoteGitWatch struct { + // dir is the folder's placeholder path, as Core named it; session is the session the watch + // runs over and cancel stops it. + dir string + session string + cancel context.CancelFunc + // limitReported is set once the host's running out of watches was logged; the window + // thread's. + limitReported bool + + // mu guards what the request's goroutine hands the window thread until it drains it. + mu sync.Mutex + // started, lost and limited are the start, a batch the host lost changes of, and the host's + // running out of watches; watching is set once the watch started. paths are the placeholder + // paths changed since the last drain. + started, lost, limited, watching bool + paths []string + woken bool +} + +// record changes the watch's pending state on the request's goroutine and queues one drain. +func (w *remoteGitWatch) record(a *App, p *project, change func(w *remoteGitWatch)) { + w.mu.Lock() + change(w) + wake := !w.woken + w.woken = true + w.mu.Unlock() + if wake { + a.post(func(a *App) { a.drainRemoteGitWatch(p, w) }) + } +} + +// remoteGitDirectories are the folders that hold the metadata of the repository watch names: +// its git directory, and its common directory unless one lies inside the other, since the host +// watches each one whole. +func remoteGitDirectories(watch core.GitWatchContext) []string { + git, common := watch.GitDirectory, watch.GitCommonDirectory + switch { + case common == "" || common == git || within(git, common): + return []string{git} + case within(common, git): + return []string{common} + } + return []string{git, common} +} + +// within reports whether path lies below dir. +func within(dir, path string) bool { + rel, err := filepath.Rel(dir, path) + return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// startRemoteGitWatches starts the host watches of p's metadata folders dirs, placeholder paths, +// over its session. +func (a *App) startRemoteGitWatches(p *project, dirs []string) { + r := p.remote + if r == nil || r.closed || r.session == "" { + return + } + p.observe.remote = make(map[string]*remoteGitWatch, len(dirs)) + for _, dir := range dirs { + host, ok := remoteplaceholder.HostPath(r.binding.LocalRoot(), r.binding.RemoteRoot(), dir) + if !ok { + // log-exempt: 预期的缺失:Core 给出的路径不在这个工作区的映射里,没有可监听的主机文件夹,状态仍在每次 Git 操作后刷新。 + continue + } + a.startRemoteGitWatch(p, dir, host) + } +} + +// startRemoteGitWatch starts the host watch of dir, whose host path is host. +func (a *App) startRemoteGitWatch(p *project, dir, host string) { + r := p.remote + ctx, cancel := context.WithCancel(p.ctx) + w := &remoteGitWatch{dir: dir, session: r.session, cancel: cancel} + p.observe.remote[dir] = w + kernel, localRoot, remoteRoot := a.kernel, r.binding.LocalRoot(), r.binding.RemoteRoot() + events := core.RemoteWatchEvents{ + Started: func() { w.record(a, p, func(w *remoteGitWatch) { w.started = true }) }, + Changed: func(changes []core.RemoteWatchChange, overflow bool) { + w.record(a, p, func(w *remoteGitWatch) { + w.lost = w.lost || overflow || len(w.paths)+len(changes) > gitObserveMaxPaths + if w.lost { + // The status is read again whole, which covers these changes too. + w.paths = nil + return + } + for _, change := range changes { + if local, ok := remoteplaceholder.LocalPath(localRoot, remoteRoot, change.Path); ok { + w.paths = append(w.paths, local) + } + } + }) + }, + LimitReached: func() { w.record(a, p, func(w *remoteGitWatch) { w.limited = true }) }, + } + // The request runs for the watch's whole life, outside the window's background tasks, as the + // folder's watch does; it ends when the watch is cancelled. + go func() { + err := kernel.RemoteRunWatch(ctx, w.session, host, nil, events) + a.post(func(a *App) { a.remoteGitWatchEnded(p, w, err) }) + }() +} + +// stopRemoteGitWatches stops p's host watches of its Git metadata. +func stopRemoteGitWatches(p *project) { + for _, w := range p.observe.remote { + w.cancel() + } + p.observe.remote = nil +} + +// drainRemoteGitWatch hands what w reported since the last drain to the classification. +func (a *App) drainRemoteGitWatch(p *project, w *remoteGitWatch) { + w.mu.Lock() + started, lost, limited, paths := w.started, w.lost, w.limited, w.paths + w.started, w.lost, w.limited, w.paths, w.woken = false, false, false, nil, false + w.watching = w.watching || started + w.mu.Unlock() + if a.project != p || p.observe.remote[w.dir] != w { + // log-exempt: 用户取消:工作区已关闭,或这次监听已停止(会话丢失、失去信任、仓库重新解析),它的变化不再适用。 + return + } + if limited && !w.limitReported { + // The part the host could watch goes on; the status is still read after every Git + // command the window runs. + w.limitReported = true + a.backgroundFailed("git_metadata_watch", errRemoteWatchLimit) + } + if started || lost || limited { + // The watch started after the last status, or missed changes: one rescan covers the gap. + p.observe.full = true + } + for _, path := range paths { + a.addGitPath(p, path) + } + a.scheduleGitObservation(p) +} + +// remoteGitWatchEnded handles the end of w's request with err. +func (a *App) remoteGitWatchEnded(p *project, w *remoteGitWatch, err error) { + if a.project != p || p.observe.remote[w.dir] != w || p.ctx.Err() != nil { + // log-exempt: 用户取消:工作区已关闭,或这次监听已停止(会话丢失、失去信任、仓库重新解析),结束是取消带来的。 + return + } + w.mu.Lock() + // The drain of the start was queued before this end and ran first; a start still pending + // counts too. + started := w.watching || w.started + w.mu.Unlock() + delete(p.observe.remote, w.dir) + var coreErr *core.Error + switch { + case err == nil && started: + // log-exempt: 预期的缺失:主机上的 Git 元数据文件夹在监听中被删除或移走,仓库随即重新解析。 + a.closeGitObservation(p) + a.startGitObservation(p) + case err == nil, errors.As(err, &coreErr) && coreErr.Code == core.CodeWorkspaceNotFound: + // A watch that ended without starting found no folder to watch; resolving the repository + // again at once would only end it again. The status read below tells what is there. + // log-exempt: 预期的缺失:主机上没有这个 Git 元数据文件夹,状态重新读取一次,下一个会话再监听。 + p.observe.full = true + a.scheduleGitObservation(p) + case remoteConnectionClosed(err): + a.loseRemote(p, w.session, err) + default: + // The status is still read after every Git command the window runs, and the next session + // watches again. + a.backgroundFailed("git_metadata_watch", remoteLogError(err)) + p.observe.full = true + a.scheduleGitObservation(p) + } +} + +// remoteRepositoryAbove reports whether status, read for p, names a repository that starts above +// the folder of p, a remote workspace: Core names such a root outside the placeholder, where the +// paths of its changes do not meet the project tree's, so the Git views say why they stay empty +// rather than show them. +func remoteRepositoryAbove(p *project, status core.GitStatus) bool { + if p.remote == nil || status.RepositoryRoot == "" { + return false + } + root := filepath.Clean(gitState{status: status}.repositoryRoot(p.root)) + return root != filepath.Clean(p.root) && !within(p.root, root) +} + +// resumeRemoteGit watches the Git metadata of p again over its new session, which rescans the +// status once it is found (startGitObservation). +func (a *App) resumeRemoteGit(p *project) { + a.closeGitObservation(p) + a.startGitObservation(p) +} + +// remoteInfoExcludeLimit is the largest info/exclude a remote workspace adds a line to; the file +// is read whole to find the line, and one that large is not a list a person keeps. +const remoteInfoExcludeLimit = 1 << 20 + +// appendInfoExclude is appendInfoExclude on the host: commonDir is the placeholder path Core named +// for the repository's common directory, which may lie outside the folder, as a linked worktree's +// does. A file that changed between the read and the write is left as it is and the exclusion +// fails, so a line someone else added is not lost. +func (r *remoteDocuments) appendInfoExclude(ctx context.Context, commonDir, pattern string) error { + host, ok := remoteplaceholder.HostPath(r.binding.LocalRoot(), r.binding.RemoteRoot(), filepath.Join(commonDir, "info", "exclude")) + if !ok { + return &remoteFileError{reason: errRemoteFileFailed, cause: errRemoteOutsideFolder} + } + session := r.binding.SessionID() + if session == "" { + return &remoteFileError{reason: errRemoteDisconnected} + } + existing, version, err := r.readHost(ctx, session, host, remoteInfoExcludeLimit) + expected := &version + switch { + case errors.Is(err, fs.ErrNotExist): + // Git creates info/ from its template, which a repository may have done without. + expected = nil + dirCtx, cancel := context.WithTimeout(ctx, remoteDocumentTimeout) + err = r.kernel.RemoteCreateDirectory(dirCtx, session, path.Dir(host)) + cancel() + if err != nil { + return r.failed(session, err) + } + case err != nil: + return err + } + addition, ok := infoExcludeAddition(existing, pattern) + if !ok { + return nil + } + return r.write(ctx, session, host, append(existing, addition...), expected) +} diff --git a/desktop/internal/workbench/remote_git_test.go b/desktop/internal/workbench/remote_git_test.go new file mode 100644 index 000000000..0d0899256 --- /dev/null +++ b/desktop/internal/workbench/remote_git_test.go @@ -0,0 +1,476 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" +) + +// remoteHostGit stands in for Core's record of the remote workspaces' trust and for the host's +// repository, which Core reaches over the session a request carries. +type remoteHostGit struct { + // trust is each host folder's recorded trust; a folder missing is undecided. decisions are + // the decisions recorded. + trust map[string]string + decisions []core.RemoteWorkspaceTrustDecision + // repository is where the host's repository starts: "" for none, "." at the folder, "above" + // at the account's home folder, above the folder. + repository string + // statuses are the sessions the status reads carried; classified are the paths Core was + // asked to classify, one batch each. + statuses []string + classified [][]string + // blame is the blame Core answers; blamed are the paths blamed. + blame []core.GitBlameLine + blamed []string + // created are the host folders created. + created []string +} + +// remoteTrustStorage is the preference file the trust decisions are kept in. +var remoteTrustStorage = core.RemoteWorkspaceTrustStorage{RelativePath: "toolchains/remote-trust.json", MaximumBytes: 1 << 20} + +func (k *remoteHostKernel) RemoteWorkspaceTrust(_ context.Context, _ *string, session, workspace string) (core.RemoteWorkspaceTrustState, error) { + state := core.RemoteWorkspaceTrustState{Storage: remoteTrustStorage} + if session == "" { + return state, nil + } + k.mu.Lock() + defer k.mu.Unlock() + decided, ok := k.git.trust[workspace] + if !ok { + decided = core.WorkspaceTrustUnset + } + state.ProjectCodeAllowed = decided == core.WorkspaceTrusted + state.WorkspaceTrust = &core.RemoteWorkspaceTrustOf{State: decided, Workspace: workspace} + return state, nil +} + +func (k *remoteHostKernel) EditRemoteWorkspaceTrust(_ context.Context, _ *string, decision core.RemoteWorkspaceTrustDecision) (core.RemoteWorkspaceTrustPublication, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.git.decisions = append(k.git.decisions, decision) + if k.git.trust == nil { + k.git.trust = map[string]string{} + } + k.git.trust[decision.Workspace] = core.WorkspaceDistrusted + if decision.Trusted { + k.git.trust[decision.Workspace] = core.WorkspaceTrusted + } + document := "{}" + return core.RemoteWorkspaceTrustPublication{Changed: true, Document: &document}, nil +} + +// onHost answers a request as Core does: one without the workspace's binding runs on this +// computer (local), one whose workspace has no session fails as a lost connection, and the host +// answers the rest from where its repository starts (host). +func onHost[T any](ctx context.Context, k *remoteHostKernel, command string, local func() (T, error), host func(repository string) (T, error)) (T, error) { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil { + return local() + } + if binding.SessionID() == "" { + var zero T + return zero, &core.Error{Command: command, Code: core.CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + k.mu.Lock() + repository := k.git.repository + k.mu.Unlock() + return host(repository) +} + +// remoteRepositoryTop is the placeholder path of the host repository's top folder. +func remoteRepositoryTop(root, repository string) string { + if repository == "above" { + top, _ := remoteplaceholder.LocalPath(root, remoteTestFolder, remoteTestHome) + return top + } + return root +} + +func (k *remoteHostKernel) GitStatus(ctx context.Context, root string) (core.GitStatus, error) { + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + k.set(func(k *remoteHostKernel) { k.git.statuses = append(k.git.statuses, binding.SessionID()) }) + } + return onHost(ctx, k, "git.status", func() (core.GitStatus, error) { return k.testKernel.GitStatus(ctx, root) }, + func(repository string) (core.GitStatus, error) { + switch repository { + case "": + return core.GitStatus{}, nil + case "above": + return core.GitStatus{RepositoryRoot: remoteRepositoryTop(root, repository), Branch: "main"}, nil + } + return core.GitStatus{RepositoryRoot: ".", Branch: "main"}, nil + }) +} + +func (k *remoteHostKernel) GitWatchContextOf(ctx context.Context, root string) (core.GitWatchContext, bool, error) { + type answer struct { + watch core.GitWatchContext + found bool + } + got, err := onHost(ctx, k, "git.watchContext", func() (answer, error) { + watch, found, err := k.Client.GitWatchContextOf(ctx, root) + return answer{watch, found}, err + }, func(repository string) (answer, error) { + if repository == "" { + return answer{}, nil + } + top := remoteRepositoryTop(root, repository) + git := filepath.Join(top, ".git") + return answer{core.GitWatchContext{RepositoryRoot: top, GitDirectory: git, GitCommonDirectory: git}, true}, nil + }) + return got.watch, got.found, err +} + +func (k *remoteHostKernel) GitClassifyMetadataChanges(ctx context.Context, metadata core.GitMetadataContext, paths []string) ([]core.GitMetadataEvent, error) { + return onHost(ctx, k, "git.classifyMetadataChanges", func() ([]core.GitMetadataEvent, error) { + return k.Client.GitClassifyMetadataChanges(ctx, metadata, paths) + }, func(string) ([]core.GitMetadataEvent, error) { + k.set(func(k *remoteHostKernel) { k.git.classified = append(k.git.classified, slices.Clone(paths)) }) + events := make([]core.GitMetadataEvent, len(paths)) + for i := range events { + events[i] = core.GitMetadataEvent{Kind: "metadata"} + } + return events, nil + }) +} + +func (k *remoteHostKernel) DiscoverWorkspaceRepositories(ctx context.Context, root string) ([]core.WorkspaceRepository, error) { + return onHost(ctx, k, "workspace.repositories", func() ([]core.WorkspaceRepository, error) { + return k.Client.DiscoverWorkspaceRepositories(ctx, root) + }, func(string) ([]core.WorkspaceRepository, error) { return nil, nil }) +} + +func (k *remoteHostKernel) GitRebaseSession(ctx context.Context, root string) (*core.RebaseSession, error) { + return onHost(ctx, k, "git.rebaseSession", func() (*core.RebaseSession, error) { return k.Client.GitRebaseSession(ctx, root) }, + func(string) (*core.RebaseSession, error) { return nil, nil }) +} + +func (k *remoteHostKernel) GitOperationState(ctx context.Context, root string) (core.GitOperation, error) { + return onHost(ctx, k, "git.operationState", func() (core.GitOperation, error) { return k.Client.GitOperationState(ctx, root) }, + func(string) (core.GitOperation, error) { return core.GitOperation{}, nil }) +} + +func (k *remoteHostKernel) GitReferences(ctx context.Context, root string) (core.GitReferences, error) { + return onHost(ctx, k, "git.references", func() (core.GitReferences, error) { return k.Client.GitReferences(ctx, root) }, + func(string) (core.GitReferences, error) { return core.GitReferences{}, nil }) +} + +func (k *remoteHostKernel) GitHistoryPage(ctx context.Context, root, reference, cursor string, limit, maxCommits int) (core.GitHistoryPage, error) { + return onHost(ctx, k, "git.historyPage", func() (core.GitHistoryPage, error) { + return k.Client.GitHistoryPage(ctx, root, reference, cursor, limit, maxCommits) + }, func(string) (core.GitHistoryPage, error) { return core.GitHistoryPage{}, nil }) +} + +func (k *remoteHostKernel) GitGraph(ctx context.Context, request core.GraphRequest) (core.Graph, error) { + return onHost(ctx, k, "git.graph", func() (core.Graph, error) { return k.Client.GitGraph(ctx, request) }, + func(string) (core.Graph, error) { return core.Graph{}, nil }) +} + +func (k *remoteHostKernel) GitDiff(ctx context.Context, request core.GitDiffRequest) ([]core.GitDiffFile, error) { + return onHost(ctx, k, "git.diff", func() ([]core.GitDiffFile, error) { return k.Client.GitDiff(ctx, request) }, + func(string) ([]core.GitDiffFile, error) { return nil, nil }) +} + +func (k *remoteHostKernel) GitBlame(ctx context.Context, root, path string) ([]core.GitBlameLine, error) { + return onHost(ctx, k, "git.blame", func() ([]core.GitBlameLine, error) { return k.Client.GitBlame(ctx, root, path) }, + func(string) ([]core.GitBlameLine, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.git.blamed = append(k.git.blamed, path) + return slices.Clone(k.git.blame), nil + }) +} + +func (k *remoteHostKernel) RemoteCreateDirectory(_ context.Context, session, path string) error { + k.mu.Lock() + defer k.mu.Unlock() + if err := k.takeFileError(session); err != nil { + return err + } + k.git.created = append(k.git.created, path) + if k.kinds == nil { + k.kinds = map[string]core.RemoteFileKind{} + } + k.kinds[path] = core.RemoteFileKindDirectory + return nil +} + +// hostGit is a copy of what the host's repository was asked. +func (k *remoteHostKernel) hostGit() remoteHostGit { + k.mu.Lock() + defer k.mu.Unlock() + g := k.git + g.statuses, g.classified, g.decisions = slices.Clone(g.statuses), slices.Clone(g.classified), slices.Clone(g.decisions) + g.blamed, g.created = slices.Clone(g.blamed), slices.Clone(g.created) + return g +} + +// trustAtHost records the host folder's trust and where its repository starts before it opens. +func (k *remoteHostKernel) trustAtHost(trust, repository string) { + k.set(func(k *remoteHostKernel) { + k.git.trust[remoteTestFolder] = trust + k.git.repository = repository + }) +} + +// watchAt is the watch the host ran last of root. +func (k *remoteHostKernel) watchAt(t *testing.T, root string) *remoteHostWatch { + t.Helper() + k.watches.mu.Lock() + defer k.watches.mu.Unlock() + for i := len(k.watches.runs) - 1; i >= 0; i-- { + if k.watches.runs[i].root == root { + return k.watches.runs[i] + } + } + t.Fatal("the host ran no watch of the folder") + return nil +} + +// sessionKept fails t when the workspace lost its session: a request Core does not answer for a +// remote workspace ends it. +func sessionKept(t *testing.T, logger *treeRecordingLog, p *project, session string) { + t.Helper() + if got := countFailures(logger, "remote_session_lost"); got != 0 || p.remote.session != session { + logger.mu.Lock() + defer logger.mu.Unlock() + for _, event := range logger.events { + if event.Fields["operation"] == "remote_session_lost" { + t.Logf("lost: %v", event.Fields) + } + } + t.Fatalf("the session was lost %d times", got) + } +} + +// awaitRemoteGit waits until the trusted workspace p read its repository's status and watches its +// git directory over its session. +func (h *harness) awaitRemoteGit(p *project) *remoteGitWatch { + h.t.Helper() + dir := filepath.Join(p.root, ".git") + h.await("the host's status and Git watch", func() bool { + w := p.observe.remote[dir] + if w == nil || !p.git.isRepository() { + return false + } + w.mu.Lock() + defer w.mu.Unlock() + return w.watching + }) + h.settle() + return p.observe.remote[dir] +} + +// A folder never decided is asked about before it opens; trusting it records the decision with +// the connection's name and opens it trusted, so its Git runs on the host over the session and +// the notice says Git works there. Neither the host nor its paths are logged. +func TestRemoteWorkspaceAsksToTrustBeforeItOpens(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.set(func(k *remoteHostKernel) { + delete(k.git.trust, remoteTestFolder) + k.git.repository = "." + }) + h.connectAndBrowse(t) + h.clickFront("project") + h.settle() + h.clickFront(i18n.SharedFormat(lang, "desktop.remote.browse.open", map[string]string{"name": "project"})) + h.await("the trust question", func() bool { return h.app.remote.trust != nil }) + h.redraw() + if p := h.app.project; p != nil && p.remote != nil { + t.Fatal("the folder opened before the question was answered") + } + h.clickFront(i18n.Shared(lang, "desktop.remote.trust.trustOpen")) + h.await("the trusted workspace", func() bool { + p := h.app.project + return p != nil && p.remote != nil && p.tree.root != nil && p.tree.root.listed + }) + p := h.app.project + h.awaitRemoteGit(p) + h.redraw() + g := k.hostGit() + want := core.RemoteWorkspaceTrustDecision{SessionID: "session-1", Workspace: remoteTestFolder, Trusted: true, Label: remoteTestHost} + if len(g.decisions) != 1 || g.decisions[0] != want { + t.Fatalf("recorded %d decisions, want the trust of the folder under the connection's name", len(g.decisions)) + } + if p.safeMode() || len(g.statuses) == 0 || slices.ContainsFunc(g.statuses, func(s string) bool { return s != "session-1" }) { + t.Fatalf("safe mode = %v, %d status reads: Git did not run over the session", p.safeMode(), len(g.statuses)) + } + if !h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.banner")) || h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.safeBanner")) { + t.Fatal("the notice does not say the trusted workspace runs Git on the host") + } + if got := remoteActions(logger); !slices.Contains(got, "remote.workspace.trust") { + t.Fatalf("performed %q, want the trust", got) + } + sessionKept(t, logger, p, "session-1") + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A folder kept in safe mode opens with Git off and says so; trusting it from the notice records +// the trust and starts Git on the host: the status, and the watch of the git directory, whose +// changes read the status again. A new session watches it again, and nothing of the repository +// is written to the placeholder. +func TestRemoteWorkspaceTrustStartsGitOnTheHost(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.set(func(k *remoteHostKernel) { k.git.repository = "." }) + p := h.openRemoteTestProject(t) + r := p.remote + if !p.safeMode() || !p.git.safeMode || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.safeBanner")) { + t.Fatal("the folder kept in safe mode did not open in safe mode") + } + if g := k.hostGit(); len(g.statuses) != 0 || k.watchRuns() != 1 { + t.Fatalf("%d status reads, %d watches: Git ran in safe mode", len(g.statuses), k.watchRuns()) + } + + h.app.askToTrustProject(p, nil) + h.redraw() + h.clickFront(i18n.Shared(lang, "desktop.trust.trustProject")) + w := h.awaitRemoteGit(p) + host := k.watchAt(t, remoteTestFolder+"/.git") + if w.session != "session-1" || host.session != "session-1" || len(host.excludes) != 0 { + t.Fatalf("watched the git directory over %q excluding %d folders, want the session and the whole folder", host.session, len(host.excludes)) + } + if g := k.hostGit(); len(g.decisions) != 1 || !g.decisions[0].Trusted || g.decisions[0].Workspace != remoteTestFolder { + t.Fatal("trusting the workspace did not record its trust") + } + + reads := len(k.hostGit().statuses) + host.changed(t, ".git/HEAD") + head := filepath.Join(p.root, ".git", "HEAD") + h.await("the classified change and the status read after it", func() bool { + g := k.hostGit() + return slices.ContainsFunc(g.classified, func(paths []string) bool { return slices.Contains(paths, head) }) && len(g.statuses) > reads + }) + h.settle() + sessionKept(t, logger, p, "session-1") + + k.set(func(k *remoteHostKernel) { + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fire(t, timers) + host.awaitEnd(t) + h.await("the second session", func() bool { return r.session == "session-2" && !r.beating }) + if w := h.awaitRemoteGit(p); w.session != "session-2" || k.watchAt(t, remoteTestFolder+"/.git").session != "session-2" { + t.Fatal("the new session does not watch the git directory") + } + if _, err := os.Lstat(filepath.Join(p.root, ".git")); err == nil { + t.Fatal("the repository's metadata was written to the placeholder") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// Excluding a file adds its pattern to the host repository's info/exclude: the folder Git +// creates from its template is created when missing, and a file that does not end its last line +// gets the line ended first. +func TestRemoteWorkspaceExcludesOnTheHost(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + k.trustAtHost(core.WorkspaceTrusted, ".") + p := h.openRemoteTestProject(t) + h.awaitRemoteGit(p) + exclude := remoteTestFolder + "/.git/info/exclude" + + h.app.excludeLocally(p, core.GitChange{Path: "build/"}) + h.await("the first exclusion", func() bool { text, _ := k.file(exclude); return text == "/build/\n" }) + if got := k.hostGit().created; !slices.Equal(got, []string{remoteTestFolder + "/.git/info"}) { + t.Fatalf("created %q, want the missing info folder", got) + } + k.put(exclude, "# local\n/build/") + h.app.excludeLocally(p, core.GitChange{Path: "out.log"}) + h.await("the second exclusion", func() bool { text, _ := k.file(exclude); return text == "# local\n/build/\n/out.log\n" }) + h.settle() + if got := countFailures(logger, "git_exclude"); got != 0 || len(k.hostGit().created) != 1 { + t.Fatalf("%d exclusions failed: the existing file was not added to", got) + } + sessionKept(t, logger, p, "session-1") +} + +// The blame of a file shows the host's text of it beside Core's annotations. +func TestRemoteWorkspaceBlamesTheHostsFile(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + k.put(remoteTestReadme, "# Project\nText\n") + k.trustAtHost(core.WorkspaceTrusted, ".") + k.set(func(k *remoteHostKernel) { + k.git.blame = []core.GitBlameLine{{Line: 1, Hash: "a1", AuthorName: "Dev", AuthorTime: 1}, {Line: 2, Hash: "a1", AuthorName: "Dev", AuthorTime: 1}} + }) + p := h.openRemoteTestProject(t) + h.awaitRemoteGit(p) + h.app.openBlame(p, "README.md") + h.await("the blame", func() bool { return !p.review.blame.loading }) + b := &p.review.blame + if b.err != "" || len(b.lines) != 2 || !slices.Equal(b.text, []string{"# Project", "Text"}) { + t.Fatalf("blame failed = %v with %d lines and %d of text, want the host's file", b.err != "", len(b.lines), len(b.text)) + } + if got := k.hostGit().blamed; !slices.Equal(got, []string{"README.md"}) { + t.Fatalf("blamed %q, want the file", got) + } + sessionKept(t, logger, p, "session-1") +} + +// A folder inside a repository that starts above it on the host keeps its Git views empty and +// says why, rather than show changes the project tree does not hold. +func TestRemoteWorkspaceSaysItsRepositoryStartsAbove(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.trustAtHost(core.WorkspaceTrusted, "above") + p := h.openRemoteTestProject(t) + h.await("the status", func() bool { return p.git.remoteAbove }) + above := i18n.Shared(lang, "desktop.remote.workspace.gitAbove") + for _, window := range []string{itemCommit, itemGit} { + h.app.openToolWindow(window) + h.redraw() + if !h.showsWrapped(above) { + t.Fatalf("the %s tool window does not say the repository starts above the folder", window) + } + } + if _, ok := p.git.changeCount(); ok || p.git.branch() != "" || countFailures(logger, "git_status") != 0 { + t.Fatal("the repository above the folder was shown or logged as a failure") + } + sessionKept(t, logger, p, "session-1") +} + +// What runs the project's code on this computer refuses in a trusted remote workspace too, and +// says so: Run and Debug, the current file's run, the tests and the build tasks, and their tool +// windows. +func TestRemoteWorkspaceRefusesToRunItsCode(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.trustAtHost(core.WorkspaceTrusted, ".") + p := h.openRemoteTestProject(t) + h.awaitRemoteGit(p) + h.app.titleStart(p, titleActionRun) + h.app.performCurrentFileAction(p, titleActionRun) + h.app.startRun(p, "run", func(*App, *project) { t.Error("a run started") }) + h.app.startTests(p, testSelection{}) + if _, err := h.app.runBuildTask(p, "project", "target", "task", nil); err == nil { + t.Fatal("a build task started") + } + h.settle() + for _, operation := range []string{"title_run", "run_current_file", "run_start", "test_start", "build_task"} { + if !rejected(logger, operation, "remote_workspace") { + t.Fatalf("%s was not logged as refused", operation) + } + } + localOnly := i18n.Shared(lang, "desktop.remote.workspace.localOnly") + if !h.notified(localOnly) || p.trust.asking { + t.Fatal("the refusal was not notified, or the trusted workspace asked to be trusted") + } + h.app.openToolWindow(itemRun) + h.redraw() + if !h.showsWrapped(localOnly) { + t.Fatal("the Run tool window does not say it does not work here") + } + sessionKept(t, logger, p, "session-1") +} diff --git a/desktop/internal/workbench/remote_trust.go b/desktop/internal/workbench/remote_trust.go index 48b2bca97..64ce73d34 100644 --- a/desktop/internal/workbench/remote_trust.go +++ b/desktop/internal/workbench/remote_trust.go @@ -13,11 +13,14 @@ import ( // Before a remote folder opens the first time, the window asks whether to trust it, as the // editor asks of a local folder: trusted, the folder's own code may run (its tasks, its build -// tools' wrappers); in safe mode it is only read. Core keeps the answers, per connection and -// folder, in the preference file remoteconn.ReadTrust names (toolchains/remote-trust.json under -// the toolchain preference root), never on the host or in the app's bundle. A folder already -// trusted or distrusted opens at once. Opening in safe mode records nothing, so the question -// comes back the next time. +// tools' wrappers, Git) and in safe mode it is only read. Both answers are kept: Core records +// them, per connection and folder, in the preference file remoteconn.ReadTrust names +// (toolchains/remote-trust.json under the toolchain preference root), never on the host or in the +// app's bundle, so a folder already trusted or kept in safe mode opens at once the next time. The +// notice above the editor of a workspace in safe mode, and the Git and Commit windows, trust it at +// any time (workspace_trust.go); trusted, its Git runs on the host (remote_git.go). Every way of +// opening a remote folder comes through openRemoteFolderAt, so none of them trusts a folder the +// user was not asked about. // remoteTrustPrompt is the question asked before dir opens over browser's session. type remoteTrustPrompt struct { @@ -50,15 +53,17 @@ func (a *App) openRemoteFolderAt(dir string) { return } b.opening = false - if err != nil { + switch of := trust.State.WorkspaceTrust; { + case err != nil: // The folder opens in safe mode: a remote workspace runs none of its code until // it is trusted, and the question comes back the next time. a.backgroundFailed("remote_trust_read", documentLogError(err)) - } else if of := trust.State.WorkspaceTrust; of != nil && of.State == core.WorkspaceTrustUnset { + a.openRemoteFolderNow(dir, false) + case of != nil && of.State == core.WorkspaceTrustUnset: r.trust = &remoteTrustPrompt{browser: b, dir: dir, trust: trust} - return + default: + a.openRemoteFolderNow(dir, remoteTrusted(trust.State)) } - a.openRemoteFolderNow(dir) } }) } @@ -68,29 +73,43 @@ func (a *App) leaveRemoteTrust() { a.remote.trust = nil } -// decideRemoteTrust opens the folder asked about, trusting it first when trusted is set. +// remoteTrusted reports whether state, Core's reading for one workspace, lets its code run. +func remoteTrusted(state core.RemoteWorkspaceTrustState) bool { + of := state.WorkspaceTrust + return state.ProjectCodeAllowed && of != nil && of.State == core.WorkspaceTrusted +} + +// remoteTrustDecision is the decision that trusts, or keeps in safe mode, the workspace trust +// was read for at dir over session, named label among the trusted locations. location also +// trusts the parent folder Core offered. +func remoteTrustDecision(trust remoteconn.Trust, session, dir, label string, trusted, location bool) core.RemoteWorkspaceTrustDecision { + of := trust.State.WorkspaceTrust + workspace := dir + if of != nil && of.Workspace != "" { + workspace = of.Workspace + } + return core.RemoteWorkspaceTrustDecision{ + SessionID: session, Workspace: workspace, Trusted: trusted, + Location: trusted && location && of != nil && of.OfferedLocation != nil, Label: label, + } +} + +// decideRemoteTrust records the answer to the question and opens the folder: trusted when +// trusted is set, in safe mode otherwise. A trust that cannot be recorded is told in the +// question, which stays; a safe mode that cannot be recorded is told in a notification and the +// folder still opens in safe mode, so the question comes back the next time. func (a *App) decideRemoteTrust(trusted bool) { r := &a.remote t := r.trust if t == nil || t.deciding || r.browser != t.browser { return } - if !trusted { + if trusted { + a.performed("remote.workspace.trust", surfaceButton) + } else { a.performed("remote.workspace.safeMode", surfaceButton) - r.trust = nil - a.openRemoteFolderNow(t.dir) - return - } - a.performed("remote.workspace.trust", surfaceButton) - of := t.trust.State.WorkspaceTrust - workspace := t.dir - if of != nil && of.Workspace != "" { - workspace = of.Workspace - } - decision := core.RemoteWorkspaceTrustDecision{ - SessionID: t.browser.session.ID, Workspace: workspace, Trusted: true, - Location: t.parent && of != nil && of.OfferedLocation != nil, Label: t.browser.name, } + decision := remoteTrustDecision(t.trust, t.browser.session.ID, t.dir, t.browser.name, trusted, t.parent) t.deciding, t.err = true, "" generation, kernel, trust := r.generation, a.kernel, t.trust a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { @@ -104,11 +123,85 @@ func (a *App) decideRemoteTrust(trusted bool) { t.deciding = false if err != nil { a.operationFailed("remote_workspace_trust", documentLogError(err)) - t.err = i18n.SharedFormat(a.language(), "desktop.remote.trust.failed", map[string]string{"reason": documentLogError(err).Error()}) - return + reason := i18n.SharedFormat(a.language(), "desktop.remote.trust.failed", map[string]string{"reason": documentLogError(err).Error()}) + if trusted { + t.err = reason + return + } + a.notifyError(reason) } r.trust = nil - a.openRemoteFolderNow(t.dir) + a.openRemoteFolderNow(t.dir, trusted) + } + }) +} + +// trustRemoteProject records the trust of the open remote workspace p, read again over its +// session so the decision is recorded against Core's record as it is now, and leaves safe mode: +// its Git then runs on the host. A trust that cannot be recorded is told, and p stays in safe +// mode. +func (a *App) trustRemoteProject(p *project, proceed func()) { + r := p.remote + if a.remoteTrustUnreachable(p) { + return + } + a.performed("workspace.trust.grant", surfaceButton) + kernel, globalRoot, session, dir, label := a.kernel, a.globalToolchainRoot(), r.session, r.binding.RemoteRoot(), r.name + a.background(p, workspaceTrustTimeout, func(ctx context.Context) func(*App) { + trust, err := remoteconn.ReadTrust(ctx, kernel, globalRoot, session, dir) + if err == nil { + _, err = trust.Decide(ctx, kernel, remoteTrustDecision(trust, session, dir, label, true, false)) + } + return func(a *App) { + if err != nil { + a.backgroundFailed("remote_workspace_trust", documentLogError(err)) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.trust.saveFailed", map[string]string{"reason": documentLogError(err).Error()})) + return + } + if a.project != p { + // log-exempt: 用户取消:信任已记录,但工作区已关闭,下次打开时直接按已信任打开。 + return + } + a.applyProjectTrust(p, true) + if proceed != nil { + proceed() + } + } + }) +} + +// remoteTrustUnreachable reports whether p is a remote workspace without a session: Core reads +// and records its trust over the session, so trusting it is refused and the notification says +// why. +func (a *App) remoteTrustUnreachable(p *project) bool { + if r := p.remote; r == nil || r.session != "" { + return false + } + language := a.language() + a.operationRejected("project_trust", "remote_disconnected") + a.notifyError(i18n.SharedFormat(language, "desktop.trust.saveFailed", map[string]string{"reason": i18n.Shared(language, "desktop.remote.document.disconnected")})) + return true +} + +// reloadRemoteTrust reads the trust of the open remote workspace p again, after the settings +// window changed it, and applies it. While p has no session, its trust stays as it is. +func (a *App) reloadRemoteTrust(p *project) { + r := p.remote + if r.session == "" { + // log-exempt: 预期的缺失:远程工作区未连接,信任记录要经会话读取;当前信任保持不变。 + return + } + kernel, globalRoot, session, dir := a.kernel, a.globalToolchainRoot(), r.session, r.binding.RemoteRoot() + a.background(p, workspaceTrustTimeout, func(ctx context.Context) func(*App) { + trust, err := remoteconn.ReadTrust(ctx, kernel, globalRoot, session, dir) + return func(a *App) { + if err != nil { + a.backgroundFailed("remote_trust_read", documentLogError(err)) + return + } + if a.project == p { + a.applyProjectTrust(p, remoteTrusted(trust.State)) + } } }) } diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 676e43c7d..368d1141a 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -27,13 +27,14 @@ import ( // keeps (App.Run). // // 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), its terminals run the host's login -// shell on the host (remote_terminal.go), and the host watches the folder, so a change made there -// shows in the tree and the open documents (remote_watch.go). The features that still read the -// project through the local file system (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. +// saves and compares the host's files (remote_documents.go), Find in Files and Search Everywhere +// search them on the host (remote_search.go), its terminals run the host's login shell on the +// host (remote_terminal.go), and the host watches the folder, so a change made there shows in the +// tree and the open documents (remote_watch.go). It opens trusted or in safe mode as the user +// decided for the folder (remote_trust.go); trusted, its Git runs on the host (remote_git.go). The +// features that still read the project through the local file system (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). const ( // remoteHeartbeatInterval is the pause between two heartbeats of a connected workspace. @@ -119,6 +120,9 @@ type remoteTarget struct { // remoteRoot is the host folder, an absolute POSIX path; root is its local placeholder. remoteRoot string root string + // trusted opens the workspace trusted, as the user decided for the folder; it opens in safe + // mode otherwise. + trusted bool } // errRemoteSessionClosed is what the binding's loss reports: a request of the workspace found @@ -150,14 +154,15 @@ func remoteConnectionClosed(err error) bool { return errors.As(err, &coreErr) && coreErr.Code == core.CodeConnectionClosed } -// remoteHostPath is the host path of full, a path below the project's root; the root itself is -// the host folder. A path outside the root, and every path of a local project, is returned as -// it is. +// remoteHostPath is the host path of full, a path of the workspace's placeholder: below the +// project's root, or a host path outside it Core named, such as a worktree's +// (remoteplaceholder.HostPath). Any other path, and every path of a local project, is returned +// as it is. func (p *project) remoteHostPath(full string) string { if p.remote == nil { return full } - if host, ok := remoteHostPathBelow(p.root, p.remote.binding.RemoteRoot(), full); ok { + if host, ok := remoteplaceholder.HostPath(p.root, p.remote.binding.RemoteRoot(), full); ok { return host } return full @@ -270,8 +275,9 @@ func (r *remoteProject) stopRemoteTimer() { r.timer++ } -// attachRemote makes session the workspace's session and starts its heartbeat and the host watch -// of its folder. +// attachRemote makes session the workspace's session and starts its heartbeat, the host watch of +// its folder and, in a trusted workspace, the watch of its Git metadata, which reads the status +// again. func (a *App) attachRemote(p *project, session string) { r := p.remote a.stopRemoteWatch(p) @@ -280,6 +286,7 @@ func (a *App) attachRemote(p *project, session string) { a.beatRemote(p) r.watchWait = remoteWatchReady a.startRemoteWatch(p) + a.resumeRemoteGit(p) } // beatRemote asks the server of the workspace's session what still runs, and schedules the next @@ -334,6 +341,7 @@ func (a *App) loseRemote(p *project, session string, err error) { } a.backgroundFailed("remote_session_lost", remoteLogError(err)) a.stopRemoteWatch(p) + a.closeGitObservation(p) r.session, r.misses = "", 0 r.binding.Detach() r.stopRemoteTimer() @@ -485,9 +493,11 @@ func (a *App) openRemoteProject(target remoteTarget) { 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, 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) + // Trusted, the workspace's Git runs on the host, and its commands are kept in the Git console + // as a local project's are; in safe mode Core runs none (remote_trust.go). + p.trust.codeAllowed.Store(target.trusted) + ctx := core.WithProjectCodeAllowed(core.WithGitConsole(context.Background(), a.gitConsole, target.root), p.trust.allowed) + p.ctx, p.cancel = context.WithCancel(core.WithRemoteWorkspace(ctx, r.binding)) a.searchView.reset() // Its first terminal runs on the host once it is shown, over the session attached below. a.openTerminals(p) @@ -495,7 +505,10 @@ func (a *App) openRemoteProject(target remoteTarget) { a.notice = "" a.logView.reset() a.worktreeView.reset() + // Attaching the session starts the watch of the Git metadata (remote_git.go). a.attachRemote(p, target.session.ID) + a.loadGit(p) + a.loadLog(p) // 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) diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index ae8f07aa2..675b6bffe 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -75,6 +75,8 @@ type remoteHostKernel struct { // search is Core's index of the folder and what the search's requests carried // (remote_search_test.go). search remoteHostSearch + // git is the workspace's trust and the host's repository (remote_git_test.go). + git remoteHostGit } // remoteTestTree is the workspace's tree the Project tool window lists by default. @@ -245,6 +247,8 @@ func countFailures(logger *treeRecordingLog, operation string) int { func remoteWorkspaceHarness(t *testing.T) (*harness, *remoteHostKernel, *remoteTimers, *treeRecordingLog) { t.Helper() k := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + // The folder was kept in safe mode before, so it opens at once and runs none of its code. + k.git.trust = map[string]string{remoteTestFolder: core.WorkspaceDistrusted} h := newHarnessWithLanguages(t, k, []string{"en-US"}) logger := &treeRecordingLog{} h.app.logSink = logger @@ -360,8 +364,8 @@ func TestRemoteWorkspaceOpensTheChosenFolder(t *testing.T) { if got, want := h.app.projectDisplayName(p), "project [SSH: "+remoteTestHost+"]"; got != want { t.Fatalf("title %q, want %q", got, want) } - if !h.shows("README.md") || !h.shows(remoteStatusText(lang, r)) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.banner")) { - t.Fatal("the workspace does not show its tree, its connection and what works in it") + if !h.shows("README.md") || !h.shows(remoteStatusText(lang, r)) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.workspace.safeBanner")) { + t.Fatal("the workspace does not show its tree, its connection and that it is in safe mode") } if got := k.listings; len(got) == 0 || slices.Contains(got, "") { t.Fatalf("listings carried sessions %q, want the workspace's on every one", got) @@ -382,8 +386,8 @@ 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 plugin's terminal, local history, trusting the folder -// and every tool window but the project's, the terminal's, Find's and the notifications'. Copying +// outside the host folder or in a viewer, a plugin's terminal, local history and every tool +// window but the project's, the terminal's, Find's, Git's, Commit's and the notifications'. Copying // a path copies the host's. func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { h, _, _, logger := remoteWorkspaceHarness(t) @@ -398,13 +402,11 @@ func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { 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 }) h.settle() - 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") + if p.selectedDocument(p.terms.bench.FocusedGroup) != nil || len(p.docs.opening) != 0 { + t.Fatal("the workspace opened a file") } - for _, operation := range []string{"open_viewer", "open_file", "local_history", "open_terminal", "project_trust"} { + for _, operation := range []string{"open_viewer", "open_file", "local_history", "open_terminal"} { if !rejected(logger, operation, "remote_workspace") { t.Fatalf("%s was not logged as refused", operation) } @@ -413,10 +415,10 @@ func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { t.Fatal("the refusal was not notified") } - h.app.openToolWindow(itemGit) + h.app.openToolWindow(itemBuild) h.redraw() if !h.showsWrapped(localOnly) { - t.Fatal("the Git tool window does not say it does not work here") + t.Fatal("the Build tool window does not say it does not work here") } var copied []string diff --git a/desktop/internal/workbench/remote_workspace_visual_test.go b/desktop/internal/workbench/remote_workspace_visual_test.go index 0eadc766d..801cae795 100644 --- a/desktop/internal/workbench/remote_workspace_visual_test.go +++ b/desktop/internal/workbench/remote_workspace_visual_test.go @@ -18,9 +18,11 @@ 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, the -// conflict a save over a change made on the host shows, and a terminal running on the host. +// the Remote Development window with a folder chosen, the question whether to trust it, the +// workspace it opened in safe mode with its notice and 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, a terminal running on the host, the host's search, and, once trusted, the Commit +// tool window of a folder inside a repository that starts above it. func TestVisualRemoteWorkspace(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") if out == "" { @@ -88,7 +90,11 @@ func TestVisualRemoteWorkspace(t *testing.T) { } shot("browse") + // A folder never decided is asked about first; opening it in safe mode reads it only. h.clickFront(i18n.SharedFormat(h.app.language(), "desktop.remote.browse.open", map[string]string{"name": "project"})) + h.await("the trust question", func() bool { return h.app.remote.trust != nil }) + shot("trust") + h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.trust.safeOpen")) h.await("the remote workspace's tree", func() bool { p := h.app.project return p != nil && p.remote != nil && !p.remote.beating && p.tree.root != nil && p.tree.root.listed && !p.tree.reading @@ -157,6 +163,18 @@ func TestVisualRemoteWorkspace(t *testing.T) { }) shot("everywhere") h.app.closeEverywhere(p) + + // Trusting the folder starts Git on the host; a repository that starts above the folder + // leaves the Commit tool window empty and says why. + kernel.set(func(k *remoteHostKernel) { k.git.repository = "above" }) + h.app.askToTrustProject(p, nil) + // Asking does not ask for a frame. + h.app.invalidator.Invalidate() + h.settleChain() + h.clickFront(i18n.Shared(h.app.language(), "desktop.trust.trustProject")) + h.await("the host's status", func() bool { return p.git.remoteAbove }) + h.app.openToolWindow(itemCommit) + shot("git-above") }) } } diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 15c39b005..4ba95a5af 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -161,6 +161,17 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { }) } +// remoteToolWindow reports whether the tool window id works in a remote workspace: the project +// listing, search and terminals run on the host, and so do Git's log and commit once the +// workspace is trusted (in safe mode they say so, as in a local project). +func remoteToolWindow(id string) bool { + switch id { + case itemProject, itemNotifications, itemTerminal, itemFind, itemGit, itemCommit: + return true + } + return false +} + // toolBody declares the body of a tool window under its header: the component of the tool, // or the placeholder of a tool that has no contents yet. func (a *App) toolBody(c ui.C, tool item, p *project) { @@ -169,11 +180,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 && tool.id != itemTerminal && tool.id != itemFind { - // A remote workspace lists, searches 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, "") }) + if p.remote != nil && !remoteToolWindow(tool.id) { + // The tool window reads or runs the project on this computer, so it says it does not work + // in a remote workspace yet. + body.Children(func() { a.remoteLocalOnlyPanel(c) }) return } body.Clip().Children(func() { @@ -356,7 +366,8 @@ func (a *App) editorArea(c ui.C) { {a.text.Editor.FindInFiles, "search.files"}, } if p := a.project; p != nil && p.remote != nil { - // The notice that says what works in a remote workspace stands over its empty editor. + // The notice that says what works in a remote workspace, or that it is in safe mode, stands + // over its empty editor. ui.Column(c.Part("remote")).Fill().Children(func() { a.safeModeNotice(c.Part("safeMode"), p) a.emptyEditorHints(c, hints[:]) diff --git a/desktop/internal/workbench/tests.go b/desktop/internal/workbench/tests.go index 40388d5b5..dfd87a2ee 100644 --- a/desktop/internal/workbench/tests.go +++ b/desktop/internal/workbench/tests.go @@ -196,6 +196,9 @@ func (a *App) startTests(p *project, selection testSelection) { if p == nil || p.tests.running { return } + if a.refuseRemote(p, "test_start") { + return + } if p.safeMode() { a.askToTrustProject(p, func() { a.startTests(p, selection) }) return diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index 688a04aed..2838e9a16 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -150,6 +150,10 @@ func (a *App) titleDebug(p *project) { // while the configurations are read, and an answer that settles them while they are asked for // performs it; otherwise Core decides what the press does now. func (a *App) titleStart(p *project, action titleAction) { + // A remote workspace's project runs on its host, which Run and Debug do not reach yet. + if a.refuseRemote(p, "title_run") { + return + } if !p.runConfigs.currentFile { p.runConfigs.pending = action a.loadTitleRunConfigs(p) diff --git a/desktop/internal/workbench/title_run_entrypoints.go b/desktop/internal/workbench/title_run_entrypoints.go index 1789c068b..6292c4e50 100644 --- a/desktop/internal/workbench/title_run_entrypoints.go +++ b/desktop/internal/workbench/title_run_entrypoints.go @@ -39,6 +39,9 @@ type entrypointFound struct { // loaded first, since the configuration names the model's project; a press waits for it as a // press on a configuration does. func (a *App) performCurrentFileAction(p *project, action titleAction) { + if a.refuseRemote(p, "run_current_file") { + return + } if p.safeMode() { a.askToTrustProject(p, func() { a.performCurrentFileAction(p, action) }) return diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index ab826c906..bdf0bcf24 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -32,6 +32,11 @@ import ( // A run, build, test or reload the user asks for first asks to trust the project; the notice // above the editor, the Git and version control windows and the language server status offer // it too. Trusting the project loads and starts what safe mode left out (applyProjectTrust). +// +// A remote workspace is trusted the same way, but its decision is Core's record for the +// connection and the host folder (remote_trust.go, remoteconn.ReadTrust), not the catalog's for +// its placeholder. Trusted, its Git runs on the host (remote_git.go); the features that would run +// the host's project on this computer stay off whatever its trust. // workspaceTrustTimeout bounds reading or saving a trust decision: a Core call and a look at // the workspace folder. @@ -169,7 +174,7 @@ func (a *App) requireProjectTrust(p *project, proceed func()) { // askToTrustProject asks to trust the open project p in safe mode, from the notice above the // editor or before an action that runs project code; then, when set, it runs proceed. func (a *App) askToTrustProject(p *project, proceed func()) { - if p.trust.asking || a.refuseRemote(p, "project_trust") { + if p.trust.asking || a.remoteTrustUnreachable(p) { return } p.trust.asking = true @@ -194,6 +199,10 @@ func (a *App) askToTrustProject(p *project, proceed func()) { // trustOpenProject saves the trust of the open project p, read again so the decision is saved // against the catalog as it is now, and leaves safe mode. func (a *App) trustOpenProject(p *project, proceed func()) { + if p.remote != nil { + a.trustRemoteProject(p, proceed) + return + } kernel, globalRoot, root := a.kernel, a.globalToolchainRoot(), p.root a.background(p, workspaceTrustTimeout, func(ctx context.Context) func(*App) { trust, err := toolchain.ReadWorkspaceTrust(ctx, kernel, globalRoot, root) @@ -219,6 +228,10 @@ func (a *App) trustOpenProject(p *project, proceed func()) { // reloadProjectTrust reads the trust of the open project again, after the settings window // changed it, and applies it. func (a *App) reloadProjectTrust(p *project) { + if p != nil && p.remote != nil { + a.reloadRemoteTrust(p) + return + } if p == nil || a.trustEveryWorkspace { return } @@ -256,6 +269,11 @@ func (a *App) applyProjectTrust(p *project, trusted bool) { } a.loadGit(p) a.startGitObservation(p) + if p.remote != nil { + // A remote workspace's Git runs on its host; its build tools and language servers do not + // run yet, so trusting it starts nothing else. + return + } p.vcs.clearFailures() for index := range p.build.instances { instance := &p.build.instances[index] @@ -276,25 +294,28 @@ func (a *App) skipUntrustedModel(instance *buildInstance) { // safeModePanel declares what a tool window shows in safe mode in place of what it would read by // running project code: message, and the button that asks to trust the project. -// -// A remote workspace stays in safe mode, since the host's project never runs on this computer: -// its panel says the feature does not work there yet and has no button. func (a *App) safeModePanel(c ui.C, p *project, message string) { - remote := p.remote != nil - if remote { - message = i18n.Shared(a.language(), "desktop.remote.workspace.localOnly") - } ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Subtle) - if !remote && ui.Button(c.Key("trust"), i18n.Shared(a.language(), "desktop.trust.bannerLink")).Ghost().Disabled(p.trust.asking).Clicked() { + if ui.Button(c.Key("trust"), i18n.Shared(a.language(), "desktop.trust.bannerLink")).Ghost().Disabled(p.trust.asking).Clicked() { c.After(func() { a.askToTrustProject(p, nil) }) } }) } +// remoteLocalOnlyPanel declares what a tool window that reads or runs the project on this +// computer shows in a remote workspace: that it does not work there yet. Trust does not change +// it, so it has no button. +func (a *App) remoteLocalOnlyPanel(c ui.C) { + ui.Column(c).Fill().Center().PadX(shellContentPad).Children(func() { + ui.Paragraph(c, i18n.Shared(a.language(), "desktop.remote.workspace.localOnly"), 3).FillWidth().TextCenter().Color(a.colors.Subtle) + }) +} + // safeModeNotice declares the notice above the editor of a project in safe mode, with the link -// that asks to trust it, as IDEA's editor notification does. A remote workspace's notice says -// what works in it and has no link: it is not trusted on this computer. +// that asks to trust it, as IDEA's editor notification does. A remote workspace's notice also +// stands over its empty editor: in safe mode it says so, with the link, and trusted it says what +// works in a remote workspace, with none. func (a *App) safeModeNotice(c ui.C, p *project) { background, border, foreground := gfx.RGB24(0xFFF6E9), gfx.RGB24(0xF4CD9A), gfx.RGB24(0x000000) if a.colors.Dark { @@ -305,12 +326,15 @@ func (a *App) safeModeNotice(c ui.C, p *project) { ui.Row(c.Part("top")).FillWidth().Height(1).Shrink(0).Background(border) ui.Row(c).FillWidth().Gap(conflictGap).PadX(conflictPadX).PadY(conflictPadY).Items(ui.Center).Children(func() { ui.Icon(c, icons.BannerWarning).Size(conflictIcon, conflictIcon).Shrink(0).Color(gfx.RGB24(0xFFFFFF)) - text := i18n.Shared(language, "desktop.trust.banner") - if p.remote != nil { - text = i18n.Shared(language, "desktop.remote.workspace.banner") + text, link := i18n.Shared(language, "desktop.trust.banner"), true + switch { + case p.remote != nil && p.safeMode(): + text = i18n.Shared(language, "desktop.remote.workspace.safeBanner") + case p.remote != nil: + text, link = i18n.Shared(language, "desktop.remote.workspace.banner"), false } ui.Paragraph(c, text, conflictMaxRows).FontSize(13).Color(foreground).Grow(1).Shrink(1) - if p.remote == nil && ui.Button(c.Key("trust"), i18n.Shared(language, "desktop.trust.bannerLink")).Link().Disabled(p.trust.asking).Clicked() { + if link && ui.Button(c.Key("trust"), i18n.Shared(language, "desktop.trust.bannerLink")).Link().Disabled(p.trust.asking).Clicked() { c.After(func() { a.askToTrustProject(p, nil) }) } }) diff --git a/desktop/internal/workbench/worktree_window.go b/desktop/internal/workbench/worktree_window.go index 7985124ec..493e3518f 100644 --- a/desktop/internal/workbench/worktree_window.go +++ b/desktop/internal/workbench/worktree_window.go @@ -8,6 +8,11 @@ import ( // started with the folder on its command line, which opens it when the window starts (see // Options.OpenPath). The current window and its project are left as they are. func (a *App) openWorktreeInNewWindow(path string) { + // A remote workspace's checkout is a host folder; a new client would open its placeholder as + // a local folder. + if a.refuseRemote(a.project, "worktree_open_new_window") { + return + } a.performed("git.worktree.openNewWindow", surfaceButton) if err := launchClient(path); err != nil { a.operationFailed("worktree_open_new_window", documentLogError(err)) diff --git a/docs/assets/remote-workspace/README.md b/docs/assets/remote-workspace/README.md index 1a09a47f2..5f10abd9c 100644 --- a/docs/assets/remote-workspace/README.md +++ b/docs/assets/remote-workspace/README.md @@ -3,26 +3,30 @@ 来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳、主机上的 `README.md` 和 `NOTES.md`、终端的输出和搜索索引也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: - 连接后“远程开发”窗口改为主机的文件夹选择:顶部是连接名和 `用户@主机`,路径框可以输入 `~` 或 `/` 开头的路径,无法读取的条目在列表下方说明数量,底部显示将打开的主机路径; -- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑、保存和搜索,终端在主机上运行,Git 和运行暂不可用,空白编辑区提示 Search Everywhere 和 Find in Files,状态栏前端显示 `SSH: 连接名 · 往返时间`; +- “打开”从未决定过的文件夹时先询问是否信任:显示连接名和主机文件夹,说明安全模式只读取文件夹,底部是“返回”“以安全模式打开”“信任并打开”; +- “以安全模式打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明工作区处于安全模式、可以浏览、编辑、保存和搜索主机上的文件,信任文件夹后才能用 Git,右侧是“信任项目…”,空白编辑区提示 Search Everywhere 和 Find in Files,状态栏前端显示 `SSH: 连接名 · 往返时间`; - 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”; - 在项目树打开 `README.md`:编辑器显示主机上的内容,Markdown 预览照常; - 主机上的文件被别人改过后再保存:保存被拒绝,通知说明文件在外部被修改,编辑器上方出现“保留编辑器版本 / 加载磁盘版本”,主机上的内容不被覆盖; - 打开终端工具窗口:终端在主机的文件夹里运行主机的登录 shell,标签页以连接名命名,没有本机 Shell 选择菜单;截图里的命令输出由测试内核返回; - Find in Files 搜索 `host`:结果来自主机上的 `NOTES.md` 和 `README.md`,带行列号和匹配数; -- Search Everywhere 搜索 `notes`:所有页签都可用(不再只有“操作”),列出主机上的文件名 `NOTES.md` 和它里面匹配的一行。 +- Search Everywhere 搜索 `notes`:所有页签都可用(不再只有“操作”),列出主机上的文件名 `NOTES.md` 和它里面匹配的一行; +- 信任文件夹后 Git 在主机上运行;文件夹位于从上级目录开始的仓库内时,提交工具窗口不显示变更,说明要打开仓库的顶层文件夹。 截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 | 场景 | 浅色英文 | 深色中文 | | --- | --- | --- | | 选择主机文件夹 | [浅色英文](remote-workspace-browse-light-en-US.png) | [深色中文](remote-workspace-browse-dark-zh-CN.png) | -| 打开的远程工作区 | [浅色英文](remote-workspace-opened-light-en-US.png) | [深色中文](remote-workspace-opened-dark-zh-CN.png) | +| 是否信任主机文件夹 | [浅色英文](remote-workspace-trust-light-en-US.png) | [深色中文](remote-workspace-trust-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) | | 主机上的终端 | [浅色英文](remote-workspace-terminal-light-en-US.png) | [深色中文](remote-workspace-terminal-dark-zh-CN.png) | | 在主机的文件夹里搜索 | [浅色英文](remote-workspace-search-light-en-US.png) | [深色中文](remote-workspace-search-dark-zh-CN.png) | | Search Everywhere 搜索主机 | [浅色英文](remote-workspace-everywhere-light-en-US.png) | [深色中文](remote-workspace-everywhere-dark-zh-CN.png) | +| 仓库从上级目录开始 | [浅色英文](remote-workspace-git-above-light-en-US.png) | [深色中文](remote-workspace-git-above-dark-zh-CN.png) | 复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/remote-workspace"`,在 `desktop/` 下通过 `../scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualRemoteWorkspace$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png index d02c42256..c0dcecd64 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png and b/docs/assets/remote-workspace/remote-workspace-browse-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png index 7b49d9c2f..b62287304 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-browse-light-en-US.png differ 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 1ddd66d1e..afd392354 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 5fc02c75b..50eb6f2bf 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-everywhere-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-everywhere-dark-zh-CN.png index 0ad38a22e..e3b09ac87 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-everywhere-dark-zh-CN.png and b/docs/assets/remote-workspace/remote-workspace-everywhere-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-everywhere-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-everywhere-light-en-US.png index 336ebb7fd..b2d6f6e7e 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-everywhere-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-everywhere-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 85a20d929..7ad372658 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 c582e2768..7c4e9d37e 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-git-above-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-git-above-dark-zh-CN.png new file mode 100644 index 000000000..d121e9bf4 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-git-above-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-git-above-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-git-above-light-en-US.png new file mode 100644 index 000000000..37b71dcd3 Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-git-above-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 a55e1fa4c..493dc2923 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 f7c1e8a3e..90dd6cc87 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 f3d7a09f2..640395847 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 a5e82764d..7eb38b32e 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-search-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-search-dark-zh-CN.png index 9c365a4fc..f692bf97e 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-search-dark-zh-CN.png and b/docs/assets/remote-workspace/remote-workspace-search-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-search-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-search-light-en-US.png index 8a0e8a339..98d570f34 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-search-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-search-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 index c46440228..73620a00a 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-terminal-dark-zh-CN.png 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 index 85b661b2a..fc22064b0 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-terminal-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-terminal-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-trust-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-trust-dark-zh-CN.png new file mode 100644 index 000000000..eed2444ee Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-trust-dark-zh-CN.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-trust-light-en-US.png b/docs/assets/remote-workspace/remote-workspace-trust-light-en-US.png new file mode 100644 index 000000000..5e76821bd Binary files /dev/null and b/docs/assets/remote-workspace/remote-workspace-trust-light-en-US.png differ diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 80b24568a..5d5b643c6 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -961,7 +961,21 @@ }, { "id": "desktop.remote.workspace.banner", - "description": "Notice above the editor of a remote workspace: what works in it so far", + "description": "Notice above the editor of a trusted remote workspace: what works in it so far", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.workspace.safeBanner", + "description": "Notice above the editor of a remote workspace in safe mode, next to the link that asks to trust the folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.workspace.gitAbove", + "description": "Changes and Git Log text when the remote workspace's folder lies inside a Git repository that starts in a folder above it on the host", "platforms": [ "desktop" ] @@ -2578,8 +2592,10 @@ "desktop.remote.import.sshHelp": "Reads {files}. The effective value is what `ssh -G` resolves each alias to; the import saves the alias, so OpenSSH keeps resolving it.", "desktop.remote.import.reload": "Read Again", "desktop.remote.import.mottyFound": "Found {hosts} host(s), {groups} group(s) · data format {format}", - "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit, save and are searched on the host, and terminals run on the host; 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, save and search the host's files and run terminals on the host.", + "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit, save and are searched on the host, and terminals and Git run on the host; running, debugging and language servers do not work here yet.", + "desktop.remote.workspace.safeBanner": "This remote workspace is in safe mode: you can browse, edit, save and search its files on the host. Trust the folder to use Git.", + "desktop.remote.workspace.gitAbove": "This folder is inside a Git repository that starts in a folder above it on the host. Open the repository's top folder to use Git in a remote workspace.", + "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit, save and search the host's files, run terminals and use Git 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", @@ -2881,8 +2897,10 @@ "desktop.remote.import.sshHelp": "读取 {files}。生效值是 `ssh -G` 对每个别名解析出的结果;导入保存的是别名,之后仍由 OpenSSH 解析。", "desktop.remote.import.reload": "重新读取", "desktop.remote.import.mottyFound": "找到 {hosts} 台主机、{groups} 个分组 · 数据格式 {format}", - "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑、保存和搜索,终端在主机上运行;Git 和运行暂不可用。", - "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端。", + "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑、保存和搜索,终端和 Git 在主机上运行;运行、调试和语言服务器暂不可用。", + "desktop.remote.workspace.safeBanner": "此远程工作区处于安全模式:可以浏览、编辑、保存和搜索主机上的文件。信任此文件夹后即可使用 Git。", + "desktop.remote.workspace.gitAbove": "此文件夹位于主机上更上层文件夹开始的 Git 仓库中。请打开仓库的顶层文件夹,以便在远程工作区中使用 Git。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端和使用 Git。", "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试", "desktop.remote.document.timedOut": "主机没有及时响应", "desktop.remote.document.notFound": "主机上已没有这个文件", diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 7ae4c47e8..d82910366 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": "远程连接、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -31,7 +31,15 @@ "desktop/internal/workbench/remote_search_test.go", "desktop/internal/workbench/search.go", "desktop/internal/workbench/search_everywhere.go", - "desktop/internal/workbench/search_replace.go" + "desktop/internal/workbench/search_replace.go", + "desktop/internal/workbench/remote_trust.go", + "desktop/internal/workbench/remote_git.go", + "desktop/internal/workbench/remote_git_test.go", + "desktop/internal/workbench/workspace_trust.go", + "desktop/internal/workbench/git_observation.go", + "desktop/internal/workbench/git_exclude.go", + "desktop/internal/workbench/gitreview.go", + "desktop/internal/remoteplaceholder/remoteplaceholder_test.go" ] }, "windows": { @@ -54,11 +62,17 @@ "desktop/internal/workbench/remote_search.go", "desktop/internal/workbench/search.go", "desktop/internal/workbench/search_everywhere.go", - "desktop/internal/workbench/search_replace.go" + "desktop/internal/workbench/search_replace.go", + "desktop/internal/workbench/remote_trust.go", + "desktop/internal/workbench/remote_git.go", + "desktop/internal/workbench/workspace_trust.go", + "desktop/internal/workbench/git_observation.go", + "desktop/internal/workbench/git_exclude.go", + "desktop/internal/workbench/gitreview.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区里主机文件可以打开、编辑、保存和搜索,终端在主机上运行,Git 和运行暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史、插件终端、Git 和信任项目都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 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 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。Git 与端口转发见 remote-development-workspace。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库、打开或新建远程工作树尚未支持;端口转发见 remote-development-workspace。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -95,5 +109,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)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。" + "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;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。 远程信任:Core 的 remote.workspaceTrust 按“会话身份 + 主机文件夹”读出记录,remote.editWorkspaceTrust 写入决定(含连接名),桌面端只把 Core 给出的文档存到偏好目录;projectCodeAllowed 且状态为 trusted 才算受信任。受信任后 git.* 请求带远程绑定发送,Core 在主机上运行 Git,返回的路径是占位路径(remoteplaceholder.LocalPath 把主机路径换成占位路径,文件夹外的主机路径映射到占位目录旁的 .lithe-remote-host 下,不会落到本机真实路径)。git 目录的监听与文件夹监听同样跑在请求自己的 goroutine 上,会话丢失或失去信任时取消。" }