diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index 1c9828307..d6f889580 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -387,13 +387,15 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context. return context.WithValue(ctx, remoteWorkspaceKey{}, binding) } -// payloadOnlyCommands are the commands an open document or the Project tool window sends that -// compute only from their payload: Core's handler reads no file, starts no process and names no +// payloadOnlyCommands are the commands an open document, the Project tool window or the search +// sends that compute only from their payload: Core's handler reads no file, starts no process and names no // workspace path, so the answer is the same on any computer. They go without the remote // workspace, which Core would refuse for want of an adapter, and keep working while the host is // disconnected, so the user can still type, decode the bytes the host returned and plan the save // that will then fail. workspace.filterChanges drops the host watch's changes in folders Core -// hides, by name alone. +// 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. // // 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. @@ -411,6 +413,8 @@ var payloadOnlyCommands = map[string]bool{ "text.decode": true, "text.encode": true, "workspace.filterChanges": true, + "workspace.replaceText": true, + "workspace.searchPresentation": true, } // RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index b1a12b3a8..40feda87f 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1820,8 +1820,8 @@ 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 and save on the host, and terminals run on the host; search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", + "desktop.remote.workspace.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.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.", @@ -5406,8 +5406,8 @@ 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.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端。", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}", "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 0c76769ab..80a917285 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -255,6 +255,7 @@ type Kernel interface { ReduceDocument(ctx context.Context, state core.DocumentState, event core.DocumentEvent) (core.DocumentDecision, error) SearchWorkspace(ctx context.Context, request core.WorkspaceSearchRequest) ([]core.WorkspaceSearchMatch, error) SearchWorkspacePage(ctx context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) + CountWorkspaceSearch(ctx context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchCounts, error) InvalidateWorkspaceSearch(ctx context.Context, root string) error FilterWorkspaceChanges(ctx context.Context, paths []string) ([]string, error) UpdateWorkspaceSearch(ctx context.Context, root string, paths []string) error diff --git a/desktop/internal/workbench/navigation_history.go b/desktop/internal/workbench/navigation_history.go index 1826f1699..487c21ce6 100644 --- a/desktop/internal/workbench/navigation_history.go +++ b/desktop/internal/workbench/navigation_history.go @@ -94,7 +94,9 @@ func (a *App) stepNavigation(p *project, forward bool) { return } // A destination that no longer exists keeps the history as it was, so the entry is not lost. - if _, err := os.Stat(destination.Document); err != nil { + // A remote workspace's file is on the host, not at its placeholder path: opening it reads the + // host and tells the user when the file is gone. + if _, err := os.Stat(destination.Document); err != nil && p.remote == nil { a.operationRejected("editor_navigation_history", "destination_unavailable") a.notifyError(i18n.Shared(a.language(), "desktop.navigation.historyUnavailable")) return diff --git a/desktop/internal/workbench/remote_search.go b/desktop/internal/workbench/remote_search.go new file mode 100644 index 000000000..5b498d123 --- /dev/null +++ b/desktop/internal/workbench/remote_search.go @@ -0,0 +1,64 @@ +package workbench + +// This file keeps the search index of a remote workspace current. Find in Files, Search +// Everywhere and Replace All run with the workspace's remote binding, so Core builds the index +// from the host's folder and answers with paths relative to it, which open in the remote editor. +// The local watch cannot observe the host, so the host watch (remote_watch.go) feeds the index in +// its place: the changed paths it reports update the index before the next query, and its start, +// and a batch it lost, build the index again. While it does not watch all of the folder, from a +// lost session until it starts again with the next one, or after the host ran out of watches, +// every query builds the index from the host again. +// +// The host watch leaves out the folders the plugins hide. A search that includes generated files +// reads some of them, so it builds the index again for every query; Search Everywhere's generated +// file names are read again each time the popup opens. Language servers do not run for a remote +// workspace yet, so Search Everywhere's symbols are only those Core finds in the host's files. + +// remoteWatching reports whether p is a remote workspace whose host watch watches all of its +// folder, so the host's changes reach the search index (remoteSearchChanged). +func (p *project) remoteWatching() bool { + r := p.remote + return r != nil && r.watch != nil && r.watch.watching && !r.watch.partial +} + +// remoteWatchMisses reports whether a search of p that includes generated files (generated) +// reads folders its host watch leaves out, whose changes never reach the index. +func (p *project) remoteWatchMisses(generated bool) bool { + return p.remote != nil && generated +} + +// remoteSearchChanged hands what p's host watch saw to Find in Files and Search Everywhere: +// names, changed paths relative to the folder, update the index before the next query, and +// resync, for a watch that started or lost changes, builds it again. The queries shown run again. +func (a *App) remoteSearchChanged(p *project, names []string, resync bool) { + available := p.remoteWatching() + if s := &p.search; s.watch != nil && s.watchReady { + s.watchAvailable = available + if resync { + s.pending, s.fullResync = nil, true + } else { + a.queueSearchChanges(&s.pending, &s.fullResync, names) + } + a.projectSearchOutdated(p) + a.runProjectSearch(p) + } + if s := &p.everywhere; s.watchAttached && s.watchReady && a.everywhereView.open { + s.watchAvailable = available + if resync { + s.pending, s.fullResync = nil, true + } else { + a.queueSearchChanges(&s.pending, &s.fullResync, names) + } + a.everywhereOutdated(p) + a.runEverywhere(p, false) + } +} + +// remoteSearchUnwatched tells p's searches that the host watch stopped, or ran out of watches: +// changes no longer reach the index, so every query builds it again until a watch starts and +// resyncs. The results shown stay; a session lost would fail the query run now, and the next +// session's watch runs it again. +func (a *App) remoteSearchUnwatched(p *project) { + p.search.watchAvailable, p.search.pending, p.search.fullResync = false, nil, true + p.everywhere.watchAvailable, p.everywhere.pending, p.everywhere.fullResync = false, nil, true +} diff --git a/desktop/internal/workbench/remote_search_test.go b/desktop/internal/workbench/remote_search_test.go new file mode 100644 index 000000000..b7332f5dc --- /dev/null +++ b/desktop/internal/workbench/remote_search_test.go @@ -0,0 +1,466 @@ +package workbench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "maps" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// The host files the search tests search besides remoteTestReadme. +const ( + remoteTestNotes = remoteTestFolder + "/NOTES.md" + remoteTestOther = remoteTestFolder + "/OTHER.md" +) + +// remoteHostSearch stands in for Core's search index of the workspace's folder: the files it +// lists, by path relative to the folder, whose text a query reads from the host when it matches, +// as Core's matcher reads the current text. A file the index does not list is not found, so a +// file added on the host shows only once the index is updated or built again. +type remoteHostSearch struct { + // indexed is nil until a query builds the index from the host's files; builds counts how + // often one did. + indexed map[string]bool + builds int + // updates are the paths of each incremental update. + updates [][]string + // sessions are the sessions the search's requests carried, "" for a request that carried no + // remote workspace. + sessions []string +} + +// searchSessionLocked records the session ctx's request carries. A request whose workspace has +// no session fails as Core does; one that carries no workspace is about the empty placeholder, so +// it answers with nothing (ok false). The lock is held. +func (k *remoteHostKernel) searchSessionLocked(ctx context.Context, command string) (bool, error) { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil { + k.search.sessions = append(k.search.sessions, "") + return false, nil + } + session := binding.SessionID() + k.search.sessions = append(k.search.sessions, session) + if session == "" { + return false, &core.Error{Command: command, Code: core.CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + return true, nil +} + +// indexLocked is the index's files in order, built from the host's files when there is none. +// The lock is held. +func (k *remoteHostKernel) indexLocked() []string { + if k.search.indexed == nil { + k.search.indexed = map[string]bool{} + k.search.builds++ + for host := range k.files { + if relative, ok := strings.CutPrefix(host, remoteTestFolder+"/"); ok { + k.search.indexed[relative] = true + } + } + } + return slices.Sorted(maps.Keys(k.search.indexed)) +} + +// matchesLocked are the file names that contain query, when names, and the lines that do, when +// content, of the index's files. The lock is held. +func (k *remoteHostKernel) matchesLocked(query string, names, content bool) []core.WorkspaceSearchMatch { + var matches []core.WorkspaceSearchMatch + for _, relative := range k.indexLocked() { + data, ok := k.files[remoteTestFolder+"/"+relative] + if !ok { + continue + } + if names && strings.Contains(strings.ToLower(path.Base(relative)), strings.ToLower(query)) { + matches = append(matches, core.WorkspaceSearchMatch{Kind: "file", Path: relative, Preview: relative}) + } + if !content { + continue + } + for i, text := range strings.Split(string(data), "\n") { + at := strings.Index(text, query) + if at < 0 { + continue + } + line, source := i+1, text + ranges := []core.SearchNameRange{{Start: utf16Length(text[:at]), Length: utf16Length(query)}} + matches = append(matches, core.WorkspaceSearchMatch{ + Kind: "content", Path: relative, Line: &line, Preview: text, + SourceLine: &source, ContentMatchRanges: ranges, PreviewRanges: ranges, + }) + } + } + return matches +} + +func (k *remoteHostKernel) InvalidateWorkspaceSearch(ctx context.Context, _ string) error { + k.mu.Lock() + defer k.mu.Unlock() + ok, err := k.searchSessionLocked(ctx, "workspace.searchIndex.invalidate") + if ok { + k.search.indexed = nil + } + return err +} + +func (k *remoteHostKernel) UpdateWorkspaceSearch(ctx context.Context, _ string, paths []string) error { + k.mu.Lock() + defer k.mu.Unlock() + ok, err := k.searchSessionLocked(ctx, "workspace.searchIndex.update") + if !ok { + return err + } + k.search.updates = append(k.search.updates, slices.Clone(paths)) + if k.search.indexed == nil { + return nil + } + for _, relative := range paths { + if _, exists := k.files[remoteTestFolder+"/"+relative]; exists { + k.search.indexed[relative] = true + } else { + delete(k.search.indexed, relative) + } + } + return nil +} + +func (k *remoteHostKernel) SearchWorkspacePage(ctx context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) { + k.mu.Lock() + defer k.mu.Unlock() + if ok, err := k.searchSessionLocked(ctx, "workspace.search"); !ok { + return core.WorkspaceSearchPage{}, err + } + names := request.MaxFileResults == nil || *request.MaxFileResults > 0 + return core.WorkspaceSearchPage{Matches: k.matchesLocked(request.Query, names, true)}, nil +} + +func (k *remoteHostKernel) CountWorkspaceSearch(ctx context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchCounts, error) { + k.mu.Lock() + defer k.mu.Unlock() + counts := core.WorkspaceSearchCounts{FileOccurrences: map[string]int{}} + if ok, err := k.searchSessionLocked(ctx, "workspace.search"); !ok { + return counts, err + } + for _, match := range k.matchesLocked(request.Query, false, true) { + occurrences := strings.Count(*match.SourceLine, request.Query) + if counts.FileOccurrences[match.Path] == 0 { + counts.Files++ + } + counts.Lines++ + counts.Occurrences += occurrences + counts.FileOccurrences[match.Path] += occurrences + } + return counts, nil +} + +func (k *remoteHostKernel) SearchEverywherePage(ctx context.Context, request core.EverywhereSearchRequest) (core.EverywhereSearchPage, error) { + k.mu.Lock() + defer k.mu.Unlock() + if ok, err := k.searchSessionLocked(ctx, "workspace.searchEverywhere"); !ok { + return core.EverywhereSearchPage{}, err + } + names, content := slices.Contains(request.ResultKinds, "file"), slices.Contains(request.ResultKinds, "content") + return core.EverywhereSearchPage{Matches: k.matchesLocked(request.Query, names, content)}, nil +} + +// PreviewWorkspaceReplace plans the replacement of query in the index's files, each with the +// identity of the bytes it read, as Core does. +func (k *remoteHostKernel) PreviewWorkspaceReplace(ctx context.Context, request core.WorkspaceReplaceRequest) ([]core.WorkspaceReplaceFile, error) { + k.mu.Lock() + defer k.mu.Unlock() + if ok, err := k.searchSessionLocked(ctx, "workspace.replacePreview"); !ok { + return nil, err + } + var files []core.WorkspaceReplaceFile + for _, relative := range k.indexLocked() { + data, ok := k.files[remoteTestFolder+"/"+relative] + if !ok || !strings.Contains(string(data), request.Query) { + continue + } + file := core.WorkspaceReplaceFile{Path: relative, ReplacementText: strings.ReplaceAll(string(data), request.Query, request.Replacement)} + for i, text := range strings.Split(string(data), "\n") { + if n := strings.Count(text, request.Query); n > 0 { + file.Matches = append(file.Matches, core.WorkspaceReplaceMatch{Line: i + 1, Before: text, After: strings.ReplaceAll(text, request.Query, request.Replacement), OccurrenceCount: n}) + } + } + identity := sha256.Sum256(data) + file.SourceIdentity = hex.EncodeToString(identity[:]) + files = append(files, file) + } + return files, nil +} + +// searched reads the host's search record. +func (k *remoteHostKernel) searched() remoteHostSearch { + k.mu.Lock() + defer k.mu.Unlock() + s := k.search + s.updates, s.sessions = slices.Clone(s.updates), slices.Clone(s.sessions) + return s +} + +// remove deletes the host file path as someone on the host does. +func (k *remoteHostKernel) remove(path string) { + k.set(func(k *remoteHostKernel) { delete(k.files, path) }) +} + +// overSession reports that every request in sessions went over the workspace's first session. +func overSession(sessions []string) bool { + return len(sessions) > 0 && !slices.ContainsFunc(sessions, func(s string) bool { return s != "session-1" }) +} + +// matchesIn are the paths and lines of matches, as path:line, a file name as path. +func matchesIn(matches []core.WorkspaceSearchMatch) []string { + found := make([]string, 0, len(matches)) + for _, match := range matches { + if match.Line == nil { + found = append(found, match.Path) + } else { + found = append(found, match.Path+":"+strconv.Itoa(*match.Line)) + } + } + return found +} + +// searchAndWait runs query in Find in Files and waits for its results and their counts. +func (h *harness) searchAndWait(p *project, query searchQuery) { + h.t.Helper() + h.app.updateProjectSearch(p, query) + h.awaitSearch(p) +} + +// awaitSearch waits for Find in Files to show the results and the counts of the current query. +func (h *harness) awaitSearch(p *project) { + h.t.Helper() + h.await("the search's results and counts", func() bool { + s := &p.search + return s.failed || (!s.loading && !s.running && s.counts != nil && s.countCancel == nil) + }) + if p.search.failed { + h.t.Fatal("the search failed") + } +} + +// Find in Files of a remote workspace searches the host's folder over the workspace's session, +// and a result opens the host's file at its match in the editor; the Find tool window works there. +// A file added on the host is found after the host watch reported it, which updates the index +// with its path instead of building it again. Neither the host nor its paths are logged. +func TestRemoteWorkspaceFindsInTheHostsFiles(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + h.app.searchView.delay = 0 + k.put(remoteTestReadme, "# Project\nfind the needle\n") + p := h.openRemoteTestProject(t) + h.awaitWatching(p) + + h.searchAndWait(p, searchQuery{text: "needle"}) + if got, want := matchesIn(p.search.matches), []string{"README.md:2"}; !slices.Equal(got, want) { + t.Fatalf("found %q, want %q", got, want) + } + if c := p.search.counts; c.Files != 1 || c.Occurrences != 1 { + t.Fatalf("counted %d files and %d occurrences, want 1 and 1", c.Files, c.Occurrences) + } + built := k.searched().builds + + k.put(remoteTestNotes, "a needle too\n") + k.lastWatch(t).changed(t, "NOTES.md") + h.await("the host's new file in the results", func() bool { + return slices.Contains(matchesIn(p.search.matches), "NOTES.md:1") && !p.search.loading && !p.search.running + }) + h.awaitSearch(p) + s := k.searched() + if s.builds != built || len(s.updates) != 1 || !slices.Equal(s.updates[0], []string{"NOTES.md"}) { + t.Fatalf("the change built the index %d more times and updated it with %q, want one update with its path", s.builds-built, s.updates) + } + if !overSession(s.sessions) { + t.Fatalf("the search went over sessions %q, want the workspace's", s.sessions) + } + + match := p.search.matches[slices.Index(matchesIn(p.search.matches), "NOTES.md:1")] + h.app.openSearchResult(p, match) + notes := filepath.Join(p.root, "NOTES.md") + awaitDocumentState(t, h, func() bool { _, opening := p.docs.opening[notes]; return p.docs.byPath(notes) != nil && !opening }) + d := p.docs.byPath(notes) + if text, _ := d.view.Text(); string(text) != "a needle too\n" { + t.Fatalf("opened %q, want the host's text", text) + } + if line, column := d.view.Caret(); line != 0 || column != 2 { + t.Fatalf("opened at %d:%d, want at the match, 0:2", line, column) + } + if _, err := os.Lstat(notes); err == nil { + t.Fatal("the result was read from the placeholder") + } + + h.app.openToolWindow(itemFind) + h.redraw() + if h.showsWrapped(i18n.Shared(h.app.language(), "desktop.remote.workspace.localOnly")) { + t.Fatal("the Find tool window says it does not work in a remote workspace") + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A search that reads folders the host watch leaves out, one that includes generated files, builds +// the index from the host for every query. So does every search once the host ran out of watches, +// whose changes then no longer reach the index; the host watch alone tells the user so, once. +func TestRemoteSearchBuildsTheIndexAgainWhileTheHostWatchMisses(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + lang := h.app.language() + h.app.searchView.delay = 0 + k.put(remoteTestReadme, "needle\n") + p := h.openRemoteTestProject(t) + h.awaitWatching(p) + w := k.lastWatch(t) + + h.searchAndWait(p, searchQuery{text: "needle", includeGenerated: true}) + built := k.searched().builds + k.put(remoteTestNotes, "needle\n") + w.changed(t, "NOTES.md") + h.await("the generated search again", func() bool { return k.searched().builds > built }) + h.awaitSearch(p) + if s := k.searched(); s.builds != built+1 || len(s.updates) != 0 { + t.Fatalf("the change built the index %d more times and updated it %d times, want it built again", s.builds-built, len(s.updates)) + } + + // Without generated files, the index the last query built is current. + built = k.searched().builds + h.searchAndWait(p, searchQuery{text: "needle"}) + if got := k.searched().builds; got != built { + t.Fatalf("the search built the index %d more times, want none", got-built) + } + + w.deliver(t, func(events core.RemoteWatchEvents) { events.LimitReached() }) + h.await("the host out of watches", func() bool { return p.remote.watch.partial }) + if p.search.watchAvailable || !p.search.fullResync { + t.Fatal("Find in Files still trusts the host watch") + } + // Every change from then on builds the index again, not only the first one after the limit. + for _, line := range []string{"OTHER.md:1", "OTHER.md:2"} { + built = k.searched().builds + other, _ := k.file(remoteTestOther) + k.put(remoteTestOther, other+"needle\n") + w.changed(t, "OTHER.md") + h.await("the search after the host ran out of watches", func() bool { + return slices.Contains(matchesIn(p.search.matches), line) && !p.search.loading && !p.search.running + }) + h.awaitSearch(p) + if s := k.searched(); s.builds != built+1 || len(s.updates) != 0 { + t.Fatalf("the change built the index %d more times and updated it %d times, want it built again", s.builds-built, len(s.updates)) + } + } + if h.countNotified(i18n.Shared(lang, "desktop.search.watchUnavailable")) != 0 || h.countNotified(i18n.Shared(lang, "desktop.project.watchUnavailable")) != 1 { + t.Fatal("the missing watches were not told once, by the host watch") + } +} + +// Search Everywhere of a remote workspace searches the host's file names and text over its +// session with every scope, not only actions, and asks no language server; a file added on the +// host shows in the open popup once the host watch reported it. +func TestRemoteSearchEverywhereSearchesTheHost(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + k.put(remoteTestReadme, "# Project\n") + p := h.openRemoteTestProject(t) + h.awaitWatching(p) + + h.app.openEverywhere(p) + h.app.everywhereView.query.SetText("README") + h.app.updateEverywhere(p, "README", 0) + awaitEverywhere := func(what string, want string) { + t.Helper() + h.await(what, func() bool { + s := &p.everywhere + return s.failed || (!s.loading && !s.running && slices.Contains(matchesIn(s.matches), want)) + }) + if p.everywhere.failed { + t.Fatal("Search Everywhere failed") + } + } + awaitEverywhere("the host's file name", "README.md") + if p.everywhere.scope != 0 || p.everywhereActionsOnly() { + t.Fatal("Search Everywhere offers only actions in a remote workspace") + } + + k.put(remoteTestNotes, "see README\n") + k.lastWatch(t).changed(t, "NOTES.md") + awaitEverywhere("the host's new file's text", "NOTES.md:1") + if s := k.searched(); !overSession(s.sessions) { + t.Fatalf("Search Everywhere went over sessions %q, want the workspace's", s.sessions) + } + if p.everywhereSymbols.discoveryStarted || len(p.everywhereSymbols.servers) != 0 { + t.Fatal("Search Everywhere asked a language server about the remote workspace") + } + h.app.closeEverywhere(p) +} + +// Replace All writes the host's closed files over the workspace's session, nothing below the +// placeholder, and only while each still holds the bytes the preview read: a file changed on the +// host since is a conflict and a file removed says so in the user's words. Neither the host nor +// its paths are logged. +func TestRemoteReplaceAllWritesTheHostsFiles(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.put(remoteTestReadme, "needle one\n") + k.put(remoteTestNotes, "needle two\n") + k.put(remoteTestOther, "needle three\n") + p := h.openRemoteTestProject(t) + h.awaitWatching(p) + replaceAll := func(want int) { + t.Helper() + h.app.previewProjectReplace(p, searchQuery{text: "needle"}, "thread") + h.await("the replacement's preview", func() bool { return !p.replace.loading }) + if p.replace.failure != "" || len(p.replace.files) != want { + t.Fatalf("the preview listed %d files, want %d", len(p.replace.files), want) + } + } + apply := func() { + t.Helper() + h.app.applyProjectReplace(p) + h.await("the replacement", func() bool { return !p.replace.applying && !p.replace.open }) + h.settle() + } + + replaceAll(3) + k.remove(remoteTestNotes) + apply() + if got, _ := k.file(remoteTestReadme); got != "thread one\n" { + t.Fatalf("README.md holds %q on the host, want the replacement", got) + } + if got, _ := k.file(remoteTestOther); got != "thread three\n" { + t.Fatalf("OTHER.md holds %q on the host, want the replacement", got) + } + if !h.notified(h.app.text.Search.ReplacePartlyFailed("2", "1", i18n.Shared(lang, "desktop.remote.document.notFound"))) { + t.Fatal("the removed file was not told in the user's words") + } + + k.put(remoteTestReadme, "needle again\n") + replaceAll(1) + k.put(remoteTestReadme, "needle changed on the host\n") + apply() + if got, _ := k.file(remoteTestReadme); got != "needle changed on the host\n" { + t.Fatalf("README.md holds %q on the host: the replacement overwrote a change made there", got) + } + if !h.notified(h.app.text.Search.ReplacePartlyFailed("0", "1", h.app.text.Search.ReplaceConflict)) { + t.Fatal("the change made on the host was not told as a conflict") + } + + for _, name := range []string{"README.md", "NOTES.md", "OTHER.md"} { + if _, err := os.Lstat(filepath.Join(p.root, name)); err == nil { + t.Fatalf("the replacement wrote %s below the placeholder", name) + } + } + if sessions := k.searched().sessions; !overSession(sessions) || !overSession(k.fileSessions) { + t.Fatalf("the replacement went over sessions %q and %q, want the workspace's", sessions, k.fileSessions) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} diff --git a/desktop/internal/workbench/remote_watch.go b/desktop/internal/workbench/remote_watch.go index 4db159e6c..ce86cceac 100644 --- a/desktop/internal/workbench/remote_watch.go +++ b/desktop/internal/workbench/remote_watch.go @@ -82,9 +82,11 @@ type remoteWatch struct { // session is the session the watch runs over; cancel stops it. session string cancel context.CancelFunc - // watching is set once the host watches the folder; lostReported and excessReported once - // this run's lost changes and too many changes were logged. They are the window thread's. + // watching is set once the host watches the folder, and partial once the host ran out of + // watches, so some of its folders go unwatched; lostReported and excessReported once this + // run's lost changes and too many changes were logged. They are the window thread's. watching bool + partial bool lostReported bool excessReported bool @@ -161,6 +163,7 @@ func (a *App) stopRemoteWatch(p *project) { r.watch = nil p.tree.eventEpoch++ p.tree.eventPending = nil + a.remoteSearchUnwatched(p) } // restartRemoteWatch starts p's running host watch again, for a new list of hidden folders. @@ -184,8 +187,10 @@ func (a *App) drainRemoteWatch(p *project, w *remoteWatch) { return } if limited { + w.partial = true a.backgroundFailed("remote_watch", errRemoteWatchLimit) a.remoteWatchUnavailable(p) + a.remoteSearchUnwatched(p) } if overflow && !w.lostReported { w.lostReported = true @@ -219,7 +224,7 @@ func (a *App) remoteWatchUnavailable(p *project) { } // resyncRemoteWorkspace reads again what p shows of its host folder: the tree's open folders, or -// its root when it could not be listed, and every document. +// its root when it could not be listed, every document and the search index. func (a *App) resyncRemoteWorkspace(p *project) { p.tree.eventEpoch++ p.tree.eventPending = nil @@ -227,10 +232,11 @@ func (a *App) resyncRemoteWorkspace(p *project) { a.refreshRemoteTree(p) } a.recheckRemoteDocuments(p) + a.remoteSearchChanged(p, nil, true) } -// applyRemoteChanges hands the tree the changed host paths below p's folder and compares the -// documents they touch with the host. +// applyRemoteChanges hands the search index and the tree the changed host paths below p's folder +// and compares the documents they touch with the host. func (a *App) applyRemoteChanges(p *project, hostPaths []string) { root := p.remote.binding.RemoteRoot() names := make([]string, 0, len(hostPaths)) @@ -242,6 +248,7 @@ func (a *App) applyRemoteChanges(p *project, hostPaths []string) { if len(names) == 0 { return } + a.remoteSearchChanged(p, names, false) a.markRemoteDocuments(p, names) t := &p.tree if t.root == nil { diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 3fe1d64ae..676e43c7d 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -135,6 +135,15 @@ func remoteLogError(err error) error { return documentLogError(err) } +// logError is err as the log keeps it for a request of p: remoteLogError for a remote workspace, +// err itself for a local one. +func (p *project) logError(err error) error { + if p.remote != nil { + return remoteLogError(err) + } + return err +} + // remoteConnectionClosed reports whether err says the session's connection is gone. func remoteConnectionClosed(err error) bool { var coreErr *core.Error diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 52873e7e0..5af189b2b 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -39,8 +39,8 @@ var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ // remoteHostKernel stands in for a host over SSH: it opens numbered sessions, lists // remoteTestFolders, answers heartbeats as the test says, lists the workspace's tree only for a // request that carries the workspace's session, keeps the files of files -// (remote_documents_test.go) and watches the workspace's folder (remote_watch_test.go). -// Everything else is the real Core. +// (remote_documents_test.go), watches the workspace's folder (remote_watch_test.go) and searches +// it (remote_search_test.go). Everything else is the real Core. type remoteHostKernel struct { *testKernel mu sync.Mutex @@ -72,6 +72,9 @@ type remoteHostKernel struct { missing bool // watches are the host's watches of the folder (remote_watch_test.go). watches remoteHostWatches + // search is Core's index of the folder and what the search's requests carried + // (remote_search_test.go). + search remoteHostSearch } // remoteTestTree is the workspace's tree the Project tool window lists by default. @@ -376,8 +379,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 and the notifications'. Copying a path -// copies the host's. +// and every tool window but the project's, the terminal's, Find's and the notifications'. Copying +// a path copies the host's. func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { h, _, _, logger := remoteWorkspaceHarness(t) lang := h.app.language() @@ -412,16 +415,6 @@ func TestRemoteWorkspaceRefusesWhatRunsLocally(t *testing.T) { t.Fatal("the Git tool window does not say it does not work here") } - // Search Everywhere does not search the host's files yet: it offers only actions, as for a - // file opened on its own, and Tab does not switch to another scope. - h.app.openEverywhere(p) - h.app.everywhereView.scope = 0 - h.redraw() - if p.everywhere.scope != everywhereScopeActions { - t.Fatal("Search Everywhere searches the remote workspace's files") - } - h.app.closeEverywhere(p) - var copied []string saved := treeCopyText treeCopyText = func(text string) error { diff --git a/desktop/internal/workbench/remote_workspace_visual_test.go b/desktop/internal/workbench/remote_workspace_visual_test.go index 6725b80a9..a8298d6a1 100644 --- a/desktop/internal/workbench/remote_workspace_visual_test.go +++ b/desktop/internal/workbench/remote_workspace_visual_test.go @@ -136,6 +136,27 @@ func TestVisualRemoteWorkspace(t *testing.T) { t.Fatal(err) } shot("terminal") + + // Find in Files searches the host's folder, and Search Everywhere the host's file names + // and text in every scope, not only actions. + kernel.put(remoteTestNotes, "Release notes kept on the host.\n") + h.app.searchView.delay = 0 + h.app.everywhereView.delay = 0 + h.app.openFindInFiles(p, false) + h.app.searchView.query.SetText("host") + h.await("the host's search results", func() bool { + s := &p.search + return !s.loading && !s.running && len(s.matches) == 2 && s.counts != nil && s.countCancel == nil + }) + shot("search") + h.app.openEverywhere(p) + h.app.everywhereView.query.SetText("notes") + h.await("the host's file name and text", func() bool { + s := &p.everywhere + return !s.loading && !s.running && len(s.matches) == 2 + }) + shot("everywhere") + h.app.closeEverywhere(p) }) } } diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index 597bfe050..b7b89e2de 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -149,7 +149,8 @@ func (a *App) startProjectSearchWatch(p *project) { wake := func() { a.post(func(a *App) { a.drainProjectSearchWatch(p, slot) }) } if p.remote != nil { // A remote workspace's folder is on the host, which the local watch cannot observe: the - // search runs without a watch, as where none is available. + // host watch feeds the index instead (remoteSearchChanged), and while it does not watch + // every query builds the index from the host again. slot.finish(nil, nil) wake() return @@ -173,8 +174,9 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { return } watch, ready, err := slot.state() + available := watch != nil || p.remoteWatching() if ready { - s.watchReady, s.watchAvailable, s.fullResync = true, watch != nil, true + s.watchReady, s.watchAvailable, s.fullResync = true, available, true if err != nil && s.watchAttached { a.operationFailed("workspace_search_watch", err) a.notifyError(i18n.Shared(a.language(), "desktop.search.watchUnavailable")) @@ -199,42 +201,55 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { a.startProjectSearchWatch(p) changed = true } else if len(events.Names) > 0 { - if len(s.pending)+len(events.Names) > searchEventLimit { - a.backgroundFailed("workspace_search_incremental_update", errWatchEventLimit) - s.pending = nil - s.fullResync = true - } else if !s.fullResync { - s.pending = append(s.pending, events.Names...) - } + a.queueSearchChanges(&s.pending, &s.fullResync, events.Names) changed = true } } if p.everywhere.watchAttached { - a.applyEverywhereWatch(p, ready, watch != nil, err, events) + a.applyEverywhereWatch(p, ready, available, err, events) } if p.tree.recursiveWatch { a.applyTreeRecursiveWatch(p, ready, watch != nil, err, events) } if changed { - if s.countCancel != nil { - s.countCancel() - s.countCancel = nil - } - s.counts = nil - s.countFailed = false - s.generation++ - if s.cancel != nil { - s.cancel() - } - if strings.TrimSpace(s.want.text) != "" { - s.loading = true - } + a.projectSearchOutdated(p) } if s.watchReady && !s.running && strings.TrimSpace(s.want.text) != "" { a.runProjectSearch(p) } } +// queueSearchChanges adds names, changed paths relative to the folder, to a search's pending +// changes, which update the index before its next query. More than searchEventLimit of them +// build the index again instead (full), and none are kept while that is due. +func (a *App) queueSearchChanges(pending *[]string, full *bool, names []string) { + if len(*pending)+len(names) > searchEventLimit { + a.backgroundFailed("workspace_search_incremental_update", errWatchEventLimit) + *pending, *full = nil, true + } else if !*full { + *pending = append(*pending, names...) + } +} + +// projectSearchOutdated drops the Find in Files query and counts running after the folder +// changed; the caller runs the query again. +func (a *App) projectSearchOutdated(p *project) { + s := &p.search + if s.countCancel != nil { + s.countCancel() + s.countCancel = nil + } + s.counts = nil + s.countFailed = false + s.generation++ + if s.cancel != nil { + s.cancel() + } + if strings.TrimSpace(s.want.text) != "" { + s.loading = true + } +} + // updateProjectSearch keeps at most one kernel operation running. Each newer // request cancels the old one; a completed stale operation starts its successor. func (a *App) updateProjectSearch(p *project, query searchQuery) { @@ -266,7 +281,9 @@ func (a *App) updateProjectSearch(p *project, query searchQuery) { s.loading = true wasAttached := s.watchAttached s.watchAttached = true - if !wasAttached && s.watchReady && !s.watchAvailable && s.watch != nil { + // A remote workspace's search waits for no local watch; the host watch tells the user once + // when it cannot watch the folder (remoteWatchUnavailable). + if !wasAttached && s.watchReady && !s.watchAvailable && s.watch != nil && p.remote == nil { _, _, err := s.watch.state() if err != nil { a.operationFailed("workspace_search_watch", err) @@ -294,7 +311,7 @@ func (a *App) runProjectSearch(p *project) { return } query, generation := s.want, s.generation - full, paths := s.fullResync || !s.watchAvailable, s.pending + full, paths := s.fullResync || !s.watchAvailable || p.remoteWatchMisses(query.includeGenerated), s.pending s.fullResync, s.pending = false, nil s.indexUsed = true ctx, cancel := context.WithCancel(p.ctx) @@ -426,12 +443,13 @@ func (a *App) countProjectSearch(p *project, request core.WorkspaceSearchRequest seen[match.Path] = true } } + kernel := a.kernel a.background(p, searchTimeout, func(deadline context.Context) func(*App) { defer close(finished) defer cancel() stop := context.AfterFunc(deadline, cancel) defer stop() - counts, err := core.NewClient().CountWorkspaceSearch(ctx, request) + counts, err := kernel.CountWorkspaceSearch(ctx, request) return func(a *App) { if generation != p.search.generation || countRevision != p.search.countRevision { return @@ -440,7 +458,7 @@ func (a *App) countProjectSearch(p *project, request core.WorkspaceSearchRequest if err != nil { p.search.countFailed = true if !errors.Is(err, context.Canceled) { - a.backgroundFailed("workspace_search_count", err) + a.backgroundFailed("workspace_search_count", p.logError(err)) } return } @@ -480,6 +498,9 @@ func synchronizeSearchIndex(ctx context.Context, kernel Kernel, root string, ful // releaseProjectSearch drops Core's index after the project closes so switching // among projects does not retain every workspace inventory for the whole session. +// A remote workspace's session has ended by then, so this drops only the index of +// its empty placeholder; the indexes Core keyed by the session stay until Core +// drops them when a session closes (#2277). func (a *App) releaseProjectSearch(p *project) { if p.search.countCancel != nil { p.search.countCancel() @@ -524,7 +545,7 @@ func (a *App) finishProjectSearch(p *project, generation uint64, matches []core. } if generation != s.generation { if err != nil && !errors.Is(err, context.Canceled) { - a.backgroundFailed("workspace_search", err) + a.backgroundFailed("workspace_search", p.logError(err)) } if s.watchReady && strings.TrimSpace(s.want.text) != "" { a.runProjectSearch(p) @@ -537,7 +558,7 @@ func (a *App) finishProjectSearch(p *project, generation uint64, matches []core. return } s.failed = true - a.operationFailed("workspace_search", err) + a.operationFailed("workspace_search", p.logError(err)) return } s.matches = matches diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index e4d1e0514..35015e0c8 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -152,10 +152,9 @@ type everywhereSearch struct { } // everywhereActionsOnly reports whether Search Everywhere offers only actions in p: a file -// opened on its own has no folder to search, and a remote workspace does not search the host's -// files yet (its results could not be opened either). +// opened on its own has no folder to search. A remote workspace searches the host's folder. func (p *project) everywhereActionsOnly() bool { - return p.standalone || p.remote != nil + return p.standalone } func (a *App) openEverywhere(p *project) { @@ -269,7 +268,8 @@ func (a *App) startEverywhereWatch(p *project) { a.startProjectSearchWatch(p) } else if p.search.watchReady { s.watchReady, s.watchAvailable, s.fullResync = true, p.search.watchAvailable, true - if !s.watchAvailable { + // The host watch of a remote workspace tells the user itself (remoteWatchUnavailable). + if !s.watchAvailable && p.remote == nil { _, _, err := p.search.watch.state() if err != nil { a.operationFailed("workspace_search_everywhere_watch", err) @@ -299,32 +299,34 @@ func (a *App) applyEverywhereWatch(p *project, ready, available bool, err error, s.pending = nil changed = true } else if len(events.Names) > 0 { - if len(s.pending)+len(events.Names) > searchEventLimit { - a.backgroundFailed("workspace_search_incremental_update", errWatchEventLimit) - s.pending, s.fullResync = nil, true - } else if !s.fullResync { - s.pending = append(s.pending, events.Names...) - } + a.queueSearchChanges(&s.pending, &s.fullResync, events.Names) changed = true } if changed { - if !p.everywhereSymbols.discovering { - p.everywhereSymbols.discoveryStarted = false - a.discoverEverywhereLanguages(p) - } - s.generation++ - if s.cancel != nil { - s.cancel() - } - if strings.TrimSpace(s.query) != "" { - s.loading = true - } + a.everywhereOutdated(p) } if s.watchReady && !s.running && strings.TrimSpace(s.query) != "" { a.runEverywhere(p, false) } } +// everywhereOutdated drops the Search Everywhere query running after the folder changed, and +// looks for the folder's languages again; the caller runs the query again. +func (a *App) everywhereOutdated(p *project) { + s := &p.everywhere + if !p.everywhereSymbols.discovering { + p.everywhereSymbols.discoveryStarted = false + a.discoverEverywhereLanguages(p) + } + s.generation++ + if s.cancel != nil { + s.cancel() + } + if strings.TrimSpace(s.query) != "" { + s.loading = true + } +} + func (a *App) runEverywhere(p *project, next bool) { s := &p.everywhere if s.running || !s.watchReady || !a.everywhereView.open || strings.TrimSpace(s.query) == "" { @@ -340,7 +342,7 @@ func (a *App) runEverywhere(p *project, next bool) { } full, paths := false, []string(nil) if !next { - full, paths = s.fullResync || !s.watchAvailable, s.pending + full, paths = s.fullResync || !s.watchAvailable || p.remoteWatchMisses(request.IncludeGenerated), s.pending s.fullResync, s.pending = false, nil } p.search.indexUsed = true @@ -399,7 +401,7 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co } if generation != s.generation { if err != nil && !errors.Is(err, context.Canceled) { - a.backgroundFailed("workspace_search_everywhere", err) + a.backgroundFailed("workspace_search_everywhere", p.logError(err)) } if s.watchReady && a.everywhereView.open && strings.TrimSpace(s.query) != "" { a.runEverywhere(p, false) @@ -413,7 +415,7 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co if err != nil { if !errors.Is(err, context.Canceled) { s.failed = true - a.operationFailed("workspace_search_everywhere", err) + a.operationFailed("workspace_search_everywhere", p.logError(err)) } return } diff --git a/desktop/internal/workbench/search_everywhere_lsp.go b/desktop/internal/workbench/search_everywhere_lsp.go index 04bbcee8e..221311802 100644 --- a/desktop/internal/workbench/search_everywhere_lsp.go +++ b/desktop/internal/workbench/search_everywhere_lsp.go @@ -73,7 +73,9 @@ func (a *App) startEverywhereSymbols(p *project, query string, scope int) { st.generation++ st.query = query st.items, st.itemKeys, st.ranked, st.servers = nil, nil, nil, nil - if strings.TrimSpace(query) == "" || !everywhereShowsSymbols(scope) || a.plugins == nil { + // Language servers do not run for a remote workspace yet; its symbols are the ones Core + // finds in the host's files. + if strings.TrimSpace(query) == "" || !everywhereShowsSymbols(scope) || a.plugins == nil || p.remote != nil { return } a.discoverEverywhereLanguages(p) @@ -160,7 +162,7 @@ func (a *App) requestEverywhereSymbols(p *project) { // Discover providers once when symbol search is requested, before any file is opened. func (a *App) discoverEverywhereLanguages(p *project) { - if p.everywhereSymbols.discoveryStarted || a.plugins == nil { + if p.everywhereSymbols.discoveryStarted || a.plugins == nil || p.remote != nil { return } p.everywhereSymbols.discoveryRevision++ diff --git a/desktop/internal/workbench/search_idea_test.go b/desktop/internal/workbench/search_idea_test.go index 32c19268b..44f869d1f 100644 --- a/desktop/internal/workbench/search_idea_test.go +++ b/desktop/internal/workbench/search_idea_test.go @@ -242,6 +242,9 @@ func TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview(t *test ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client := core.NewClient() + guardedWrite := func(_ context.Context, path string, data, expected []byte) error { + return documentio.WriteGuarded(path, data, expected) + } for _, encoding := range []string{"gbk", "utf-16le-bom", "utf-16be-bom", "utf-8-bom", "windows-1252"} { t.Run(encoding, func(t *testing.T) { root := t.TempDir() @@ -264,7 +267,7 @@ func TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview(t *test if err != nil || len(preview) != 1 { t.Fatalf("preview %+v %v", preview, err) } - outcome := replacePreviewInFile(ctx, client, documentio.WriteGuarded, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) + outcome := replacePreviewInFile(ctx, client, localDocumentBytes, guardedWrite, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) if outcome.err != nil || outcome.skipped { t.Fatalf("replace %+v", outcome) } @@ -279,7 +282,7 @@ func TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview(t *test if err = os.WriteFile(path, []byte("external needle"), 0600); err != nil { t.Fatal(err) } - outcome = replacePreviewInFile(ctx, client, documentio.WriteGuarded, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) + outcome = replacePreviewInFile(ctx, client, localDocumentBytes, guardedWrite, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) if !errors.Is(outcome.err, documentio.ErrConflict) { t.Fatalf("stale preview wrote: %+v", outcome) } diff --git a/desktop/internal/workbench/search_replace.go b/desktop/internal/workbench/search_replace.go index 73251dc06..00a620fb0 100644 --- a/desktop/internal/workbench/search_replace.go +++ b/desktop/internal/workbench/search_replace.go @@ -20,7 +20,8 @@ import ( // preview, and the host applies it. An open document is changed in its editor // as one undoable edit and saved by the user; a closed file is read again, // replaced by Core (workspace.replaceText) and written only if it still holds the -// bytes that were read. +// bytes that were read. A remote workspace's closed files are read and written +// on its host the way its documents are (remote_documents.go). // searchReplacer is the part of Core Replace in Files needs. type searchReplacer interface { @@ -79,7 +80,7 @@ func (a *App) previewProjectReplace(p *project, query searchQuery, replacement s } r.loading = false if err != nil { - a.operationFailed("workspace_replace_preview", err) + a.operationFailed("workspace_replace_preview", p.logError(err)) r.failure = a.text.Search.ReplaceFailed(err.Error()) return } @@ -155,14 +156,18 @@ func (a *App) applyProjectReplace(p *project) { } query, replacement, root := r.query, r.replacement, p.root budget := int64(a.searchPreferences.ReplacementMaxFileBytes) - write := func(path string, data, expected []byte) error { + read := a.documentBytesOf(p) + write := func(_ context.Context, path string, data, expected []byte) error { return documentio.WriteGuardedLimit(path, data, expected, budget) } + if remote := a.remoteDocuments(p); remote != nil { + write = remote.save + } r.applying = true a.background(p, searchTimeout, func(ctx context.Context) func(*App) { for _, file := range closed { path := filepath.Join(root, filepath.FromSlash(file.Path)) - outcomes = append(outcomes, replacePreviewInFile(ctx, replacer, write, path, query, replacement, budget, file.SourceIdentity)) + outcomes = append(outcomes, replacePreviewInFile(ctx, replacer, read, write, path, query, replacement, budget, file.SourceIdentity)) } return func(a *App) { p.replace = projectReplace{} @@ -198,10 +203,11 @@ func (a *App) replaceInDocument(d *document, file core.WorkspaceReplaceFile, rev return outcome } -// A closed file is decoded and re-encoded by Core; native writes guard exact disk bytes. -func replacePreviewInFile(ctx context.Context, replacer searchReplacer, write func(string, []byte, []byte) error, path string, query searchQuery, replacement string, limit int64, identity string) replaceOutcome { +// A closed file is read with read, decoded and re-encoded by Core, and written with write, which +// writes only while the file still holds the bytes read. +func replacePreviewInFile(ctx context.Context, replacer searchReplacer, read documentBytes, write func(context.Context, string, []byte, []byte) error, path string, query searchQuery, replacement string, limit int64, identity string) replaceOutcome { outcome := replaceOutcome{path: path} - data, err := documentio.ReadFileLimit(path, limit) + data, err := read(ctx, path, limit) if err != nil { outcome.err = err return outcome @@ -228,7 +234,7 @@ func replacePreviewInFile(ctx context.Context, replacer searchReplacer, write fu outcome.err = err return outcome } - outcome.err = write(path, encoded.Bytes, data) + outcome.err = write(ctx, path, encoded.Bytes, data) outcome.before = []byte(decoded.Text) return outcome } @@ -255,6 +261,8 @@ func (a *App) reportProjectReplace(outcomes []replaceOutcome) { message := reason.Error() if errors.Is(reason, documentio.ErrConflict) { message = t.ReplaceConflict + } else if words, remote := a.remoteDocumentReason(reason); remote { + message = words } a.operationFailed("project_replace", documentLogError(reason)) a.notifyError(t.ReplacePartlyFailed(strconv.Itoa(changed), strconv.Itoa(failed), message)) diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 581a2c6ec..15c39b005 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -169,10 +169,10 @@ func (a *App) toolBody(c ui.C, tool item, p *project) { body.Children(func() { a.toolPlaceholder(c) }) return } - if p.remote != nil && tool.id != itemProject && tool.id != itemNotifications && tool.id != itemTerminal { - // A remote workspace lists the host's files and runs its terminals on the host; every - // other tool window reads or runs the project on this computer, so it says it does not - // work there yet. + 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, "") }) return } @@ -356,12 +356,10 @@ func (a *App) editorArea(c ui.C) { {a.text.Editor.FindInFiles, "search.files"}, } if p := a.project; p != nil && p.remote != nil { - // A remote workspace opens no file yet, so the notice that says what works in it stands - // over the empty editor. Find in Files does not search the host yet, and Search Everywhere - // offers only actions there (project.everywhereActionsOnly). + // The notice that says what works in a remote workspace stands over its empty editor. ui.Column(c.Part("remote")).Fill().Children(func() { a.safeModeNotice(c.Part("safeMode"), p) - a.emptyEditorHints(c, hints[:1]) + a.emptyEditorHints(c, hints[:]) }) return } diff --git a/docs/assets/remote-workspace/README.md b/docs/assets/remote-workspace/README.md index a879319b5..1a09a47f2 100644 --- a/docs/assets/remote-workspace/README.md +++ b/docs/assets/remote-workspace/README.md @@ -1,13 +1,15 @@ # 远程工作区(#2231)无头测试截图 -来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳、主机上的 `README.md` 和终端的输出也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: +来自生产 Viva Page 的无头渲染。主机由测试替换的内核模拟:连接直接成功,主目录 `/home/dev` 下有 `linked`、`project`、`.cache` 三个文件夹和一个无法读取的条目,项目树的目录列表、心跳、主机上的 `README.md` 和 `NOTES.md`、终端的输出和搜索索引也由它返回。测试不启动 OpenSSH,也不上传远端服务。截图覆盖深色与浅色主题、中文与英文界面,用于确认: - 连接后“远程开发”窗口改为主机的文件夹选择:顶部是连接名和 `用户@主机`,路径框可以输入 `~` 或 `/` 开头的路径,无法读取的条目在列表下方说明数量,底部显示将打开的主机路径; -- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑和保存,终端在主机上运行,搜索、Git 和运行暂不可用,空白编辑区只提示 Search Everywhere(只有“操作”页),状态栏前端显示 `SSH: 连接名 · 往返时间`; +- “打开”后远程工作区在新标签页打开:项目树列出主机目录,编辑器上方说明主机上的文件可以打开、编辑、保存和搜索,终端在主机上运行,Git 和运行暂不可用,空白编辑区提示 Search Everywhere 和 Find in Files,状态栏前端显示 `SSH: 连接名 · 往返时间`; - 点状态栏的连接项弹出菜单:主机位置、“断开并关闭”和“远程开发…”; - 在项目树打开 `README.md`:编辑器显示主机上的内容,Markdown 预览照常; - 主机上的文件被别人改过后再保存:保存被拒绝,通知说明文件在外部被修改,编辑器上方出现“保留编辑器版本 / 加载磁盘版本”,主机上的内容不被覆盖; -- 打开终端工具窗口:终端在主机的文件夹里运行主机的登录 shell,标签页以连接名命名,没有本机 Shell 选择菜单;截图里的命令输出由测试内核返回。 +- 打开终端工具窗口:终端在主机的文件夹里运行主机的登录 shell,标签页以连接名命名,没有本机 Shell 选择菜单;截图里的命令输出由测试内核返回; +- Find in Files 搜索 `host`:结果来自主机上的 `NOTES.md` 和 `README.md`,带行列号和匹配数; +- Search Everywhere 搜索 `notes`:所有页签都可用(不再只有“操作”),列出主机上的文件名 `NOTES.md` 和它里面匹配的一行。 截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 @@ -19,6 +21,8 @@ | 打开主机上的文件 | [浅色英文](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) | 复验:从仓库根目录设置绝对路径 `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 99f4185d6..d02c42256 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 2bfc8e4ce..7b49d9c2f 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 7e48bfa7d..1ddd66d1e 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 61f7ddde7..5fc02c75b 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 new file mode 100644 index 000000000..0ad38a22e Binary files /dev/null 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 new file mode 100644 index 000000000..336ebb7fd Binary files /dev/null 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 4d8869b7f..85a20d929 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 cef7661f0..c582e2768 100644 Binary files a/docs/assets/remote-workspace/remote-workspace-file-light-en-US.png and b/docs/assets/remote-workspace/remote-workspace-file-light-en-US.png differ diff --git a/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png b/docs/assets/remote-workspace/remote-workspace-menu-dark-zh-CN.png index ea1f83e5f..a55e1fa4c 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 e45796546..f7c1e8a3e 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 f0a735db7..f3d7a09f2 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 2d3e89527..a5e82764d 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 new file mode 100644 index 000000000..9c365a4fc Binary files /dev/null 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 new file mode 100644 index 000000000..8a0e8a339 Binary files /dev/null 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 8458f14eb..c46440228 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 03d80b5c2..85b661b2a 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/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 50d501af0..223e4d752 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -2235,8 +2235,8 @@ "desktop.remote.import.mottyTooLarge": "Motty's configuration is too large to read.", "desktop.remote.import.mottyUnsupported": "This version of Motty's configuration is not supported.", "desktop.remote.import.failed": "Could not import: {reason}", - "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit and save on the host, and terminals run on the host; search, Git and running do not work here yet.", - "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", + "desktop.remote.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.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", @@ -2496,8 +2496,8 @@ "desktop.remote.import.mottyTooLarge": "Motty 的配置过大,无法读取。", "desktop.remote.import.mottyUnsupported": "不支持这个版本的 Motty 配置。", "desktop.remote.import.failed": "无法导入:{reason}", - "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存,终端在主机上运行;搜索、Git 和运行暂不可用。", - "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件,也可以在主机上运行终端。", + "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑、保存和搜索,终端在主机上运行;Git 和运行暂不可用。", + "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端。", "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 dacba70f6..7ae4c47e8 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -2,7 +2,7 @@ "id": "remote-workspace", "area": "工作区", "group": "远程开发", - "capability": "远程连接、远程路径工作区、主机文件编辑与监听、主机终端", + "capability": "远程连接、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -26,7 +26,12 @@ "desktop/internal/workbench/remote_workspace_test.go", "desktop/internal/workbench/remote_terminal_test.go", "desktop/internal/workbench/remote_watch_test.go", - "desktop/internal/workbench/remote_workspace_visual_test.go" + "desktop/internal/workbench/remote_workspace_visual_test.go", + "desktop/internal/workbench/remote_search.go", + "desktop/internal/workbench/remote_search_test.go", + "desktop/internal/workbench/search.go", + "desktop/internal/workbench/search_everywhere.go", + "desktop/internal/workbench/search_replace.go" ] }, "windows": { @@ -45,11 +50,15 @@ "desktop/internal/workbench/remote_status_view.go", "desktop/internal/workbench/remote_terminal.go", "desktop/internal/core/remote_watch.go", - "desktop/internal/workbench/remote_watch.go" + "desktop/internal/workbench/remote_watch.go", + "desktop/internal/workbench/remote_search.go", + "desktop/internal/workbench/search.go", + "desktop/internal/workbench/search_everywhere.go", + "desktop/internal/workbench/search_replace.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;编辑器上方说明远程工作区里主机文件可以打开、编辑和保存,终端在主机上运行,搜索、Git 和运行暂不可用。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史、插件终端、Git 和信任项目都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、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 和运行暂不可用;空白编辑区提示 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。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -86,5 +95,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 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。" + "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)。" }