From 2ad07952f3f832547aed14a0fc2c30e0b7902b1d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 24 Nov 2026 03:02:27 +0800 Subject: [PATCH] feat(plugin-api): wire workspace reads, search and native watches through Core --- ...ugin-host-services-and-backend-sessions.md | 25 +- desktop/internal/core/workspace_find_watch.go | 84 +++++++ .../core/workspace_find_watch_test.go | 90 +++++++ desktop/internal/core/workspace_read.go | 81 ++++++ desktop/internal/core/workspace_read_test.go | 72 ++++++ desktop/internal/pluginhost/pluginhost.go | 9 +- .../internal/pluginservice/hostdocuments.go | 15 ++ .../pluginservice/hostworkspacefind.go | 97 ++++++++ .../pluginservice/hostworkspacefind_test.go | 74 ++++++ .../pluginservice/hostworkspaceread.go | 136 ++++++++++ .../pluginservice/hostworkspaceread_test.go | 132 ++++++++++ .../pluginservice/hostworkspacewatch.go | 234 ++++++++++++++++++ .../pluginservice/hostworkspacewatch_test.go | 206 +++++++++++++++ .../internal/pluginservice/pluginservice.go | 2 + desktop/internal/workbench/app.go | 4 + .../internal/workbench/pluginworkspaceread.go | 116 +++++++++ .../workbench/pluginworkspaceread_test.go | 118 +++++++++ docs/development/macos-plugin-api-plan.md | 6 +- scripts/desktop/build-desktop-core.sh | 6 +- ...ugin-host-editor-file-window-services.json | 32 ++- 20 files changed, 1526 insertions(+), 13 deletions(-) create mode 100644 desktop/internal/core/workspace_find_watch.go create mode 100644 desktop/internal/core/workspace_find_watch_test.go create mode 100644 desktop/internal/core/workspace_read.go create mode 100644 desktop/internal/core/workspace_read_test.go create mode 100644 desktop/internal/pluginservice/hostworkspacefind.go create mode 100644 desktop/internal/pluginservice/hostworkspacefind_test.go create mode 100644 desktop/internal/pluginservice/hostworkspaceread.go create mode 100644 desktop/internal/pluginservice/hostworkspaceread_test.go create mode 100644 desktop/internal/pluginservice/hostworkspacewatch.go create mode 100644 desktop/internal/pluginservice/hostworkspacewatch_test.go create mode 100644 desktop/internal/workbench/pluginworkspaceread.go create mode 100644 desktop/internal/workbench/pluginworkspaceread_test.go diff --git a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md index 70bf03d0e..0fc69f2ea 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md +++ b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md @@ -89,7 +89,29 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 - **订阅与资源释放**:`hostResources` 统一登记订阅、内容提供者、终端句柄,归属 `(插件, 会话, 上下文)`;`subscriptions/dispose` 只释放调用方自己的 ID;会话结束与上下文关闭自动释放。 - **命令**:`commands/didRun` 的发送端 `Service.NotifyCommandRun` 已实现(运行中的后端直接收;已停止的只有清单声明 `onCommand:` 才被启动),但 Viva 目前没有命令面板、编辑器右键菜单或插件命令贡献入口,没有调用方。 -未接通(会被 Core 以 `plugin.host.unavailable` 拒绝):`editor/registerActions`、`editor/registerProviders`(没有编辑器行首图标、命令入口与右键菜单,注册了用户也触发不了,所以不声明)、`preview/openHTML`、`workspace/readDirectory|stat|readFile|watch|findFiles|findText`、`run/*`、`debug/*`(后两者属其他车道)。凭据在插件卸载时的清理也未做:除 macOS 外平台存储不能按 service 枚举,需要后续由插件管理器记录已用的 key。 +未接通(会被 Core 以 `plugin.host.unavailable` 拒绝):`editor/registerActions`、`editor/registerProviders`(没有编辑器行首图标、命令入口与右键菜单,注册了用户也触发不了,所以不声明)、`preview/openHTML`、`run/*`、`debug/*`(后两者属其他车道)。凭据在插件卸载时的清理也未做:除 macOS 外平台存储不能按 service 枚举,需要后续由插件管理器记录已用的 key。 + +### API-06:先由 Core 提供磁盘读取,再接窗口 + +`workspace/readDirectory|stat|readFile` 的共享规则和执行命令由 Rust Core 提供,桌面只把经过授权的工作区根与相对路径交给 Core,并把返回路径封装为插件自己的资源标识。这样分页、字节预算、隐藏规则和错误分类在所有客户端保持一致。具体参数和限制只在 Core 插件契约中维护。 + +文件读取不复用打开文档的内容:例如编辑器里已把 `alpha` 改成未保存的 `ALPHA`,`readFile` 仍返回磁盘上的 `alpha`。逐段拒绝符号链接以及 Windows 的文件系统重解析点(reparse point,可把路径转到另一位置);Unix 使用相对目录句柄,Windows 持有禁止写入和删除共享的祖先目录句柄,防止校验后路径被换成链接。代价是 Windows 读取期间无法重命名这些目录,遇到冲突的共享方式会拒绝读取,不降低保护后重试。 + +正确做法是宿主请求所在的后台任务调用 Core,窗口线程只确认本地项目仍然有效。不要先在 Go 里解析真实路径再读取:路径可能在两步之间被替换,也会复制一份 Core 的规则。请求取消或项目关闭会取消读取,发布前再次核对同一个项目和工作区上下文,避免关闭后重开同一路径接收旧结果。这里只读取文件,不产生缓存或写入安装目录,因此不会改变代码签名或 Sparkle 增量更新基线。 + +三个方法仅在窗口实现 `WorkspaceReadHost` 后注册。没有远程读取适配器时拒绝远程工作区,不读取本机占位目录。监听与搜索也按各自的可选宿主接口注册,遵循相同的上下文检查。 + +验证使用 `scripts/desktop/desktop-go.sh test ./internal/pluginservice ./internal/workbench -run 'TestWorkspaceReads|TestPluginWorkspaceReads' -count=1`。默认构建固定到 Core `9ab2336`,包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) 并保留现有 #187 增量更新依赖;无需本地覆盖路径。测试读取真实临时文件,覆盖资源隔离、磁盘与未保存文档的区别及项目关闭取消;不依赖任何具体插件。Windows 的原生目录句柄行为须在 Windows 单独验证,本机 macOS 测试不能替代。 + +### API-07/08:Core 处理搜索与监听语义,Viva 只提供原生事件 + +文件名搜索与文本搜索复用 Core 已有的匹配器、编码识别、隐藏规则和工作区索引排除策略。插件磁盘入口要求逐段拒绝链接,现有搜索索引读取链路不能保证这一点,因此这里复用匹配和策略,以同一套 no-follow 句柄做有界遍历,不调用会在校验后重新按路径打开文件的索引读取。搜索不为每个插件保留整棵树或内容索引,只保留一页与一个额外候选;代价是每页重新遍历,查询可能在大工程上超时,当前不宣称具备索引查询的延迟。以后改用索引候选时,也必须保留句柄读取和当前范围限制。 + +正确做法是先由 Core 验证监听目标,再让 Viva 建立原生文件事件流,并在注册后核对根与目标身份。原生流覆盖工作区根,使目标的父目录被替换也能触发重扫;Core 决定哪些名字属于订阅、哪些隐藏、哪些情况丢失细节需要重扫。不要在 Go 中复制路径匹配、排序、隐藏规则,也不要使用空闲轮询。注册完成后先发一次重扫,事件丢失、根消失或替换时要求重新读取;根消失或替换后释放旧流,不把旧流用于新根。 + +监听在 `hostResources` 中归属插件、会话与上下文,复用原生注册限额。取消在途通知后再关闭原生句柄,通知与释放串行,因此 `dispose` 返回后不会继续发送;请求返回不结束长期订阅,关闭工作区、退出会话或停用插件才结束。旧订阅不能转移给同路径的新上下文。监听只保留有界名字批次,无文件内容缓存和磁盘写入,不影响发行包、代码签名或 Sparkle 更新基线。 + +验证读取 Core 的共享 fixture 和真实临时文件,macOS 使用 Viva 的原生文件事件覆盖递归创建、原子保存、删除、初始重扫、三种释放入口及根目录替换后的最终重扫与释放,并用可控通知验证释放会取消在途发送。`scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginservice ./internal/workbench -run 'TestWorkspace(Reads|Find|Search|Watch)|TestPluginWorkspace' -count=1` 与定向竞态检查覆盖桥接、资源封装、未保存缓冲区隔离和关闭取消;监听测试没有用定时睡眠同步。Windows 原生运行按本次任务范围不验收,不能据 macOS 结果标为 Windows 已验证。 ## 适用范围 @@ -100,4 +122,5 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 - `desktop/internal/credentials/` - `desktop/internal/pluginservice/`(hostdocuments、hostsurface、hostterminal、hostcontent、hostcommands、hostresources、hostcredentials) - `desktop/internal/workbench/`(pluginworkbench、pluginprompt、pluginterminals、plugincontent) +- `desktop/internal/core/workspace_read.go`、`desktop/internal/core/workspace_find_watch.go`、`desktop/internal/pluginservice/hostworkspaceread.go`、`desktop/internal/pluginservice/hostworkspacefind.go`、`desktop/internal/pluginservice/hostworkspacewatch.go`、`desktop/internal/workbench/pluginworkspaceread.go` - `desktop/internal/editorview/hostedit.go`、`desktop/internal/termview/`、`desktop/internal/localshell/` diff --git a/desktop/internal/core/workspace_find_watch.go b/desktop/internal/core/workspace_find_watch.go new file mode 100644 index 000000000..3e96cb6fd --- /dev/null +++ b/desktop/internal/core/workspace_find_watch.go @@ -0,0 +1,84 @@ +package core + +import "context" + +// WorkspaceFindRequest is a bounded plugin search of disk files, without editor snapshots. +type WorkspaceFindRequest struct { + Root string `json:"root"` + Query string `json:"query,omitempty"` + Pattern string `json:"pattern,omitempty"` + FileMask string `json:"fileMask,omitempty"` + CaseSensitive bool `json:"caseSensitive,omitempty"` + WholeWords bool `json:"wholeWords,omitempty"` + RegularExpression bool `json:"regularExpression,omitempty"` + Cursor *string `json:"cursor,omitempty"` + Limit *int `json:"limit,omitempty"` + HiddenDirectoryNames []string `json:"hiddenDirectoryNames,omitempty"` + HiddenFilePatterns []string `json:"hiddenFilePatterns,omitempty"` +} + +// WorkspaceFindMatch is a relative file name or one matched disk line. +// Range is kept as Core's null until the public search owner supplies exact spans. +type WorkspaceFindMatch struct { + Path string `json:"path"` + Line *int `json:"line,omitempty"` + Preview string `json:"preview,omitempty"` +} + +// WorkspaceFindPage carries a query-bound continuation and explicit source/omissions. +type WorkspaceFindPage struct { + Matches []WorkspaceFindMatch `json:"matches"` + NextCursor *string `json:"nextCursor"` + IsTruncated bool `json:"isTruncated"` + Source string `json:"source"` +} + +// FindWorkspaceFiles searches disk file names off the UI thread. +func (c *Client) FindWorkspaceFiles(ctx context.Context, request WorkspaceFindRequest) (WorkspaceFindPage, error) { + var result WorkspaceFindPage + err := c.Execute(ctx, "workspace.findFiles", request, &result) + return result, err +} + +// FindWorkspaceText searches disk lines off the UI thread. +func (c *Client) FindWorkspaceText(ctx context.Context, request WorkspaceFindRequest) (WorkspaceFindPage, error) { + var result WorkspaceFindPage + err := c.Execute(ctx, "workspace.findText", request, &result) + return result, err +} + +// WorkspaceWatchPlan is Core's validated local scope for a native registration. +type WorkspaceWatchPlan struct { + Root string `json:"root"` + Path string `json:"path"` + IsDirectory bool `json:"isDirectory"` + Recursive bool `json:"recursive"` +} + +// PlanWorkspaceWatch rejects invalid, missing and linked scopes before native I/O. +func (c *Client) PlanWorkspaceWatch(ctx context.Context, root, path string, recursive bool) (WorkspaceWatchPlan, error) { + var plan WorkspaceWatchPlan + err := c.Execute(ctx, "workspace.watchPlan", struct { + Root string `json:"root"` + Path string `json:"path"` + Recursive bool `json:"recursive"` + }{root, path, recursive}, &plan) + return plan, err +} + +// WorkspaceWatchEvents are sorted, visible, root-relative names, or a rescan request. +type WorkspaceWatchEvents struct { + ChangedPaths []string `json:"changedPaths"` + RequiresRescan bool `json:"requiresRescan"` +} + +// FilterWorkspaceWatchEvents applies the public watch scope and budgets in Core. +func (c *Client) FilterWorkspaceWatchEvents(ctx context.Context, plan WorkspaceWatchPlan, paths []string, rescan bool) (WorkspaceWatchEvents, error) { + var result WorkspaceWatchEvents + err := c.Execute(ctx, "workspace.watchEvents", struct { + WorkspaceWatchPlan + Paths []string `json:"paths"` + RequiresRescan bool `json:"requiresRescan"` + }{plan, nonNil(paths), rescan}, &result) + return result, err +} diff --git a/desktop/internal/core/workspace_find_watch_test.go b/desktop/internal/core/workspace_find_watch_test.go new file mode 100644 index 000000000..570608bf5 --- /dev/null +++ b/desktop/internal/core/workspace_find_watch_test.go @@ -0,0 +1,90 @@ +package core + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestWorkspaceFindAndWatchFollowTheLinkedCoreFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("workspace/find-watch-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Files []struct{ Path, Text string } + FileRequest WorkspaceFindRequest + FilePaths []string + TextRequest WorkspaceFindRequest + TextMatches []WorkspaceFindMatch + Watch struct { + Paths []string + Expected WorkspaceWatchEvents + } + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + root := t.TempDir() + for _, file := range fixture.Files { + path := filepath.Join(root, filepath.FromSlash(file.Path)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(file.Text), 0o600); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + client := NewClient() + collect := func(request WorkspaceFindRequest, text bool) []WorkspaceFindMatch { + t.Helper() + request.Root = root + var matches []WorkspaceFindMatch + for pageNumber := 0; pageNumber < 10; pageNumber++ { + var page WorkspaceFindPage + var err error + if text { + page, err = client.FindWorkspaceText(ctx, request) + } else { + page, err = client.FindWorkspaceFiles(ctx, request) + } + if err != nil || page.Source != "disk" || page.IsTruncated { + t.Fatalf("page = %+v, error = %v", page, err) + } + matches = append(matches, page.Matches...) + if page.NextCursor == nil { + return matches + } + request.Cursor = page.NextCursor + } + t.Fatal("fixture search did not exhaust in ten pages") + return nil + } + files := collect(fixture.FileRequest, false) + var paths []string + for _, file := range files { + paths = append(paths, file.Path) + } + if !reflect.DeepEqual(paths, fixture.FilePaths) { + t.Fatalf("files = %v, want %v", paths, fixture.FilePaths) + } + if matches := collect(fixture.TextRequest, true); !reflect.DeepEqual(matches, fixture.TextMatches) { + t.Fatalf("text = %+v, want %+v", matches, fixture.TextMatches) + } + plan, err := client.PlanWorkspaceWatch(ctx, root, "", true) + if err != nil || !plan.IsDirectory || !plan.Recursive { + t.Fatalf("plan = %+v, %v", plan, err) + } + events, err := client.FilterWorkspaceWatchEvents(ctx, plan, fixture.Watch.Paths, false) + if err != nil || !reflect.DeepEqual(events, fixture.Watch.Expected) { + t.Fatalf("events = %+v, want %+v, %v", events, fixture.Watch.Expected, err) + } +} diff --git a/desktop/internal/core/workspace_read.go b/desktop/internal/core/workspace_read.go new file mode 100644 index 000000000..b2501d1be --- /dev/null +++ b/desktop/internal/core/workspace_read.go @@ -0,0 +1,81 @@ +package core + +import "context" + +// WorkspaceDirectoryRequest asks Core for one bounded disk directory page (API-06). +type WorkspaceDirectoryRequest struct { + Root string `json:"root"` + Path string `json:"path"` + Cursor *string `json:"cursor,omitempty"` + Limit *int `json:"limit,omitempty"` + HiddenDirectoryNames []string `json:"hiddenDirectoryNames,omitempty"` + HiddenFilePatterns []string `json:"hiddenFilePatterns,omitempty"` +} + +// WorkspaceDirectoryEntry is a child path in Core's directory page. +type WorkspaceDirectoryEntry struct { + Name string `json:"name"` + Path string `json:"path"` + Kind string `json:"kind"` +} + +// WorkspaceDirectoryPage contains entries and an opaque continuation, nil at the end. +type WorkspaceDirectoryPage struct { + Entries []WorkspaceDirectoryEntry `json:"entries"` + NextCursor *string `json:"nextCursor"` +} + +// WorkspaceStat describes the leaf itself, without following ancestor links. +type WorkspaceStat struct { + Path string `json:"path"` + Kind string `json:"kind"` + Size uint64 `json:"size"` + ModifiedMilliseconds *uint64 `json:"modifiedMilliseconds"` +} + +// WorkspaceReadIdentity describes exactly the returned bytes, including truncation. +type WorkspaceReadIdentity struct { + SHA256 string `json:"sha256"` + ByteCount int `json:"byteCount"` + IsTruncated bool `json:"isTruncated"` +} + +// WorkspaceFileRead is a bounded disk prefix. Exactly one of Text and Base64 is present. +type WorkspaceFileRead struct { + Path string `json:"path"` + Source string `json:"source"` + ByteCount int `json:"byteCount"` + IsTruncated bool `json:"isTruncated"` + Identity WorkspaceReadIdentity `json:"identity"` + Text *string `json:"text,omitempty"` + Encoding *string `json:"encoding,omitempty"` + Base64 *string `json:"base64,omitempty"` +} + +// ReadWorkspaceDirectory blocks on a no-follow disk listing; call off the window thread. +func (c *Client) ReadWorkspaceDirectory(ctx context.Context, request WorkspaceDirectoryRequest) (WorkspaceDirectoryPage, error) { + var page WorkspaceDirectoryPage + err := c.Execute(ctx, "workspace.readDirectory", request, &page) + return page, err +} + +// StatWorkspaceEntry blocks on disk metadata; call off the window thread. +func (c *Client) StatWorkspaceEntry(ctx context.Context, root, path string) (WorkspaceStat, error) { + var result WorkspaceStat + err := c.Execute(ctx, "workspace.stat", struct { + Root string `json:"root"` + Path string `json:"path"` + }{root, path}, &result) + return result, err +} + +// ReadWorkspaceFile blocks on a bounded no-follow disk read; it never reads a live buffer. +func (c *Client) ReadWorkspaceFile(ctx context.Context, root, path string, maximumBytes *int) (WorkspaceFileRead, error) { + var result WorkspaceFileRead + err := c.Execute(ctx, "workspace.readFile", struct { + Root string `json:"root"` + Path string `json:"path"` + MaximumBytes *int `json:"maximumBytes,omitempty"` + }{root, path, maximumBytes}, &result) + return result, err +} diff --git a/desktop/internal/core/workspace_read_test.go b/desktop/internal/core/workspace_read_test.go new file mode 100644 index 000000000..92a87a265 --- /dev/null +++ b/desktop/internal/core/workspace_read_test.go @@ -0,0 +1,72 @@ +package core + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestWorkspaceReadsFollowTheLinkedCoreByteFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("workspace/read-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Files []struct { + ID string + Bytes []byte + MaximumBytes *int + Expected map[string]json.RawMessage + } + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Files) == 0 { + t.Fatal("the linked Core fixture has no file cases") + } + client := NewClient() + root := t.TempDir() + for _, test := range fixture.Files { + t.Run(test.ID, func(t *testing.T) { + if err := os.WriteFile(filepath.Join(root, "input"), test.Bytes, 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + file, err := client.ReadWorkspaceFile(ctx, root, "input", test.MaximumBytes) + if err != nil { + t.Fatal(err) + } + encoded, err := json.Marshal(file) + if err != nil { + t.Fatal(err) + } + var actual map[string]json.RawMessage + if err := json.Unmarshal(encoded, &actual); err != nil { + t.Fatal(err) + } + for key, expected := range test.Expected { + var got, want any + if err := json.Unmarshal(actual[key], &got); err != nil { + t.Fatalf("%s: %v", key, err) + } + if err := json.Unmarshal(expected, &want); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("%s = %v, want %v", key, got, want) + } + } + if (file.Text == nil) == (file.Base64 == nil) { + t.Fatalf("read must contain exactly one of text/base64: %+v", file) + } + }) + } +} diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 730a38af7..7516a89e2 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -91,11 +91,12 @@ type Capabilities map[string][]int // and documentLink), window/showInformation|showWarning|showError, // browser/openExternal (http and https only), terminal/create|show|close| // reopen|dispose|onExit, documents/registerContentProvider, run/start|stop| -// didExit and debug/start. Window-bound methods are registered only when the +// didExit, debug/start and workspace/readDirectory|stat|readFile|watch| +// findFiles|findText (bounded disk reads, search and event projection through +// Core, with Viva native watches). Window-bound methods are registered only when the // window attaches (Service.AttachWorkbench); getCapabilities lists only what -// is registered. Workspace file and search services and preview/openHTML are -// not registered, so a plugin that needs one is refused when it asks for -// that permission. +// is registered. preview/openHTML is not registered, so a plugin that needs +// it is refused when it asks for that permission. // - buildSystems and buildProviders: the Build window detects instances, // loads provider models, resolves the ordered executable candidates Core // returns, runs command and provider tasks, prepares application targets diff --git a/desktop/internal/pluginservice/hostdocuments.go b/desktop/internal/pluginservice/hostdocuments.go index 51757c206..ddb25ba67 100644 --- a/desktop/internal/pluginservice/hostdocuments.go +++ b/desktop/internal/pluginservice/hostdocuments.go @@ -97,6 +97,21 @@ func (s *Service) AttachWorkbench(workbench Workbench) error { return nil } s.workbench = workbench + if host, ok := workbench.(WorkspaceFindHost); ok { + if err := s.registerWorkspaceFind(host); err != nil { + return err + } + } + if host, ok := workbench.(WorkspaceWatchHost); ok { + if err := s.registerWorkspaceWatch(host); err != nil { + return err + } + } + if host, ok := workbench.(WorkspaceReadHost); ok { + if err := s.registerWorkspaceReads(host); err != nil { + return err + } + } for _, entry := range []struct { method string handler pluginhost.Handler diff --git a/desktop/internal/pluginservice/hostworkspacefind.go b/desktop/internal/pluginservice/hostworkspacefind.go new file mode 100644 index 000000000..accb22b2b --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspacefind.go @@ -0,0 +1,97 @@ +package pluginservice + +import ( + "context" + "encoding/json" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +const ( + methodWorkspaceFindFiles = pluginhost.MethodPrefix + "workspace/findFiles" + methodWorkspaceFindText = pluginhost.MethodPrefix + "workspace/findText" +) + +// WorkspaceFindHost executes Core's bounded disk searches outside the UI thread. +type WorkspaceFindHost interface { + FindFiles(context.Context, core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) + FindText(context.Context, core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) +} + +func (s *Service) registerWorkspaceFind(host WorkspaceFindHost) error { + for _, method := range []string{methodWorkspaceFindFiles, methodWorkspaceFindText} { + if err := s.HostServices.Register(method, func(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + return s.handleWorkspaceFind(ctx, host, method, params) + }); err != nil { + return err + } + } + return nil +} + +func (s *Service) handleWorkspaceFind(ctx context.Context, host WorkspaceFindHost, method string, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + var request struct { + Context ContextRef `json:"context"` + Resource Resource `json:"resource"` + Query string `json:"query"` + Pattern string `json:"pattern"` + FileMask string `json:"fileMask"` + CaseSensitive bool `json:"caseSensitive"` + WholeWords bool `json:"wholeWords"` + RegularExpression bool `json:"regularExpression"` + Cursor *string `json:"cursor"` + Limit *int `json:"limit"` + } + if err := decodeStrict(params, &request); err != nil { + return nil, invalidParams(err) + } + caller, workspace, refusal := s.workspaceRequest(ctx, request.Context) + if refusal != nil { + return nil, refusal + } + if refusal := s.checkRoot(caller.PluginID, workspace, request.Resource); refusal != nil { + return nil, refusal + } + query := core.WorkspaceFindRequest{ + Root: workspace.Path, Query: request.Query, Pattern: request.Pattern, FileMask: request.FileMask, + CaseSensitive: request.CaseSensitive, WholeWords: request.WholeWords, RegularExpression: request.RegularExpression, + Cursor: request.Cursor, Limit: request.Limit, + } + var page core.WorkspaceFindPage + var err error + if method == methodWorkspaceFindFiles { + page, err = host.FindFiles(ctx, query) + } else { + page, err = host.FindText(ctx, query) + } + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + if _, err := s.Contexts.Lookup(request.Context); err != nil { + return nil, contextFailure(err) + } + if err := ctx.Err(); err != nil { + return nil, hostFailureOf(err) + } + matches := make([]any, 0, len(page.Matches)) + for _, hit := range page.Matches { + resource := Resource{request.Resource.RootID, hit.Path} + if method == methodWorkspaceFindFiles { + matches = append(matches, resource) + } else { + matches = append(matches, struct { + Resource Resource `json:"resource"` + Line *int `json:"line"` + Preview string `json:"preview"` + Range *Range `json:"range"` + }{resource, hit.Line, hit.Preview, nil}) + } + } + return marshalResult(struct { + Matches []any `json:"matches"` + NextCursor *string `json:"nextCursor"` + IsTruncated bool `json:"isTruncated"` + Source string `json:"source"` + }{matches, page.NextCursor, page.IsTruncated, page.Source}) +} diff --git a/desktop/internal/pluginservice/hostworkspacefind_test.go b/desktop/internal/pluginservice/hostworkspacefind_test.go new file mode 100644 index 000000000..3c7fd0104 --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspacefind_test.go @@ -0,0 +1,74 @@ +package pluginservice + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestWorkspaceSearchPublishesDiskResourcesAndContinuation(t *testing.T) { + service := openHostService(t) + if err := service.AttachWorkbench(diskReadWorkbench{&fakeWorkbench{}, core.NewClient()}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + for _, name := range []string{"a.txt", "b.txt"} { + if err := os.WriteFile(filepath.Join(root, name), []byte("alpha\nBETA\n"), 0o600); err != nil { + t.Fatal(err) + } + } + workspace := service.Contexts.Open(root) + t.Cleanup(func() { service.Contexts.Close(root) }) + rootID := service.Contexts.RootID("a", root) + request := map[string]any{"context": workspace.ContextRef, "resource": Resource{rootID, ""}, "query": ".txt", "limit": 1} + var paths []string + for range 2 { + body, _ := json.Marshal(request) + result, refusal := respond(t, service, "a", "workspace/findFiles", string(body)) + var page struct { + Matches []Resource + NextCursor *string + Source string + IsTruncated bool + } + if err := json.Unmarshal(result, &page); err != nil || refusal != nil || len(page.Matches) != 1 || page.Source != "disk" || page.IsTruncated { + t.Fatalf("page = %s, %+v, %v", result, refusal, err) + } + if page.Matches[0].RootID != rootID { + t.Fatalf("resource = %+v", page.Matches[0]) + } + paths = append(paths, page.Matches[0].Path) + request["cursor"] = page.NextCursor + } + if paths[0] != "a.txt" || paths[1] != "b.txt" { + t.Fatalf("paths = %v", paths) + } + text := map[string]any{"context": workspace.ContextRef, "resource": Resource{rootID, ""}, "pattern": "beta", "fileMask": "a.*", "wholeWords": true} + body, _ := json.Marshal(text) + result, refusal := respond(t, service, "a", "workspace/findText", string(body)) + var page struct { + Matches []struct { + Resource Resource + Line int + Preview string + Range json.RawMessage + } + } + if err := json.Unmarshal(result, &page); err != nil || refusal != nil || len(page.Matches) != 1 { + t.Fatalf("text = %s, %+v, %v", result, refusal, err) + } + if hit := page.Matches[0]; hit.Resource != (Resource{rootID, "a.txt"}) || hit.Line != 2 || hit.Preview != "BETA" || string(hit.Range) != "null" { + t.Fatalf("hit = %+v", hit) + } + text["pattern"], text["regularExpression"] = "[", true + body, _ = json.Marshal(text) + if _, refusal := respond(t, service, "a", "workspace/findText", string(body)); refusal == nil || refusal.Code != codeInvalidParams { + t.Fatalf("invalid regex = %+v", refusal) + } + if _, refusal := respond(t, service, "b", "workspace/findText", string(body)); refusal == nil || refusal.Code != codeInvalidParams { + t.Fatalf("foreign root = %+v", refusal) + } +} diff --git a/desktop/internal/pluginservice/hostworkspaceread.go b/desktop/internal/pluginservice/hostworkspaceread.go new file mode 100644 index 000000000..824876e95 --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspaceread.go @@ -0,0 +1,136 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +const ( + methodWorkspaceReadDirectory = pluginhost.MethodPrefix + "workspace/readDirectory" + methodWorkspaceStat = pluginhost.MethodPrefix + "workspace/stat" + methodWorkspaceReadFile = pluginhost.MethodPrefix + "workspace/readFile" +) + +// WorkspaceReadHost bridges authorized workspace reads to Core off the UI thread. +// Core owns paths, no-follow traversal, visibility, pagination and byte limits. +type WorkspaceReadHost interface { + ReadDirectory(context.Context, core.WorkspaceDirectoryRequest) (core.WorkspaceDirectoryPage, error) + StatEntry(ctx context.Context, root, path string) (core.WorkspaceStat, error) + ReadFile(ctx context.Context, root, path string, maximumBytes *int) (core.WorkspaceFileRead, error) +} + +func (s *Service) registerWorkspaceReads(host WorkspaceReadHost) error { + for _, method := range []string{methodWorkspaceReadDirectory, methodWorkspaceStat, methodWorkspaceReadFile} { + if err := s.HostServices.Register(method, func(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + return s.handleWorkspaceRead(ctx, host, method, params) + }); err != nil { + return err + } + } + return nil +} + +func (s *Service) handleWorkspaceRead(ctx context.Context, host WorkspaceReadHost, method string, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + // The session's Core router already validated the method-specific fields. + var request struct { + Context ContextRef `json:"context"` + Resource Resource `json:"resource"` + Cursor *string `json:"cursor"` + Limit *int `json:"limit"` + MaximumBytes *int `json:"maximumBytes"` + } + if err := decodeStrict(params, &request); err != nil { + return nil, invalidParams(err) + } + caller, workspace, refusal := s.workspaceRequest(ctx, request.Context) + if refusal != nil { + return nil, refusal + } + if refusal := s.checkRoot(caller.PluginID, workspace, request.Resource); refusal != nil { + return nil, refusal + } + var result any + switch method { + case methodWorkspaceReadDirectory: + page, err := host.ReadDirectory(ctx, core.WorkspaceDirectoryRequest{Root: workspace.Path, Path: request.Resource.Path, Cursor: request.Cursor, Limit: request.Limit}) + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + type entry struct { + Name string `json:"name"` + Resource Resource `json:"resource"` + Kind string `json:"kind"` + } + entries := make([]entry, 0, len(page.Entries)) + for _, child := range page.Entries { + entries = append(entries, entry{child.Name, Resource{request.Resource.RootID, child.Path}, child.Kind}) + } + result = struct { + Entries []entry `json:"entries"` + NextCursor *string `json:"nextCursor"` + }{entries, page.NextCursor} + case methodWorkspaceStat: + stat, err := host.StatEntry(ctx, workspace.Path, request.Resource.Path) + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + result = struct { + Resource Resource `json:"resource"` + Kind string `json:"kind"` + Size uint64 `json:"size"` + ModifiedMilliseconds *uint64 `json:"modifiedMilliseconds"` + }{request.Resource, stat.Kind, stat.Size, stat.ModifiedMilliseconds} + case methodWorkspaceReadFile: + file, err := host.ReadFile(ctx, workspace.Path, request.Resource.Path, request.MaximumBytes) + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + result = struct { + Resource Resource `json:"resource"` + Source string `json:"source"` + ByteCount int `json:"byteCount"` + IsTruncated bool `json:"isTruncated"` + Identity core.WorkspaceReadIdentity `json:"identity"` + Text *string `json:"text,omitempty"` + Encoding *string `json:"encoding,omitempty"` + Base64 *string `json:"base64,omitempty"` + }{request.Resource, file.Source, file.ByteCount, file.IsTruncated, file.Identity, file.Text, file.Encoding, file.Base64} + } + // A window may close or replace the context while Core reads. Never publish + // the old request under a newly opened context with the same root. + if _, err := s.Contexts.Lookup(request.Context); err != nil { + return nil, contextFailure(err) + } + if err := ctx.Err(); err != nil { + return nil, hostFailureOf(err) + } + return marshalResult(result) +} + +// WorkspaceReadError maps Core failures without turning access failures into bad params. +func WorkspaceReadError(err error) error { + var hostErr *HostError + var coreErr *core.Error + switch { + case err == nil, errors.As(err, &hostErr), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + return err + case errors.As(err, &coreErr): + code := CodeFailed + switch coreErr.Code { + case core.CodeEntryNotFound, core.CodeWorkspaceNotFound: + code = CodeNotFound + case core.CodeInvalidRequest, core.CodeParseFailed: + code = codeInvalidParams + case core.CodePermissionDenied: + code = CodePermissionDenied + case core.CodeNotSupported: + code = codeAuthorityUnsupported + } + return &HostError{Code: code, Message: coreErr.Message} + } + return &HostError{Code: CodeFailed, Message: "The workspace read failed."} +} diff --git a/desktop/internal/pluginservice/hostworkspaceread_test.go b/desktop/internal/pluginservice/hostworkspaceread_test.go new file mode 100644 index 000000000..737a0ca50 --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspaceread_test.go @@ -0,0 +1,132 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +// diskReadWorkbench delegates reads to the actual Core, with only the UI surface replaced. +type diskReadWorkbench struct { + *fakeWorkbench + kernel *core.Client +} + +func (w diskReadWorkbench) ReadDirectory(ctx context.Context, request core.WorkspaceDirectoryRequest) (core.WorkspaceDirectoryPage, error) { + return w.kernel.ReadWorkspaceDirectory(ctx, request) +} + +func (w diskReadWorkbench) StatEntry(ctx context.Context, root, path string) (core.WorkspaceStat, error) { + return w.kernel.StatWorkspaceEntry(ctx, root, path) +} + +func (w diskReadWorkbench) ReadFile(ctx context.Context, root, path string, maximumBytes *int) (core.WorkspaceFileRead, error) { + return w.kernel.ReadWorkspaceFile(ctx, root, path, maximumBytes) +} + +func (w diskReadWorkbench) FindFiles(ctx context.Context, request core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) { + return w.kernel.FindWorkspaceFiles(ctx, request) +} + +func (w diskReadWorkbench) FindText(ctx context.Context, request core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) { + return w.kernel.FindWorkspaceText(ctx, request) +} + +func (w diskReadWorkbench) PlanWatch(ctx context.Context, root, path string, recursive bool) (core.WorkspaceWatchPlan, error) { + return w.kernel.PlanWorkspaceWatch(ctx, root, path, recursive) +} + +func (w diskReadWorkbench) FilterWatchEvents(ctx context.Context, _ string, plan core.WorkspaceWatchPlan, paths []string, rescan bool) (core.WorkspaceWatchEvents, error) { + return w.kernel.FilterWorkspaceWatchEvents(ctx, plan, paths, rescan) +} + +func TestWorkspaceReadsUseCoreAndPreservePublicResourceEnvelopes(t *testing.T) { + service := openHostService(t) + if err := service.AttachWorkbench(diskReadWorkbench{&fakeWorkbench{}, core.NewClient()}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "a.txt"), []byte("disk"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "binary"), []byte{0, 255}, 0o600); err != nil { + t.Fatal(err) + } + workspace := service.Contexts.Open(root) + t.Cleanup(func() { service.Contexts.Close(workspace.Path) }) + rootID := service.Contexts.RootID("a", workspace.Path) + call := func(plugin, method, path, extra string) (map[string]json.RawMessage, *pluginhost.Failure) { + t.Helper() + body, _ := json.Marshal(map[string]any{"context": workspace.ContextRef, "resource": Resource{rootID, path}}) + if extra != "" { + body = append(body[:len(body)-1], []byte(","+extra+"}")...) + } + result, refusal := respond(t, service, plugin, "workspace/"+method, string(body)) + var value map[string]json.RawMessage + if refusal == nil { + if err := json.Unmarshal(result, &value); err != nil { + t.Fatal(err) + } + } + return value, refusal + } + file, refusal := call("a", "readFile", "a.txt", "") + if refusal != nil || string(file["text"]) != `"disk"` || string(file["source"]) != `"disk"` || file["path"] != nil { + t.Fatalf("file = %s, %+v", file, refusal) + } + var resource Resource + if err := json.Unmarshal(file["resource"], &resource); err != nil || resource != (Resource{rootID, "a.txt"}) { + t.Fatalf("resource = %+v, %v", resource, err) + } + binary, refusal := call("a", "readFile", "binary", "") + if refusal != nil || string(binary["base64"]) != `"AP8="` || binary["text"] != nil { + t.Fatalf("binary = %s, %+v", binary, refusal) + } + stat, refusal := call("a", "stat", "a.txt", "") + if refusal != nil || string(stat["size"]) != "4" || stat["path"] != nil { + t.Fatalf("stat = %s, %+v", stat, refusal) + } + page, refusal := call("a", "readDirectory", "", `"limit":1`) + var entries []struct { + Name string + Resource Resource + } + if err := json.Unmarshal(page["entries"], &entries); err != nil || refusal != nil || len(entries) != 1 || entries[0].Resource != (Resource{rootID, "a.txt"}) || string(page["nextCursor"]) == "null" { + t.Fatalf("directory = %s, %+v, %v", page, refusal, err) + } + for _, test := range []struct{ method, path, extra, code string }{ + {"readFile", "missing", "", CodeNotFound}, + {"readFile", "../outside", "", codeInvalidParams}, + {"readFile", "a.txt", `"maximumBytes":131073`, codeInvalidParams}, + } { + if _, refusal := call("a", test.method, test.path, test.extra); refusal == nil || refusal.Code != test.code { + t.Fatalf("%+v = %+v", test, refusal) + } + } + if _, refusal := call("b", "readFile", "a.txt", ""); refusal == nil || refusal.Code != codeInvalidParams { + t.Fatalf("another plugin's root = %+v", refusal) + } + service.Contexts.Close(workspace.Path) + if _, refusal := call("a", "stat", "a.txt", ""); refusal == nil || refusal.Code != CodeContextExpired { + t.Fatalf("closed context = %+v", refusal) + } +} + +func TestWorkspaceReadsAreAdvertisedOnlyWithAnAttachedReadHost(t *testing.T) { + service := openHostService(t) + methods := []string{methodWorkspaceReadDirectory, methodWorkspaceStat, methodWorkspaceReadFile, methodWorkspaceFindFiles, methodWorkspaceFindText, methodWorkspaceWatch} + if grants := pluginhost.GrantServices(methods, service.HostServices); len(grants) != 0 { + t.Fatalf("windowless grants = %v", grants) + } + if err := service.AttachWorkbench(diskReadWorkbench{&fakeWorkbench{}, core.NewClient()}); err != nil { + t.Fatal(err) + } + if grants := pluginhost.GrantServices(methods, service.HostServices); len(grants) != len(methods) { + t.Fatalf("attached grants = %v", grants) + } +} diff --git a/desktop/internal/pluginservice/hostworkspacewatch.go b/desktop/internal/pluginservice/hostworkspacewatch.go new file mode 100644 index 000000000..8f5e7df89 --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspacewatch.go @@ -0,0 +1,234 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/vivaui/viva/app" +) + +const methodWorkspaceWatch = pluginhost.MethodPrefix + "workspace/watch" + +// WorkspaceWatchHost delegates watch scope and event projection to Core. +// root remains the window's context path even if Core canonicalizes plan.Root. +type WorkspaceWatchHost interface { + PlanWatch(context.Context, string, string, bool) (core.WorkspaceWatchPlan, error) + FilterWatchEvents(context.Context, string, core.WorkspaceWatchPlan, []string, bool) (core.WorkspaceWatchEvents, error) +} + +// workspaceWatch serializes delivery with disposal. Cancelling before taking mu +// also interrupts a notification already waiting for Core's bounded queue. +type workspaceWatch struct { + mu sync.Mutex + closed bool + native *app.DirectoryWatch + cancel context.CancelFunc +} + +func (w *workspaceWatch) stop() { + w.cancel() + w.mu.Lock() + defer w.mu.Unlock() + w.closed = true + if w.native != nil { + w.native.Close() + w.native = nil + } +} + +func (s *Service) registerWorkspaceWatch(host WorkspaceWatchHost) error { + return s.HostServices.Register(methodWorkspaceWatch, func(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + return s.handleWorkspaceWatch(ctx, host, params) + }) +} + +func (s *Service) handleWorkspaceWatch(ctx context.Context, host WorkspaceWatchHost, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + var request struct { + Context ContextRef `json:"context"` + Resource Resource `json:"resource"` + Recursive bool `json:"recursive"` + } + if err := decodeStrict(params, &request); err != nil { + return nil, invalidParams(err) + } + caller, workspace, refusal := s.workspaceRequest(ctx, request.Context) + if refusal != nil { + return nil, refusal + } + if refusal := s.checkRoot(caller.PluginID, workspace, request.Resource); refusal != nil { + return nil, refusal + } + _, session, refusal := s.buildCaller(ctx) + if refusal != nil { + return nil, refusal + } + if session.isEnded() { + return nil, failure(pluginhost.CodeCancelled, "The requesting backend session ended.") + } + plan, err := host.PlanWatch(ctx, workspace.Path, request.Resource.Path, request.Recursive) + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + lifetime, cancel := context.WithCancel(context.WithoutCancel(ctx)) + watch := &workspaceWatch{cancel: cancel} + id := s.resources.addLimited(caller, workspace.ContextID, watch.stop, maxBuildConfigurationWatches) + if id == "" { + watch.stop() + return nil, failure("plugin.host.limitExceeded", "The backend has reached its native subscription limit.") + } + accepted := false + defer func() { + if !accepted { + s.resources.dispose(caller, id) + } + }() + stopRequest := context.AfterFunc(ctx, watch.stop) + defer stopRequest() + wake := make(chan struct{}, 1) + signal := func() { + select { + case wake <- struct{}{}: + default: + } + } + // The native stream follows the whole root, including ancestor replacement. + // Only raw identity facts are checked here; Core decides scope and visibility. + rootBefore, err := os.Stat(plan.Root) + if err != nil { + return nil, s.workspaceWatchFailure(ctx, err) + } + target := filepath.Join(plan.Root, filepath.FromSlash(plan.Path)) + targetBefore, err := os.Stat(target) + if err != nil { + return nil, s.workspaceWatchFailure(ctx, err) + } + native, err := app.WatchTree(plan.Root, nil, signal) + if err != nil { + return nil, s.workspaceWatchFailure(ctx, err) + } + watch.mu.Lock() + if watch.closed { + native.Close() + } else { + watch.native = native + } + watch.mu.Unlock() + confirmed, err := host.PlanWatch(ctx, workspace.Path, request.Resource.Path, request.Recursive) + if err != nil { + return nil, hostFailureOf(WorkspaceReadError(err)) + } + rootAfter, rootErr := os.Stat(plan.Root) + targetAfter, targetErr := os.Stat(target) + if rootErr != nil { + return nil, s.workspaceWatchFailure(ctx, rootErr) + } + if targetErr != nil { + return nil, s.workspaceWatchFailure(ctx, targetErr) + } + if confirmed != plan || !os.SameFile(rootBefore, rootAfter) || !os.SameFile(targetBefore, targetAfter) { + return nil, s.workspaceWatchFailure(ctx, errors.New("workspace locations changed during watch registration")) + } + if _, err := s.Contexts.Lookup(request.Context); err != nil { + return nil, contextFailure(err) + } + if session.isEnded() || lifetime.Err() != nil || ctx.Err() != nil { + return nil, failure(pluginhost.CodeCancelled, "The workspace watch request ended.") + } + // A successful registration owns its lifetime independently of the request. + // The initial rescan closes changes between validation and native registration. + accepted = true + go func() { + defer s.resources.dispose(caller, id) + sequence := uint64(1) + if !s.sendWorkspaceWatch(lifetime, watch, session, request.Context, caller, id, request.Resource.RootID, sequence, core.WorkspaceWatchEvents{ChangedPaths: []string{}, RequiresRescan: true}) { + return + } + var names []string + for { + select { + case <-lifetime.Done(): + return + case <-wake: + } + changes := native.Changes(names[:0]) + names = changes.Names + currentRoot, err := os.Stat(plan.Root) + if err != nil || !os.SameFile(rootBefore, currentRoot) { + if err != nil && !errors.Is(err, os.ErrNotExist) && lifetime.Err() == nil && s.WorkspaceWatchIssue != nil { + s.WorkspaceWatchIssue(lifetime, err) + } + // log-exempt: 预期的缺失:被删除或替换的根不能继续使用旧原生事件流。 + sequence++ + s.sendWorkspaceWatch(lifetime, watch, session, request.Context, caller, id, request.Resource.RootID, sequence, core.WorkspaceWatchEvents{ChangedPaths: []string{}, RequiresRescan: true}) + return + } + events, err := host.FilterWatchEvents(lifetime, workspace.Path, plan, names, changes.Resync) + if err != nil { + // log-exempt: 同一次失败已经记录过:Core/Workbench records rejected event projection. + if lifetime.Err() == nil { + sequence++ + s.sendWorkspaceWatch(lifetime, watch, session, request.Context, caller, id, request.Resource.RootID, sequence, core.WorkspaceWatchEvents{ChangedPaths: []string{}, RequiresRescan: true}) + } + return + } + if len(events.ChangedPaths) == 0 && !events.RequiresRescan { + continue + } + sequence++ + if !s.sendWorkspaceWatch(lifetime, watch, session, request.Context, caller, id, request.Resource.RootID, sequence, events) { + return + } + } + }() + return marshalResult(map[string]string{"subscriptionID": id}) +} + +func (s *Service) workspaceWatchFailure(ctx context.Context, err error) *pluginhost.Failure { + if s.WorkspaceWatchIssue != nil { + s.WorkspaceWatchIssue(ctx, err) + } + switch { + case errors.Is(err, os.ErrNotExist): + return failure(CodeNotFound, "The workspace watch target no longer exists.") + case errors.Is(err, os.ErrPermission): + return failure(CodePermissionDenied, "The workspace watch target is not accessible.") + case errors.Is(err, app.ErrUnsupported): + return failure(codeAuthorityUnsupported, "Native workspace watches are unavailable.") + case errors.Is(err, app.ErrWatchTooLarge): + return failure("plugin.host.limitExceeded", "The workspace tree exceeds the native watch limit.") + default: + return failure(CodeFailed, "The workspace could not be watched.") + } +} + +func (s *Service) sendWorkspaceWatch(parent context.Context, watch *workspaceWatch, session *BackendSession, ref ContextRef, caller pluginhost.Caller, id, rootID string, sequence uint64, events core.WorkspaceWatchEvents) bool { + watch.mu.Lock() + defer watch.mu.Unlock() + if watch.closed || parent.Err() != nil || session.isEnded() { + return false + } + if _, err := s.Contexts.Lookup(ref); err != nil { + // log-exempt: 用户取消:关闭的工作区不再接收监听通知。 + return false + } + ctx, cancel := context.WithTimeout(parent, 5*time.Second) + defer cancel() + params, _ := json.Marshal(map[string]any{ + "subscriptionID": id, "sequence": sequence, + "event": map[string]any{"rootID": rootID, "changedPaths": events.ChangedPaths, "requiresRescan": events.RequiresRescan}, + }) + // Core records lsp.hostNotify's terminal outcome at the request boundary. + sent, err := s.kernel.SendPluginHostNotification(ctx, caller.SessionID, notifySubscription, params) + if err != nil || !sent { + // log-exempt: 同一次失败已经记录过:Core records delivery failure; session closure is cancellation. + return false + } + return true +} diff --git a/desktop/internal/pluginservice/hostworkspacewatch_test.go b/desktop/internal/pluginservice/hostworkspacewatch_test.go new file mode 100644 index 000000000..8baf99861 --- /dev/null +++ b/desktop/internal/pluginservice/hostworkspacewatch_test.go @@ -0,0 +1,206 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestWorkspaceWatchUsesNativeEventsAndReleasesOwnedSubscriptions(t *testing.T) { + for _, ending := range []string{"dispose", "context", "session", "root-replacement"} { + t.Run(ending, func(t *testing.T) { + kernel := &buildWatchKernel{events: make(chan buildWatchNotification, 32)} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := service.AttachWorkbench(diskReadWorkbench{&fakeWorkbench{}, core.NewClient()}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "src"), 0o700); err != nil { + t.Fatal(err) + } + workspace := service.Contexts.Open(root) + t.Cleanup(func() { service.Contexts.Close(root) }) + const plugin = "dev.lithe.test.workspace-watch" + session := runningActionSession(service, plugin, "workspace-watch-session") + caller := pluginhost.Caller{PluginID: plugin, SessionID: session.Session.ID} + ctx, cancel := context.WithTimeout(pluginhost.WithCaller(context.Background(), caller), 8*time.Second) + defer cancel() + rootID := service.Contexts.RootID(plugin, root) + body, _ := json.Marshal(map[string]any{"context": workspace.ContextRef, "resource": Resource{rootID, ""}, "recursive": true}) + result, refusal := service.HostServices.Respond(ctx, methodWorkspaceWatch, body) + var subscription struct{ SubscriptionID string } + if err := json.Unmarshal(result, &subscription); err != nil || refusal != nil || subscription.SubscriptionID == "" { + t.Fatalf("registration = %s, %+v, %v", result, refusal, err) + } + id := subscription.SubscriptionID + defer service.resources.dispose(caller, id) + released := make(chan struct{}) + service.resources.mu.Lock() + release := service.resources.byID[id].dispose + service.resources.byID[id].dispose = func() { + release() + close(released) + } + service.resources.mu.Unlock() + var sequence uint64 + await := func(operation, path string) { + t.Helper() + for { + select { + case notification := <-kernel.events: + var value struct { + SubscriptionID string + Sequence uint64 + Event struct { + RootID string + ChangedPaths []string + RequiresRescan bool + } + } + if err := json.Unmarshal(notification.body, &value); err != nil || notification.session != session.Session.ID || notification.method != notifySubscription || value.SubscriptionID != id || value.Sequence <= sequence || value.Event.RootID != rootID { + t.Fatalf("%s notification = %+v, %v", operation, notification, err) + } + sequence = value.Sequence + if path == "" && value.Event.RequiresRescan { + return + } + if path != "" && (value.Event.RequiresRescan || slices.Contains(value.Event.ChangedPaths, path) || slices.Contains(value.Event.ChangedPaths, "src")) { + return + } + case <-ctx.Done(): + t.Fatalf("%s did not reach the native watch: %v", operation, ctx.Err()) + } + } + } + await("initial rescan", "") + if sequence != 1 { + t.Fatalf("initial sequence = %d, want 1", sequence) + } + // Disposal is scoped to the plugin and exact backend session. + service.resources.dispose(pluginhost.Caller{PluginID: plugin, SessionID: "replacement-session"}, id) + file := filepath.Join(root, "src", "a.txt") + if err := os.WriteFile(file, []byte("first"), 0o600); err != nil { + t.Fatal(err) + } + await("nested creation", "src/a.txt") + staging := filepath.Join(root, "src", "next") + if err := os.WriteFile(staging, []byte("saved"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(staging, file); err != nil { + t.Fatal(err) + } + await("atomic replacement", "src/a.txt") + if err := os.Remove(file); err != nil { + t.Fatal(err) + } + await("deletion", "src/a.txt") + switch ending { + case "dispose": + params, _ := json.Marshal(map[string]string{"subscriptionID": id}) + if _, refusal := service.HostServices.Respond(ctx, pluginhost.MethodPrefix+"subscriptions/dispose", params); refusal != nil { + t.Fatal(refusal) + } + case "context": + service.Contexts.Close(root) + case "session": + service.resources.releaseSession(session.Session.ID) + case "root-replacement": + // Reusing the same path must not keep the old directory's stream alive. + if err := os.Rename(root, filepath.Join(t.TempDir(), "old-root")); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatal(err) + } + await("root replacement rescan", "") + } + select { + case <-released: + case <-ctx.Done(): + t.Fatalf("%s did not release its native stream: %v", ending, ctx.Err()) + } + service.resources.mu.Lock() + remaining := len(service.resources.byID) + service.resources.mu.Unlock() + if remaining != 0 { + t.Fatalf("%s left %d native subscriptions", ending, remaining) + } + }) + } +} + +type blockedWorkspaceNotification struct { + fakeKernel + started chan struct{} + finished chan struct{} +} + +func (k *blockedWorkspaceNotification) SendPluginHostNotification(ctx context.Context, _, _ string, _ json.RawMessage) (bool, error) { + close(k.started) + defer close(k.finished) + <-ctx.Done() // Production gives every notification a five-second deadline. + return false, ctx.Err() +} + +func TestWorkspaceWatchDisposeCancelsAnInFlightNotification(t *testing.T) { + kernel := &blockedWorkspaceNotification{started: make(chan struct{}), finished: make(chan struct{})} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := service.AttachWorkbench(diskReadWorkbench{&fakeWorkbench{}, core.NewClient()}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + workspace := service.Contexts.Open(root) + defer service.Contexts.Close(root) + const plugin = "dev.lithe.test.workspace-watch-cancel" + session := runningActionSession(service, plugin, "workspace-watch-cancel-session") + caller := pluginhost.Caller{PluginID: plugin, SessionID: session.Session.ID} + ctx, cancel := context.WithTimeout(pluginhost.WithCaller(context.Background(), caller), 8*time.Second) + defer cancel() + body, _ := json.Marshal(map[string]any{"context": workspace.ContextRef, "resource": Resource{service.Contexts.RootID(plugin, root), ""}}) + // Check the shared per-session native limit before allocating an OS stream. + var placeholders []string + for range maxBuildConfigurationWatches { + placeholders = append(placeholders, service.resources.addLimited(caller, workspace.ContextID, nil, maxBuildConfigurationWatches)) + } + if _, refusal := service.HostServices.Respond(ctx, methodWorkspaceWatch, body); refusal == nil || refusal.Code != "plugin.host.limitExceeded" { + t.Fatalf("limit = %+v", refusal) + } + for _, id := range placeholders { + service.resources.dispose(caller, id) + } + result, refusal := service.HostServices.Respond(ctx, methodWorkspaceWatch, body) + var subscription struct{ SubscriptionID string } + if err := json.Unmarshal(result, &subscription); refusal != nil || err != nil || subscription.SubscriptionID == "" { + t.Fatalf("registration = %s, %+v, %v", result, refusal, err) + } + id := subscription.SubscriptionID + defer service.resources.dispose(caller, id) + select { + case <-kernel.started: + case <-ctx.Done(): + t.Fatal("initial notification did not start") + } + service.resources.dispose(caller, id) + // Disposal waits for the current delivery and closes the native registration. + select { + case <-kernel.finished: + default: + t.Fatal("dispose returned while a notification was still active") + } + service.resources.dispose(caller, id) +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index 585047cb9..80a0dd4f9 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -71,6 +71,8 @@ type Service struct { ToolchainIssue func(context.Context, error) // BuildConfigurationIssue records native failures opening or rebinding configuration watches. BuildConfigurationIssue func(context.Context, error) + // WorkspaceWatchIssue records native failures establishing or maintaining a workspace stream. + WorkspaceWatchIssue func(context.Context, error) // providers2 holds the editor provider registrations of the window (hostproviders.go). providers2 *editorProviderBindings // actions holds the editor action registrations of the window (hostactions.go). diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 321c4f87b..b17e01985 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -54,6 +54,7 @@ import ( // the calls that read the disk or run Git, so a screen can be checked against answers the // test chooses. type Kernel interface { + workspaceReadKernel CLIOpenTarget(context.Context, string) (core.CLITarget, error) ReadSourceSettings(context.Context, json.RawMessage) (core.SourceSettingsState, error) PlanSourceSettingsEdits(context.Context, core.SourceSettingsSnapshot, []core.SourceSettingsEdits, bool) ([]core.SourceSettingsWrite, error) @@ -1141,6 +1142,9 @@ func (a *App) openPlugins(options Options) { service.BuildConfigurationIssue = func(ctx context.Context, err error) { a.backgroundFailedIn(ctx, "plugin_build_configuration_watch", documentLogError(err)) } + service.WorkspaceWatchIssue = func(ctx context.Context, err error) { + a.backgroundFailedIn(ctx, "plugin_workspace_watch", documentLogError(err)) + } service.RuntimeIssue = a.recordPluginRuntimeIssue service.SetRuntimeLanguage(a.language().Code()) if err := service.AttachWorkbench(pluginWorkbench{app: a}); err != nil { diff --git a/desktop/internal/workbench/pluginworkspaceread.go b/desktop/internal/workbench/pluginworkspaceread.go new file mode 100644 index 000000000..bfcafa15f --- /dev/null +++ b/desktop/internal/workbench/pluginworkspaceread.go @@ -0,0 +1,116 @@ +package workbench + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// workspaceReadKernel is the API-06/07/08 part of the shared kernel. +type workspaceReadKernel interface { + ReadWorkspaceDirectory(context.Context, core.WorkspaceDirectoryRequest) (core.WorkspaceDirectoryPage, error) + StatWorkspaceEntry(context.Context, string, string) (core.WorkspaceStat, error) + ReadWorkspaceFile(context.Context, string, string, *int) (core.WorkspaceFileRead, error) + FindWorkspaceFiles(context.Context, core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) + FindWorkspaceText(context.Context, core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) + PlanWorkspaceWatch(context.Context, string, string, bool) (core.WorkspaceWatchPlan, error) + FilterWorkspaceWatchEvents(context.Context, core.WorkspaceWatchPlan, []string, bool) (core.WorkspaceWatchEvents, error) +} + +var _ pluginservice.WorkspaceReadHost = pluginWorkbench{} +var _ pluginservice.WorkspaceFindHost = pluginWorkbench{} +var _ pluginservice.WorkspaceWatchHost = pluginWorkbench{} + +// readWorkspace captures window-owned state, reads on the calling host goroutine, +// and checks the same project before publishing. Project closure and host request +// cancellation both cancel Core; no I/O runs on the window thread. +func readWorkspace[T any](w pluginWorkbench, ctx context.Context, root, operation string, read func(context.Context, workspaceReadKernel) (T, error)) (T, error) { + type scope struct { + project *project + kernel workspaceReadKernel + ctx context.Context + } + var zero T + state, err := onWindow(w.app, ctx, func(a *App) (scope, error) { + p, err := a.localProjectAt(root) + if err != nil { + return scope{}, err + } + if a.kernel == nil { + return scope{}, hostError(pluginservice.CodeFailed, "The window has no kernel.") + } + return scope{p, a.kernel, a.operationContext(ctx)}, nil + }) + if err != nil { + return zero, err + } + readCtx, cancel := context.WithTimeout(state.ctx, 30*time.Second) + defer cancel() + stop := context.AfterFunc(state.project.ctx, cancel) + defer stop() + result, readErr := read(readCtx, state.kernel) + return onWindow(w.app, ctx, func(a *App) (T, error) { + if a.project != state.project || state.project.ctx.Err() != nil { + return zero, hostError(pluginservice.CodeContextExpired, "The workspace is no longer open.") + } + if readErr != nil { + mapped := pluginservice.WorkspaceReadError(readErr) + var refusal *pluginservice.HostError + if errors.As(mapped, &refusal) && refusal.Code != pluginservice.CodeFailed { + a.operationRejectedIn(state.ctx, operation, strings.TrimPrefix(refusal.Code, "plugin.host.")) + } else if !errors.Is(mapped, context.Canceled) { + a.operationFailedIn(state.ctx, operation, documentLogError(readErr)) + } else { + // log-exempt: 用户取消:请求结束后不再发布磁盘读取结果。 + } + return zero, mapped + } + return result, nil + }) +} + +func (w pluginWorkbench) ReadDirectory(ctx context.Context, request core.WorkspaceDirectoryRequest) (core.WorkspaceDirectoryPage, error) { + return readWorkspace(w, ctx, request.Root, "plugin_directory_read", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceDirectoryPage, error) { + return kernel.ReadWorkspaceDirectory(ctx, request) + }) +} + +func (w pluginWorkbench) StatEntry(ctx context.Context, root, path string) (core.WorkspaceStat, error) { + return readWorkspace(w, ctx, root, "plugin_entry_stat", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceStat, error) { + return kernel.StatWorkspaceEntry(ctx, root, path) + }) +} + +func (w pluginWorkbench) ReadFile(ctx context.Context, root, path string, maximumBytes *int) (core.WorkspaceFileRead, error) { + return readWorkspace(w, ctx, root, "plugin_file_read", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceFileRead, error) { + return kernel.ReadWorkspaceFile(ctx, root, path, maximumBytes) + }) +} + +func (w pluginWorkbench) FindFiles(ctx context.Context, request core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) { + return readWorkspace(w, ctx, request.Root, "plugin_find_files", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceFindPage, error) { + return kernel.FindWorkspaceFiles(ctx, request) + }) +} + +func (w pluginWorkbench) FindText(ctx context.Context, request core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) { + return readWorkspace(w, ctx, request.Root, "plugin_find_text", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceFindPage, error) { + return kernel.FindWorkspaceText(ctx, request) + }) +} + +func (w pluginWorkbench) PlanWatch(ctx context.Context, root, path string, recursive bool) (core.WorkspaceWatchPlan, error) { + return readWorkspace(w, ctx, root, "plugin_workspace_watch", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceWatchPlan, error) { + return kernel.PlanWorkspaceWatch(ctx, root, path, recursive) + }) +} + +func (w pluginWorkbench) FilterWatchEvents(ctx context.Context, root string, plan core.WorkspaceWatchPlan, paths []string, rescan bool) (core.WorkspaceWatchEvents, error) { + return readWorkspace(w, ctx, root, "plugin_workspace_watch_events", func(ctx context.Context, kernel workspaceReadKernel) (core.WorkspaceWatchEvents, error) { + return kernel.FilterWorkspaceWatchEvents(ctx, plan, paths, rescan) + }) +} diff --git a/desktop/internal/workbench/pluginworkspaceread_test.go b/desktop/internal/workbench/pluginworkspaceread_test.go new file mode 100644 index 000000000..2940aa687 --- /dev/null +++ b/desktop/internal/workbench/pluginworkspaceread_test.go @@ -0,0 +1,118 @@ +package workbench + +import ( + "context" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +func TestPluginWorkspaceReadsUseDiskWhileTheLiveDocumentIsDirty(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + root, d := openNote(t, h, "alpha") + pluginEdit(t, h, root, d, "ALPHA") + w := pluginWorkbench{app: h.app} + file, err := callOnWindow(h, "read disk", func(ctx context.Context) (core.WorkspaceFileRead, error) { + return w.ReadFile(ctx, root, "note.txt", nil) + }) + if err != nil || file.Text == nil || *file.Text != "alpha" || file.Source != "disk" || file.IsTruncated { + t.Fatalf("read = %+v, %v", file, err) + } + if text, _ := d.view.Text(); string(text) != "ALPHA" || !d.dirty() { + t.Fatal("reading disk changed the live document") + } + search, err := callOnWindow(h, "search disk", func(ctx context.Context) (core.WorkspaceFindPage, error) { + return w.FindText(ctx, core.WorkspaceFindRequest{Root: root, Pattern: "alpha", CaseSensitive: true}) + }) + if err != nil || len(search.Matches) != 1 || search.Matches[0].Preview != "alpha" || search.Source != "disk" { + t.Fatalf("search = %+v, %v", search, err) + } + plan, err := callOnWindow(h, "plan watch", func(ctx context.Context) (core.WorkspaceWatchPlan, error) { + return w.PlanWatch(ctx, root, "note.txt", false) + }) + if err != nil { + t.Fatal(err) + } + events, err := callOnWindow(h, "project watch event", func(ctx context.Context) (core.WorkspaceWatchEvents, error) { + return w.FilterWatchEvents(ctx, root, plan, []string{"note.txt", "other.txt"}, false) + }) + if err != nil || len(events.ChangedPaths) != 1 || events.ChangedPaths[0] != "note.txt" || events.RequiresRescan { + t.Fatalf("events = %+v, %v", events, err) + } + stat, err := callOnWindow(h, "stat disk", func(ctx context.Context) (core.WorkspaceStat, error) { + return w.StatEntry(ctx, root, "note.txt") + }) + if err != nil || stat.Kind != "file" || stat.Size != 5 { + t.Fatalf("stat = %+v, %v", stat, err) + } + page, err := callOnWindow(h, "list disk", func(ctx context.Context) (core.WorkspaceDirectoryPage, error) { + return w.ReadDirectory(ctx, core.WorkspaceDirectoryRequest{Root: root}) + }) + if err != nil || len(page.Entries) != 1 || page.Entries[0].Path != "note.txt" { + t.Fatalf("page = %+v, %v", page, err) + } + _, err = callOnWindow(h, "read other workspace", func(ctx context.Context) (core.WorkspaceFileRead, error) { + return w.ReadFile(ctx, root+"-other", "note.txt", nil) + }) + if hostErrorCode(err) != pluginservice.CodeContextExpired { + t.Fatalf("other workspace = %v", err) + } + _, err = callOnWindow(h, "missing file", func(ctx context.Context) (core.WorkspaceStat, error) { + return w.StatEntry(ctx, root, "missing") + }) + if hostErrorCode(err) != pluginservice.CodeNotFound { + t.Fatalf("missing = %v", err) + } +} + +// closingWorkspaceReadKernel waits for cancellation instead of returning file +// contents. The window event closes the project only after its read has started. +type closingWorkspaceReadKernel struct { + *testKernel + closeProject func() +} + +func (k *closingWorkspaceReadKernel) ReadWorkspaceFile(ctx context.Context, _, _ string, _ *int) (core.WorkspaceFileRead, error) { + k.closeProject() + <-ctx.Done() // callOnWindow supplies an eight-second request deadline. + return core.WorkspaceFileRead{}, ctx.Err() +} + +func (k *closingWorkspaceReadKernel) FindWorkspaceText(ctx context.Context, _ core.WorkspaceFindRequest) (core.WorkspaceFindPage, error) { + k.closeProject() + <-ctx.Done() // callOnWindow supplies an eight-second request deadline. + return core.WorkspaceFindPage{}, ctx.Err() +} + +func TestPluginWorkspaceReadsCancelWhenTheProjectCloses(t *testing.T) { + checkWorkspaceCloseCancellation(t, false) +} + +func TestPluginWorkspaceSearchCancelsWhenTheProjectCloses(t *testing.T) { + checkWorkspaceCloseCancellation(t, true) +} + +func checkWorkspaceCloseCancellation(t *testing.T, search bool) { + t.Helper() + kernel := &closingWorkspaceReadKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarness(t, kernel) + root := t.TempDir() + h.open(root) + h.settle() + kernel.closeProject = func() { + h.app.post(func(a *App) { a.closeProject() }) + } + _, err := callOnWindow(h, "close project during disk operation", func(ctx context.Context) (bool, error) { + w := pluginWorkbench{app: h.app} + if search { + _, err := w.FindText(ctx, core.WorkspaceFindRequest{Root: root, Pattern: "input"}) + return false, err + } + _, err := w.ReadFile(ctx, root, "input", nil) + return false, err + }) + if hostErrorCode(err) != pluginservice.CodeContextExpired || h.app.project != nil { + t.Fatalf("closed project read = %v, project = %p", err, h.app.project) + } +} diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 91730e9ce..d3237ed49 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -28,9 +28,9 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-03 | 部分完成 | 既有命令 placements 可用;通用菜单、快捷键贡献、context.set/状态栏未做 | | API-04 | 部分完成 | didChangeContexts 与 watch 事件;文档/选区/活动编辑器语义事件未做 | | API-05 | 已公开 | listContexts/getContext/getFolders,context/generation 与 rootID | -| API-06 | 部分完成 | readDirectory/stat/readFile;公共读上限 128 KiB,内部上限不冒充协议能力;契约和 Core 已公开,Viva 桌面端未接通(旧 Swift 客户端已退役) | -| API-07 | 部分完成 | watch + subscriptions/notify/dispose,context/session 回收与溢出重扫;契约和 Core 已公开,Viva 桌面端未接通 | -| API-08 | 部分完成 | findFiles/findText 分页与取消;只搜磁盘,精确匹配范围尚为 null;Viva 桌面端未接通 | +| API-06 | 已实现,待合入 | readDirectory/stat/readFile 已由 Rust Core 执行并接入 Viva 本地工作区;逐段拒绝符号链接/reparse point,目录有界分页,磁盘读取上限 128 KiB,支持文本/base64 与截断标记。macOS 定向验证通过;默认 Core 已固定到包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) 与既有增量更新依赖的 `9ab2336`,本轮不做 Windows 验收 | +| API-07 | 已实现,待合入 | watch 已接入 Viva 原生事件,Core 负责范围、隐藏过滤、排序去重和溢出重扫;注册先发重扫,dispose/context/session 结束释放且停止通知;macOS 真实文件事件已验证,本轮不做 Windows 验收 | +| API-08 | 已实现,精确范围未提供 | findFiles/findText 已由 Core 执行并接入 Viva;查询绑定游标、分页与 200 条总上限、取消、隐藏/索引过滤、no-follow 与磁盘编码处理;只搜磁盘,一行一条结果,range 如实为 null;macOS 定向验证通过 | | API-09 | 已公开 | documents/list/getSnapshot、editor/getActive/getSelections,含 dirty/版本/编码/EOL | | API-10 | 已公开 | applyEdits/replaceSelections/insertText;版本校验、IME/只读拒绝、一次 Undo | | API-11 | 已公开 | Viva 桌面端:`documents/save\|saveAs\|close`(`documents.save`)走文档自己的保存,冲突、硬链接、未命名、组字返回错误码不弹窗;`workspace/create\|rename\|copy\|trash`(`workspace.files.write`)由 Core 严格检查参数并完成磁盘变更(不覆盖、不跟随最后一段),`create` 支持 `kind:"symlink"`,不新增读链接的权限;trash 进系统废纸篓,不提供永久删除;Windows 实机与整机验收未做 | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index f067db7fd..64d81a5de 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -372,7 +372,11 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # The plugin delta branch (#187) includes current Core main, including the # built-in file association catalog and plans (#186). It adds the pinned # companion index and verifies and reconstructs ZIPs for marketplace updates. -PINNED_CORE_REVISION="076ce04e314ecdde790b36ee3f374becb11951a0" +# Desktop integration of Core #190 (API-06/07/08) at 095d013 with the existing +# #187 delta dependency at 076ce04. Both parents remain independently reviewable; +# the pin preserves marketplace delta commands while adding workspace disk reads, +# bounded search and native-watch planning/filtering. +PINNED_CORE_REVISION="9ab2336e8ca651e40baa5e65848b717b26f69e43" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json b/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json index c96ca8b0e..f322bd2d3 100644 --- a/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json +++ b/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json @@ -19,7 +19,19 @@ "desktop/internal/pluginservice/hostfilechanges_test.go", "desktop/internal/workbench/pluginfilechanges.go", "desktop/internal/workbench/pluginfilechanges_test.go", - "desktop/internal/core/file_changes.go" + "desktop/internal/core/file_changes.go", + "desktop/internal/core/workspace_read.go", + "desktop/internal/core/workspace_read_test.go", + "desktop/internal/pluginservice/hostworkspaceread.go", + "desktop/internal/pluginservice/hostworkspaceread_test.go", + "desktop/internal/workbench/pluginworkspaceread.go", + "desktop/internal/workbench/pluginworkspaceread_test.go", + "desktop/internal/core/workspace_find_watch.go", + "desktop/internal/core/workspace_find_watch_test.go", + "desktop/internal/pluginservice/hostworkspacefind.go", + "desktop/internal/pluginservice/hostworkspacefind_test.go", + "desktop/internal/pluginservice/hostworkspacewatch.go", + "desktop/internal/pluginservice/hostworkspacewatch_test.go" ] }, "windows": { @@ -38,12 +50,24 @@ "desktop/internal/pluginservice/hostfilechanges_test.go", "desktop/internal/workbench/pluginfilechanges.go", "desktop/internal/workbench/pluginfilechanges_test.go", - "desktop/internal/core/file_changes.go" + "desktop/internal/core/file_changes.go", + "desktop/internal/core/workspace_read.go", + "desktop/internal/core/workspace_read_test.go", + "desktop/internal/pluginservice/hostworkspaceread.go", + "desktop/internal/pluginservice/hostworkspaceread_test.go", + "desktop/internal/workbench/pluginworkspaceread.go", + "desktop/internal/workbench/pluginworkspaceread_test.go", + "desktop/internal/core/workspace_find_watch.go", + "desktop/internal/core/workspace_find_watch_test.go", + "desktop/internal/pluginservice/hostworkspacefind.go", + "desktop/internal/pluginservice/hostworkspacefind_test.go", + "desktop/internal/pluginservice/hostworkspacewatch.go", + "desktop/internal/pluginservice/hostworkspacewatch_test.go" ] }, "owner": "Extensions", - "verification": "macOS 单测:scripts/macos/test/test-macos.sh --filter \"EditorTextEditPlannerTests|EditorDocumentServiceTests|PluginWorkspaceFileServiceTests|PluginHostEditorServiceTests|PluginHostBrowserServiceTests|PluginHostMessageServiceTests|HTMLPreviewBridgeIsolationTests\";前端:frontend/editor 下运行 plugin-edits.test.ts。服务接入宿主分发、对插件开放后,按计划 §7 用三个验收插件(选区转换器、分页文件浏览器、HTML 预览启动器)在 debug 应用中原生验收:版本冲突与 IME 组字时编辑被拒、撤销一步回退整批编辑;符号链接与 .. 越界被拒、远程工作区返回 authorityUnsupported;后台窗口打开文件不抢焦点、消息限频生效;验收后关闭应用并确认无残留进程。 显式设置 LITHE_PLUGIN_HOST_TEST_NODE 后运行 PluginHostProcessIntegrationTests,验证真实 Node 后端经 Core 请求宿主、编辑 dirty 缓冲区、退出清理及插件包字节不变;scripts/macos/probe/probe-macos-monaco.sh --workbench-tests 验证真实 WebKit 的整批编辑与一次撤销。 Viva 的 API-11:scripts/desktop/desktop-go.sh test -run 'TestFileChanges|TestChangeError' ./internal/pluginservice 与 -run 'TestPlugin(Save|Create|Rename|Trash)' ./internal/workbench(真实 Core 新建/符号链接/复制/重命名/废纸篓/另存为及错误码);整机验收用合成插件在 debug 应用中保存、另存为、新建符号链接、重命名打开中的文件并确认标签跟随、移到废纸篓后能从废纸篓恢复,验收后关闭应用并确认无残留进程。", - "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(仅 http/https URL)、documents/registerContentProvider、editor/registerProviders。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。API-11(documents.save、workspace.files.write)已接通:documents/save|saveAs|close 走文档自己的保存,磁盘冲突、硬链接、未命名文档、组字被拒并返回错误码,不弹窗;workspace/create(文件、文件夹、kind:\"symlink\" 的符号链接)|rename|copy|trash 的参数由 Core 严格检查,磁盘变更由 Core 内核命令 workspace.createEntry|renameEntry|copyEntry|resolveEntry 完成(不跟随最后一段、不覆盖),窗口只负责先保存其下文档、打开的文档跟随文件移动、本地历史、项目树和系统废纸篓;Windows 上建符号链接需要开发者模式或管理员,否则返回 failed。未接通:workspace/readDirectory|stat|readFile|watch|findFiles|findText(需要 workspace.files/search 授权的文件服务)、preview/openHTML(Viva 有系统 Web 视图,但编辑器区还没有嵌入网页的标签)、browser/openExternal 的 resource 形式(返回 unsupportedOption)。", + "verification": "API-06–08:默认固定 Core 9ab2336(含 Core #190 与既有 #187 增量更新),运行 scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginservice ./internal/workbench -run 'TestWorkspace(Reads|Find|Search|Watch)|TestPluginWorkspace' -count=1 及对应 -race 检查,验证真实文件分页、文本/二进制读取、资源封装与权限上下文隔离、dirty 文档仍读磁盘及项目关闭取消,搜索分页/查询游标/范围与磁盘隔离,以及 macOS Viva 原生监听的递归创建、原子保存、删除、调用方归属、会话/上下文释放、在途通知取消、根目录替换后的最终重扫与释放。Windows 原生验收按用户要求本轮不执行,保持 pending。API-11:scripts/desktop/desktop-go.sh test ./internal/pluginservice -run 'TestFileChanges|TestChangeError' 与 ./internal/workbench -run 'TestPlugin(Save|Create|Rename|Trash)'。两平台原生验收使用内联合成插件:读取分页目录、磁盘文件,验证链接与 .. 越界拒绝、取消和重开工作区隔离,再保存/另存为、复制、重命名打开文件、移到废纸篓并恢复;无头测试不能替代 Windows reparse point 与目录共享行为验收。验收后关闭应用并确认无残留进程。", + "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(仅 http/https URL)、documents/registerContentProvider、editor/registerProviders。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。API-11(documents.save、workspace.files.write)已接通:documents/save|saveAs|close 走文档自己的保存,磁盘冲突、硬链接、未命名文档、组字被拒并返回错误码,不弹窗;workspace/create(文件、文件夹、kind:\"symlink\" 的符号链接)|rename|copy|trash 的参数由 Core 严格检查,磁盘变更由 Core 内核命令 workspace.createEntry|renameEntry|copyEntry|resolveEntry 完成(不跟随最后一段、不覆盖),窗口只负责先保存其下文档、打开的文档跟随文件移动、本地历史、项目树和系统废纸篓;Windows 上建符号链接需要开发者模式或管理员,否则返回 failed。API-06(workspace.files.read)已接通本地工作区的 workspace/readDirectory|stat|readFile:路径、隐藏规则、有界分页、no-follow 和 128 KiB 磁盘读取预算均由 Core 执行,文本/base64 与截断前缀 identity 如实返回,不读取 dirty 文档;窗口关闭或替换会取消并拒绝旧结果,remote authority 明确拒绝。API-07/08 已接通 workspace/watch|findFiles|findText:Core 复用匹配、编码和隐藏/索引规则,以 no-follow 句柄搜索磁盘、处理分页游标与监听过滤;Viva 原生事件无空闲轮询,订阅按插件/会话/上下文释放,dispose 返回前停止通知;搜索每页和总结果最多 200,精确范围为 null。macOS 真实文件与原生事件测试已通过;Windows 本轮不验收。默认 Core 已固定到 9ab2336,包含本次 Core #190 改动并保留既有 #187 增量更新依赖。整体条目仍含其他未完成能力,状态保持 partial/pending。未接通:preview/openHTML(Viva 有系统 Web 视图,但编辑器区还没有嵌入网页的标签)、browser/openExternal 的 resource 形式(返回 unsupportedOption)。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {