From b29977907672533598c03dca500f48ab3077075f Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 18:01:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E8=BF=9C=E7=A8=8B=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8C=BA=E5=9C=A8=E4=B8=BB=E6=9C=BA=E4=B8=8A=E7=9B=91?= =?UTF-8?q?=E5=90=AC=E6=96=87=E4=BB=B6=E5=A4=B9=EF=BC=8C=E4=B8=BB=E6=9C=BA?= =?UTF-8?q?=E4=B8=8A=E7=9A=84=E4=BF=AE=E6=94=B9=E6=9B=B4=E6=96=B0=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E6=A0=91=E5=92=8C=E6=89=93=E5=BC=80=E7=9A=84=E6=96=87?= =?UTF-8?q?=E6=A1=A3=20(#2231)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 经工作区会话调用 Core 的 remote.runWatch 递归监听主机文件夹,跳过插件隐藏的文件夹名;变化交给项目树已有的过滤与重新列出流程,打开的文档与主机比对。监听开始、主机丢失变化、变化超过 4096 个时重新读取树和文档;监听数用尽提示一次;文件夹被删除时重新监听,找不到文件夹时等树重新列出;连接断开时结束会话并重连。workspace.filterChanges 改为不带远程绑定发送。 --- desktop/internal/core/remote_session.go | 13 +- desktop/internal/core/remote_watch.go | 122 +++++ desktop/internal/core/remote_watch_test.go | 92 ++++ desktop/internal/workbench/app.go | 1 + desktop/internal/workbench/documents.go | 5 +- desktop/internal/workbench/filetree.go | 9 + desktop/internal/workbench/filetree_watch.go | 21 +- .../internal/workbench/hidden_directories.go | 20 +- .../workbench/hidden_directories_test.go | 1 + .../internal/workbench/remote_documents.go | 4 +- desktop/internal/workbench/remote_watch.go | 352 +++++++++++++++ .../internal/workbench/remote_watch_test.go | 427 ++++++++++++++++++ .../internal/workbench/remote_workspace.go | 21 +- .../workbench/remote_workspace_test.go | 39 +- .../features/remote-workspace.json | 14 +- 15 files changed, 1100 insertions(+), 41 deletions(-) create mode 100644 desktop/internal/core/remote_watch.go create mode 100644 desktop/internal/core/remote_watch_test.go create mode 100644 desktop/internal/workbench/remote_watch.go create mode 100644 desktop/internal/workbench/remote_watch_test.go diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index f3e973b33e..e17b976eef 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -331,11 +331,13 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context. return context.WithValue(ctx, remoteWorkspaceKey{}, binding) } -// payloadOnlyCommands are the commands an open document sends that compute only from their -// payload: Core's handler reads no file, starts no process and names no workspace path, so the -// answer is the same on any computer. They go without the remote workspace, which Core would -// refuse for want of an adapter, and keep working while the host is disconnected, so the user -// can still type, decode the bytes the host returned and plan the save that will then fail. +// 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 +// 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. // // 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. @@ -352,6 +354,7 @@ var payloadOnlyCommands = map[string]bool{ "markdown.outline": true, "text.decode": true, "text.encode": true, + "workspace.filterChanges": true, } // RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context. diff --git a/desktop/internal/core/remote_watch.go b/desktop/internal/core/remote_watch.go new file mode 100644 index 0000000000..809e268bec --- /dev/null +++ b/desktop/internal/core/remote_watch.go @@ -0,0 +1,122 @@ +package core + +import ( + "bytes" + "context" + "encoding/json" + "errors" +) + +// RemoteWatchChange is one change below a watched host folder. +type RemoteWatchChange struct { + // Path is the absolute host path that changed. + Path string `json:"path"` + // Kind is how it changed: "created", "modified" or "deleted". + Kind string `json:"kind"` +} + +// RemoteWatchEvents receive a host watch's events. They run on the request's goroutine and must +// return at once: they must not wait for a UI thread. +type RemoteWatchEvents struct { + // Started is called once the host watches the folder, before any change. A change made + // before it may not be reported. + Started func() + // Changed receives a batch of changes since the previous one, one per path, sorted by path. + // overflow is true when the host lost changes: the folder must be read again instead of + // trusting changes. Changed owns changes. + Changed func(changes []RemoteWatchChange, overflow bool) + // LimitReached is called when the host ran out of watches: part of the folder is no longer + // watched, and the watch goes on for the rest. + LimitReached func() +} + +// remoteWatchEvent is one remote event of remote.runWatch, whose params are read by its kind. +type remoteWatchEvent struct { + Type string `json:"type"` + Event string `json:"event"` + Params json.RawMessage `json:"params"` +} + +// errRemoteWatchEvent is an event of remote.runWatch the client cannot read. +var errRemoteWatchEvent = errors.New("core: unreadable remote watch event") + +// RemoteRunWatch watches root, an absolute host folder of sessionID, recursively until ctx ends +// or the folder is removed. Folders below root named like one of excludeNames are neither watched +// nor reported; the names are matched exactly against each path component. It blocks the +// calling goroutine for the watch's whole life, so run it off the UI thread. +// +// It returns nil once root was deleted or moved, which ends the watch. Ending ctx stops the +// watch: Core sends watch.stop and returns the context's error. A broken or unknown session fails +// with CodeConnectionClosed. An event the client cannot read stops the watch too and is returned +// as the error, since changes would be missed. +func (c *Client) RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events RemoteWatchEvents) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + var unreadable error + observer := func(raw json.RawMessage) { + if unreadable != nil { + return + } + if err := deliverRemoteWatchEvent(raw, events); err != nil { + // Cancelling stops the watch rather than letting it miss changes unseen. + unreadable = err + cancel() + } + } + type watchParams struct { + Root string `json:"root"` + ExcludeNames []string `json:"excludeNames"` + } + observationErr, err := c.ExecuteWithEvents(ctx, "remote.runWatch", struct { + SessionID string `json:"sessionId"` + Params watchParams `json:"params"` + }{sessionID, watchParams{root, nonNil(excludeNames)}}, nil, observer) + switch { + case unreadable != nil: + return unreadable + case err != nil: + return err + } + return observationErr +} + +// deliverRemoteWatchEvent hands one event of remote.runWatch to events. Events of other kinds are +// not the watch's and are ignored, and so is the root's removal, which the request reports by +// ending. +func deliverRemoteWatchEvent(raw json.RawMessage, events RemoteWatchEvents) error { + if !bytes.Contains(raw, []byte(`"remote"`)) { + return nil + } + var event remoteWatchEvent + if err := json.Unmarshal(raw, &event); err != nil || event.Type != "remote" { + return nil + } + switch event.Event { + case "watch.started": + if events.Started != nil { + events.Started() + } + case "watch.changed": + var changed struct { + Changes []RemoteWatchChange `json:"changes"` + Overflow bool `json:"overflow"` + } + if err := json.Unmarshal(event.Params, &changed); err != nil { + return errRemoteWatchEvent + } + if events.Changed != nil && (len(changed.Changes) > 0 || changed.Overflow) { + events.Changed(changed.Changes, changed.Overflow) + } + case "watch.error": + var failed struct { + Code string `json:"code"` + } + if err := json.Unmarshal(event.Params, &failed); err != nil { + return errRemoteWatchEvent + } + if failed.Code == "LIMIT_REACHED" && events.LimitReached != nil { + events.LimitReached() + } + } + return nil +} diff --git a/desktop/internal/core/remote_watch_test.go b/desktop/internal/core/remote_watch_test.go new file mode 100644 index 0000000000..498669c95e --- /dev/null +++ b/desktop/internal/core/remote_watch_test.go @@ -0,0 +1,92 @@ +package core + +import ( + "encoding/json" + "errors" + "slices" + "strings" + "testing" +) + +// The watch's events reach their callbacks in order: started, a batch of changes, a batch that +// only lost changes, and the host's watch limit. An empty batch, the root's removal (which ends +// the request instead) and events that are not the watch's are not delivered. A batch that cannot +// be read is an error, since its changes would be missed. +func TestRemoteWatchEventsReachTheirCallbacks(t *testing.T) { + var got []string + events := RemoteWatchEvents{ + Started: func() { got = append(got, "started") }, + Changed: func(changes []RemoteWatchChange, overflow bool) { + entry := "changed" + for _, change := range changes { + entry += " " + change.Kind + ":" + change.Path + } + if overflow { + entry += " overflow" + } + got = append(got, entry) + }, + LimitReached: func() { got = append(got, "limit") }, + } + for _, raw := range []string{ + `{"type":"progress","message":"remote"}`, + `{"type":"remote","event":"watch.started","params":{"watchId":3,"pid":null}}`, + `{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[{"path":"/srv/repo/a.go","kind":"modified"},{"path":"/srv/repo/b","kind":"deleted"}],"overflow":false}}`, + `{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[],"overflow":false}}`, + `{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[],"overflow":true}}`, + `{"type":"remote","event":"watch.error","params":{"watchId":3,"code":"LIMIT_REACHED","message":"inotify limit"}}`, + `{"type":"remote","event":"watch.error","params":{"watchId":3,"code":"ROOT_REMOVED","message":"gone"}}`, + `{"type":"remote","event":"terminal.output","params":{"terminalId":1,"data":"aGk="}}`, + } { + if err := deliverRemoteWatchEvent(json.RawMessage(raw), events); err != nil { + t.Fatalf("event %s: %v", raw, err) + } + } + want := []string{"started", "changed modified:/srv/repo/a.go deleted:/srv/repo/b", "changed overflow", "limit"} + if !slices.Equal(got, want) { + t.Fatalf("delivered %q, want %q", got, want) + } + for _, bad := range []string{ + `{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":"not a list"}}`, + `{"type":"remote","event":"watch.error","params":{"watchId":3,"code":7}}`, + } { + if err := deliverRemoteWatchEvent(json.RawMessage(bad), events); !errors.Is(err, errRemoteWatchEvent) { + t.Fatalf("unreadable event %s = %v, want errRemoteWatchEvent", bad, err) + } + } +} + +// With the real kernel, a watch over a session Core does not know fails with connection_closed +// and never reports a start. +func TestRemoteWatchOfAnUnknownSession(t *testing.T) { + client := NewClient() + started := false + err := client.RemoteRunWatch(testContext(t), "no-such-session", "/srv/repo", []string{"target"}, RemoteWatchEvents{ + Started: func() { started = true }, + }) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed || started { + t.Fatalf("runWatch = %v, started %v, want connection_closed", err, started) + } +} + +// The tree filters the host watch's changes in Core without the session: a remote workspace's +// context, connected or not, gets the folders Core hides dropped by name. +func TestRemoteWorkspaceFiltersChangesWithoutTheHost(t *testing.T) { + client := NewClient() + binding := NewRemoteWorkspace("/cache/remote/1/abc/repo", "/srv/repo", nil) + ctx := WithRemoteWorkspace(testContext(t), binding) + for _, attached := range []bool{false, true} { + if attached { + binding.Attach("no-such-session") + } + filtered, err := client.FilterWorkspaceChanges(ctx, []string{".git/index", "src/main.go"}) + if err != nil || strings.Join(filtered, ",") != "src/main.go" { + t.Fatalf("filterChanges (attached %v) = %q, %v, want src/main.go", attached, filtered, err) + } + } + // A command that reads the workspace still goes to the host. + if _, err := client.ListDirectories(ctx, "/cache/remote/1/abc/repo", []string{""}); err == nil { + t.Fatal("listing the remote workspace without its host succeeded") + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index bb22a5f9fd..abdfc208ea 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -222,6 +222,7 @@ type Kernel interface { RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error) RemoteServerState(ctx context.Context, sessionID string) error RemoteRunTerminal(ctx context.Context, sessionID string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error) + RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events core.RemoteWatchEvents) error RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error) RemoteTerminalResize(ctx context.Context, sessionID string, terminalID uint64, columns, rows uint16) error GitCreateTag(ctx context.Context, root, name, revision, message string) error diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 1256ef0446..def6e81038 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -568,8 +568,9 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. a.refreshInlineBlame(p, d) p.docs.group = group if !virtual && p.remote == nil { - // The host's folder is not watched yet; a remote document is checked when it is saved, - // before it closes and after the connection opens again (remote_documents.go). + // A remote document is checked when the host watch reports a change of its file + // (remote_watch.go), when it is saved, before it closes and after the connection opens + // again (remote_documents.go). a.watchDocument(p, d) } a.focusDocument(id) diff --git a/desktop/internal/workbench/filetree.go b/desktop/internal/workbench/filetree.go index 956cadcda8..552a356be9 100644 --- a/desktop/internal/workbench/filetree.go +++ b/desktop/internal/workbench/filetree.go @@ -256,6 +256,9 @@ func (a *App) pumpTreeListings(p *project) { } top := treeTopPath(t) loggedFailure := t.failureReported + // rootRead is set when the root was listed in this batch, and rootListed when it + // could be. + rootRead, rootListed := false, false byPath := make(map[string]core.DirectoryListing, len(listings)) for _, listing := range listings { byPath[listing.Path] = listing @@ -281,6 +284,7 @@ func (a *App) pumpTreeListings(p *project) { } if n == t.root { t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") + rootRead = true } else if !n.listed { n.expanded, t.rowsDirty = false, true } @@ -292,11 +296,13 @@ func (a *App) pumpTreeListings(p *project) { n.listed, n.empty = true, len(n.children) == 0 if n == t.root { t.failed = "" + rootRead, rootListed = true, true } } else { if n == t.root { a.operationFailed("project_tree_list", errors.New("workspace root unavailable")) t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") + rootRead = true } else { // log-exempt: 预期的缺失:Core 的列表里没有这个目录,它已被外部删除或隐藏。 n.expanded, t.rowsDirty = false, true @@ -319,6 +325,9 @@ func (a *App) pumpTreeListings(p *project) { } } } + if rootRead { + a.remoteTreeRootRead(p, rootListed) + } a.pumpTreeListings(p) a.continueTreeActions(p) } diff --git a/desktop/internal/workbench/filetree_watch.go b/desktop/internal/workbench/filetree_watch.go index eb2f9048be..cd36f2ed9f 100644 --- a/desktop/internal/workbench/filetree_watch.go +++ b/desktop/internal/workbench/filetree_watch.go @@ -18,8 +18,8 @@ const treeWatchLimit = 128 func (a *App) watchTreeNode(p *project, n *treeNode) { if p.remote != nil { - // A remote workspace's folder is on the host; the local watch would only fail on its - // placeholder. The tree is read again when the connection comes back. + // A remote workspace's folder is on the host, which watches it whole (remote_watch.go); + // the local watch would only fail on its placeholder. return } if treeUsesRecursiveWatch() { @@ -124,11 +124,17 @@ func (a *App) applyTreeRecursiveWatch(p *project, ready, available bool, err err a.filterTreeEvents(p) } +// treeChangesObserved reports whether a watch feeds the tree's queue of changed paths: the +// recursive native stream of a local project, or the host watch of a remote workspace. +func treeChangesObserved(p *project) bool { + return p.tree.recursiveWatch || p.remote != nil && p.remote.watch != nil +} + // Filter off the window thread and keep a bounded, coalesced queue. Core owns // hidden-path rules, including built-in build and dependency directories. func (a *App) filterTreeEvents(p *project) { t := &p.tree - if t.eventFiltering || !t.recursiveWatch || len(t.eventPending) == 0 { + if t.eventFiltering || !treeChangesObserved(p) || len(t.eventPending) == 0 { return } paths := t.eventPending @@ -141,10 +147,10 @@ func (a *App) filterTreeEvents(p *project) { t.eventFiltering = false if err != nil { a.backgroundFailed("project_tree_filter_changes", err) - if t.recursiveWatch { + if treeChangesObserved(p) { a.resyncTreeListings(p) } - } else if t.recursiveWatch && epoch == t.eventEpoch { + } else if treeChangesObserved(p) && epoch == t.eventEpoch { a.applyFilteredTreeEvents(p, filtered) } a.filterTreeEvents(p) @@ -177,14 +183,15 @@ func (a *App) applyFilteredTreeEvents(p *project, names []string) { // The event paths are native notifications. Look up only nodes already // represented by the tree; Core owns visibility and the actual listing. // Reuse the loaded-node index. Only build a folded lookup if a Windows - // notification actually differs in case from the listing. + // notification actually differs in case from the listing; a remote + // workspace's host compares names by case, whatever this computer does. p.tree.find("") var folded map[string]*treeNode lookup := func(name string) *treeNode { if node := p.tree.byPath[name]; node != nil && node.dir { return node } - if runtime.GOOS != "windows" { + if runtime.GOOS != "windows" || p.remote != nil { return nil } if folded == nil { diff --git a/desktop/internal/workbench/hidden_directories.go b/desktop/internal/workbench/hidden_directories.go index ea5bdfcc4c..e6f3898ac1 100644 --- a/desktop/internal/workbench/hidden_directories.go +++ b/desktop/internal/workbench/hidden_directories.go @@ -75,18 +75,28 @@ func (a *App) configureVisibility(ctx context.Context, entries []pluginmanager.E // applyHiddenDirectories shows what configureVisibility did. When Core took a new list, the // tree of every open tab lists the folders it shows again, keeping what is open and selected, -// and a listing still in flight under the old list is dropped for the new one. The list is -// the same for every tab, so the tabs reloading after one plugin change find it unchanged -// after the first and list nothing again. +// and a listing still in flight under the old list is dropped for the new one. The host watch of +// every remote workspace starts again to leave out the new names as they are written, which the +// host compares by case. The list is the same for every tab, so the tabs reloading after one +// plugin change find it unchanged after the first and list nothing again. func (a *App) applyHiddenDirectories(hidden hiddenDirectories) { if hidden.err != nil { a.backgroundFailed("workspace_visibility", hidden.err) } - if !hidden.answered || !fileicons.SetHiddenDirectoryNames(hidden.names) { + if !hidden.answered { return } + excludes := setRemoteWatchExcludes(hidden.names) + icons := fileicons.SetHiddenDirectoryNames(hidden.names) for _, tab := range a.openTabs() { - if p := tab.project; p != nil && p.tree.root != nil && p.tree.failed == "" { + p := tab.project + if p == nil { + continue + } + if excludes { + tab.restartRemoteWatch(p) + } + if icons && p.tree.root != nil && p.tree.failed == "" { tab.resyncTreeListings(p) } } diff --git a/desktop/internal/workbench/hidden_directories_test.go b/desktop/internal/workbench/hidden_directories_test.go index a69307fc53..9fe43a2bd0 100644 --- a/desktop/internal/workbench/hidden_directories_test.go +++ b/desktop/internal/workbench/hidden_directories_test.go @@ -78,6 +78,7 @@ func clearHiddenFolders(t *testing.T) { t.Errorf("clearing the hidden folders: %v", err) } fileicons.SetHiddenDirectoryNames(nil) + setRemoteWatchExcludes(nil) }) } diff --git a/desktop/internal/workbench/remote_documents.go b/desktop/internal/workbench/remote_documents.go index 2b6ca00f7e..8aa6f99551 100644 --- a/desktop/internal/workbench/remote_documents.go +++ b/desktop/internal/workbench/remote_documents.go @@ -35,8 +35,8 @@ import ( // // Core decodes, encodes, recovers and names the language of a file without reading it: those // are payload-only commands, which the Core client sends without the workspace's binding, so -// they also work while the host is away. Until the host watches the workspace (the next step of -// R0), a change on the host is found when a document is saved, before it closes and after the +// they also work while the host is away. A change on the host is found when the host watch +// reports it (remote_watch.go), when a document is saved, before it closes and after the // connection opens again. A host file opens up to remoteDocumentReadLimit, Core's limit, and // saves up to remoteDocumentWriteLimit, the most the host takes in one request. Unsaved edits are // drafts on this computer under the placeholder path, which is the same each time the folder diff --git a/desktop/internal/workbench/remote_watch.go b/desktop/internal/workbench/remote_watch.go new file mode 100644 index 0000000000..4db159e6cf --- /dev/null +++ b/desktop/internal/workbench/remote_watch.go @@ -0,0 +1,352 @@ +package workbench + +import ( + "context" + "errors" + "path" + "slices" + "strings" + "sync" + "sync/atomic" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// This file watches a remote workspace's folder on its host (remote.runWatch). The host watches +// the whole folder for as long as the session lasts, leaving out the folders the enabled plugins +// hide, and reports each batch of changes by host path. The Project tool window takes the +// changes as a local project's recursive watch hands them over: Core drops the hidden paths +// (workspace.filterChanges, which needs no session) and the folders holding the rest are listed +// again. An open document whose file, or a folder above it, changed is compared with the host's +// file, so a change made on the host reloads it or shows the conflict. +// +// The watch starts with each session and stops when the session is lost or the workspace closes. +// When it starts, and when the host lost changes or sent more than the window applies one by one, +// the tree lists its open folders again and every document is compared with the host. When the +// host runs out of watches, the part it could watch goes on and the user is told once that files +// may not update. The request runs on its own goroutine for the watch's whole life, outside the +// window's background tasks, which waits for none of them; it ends when the watch is cancelled. +// +// A folder removed while watched ends the watch, which starts again at once and finds the folder +// back or missing. A watch that finds its folder missing waits for the tree to list it again; when +// the tree had just listed it, it waits for the tree to find it missing too first, so the two never +// take turns over a folder one of them can read. Any other failure is logged by command and code, +// since Core's message may name a host path, and the watch waits for the next session. + +// remoteWatchExcludes are the folder names the enabled plugins hide, as Core last answered them +// (hidden_directories.go). Core keeps one list for the process, so every workspace's host watch +// leaves out the same names. +var remoteWatchExcludes atomic.Pointer[[]string] + +// setRemoteWatchExcludes keeps names, Core's sorted list, for the host watches started from now +// on, and reports whether it differs from the one kept before. +func setRemoteWatchExcludes(names []string) bool { + names = slices.Clone(names) + var before []string + if previous := remoteWatchExcludes.Swap(&names); previous != nil { + before = *previous + } + return !slices.Equal(before, names) +} + +// remoteWatchExcludeNames is the list setRemoteWatchExcludes kept, nil before Core answered. +func remoteWatchExcludeNames() []string { + if names := remoteWatchExcludes.Load(); names != nil { + return *names + } + return nil +} + +// errRemoteWatchLimit is what the log keeps when the host ran out of watches. +var errRemoteWatchLimit = errors.New("remote workspace watch limit reached on the host") + +// remoteWatchWait is what a remote workspace's host watch waits for while it does not run. +type remoteWatchWait int + +const ( + // remoteWatchReady: nothing; the watch runs, or starts with the session. + remoteWatchReady remoteWatchWait = iota + // remoteWatchRootListed: the watch found the folder missing; it starts once the tree lists + // the folder. + remoteWatchRootListed + // remoteWatchRootMissed: the watch found the folder missing while the tree could list it; it + // waits for the tree to find the folder missing, then for the tree to list it again. + remoteWatchRootMissed + // remoteWatchSession: the watch failed; it starts again with the next session. + remoteWatchSession +) + +// remoteWatch is one run of a remote workspace's host watch (remoteProject.watch). +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 bool + lostReported bool + excessReported bool + + // mu guards what the request's goroutine hands the window thread until it drains it. + mu sync.Mutex + // started, overflow and limited are the start, a batch the host lost changes of, and the + // host's running out of watches. excess is set when more than searchEventLimit paths came + // before the window drained them, which are then dropped. + started, overflow, limited, excess bool + // paths are the host paths changed since the last drain. + paths []string + // woken is set while a drain is queued. + woken bool +} + +// record changes the watch's pending state on the request's goroutine and queues one drain. +func (w *remoteWatch) record(a *App, p *project, change func(w *remoteWatch)) { + w.mu.Lock() + change(w) + wake := !w.woken + w.woken = true + w.mu.Unlock() + if wake { + a.post(func(a *App) { a.drainRemoteWatch(p, w) }) + } +} + +// startRemoteWatch starts the host watch of p's folder over its session, unless one runs or the +// watch waits for something. +func (a *App) startRemoteWatch(p *project) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.watch != nil || r.watchWait != remoteWatchReady { + return + } + ctx, cancel := context.WithCancel(p.ctx) + w := &remoteWatch{session: r.session, cancel: cancel} + r.watch = w + kernel, root, excludes := a.kernel, r.binding.RemoteRoot(), remoteWatchExcludeNames() + events := core.RemoteWatchEvents{ + Started: func() { w.record(a, p, func(w *remoteWatch) { w.started = true }) }, + Changed: func(changes []core.RemoteWatchChange, overflow bool) { + w.record(a, p, func(w *remoteWatch) { + w.overflow = w.overflow || overflow + if w.overflow || w.excess { + // Everything is read again, which covers these changes too. + w.paths = nil + return + } + if len(w.paths)+len(changes) > searchEventLimit { + w.excess, w.paths = true, nil + return + } + for _, change := range changes { + w.paths = append(w.paths, change.Path) + } + }) + }, + LimitReached: func() { w.record(a, p, func(w *remoteWatch) { w.limited = true }) }, + } + go func() { + err := kernel.RemoteRunWatch(ctx, w.session, root, excludes, events) + a.post(func(a *App) { a.remoteWatchEnded(p, w, err) }) + }() +} + +// stopRemoteWatch stops p's host watch. Changes it queued for the tree are dropped, and so is a +// drain or an end it already posted. +func (a *App) stopRemoteWatch(p *project) { + r := p.remote + if r == nil || r.watch == nil { + return + } + r.watch.cancel() + r.watch = nil + p.tree.eventEpoch++ + p.tree.eventPending = nil +} + +// restartRemoteWatch starts p's running host watch again, for a new list of hidden folders. +func (a *App) restartRemoteWatch(p *project) { + if p.remote == nil || p.remote.watch == nil { + return + } + a.stopRemoteWatch(p) + a.startRemoteWatch(p) +} + +// drainRemoteWatch applies what w handed over since the last drain. +func (a *App) drainRemoteWatch(p *project, w *remoteWatch) { + w.mu.Lock() + started, overflow, limited, excess, paths := w.started, w.overflow, w.limited, w.excess, w.paths + w.started, w.overflow, w.limited, w.excess, w.paths, w.woken = false, false, false, false, nil, false + w.mu.Unlock() + r := p.remote + if a.project != p || r == nil || r.watch != w { + // log-exempt: 用户取消:工作区已关闭,或这次监听已停止(会话丢失、隐藏目录变化),它的变化不再适用。 + return + } + if limited { + a.backgroundFailed("remote_watch", errRemoteWatchLimit) + a.remoteWatchUnavailable(p) + } + if overflow && !w.lostReported { + w.lostReported = true + a.backgroundFailed("remote_watch", errWatchEventsLost) + } + if excess && !w.excessReported { + w.excessReported = true + a.backgroundFailed("remote_watch", errWatchEventLimit) + } + if started { + w.watching = true + } + if started || overflow || excess { + // A change before the start, or one the host or the window dropped, is found by reading + // everything shown again. + a.resyncRemoteWorkspace(p) + return + } + a.applyRemoteChanges(p, paths) +} + +// remoteWatchUnavailable tells the user, once for the workspace, that the host does not watch all +// of its folder. +func (a *App) remoteWatchUnavailable(p *project) { + if p.remote.watchNotified { + // log-exempt: 同一次失败已经记录过:每次失败都已记 remote_watch,提示对一个工作区只显示一次。 + return + } + p.remote.watchNotified = true + a.notifyError(i18n.Shared(a.language(), "desktop.project.watchUnavailable")) +} + +// 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. +func (a *App) resyncRemoteWorkspace(p *project) { + p.tree.eventEpoch++ + p.tree.eventPending = nil + if p.tree.root != nil { + a.refreshRemoteTree(p) + } + a.recheckRemoteDocuments(p) +} + +// applyRemoteChanges hands 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)) + for _, host := range hostPaths { + if name, ok := remoteRelativePath(root, host); ok { + names = append(names, name) + } + } + if len(names) == 0 { + return + } + a.markRemoteDocuments(p, names) + t := &p.tree + if t.root == nil { + return + } + if len(t.eventPending)+len(names) > searchEventLimit { + t.eventEpoch++ + t.eventPending = nil + a.backgroundFailed("remote_watch", errWatchEventLimit) + a.resyncTreeListings(p) + return + } + t.eventPending = append(t.eventPending, names...) + a.filterTreeEvents(p) +} + +// markRemoteDocuments compares with the host every document of p whose file, or a folder above +// it, is one of names, paths relative to the folder. +func (a *App) markRemoteDocuments(p *project, names []string) { + changed := make(map[string]struct{}, len(names)) + for _, name := range names { + changed[name] = struct{}{} + } + root, marked := p.remote.binding.RemoteRoot(), false + for _, d := range p.docs.list { + if d.virtual { + continue + } + name, ok := remoteRelativePath(root, p.remoteHostPath(d.path)) + for ok { + if _, hit := changed[name]; hit { + d.checkPending, marked = true, true + break + } + name = path.Dir(name) + ok = name != "." + } + } + if marked { + a.scheduleDocumentChecks(p) + } +} + +// remoteRelativePath is host, an absolute host path, relative to root, the workspace's folder. +// ok is false for root itself and for a path outside it. +func remoteRelativePath(root, host string) (string, bool) { + prefix := strings.TrimSuffix(root, "/") + "/" + name, ok := strings.CutPrefix(host, prefix) + return name, ok && name != "" +} + +// remoteWatchEnded handles the end of w's request with err. +func (a *App) remoteWatchEnded(p *project, w *remoteWatch, err error) { + r := p.remote + if a.project != p || r == nil || r.closed || r.watch != 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() + a.stopRemoteWatch(p) + var coreErr *core.Error + switch { + case err == nil && started: + // log-exempt: 预期的缺失:主机上的文件夹在监听中被删除或移走,监听随即重新开始,找回或找不到它都另有处理。 + a.startRemoteWatch(p) + a.resyncRemoteWorkspace(p) + case err == nil, errors.As(err, &coreErr) && coreErr.Code == core.CodeWorkspaceNotFound: + // A watch that ended without starting found no folder to watch either; starting it again + // at once would only end it again. + // log-exempt: 预期的缺失:主机上没有这个文件夹,项目树显示根目录不可用,监听等树重新列出它。 + if p.tree.root == nil || p.tree.failed != "" { + // The tree shows no listing of the folder, so its next one finds the folder back. + r.watchWait = remoteWatchRootListed + } else { + // The tree's listing may be older than the folder's removal; the one read below + // tells. + r.watchWait = remoteWatchRootMissed + } + a.resyncRemoteWorkspace(p) + case remoteConnectionClosed(err): + a.loseRemote(p, w.session, err) + default: + a.backgroundFailed("remote_watch", remoteLogError(err)) + r.watchWait = remoteWatchSession + a.remoteWatchUnavailable(p) + a.resyncRemoteWorkspace(p) + } +} + +// remoteTreeRootRead lets a waiting host watch know how the tree's listing of the root went: +// listed, or found missing. +func (a *App) remoteTreeRootRead(p *project, listed bool) { + r := p.remote + if r == nil { + return + } + switch { + case !listed && r.watchWait == remoteWatchRootMissed: + r.watchWait = remoteWatchRootListed + case listed && r.watchWait == remoteWatchRootListed: + r.watchWait = remoteWatchReady + a.startRemoteWatch(p) + } +} diff --git a/desktop/internal/workbench/remote_watch_test.go b/desktop/internal/workbench/remote_watch_test.go new file mode 100644 index 0000000000..196fa1dbb5 --- /dev/null +++ b/desktop/internal/workbench/remote_watch_test.go @@ -0,0 +1,427 @@ +package workbench + +import ( + "context" + "slices" + "strconv" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// remoteTestFolder is the host folder the tests open as the workspace. +const remoteTestFolder = remoteTestHome + "/project" + +// remoteHostWatches stands in for the host's watches of the workspace's folder +// (remote.runWatch): a watch starts at once, unless the test refuses it or the folder is +// missing, and hands over what the test sends until the test ends it or its request ends. +type remoteHostWatches struct { + mu sync.Mutex + runs []*remoteHostWatch + // refuse, when set, fails the next watch before it starts. + refuse error +} + +// remoteHostWatch is one watch the host ran. +type remoteHostWatch struct { + session, root string + excludes []string + send chan func(core.RemoteWatchEvents) + end chan error + // ended is closed when the request returned. + ended chan struct{} +} + +// remoteWatchWaitLimit bounds how long a test waits for the host's watch to take an event or end. +const remoteWatchWaitLimit = 5 * time.Second + +func (k *remoteHostKernel) RemoteRunWatch(ctx context.Context, session, root string, excludes []string, events core.RemoteWatchEvents) error { + k.mu.Lock() + missing := k.missing + k.mu.Unlock() + h := &k.watches + h.mu.Lock() + run := &remoteHostWatch{ + session: session, root: root, excludes: slices.Clone(excludes), + send: make(chan func(core.RemoteWatchEvents)), end: make(chan error, 1), ended: make(chan struct{}), + } + h.runs = append(h.runs, run) + refused := h.refuse + h.refuse = nil + h.mu.Unlock() + defer close(run.ended) + switch { + case refused != nil: + return refused + case missing: + return &core.Error{Command: "remote.runWatch", Code: core.CodeWorkspaceNotFound, Message: "no such folder: " + root} + } + events.Started() + for { + select { + case deliver := <-run.send: + deliver(events) + case err := <-run.end: + return err + case <-ctx.Done(): + // Core stops the watch and answers with the context's error. + return ctx.Err() + } + } +} + +// watchRuns is how many watches the host ran. +func (k *remoteHostKernel) watchRuns() int { + k.watches.mu.Lock() + defer k.watches.mu.Unlock() + return len(k.watches.runs) +} + +// refuseWatch fails the next watch with err before it starts. +func (k *remoteHostKernel) refuseWatch(err error) { + k.watches.mu.Lock() + defer k.watches.mu.Unlock() + k.watches.refuse = err +} + +// lastWatch is the watch the host ran last. +func (k *remoteHostKernel) lastWatch(t *testing.T) *remoteHostWatch { + t.Helper() + k.watches.mu.Lock() + defer k.watches.mu.Unlock() + if len(k.watches.runs) == 0 { + t.Fatal("the host ran no watch") + } + return k.watches.runs[len(k.watches.runs)-1] +} + +// deliver hands events, as the host sends them, to the watch's request. +func (w *remoteHostWatch) deliver(t *testing.T, deliver func(core.RemoteWatchEvents)) { + t.Helper() + timer := time.NewTimer(remoteWatchWaitLimit) + defer timer.Stop() + select { + case w.send <- deliver: + case <-w.ended: + t.Fatal("the watch ended before it took the events") + case <-timer.C: + t.Fatal("timed out handing the watch its events") + } +} + +// changed reports the host paths changed below the folder in one batch. +func (w *remoteHostWatch) changed(t *testing.T, names ...string) { + t.Helper() + changes := make([]core.RemoteWatchChange, 0, len(names)) + for _, name := range names { + changes = append(changes, core.RemoteWatchChange{Path: remoteTestFolder + "/" + name, Kind: "modified"}) + } + w.deliver(t, func(events core.RemoteWatchEvents) { events.Changed(changes, false) }) +} + +// finish ends the watch's request with err and waits for it to return. +func (w *remoteHostWatch) finish(t *testing.T, err error) { + t.Helper() + w.end <- err + w.awaitEnd(t) +} + +// awaitEnd waits for the watch's request to return. +func (w *remoteHostWatch) awaitEnd(t *testing.T) { + t.Helper() + timer := time.NewTimer(remoteWatchWaitLimit) + defer timer.Stop() + select { + case <-w.ended: + case <-timer.C: + t.Fatal("timed out waiting for the watch to end") + } +} + +// awaitWatching waits until the workspace's host watch runs and the host watches the folder, and +// for the tree and the documents it reads again then. +func (h *harness) awaitWatching(p *project) { + h.t.Helper() + h.await("the host watch", func() bool { + r := p.remote + return r.watch != nil && r.watch.watching && !p.tree.reading && !remoteChecksPending(p) + }) + h.settle() +} + +// remoteChecksPending reports that a document of p is still being compared with the host. +func remoteChecksPending(p *project) bool { + return slices.ContainsFunc(p.docs.list, func(d *document) bool { return d.checking || d.checkPending }) +} + +// remoteWatchFailures are the logged errors of the window's work on the host watch. +func remoteWatchFailures(logger *treeRecordingLog) []string { + logger.mu.Lock() + defer logger.mu.Unlock() + var errs []string + for _, event := range logger.events { + if event.Event == backgroundFailedEvent && event.Fields["operation"] == "remote_watch" { + errs = append(errs, event.Fields["error"].(string)) + } + } + return errs +} + +// countNotified counts the notifications that say text. +func (h *harness) countNotified(text string) int { + n := 0 + for _, notice := range h.app.notifications.list { + if notice.text == text { + n++ + } + } + return n +} + +// The host watches the workspace's folder over its session, leaving out no folder while no plugin +// hides one. A change made on the host shows in the tree, reloads an open document that has no +// edits and shows the conflict in one that has; a change of a folder Core hides and a path outside +// the folder change nothing. Neither the host nor its paths are logged. +func TestRemoteWorkspaceShowsChangesMadeOnTheHost(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + k.put(remoteTestReadme, "# Project\n") + p := h.openRemoteTestProject(t) + d := h.openRemoteFile(t, p, "README.md") + if d == nil { + t.Fatal("README.md did not open") + } + h.awaitWatching(p) + w := k.lastWatch(t) + if w.session != "session-1" || w.root != remoteTestFolder || len(w.excludes) != 0 || k.watchRuns() != 1 { + t.Fatalf("watched over %q with %d excluded names in %d runs, want the workspace's folder over its session", w.session, len(w.excludes), k.watchRuns()) + } + + k.set(func(k *remoteHostKernel) { + k.tree = map[string][]core.WorkspaceNode{"": append(slices.Clone(remoteTestTree[""]), core.WorkspaceNode{Path: "NOTES.md", Name: "NOTES.md"})} + }) + k.put(remoteTestReadme, "changed on the host\n") + w.changed(t, "NOTES.md", "README.md", ".git/index") + h.await("the host's changes", func() bool { + text, _ := d.view.Text() + return p.tree.find("NOTES.md") != nil && string(text) == "changed on the host\n" && !p.tree.reading && !remoteChecksPending(p) + }) + if d.dirty() || d.conflicted { + t.Fatal("reloading the host's change left the document edited or in conflict") + } + + // A change outside the folder, of the folder itself or of a folder Core hides lists nothing + // again: of these changes, only the last lists the tree's root. + listed := k.count(func(k *remoteHostKernel) int { return len(k.listings) }) + w.deliver(t, func(events core.RemoteWatchEvents) { + events.Changed([]core.RemoteWatchChange{{Path: remoteTestHome + "/notes.txt", Kind: "modified"}, {Path: remoteTestFolder, Kind: "modified"}}, false) + }) + w.changed(t, ".git/HEAD") + w.changed(t, "README.md") + h.await("the last change", func() bool { + return k.count(func(k *remoteHostKernel) int { return len(k.listings) }) > listed && !p.tree.eventFiltering && !p.tree.reading && !remoteChecksPending(p) + }) + h.settle() + if got := k.count(func(k *remoteHostKernel) int { return len(k.listings) }); got != listed+1 { + t.Fatalf("the changes listed the tree %d times, want once for the last", got-listed) + } + + typeAtCaret(t, d, "local ") + k.put(remoteTestReadme, "changed again\n") + w.changed(t, "README.md") + h.await("the conflict", func() bool { return d.conflicted && !remoteChecksPending(p) }) + if text, _ := d.view.Text(); string(text) == "changed again\n" || !d.dirty() { + t.Fatal("the host's change replaced the edits") + } + if got := remoteWatchFailures(logger); len(got) != 0 { + t.Fatalf("logged %q, want no failure", got) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// When the host lost changes, or sent more than the window applies one by one, the tree and every +// document are read again, and the log keeps it once for the watch. When the host runs out of +// watches, the watch goes on for the rest of the folder and the user is told once. +func TestRemoteWatchReadsEverythingAgainWhenChangesAreLost(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.put(remoteTestReadme, "# Project\n") + p := h.openRemoteTestProject(t) + d := h.openRemoteFile(t, p, "README.md") + if d == nil { + t.Fatal("README.md did not open") + } + h.awaitWatching(p) + w := k.lastWatch(t) + + readAgain := func(what string, send func()) { + t.Helper() + listed := k.count(func(k *remoteHostKernel) int { return len(k.listings) }) + k.put(remoteTestReadme, what+"\n") + send() + h.await(what, func() bool { + text, _ := d.view.Text() + return string(text) == what+"\n" && !p.tree.reading && !remoteChecksPending(p) && + k.count(func(k *remoteHostKernel) int { return len(k.listings) }) > listed + }) + h.settle() + } + for _, what := range []string{"lost once", "lost twice"} { + readAgain(what, func() { + w.deliver(t, func(events core.RemoteWatchEvents) { events.Changed(nil, true) }) + }) + } + readAgain("too many", func() { + names := make([]string, searchEventLimit+1) + for i := range names { + names[i] = "src/file" + strconv.Itoa(i) + } + w.changed(t, names...) + }) + + unavailable := i18n.Shared(lang, "desktop.project.watchUnavailable") + for range 2 { + before := len(remoteWatchFailures(logger)) + w.deliver(t, func(events core.RemoteWatchEvents) { events.LimitReached() }) + h.await("the watch limit", func() bool { return len(remoteWatchFailures(logger)) > before }) + } + h.settle() + if got := h.countNotified(unavailable); got != 1 { + t.Fatalf("told the user %d times that files may not update, want once", got) + } + if p.remote.watch == nil || k.watchRuns() != 1 { + t.Fatalf("the watch stopped after the host ran out of watches; %d runs", k.watchRuns()) + } + want := []string{errWatchEventsLost.Error(), errWatchEventLimit.Error(), errRemoteWatchLimit.Error(), errRemoteWatchLimit.Error()} + if got := remoteWatchFailures(logger); !slices.Equal(got, want) { + t.Fatalf("logged %q, want %q", got, want) + } +} + +// The watch follows the workspace's session. One that fails is logged by command and code, tells +// the user once and waits for the next session; one that finds the connection closed ends the +// session, and the workspace connects again and watches over the new one. Closing the workspace +// ends the watch. +func TestRemoteWatchFollowsTheSession(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + r := p.remote + h.awaitWatching(p) + + k.lastWatch(t).finish(t, &core.Error{Command: "remote.runWatch", Code: core.CodeProcessFailed, Message: "cannot watch " + remoteTestFolder}) + h.await("the failed watch", func() bool { return r.watch == nil && r.watchWait == remoteWatchSession && !p.tree.reading }) + h.settle() + if got := remoteWatchFailures(logger); len(got) != 1 || !h.notified(i18n.Shared(lang, "desktop.project.watchUnavailable")) || k.watchRuns() != 1 { + t.Fatalf("logged %d failures in %d runs: the failed watch was not reported once and left waiting", len(got), k.watchRuns()) + } + + k.set(func(k *remoteHostKernel) { + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fire(t, timers) + h.await("the second session", func() bool { return r.session == "session-2" && !r.beating }) + h.awaitWatching(p) + if w := k.lastWatch(t); w.session != "session-2" || k.watchRuns() != 2 { + t.Fatalf("watched over %q in %d runs, want the new session", w.session, k.watchRuns()) + } + + k.lastWatch(t).finish(t, &core.Error{Command: "remote.runWatch", Code: core.CodeConnectionClosed, Message: "closed"}) + h.await("the third session", func() bool { return r.session == "session-3" && !r.beating }) + h.awaitWatching(p) + if w := k.lastWatch(t); w.session != "session-3" || !slices.Contains(k.closed, "session-2") { + t.Fatalf("watched over %q, closed %q: the closed connection was not replaced", w.session, k.closed) + } + if got := countFailures(logger, "remote_session_lost"); got != 2 { + t.Fatalf("remote_session_lost logged %d times, want once per session", got) + } + + w := k.lastWatch(t) + h.app.closeProject() + h.settle() + w.awaitEnd(t) + if got := len(remoteWatchFailures(logger)); got != 1 { + t.Fatalf("logged %d watch failures, want only the first", got) + } + if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { + t.Fatalf("logged the host or its paths: %s", event) + } +} + +// A folder removed while watched ends the watch, which starts again at once, finds the folder +// missing and waits: it starts again once the tree lists the folder, not before. A watch that +// finds the folder missing while the tree lists it waits too instead of trying again and again. +// None of it is logged as a failure of the watch. +func TestRemoteWatchWaitsForAMissingFolder(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + r := p.remote + h.awaitWatching(p) + + k.set(func(k *remoteHostKernel) { k.missing = true }) + k.lastWatch(t).finish(t, nil) + h.await("the missing folder", func() bool { + return r.watch == nil && r.watchWait == remoteWatchRootListed && p.tree.failed != "" && !p.tree.reading && k.watchRuns() == 2 + }) + h.settle() + h.app.retryProjectTree(p) + h.settle() + h.await("the tree to find the folder still missing", func() bool { return !p.tree.reading }) + h.settle() + if k.watchRuns() != 2 || r.watch != nil { + t.Fatalf("%d runs: the watch started again while the folder is missing", k.watchRuns()) + } + + k.set(func(k *remoteHostKernel) { k.missing = false }) + h.app.retryProjectTree(p) + h.awaitWatching(p) + if w := k.lastWatch(t); k.watchRuns() != 3 || w.session != "session-1" || p.tree.failed != "" { + t.Fatalf("%d runs over %q: the watch did not start again once the folder was back", k.watchRuns(), w.session) + } + + // The host finds the folder missing while the tree lists it. + k.refuseWatch(&core.Error{Command: "remote.runWatch", Code: core.CodeWorkspaceNotFound, Message: "no such folder"}) + k.lastWatch(t).finish(t, nil) + h.await("the watch to wait", func() bool { + return r.watch == nil && r.watchWait == remoteWatchRootMissed && !p.tree.reading && k.watchRuns() == 4 + }) + h.settle() + h.app.retryProjectTree(p) + h.settle() + h.await("the tree to list the folder", func() bool { return !p.tree.reading }) + h.settle() + if k.watchRuns() != 4 || r.watch != nil { + t.Fatalf("%d runs: the watch tried again while the host does not find the folder", k.watchRuns()) + } + if got := remoteWatchFailures(logger); len(got) != 0 { + t.Fatalf("logged %q, want no failure of the watch", got) + } +} + +// Other hidden folder names start the watch again leaving them out, as written; the same names +// leave it running. +func TestRemoteWatchLeavesOutTheHiddenFolders(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + clearHiddenFolders(t) + p := h.openRemoteTestProject(t) + h.awaitWatching(p) + first := k.lastWatch(t) + + h.app.applyHiddenDirectories(hiddenDirectories{names: []string{"target"}, answered: true}) + first.awaitEnd(t) + h.awaitWatching(p) + if w := k.lastWatch(t); k.watchRuns() != 2 || !slices.Equal(w.excludes, []string{"target"}) { + t.Fatalf("%d runs leaving out %q, want a new watch leaving out the hidden folders", k.watchRuns(), w.excludes) + } + h.app.applyHiddenDirectories(hiddenDirectories{names: []string{"target"}, answered: true}) + h.settle() + h.app.applyHiddenDirectories(hiddenDirectories{names: []string{"Target"}, answered: true}) + h.awaitWatching(p) + if w := k.lastWatch(t); k.watchRuns() != 3 || !slices.Equal(w.excludes, []string{"Target"}) { + t.Fatalf("%d runs leaving out %q, want one more watch for the names in another case", k.watchRuns(), w.excludes) + } +} diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 9eb81064ab..3fe1d64aee 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -27,9 +27,10 @@ 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), and its terminals run the host's -// login shell on the host (remote_terminal.go). The features that still read the project through -// the local file system (the watch of the folder, search, local history, language servers, run +// 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. @@ -99,6 +100,12 @@ type remoteProject struct { failure *remoteProbeOutcome // menuOpen is the status bar's menu of the connection. menuOpen bool + // watch is the host watch of the folder over the session (remote_watch.go), nil while none + // runs; watchWait is what it waits for then. watchNotified is set once the user was told the + // folder is not watched in full. + watch *remoteWatch + watchWait remoteWatchWait + watchNotified bool // closed is set once the project closes; nothing of the workspace runs afterwards. closed bool } @@ -254,12 +261,16 @@ func (r *remoteProject) stopRemoteTimer() { r.timer++ } -// attachRemote makes session the workspace's session and starts its heartbeat. +// attachRemote makes session the workspace's session and starts its heartbeat and the host watch +// of its folder. func (a *App) attachRemote(p *project, session string) { r := p.remote + a.stopRemoteWatch(p) r.session, r.link, r.attempt, r.misses, r.failure = session, remoteConnected, 0, 0, nil r.binding.Attach(session) a.beatRemote(p) + r.watchWait = remoteWatchReady + a.startRemoteWatch(p) } // beatRemote asks the server of the workspace's session what still runs, and schedules the next @@ -313,6 +324,7 @@ func (a *App) loseRemote(p *project, session string, err error) { return } a.backgroundFailed("remote_session_lost", remoteLogError(err)) + a.stopRemoteWatch(p) r.session, r.misses = "", 0 r.binding.Detach() r.stopRemoteTimer() @@ -429,6 +441,7 @@ func (a *App) closeRemoteWorkspace(p *project) { } r.closed = true r.stopRemoteTimer() + a.stopRemoteWatch(p) if r.reconnecting != nil { r.reconnecting.cancel() r.reconnecting = nil diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 093f72b247..6442d67f12 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -38,8 +38,9 @@ var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ // remoteHostKernel stands in for a host over SSH: it opens numbered sessions, lists // remoteTestFolders, answers heartbeats as the test says, lists the workspace's tree only for a -// request that carries the workspace's session and keeps the files of files -// (remote_documents_test.go). Everything else is the real Core. +// 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. type remoteHostKernel struct { *testKernel mu sync.Mutex @@ -65,6 +66,20 @@ type remoteHostKernel struct { fileSessions []string // terminals are the host's terminals (remote_terminal_test.go). terminals remoteHostTerminals + // tree is the workspace's folders the Project tool window lists, by path relative to the + // folder; nil lists remoteTestTree. missing is set while the folder is gone from the host. + tree map[string][]core.WorkspaceNode + missing bool + // watches are the host's watches of the folder (remote_watch_test.go). + watches remoteHostWatches +} + +// remoteTestTree is the workspace's tree the Project tool window lists by default. +var remoteTestTree = map[string][]core.WorkspaceNode{ + "": { + {Path: "src", Name: "src", IsDirectory: true}, + {Path: "README.md", Name: "README.md"}, + }, } func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) { @@ -114,21 +129,21 @@ func (k *remoteHostKernel) ListDirectories(ctx context.Context, _ string, paths session = binding.SessionID() } k.mu.Lock() + defer k.mu.Unlock() k.listings = append(k.listings, session) - k.mu.Unlock() - if session == "" { + switch { + case session == "": return nil, &core.Error{Command: "workspace.listDirectories", Code: core.CodeConnectionClosed, Message: "the remote workspace is not connected"} + case k.missing: + return nil, &core.Error{Command: "workspace.listDirectories", Code: core.CodeWorkspaceNotFound, Message: "the folder is gone"} + } + tree := k.tree + if tree == nil { + tree = remoteTestTree } listings := make([]core.DirectoryListing, 0, len(paths)) for _, dir := range paths { - listing := core.DirectoryListing{Path: dir} - if dir == "" { - listing.Children = []core.WorkspaceNode{ - {Path: "src", Name: "src", IsDirectory: true}, - {Path: "README.md", Name: "README.md"}, - } - } - listings = append(listings, listing) + listings = append(listings, core.DirectoryListing{Path: dir, Children: slices.Clone(tree[dir])}) } return listings, nil } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 987593e582..dacba70f6c 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", @@ -11,6 +11,8 @@ "desktop/internal/core/remote_session_test.go", "desktop/internal/core/remote_terminal.go", "desktop/internal/core/remote_terminal_test.go", + "desktop/internal/core/remote_watch.go", + "desktop/internal/core/remote_watch_test.go", "desktop/internal/remoteplaceholder/remoteplaceholder.go", "desktop/internal/workbench/remote_browse.go", "desktop/internal/workbench/remote_browse_view.go", @@ -19,9 +21,11 @@ "desktop/internal/workbench/remote_status_view.go", "desktop/internal/workbench/remote_documents_test.go", "desktop/internal/workbench/remote_terminal.go", + "desktop/internal/workbench/remote_watch.go", "desktop/internal/termview/open_test.go", "desktop/internal/workbench/remote_workspace_test.go", "desktop/internal/workbench/remote_terminal_test.go", + "desktop/internal/workbench/remote_watch_test.go", "desktop/internal/workbench/remote_workspace_visual_test.go" ] }, @@ -39,11 +43,13 @@ "desktop/internal/workbench/remote_documents.go", "desktop/internal/workbench/remote_workspace.go", "desktop/internal/workbench/remote_status_view.go", - "desktop/internal/workbench/remote_terminal.go" + "desktop/internal/workbench/remote_terminal.go", + "desktop/internal/core/remote_watch.go", + "desktop/internal/workbench/remote_watch.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 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。查找工具窗口说明暂不可用,Search Everywhere 只有“操作”页。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、internal/core 的 TestRemoteTerminal* 与 termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放)仍待完成。主机文件的外部修改监听、Git、搜索与端口转发见 remote-development-workspace。", + "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。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -80,5 +86,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;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。" + "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 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。" }