diff --git a/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md b/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md index 8f3a455a16..220bc085c6 100644 --- a/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md +++ b/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md @@ -1,10 +1,10 @@ -# Agent 笔记:独立的插件高亮与编辑器动作 API +# Agent 笔记:独立的插件高亮、编辑器动作与编辑器 Provider API 状态:已实现 ## 先说结论 -普通工具插件可以独立提供文本高亮、编辑器配置和位置动作,不要求实现 LSP(语言服务器协议)、构建、运行或调试提供者。静态资源使用 `languages:2`,位置动作通过函数协议 3 的独立宿主方法注册,再复用原有函数调用执行;没有 `runMarkers` 清单能力,也不修改 `commands/didRun`。当前接线限 macOS,运行和界面验收以功能矩阵为准,不把静态校验当作产品验收。 +普通工具插件可以独立提供文本高亮、编辑器配置、位置动作和编辑器语言功能(跳转、悬浮、补全、CodeLens、折叠、语义着色、文档链接),不要求实现 LSP(语言服务器协议)、构建、运行或调试提供者。静态资源使用 `languages:2`;位置动作与语言功能都通过函数协议 3 的独立宿主方法注册,再复用原有函数调用执行;没有 `runMarkers` 清单能力,也不修改 `commands/didRun`。语言功能只“补充”语言服务器:服务器先答,插件的答案只增加不替换。当前接线限 macOS,运行和界面验收以功能矩阵为准,不把静态校验当作产品验收。 ## 问题 @@ -30,6 +30,17 @@ Monarch 的 `cases` 按声明顺序执行,不能把语法当成无序字典重 点击时浏览器只回传宿主生成的批次和动作键,不能提供函数或业务参数。宿主重新验证内容版本、上下文、注册租约与会话函数,再用已有 invocation 调用;插件收到文档身份、预期版本和自己的不透明数据,执行前核对当前文本。命令通知保持原样,命令面板可调用同一插件业务实现。 +### 动作版本 2:同一行的多个图标、替代项与点击后展示位置 + +IDEA 里一行可以同时有“运行”、“调试”、“测试通过/失败”和“跳到父方法/实现”这类图标。版本 2 在不新增方法的前提下,让 `editor/registerActions` 表达它们: + +- 图标来自宿主声明的图标表(`getCapabilities` 的 `services.editor.options.actionIcons`,macOS 目前是 `run`、`run-all`、`debug`、`test`、`test-passed`、`test-failed`、`test-skipped`、`navigate-super`、`navigate-implementations`)。插件不能提供自己的 SVG;表外的图标名由 Core 拒绝。表和网页里 `editorActionIcons` 的键必须一致,`scripts/architecture/verify-editor-boundaries.mjs` 会检查。 +- 运行类图标画在行号右侧,导航类图标画在行号左侧,两条车道各自排列;同一行的多个动作仍进入同一个菜单。 +- 一个标记可以带至多 4 个 `alternatives`(例如“运行 main”旁边的“调试 main”“测试此包”),各有自己的图标、标题和函数绑定。点击回传的仍然只是宿主生成的批次、动作键,外加备选项键。 +- 动作函数的返回值可以带 `reveal`(1 到 100 个 LSP 位置),宿主把它展示出来(单个位置直接打开,多个位置用现有的导航列表)。返回值的其他成员属于插件自己,宿主不解释。这是“导航类图标点击后去哪里”的通用答案,宿主不需要知道 Spring 或 MyBatis。 + +测试标记与测试结果不新增任何测试专用契约:插件用 `test`、`test-passed`、`test-failed`、`test-skipped` 图标画状态和入口,点击后执行仍走 API-29(Maven/Gradle 等构建插件负责测试发现与运行,语言插件的点击函数调用 `lithe/build/*` 或 `lithe/host/run|debug/start`;插件之间互相调用函数要等 API-35)。图标只负责画状态,宿主不会因为一个图标自己启动任何东西;运行结果显示在宿主的运行/调试窗口和原生测试面板里,不由编辑器图标承载。 + ### 生命周期与兼容 动作刷新只确认已调度,不能等待插件返回后才结束编辑器桥接调用。整批收集共享八秒期限,各注册只拿剩余预算;失败不进入编辑、保存同步的致命错误路径。模块状态观察者弱引用运行时,避免事件源持有回调、回调又持有事件源,导致关闭项目后模块图不能释放。 @@ -51,25 +62,54 @@ grammar 从只读插件包有界读取,校验结果仅在本次进程内缓存 - 函数名约定或插件名分支:宿主猜私有协议且无法安全撤回,拒绝。 - 首版做任意样式装饰/万能工具工作流:超出当前需求;仅开放范围、标题、图标与函数绑定。 - 直接在主线程运行语法:长度限额不能阻止病态回溯,采用可终止 worker。 +- 让工具插件把 Provider 注册成一个语言服务器:强加服务器生命周期和文档同步,而且无法表达“只补充”,拒绝。 +- 让插件的答案覆盖语言服务器:会让一个补充性的小插件破坏上游语言能力,拒绝;语义着色因此也只在服务器没有答案处生效。 +- 把插件返回的 URL 或命令直接交给 Monaco:`command:` 链接会被 Monaco 执行,拒绝;页面只持有不透明键。 +- 为测试标记新增测试专用契约:测试发现和运行已经是 API-29 的职责,编辑器只需要多种图标,拒绝。 +- 允许插件提供自己的图标 SVG 或 CSS:等于向编辑器注入界面,拒绝;改为宿主声明图标表。 +- 把诊断放进 Provider 通道:诊断是推送式集合,要有版本、撤回和合并语义,留给 API-26 单独设计。 ## 后果 -收益是工具插件不污染领域模型,执行复用现成函数基础设施。代价是增加一个明确授权的独立编辑器贡献契约,需要跨语言校验与生命周期接线。首版不支持远程、只读预览动作,也不承诺任意大型文档的插件高亮;Windows 产品接入和完整界面验收仍需后续完成。 +收益是工具插件不污染领域模型,执行复用现成函数基础设施。代价是增加一个明确授权的独立编辑器贡献契约,需要跨语言校验与生命周期接线。首版不支持远程、只读预览动作,也不承诺任意大型文档的插件高亮;Windows 产品接入和完整界面验收仍需后续完成。Provider 通道额外增加一个权限(`editor.providers`)、每次触发后的并发询问成本(由各类型的答题期限限制)和一套页面与宿主的不透明键协议;换来的是 Java 之外的工具(Spring、MyBatis 的跨文件能力,或 Go、`.http`)不必为了一个按钮或跳转实现整台语言服务器。早先 Java 专用的运行标记与宿主分支是这个通用契约要取代的对象,它们的删除不在本契约的改动里。 + +### API-25:Provider 通道补充语言服务器,不替代它 + +后端先注册普通函数,再调用 `editor/registerProviders`(权限 `editor.providers`,同时需要 `documents.read`),给一个文件选择器(语言、扩展名、文件名,三者任一命中即可)绑定若干类型的函数:`definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink`。和动作注册一样,注册时只记录绑定;询问发生在之后的事件轮,插件通过 `documents/getSnapshot` 读取预期版本的文本再回答。 + +**宿主与 Core 的分工。** 宿主不认识任何语言,也不解释插件的数据: + +- Core 校验注册(选择器必须命中点什么、类型必须是宿主声明的、语义着色必须带 legend)并规范化每种答案的形状。补全只保留展示和编辑信息,丢弃 `data` 和 `command`,因此没有“解析补全”往返,也不会通过补全执行命令;CodeLens 只能带一个同插件的函数;文档链接目标必须是绝对 URL。 +- 每种类型的答题期限由宿主决定,插件不能自带 `budgetMs`:悬浮和补全 400 毫秒,跳转 1500 毫秒,其余 2000 毫秒。超时、失败、形状不对、文档已经变化或注册已被撤回的答案一律安静丢弃,只写 `PluginsEditorProviderFailed` 日志。 +- 同一个文件上所有匹配的注册并发询问;补全的触发字符只会问到声明过该字符的注册。 + +**合并规则(语言服务器优先)。** + +- 悬浮和补全:宿主在 Monaco 里把插件当作另一个 Provider,由 Monaco 自己合并多个来源的结果。宿主自己的悬浮、补全 Provider 也注册在 `*` 上;Monaco 对得分相同的 Provider 把后注册的排在前面,所以插件 Provider 必须先于宿主 Provider 注册,宿主的答案才排第一。 +- 跳转:语言服务器先答,插件的位置追加在后;重复位置只保留一个;服务器只指回光标所在符号本身时让位给插件(区间终点不含)。这个规则在 Core 的 `mergeDefinitions` 里,Swift 只照着保留下标取值。修饰键点击、F12 和原生 Go to Definition 命令(菜单、命令面板、快捷键)走同一个查询和合并;文件没有语言服务器跳转时只展示插件的位置。 +- 跳转结果在展示前再核对一次文档版本:查询结束和等待它的调用方恢复是两个事件轮,中间可能有编辑。版本变了就丢弃插件位置,语言服务器的答案照常展示。 +- 修饰键悬停判断“是否可点”时,只有语言服务器说没有跳转才问插件;同一个窗口同时最多一组插件跳转查询在跑,新的悬停取消上一组,上一次悬停迟到的服务器答复也不能再发起查询。 +- CodeLens、折叠、文档链接:直接追加。 +- 语义着色:只在语言服务器没有语义着色的位置生效。Monaco 0.55.1 里 `*` 选择器的 Provider 得分低于具体语言的 Provider,因此插件的 `*` 注册不会盖过服务器。 +- 只读预览不询问插件:页面 Provider 路由和原生跳转路由(`definitionHover`、`definition`)都按 `isReadOnlyPreview` 跳过插件,预览里只看语言服务器的跳转。 -### API-25 当前不是通用 Provider 注册框架 +**页面不接触插件的目标。** 网页只收到宿主生成的批次和条目键(UUID),点击 CodeLens 或链接时回传这些键,宿主在自己的表里找到真正的函数、参数和目标。文档链接在 Monaco 里画成不透明的 `lithe-plugin-link:/<批次>/<键>`,并由页面登记的 opener 先于 Monaco 默认处理拦截:Monaco 的链接检测会以 `allowCommands: true` 打开 `command:` 链接,如果把插件给的 URL 直接交给它,插件就能让编辑器执行任意命令。宿主只打开 http/https 和工作区内的 `file:`。 -当前高亮入口只接受插件清单和包内 JSON 资源;纯静态插件的安装、更新与撤回即时生效,不代表后端可以在运行中直接传 JSON 注册、替换或释放高亮 Provider(能力提供者)。已安装包仍只读,也没有任意语法文件修改后自动重载的承诺。 +**错误码。** 不认识的类型是 `plugin.host.unsupportedOption`(`details.option` 为 `providers.<类型>`,包括 `diagnostics`、`signatureHelp`),其余注册错误都是 `plugin.host.invalidParams`;重复 ID 是 `preconditionFailed`,每个插件最多 32 个注册(`limitExceeded`)。没有新增错误码。撤回某个函数会使该插件的全部注册失效,插件必须显式重新注册,复用的函数 ID 不会让旧绑定复活。 -独立补全、悬浮、定义、符号、格式化、重命名和 Code Action 尚无 JSON 到普通插件函数的注册绑定;既有 LSP 实现和独立 `editor/registerActions` 都不能冒充这些接口。新增符合既有 Monarch 结构的文本格式只改插件,不因规则变化升级 API;新增引擎或能力种类则仍需宿主适配与契约,不能靠未知 `kind` 自动获得实现。 +**不做什么。** 诊断是推送式集合,属于 API-26,不在 Provider 里;符号、格式化、重命名、Code Action、签名帮助、内联提示尚无绑定;运行期传入 JSON 注册高亮也没有。当前 worker 对超过 128 Ki UTF-16 单位或 10,000 行的文档保持普通文本,嵌入语言也按普通文本处理。 -因此 API-25 只完成静态语法与编辑配置这一部分。当前 worker 对超过 128 Ki UTF-16 单位或 10,000 行的文档保持普通文本,嵌入语言也按普通文本处理;SDK 兼容性测试通过不等于新增能力的封装、发布及真实插件安装验收已经完成。 +正确做法:一个“资源 key 在模板和 `.properties` 之间跳转”的插件注册 `definition`、`hover`、`completion` 三个函数,选择器写 `html` 和 `properties`;语言服务器照常提供模板的普通跳转,插件补上 key 的跳转。不要这样做:在宿主里按语言名加分支,或让插件返回 `command:` 链接让页面去执行。 ## 验证 - `cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib plugin_editor_resources`:静态资源、配置及 include 预算。 - `cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib plugins::editor_actions`:HTTP/SQL 同构动作、范围、重复身份及不透明数据。 - `bun test frontend/editor/src`:活跃文件匹配、别名身份、配置独立应用与撤回。 -- `scripts/macos/test/test-macos.sh --filter 'PluginEditorLanguagesTests|PluginEditorActionTests'`:真实 catalog 接纳、独立模块与动作注册清理。 +- `cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib plugins::editor_providers`:注册、答案形状、预算和定义合并,含共享契约 fixture。 +- `bun test frontend/editor/src/plugin-editor-action-rules.test.ts frontend/editor/src/plugin-editor-provider-rules.test.ts`:车道与备选项排布、位置换算、不透明链接 URL、语义着色合并。 +- `scripts/macos/test/test-macos.sh --filter 'PluginEditorLanguagesTests|PluginEditorActionTests|PluginEditorProviderTests|MonacoWorkbenchSessionLifetimeTests'`:真实 catalog 接纳、独立模块、动作与 Provider 注册清理、查询丢弃规则。 +- `node scripts/architecture/verify-editor-boundaries.mjs`:宿主图标表与网页图标键一致。 - `scripts/macos/verify/verify-runtime-bundle-immutability.sh`:发行路径只读静态边界。 ## 适用范围 @@ -80,4 +120,12 @@ grammar 从只读插件包有界读取,校验结果仅在本次进程内缓存 - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginEditorLanguages.swift` - `frontend/editor/src/plugin-languages.ts` - `frontend/editor/src/plugin-editor-actions.ts` +- `rust/lithe-core/src/plugins/editor_providers.rs` +- `macos/Sources/Lithe/Application/Features/PluginEditorProviderHostService.swift` +- `macos/Sources/Lithe/Models/AppModel/AppModel+PluginDefinitions.swift` +- `macos/Sources/Lithe/Platform/MacOS/MonacoPluginEditorProviders.swift` +- `macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift` +- `frontend/editor/src/plugin-editor-action-rules.ts` +- `frontend/editor/src/plugin-editor-provider-rules.ts` +- `frontend/editor/src/plugin-editor-providers.ts` - `frontend/editor/src/plugin-grammar-tokenizer.ts` diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 065bbcebbb..622e0dcf93 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -47,9 +47,9 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-22 | 部分完成 | 既有函数进度与取消;独立 output channel、通用 log/progress API 未做;Java 拆分计划(C-LS、C-RUN):语言服务器准备状态 setStatus、输出链接匹配器 | | API-23 | 部分完成 | 已有进程声明与运行时解析;通用 toolchains/process 服务未开放;Java 拆分计划(C-RUN):run/start、run/stop、工具 ID 引用与 requiresTools | | API-24 | 部分完成 | 已公开插件自有原生终端 create/show/close/reopen/dispose/onExit(macOS、本机);不开放 sendText/输出读取,Windows 待接入 | -| API-25 | 部分完成 | 既有语言/LSP 贡献;新增 `languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;运行期传入 JSON 动态注册/替换高亮 Provider、独立语言语义 Provider 未做,详见下方范围说明;Java 拆分计划(C-LS、C-EDIT):后端启动解析器,以及向自己声明的语言服务器 request、notify、setStatus;Spring、MyBatis 只补上游缺失的 Provider | -| API-26 | 未做 | 公共诊断 collection/events API 未开放;既有 LSP 诊断不等于该 API;Java 拆分计划(C-EDIT):推送式 collection,带文档版本 | -| API-27 | 部分完成 | 独立 `editor/registerActions` 绑定普通函数与文档范围,不依赖 LSP/Build/Run;通用主题、片段、其他装饰未做;Java 拆分计划(C-EDIT):图标、alternatives、reveal、CodeLens、运行与测试标记 | +| API-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;符号、格式化、重命名、Code Action、签名帮助、内联提示和运行期传入 JSON 动态注册高亮未做,详见下方范围说明;Java 拆分计划(C-LS、C-EDIT):后端启动解析器,以及向自己声明的语言服务器 request、notify、setStatus;Spring、MyBatis 只补上游缺失的 Provider | +| API-26 | 未做 | 公共诊断 collection/events API 未开放;既有 LSP 诊断不等于该 API;`registerProviders` 不接受 `diagnostics` 类型(返回 unsupportedOption),推送式诊断集合另行设计;Java 拆分计划(C-EDIT):推送式 collection,带文档版本 | +| API-27 | 部分完成 | 独立 `editor/registerActions` 绑定普通函数与文档范围,不依赖 LSP/Build/Run;版本 2 增加行首多图标(run/run-all/debug/test 与 test-passed/test-failed/test-skipped 结果态、navigate-super/navigate-implementations 导航)、同一标记的 `alternatives`(至多 4 个)和点击结果的 `reveal`(宿主展示位置);通用主题、片段、其他装饰未做;Java 拆分计划(C-EDIT):图标、alternatives、reveal、CodeLens、运行与测试标记 | | API-28 | 未做 | 公共 custom editor 文档 owner/保存/撤销/恢复未开放 | | API-29 | 部分完成 | #1517 BuildProvider 1–6/model inputs;普通编辑器动作不属于本领域项;新指南未齐全;Java 拆分不改协议:测试发现与运行沿用 #1517,由 Maven、Gradle 插件提供 | | API-30 | 既有能力 | 已有 debugAdapters 1/2 与 DAP 宿主;本 PR 不重建调试协议;Java 拆分计划(C-RUN):debug/start、debugAdapters 3 的 features 与 defaults | @@ -70,15 +70,16 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 ### API-25:JSON 配置的支持范围与局限 -当前新增的是**静态编辑器资源贡献**,不是任意 Provider(能力提供者)的运行期注册框架。 +静态编辑器资源贡献(语法、编辑配置)与运行期 Provider 注册是两条独立入口:前者来自只读插件包,后者由后端调用宿主方法注册。 | 场景 | 当前支持范围 | | --- | --- | | 新增文本格式或高亮规则 | 通过插件清单 `languages[]` 声明文件类型,`grammar.path` 引用包内 JSON 语法;宿主校验后由 worker 执行,不需要 LSP 或后端 | | 注释、括号、自动配对 | 可仅贡献 `configuration`,不要求同时提供 grammar | | 安装、更新、停用或卸载纯静态贡献 | 随已验证插件包的生命周期更新编辑器;这不等于插件可以调用动态 Provider 注册方法,也不授权修改已安装包或监听任意 JSON 文件自动重载 | -| 运行中直接提交 JSON,注册、替换或释放高亮 Provider | 尚未开放公共方法;当前不是接收任意内联 grammar 的注册入口 | -| 用 JSON 将独立补全、悬浮、定义、符号、格式化、重命名或 Code Action 绑定到普通插件函数 | 尚未开放;既有 LSP 能力不等于已有这些独立 Provider 接口,`editor/registerActions` 也不提供它们 | +| 运行中直接提交 JSON,注册、替换或释放高亮 Provider | 尚未开放公共方法;当前不是接收任意内联 grammar 的注册入口。`semanticTokens` Provider 提供的是按文档请求的语义着色,只在语言服务器没有语义着色的位置生效,不替代 grammar | +| 将补全、悬浮、定义、CodeLens、折叠、语义着色或文档链接绑定到普通插件函数 | 已开放:`lithe/host/editor/registerProviders`,需要 `editor.providers` 权限;每次最多 32 个注册,答案形状与预算由 Core 规定,宿主只能补充语言服务器的答案(见 Agent Note) | +| 符号、格式化、重命名、Code Action、签名帮助、内联提示、诊断 | 尚未开放;`registerProviders` 对这些类型返回 `plugin.host.unsupportedOption`(`details.option` 为 `providers.<类型>`),诊断属于 API-26 | | 切换语法引擎或新增宿主不认识的能力种类 | `grammar.kind` 当前仅接受 `monarch`;TextMate、tree-sitter 等新引擎及新能力种类仍需宿主适配和明确契约,不能只增加一个 JSON `kind` 值 | 新增一个使用**已支持结构**的语言实例、语法规则或编辑配置,只改插件内容,不因此升级宿主 API; @@ -229,9 +230,9 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | API-22 H/E | `output.createChannel/append/dispose`、`log`、`progress.withCancellation`;已有函数进度与输出生命周期 [S2/S11] | 插件/操作归属、日志脱敏与字节预算;取消/超时后不再更新 UI。只复用已有进度状态机,不把 stdout 协议流与业务日志混用 | M1:命令结果/进度;M3:独立输出;Java 拆分(C-LS、C-RUN):setStatus、输出链接匹配器 | | API-23 H | `toolchains.resolve/list`、受管 `process.run/cancel`;已有 executable/runtime 解析与进程链路 [S1/S11] | 显式执行授权,executable/argv 分离,cwd/环境白名单、输出和超时上限、进程树清理;不提供任意 shell 字符串,也不自动下载运行时 | M4;Java 拆分(C-RUN):run/start、run/stop、工具 ID 引用;Run 会话比受管进程多一层宿主展示 | | API-24 H/E | `terminal.create/show/close/reopen/dispose/onExit` 已复用原生终端模块 [S12];函数协议 3 宿主服务 | `terminal.create` 权限、创建逐操作确认;只控制本 backend session/context 的终端,禁用/关闭工作区清理。无 sendText 或输出读取;本机 macOS,Windows 与远程未实现 | 首版接线,原生验收见功能矩阵 | -| API-25 C/P | 语言/语法/LSP、补全/悬浮/定义/符号/格式化/重命名/Code Action;已有语言服务器贡献 [S1/S13] | 优先接成熟 LSP 的完整能力;自定义 Provider 仅补上游确实缺失项,按文档版本取消旧请求。避免让 SDK 成为第二套语言/工程引擎 | M4:已支持能力文档;`languages:2` 声明式语法已实现(见 Agent Note 2026-10-31-plugin-editor-extension-apis);后续:新 Provider;Java 拆分(C-LS、C-EDIT):后端启动解析器与向自有语言服务器的请求;Spring、MyBatis 属于上游缺失项 | +| API-25 C/P | 语言/语法/LSP、补全/悬浮/定义/符号/格式化/重命名/Code Action;已有语言服务器贡献 [S1/S13] | 优先接成熟 LSP 的完整能力;自定义 Provider 仅补上游确实缺失项,按文档版本取消旧请求。避免让 SDK 成为第二套语言/工程引擎 | M4:已支持能力文档;`languages:2` 声明式语法已实现;`editor/registerProviders` 已接线 macOS(Core 校验注册与结果形状,宿主按类型预算并发询问,合并规则见 Agent Note 2026-10-31-plugin-editor-extension-apis);后续:符号/格式化/重命名/Code Action、Windows;Java 拆分(C-LS、C-EDIT):后端启动解析器与向自有语言服务器的请求;Spring、MyBatis 属于上游缺失项 | | API-26 H/P/E | `diagnostics.createCollection/set/delete/onDidChange`;已有 Problems/诊断 owner [S13] | 只能写本插件 collection,带文档版本和稳定范围;编辑/卸载后旧诊断可撤回。不能覆盖其他 LSP 结果或伪造宿主诊断身份 | M4;Java 拆分(C-EDIT):推送式 collection | -| API-27 C/H/P | 主题/图标/片段、只读装饰、CodeLens/Inlay;已有内部 theme/editor 能力 [S5/S16] | 数据贡献/资源路径校验、预算与卸载;图标/主题用宿主 token,不允许 CSS/原生视图注入。语言信息优先走 LSP,UI 资源不得执行脚本 | 独立编辑器动作 API 已接线(Mac,待运行验收;复用 backend 2/函数协议 3,不升领域版本);主题/片段/其他装饰后续;Java 拆分(C-EDIT):图标、alternatives、reveal、CodeLens、运行与测试标记 | +| API-27 C/H/P | 主题/图标/片段、只读装饰、CodeLens/Inlay;已有内部 theme/editor 能力 [S5/S16] | 数据贡献/资源路径校验、预算与卸载;图标/主题用宿主 token,不允许 CSS/原生视图注入。语言信息优先走 LSP,UI 资源不得执行脚本 | 独立编辑器动作 API 已接线(Mac,待运行验收;复用 backend 2/函数协议 3,不升领域版本);版本 2 的多图标、alternatives、reveal 同属该方法,由宿主声明的图标表约束;主题/片段/其他装饰后续;Java 拆分(C-EDIT):图标、alternatives、reveal、CodeLens、运行与测试标记 | | API-28 C/P/H | `customEditors.register`、打开/保存/撤销/恢复;已有特殊文档视图不等于公开扩展点 [S5/S9] | 先说明唯一文档 owner 和 readonly/dirty/backup/undo 语义;可选 Webview 仅做视图。崩溃后可恢复且不丢未保存内容才可发布 | 后续 | 设置分类遵循[macOS 设置层级](../../.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md),原生配置编辑遵循[真实来源决策](../../.agents/notes/implemented/architecture/2026-10-25-settings-native-configuration-editing.md)。插件提供的文本/上游诊断不伪装成宿主翻译;宿主新增按钮、权限说明和错误必须走 `shared/i18n/`。 diff --git a/frontend/editor/src/plugin-editor-action-rules.test.ts b/frontend/editor/src/plugin-editor-action-rules.test.ts new file mode 100644 index 0000000000..b9ae94142c --- /dev/null +++ b/frontend/editor/src/plugin-editor-action-rules.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from "bun:test"; +import { + actionChoices, actionLane, actionMarkers, normalizeEditorActions, type EditorAction, +} from "./plugin-editor-action-rules"; + +function action(overrides: Partial): EditorAction { + return { id: "a", line: 1, endLine: 1, title: "Run", icon: "run", alternatives: [], ...overrides }; +} + +describe("plugin editor actions", () => { + test("navigation icons use the left lane and everything else the run lane", () => { + expect(actionLane("navigate-super")).toBe("left"); + expect(actionLane("navigate-implementations")).toBe("left"); + expect(actionLane("run")).toBe("right"); + expect(actionLane("test-failed")).toBe("right"); + }); + + test("keep well-formed actions inside the document and tolerate a missing alternatives list", () => { + const actions = normalizeEditorActions([ + { id: "a", line: 2, endLine: 9, title: "Run", icon: "run" }, + { id: "b", line: 40, endLine: 40, title: "Late", icon: "run" }, + { id: "c", line: 3, title: "Bad icon", icon: "Run Now" }, + { id: "d", line: 3, title: 7, icon: "run" }, + { id: "e", line: 4, endLine: 99, title: "Test", icon: "test", alternatives: [ + { id: "debug", title: "Debug", icon: "debug" }, + { id: "broken", title: "No icon" }, + ] }, + ], 10); + + expect(actions.map(item => item.id)).toEqual(["a", "e"]); + expect(actions[0]).toMatchObject({ endLine: 9, alternatives: [] }); + expect(actions[1].endLine).toBe(10); + expect(actions[1].alternatives).toEqual([{ id: "debug", title: "Debug", icon: "debug" }]); + expect(normalizeEditorActions({ actions: [] }, 10)).toEqual([]); + }); + + test("accept at most four alternatives", () => { + const alternatives = Array.from({ length: 6 }, (_, index) => ({ id: `alt${index}`, title: "Alt", icon: "run" })); + expect(normalizeEditorActions([{ id: "a", line: 1, title: "Run", icon: "run", alternatives }], 3)[0].alternatives) + .toHaveLength(4); + }); + + test("draw one marker per line and lane, led by the first action", () => { + const markers = actionMarkers([ + action({ id: "run", line: 3, title: "Run test", icon: "test-passed" }), + action({ id: "preview", line: 3, title: "Preview", icon: "run" }), + action({ id: "super", line: 3, title: "Go to super", icon: "navigate-super" }), + action({ id: "first", line: 1, title: "Run main", icon: "run" }), + ]); + + expect(markers).toEqual([ + { line: 1, lane: "right", icon: "run", title: "Run main" }, + { line: 3, lane: "right", icon: "test-passed", title: "Run test" }, + { line: 3, lane: "left", icon: "navigate-super", title: "Go to super" }, + ]); + }); + + test("a marker's menu lists its lane's actions with each action's alternatives after it", () => { + const actions = [ + action({ id: "run", line: 3, title: "Run test", icon: "test", alternatives: [ + { id: "debug", title: "Debug test", icon: "debug" }, + ] }), + action({ id: "preview", line: 3, title: "Preview", icon: "run" }), + action({ id: "super", line: 3, title: "Go to super", icon: "navigate-super" }), + action({ id: "other", line: 4, title: "Elsewhere", icon: "run" }), + ]; + + expect(actionChoices(actions, 3, "right")).toEqual([ + { key: "run", title: "Run test", action: "run" }, + { key: "run.debug", title: "Debug test", action: "run", alternative: "debug" }, + { key: "preview", title: "Preview", action: "preview" }, + ]); + expect(actionChoices(actions, 3, "left").map(item => item.action)).toEqual(["super"]); + expect(actionChoices(actions, 9, "right")).toEqual([]); + }); +}); diff --git a/frontend/editor/src/plugin-editor-action-rules.ts b/frontend/editor/src/plugin-editor-action-rules.ts new file mode 100644 index 0000000000..e036287b30 --- /dev/null +++ b/frontend/editor/src/plugin-editor-action-rules.ts @@ -0,0 +1,98 @@ +// Pure rules for plugin editor actions (API-27): what the page accepts from +// the host's list, where each marker sits in the gutter and what its menu +// offers. Core and the host have already validated the list; this module +// only keeps the page safe against a malformed or stale reply. + +/** The gutter lane a marker is drawn in: navigation beside the run lane. */ +export type ActionLane = "left" | "right"; + +export interface EditorActionAlternative { + id: string; + title: string; + icon: string; +} + +/** One action as the host sends it, with one-based lines. */ +export interface EditorAction { + id: string; + line: number; + endLine: number; + title: string; + icon: string; + alternatives: EditorActionAlternative[]; +} + +/** One gutter decoration: the first action of a line and lane draws it. */ +export interface ActionMarker { + line: number; + lane: ActionLane; + icon: string; + title: string; +} + +/** One menu row: the action alone, or the action with one alternative. */ +export interface ActionChoice { + key: string; + title: string; + action: string; + alternative?: string; +} + +// The host declares icon names (`actionIcons` in its options); they become +// CSS class suffixes, so only that spelling is ever put into a class. +const ICON_NAME = /^[a-z][a-z0-9-]*$/; +const MAX_ALTERNATIVES = 4; + +export function actionLane(icon: string): ActionLane { + return icon.startsWith("navigate-") ? "left" : "right"; +} + +function normalizeAlternatives(value: unknown): EditorActionAlternative[] { + if (!Array.isArray(value)) return []; + return (value as Partial[]) + .filter(item => typeof item?.id === "string" && typeof item.title === "string" && + typeof item.icon === "string" && ICON_NAME.test(item.icon)) + .slice(0, MAX_ALTERNATIVES) + .map(item => ({ id: item.id!, title: item.title!, icon: item.icon! })); +} + +/** Keeps only well-formed actions that start inside the document. */ +export function normalizeEditorActions(value: unknown, lineCount: number): EditorAction[] { + if (!Array.isArray(value)) return []; + const actions: EditorAction[] = []; + for (const item of value as Partial[]) { + if (typeof item?.id !== "string" || typeof item.title !== "string" || + typeof item.icon !== "string" || !ICON_NAME.test(item.icon) || + !Number.isInteger(item.line) || item.line! < 1 || item.line! > lineCount) continue; + const endLine = Number.isInteger(item.endLine) && item.endLine! >= item.line! + ? Math.min(item.endLine!, lineCount) : item.line!; + actions.push({ + id: item.id, line: item.line!, endLine, title: item.title, icon: item.icon, + alternatives: normalizeAlternatives(item.alternatives), + }); + } + return actions; +} + +/** One marker per line and lane, in document order. */ +export function actionMarkers(actions: readonly EditorAction[]): ActionMarker[] { + const markers = new Map(); + for (const action of actions) { + const lane = actionLane(action.icon), key = `${action.line}:${lane}`; + if (!markers.has(key)) markers.set(key, { line: action.line, lane, icon: action.icon, title: action.title }); + } + return [...markers.values()].sort((left, right) => left.line - right.line); +} + +/** + * The menu behind one marker: each action of the line and lane, followed by + * its alternatives (for example "Debug" after "Run"). + */ +export function actionChoices(actions: readonly EditorAction[], line: number, lane: ActionLane): ActionChoice[] { + return actions.filter(action => action.line === line && actionLane(action.icon) === lane).flatMap(action => [ + { key: action.id, title: action.title, action: action.id }, + ...action.alternatives.map(alternative => ({ + key: `${action.id}.${alternative.id}`, title: alternative.title, action: action.id, alternative: alternative.id, + })), + ]); +} diff --git a/frontend/editor/src/plugin-editor-actions.ts b/frontend/editor/src/plugin-editor-actions.ts index 9d6772876f..34112a05b7 100644 --- a/frontend/editor/src/plugin-editor-actions.ts +++ b/frontend/editor/src/plugin-editor-actions.ts @@ -2,17 +2,21 @@ import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js"; import { Action } from "monaco-editor/esm/vs/base/common/actions.js"; import { StandaloneServices } from "monaco-editor/esm/vs/editor/standalone/browser/standaloneServices.js"; import { IContextMenuService } from "monaco-editor/esm/vs/platform/contextview/browser/contextView.js"; +import { actionChoices, actionMarkers, normalizeEditorActions, type ActionLane, type EditorAction } from "./plugin-editor-action-rules"; type Entry = { model: monaco.editor.ITextModel; revision: number; chain: Promise; readonly: boolean; frozen: boolean; closingHolds?: number; }; -type EditorAction = { id: string; line: number; endLine: number; title: string; icon: string }; type State = { generation: number; version: number; revision: number; batch?: string; actions: EditorAction[]; decorations: string[]; timer?: ReturnType; + /** Whether the last list had a navigation marker; kept across edits so the gutter does not jump. */ + navigation: boolean; }; +const LANE_CLASS_PREFIX = "lithe-editor-action-lane-"; + /** Presentation only: opaque action keys route back to a versioned host list. */ export function attachPluginEditorActions(host: { entries(): Map; @@ -20,17 +24,24 @@ export function attachPluginEditorActions(host: { request(payload: object): Promise; current(id: string, entry: E): () => boolean; lineNumbersFirst: boolean; + /** Called after an entry's markers changed, so the gutter can make room for the left lane. */ + changed?(entry: E): void; }) { const states = new Map(); let disposed = false; const get = (entry: E): State => { const found = states.get(entry); if (found) return found; - const state: State = { generation: 0, version: 0, revision: 0, actions: [], decorations: [] }; + const state: State = { generation: 0, version: 0, revision: 0, actions: [], decorations: [], navigation: false }; states.set(entry, state); entry.model.onWillDispose(() => { clearTimeout(state.timer); state.generation++; states.delete(entry); }); return state; }; + // Without a current list the model shows no markers and nothing is clickable. + const forget = (entry: E, state: State) => { + clearTimeout(state.timer); state.generation++; state.actions = []; state.batch = undefined; + if (!entry.model.isDisposed()) state.decorations = entry.model.deltaDecorations(state.decorations, []); + }; async function refreshOne(id: string, entry: E) { const state = get(entry), generation = ++state.generation, version = entry.model.getVersionId(); clearTimeout(state.timer); @@ -39,60 +50,62 @@ export function attachPluginEditorActions(host: { if (disposed || entry.model.isDisposed() || !current() || entry.readonly) return; const result = await host.request({ type: "pluginEditorActions", id, revision }); if (disposed || !current() || state.generation !== generation || result.cancelled || entry.model.getVersionId() !== version) return; - const actions: EditorAction[] = (Array.isArray(result.actions) ? result.actions : []).filter((item: EditorAction) => - typeof item?.id === "string" && typeof item.title === "string" && - Number.isInteger(item.line) && item.line >= 1 && item.line <= entry.model.getLineCount()); - // Multiple actions on one line share a popup rather than overwriting one another. - const lines = [...new Map(actions.map(item => [item.line, item])).values()]; - state.decorations = entry.model.deltaDecorations(state.decorations, lines.map(item => ({ - range: new monaco.Range(item.line, 1, item.line, 1), options: { - glyphMarginClassName: `lithe-plugin-editor-action lithe-java-run-${item.icon}`, - linesDecorationsClassName: host.lineNumbersFirst ? `lithe-plugin-editor-action lithe-java-run-${item.icon}` : undefined, - linesDecorationsTooltip: item.title, - glyphMargin: { position: monaco.editor.GlyphMarginLane.Right }, - glyphMarginHoverMessage: { value: item.title.replace(/[\\`*_{}\[\]()#+.!<>|]/g, "\\$&"), isTrusted: false }, - }, - }))); - Object.assign(state, { version, revision, batch: result.batch, actions }); + const actions = normalizeEditorActions(result.actions, entry.model.getLineCount()); + // Actions of one line and lane share a popup rather than overwriting one another. + state.decorations = entry.model.deltaDecorations(state.decorations, actionMarkers(actions).map(marker => { + const classes = `lithe-editor-action lithe-editor-action-${marker.icon} ${LANE_CLASS_PREFIX}${marker.lane}`; + return { + range: new monaco.Range(marker.line, 1, marker.line, 1), options: { + glyphMarginClassName: classes, + linesDecorationsClassName: host.lineNumbersFirst ? classes : undefined, + linesDecorationsTooltip: marker.title, + glyphMargin: { position: marker.lane === "left" ? monaco.editor.GlyphMarginLane.Left : monaco.editor.GlyphMarginLane.Right }, + glyphMarginHoverMessage: { value: marker.title.replace(/[\\`*_{}\[\]()#+.!<>|]/g, "\\$&"), isTrusted: false }, + }, + }; + })); + Object.assign(state, { version, revision, batch: result.batch, actions, + navigation: actions.some(action => action.icon.startsWith("navigate-")) }); + host.changed?.(entry); } function schedule(id: string, entry: E) { const state = get(entry); - clearTimeout(state.timer); state.generation++; state.actions = []; state.batch = undefined; - if (!entry.model.isDisposed()) state.decorations = entry.model.deltaDecorations(state.decorations, []); + forget(entry, state); state.timer = setTimeout(() => { void refreshOne(id, entry).catch(console.error); }, 180); } return { schedule, + /** Whether the entry's gutter needs the left lane for navigation markers. */ + hasNavigation: (entry: E) => states.get(entry)?.navigation === true, async refresh() { - for (const [entry, state] of states) { - clearTimeout(state.timer); state.generation++; state.actions = []; state.batch = undefined; - if (!entry.model.isDisposed()) state.decorations = entry.model.deltaDecorations(state.decorations, []); - } + for (const [entry, state] of states) { forget(entry, state); state.navigation = false; host.changed?.(entry); } await Promise.all([...host.entries()].filter(([, entry]) => host.editors().some(view => view.getModel() === entry.model)) .map(([id, entry]) => refreshOne(id, entry))); }, attach(view: monaco.editor.IStandaloneCodeEditor) { const mouse = view.onMouseDown(event => { - const element = event.target.element?.closest(".lithe-plugin-editor-action"); + const element = event.target.element?.closest(".lithe-editor-action"); const pair = [...host.entries()].find(([, entry]) => entry.model === view.getModel()); if (!element || !pair || !event.target.position || !event.event.leftButton) return; event.event.preventDefault(); event.event.stopPropagation(); const [id, entry] = pair, state = states.get(entry), line = event.target.position.lineNumber; + const lane: ActionLane = element.classList.contains(`${LANE_CLASS_PREFIX}left`) ? "left" : "right"; const current = host.current(id, entry); if (!state || !current() || entry.readonly || entry.frozen || entry.closingHolds || state.version !== entry.model.getVersionId() || state.revision !== entry.revision) return; const batch = state.batch; - const items = state.actions.filter(item => item.line === line).map(item => new Action( - `lithe.pluginEditor.${item.id}`, item.title, undefined, true, async () => { + const items = actionChoices(state.actions, line, lane).map(choice => new Action( + `lithe.pluginEditor.${choice.key}`, choice.title, undefined, true, async () => { if (!current() || states.get(entry)?.batch !== batch || entry.readonly) return; - await host.request({ type: "pluginEditorAction", id, revision: state.revision, batch, action: item.id }); + await host.request({ type: "pluginEditorAction", id, revision: state.revision, batch, + action: choice.action, ...(choice.alternative === undefined ? {} : { alternative: choice.alternative }) }); })); if (items.length) StandaloneServices.get(IContextMenuService).showContextMenu({ getAnchor: () => ({ x: event.event.posx, y: event.event.posy }), getActions: () => items, }); }); const mouseUp = (event: MouseEvent) => { - if ((event.target as Element | null)?.closest(".lithe-plugin-editor-action") && view.getDomNode()?.contains(event.target as Node)) + if ((event.target as Element | null)?.closest(".lithe-editor-action") && view.getDomNode()?.contains(event.target as Node)) event.stopPropagation(); }; document.addEventListener("mouseup", mouseUp, true); diff --git a/frontend/editor/src/plugin-editor-provider-rules.test.ts b/frontend/editor/src/plugin-editor-provider-rules.test.ts new file mode 100644 index 0000000000..6588a04088 --- /dev/null +++ b/frontend/editor/src/plugin-editor-provider-rules.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import { encodeMonacoSemanticTokens } from "./semantic-tokens"; +import { + foldingSpans, hoverSections, lensItems, linkItems, linkUrl, mergeSemanticResponses, parseLinkUrl, toSpan, +} from "./plugin-editor-provider-rules"; + +const span = (line: number, from: number, to: number) => + ({ start: { line, character: from }, end: { line, character: to } }); + +describe("plugin editor provider rules", () => { + test("convert zero-based LSP ranges to one-based spans and refuse foreign ones", () => { + expect(toSpan(span(0, 2, 8), 3)).toEqual({ startLineNumber: 1, startColumn: 3, endLineNumber: 1, endColumn: 9 }); + expect(toSpan(span(3, 0, 1), 3)).toBeUndefined(); + expect(toSpan(span(1, 5, 2), 3)).toBeUndefined(); + expect(toSpan({ start: { line: -1, character: 0 }, end: { line: 0, character: 0 } }, 3)).toBeUndefined(); + expect(toSpan(undefined, 3)).toBeUndefined(); + }); + + test("hover keeps markdown and escapes plain text; a missing list is empty", () => { + const sections = hoverSections({ contents: [ + { kind: "markdown", value: "**bold** `code`" }, + { kind: "plaintext", value: "a*b_c" }, + { kind: "markdown", value: "" }, + "not an object", + ] }); + + expect(sections.map(item => item.value)).toEqual(["**bold** `code`", "a\\*b\\_c"]); + expect(sections.every(item => item.isTrusted === false && item.supportHtml === false)).toBe(true); + expect(hoverSections({})).toEqual([]); + expect(hoverSections(undefined)).toEqual([]); + }); + + test("folding ranges are one-based, multi-line and inside the document", () => { + expect(foldingSpans({ ranges: [ + { startLine: 0, endLine: 3, kind: "imports" }, + { startLine: 2, endLine: 2 }, + { startLine: 1, endLine: 9 }, + { startLine: 4, endLine: 5, kind: "bogus" }, + { startLine: 6, endLine: 10 }, + ] }, 10)).toEqual([ + { start: 1, end: 4, kind: "imports" }, + { start: 2, end: 10, kind: undefined }, + { start: 5, end: 6, kind: undefined }, + ]); + expect(foldingSpans(undefined, 10)).toEqual([]); + }); + + test("lenses and links need a batch and a span inside the document", () => { + const lenses = lensItems({ batch: "b1", lenses: [ + { id: "l1", range: span(1, 0, 3), title: "3 usages" }, + { id: "l2", range: span(9, 0, 3), title: "outside" }, + { id: 4, range: span(0, 0, 1), title: "bad id" }, + ] }, 4); + expect(lenses.batch).toBe("b1"); + expect(lenses.lenses.map(item => item.id)).toEqual(["l1"]); + expect(lenses.lenses[0].range.startLineNumber).toBe(2); + expect(lensItems({ batch: "", lenses: [{ id: "l", range: span(0, 0, 1), title: "t" }] }, 4).lenses).toEqual([]); + + const links = linkItems({ batch: "b2", links: [ + { id: "k1", range: span(0, 1, 5), tooltip: "Open" }, + { id: "k2", range: span(0, 1, 5) }, + { range: span(0, 1, 5) }, + ] }, 4); + expect(links.links.map(item => [item.id, item.tooltip])).toEqual([["k1", "Open"], ["k2", undefined]]); + expect(linkItems({}, 4)).toEqual({ batch: "", links: [] }); + }); + + test("link URLs carry only the host's opaque batch and key", () => { + const url = linkUrl("b-1", "k 1"); + expect(url).toBe("lithe-plugin-link:/b-1/k%201"); + expect(parseLinkUrl(url)).toEqual({ batch: "b-1", id: "k 1" }); + expect(parseLinkUrl("https://example.com/a")).toBeUndefined(); + expect(parseLinkUrl("command:editor.action.selectAll")).toBeUndefined(); + }); + + test("merge semantic answers with different legends into one token list", () => { + const merged = mergeSemanticResponses([ + { legend: { tokenTypes: ["property"], tokenModifiers: ["readonly"] }, data: [0, 0, 3, 0, 1] }, + { legend: { tokenTypes: ["keyword", "property"], tokenModifiers: ["static"] }, data: [1, 2, 4, 1, 1, 0, 6, 2, 0, 0] }, + ]); + + expect(merged.tokenTypes).toEqual(["property", "keyword"]); + expect(merged.tokenModifiers).toEqual(["readonly", "static"]); + expect(merged.tokens).toEqual([ + { line: 0, startChar: 0, length: 3, tokenType: 0, tokenModifiers: 1 }, + { line: 1, startChar: 2, length: 4, tokenType: 0, tokenModifiers: 2 }, + { line: 1, startChar: 8, length: 2, tokenType: 1, tokenModifiers: 0 }, + ]); + + const model = { getLineCount: () => 3, getLineMaxColumn: () => 40 }; + expect(Array.from(encodeMonacoSemanticTokens(merged, model)).length).toBe(15); + expect(mergeSemanticResponses("nope").tokens).toEqual([]); + expect(mergeSemanticResponses([{ legend: { tokenTypes: [], tokenModifiers: [] }, data: [0, 0, 1] }]).tokens).toEqual([]); + }); +}); diff --git a/frontend/editor/src/plugin-editor-provider-rules.ts b/frontend/editor/src/plugin-editor-provider-rules.ts new file mode 100644 index 0000000000..97d1c89d83 --- /dev/null +++ b/frontend/editor/src/plugin-editor-provider-rules.ts @@ -0,0 +1,167 @@ +// Pure rules for plugin editor providers (API-25): how the host's answers, +// already validated and normalized by Core, become editor data. The host +// sends LSP shapes with zero-based positions; Monaco is one-based. Nothing +// here touches Monaco, so every rule is testable on its own. + +import type { LspSemanticTokensResponse } from "./semantic-token-types"; + +/** A one-based Monaco range. */ +export interface Span { + startLineNumber: number; + startColumn: number; + endLineNumber: number; + endColumn: number; +} + +export interface HoverSection { + value: string; + isTrusted: false; + supportHtml: false; +} + +export interface FoldingSpan { + start: number; + end: number; + kind?: "comment" | "imports" | "region"; +} + +export interface LensItem { + id: string; + range: Span; + title: string; +} + +export interface LinkItem { + id: string; + range: Span; + tooltip?: string; +} + +export interface SemanticLegend { + tokenTypes: string[]; + tokenModifiers: string[]; +} + +const MARKDOWN_SPECIALS = /[\\`*_{}[\]()<>#+.!|~-]/g; + +const isNonNegativeInteger = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0; +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null; +const list = (value: unknown): unknown[] => Array.isArray(value) ? value : []; + +/** An LSP range inside the document, as a one-based span; nothing for a malformed or foreign one. */ +export function toSpan(value: unknown, lineCount: number): Span | undefined { + if (!isRecord(value) || !isRecord(value.start) || !isRecord(value.end)) return undefined; + const { line: startLine, character: startCharacter } = value.start; + const { line: endLine, character: endCharacter } = value.end; + if (!isNonNegativeInteger(startLine) || !isNonNegativeInteger(startCharacter) || + !isNonNegativeInteger(endLine) || !isNonNegativeInteger(endCharacter) || + endLine >= lineCount || startLine > endLine || (startLine === endLine && startCharacter > endCharacter)) return undefined; + return { startLineNumber: startLine + 1, startColumn: startCharacter + 1, endLineNumber: endLine + 1, endColumn: endCharacter + 1 }; +} + +/** Hover sections in plugin order: markdown as is, plain text escaped so it renders as written. */ +export function hoverSections(reply: unknown): HoverSection[] { + const sections: HoverSection[] = []; + for (const part of list(isRecord(reply) ? reply.contents : undefined)) { + if (!isRecord(part) || typeof part.value !== "string" || part.value === "") continue; + const value = part.kind === "plaintext" ? part.value.replace(MARKDOWN_SPECIALS, "\\$&") : part.value; + sections.push({ value, isTrusted: false, supportHtml: false }); + } + return sections; +} + +/** Folding ranges inside the document; the host's `startLine` and `endLine` are zero-based. */ +export function foldingSpans(reply: unknown, lineCount: number): FoldingSpan[] { + const spans: FoldingSpan[] = []; + for (const item of list(isRecord(reply) ? reply.ranges : undefined)) { + if (!isRecord(item) || !isNonNegativeInteger(item.startLine) || !isNonNegativeInteger(item.endLine) || + item.endLine <= item.startLine || item.endLine >= lineCount) continue; + const kind = item.kind === "comment" || item.kind === "imports" || item.kind === "region" ? item.kind : undefined; + spans.push({ start: item.startLine + 1, end: item.endLine + 1, kind }); + } + return spans; +} + +/** Code lenses the page can ask the host to run: each has an opaque key, a span and a title. */ +export function lensItems(reply: unknown, lineCount: number): { batch: string; lenses: LensItem[] } { + const batch = isRecord(reply) && typeof reply.batch === "string" ? reply.batch : ""; + const lenses: LensItem[] = []; + for (const item of batch ? list(isRecord(reply) ? reply.lenses : undefined) : []) { + if (!isRecord(item) || typeof item.id !== "string" || typeof item.title !== "string") continue; + const range = toSpan(item.range, lineCount); + if (range) lenses.push({ id: item.id, range, title: item.title }); + } + return { batch, lenses }; +} + +/** Document links the page can ask the host to open: opaque key, span and optional tooltip. */ +export function linkItems(reply: unknown, lineCount: number): { batch: string; links: LinkItem[] } { + const batch = isRecord(reply) && typeof reply.batch === "string" ? reply.batch : ""; + const links: LinkItem[] = []; + for (const item of batch ? list(isRecord(reply) ? reply.links : undefined) : []) { + if (!isRecord(item) || typeof item.id !== "string") continue; + const range = toSpan(item.range, lineCount); + if (range) links.push({ id: item.id, range, tooltip: typeof item.tooltip === "string" ? item.tooltip : undefined }); + } + return { batch, links }; +} + +/** + * The URL a drawn link carries: the batch is the host's list, the key one + * entry of it. Both are opaque tokens the host generated (UUIDs), so the URL + * survives Monaco parsing it; the host looks the real target up itself. + */ +export const LINK_SCHEME = "lithe-plugin-link"; + +export function linkUrl(batch: string, id: string): string { + return `${LINK_SCHEME}:/${encodeURIComponent(batch)}/${encodeURIComponent(id)}`; +} + +export function parseLinkUrl(value: string): { batch: string; id: string } | undefined { + const match = new RegExp(`^${LINK_SCHEME}:/([^/]+)/([^/]+)$`).exec(value); + if (!match) return undefined; + try { + return { batch: decodeURIComponent(match[1]), id: decodeURIComponent(match[2]) }; + } catch { + return undefined; + } +} + +/** + * Semantic token answers as one absolute token list. Registrations may use + * different legends, so type and modifier names are merged into one legend + * and every token is renumbered into it; the existing LSP encoder then maps + * them to Monaco's legend, drops overlaps and orders them. + */ +export function mergeSemanticResponses(responses: unknown): LspSemanticTokensResponse { + const merged: LspSemanticTokensResponse = { tokens: [], tokenTypes: [], tokenModifiers: [] }; + const indexOf = (names: string[], name: string) => { + const found = names.indexOf(name); + if (found >= 0) return found; + names.push(name); + return names.length - 1; + }; + for (const response of list(responses)) { + if (!isRecord(response) || !isRecord(response.legend) || !Array.isArray(response.data)) continue; + const legend = response.legend as Partial, data = response.data as unknown[]; + if (!Array.isArray(legend.tokenTypes) || !Array.isArray(legend.tokenModifiers) || data.length % 5 !== 0) continue; + const typeMap = legend.tokenTypes.map(name => indexOf(merged.tokenTypes, String(name))); + // A legend of more than 32 modifiers cannot be a bit set; the host already refuses it. + const modifierMap = legend.tokenModifiers.slice(0, 32).map(name => indexOf(merged.tokenModifiers, String(name))); + let line = 0, character = 0; + for (let offset = 0; offset < data.length; offset += 5) { + const [deltaLine, deltaStart, length, type, modifiers] = data.slice(offset, offset + 5); + if (![deltaLine, deltaStart, length, type, modifiers].every(isNonNegativeInteger)) break; + line += deltaLine as number; + character = deltaLine === 0 ? character + (deltaStart as number) : (deltaStart as number); + const tokenType = typeMap[type as number]; + if (tokenType === undefined) continue; + let tokenModifiers = 0; + modifierMap.forEach((target, source) => { + if ((((modifiers as number) >>> source) & 1) === 1 && target < 32) tokenModifiers |= 1 << target; + }); + merged.tokens.push({ line, startChar: character, length: length as number, tokenType, tokenModifiers: tokenModifiers >>> 0 }); + } + } + return merged; +} diff --git a/frontend/editor/src/plugin-editor-providers.ts b/frontend/editor/src/plugin-editor-providers.ts new file mode 100644 index 0000000000..4cbfc9ff07 --- /dev/null +++ b/frontend/editor/src/plugin-editor-providers.ts @@ -0,0 +1,232 @@ +import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js"; +import { Emitter } from "monaco-editor/esm/vs/base/common/event.js"; +import { StandaloneServices } from "monaco-editor/esm/vs/editor/standalone/browser/standaloneServices.js"; +import { IOpenerService } from "monaco-editor/esm/vs/platform/opener/common/opener.js"; +import { mapCompletionKind } from "./completion-kind"; +import { MONACO_SEMANTIC_TOKEN_LEGEND, encodeMonacoSemanticTokens } from "./semantic-tokens"; +import { + foldingSpans, hoverSections, lensItems, linkItems, linkUrl, mergeSemanticResponses, parseLinkUrl, toSpan, + type FoldingSpan, +} from "./plugin-editor-provider-rules"; + +type Entry = { + model: monaco.editor.ITextModel; revision: number; chain: Promise; + readonly: boolean; frozen: boolean; closingHolds?: number; +}; +type Answer = { id: string; entry: E; revision: number; reply: any; current: () => boolean }; +type Origin = { id: string; entry: E; revision: number; current: () => boolean }; + +// Monaco needs the characters that start a completion when it registers the +// provider, but a plugin names its own. Listening for all ASCII punctuation +// lets any of them through; the host passes a typed character only to +// registrations that asked for it and answers nothing otherwise. +const COMPLETION_TRIGGERS = [..."!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]; +const LENS_COMMAND = "lithe.pluginCodeLens"; +const MAX_LINK_BATCHES = 64; + +const foldingKind = (kind: FoldingSpan["kind"]) => { + const kinds = monaco.languages.FoldingRangeKind; + return kind === "comment" ? kinds.Comment : kind === "imports" ? kinds.Imports : kind === "region" ? kinds.Region : undefined; +}; + +/** + * Editor providers that plugins register (API-25). The page only names a + * provider type and a position; the host calls the plugins, validates and + * merges their answers, and keeps every private reference behind opaque keys. + * Each provider here only supplements the language server's own: Monaco asks + * all providers and combines hovers, completions, lenses, folding ranges and + * links. Definitions are answered by the host's own navigation. + */ +export function attachPluginEditorProviders(host: { + entries(): Map; + request(payload: object): Promise; + current(id: string, entry: E): () => boolean; +}) { + const lensChanges = new Emitter(); + const foldingChanges = new Emitter(); + const semanticChanges = new Emitter(); + const linkOrigins = new Map>(); + let disposed = false; + + /** One round trip: waits for the document to settle, asks, and drops the answer if it went stale. */ + async function ask(model: monaco.editor.ITextModel, token: monaco.CancellationToken, body: object): Promise | undefined> { + const pair = [...host.entries()].find(([, entry]) => entry.model === model); + if (!pair || disposed) return undefined; + const [id, entry] = pair, current = host.current(id, entry); + await entry.chain; + if (disposed || !current() || token.isCancellationRequested || model.isDisposed()) return undefined; + const revision = entry.revision; + const reply = await host.request({ type: "pluginEditorProviders", id, revision, language: model.getLanguageId(), ...body }); + if (disposed || !current() || token.isCancellationRequested || model.isDisposed() || entry.revision !== revision || + reply?.cancelled) return undefined; + return { id, entry, revision, reply, current }; + } + + const hover = monaco.languages.registerHoverProvider("*", { + async provideHover(model, position, token) { + const answer = await ask(model, token, { provider: "hover", line: position.lineNumber - 1, character: position.column - 1 }); + const contents = answer ? hoverSections(answer.reply) : []; + if (!answer || !contents.length) return null; + const span = toSpan(answer.reply.range, model.getLineCount()); + return { contents, range: span ? model.validateRange(span) : undefined }; + }, + }); + + function suggestion(model: monaco.editor.ITextModel, item: any, fallback: monaco.Range): monaco.languages.CompletionItem | undefined { + if (typeof item?.label !== "string") return undefined; + const lineCount = model.getLineCount(); + const valid = (range: unknown) => { const span = toSpan(range, lineCount); return span && model.validateRange(span); }; + let range: monaco.languages.CompletionItem["range"] = fallback; + let insertText = typeof item.insertText === "string" ? item.insertText : item.label; + if (item.textEdit) { + insertText = item.textEdit.newText; + if (item.textEdit.range) { + const edit = valid(item.textEdit.range); + if (!edit) return undefined; + range = edit; + } else { + const insert = valid(item.textEdit.insert), replace = valid(item.textEdit.replace); + if (!insert || !replace) return undefined; + range = { insert, replace }; + } + } + const additionalTextEdits: monaco.languages.TextEdit[] = []; + for (const edit of Array.isArray(item.additionalTextEdits) ? item.additionalTextEdits : []) { + const editRange = valid(edit?.range); + if (!editRange || typeof edit.newText !== "string") return undefined; + additionalTextEdits.push({ range: editRange, text: edit.newText }); + } + const documentation = item.documentation + ? item.documentation.kind === "markdown" + ? { value: item.documentation.value, isTrusted: false, supportHtml: false } : item.documentation.value + : undefined; + return { + label: item.labelDetails ? { label: item.label, detail: item.labelDetails.detail, description: item.labelDetails.description } : item.label, + kind: mapCompletionKind(item.kind), + insertText, range, documentation, + insertTextRules: item.insertTextFormat === 2 ? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet : undefined, + detail: item.detail, sortText: item.sortText, filterText: item.filterText, + tags: Array.isArray(item.tags) && item.tags.includes(1) ? [monaco.languages.CompletionItemTag.Deprecated] : undefined, + commitCharacters: item.commitCharacters, + additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : undefined, + }; + } + + const completion = monaco.languages.registerCompletionItemProvider("*", { + triggerCharacters: COMPLETION_TRIGGERS, + async provideCompletionItems(model, position, context, token) { + const triggered = context.triggerKind === monaco.languages.CompletionTriggerKind.TriggerCharacter && + typeof context.triggerCharacter === "string"; + const answer = await ask(model, token, { provider: "completion", line: position.lineNumber - 1, character: position.column - 1, + ...(triggered ? { triggerCharacter: context.triggerCharacter } : {}) }); + if (!answer) return { suggestions: [] }; + const word = model.getWordUntilPosition(position); + const fallback = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); + return { + incomplete: answer.reply.isIncomplete === true, + suggestions: (Array.isArray(answer.reply.items) ? answer.reply.items : []) + .flatMap((item: unknown) => suggestion(model, item, fallback) ?? []), + }; + }, + }); + + // A lens click names the host's opaque batch and key; the host runs the + // plugin function and the page learns nothing about it. + const lensCommand = monaco.editor.registerCommand(LENS_COMMAND, async (_accessor, context: Origin & { batch: string; lens: string }) => { + const { id, entry, revision, batch, lens, current } = context; + if (disposed || !current() || host.entries().get(id) !== entry || entry.model.isDisposed() || entry.revision !== revision || + entry.readonly || entry.frozen || entry.closingHolds) return; + await host.request({ type: "pluginEditorProviderCommand", id, revision, batch, lens }); + }); + const codeLens: monaco.languages.CodeLensProvider = { + onDidChange: listener => lensChanges.event(() => listener(codeLens)), + async provideCodeLenses(model, token) { + const answer = await ask(model, token, { provider: "codeLens" }); + const { batch, lenses } = lensItems(answer?.reply, model.getLineCount()); + return { + lenses: !answer ? [] : lenses.map(item => ({ + range: model.validateRange(item.range), + command: { id: LENS_COMMAND, title: item.title, + arguments: [{ id: answer.id, entry: answer.entry, revision: answer.revision, current: answer.current, batch, lens: item.id }] }, + })), + dispose() {}, + }; + }, + }; + const codeLensRegistration = monaco.languages.registerCodeLensProvider("*", codeLens); + + const folding: monaco.languages.FoldingRangeProvider = { + onDidChange: listener => foldingChanges.event(() => listener(folding)), + async provideFoldingRanges(model, _context, token) { + const answer = await ask(model, token, { provider: "foldingRange" }); + if (!answer) return null; + const ranges = foldingSpans(answer.reply, model.getLineCount()) + .map(span => ({ start: span.start, end: span.end, kind: foldingKind(span.kind) })); + return ranges.length ? ranges : null; + }, + }; + const foldingRegistration = monaco.languages.registerFoldingRangeProvider("*", folding); + + // A "*" registration scores below one for the document's own language, so + // this runs only for files whose language has no semantic tokens of its + // own; where the language server provides them, theirs stay. + const semanticTokens = monaco.languages.registerDocumentSemanticTokensProvider("*", { + getLegend: () => MONACO_SEMANTIC_TOKEN_LEGEND, + onDidChange: semanticChanges.event, + releaseDocumentSemanticTokens() {}, + async provideDocumentSemanticTokens(model, _lastResultID, token) { + const answer = await ask(model, token, { provider: "semanticTokens" }); + if (!answer) return null; + const merged = mergeSemanticResponses(answer.reply.responses); + return merged.tokens.length ? { data: encodeMonacoSemanticTokens(merged, model) } : null; + }, + }); + + // Link targets stay in the host: the page draws a link that carries only + // an opaque URL of its own scheme, and the opener below sends the click + // back. Monaco would otherwise act on a plugin's own URL (`command:` runs + // editor commands), so no plugin URL reaches Monaco at all. + const linkProvider: monaco.languages.LinkProvider = { + async provideLinks(model, token) { + const answer = await ask(model, token, { provider: "documentLink" }); + const { batch, links } = linkItems(answer?.reply, model.getLineCount()); + if (!answer || !links.length) return { links: [] }; + for (const [key, origin] of linkOrigins) if (origin.entry === answer.entry) linkOrigins.delete(key); + if (linkOrigins.size >= MAX_LINK_BATCHES) linkOrigins.delete(linkOrigins.keys().next().value!); + linkOrigins.set(batch, { id: answer.id, entry: answer.entry, revision: answer.revision, current: answer.current }); + return { links: links.map(item => ({ range: model.validateRange(item.range), url: linkUrl(batch, item.id), tooltip: item.tooltip })) }; + }, + }; + let linkRegistration = monaco.languages.registerLinkProvider("*", linkProvider); + const opener = StandaloneServices.get(IOpenerService).registerOpener({ + async open(resource) { + const target = parseLinkUrl(String(resource)); + if (!target) return false; + const origin = linkOrigins.get(target.batch); + // A link from a list that is no longer current is swallowed, not handed to the browser. + if (origin && !disposed && origin.current() && host.entries().get(origin.id) === origin.entry && + origin.entry.revision === origin.revision && !origin.entry.frozen && !origin.entry.closingHolds) + await host.request({ type: "pluginEditorProviderLink", id: origin.id, revision: origin.revision, batch: target.batch, link: target.id }); + return true; + }, + }); + + return { + /** Every registration changed: ask again for what the page already shows. */ + refresh() { + if (disposed) return; + linkOrigins.clear(); + lensChanges.fire(); foldingChanges.fire(); semanticChanges.fire(); + // Links have no change event of their own; registering again makes Monaco recompute them. + linkRegistration.dispose(); + linkRegistration = monaco.languages.registerLinkProvider("*", linkProvider); + }, + dispose() { + disposed = true; + linkOrigins.clear(); + for (const registration of [hover, completion, lensCommand, codeLensRegistration, foldingRegistration, semanticTokens, linkRegistration, opener]) + registration.dispose(); + lensChanges.dispose(); foldingChanges.dispose(); semanticChanges.dispose(); + }, + }; +} diff --git a/frontend/editor/src/workbench.ts b/frontend/editor/src/workbench.ts index 9b0b0487db..5a304906d3 100644 --- a/frontend/editor/src/workbench.ts +++ b/frontend/editor/src/workbench.ts @@ -29,6 +29,7 @@ import { IContextMenuService } from "monaco-editor/esm/vs/platform/contextview/b import { Action, Separator, type IAction } from "monaco-editor/esm/vs/base/common/actions.js"; import { normalizeRunMarkers, runMarkerForLine, runMarkerIcon, type RunMarker, type RunMarkerIcon } from "./run-markers"; import { attachPluginEditorActions } from "./plugin-editor-actions"; +import { attachPluginEditorProviders } from "./plugin-editor-providers"; import { installPluginGrammar, inheritPluginTokenizer } from "./plugin-grammar-tokenizer"; import { setPluginLanguages, hasPluginLanguage, pluginLanguageForFilename, type PluginLanguage } from "./plugin-languages"; @@ -50,6 +51,9 @@ export interface WorkbenchHost { /** IDEA test-state SVGs for Java Run markers. */ javaRunIcons?: Record; javaRunIconsDark?: Partial>; + /** Gutter SVGs for plugin editor actions, keyed by the icon names the host offers plugins (API-27). */ + editorActionIcons?: Record; + editorActionIconsDark?: Record; /** Native IDEA order: line numbers, then action decorations. */ lineNumbersFirst?: boolean; reportIndentation?: boolean; @@ -228,7 +232,11 @@ export function mountWorkbench(host: WorkbenchHost) { entries: () => entries, editors: allEditors, request: languageRequest, current: (id, entry) => documentCheckpoint(id, entry), lineNumbersFirst: host.lineNumbersFirst === true, + // The left lane widens the gutter; let every view showing the entry recompute it. + changed: () => { for (const view of allEditors()) navigationContexts.get(view)?.(); }, }); + // Registered with Monaco once it is set up (see `main`), next to the language server's own providers. + let pluginProviders: ReturnType> | undefined; // Java Run markers: the host answers which `main` methods and tests exist and // their last outcomes; the editor only draws them and routes actions back. type RunMarkerState = { generation: number; version: number; revision: number; markers: RunMarker[]; @@ -830,7 +838,7 @@ export function mountWorkbench(host: WorkbenchHost) { // before FoldingController interprets it as a click on the folding arrow. const actionMouseUp = (event: MouseEvent) => { const element = event.target as Element | null; - if (element?.closest(".lithe-java-run,.lithe-java-navigation") && view.getDomNode()?.contains(element)) { + if (element?.closest(".lithe-java-run,.lithe-java-navigation,.lithe-editor-action") && view.getDomNode()?.contains(element)) { event.stopPropagation(); } }; @@ -915,7 +923,7 @@ export function mountWorkbench(host: WorkbenchHost) { const refresh = () => { if (host.lineNumbersFirst) { const entry = [...entries.values()].find(entry => entry.model === view.getModel()); - const needsLane = !!(entry && navigationStates.get(entry)?.markers.length); + const needsLane = !!(entry && (navigationStates.get(entry)?.markers.length || pluginActions.hasNavigation(entry))); const width = nativeFoldingOffset + (needsLane ? nativeGutter.icon : 0); const className = `lithe-line-numbers-first${needsLane ? " lithe-gutter-navigation" : ""}`; const options = view.getRawOptions(); @@ -1011,7 +1019,7 @@ export function mountWorkbench(host: WorkbenchHost) { // Edit Breakpoint action may open the native editor sheet. if (host.gitBlameMenu && host.lineNumbersFirst && (event.event.rightButton || isMacintosh && event.event.ctrlKey) && event.target.type === monaco.editor.MouseTargetType.GUTTER_LINE_NUMBERS) return; - if (event.target.element?.closest(".lithe-java-navigation, .lithe-java-run, .lithe-blame") || + if (event.target.element?.closest(".lithe-java-navigation, .lithe-java-run, .lithe-editor-action, .lithe-blame") || host.lineNumbersFirst && typeof view.getRawOptions().lineNumbers === "function" && view.getRawOptions().lineNumbers !== hiddenLineNumbers) return; if ((event.target.type !== monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN && @@ -1114,6 +1122,11 @@ export function mountWorkbench(host: WorkbenchHost) { // must never hold the native save/edit bridge until its fatal deadline. void pluginActions.refresh().catch(console.error); }, + async refreshPluginEditorProviders() { + await activation; + // Same rule as the actions: Monaco asks again on its own schedule. + pluginProviders?.refresh(); + }, async refreshJavaRunMarkers() { await activation; await Promise.all([...entries].filter(([, entry]) => allEditors().some(view => view.getModel() === entry.model)) @@ -1603,6 +1616,10 @@ export function mountWorkbench(host: WorkbenchHost) { `.monaco-editor .lithe-java-run-${icon}{background-image:url("data:image/svg+xml,${encodeURIComponent(svg)}")}`).join("\n"); const darkRunIconStyles = Object.entries(host.javaRunIconsDark ?? {}).map(([icon, svg]) => `.monaco-editor.vs-dark .lithe-java-run-${icon}{background-image:url("data:image/svg+xml,${encodeURIComponent(svg)}")}`).join("\n"); + const actionIconStyles = Object.entries(host.editorActionIcons ?? {}).map(([icon, svg]) => + `.monaco-editor .lithe-editor-action-${icon}{background-image:url("data:image/svg+xml,${encodeURIComponent(svg)}")}`).join("\n"); + const darkActionIconStyles = Object.entries(host.editorActionIconsDark ?? {}).map(([icon, svg]) => + `.monaco-editor.vs-dark .lithe-editor-action-${icon}{background-image:url("data:image/svg+xml,${encodeURIComponent(svg)}")}`).join("\n"); const foldingIconStyles = Object.entries(host.foldingIcons ?? {}).flatMap(([state, icons]) => (["light", "dark"] as const).map(appearance => { const theme = (appearance === "dark" ? ".vs-dark" : "") + ".lithe-line-numbers-first"; @@ -1616,17 +1633,19 @@ export function mountWorkbench(host: WorkbenchHost) { .monaco-editor .lithe-java-navigation-down:after,.monaco-editor .lithe-java-navigation-both:after{content:'↓'} .monaco-editor .lithe-java-navigation-both:before,.monaco-editor .lithe-java-navigation-both:after{width:50%;max-width:12px} ${navigationIconStyles} - .monaco-editor .lithe-java-run,.monaco-editor .lithe-plugin-editor-action{cursor:pointer;background-size:14px 14px;background-repeat:no-repeat;background-position:center;opacity:.9} - .monaco-editor .lithe-java-run:hover{opacity:1} + .monaco-editor .lithe-java-run,.monaco-editor .lithe-editor-action{cursor:pointer;background-size:14px 14px;background-repeat:no-repeat;background-position:center;opacity:.9} + .monaco-editor .lithe-java-run:hover,.monaco-editor .lithe-editor-action:hover{opacity:1} ${runIconStyles} ${darkRunIconStyles} + ${actionIconStyles} + ${darkActionIconStyles} ${host.lineNumbersFirst ? ` .monaco-editor.lithe-line-numbers-first .line-numbers.lithe-breakpoint{font-size:0;color:var(--vscode-debugIcon-breakpointForeground,#e51400)} .monaco-editor.lithe-line-numbers-first .line-numbers.lithe-breakpoint:before{font-size:16px} - .monaco-editor.lithe-line-numbers-first .cldr.lithe-java-run,.monaco-editor.lithe-line-numbers-first .cldr.lithe-plugin-editor-action{width:${nativeGutter.icon}px!important;margin-left:${nativeGutter.gap}px;opacity:1} - .monaco-editor.lithe-line-numbers-first .lithe-java-run-run,.monaco-editor.lithe-line-numbers-first .lithe-java-run-run-all{background-size:16px 16px} - .monaco-editor.lithe-line-numbers-first .lithe-java-run-passed,.monaco-editor.lithe-line-numbers-first .lithe-java-run-failed{background-size:14px 14px} - .monaco-editor.lithe-line-numbers-first .cldr.lithe-java-navigation{width:${nativeGutter.icon}px!important;margin-left:${nativeGutter.gap + nativeGutter.icon}px} + .monaco-editor.lithe-line-numbers-first .cldr.lithe-java-run,.monaco-editor.lithe-line-numbers-first .cldr.lithe-editor-action{width:${nativeGutter.icon}px!important;margin-left:${nativeGutter.gap}px;opacity:1} + .monaco-editor.lithe-line-numbers-first .lithe-java-run-run,.monaco-editor.lithe-line-numbers-first .lithe-java-run-run-all,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-run,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-run-all,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-debug,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-test{background-size:16px 16px} + .monaco-editor.lithe-line-numbers-first .lithe-java-run-passed,.monaco-editor.lithe-line-numbers-first .lithe-java-run-failed,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-test-passed,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-test-failed,.monaco-editor.lithe-line-numbers-first .lithe-editor-action-test-skipped{background-size:14px 14px} + .monaco-editor.lithe-line-numbers-first .cldr.lithe-java-navigation,.monaco-editor.lithe-line-numbers-first .cldr.lithe-editor-action-lane-left{width:${nativeGutter.icon}px!important;margin-left:${nativeGutter.gap + nativeGutter.icon}px} .monaco-editor.lithe-line-numbers-first .margin-view-overlays .cldr[class*="codicon-folding-"]{width:${nativeGutter.icon}px!important;margin-left:${nativeFoldingOffset}px} .monaco-editor.lithe-line-numbers-first.lithe-gutter-navigation .cldr[class*="codicon-folding-"]{margin-left:${nativeFoldingOffset + nativeGutter.icon}px} .monaco-editor.lithe-line-numbers-first .cldr[class*="codicon-folding-"]:before{content:"";width:${nativeGutter.fold}px;height:${nativeGutter.fold}px;background-repeat:no-repeat;background-position:center;background-size:${nativeGutter.fold}px ${nativeGutter.fold}px} @@ -1644,6 +1663,13 @@ export function mountWorkbench(host: WorkbenchHost) { .monaco-editor .lithe-debug-value{color:var(--vscode-editor-inlineValuesForeground,#888);background:var(--vscode-editor-inlineValuesBackground,transparent);font-style:italic}`; document.head.append(debugStyle); textmate = await installJavaTextMate(); + // The language server answers first; plugin providers only add to what it + // gave. Monaco puts the later of two equally matching providers first, so + // these register before the host's own hover and completion providers. + pluginProviders = attachPluginEditorProviders({ + entries: () => entries, request: languageRequest, + current: (id, entry) => documentCheckpoint(id, entry), + }); if (host.foldJavaImportsByDefault) monaco.languages.registerFoldingRangeProvider("java", { async provideFoldingRanges(model, _context, token) { const pair = [...entries].find(([, entry]) => entry.model === model); @@ -1912,6 +1938,7 @@ export function mountWorkbench(host: WorkbenchHost) { }); addEventListener("pagehide", () => { clearTimeout(markdownScrollTimer); + pluginProviders?.dispose(); codeActionCommand.dispose(); codeVisionCommand.dispose(); codeVisionProvider.dispose(); codeVisionChanges.dispose(); debugStyle.remove(); diff --git a/macos/EditorFrontend/main.ts b/macos/EditorFrontend/main.ts index d03166376b..9554672974 100644 --- a/macos/EditorFrontend/main.ts +++ b/macos/EditorFrontend/main.ts @@ -32,6 +32,10 @@ import passedIcon from "../Resources/IDEAIcons/expui/gutter/runSuccess.svg" with import passedIconDark from "../Resources/IDEAIcons/expui/gutter/runSuccess_dark.svg" with { type: "text" }; import failedIcon from "../Resources/IDEAIcons/expui/gutter/runError.svg" with { type: "text" }; import failedIconDark from "../Resources/IDEAIcons/expui/gutter/runError_dark.svg" with { type: "text" }; +import debugIcon from "../Resources/IDEAIcons/expui/run/debug.svg" with { type: "text" }; +import debugIconDark from "../Resources/IDEAIcons/expui/run/debug_dark.svg" with { type: "text" }; +import skippedIcon from "../Resources/IDEAIcons/expui/run/testIgnored.svg" with { type: "text" }; +import skippedIconDark from "../Resources/IDEAIcons/expui/run/testIgnored_dark.svg" with { type: "text" }; import foldIcon from "../Resources/IDEAIcons/expui/gutter/fold.svg" with { type: "text" }; import foldIconDark from "../Resources/IDEAIcons/expui/gutter/fold_dark.svg" with { type: "text" }; import unfoldIcon from "../Resources/IDEAIcons/expui/gutter/unfold.svg" with { type: "text" }; @@ -227,6 +231,16 @@ const workbench = mountWorkbench({ collapsed: { light: unfoldIcon, dark: unfoldIconDark } }, javaRunIconsDark: { run: runIconDark, "run-all": runAllIconDark, passed: passedIconDark, failed: failedIconDark }, javaRunIcons: { run: runIcon, "run-all": runAllIcon, passed: passedIcon, failed: failedIcon }, + // Keys are the icon names the host offers plugins (`PluginEditorHostOptions.macOS`). + editorActionIcons: { + run: runIcon, "run-all": runAllIcon, debug: debugIcon, test: runIcon, + "test-passed": passedIcon, "test-failed": failedIcon, "test-skipped": skippedIcon, + "navigate-super": overridingMethod, "navigate-implementations": overriddenMethod, + }, + editorActionIconsDark: { + run: runIconDark, "run-all": runAllIconDark, debug: debugIconDark, test: runIconDark, + "test-passed": passedIconDark, "test-failed": failedIconDark, "test-skipped": skippedIconDark, + }, keybindings: [ { command: "editor.action.duplicateSelection", label: "Duplicate Line or Selection", keybinding: KeyMod.CtrlCmd | KeyCode.KeyD }, { command: "editor.action.moveLinesUpAction", label: "Move Line Up", keybinding: KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow }, diff --git a/macos/Experiments/Monaco/workbench.integration.ts b/macos/Experiments/Monaco/workbench.integration.ts index d1469c9b01..d646978c3c 100644 --- a/macos/Experiments/Monaco/workbench.integration.ts +++ b/macos/Experiments/Monaco/workbench.integration.ts @@ -332,34 +332,46 @@ async function verify() { request: async payload => { if ((payload as any).type === "pluginEditorAction") { calls.push(payload); return { ok: true }; } return { batch: String(++collections), actions: [ - { id: "send", line: 1, endLine: 1, title: "Send request", icon: "run" }, + { id: "send", line: 1, endLine: 1, title: "Send request", icon: "run", + alternatives: [{ id: "debug", title: "Debug request", icon: "debug" }] }, { id: "preview", line: 1, endLine: 1, title: "Preview request", icon: "run" }, + { id: "parent", line: 1, endLine: 1, title: "Go to parent", icon: "navigate-super" }, ] }; }, }); - try { - initialEditor.setModel(model); - binding.attach(initialEditor); - await binding.refresh(); - assert(model.getAllDecorations().filter(value => value.options.linesDecorationsClassName?.includes("lithe-plugin-editor-action")).length === 1, - "same-line actions created competing gutter decorations"); + const actionDecorations = () => model.getAllDecorations() + .filter(value => value.options.linesDecorationsClassName?.includes("lithe-editor-action")); + const click = (lane: "left" | "right") => { const target = document.createElement("span"); - target.className = "lithe-plugin-editor-action"; + target.className = `lithe-editor-action lithe-editor-action-lane-${lane}`; (initialEditor as any)._onMouseDown.fire({ target: { element: target, position: new Position(1, 1) }, event: { leftButton: true, posx: 10, posy: 10, preventDefault() {}, stopPropagation() {} }, }); - assert(menu.length === 2 && menu[0].label === "Send request" && menu[1].label === "Preview request", - "same-line plugin actions lost their separate menu labels"); + }; + try { + initialEditor.setModel(model); + binding.attach(initialEditor); + await binding.refresh(); + // One marker per line and lane: run actions share one, navigation has its own. + assert(actionDecorations().length === 2, "same-line actions created competing gutter decorations"); + assert(binding.hasNavigation(entry), "navigation marker did not ask for the left lane"); + click("right"); + assert(menu.length === 3 && menu[0].label === "Send request" && menu[1].label === "Debug request" && + menu[2].label === "Preview request", "same-line plugin actions lost their menu labels or alternatives"); + await menu[1].run(); + assert(calls.length === 1 && calls[0].action === "send" && calls[0].alternative === "debug" && calls[0].batch === "1", + "alternative click did not preserve the opaque action/alternative/batch identity"); await menu[0].run(); - assert(calls.length === 1 && calls[0].action === "send" && calls[0].batch === "1", - "explicit click did not preserve the opaque action/batch identity"); + assert(calls.length === 2 && calls[1].action === "send" && !("alternative" in calls[1]), + "primary click named an alternative"); + click("left"); + assert(menu.length === 1 && menu[0].label === "Go to parent", "navigation lane menu mixed in run actions"); entry.revision++; binding.schedule("tool", entry); - assert(!model.getAllDecorations().some(value => value.options.linesDecorationsClassName?.includes("lithe-plugin-editor-action")), - "edited document kept its old action clickable"); + assert(actionDecorations().length === 0, "edited document kept its old action clickable"); await menu[0].run(); - assert(calls.length === 1, "retained menu executed an action after its batch was revoked"); + assert(calls.length === 2, "retained menu executed an action after its batch was revoked"); } finally { service.showContextMenu = originalMenu; active = false; binding.dispose(); initialEditor.setModel(previous); model.dispose(); diff --git a/macos/Resources/en.lproj/Localizable.strings b/macos/Resources/en.lproj/Localizable.strings index b9d252d8da..4f94470e84 100644 --- a/macos/Resources/en.lproj/Localizable.strings +++ b/macos/Resources/en.lproj/Localizable.strings @@ -256,6 +256,7 @@ "Add at least one absolute folder path after the package argument, one per line. Filesystem can read and write only in the folders you allow. Requires Node.js 24 or later." = "Add at least one absolute folder path after the package argument, one per line. Filesystem can read and write only in the folders you allow. Requires Node.js 24 or later."; "Add clickable actions beside document text" = "Add clickable actions beside document text"; "Add database connection" = "Add database connection"; +"Add definitions, hovers, completions and other editor features for matching files" = "Add definitions, hovers, completions and other editor features for matching files"; "Add header" = "Add header"; "Add memory usage monitoring\n\nTrack current and average memory usage in the status bar." = "Add memory usage monitoring\n\nTrack current and average memory usage in the status bar."; "Add memory usage visibility to the status bar" = "Add memory usage visibility to the status bar"; @@ -5464,6 +5465,7 @@ "native.addAtLeastOneAbsoluteFolderPathAfterThePackageArgumentOnePerLineFilesystemCanReadAndWriteOnlyInTheFoldersYouAllowRequiresNodeJs24OrLater" = "Add at least one absolute folder path after the package argument, one per line. Filesystem can read and write only in the folders you allow. Requires Node.js 24 or later."; "native.addClickableActionsBesideDocumentText" = "Add clickable actions beside document text"; "native.addDatabaseConnection" = "Add database connection"; +"native.addEditorProvidersForMatchingFiles" = "Add definitions, hovers, completions and other editor features for matching files"; "native.addHeader" = "Add header"; "native.addHook" = "Add Hook"; "native.addMemoryUsageMonitoringTrackCurrentAndAverageMemoryUsageInTheStatusBar" = "Add memory usage monitoring\n\nTrack current and average memory usage in the status bar."; diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 8aa13e6b10..48de02c69c 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -256,6 +256,7 @@ "Add at least one absolute folder path after the package argument, one per line. Filesystem can read and write only in the folders you allow. Requires Node.js 24 or later." = "在包参数后至少添加一个文件夹的绝对路径,每行一个。Filesystem 只可读写你允许的文件夹。需要 Node.js 24 或更高版本。"; "Add clickable actions beside document text" = "在文档文本旁添加可点击的操作"; "Add database connection" = "添加数据库连接"; +"Add definitions, hovers, completions and other editor features for matching files" = "为匹配的文件添加定义跳转、悬停提示、补全等编辑器功能"; "Add header" = "添加请求头"; "Add memory usage monitoring\n\nTrack current and average memory usage in the status bar." = "添加内存占用监控\n\n在状态栏显示当前及平均内存占用。"; "Add memory usage visibility to the status bar" = "在状态栏显示内存占用"; @@ -5464,6 +5465,7 @@ "native.addAtLeastOneAbsoluteFolderPathAfterThePackageArgumentOnePerLineFilesystemCanReadAndWriteOnlyInTheFoldersYouAllowRequiresNodeJs24OrLater" = "在包参数后至少添加一个文件夹的绝对路径,每行一个。Filesystem 只可读写你允许的文件夹。需要 Node.js 24 或更高版本。"; "native.addClickableActionsBesideDocumentText" = "在文档文本旁添加可点击的操作"; "native.addDatabaseConnection" = "添加数据库连接"; +"native.addEditorProvidersForMatchingFiles" = "为匹配的文件添加定义跳转、悬停提示、补全等编辑器功能"; "native.addHeader" = "添加请求头"; "native.addHook" = "添加 Hook"; "native.addMemoryUsageMonitoringTrackCurrentAndAverageMemoryUsageInTheStatusBar" = "添加内存占用监控\n\n在状态栏显示当前及平均内存占用。"; diff --git a/macos/Sources/Lithe/Application/Composition/AppServices.swift b/macos/Sources/Lithe/Application/Composition/AppServices.swift index d18f17e944..6d780df849 100644 --- a/macos/Sources/Lithe/Application/Composition/AppServices.swift +++ b/macos/Sources/Lithe/Application/Composition/AppServices.swift @@ -74,6 +74,7 @@ final class AppServices { /// `nil` when the platform runs no plugin backends. var pluginBackendActivation: (any PluginBackendActivating)? var pluginEditorActions: PluginEditorActionHostService? + var pluginEditorProviders: PluginEditorProviderHostService? /// Static plugin editor resources; `nil` when /// the platform loads no plugins. var pluginEditorLanguages: (any PluginEditorLanguageProviding)? diff --git a/macos/Sources/Lithe/Application/Features/PluginEditorActionHostService.swift b/macos/Sources/Lithe/Application/Features/PluginEditorActionHostService.swift index edc5593413..fedc312d93 100644 --- a/macos/Sources/Lithe/Application/Features/PluginEditorActionHostService.swift +++ b/macos/Sources/Lithe/Application/Features/PluginEditorActionHostService.swift @@ -40,6 +40,8 @@ final class PluginEditorActionHostService: PluginHostServiceHandling { let methods: Set = ["lithe/host/editor/registerActions"] private let contexts: PluginWorkspaceContexts private let decoder: any PluginEditorActionDecoding + /// What this host draws; Core validates every result against it. + let host: PluginEditorHostOptions private let changed = PassthroughSubject() private var entries: [UUID: PluginEditorActionRegistration] = [:] private var disposeRegistration: [UUID: @MainActor () -> Void] = [:] @@ -47,9 +49,10 @@ final class PluginEditorActionHostService: PluginHostServiceHandling { var changes: AnyPublisher { changed.eraseToAnyPublisher() } - init(contexts: PluginWorkspaceContexts, decoder: any PluginEditorActionDecoding) { + init(contexts: PluginWorkspaceContexts, decoder: any PluginEditorActionDecoding, host: PluginEditorHostOptions) { self.contexts = contexts self.decoder = decoder + self.host = host } func registrations(context: PluginWorkspaceContextReference, filename: String) -> [PluginEditorActionRegistration] { @@ -87,7 +90,7 @@ final class PluginEditorActionHostService: PluginHostServiceHandling { "selector": .object(try args.object("selector")), ]) let normalized: ToolingJSONValue - do { normalized = try decoder.decodeEditorActions(kind: "registration", value: input, text: "") } + do { normalized = try decoder.decodeEditorActions(kind: "registration", value: input, text: "", host: host) } catch { throw PluginHostArguments.invalid } guard case .object(let result) = normalized, case .object(let value)? = result["registration"], case .string(let id)? = value["id"], case .string(let functionID)? = value["function"], @@ -128,11 +131,19 @@ final class PluginEditorActionHostService: PluginHostServiceHandling { } func decode(_ result: ToolingJSONValue, text: String) throws -> [PluginEditorAction] { - let value = try decoder.decodeEditorActions(kind: "actions", value: result, text: text) + let value = try decoder.decodeEditorActions(kind: "actions", value: result, text: text, host: host) struct Response: Decodable { let actions: [PluginEditorAction] } return try JSONDecoder().decode(Response.self, from: JSONEncoder().encode(value)).actions } + /// The `reveal` of a clicked action's result, or nil when the function + /// answered without one. Other members of the result stay the plugin's own. + func decodeReveal(_ result: ToolingJSONValue) throws -> PluginEditorReveal? { + let value = try decoder.decodeEditorActions(kind: "invokeResult", value: result, text: "", host: host) + struct Response: Decodable { let reveal: PluginEditorReveal? } + return try JSONDecoder().decode(Response.self, from: JSONEncoder().encode(value)).reveal + } + func endSession(pluginID: String, sessionID: String) { guard functions[pluginID]?.session == sessionID else { return } functions[pluginID] = nil diff --git a/macos/Sources/Lithe/Application/Features/PluginEditorProviderHostService.swift b/macos/Sources/Lithe/Application/Features/PluginEditorProviderHostService.swift new file mode 100644 index 0000000000..e359d6c7ff --- /dev/null +++ b/macos/Sources/Lithe/Application/Features/PluginEditorProviderHostService.swift @@ -0,0 +1,271 @@ +import Combine +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +// Note: 编辑器 Provider 与语言服务器的合并取舍见 .agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md + +/// A context/session-owned binding of editor language-feature functions to a +/// file selector. It is not a language, Build or Run provider: a language +/// server answers first and a registration only adds to it. +struct PluginEditorProviderRegistration: Equatable { + /// One provider entry; `budget` is Core's per-type answer deadline. + struct Provider: Equatable { + let functionID: String + let budget: Duration + let triggerCharacters: [String] + let legend: ToolingJSONValue? + } + + let lease: UUID + let pluginID: String + let sessionID: String + let context: PluginWorkspaceContextReference + let id: String + let languages: [String] + let fileExtensions: [String] + let fileNames: [String] + let providers: [String: Provider] + + /// Selector entries are lowercased literals; any matching entry selects the file. + func matches(filename: String, language: String) -> Bool { + let filename = filename.lowercased() + return languages.contains(language.lowercased()) || fileNames.contains(filename) + || fileExtensions.contains { filename.hasSuffix("." + $0) } + } +} + +/// The document one provider call is about. The plugin reads its text with +/// `documents/getSnapshot` and answers for exactly `version`. +struct PluginEditorProviderDocument { + let documentID: String + let version: UInt64 + let filename: String + let language: String +} + +/// One validated provider answer with the registration that produced it. +struct PluginEditorProviderAnswer { + let registration: PluginEditorProviderRegistration + let provider: PluginEditorProviderRegistration.Provider + /// Core's normalized result for the provider type (`{locations}`, `{contents}`, ...). + let result: ToolingJSONValue +} + +/// Registration only changes a binding. It never calls a backend while the +/// backend is awaiting this host response; queries happen in a later turn. +@MainActor +final class PluginEditorProviderHostService: PluginHostServiceHandling { + /// The largest document the plugin document service can snapshot. + static let snapshotLimitBytes = 128 * 1024 + private static let registrationsPerPlugin = 32 + + let service = "editor" + let methods: Set = ["lithe/host/editor/registerProviders"] + private let contexts: PluginWorkspaceContexts + private let decoder: any PluginEditorProviderDecoding + private let providerTypes: [String] + private let logSink: (any LogSink)? + private let changed = PassthroughSubject() + private var entries: [UUID: PluginEditorProviderRegistration] = [:] + private var disposeRegistration: [UUID: @MainActor () -> Void] = [:] + private var functions: [String: (session: String, ids: Set)] = [:] + + var changes: AnyPublisher { changed.eraseToAnyPublisher() } + + init( + contexts: PluginWorkspaceContexts, decoder: any PluginEditorProviderDecoding, + host: PluginEditorHostOptions, logSink: (any LogSink)? = nil + ) { + self.contexts = contexts + self.decoder = decoder + self.providerTypes = host.providerTypes + self.logSink = logSink + } + + /// Registrations of `context` whose selector matches the file and that provide `type`. + func registrations( + context: PluginWorkspaceContextReference, filename: String, language: String, type: String + ) -> [PluginEditorProviderRegistration] { + entries.values.filter { + $0.context == context && $0.providers[type] != nil && $0.matches(filename: filename, language: language) + }.sorted { ($0.pluginID, $0.id) < ($1.pluginID, $1.id) } + } + + func contains(_ registration: PluginEditorProviderRegistration, functionID: String) -> Bool { + entries[registration.lease] == registration + && functions[registration.pluginID]?.session == registration.sessionID + && functions[registration.pluginID]?.ids.contains(functionID) == true + } + + /// Function withdrawal invalidates every registration of the plugin. A + /// plugin registers again explicitly; a reused function ID must not + /// resurrect an old binding. + func updateFunctions(pluginID: String, sessionID: String, ids: [String]) { + let ids = Set(ids) + guard functions[pluginID]?.session != sessionID || functions[pluginID]?.ids != ids else { return } + let previous = functions[pluginID] + functions[pluginID] = (sessionID, ids) + let revoked = previous?.session != sessionID || !(previous?.ids ?? []).isSubset(of: ids) + guard revoked else { return } + for entry in Array(entries.values) where entry.pluginID == pluginID { + disposeRegistration[entry.lease]?() + } + changed.send() + } + + func answer(_ call: PluginHostCall) async -> Result { + do { + let scope = try PluginHostAPIContext(call, contexts: contexts) + let args = try PluginHostArguments(call.params, allowed: ["context", "id", "selector", "providers"]) + let input: ToolingJSONValue = .object([ + "id": .string(try args.string("id")), "selector": .object(try args.object("selector")), + "providers": .object(try args.object("providers")), + ]) + let normalized: ToolingJSONValue + do { normalized = try decoder.decodeEditorProviderRegistration(value: input, types: providerTypes) } + catch let unsupported as PluginEditorProviderUnsupported { + throw PluginHostServiceError( + .unsupportedOption, L10n.string("The host does not support the requested option yet."), + details: ["option": .string(unsupported.option)]) + } catch { throw PluginHostArguments.invalid } + guard case .object(let result) = normalized, case .object(let value)? = result["registration"], + case .string(let id)? = value["id"], case .object(let selector)? = value["selector"], + case .object(let providers)? = value["providers"] else { throw PluginHostArguments.invalid } + func names(_ key: String) -> [String] { + guard case .array(let list)? = selector[key] else { return [] } + return list.compactMap { if case .string(let text) = $0 { text } else { nil } } + } + var parsed: [String: PluginEditorProviderRegistration.Provider] = [:] + for (type, entry) in providers { + guard case .object(let object) = entry, case .string(let functionID)? = object["function"], + case .integer(let budget)? = object["budgetMs"], + functions[call.pluginID]?.session == call.sessionID, + functions[call.pluginID]?.ids.contains(functionID) == true else { throw PluginHostArguments.invalid } + var triggers: [String] = [] + if case .array(let list)? = object["triggerCharacters"] { + triggers = list.compactMap { if case .string(let text) = $0 { text } else { nil } } + } + parsed[type] = .init( + functionID: functionID, budget: .milliseconds(budget), triggerCharacters: triggers, + legend: object["legend"]) + } + guard entries.values.filter({ $0.pluginID == call.pluginID }).count < Self.registrationsPerPlugin else { + throw PluginHostServiceError(.limitExceeded, L10n.string("The plugin host request could not be completed.")) + } + guard !entries.values.contains(where: { + $0.pluginID == call.pluginID && $0.context == scope.workspace.reference && $0.id == id + }) else { + throw PluginHostServiceError(.preconditionFailed, L10n.string("The plugin host request parameters are invalid.")) + } + let lease = UUID() + let registration = PluginEditorProviderRegistration( + lease: lease, pluginID: call.pluginID, sessionID: call.sessionID, context: scope.workspace.reference, + id: id, languages: names("languages"), fileExtensions: names("fileExtensions"), + fileNames: names("fileNames"), providers: parsed) + let subscription = call.subscriptions.add(pluginID: call.pluginID, contextID: scope.workspace.reference.contextID) { [weak self] in + self?.disposeRegistration[lease] = nil + guard self?.entries.removeValue(forKey: lease) != nil else { return } + self?.changed.send() + } + entries[lease] = registration + let pluginID = call.pluginID + disposeRegistration[lease] = { [weak subscriptions = call.subscriptions] in + subscriptions?.dispose(pluginID: pluginID, subscriptionID: subscription) + } + changed.send() + return .success(.object(["subscriptionID": .string(subscription)])) + } catch { + var failure = PluginHostAPIValues.failure(error) + failure.logError = error + return .failure(failure) + } + } + + func endSession(pluginID: String, sessionID: String) { + guard functions[pluginID]?.session == sessionID else { return } + functions[pluginID] = nil + for entry in Array(entries.values) where entry.pluginID == pluginID { + disposeRegistration[entry.lease]?() + } + changed.send() + } + + func closeContext(_ contextID: String) { + for entry in Array(entries.values) where entry.context.contextID == contextID { + disposeRegistration[entry.lease]?() + } + } + + /// Core's definition merge of the language server's locations with the + /// plugins'; returns the indices each side keeps. + func mergeDefinitions( + documentURL: URL, line: Int, character: Int, server: [ToolingJSONValue], plugin: [ToolingJSONValue] + ) throws -> (server: [Int], plugin: [Int]) { + try decoder.mergeEditorDefinitions( + documentURI: documentURL.standardizedFileURL.absoluteString, line: line, character: character, + server: server, plugin: plugin) + } + + /// Calls every matching provider of `type` concurrently, each within the + /// budget Core assigned its type, and returns the answers that are valid + /// and still current. A late, failed or malformed answer is dropped + /// without an error toward the user; `isCurrent` reports whether the + /// document is still the version the call was made for. + func query( + type: String, document: PluginEditorProviderDocument, context: PluginWorkspaceContextReference, + position: (line: Int, character: Int)?, triggerCharacter: String?, + backends: any PluginBackendRequesting, isCurrent: @escaping @MainActor () -> Bool + ) async -> [PluginEditorProviderAnswer] { + let registrations = self.registrations( + context: context, filename: document.filename, language: document.language, type: type) + guard !registrations.isEmpty else { return [] } + var members: [String: ToolingJSONValue] = [ + "documentID": .string(document.documentID), "version": .integer(Int(clamping: document.version)), + ] + if let position { + members["position"] = .object(["line": .integer(position.line), "character": .integer(position.character)]) + } + if let triggerCharacter { members["triggerCharacter"] = .string(triggerCharacter) } + let params: ToolingJSONValue = .object(members) + var answers: [PluginEditorProviderAnswer] = [] + await withTaskGroup(of: PluginEditorProviderAnswer?.self) { group in + for registration in registrations { + // A character-triggered request only reaches registrations that asked for that character. + guard let provider = registration.providers[type], + triggerCharacter.map({ provider.triggerCharacters.contains($0) }) ?? true else { continue } + group.addTask { @MainActor [weak self] in + await self?.invoke( + registration, provider, type: type, params: params, context: context, + backends: backends, isCurrent: isCurrent) + } + } + for await answer in group { if let answer { answers.append(answer) } } + } + return answers.sorted { ($0.registration.pluginID, $0.registration.id) < ($1.registration.pluginID, $1.registration.id) } + } + + private func invoke( + _ registration: PluginEditorProviderRegistration, _ provider: PluginEditorProviderRegistration.Provider, + type: String, params: ToolingJSONValue, context: PluginWorkspaceContextReference, + backends: any PluginBackendRequesting, isCurrent: @MainActor () -> Bool + ) async -> PluginEditorProviderAnswer? { + guard contains(registration, functionID: provider.functionID) else { return nil } + do { + let raw = try await backends.invokePluginFunction( + provider.functionID, params: params, ofPlugin: registration.pluginID, context: context, + timeout: provider.budget, progress: { _ in }) + try Task.checkCancellation() + guard isCurrent(), contains(registration, functionID: provider.functionID) else { return nil } + let decoded = try decoder.decodeEditorProviderResult(type: type, value: raw, legend: provider.legend) + guard case .object(let object) = decoded, let result = object["result"] else { return nil } + return PluginEditorProviderAnswer(registration: registration, provider: provider, result: result) + } catch { + if Task.isCancelled { return nil } + if let plugin = LogSegment(registration.pluginID) { + logSink?.emit(PluginsEditorProviderFailed(error: error, plugin: plugin)) + } + return nil + } + } +} diff --git a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift index 61c447fef7..9cd7e1fdfc 100644 --- a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift +++ b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift @@ -1882,6 +1882,8 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let workspaceConfiguration: ToolingJSONValue? /// Host services a plugin backend may request; omitted when none. let hostServices: [String]? + /// What the host declares for the services it serves; omitted when none. + let hostOptions: LspHostOptions? /// Manifest providers offered to a plugin backend; omitted when none. let toolchainProviders: [String]? /// Shortcut import providers offered to a plugin backend; omitted when none. @@ -1898,6 +1900,12 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let shutdownTimeoutMilliseconds: Int } + /// `lsp.startServer.hostOptions`: Core relays it to the plugin backend + /// through `getCapabilities`, only for the methods it grants. + private struct LspHostOptions: Encodable { + let editor: PluginEditorHostOptions + } + private struct LspJavaRuntimeRequest: Encodable { let isDefault: Bool let homePath: String @@ -3842,6 +3850,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { initializationOptions: ToolingJSONValue? = nil, workspaceConfiguration: ToolingJSONValue? = nil, hostServices: [String] = [], + editorOptions: PluginEditorHostOptions? = nil, toolchainProviders: [String] = [], keymapImportProviders: [String] = [], runtimeExecutableURL: URL? = nil, @@ -3869,6 +3878,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { initializationOptions: initializationOptions, workspaceConfiguration: workspaceConfiguration, hostServices: hostServices.isEmpty ? nil : hostServices, + hostOptions: editorOptions.map(LspHostOptions.init), toolchainProviders: toolchainProviders.isEmpty ? nil : toolchainProviders, keymapImportProviders: keymapImportProviders.isEmpty ? nil : keymapImportProviders, runtimeExecutablePath: runtimeExecutableURL?.standardizedFileURL.path, diff --git a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift index d39822c296..cad8f56bea 100644 --- a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift +++ b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift @@ -7,7 +7,7 @@ import LitheModuleAPI /// translates payloads and outcomes. struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, DeclarativeExecutionPlanning, DeclarativeLanguageServerLaunchPlanning, DeclarativePluginSettingsResolving, LanguageServerRuntimeVersionChecking, - DeclarativeEditorContributionDecoding, PluginEditorActionDecoding { + DeclarativeEditorContributionDecoding, PluginEditorActionDecoding, PluginEditorProviderDecoding { let core: RustCoreBridge func validateNativeNodes(ui: PluginNativeUI, data: ToolingJSONValue) throws -> [PluginNativeUI.Node] { @@ -310,13 +310,76 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec return outcome.value.language } - func decodeEditorActions(kind: String, value: ToolingJSONValue, text: String = "") throws -> ToolingJSONValue { - struct Payload: Encodable { let kind: String; let value: ToolingJSONValue; let text: String } + func decodeEditorActions( + kind: String, value: ToolingJSONValue, text: String = "", host: PluginEditorHostOptions + ) throws -> ToolingJSONValue { + struct Payload: Encodable { + let kind: String + let value: ToolingJSONValue + let text: String + let version = 2 + let icons: [String] + let sourceBytes: Int + } let result: ToolingJSONValue = try core.executeResult( - command: "plugins.editorActions.decode", payload: Payload(kind: kind, value: value, text: text)).get() + command: "plugins.editorActions.decode", + payload: Payload(kind: kind, value: value, text: text, icons: host.actionIcons, sourceBytes: host.actionSourceBytes) + ).get() return result } + func decodeEditorProviderRegistration(value: ToolingJSONValue, types: [String]) throws -> ToolingJSONValue { + struct Payload: Encodable { let kind = "registration"; let value: ToolingJSONValue; let types: [String] } + let outcome: Result = core.executeResult( + command: "plugins.editorProviders.decode", payload: Payload(value: value, types: types)) + switch outcome { + case .success(let result): return result + case .failure(let error): + // Core reports a type the host does not route as notSupported + // with `providers.`; every other failure is malformed input. + if error.code == "not_supported", let option = error.details, option.hasPrefix("providers.") { + throw PluginEditorProviderUnsupported(option: option) + } + throw error + } + } + + func decodeEditorProviderResult( + type: String, value: ToolingJSONValue, legend: ToolingJSONValue? + ) throws -> ToolingJSONValue { + struct Payload: Encodable { + let kind = "result" + let type: String + let value: ToolingJSONValue + let legend: ToolingJSONValue? + } + let result: ToolingJSONValue = try core.executeResult( + command: "plugins.editorProviders.decode", payload: Payload(type: type, value: value, legend: legend) + ).get() + return result + } + + func mergeEditorDefinitions( + documentURI: String, line: Int, character: Int, server: [ToolingJSONValue], plugin: [ToolingJSONValue] + ) throws -> (server: [Int], plugin: [Int]) { + struct Position: Encodable { let line: Int; let character: Int } + struct Value: Encodable { + let documentUri: String + let position: Position + let server: [ToolingJSONValue] + let plugin: [ToolingJSONValue] + } + struct Payload: Encodable { let kind = "mergeDefinitions"; let value: Value } + struct Kept: Decodable { let server: [Int]; let plugin: [Int] } + let kept: Kept = try core.executeResult( + command: "plugins.editorProviders.decode", + payload: Payload(value: Value( + documentUri: documentURI, position: Position(line: line, character: character), + server: server, plugin: plugin)) + ).get() + return (kept.server, kept.plugin) + } + func resolveSettings( manifest: Data, settings: [String: ToolingJSONValue], diff --git a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift index 767978b19f..9f9288d14a 100644 --- a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift +++ b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift @@ -317,6 +317,7 @@ extension RustCoreBridge: LanguageServerRuntimeCore { initializationOptions: initializationOptions, workspaceConfiguration: workspaceConfiguration, hostServices: hostServices, + editorOptions: .macOS, runtimeExecutableURL: hostIntegrationLaunch?.runtimeExecutableURL, jdtlsLaunchResources: hostIntegrationLaunch?.coreLaunch?.jdtlsLaunchResources, cacheDirectoryURL: cacheDirectoryURL, @@ -358,7 +359,7 @@ extension RustCoreBridge: LanguageServerRuntimeCore { lspStartServer( providerID: providerID, pluginID: pluginID, executableURL: executableURL, arguments: arguments, environment: environment, rootURL: rootURL, workingDirectoryURL: rootURL, - initializationOptions: initializationOptions, hostServices: hostServices, + initializationOptions: initializationOptions, hostServices: hostServices, editorOptions: .macOS, toolchainProviders: toolchainProviders, keymapImportProviders: keymapImportProviders, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout ).map { @@ -390,6 +391,7 @@ extension RustCoreBridge: LanguageServerRuntimeCore { workingDirectoryURL: rootURL, initializationOptions: initializationOptions, hostServices: hostServices, + editorOptions: .macOS, toolchainProviders: toolchainProviders, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, @@ -422,6 +424,7 @@ extension RustCoreBridge: LanguageServerRuntimeCore { workingDirectoryURL: rootURL, initializationOptions: initializationOptions, hostServices: hostServices, + editorOptions: .macOS, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift index dd97bb0ac4..88bc7e3703 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift @@ -29,6 +29,22 @@ extension AppModel { ) return } + if languageServerIsPreparing(for: document.url) { return } + // The command asks the same plugin providers a modifier click does. + if let pluginDefinitions = pluginDefinitionQuery( + for: document, line: caret.line, utf16Column: caret.utf16Column + ) { + if supportsLanguageServerFeature(.definition) { + performGenericNavigation( + method: "textDocument/definition", kind: .definitions, + document: document, pluginDefinitions: pluginDefinitions) + } else { + presentPluginDefinitions( + pluginDefinitions, documentURL: document.url.standardizedFileURL, + line: caret.line, utf16Column: caret.utf16Column) + } + return + } } guard languageServerFeatureIsReady( .definition, @@ -59,29 +75,39 @@ extension AppModel { /// Resolve link availability without moving the caret, recording history, or /// publishing a results panel. The bridge rejects stale document replies. + /// A read-only preview passes `askPlugins: false`, so hovering a file the + /// user only glanced at never runs plugin code. func requestDefinitionAvailability( - for document: EditorDocument, line: Int, utf16Column: Int, + for document: EditorDocument, line: Int, utf16Column: Int, askPlugins: Bool = true, completion: @escaping (Result) -> Void ) { + // Every hover supersedes the previous one, even one that ends here. + let hover = pluginDefinitionHover.begin() guard documentFeature.editorDocuments.contains(where: { $0 === document }) else { completion(.success(false)); return } if !productNavigationLocations(for: document.url, line: line, utf16Column: utf16Column).isEmpty { completion(.success(true)); return } + let complete = askPlugins + ? pluginSupplementedAvailability( + ticket: hover, for: document, line: line, utf16Column: utf16Column, completion: completion) + : completion guard let sessions = languageToolingSessionsIfActive, let workspaceURL, featureGraph.languageCapabilityPolicy.supports( .definition, documentURL: document.url, sessions: sessions - ) else { completion(.success(false)); return } + ) else { complete(.success(false)); return } do { try sessions.navigate( method: "textDocument/definition", fileURL: document.url, text: document.text, position: LanguageServerPosition(line: line, utf16Column: utf16Column), rootURL: workspaceURL - ) { result in completion(result.map { !$0.isEmpty }) } - } catch { completion(.failure(error)) } + ) { result in complete(result.map { !$0.isEmpty }) } + } catch { complete(.failure(error)) } } - func navigateToSymbol(line: Int, utf16Column: Int, in fileURL: URL) { + /// `askPlugins: false` keeps a read-only preview's click on the language + /// server alone, as for `requestDefinitionAvailability`. + func navigateToSymbol(line: Int, utf16Column: Int, in fileURL: URL, askPlugins: Bool = true) { let normalizedURL = fileURL.standardizedFileURL editorCaret = EditorCaret( url: normalizedURL, @@ -102,20 +128,30 @@ extension AppModel { ) return } - guard languageProviderCatalog.provider(for: normalizedURL)?.capabilities.contains(.languageServer) == true - else { return } - if featureGraph.languageCapabilityPolicy.supports( - .definition, - documentURL: normalizedURL, - sessions: languageToolingSessionsIfActive - ) { - performGenericNavigation( - method: "textDocument/definition", - kind: .definitions, - fallbackToImplementationsIfSelf: true, - document: openDocuments.first { $0.url.standardizedFileURL == normalizedURL } + let document = openDocuments.first { $0.url.standardizedFileURL == normalizedURL } + // Plugin providers add to the language server's answer, so both run together. + let pluginDefinitions = askPlugins ? document.flatMap { + pluginDefinitionQuery(for: $0, line: line, utf16Column: utf16Column) + } : nil + let serverCanAnswer = languageProviderCatalog.provider(for: normalizedURL)?.capabilities.contains(.languageServer) == true + && featureGraph.languageCapabilityPolicy.supports( + .definition, + documentURL: normalizedURL, + sessions: languageToolingSessionsIfActive ) + guard serverCanAnswer else { + if let pluginDefinitions { + presentPluginDefinitions(pluginDefinitions, documentURL: normalizedURL, line: line, utf16Column: utf16Column) + } + return } + performGenericNavigation( + method: "textDocument/definition", + kind: .definitions, + fallbackToImplementationsIfSelf: true, + document: document, + pluginDefinitions: pluginDefinitions + ) } func findReferences() { @@ -351,11 +387,7 @@ extension AppModel { _ feature: LanguageServerFeatureSet, unsupportedMessage: String ) -> Bool { - guard let document = focusedEditorDocument else { return false } - if isJavaLanguageServerPreparing(for: document.url) { - showJavaLanguageServerPreparingNotification() - return false - } + guard let document = focusedEditorDocument, !languageServerIsPreparing(for: document.url) else { return false } guard supportsLanguageServerFeature(feature) else { showNotification(unsupportedMessage, logReference: notificationRejection(operation: "navigation", reason: "unsupported")) return false @@ -363,12 +395,21 @@ extension AppModel { return true } + /// Whether the language server for the file is still preparing. Tells the + /// user so, rather than letting navigation report a spurious "not found". + private func languageServerIsPreparing(for fileURL: URL) -> Bool { + guard isJavaLanguageServerPreparing(for: fileURL) else { return false } + showJavaLanguageServerPreparingNotification() + return true + } + private func performGenericNavigation( method: String, kind: LanguageNavigationResultKind, navigateToSingleResult: Bool = true, fallbackToImplementationsIfSelf: Bool = false, - document requestedDocument: EditorDocument? = nil + document requestedDocument: EditorDocument? = nil, + pluginDefinitions: PluginDefinitionQuery? = nil ) { guard !languageNavigationCoordinator.state.isLoading, let document = requestedDocument ?? focusedEditorDocument, @@ -389,6 +430,38 @@ extension AppModel { caret: caret, workspaceURL: workspaceURL ) + func present(_ values: [LanguageServerLocation]) { + let fallback = languageNavigationCoordinator.implementationFallbackDecision( + method: method, + kind: kind, + values: values, + documentURL: document.url, + position: request.position, + supportsImplementation: fallbackToImplementationsIfSelf + && featureGraph.languageCapabilityPolicy.supports( + .implementation, + documentURL: document.url, + sessions: languageToolingSessionsIfActive + ) + ) + if fallback.shouldRequestImplementations { + requestGenericImplementationFallback( + document: document, + caret: caret, + workspaceURL: workspaceURL, + originalValues: fallback.originalValues, + navigateToSingleResult: navigateToSingleResult, + providerID: provider.id + ) + return + } + presentGenericNavigationValues( + values, + kind: kind, + navigateToSingleResult: navigateToSingleResult, + providerID: provider.id + ) + } do { try languageToolingSessionsIfActive?.navigate( method: request.method, @@ -406,36 +479,17 @@ extension AppModel { message: error.localizedDescription ) case .success(let values): - let fallback = self.languageNavigationCoordinator.implementationFallbackDecision( - method: method, - kind: kind, - values: values, - documentURL: document.url, - position: request.position, - supportsImplementation: fallbackToImplementationsIfSelf - && self.featureGraph.languageCapabilityPolicy.supports( - .implementation, - documentURL: document.url, - sessions: self.languageToolingSessionsIfActive - ) - ) - if fallback.shouldRequestImplementations { - self.requestGenericImplementationFallback( - document: document, - caret: caret, - workspaceURL: workspaceURL, - originalValues: fallback.originalValues, - navigateToSingleResult: navigateToSingleResult, - providerID: provider.id - ) - return + guard let pluginDefinitions else { present(values); return } + // The server answered first; the providers finish within their own budgets. + Task { @MainActor [weak self] in + let plugin = await pluginDefinitions.task.value + guard let self, self.languageNavigationCoordinator.owns(operationID) else { return } + // Locations for an older revision of the document would point at the wrong text. + guard self.isCurrent(pluginDefinitions) else { present(values); return } + present(self.mergePluginDefinitions( + server: values, plugin: plugin, documentURL: document.url, + line: request.position.line, utf16Column: request.position.utf16Column)) } - self.presentGenericNavigationValues( - values, - kind: kind, - navigateToSingleResult: navigateToSingleResult, - providerID: provider.id - ) } } } catch { @@ -517,7 +571,7 @@ extension AppModel { return springFeature.navigationLocations(for: url, line: line) } - private func presentGenericNavigationValues( + func presentGenericNavigationValues( _ values: [LanguageServerLocation], kind: LanguageNavigationResultKind, navigateToSingleResult: Bool, diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginDefinitions.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginDefinitions.swift new file mode 100644 index 0000000000..d3a0d05df5 --- /dev/null +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginDefinitions.swift @@ -0,0 +1,199 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +// Note: 编辑器 Provider 与语言服务器的合并取舍见 .agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md + +/// Plugin definition providers running for one place in one revision of a +/// document. The task never fails; a late, failed or malformed provider +/// answer contributes no locations. +struct PluginDefinitionQuery { + weak var document: EditorDocument? + let version: UInt64 + let task: Task<[LanguageServerLocation], Never> +} + +/// Keeps at most one plugin definition query running for modifier hovers +/// in a window. Each hover supersedes the one before it: the earlier query +/// is cancelled, and its language server reply can no longer start one. +@MainActor +final class PluginDefinitionHover { + private var latest = 0 + private var running: Task<[LanguageServerLocation], Never>? + + /// Starts a hover, cancelling the previous hover's query; returns its ticket. + func begin() -> Int { + running?.cancel() + running = nil + latest += 1 + return latest + } + + /// Whether `ticket` belongs to the most recent hover. + func isLatest(_ ticket: Int) -> Bool { ticket == latest } + + /// Records the query the most recent hover started, so the next hover can cancel it. + func run(_ query: Task<[LanguageServerLocation], Never>) { + running?.cancel() + running = query + } + + func finished(_ query: Task<[LanguageServerLocation], Never>) { + if running == query { running = nil } + } +} + +/// Definition providers supplement the language server's answer; they never +/// replace it. Core owns the merge rule, this file only converts locations. +extension AppModel { + /// Starts the matching plugin definition providers for the caret, or + /// returns nil when no registration matches the file so the language + /// server path runs exactly as it did before. + func pluginDefinitionQuery( + for document: EditorDocument, line: Int, utf16Column: Int + ) -> PluginDefinitionQuery? { + guard let service = services.pluginEditorProviders, let backends = pluginWebBackends, + let context = pluginWebWorkspaceContext, + services.pluginWorkspaceContexts?.contexts.contains(where: { + $0.reference == context && $0.authority == .local + }) == true, + document.text.utf8.count <= PluginEditorProviderHostService.snapshotLimitBytes else { return nil } + // The editor frontend names the language itself for its own requests; + // this path knows only the language provider that owns the file. + let language = languageProviderCatalog.provider(for: document.url)?.id ?? "" + let filename = document.url.lastPathComponent + guard !service.registrations(context: context, filename: filename, language: language, type: "definition").isEmpty + else { return nil } + let version = document.contentVersion + let item = PluginEditorProviderDocument( + documentID: document.id.uuidString, version: version, filename: filename, language: language) + let task = Task { @MainActor [weak self, weak document] in + let answers = await service.query( + type: "definition", document: item, context: context, position: (line, utf16Column), + triggerCharacter: nil, backends: backends, + isCurrent: { [weak self, weak document] in + self?.isOpen(document, at: version) == true + }) + return answers.flatMap { Self.pluginLocations(in: $0.result).compactMap(Self.languageServerLocation) } + } + return PluginDefinitionQuery(document: document, version: version, task: task) + } + + /// Whether the query's document is still open at the revision it asked + /// about. Checked where locations are shown: the query finishing and its + /// awaiting caller resuming are separate turns, and an edit can fall between. + func isCurrent(_ query: PluginDefinitionQuery) -> Bool { + isOpen(query.document, at: query.version) + } + + private func isOpen(_ document: EditorDocument?, at version: UInt64) -> Bool { + guard let document else { return false } + return document.contentVersion == version && documentFeature.editorDocuments.contains { $0 === document } + } + + /// A file with no language server answer still shows what its plugin + /// providers found, such as a key's entry in another file. + func presentPluginDefinitions(_ query: PluginDefinitionQuery, documentURL: URL, line: Int, utf16Column: Int) { + Task { @MainActor [weak self] in + let plugin = await query.task.value + // The document was edited or the caret moved on while the providers answered. + guard let self, !plugin.isEmpty, self.isCurrent(query), let caret = self.editorCaret, + caret.url.standardizedFileURL == documentURL, caret.line == line, caret.utf16Column == utf16Column + else { return } + let locations = self.mergePluginDefinitions( + server: [], plugin: plugin, documentURL: documentURL, line: line, utf16Column: utf16Column) + self.presentGenericNavigationValues(locations, kind: .definitions, navigateToSingleResult: true, providerID: nil) + } + } + + /// Wraps the link-availability completion of the hover `ticket`: when the + /// language server found nothing, the plugin providers get to say whether + /// the place is a link. Only the most recent hover asks them. + func pluginSupplementedAvailability( + ticket: Int, for document: EditorDocument, line: Int, utf16Column: Int, + completion: @escaping (Result) -> Void + ) -> (Result) -> Void { + { [weak self] result in + guard case .success(false) = result, let self, self.pluginDefinitionHover.isLatest(ticket), + let query = self.pluginDefinitionQuery(for: document, line: line, utf16Column: utf16Column) + else { completion(result); return } + self.pluginDefinitionHover.run(query.task) + Task { @MainActor [weak self] in + let locations = await query.task.value + self?.pluginDefinitionHover.finished(query.task) + completion(.success(!locations.isEmpty && self?.isCurrent(query) == true)) + } + } + } + + /// The language server's locations first, then the plugin locations it + /// did not already give. A server location that is the requested place + /// itself yields when a plugin answered. Core validates and decides; when + /// it refuses a list the language server's answer stands alone. + func mergePluginDefinitions( + server: [LanguageServerLocation], plugin: [LanguageServerLocation], + documentURL: URL, line: Int, utf16Column: Int + ) -> [LanguageServerLocation] { + guard !plugin.isEmpty, let service = services.pluginEditorProviders else { return server } + do { + let kept = try service.mergeDefinitions( + documentURL: documentURL, line: line, character: utf16Column, + server: server.map(Self.locationValue), plugin: plugin.map(Self.locationValue)) + return kept.server.compactMap { server.indices.contains($0) ? server[$0] : nil } + + kept.plugin.compactMap { plugin.indices.contains($0) ? plugin[$0] : nil } + } catch { + showNotification( + L10n.string("The plugin host request could not be completed."), + logReference: notificationFailure(error, operation: "plugin_definitions")) + return server + } + } + + /// Presents locations a clicked editor action asked the host to reveal. + func revealPluginLocations(_ reveal: PluginEditorReveal) { + let locations = reveal.locations.compactMap(Self.languageServerLocation) + guard !locations.isEmpty else { return } + presentGenericNavigationValues(locations, kind: .definitions, navigateToSingleResult: true, providerID: nil) + } + + /// Opens a clicked document link a plugin provided: a file inside the + /// workspace in the editor, a web address in the default browser. Other + /// targets were already dropped; a file outside the workspace is ignored. + func openPluginDocumentLink(_ url: URL) { + guard url.isFileURL else { platformUI.open(url); return } + guard let root = workspaceURL?.standardizedFileURL.resolvingSymlinksInPath() else { return } + let file = url.standardizedFileURL.resolvingSymlinksInPath() + guard file.path.hasPrefix(root.path + "/") else { return } + openFile(file) + } + + private static func pluginLocations(in result: ToolingJSONValue) -> [PluginEditorReveal.Location] { + struct Response: Decodable { let locations: [PluginEditorReveal.Location] } + do { + return try JSONDecoder().decode(Response.self, from: JSONEncoder().encode(result)).locations + } catch { // log-exempt: Core 已校验形状;解码失败只表示这一个 Provider 没有可补充的位置 + return [] + } + } + + /// Plugin locations are file locations only; any other scheme is dropped. + private static func languageServerLocation(_ location: PluginEditorReveal.Location) -> LanguageServerLocation? { + guard let url = URL(string: location.uri), url.isFileURL else { return nil } + func position(_ value: PluginEditorReveal.Position) -> LanguageServerPosition { + LanguageServerPosition(line: value.line, utf16Column: value.character) + } + return LanguageServerLocation( + url: url.standardizedFileURL, + range: LanguageServerRange(start: position(location.range.start), end: position(location.range.end))) + } + + private static func locationValue(_ location: LanguageServerLocation) -> ToolingJSONValue { + func position(_ value: LanguageServerPosition) -> ToolingJSONValue { + .object(["line": .integer(value.line), "character": .integer(value.utf16Column)]) + } + return .object([ + "uri": .string(location.url.standardizedFileURL.absoluteString), + "range": .object(["start": position(location.range.start), "end": position(location.range.end)]), + ]) + } +} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel.swift b/macos/Sources/Lithe/Models/AppModel/AppModel.swift index bf141c3273..081d84a6a9 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel.swift @@ -160,6 +160,8 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { private var shortcutSessionCoordinator: ShortcutSessionCoordinator? private var documentLanguageCoordinator: DocumentLanguageCoordinator? private var sidebarRefreshTask: Task? + /// The modifier hover's plugin definition query; a newer hover cancels it. + let pluginDefinitionHover = PluginDefinitionHover() private var moduleSessionCoordinator: ModuleSessionCoordinator? var isModuleRuntimeShuttingDown: Bool { moduleSessionCoordinator?.isShuttingDown == true } private(set) var isProjectSessionClosed = false diff --git a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift index b7eb189cab..d5d8ec94c3 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift @@ -471,8 +471,12 @@ final class MacServiceContainer { hostDispatcher.register(workspaceHost) hostDispatcher.register(PluginDocumentHostService(contexts: .shared)) hostDispatcher.register(PluginTerminalHostService(contexts: .shared, metadata: workspaceHost)) - let editorActions = PluginEditorActionHostService(contexts: .shared, decoder: declarativePluginOperations) + let editorActions = PluginEditorActionHostService( + contexts: .shared, decoder: declarativePluginOperations, host: .macOS) hostDispatcher.register(editorActions) + let editorProviders = PluginEditorProviderHostService( + contexts: .shared, decoder: declarativePluginOperations, host: .macOS, logSink: logSink) + hostDispatcher.register(editorProviders) hostDispatcher.register(PluginFileHostService(contexts: .shared, metadata: workspaceHost, files: MacPluginWorkspaceFileService( searchOperations: RustWorkspaceOperations(core: rustCore), @@ -506,6 +510,7 @@ final class MacServiceContainer { hostDispatcher: hostDispatcher ) sessions.editorActions = editorActions + sessions.editorProviders = editorProviders sessions.onActivationFailure = { pluginID, error in if let plugin = LogSegment(pluginID) { logSink?.emit(PluginsBackendActivationFailed(error: error, plugin: plugin)) } } @@ -1216,6 +1221,7 @@ final class MacServiceContainer { } } services.pluginEditorActions = pluginBackends.editorActions + services.pluginEditorProviders = pluginBackends.editorProviders services.pluginEditorLanguages = MacPluginEditorLanguages( launchRegistered: pluginStartup.registeredPlugins, isModuleUsable: { [weak moduleRuntime] id in diff --git a/macos/Sources/Lithe/Platform/MacOS/MonacoPluginEditorProviders.swift b/macos/Sources/Lithe/Platform/MacOS/MonacoPluginEditorProviders.swift new file mode 100644 index 0000000000..e4c56503b3 --- /dev/null +++ b/macos/Sources/Lithe/Platform/MacOS/MonacoPluginEditorProviders.swift @@ -0,0 +1,268 @@ +import Combine +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +// Note: 编辑器 Provider 与语言服务器的合并取舍见 .agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md + +/// Bridges the web editor's language-feature requests to the plugin editor +/// providers registered on this window's workspace context. The web editor +/// only names a provider type and a position; function IDs, registrations and +/// code lens parameters stay behind opaque per-batch keys on this side, and +/// every answer is validated by Core before it reaches the page. +@MainActor +final class MonacoPluginEditorProviders { + /// Provider types the page asks for. Definitions are answered through the + /// host's own navigation (see `AppModel.pluginDefinitionQuery`). + static let pageTypes: Set = ["hover", "completion", "codeLens", "foldingRange", "semanticTokens", "documentLink"] + private static let maximumRequests = 32 + private static let maximumExecutions = 16 + private static let maximumLenses = 1000 + private static let maximumLinks = 1000 + /// Link targets the host opens itself; any other scheme is dropped. + private static let linkSchemes: Set = ["http", "https", "file"] + + private struct LensItem { + let registration: PluginEditorProviderRegistration + let functionID: String + let params: ToolingJSONValue + } + private struct LensList { + let batch: String + let version: UInt64 + let items: [String: LensItem] + } + private struct LinkList { + let batch: String + let version: UInt64 + let targets: [String: URL] + } + private var lensLists: [String: LensList] = [:] + private var linkLists: [String: LinkList] = [:] + private var requests: [UUID: (documentID: String, task: Task)] = [:] + private var executions: [UUID: (documentID: String, item: LensItem, task: Task)] = [:] + private var subscription: AnyCancellable? + + /// Cancels in-flight requests when a registration is withdrawn or added, + /// then asks the page to ask again. Every list the page holds is stale. + func observe(model: AppModel, refresh: @escaping @MainActor () -> Void) { + guard subscription == nil, let service = model.services.pluginEditorProviders else { return } + subscription = service.changes.receive(on: DispatchQueue.main).sink { [weak self, weak service] in + guard let self, let service else { return } + self.cancelRequests() + self.lensLists.removeAll() + self.linkLists.removeAll() + for (id, execution) in self.executions + where !service.contains(execution.item.registration, functionID: execution.item.functionID) { + execution.task.cancel() + self.executions[id] = nil + } + refresh() + } + } + + /// Forgets one document's lists; `closing` also cancels its executions. + func cancel(documentID: String, closing: Bool) { + lensLists[documentID] = nil + linkLists[documentID] = nil + for (id, request) in requests where request.documentID == documentID { + request.task.cancel() + requests[id] = nil + } + if closing { + for (id, execution) in executions where execution.documentID == documentID { + execution.task.cancel() + executions[id] = nil + } + } + } + + func cancelAll() { + cancelRequests() + executions.values.forEach { $0.task.cancel() } + executions.removeAll() + lensLists.removeAll() + linkLists.removeAll() + } + + private func cancelRequests() { + requests.values.forEach { $0.task.cancel() } + requests.removeAll() + } + + /// Answers one `pluginEditorProviders` page message. `isCurrent` reports + /// whether the document is still the revision the page asked about. A + /// request nothing applies to gets the type's empty answer, so the page + /// falls back to the language server alone. + func answer( + body: [String: Any], document: EditorDocument, documentID: String, model: AppModel, + isCurrent: @escaping @MainActor () -> Bool, reply: @escaping (Any?, String?) -> Void + ) { + guard let type = body["provider"] as? String, Self.pageTypes.contains(type), + let language = body["language"] as? String else { reply(nil, "Invalid provider request"); return } + guard isCurrent() else { reply(["cancelled": true], nil); return } + var position: (line: Int, character: Int)? + if type == "hover" || type == "completion" { + guard let line = body["line"] as? Int, let character = body["character"] as? Int, + line >= 0, character >= 0 else { reply(nil, "Invalid provider position"); return } + position = (line, character) + } + let version = document.contentVersion + let item = PluginEditorProviderDocument( + documentID: documentID, version: version, filename: document.url.lastPathComponent, language: language) + guard let service = model.services.pluginEditorProviders, let backends = model.pluginWebBackends, + let workspace = model.pluginWebWorkspaceContext, + model.services.pluginWorkspaceContexts?.contexts.contains(where: { $0.reference == workspace && $0.authority == .local }) == true, + document.text.utf8.count <= PluginEditorProviderHostService.snapshotLimitBytes, + !service.registrations(context: workspace, filename: item.filename, language: language, type: type).isEmpty, + requests.count < Self.maximumRequests else { + reply(payload(type: type, answers: [], service: nil, documentID: documentID, version: version).foundationObject, nil) + return + } + let requestID = UUID() + let trigger = body["triggerCharacter"] as? String + let task = Task { @MainActor [weak self, weak document] in + let answers = await service.query( + type: type, document: item, context: workspace, position: position, triggerCharacter: trigger, + backends: backends, + isCurrent: { [weak document] in isCurrent() && document?.contentVersion == version }) + defer { self?.requests[requestID] = nil } + guard let self, let document, !Task.isCancelled, isCurrent(), document.contentVersion == version else { + reply(["cancelled": true], nil); return + } + reply(self.payload(type: type, answers: answers, service: service, documentID: documentID, version: version).foundationObject, nil) + } + requests[requestID] = (documentID, task) + } + + /// The page's view of the answers: Core's normalized shapes, merged for + /// the type. Lens commands become opaque keys; nothing private to a + /// plugin is handed to the page. + private func payload( + type: String, answers: [PluginEditorProviderAnswer], service: PluginEditorProviderHostService?, + documentID: String, version: UInt64 + ) -> ToolingJSONValue { + func members(_ answer: PluginEditorProviderAnswer, _ key: String) -> [ToolingJSONValue] { + guard case .object(let result) = answer.result, case .array(let list)? = result[key] else { return [] } + return list + } + switch type { + case "hover": + var range: ToolingJSONValue? + for answer in answers where range == nil { + if case .object(let result) = answer.result { range = result["range"] } + } + var value: [String: ToolingJSONValue] = ["contents": .array(answers.flatMap { members($0, "contents") })] + value["range"] = range + return .object(value) + case "completion": + let incomplete = answers.contains { + if case .object(let result) = $0.result, case .bool(true)? = result["isIncomplete"] { true } else { false } + } + return .object(["isIncomplete": .bool(incomplete), "items": .array(answers.flatMap { members($0, "items") })]) + case "codeLens": + var items: [String: LensItem] = [:] + var lenses: [ToolingJSONValue] = [] + for answer in answers { + for lens in members(answer, "lenses") { + guard case .object(let object) = lens, let range = object["range"], + case .object(let command)? = object["command"], case .string(let title)? = command["title"], + case .string(let functionID)? = command["command"], case .array(let arguments)? = command["arguments"], + let params = arguments.first, + service?.contains(answer.registration, functionID: functionID) == true, + items.count < Self.maximumLenses else { continue } + let key = UUID().uuidString + items[key] = LensItem(registration: answer.registration, functionID: functionID, params: params) + lenses.append(.object(["id": .string(key), "range": range, "title": .string(title)])) + } + } + // Nothing to click: no list to remember. + guard !items.isEmpty else { return .object(["batch": .string(""), "lenses": .array([])]) } + let batch = UUID().uuidString + lensLists[documentID] = LensList(batch: batch, version: version, items: items) + return .object(["batch": .string(batch), "lenses": .array(lenses)]) + case "foldingRange": + return .object(["ranges": .array(answers.flatMap { members($0, "ranges") })]) + case "semanticTokens": + // Registrations may declare different legends, so each answer keeps its own. + return .object(["responses": .array(answers.compactMap { answer in + guard case .object(let result) = answer.result, let data = result["data"], let legend = answer.provider.legend else { return nil } + return .object(["legend": legend, "data": data]) + })]) + default: + var targets: [String: URL] = [:] + var links: [ToolingJSONValue] = [] + for answer in answers { + for link in members(answer, "links") { + guard case .object(let object) = link, let range = object["range"], + case .string(let target)? = object["target"], let url = URL(string: target), + let scheme = url.scheme?.lowercased(), Self.linkSchemes.contains(scheme), + targets.count < Self.maximumLinks else { continue } + let key = UUID().uuidString + targets[key] = url + var entry: [String: ToolingJSONValue] = ["id": .string(key), "range": range] + entry["tooltip"] = object["tooltip"] + links.append(.object(entry)) + } + } + // Nothing to click: no list to remember. + guard !targets.isEmpty else { return .object(["batch": .string(""), "links": .array([])]) } + let batch = UUID().uuidString + linkLists[documentID] = LinkList(batch: batch, version: version, targets: targets) + return .object(["batch": .string(batch), "links": .array(links)]) + } + } + + /// Opens the target of a clicked document link. The page names only the + /// opaque batch and link keys, so a plugin's target never comes from the page. + func open( + body: [String: Any], document: EditorDocument, documentID: String, model: AppModel, + isCurrent: @escaping @MainActor () -> Bool, reply: @escaping (Any?, String?) -> Void + ) { + guard isCurrent(), let list = linkLists[documentID], list.batch == body["batch"] as? String, + list.version == document.contentVersion, let key = body["link"] as? String, + let url = list.targets[key] else { reply(["cancelled": true], nil); return } + model.openPluginDocumentLink(url) + reply(["ok": true], nil) + } + + /// Runs the function of a clicked code lens. The page names only the + /// opaque batch and lens keys. + func run( + body: [String: Any], document: EditorDocument, documentID: String, model: AppModel, + isCurrent: @escaping @MainActor () -> Bool, reply: @escaping (Any?, String?) -> Void + ) { + guard isCurrent(), let list = lensLists[documentID], list.batch == body["batch"] as? String, + list.version == document.contentVersion, let key = body["lens"] as? String, let item = list.items[key], + let service = model.services.pluginEditorProviders, + service.contains(item.registration, functionID: item.functionID), + model.pluginWebWorkspaceContext == item.registration.context, let backends = model.pluginWebBackends, + executions.count < Self.maximumExecutions else { reply(["cancelled": true], nil); return } + model.editorDidFocus(document) + let operation = UUID() + let params: ToolingJSONValue = .object([ + "documentID": .string(documentID), "expectedVersion": .integer(Int(clamping: list.version)), "data": item.params, + ]) + let task = Task { @MainActor [weak self, weak model] in + defer { self?.executions[operation] = nil } + do { + _ = try await backends.invokePluginFunction( + item.functionID, params: params, ofPlugin: item.registration.pluginID, + context: item.registration.context, timeout: .seconds(60), progress: { _ in }) + try Task.checkCancellation() + reply(["ok": true], nil) + } catch { + if Task.isCancelled { reply(["cancelled": true], nil); return } + var reference: LogRecordReference? + if let plugin = LogSegment(item.registration.pluginID) { + let event = PluginsEditorProviderFailed(error: error, plugin: plugin) + model?.services.logSink?.emit(event) + reference = event.reference + } + model?.showNotification(L10n.string("The plugin host request could not be completed."), logReference: reference) + reply(["ok": false], nil) + } + } + executions[operation] = (documentID, item, task) + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift b/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift index 64f33b71c9..46c68d1054 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift @@ -327,6 +327,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele private var pluginActionRequests: [String: (id: UUID, task: Task, deadline: Task)] = [:] private var pluginActionExecutions: [UUID: (documentID: String, registration: PluginEditorActionRegistration, task: Task)] = [:] private var pluginActionsSubscription: AnyCancellable? + private let pluginProviders = MonacoPluginEditorProviders() private var pluginLanguagesSubscription: AnyCancellable? private var lastPluginLanguages: PluginEditorLanguageSet? private var testOutcomeSubscription: AnyCancellable? @@ -621,6 +622,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele subscriptions[id] = document.textDidChange.sink { [weak self, weak document] in guard let self, let document, self.currentDocument(id) === document, !self.applyingEdit else { return } self.cancelPluginActions(for: id) + self.pluginProviders.cancel(documentID: id, closing: false) let previous = self.revisions[id] ?? 0 self.revisions[id] = previous + 1 self.call("window.lithe.replace(payload)", arguments: ["payload": ["id": id, "text": document.text, "previousRevision": previous, "revision": previous + 1]]) @@ -776,6 +778,19 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } } + /// Provider registrations are per window; whenever they change the page + /// drops what it holds and asks again. + private func observePluginProviders(model: AppModel) { + pluginProviders.observe(model: model) { [weak self] in + guard let self, self.ready, !self.failed else { return } + self.call("window.lithe.refreshPluginEditorProviders()") { result in + if case .failure(let error) = result { + self.model?.services.logSink?.emit(PluginsEditorRefreshFailed(error: error)) + } + } + } + } + private func observePluginActions(model: AppModel) { guard pluginActionsSubscription == nil, let service = model.services.pluginEditorActions else { return } pluginActionsSubscription = service.changes.receive(on: DispatchQueue.main).sink { [weak self, weak service] in @@ -916,6 +931,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele // Before the document: its file may be of a plugin language. observePluginLanguages(model: model) observePluginActions(model: model) + observePluginProviders(model: model) let id = document.id.uuidString let groupDocuments: [EditorDocument] if let scopedDocumentID { @@ -940,6 +956,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele javaRunMarkerLists[oldID] = nil javaRunMarkerRequests[oldID] = nil cancelPluginActions(for: oldID, closing: true) + pluginProviders.cancel(documentID: oldID, closing: true) lastGitStates[oldID] = nil gitLoads.removeValue(forKey: oldID)?.cancel() blameLoads.removeValue(forKey: oldID)?.cancel() @@ -1157,7 +1174,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele func allowsMessage(_ type: String) -> Bool { !isReadOnlyPreview || !["format", "codeActions", "resolveCodeAction", "executeCodeAction", "rename", "resolveCompletion", "javaRunMarkerAction", "pluginEditorAction", - "setBlameVisibility"].contains(type) + "pluginEditorProviderCommand", "setBlameVisibility"].contains(type) } func receive(_ message: WKScriptMessage, reply: @escaping (Any?, String?) -> Void) { @@ -1316,7 +1333,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele let workspace = model.pluginWebWorkspaceContext, model.services.pluginWorkspaceContexts?.contexts.contains(where: { $0.reference == workspace && $0.authority == .local }) == true, let service = model.services.pluginEditorActions, let backends = model.pluginWebBackends, - document.text.utf8.count <= 128 * 1024 else { reply(["actions": []], nil); return } + document.text.utf8.count <= service.host.actionSourceBytes else { reply(["actions": []], nil); return } cancelPluginActions(for: id) let registrations = service.registrations(context: workspace, filename: document.url.lastPathComponent) let text = document.text, version = document.contentVersion, requestID = UUID(), batch = UUID().uuidString @@ -1345,7 +1362,9 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele ofPlugin: registration.pluginID, context: workspace, timeout: remaining, progress: { _ in }) try Task.checkCancellation() let actions = try service.decode(result, text: text) - guard service.contains(registration), actions.allSatisfy({ service.contains(registration, functionID: $0.invoke.functionID) }) else { continue } + guard service.contains(registration), + actions.allSatisfy({ action in action.functionIDs.allSatisfy { service.contains(registration, functionID: $0) } }) + else { continue } for action in actions { items.append((UUID().uuidString, registration, action)) } guard items.count <= 1000 else { items = []; break } } catch { @@ -1355,14 +1374,15 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } guard let self, let document, !Task.isCancelled, self.isCurrent(context), document.contentVersion == version, self.pluginActionRequests[id]?.id == requestID, - items.allSatisfy({ service.contains($0.registration, functionID: $0.action.invoke.functionID) }) else { + items.allSatisfy({ item in item.action.functionIDs.allSatisfy { service.contains(item.registration, functionID: $0) } }) else { reply(["cancelled": true], nil); return } self.pluginActionRequests.removeValue(forKey: id)?.deadline.cancel() self.pluginActionLists[id] = EditorActionList(context: context, contentVersion: version, batch: batch, actions: items) reply(["batch": batch, "actions": items.map { item in ["id": item.key, "line": item.action.range.start.line, "endLine": item.action.range.end.line, - "title": item.action.title, "icon": item.action.icon] as [String: Any] + "title": item.action.title, "icon": item.action.icon, + "alternatives": item.action.alternatives.map { ["id": $0.id, "title": $0.title, "icon": $0.icon] }] as [String: Any] }], nil) } let deadline = Task { @MainActor [weak self] in @@ -1379,23 +1399,28 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele isCurrent(list.context), list.contentVersion == document.contentVersion, let key = body["action"] as? String, let item = list.actions.first(where: { $0.key == key }), let service = model.services.pluginEditorActions, - service.contains(item.registration, functionID: item.action.invoke.functionID), + let chosen = Self.chosenInvocation(of: item.action, alternativeID: body["alternative"]), + service.contains(item.registration, functionID: chosen.invoke.functionID), model.pluginWebWorkspaceContext == item.registration.context, let backends = model.pluginWebBackends, pluginActionExecutions.count < 16 else { reply(["cancelled": true], nil); return } model.editorDidFocus(document) let operation = UUID() - let params: ToolingJSONValue = .object([ + var members: [String: ToolingJSONValue] = [ "documentID": .string(id), "expectedVersion": .integer(Int(clamping: list.contentVersion)), - "actionID": .string(item.action.id), "data": item.action.invoke.params, - ]) + "actionID": .string(item.action.id), "data": chosen.invoke.params, + ] + if let alternativeID = chosen.alternativeID { members["alternativeID"] = .string(alternativeID) } + let params = ToolingJSONValue.object(members) let task = Task { @MainActor [weak self] in defer { self?.pluginActionExecutions[operation] = nil } do { - _ = try await backends.invokePluginFunction(item.action.invoke.functionID, params: params, + let result = try await backends.invokePluginFunction(chosen.invoke.functionID, params: params, ofPlugin: item.registration.pluginID, context: item.registration.context, timeout: .seconds(60), progress: { _ in }) try Task.checkCancellation() + // The plugin may point at places the click led to; showing them is the host's job. + if let reveal = try service.decodeReveal(result) { self?.model?.revealPluginLocations(reveal) } reply(["ok": true], nil) } catch { if Task.isCancelled { reply(["cancelled": true], nil) } @@ -1406,12 +1431,31 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele self?.model?.services.logSink?.emit(event) reference = event.reference } - self?.model?.showNotification("The plugin host request could not be completed.", logReference: reference) + self?.model?.showNotification( + L10n.string("The plugin host request could not be completed."), logReference: reference) reply(["ok": false], nil) } } } pluginActionExecutions[operation] = (id, item.registration, task) + case "pluginEditorProviders": + guard let model, !failed, !isReadOnlyPreview, body["revision"] as? Int == revisions[id] else { + reply(["cancelled": true], nil); return + } + pluginProviders.answer(body: body, document: document, documentID: id, model: model, + isCurrent: { [weak self] in self?.isCurrent(context) == true }, reply: reply) + case "pluginEditorProviderCommand": + guard let model, !failed, !isReadOnlyPreview, !self.isReadOnly(document), body["revision"] as? Int == revisions[id] else { + reply(["cancelled": true], nil); return + } + pluginProviders.run(body: body, document: document, documentID: id, model: model, + isCurrent: { [weak self] in self?.isCurrent(context) == true }, reply: reply) + case "pluginEditorProviderLink": + guard let model, !failed, !isReadOnlyPreview, body["revision"] as? Int == revisions[id] else { + reply(["cancelled": true], nil); return + } + pluginProviders.open(body: body, document: document, documentID: id, model: model, + isCurrent: { [weak self] in self?.isCurrent(context) == true }, reply: reply) case "javaNavigationAction": guard let model, !failed, let revision = body["revision"] as? Int, revision == revisions[id], let list = javaNavigationLists[id], isCurrent(list.context), list.revision == revision, list.url == document.url, @@ -1549,6 +1593,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } case "edit": cancelPluginActions(for: id) + pluginProviders.cancel(documentID: id, closing: false) guard !self.isReadOnly(document), !failed, body["baseRevision"] as? Int == revisions[id], let changes = body["changes"] as? [[String: Any]] else { reply(nil, "Stale editor edit"); return } var bound = (document.text as NSString).length @@ -1845,7 +1890,9 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele reply(["available": false], nil); return } let revision = revisions[id] - model.requestDefinitionAvailability(for: document, line: line, utf16Column: column) { [weak self] result in + model.requestDefinitionAvailability( + for: document, line: line, utf16Column: column, askPlugins: !isReadOnlyPreview + ) { [weak self] result in guard let self, self.isCurrent(context), self.revisions[id] == revision else { reply(["available": false], nil); return } @@ -1860,12 +1907,23 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele reply(["cancelled": true], nil); return } model.editorDidFocus(document) - model.navigateToSymbol(line: line, utf16Column: column, in: document.url) + model.navigateToSymbol(line: line, utf16Column: column, in: document.url, askPlugins: !isReadOnlyPreview) reply(["ok": true], nil) default: reply(nil, "Unknown editor message") } } + /// The invocation a click on `action` calls: its own, or the alternative + /// the page named. nil when the page named an alternative the action lacks. + private static func chosenInvocation( + of action: PluginEditorAction, alternativeID: Any? + ) -> (invoke: PluginEditorAction.Invocation, alternativeID: String?)? { + guard let alternativeID, !(alternativeID is NSNull) else { return (action.invoke, nil) } + guard let id = alternativeID as? String, + let alternative = action.alternatives.first(where: { $0.id == id }) else { return nil } + return (alternative.invoke, id) + } + private static func completionPayload(_ item: LanguageServerCompletionItem) -> [String: Any] { func range(_ value: LanguageServerRange) -> [String: Int] { ["startLineNumber": value.start.line + 1, "startColumn": value.start.utf16Column + 1, @@ -1886,6 +1944,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele pluginActionRequests.values.forEach { $0.deadline.cancel(); $0.task.cancel() } pluginActionExecutions.values.forEach { $0.task.cancel() } pluginActionRequests.removeAll(); pluginActionExecutions.removeAll(); pluginActionLists.removeAll() + pluginProviders.cancelAll() contextMenu.dismiss() model?.showNotification("Editor: \(message)", logReference: model?.notificationRejection(operation: "editor", reason: "web_content_failed")) } @@ -1898,6 +1957,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele isolated deinit { pluginActionRequests.values.forEach { $0.deadline.cancel(); $0.task.cancel() } pluginActionExecutions.values.forEach { $0.task.cancel() } + pluginProviders.cancelAll() contextMenu.dismiss() gitLoads.values.forEach { $0.cancel() } blameLoads.values.forEach { $0.cancel() } diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift index a6b9ea08b4..e16fe90007 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift @@ -91,6 +91,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi /// Reports a backend that an activation event failed to start; the /// workspace or command goes on without it. var editorActions: PluginEditorActionHostService? + var editorProviders: PluginEditorProviderHostService? var onActivationFailure: (@MainActor (_ pluginID: String, _ error: Error) -> Void)? private static let maximumBackgroundStarts = 2 private static let maximumPendingNotifications = 128 @@ -674,6 +675,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi entry.hostServices = Set(hostServices) session.onFunctionsChange = { [weak self] ids in self?.editorActions?.updateFunctions(pluginID: pluginID, sessionID: sessionToken, ids: ids) + self?.editorProviders?.updateFunctions(pluginID: pluginID, sessionID: sessionToken, ids: ids) } session.onHostRequest = { [weak session] request in hostDispatcher.handle(request, pluginID: pluginID, sessionID: sessionToken) { outcome in diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift new file mode 100644 index 0000000000..9987de5e7c --- /dev/null +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift @@ -0,0 +1,23 @@ +import LitheCoreContracts + +// Note: 编辑器扩展点的契约与宿主声明见 .agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md + +extension PluginEditorHostOptions { + /// What the macOS editor draws and routes. The icon names are the keys of + /// `editorActionIcons` in `macos/EditorFrontend/main.ts`; each maps to an + /// IDEA icon resource bundled with the web editor, so a name declared + /// here without a resource there would draw nothing. + /// + /// Core relays this to a plugin backend through `getCapabilities` and + /// validates registrations and results against it. + static let macOS = PluginEditorHostOptions( + actionIcons: [ + "run", "run-all", "debug", "test", "test-passed", "test-failed", "test-skipped", + "navigate-super", "navigate-implementations", + ], + actionSourceBytes: 1024 * 1024, + providerTypes: [ + "definition", "hover", "completion", "codeLens", "foldingRange", "semanticTokens", "documentLink", + ] + ) +} diff --git a/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift b/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift index e2968dc096..88daaa7041 100644 --- a/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift +++ b/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift @@ -767,6 +767,8 @@ enum PluginMarketplacePresentation { PluginMarketplacePresentation.localized("Start a language server when you open files of its language", locale: locale) case "editor.actions": L10n.string("Add clickable actions beside document text") + case "editor.providers": + L10n.string("Add definitions, hovers, completions and other editor features for matching files") case "terminal.create": L10n.string("Open and manage its own native terminals, retaining bounded display history for reopening") case "keymaps.provide": diff --git a/macos/Sources/LitheCoreContracts/Plugins/PluginEditorActionContracts.swift b/macos/Sources/LitheCoreContracts/Plugins/PluginEditorActionContracts.swift index 416abaa851..db42f9a5d5 100644 --- a/macos/Sources/LitheCoreContracts/Plugins/PluginEditorActionContracts.swift +++ b/macos/Sources/LitheCoreContracts/Plugins/PluginEditorActionContracts.swift @@ -1,8 +1,57 @@ import Foundation +/// The editor presentation one host declares to Core, which relays it to a +/// plugin backend through `lithe/host/getCapabilities` and validates every +/// registration and result against it. +public struct PluginEditorHostOptions: Encodable, Equatable, Sendable { + /// Icon names the host has resources for; actions and alternatives use them. + public let actionIcons: [String] + /// Largest document, in UTF-8 bytes, the host collects actions for. + public let actionSourceBytes: Int + /// Provider types `lithe/host/editor/registerProviders` routes on this host. + public let providerTypes: [String] + + public init(actionIcons: [String], actionSourceBytes: Int, providerTypes: [String]) { + self.actionIcons = actionIcons + self.actionSourceBytes = actionSourceBytes + self.providerTypes = providerTypes + } +} + /// Core validates independent editor presentation without interpreting plugin business data. public protocol PluginEditorActionDecoding: Sendable { - func decodeEditorActions(kind: String, value: ToolingJSONValue, text: String) throws -> ToolingJSONValue + /// `kind` is `registration`, `actions` (with the exact document `text`) + /// or `invokeResult`; `host` selects the version 2 rules. + func decodeEditorActions( + kind: String, value: ToolingJSONValue, text: String, host: PluginEditorHostOptions + ) throws -> ToolingJSONValue +} + +/// A provider registration naming a type the host does not route. +public struct PluginEditorProviderUnsupported: Error, Equatable, Sendable { + /// The offending option, for example `providers.hover`. + public let option: String + + public init(option: String) { + self.option = option + } +} + +/// Core validates provider registrations and the normalized shape of each +/// provider function's answer; the host never interprets plugin payloads. +public protocol PluginEditorProviderDecoding: Sendable { + /// Throws `PluginEditorProviderUnsupported` for a type outside `types`. + func decodeEditorProviderRegistration(value: ToolingJSONValue, types: [String]) throws -> ToolingJSONValue + /// `legend` is the registered legend of a semantic tokens provider. + func decodeEditorProviderResult( + type: String, value: ToolingJSONValue, legend: ToolingJSONValue? + ) throws -> ToolingJSONValue + /// Core's definition merge: the language server's locations come first and + /// plugin locations only add to them. Both lists are LSP `Location` values; + /// the result is the indices each side keeps. + func mergeEditorDefinitions( + documentURI: String, line: Int, character: Int, server: [ToolingJSONValue], plugin: [ToolingJSONValue] + ) throws -> (server: [Int], plugin: [Int]) } /// One plugin-private action, anchored in a one-based UTF-16 document range. @@ -19,9 +68,51 @@ public struct PluginEditorAction: Equatable, Decodable, Sendable { public let functionID: String public let params: ToolingJSONValue } + /// A further choice offered next to the main action, such as debugging + /// next to running; clicking it invokes its own function. + public struct Alternative: Equatable, Decodable, Sendable { + public let id: String + public let title: String + public let icon: String + public let invoke: Invocation + } public let id: String public let range: Range public let title: String public let icon: String public let invoke: Invocation + public let alternatives: [Alternative] + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + range = try container.decode(Range.self, forKey: .range) + title = try container.decode(String.self, forKey: .title) + icon = try container.decode(String.self, forKey: .icon) + invoke = try container.decode(Invocation.self, forKey: .invoke) + alternatives = try container.decodeIfPresent([Alternative].self, forKey: .alternatives) ?? [] + } + + /// Every function a click on this action or one of its alternatives calls. + public var functionIDs: [String] { [invoke.functionID] + alternatives.map(\.invoke.functionID) } + + private enum CodingKeys: String, CodingKey { case id, range, title, icon, invoke, alternatives } +} + +/// Where a clicked action asks the host to look, from the action function's +/// `reveal` result: LSP shaped locations the host presents. +public struct PluginEditorReveal: Equatable, Decodable, Sendable { + public struct Position: Equatable, Decodable, Sendable { + public let line: Int + public let character: Int + } + public struct Range: Equatable, Decodable, Sendable { + public let start: Position + public let end: Position + } + public struct Location: Equatable, Decodable, Sendable { + public let uri: String + public let range: Range + } + public let locations: [Location] } diff --git a/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift b/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift index 9ebbe7e429..7b8b645c0f 100644 --- a/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift +++ b/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift @@ -3634,6 +3634,30 @@ public struct PluginsEditorActionsFailed: LogEvent { } } +public struct PluginsEditorProviderFailed: LogEvent { + public static let id = "plugins.editor.provider_failed" + public static let level: LogLevel = .warn + public static let messageTemplate = "Plugin {plugin} editor provider failed" + public static let ratePerMinute = 60 + public static let owner = "Lithe" + public static let debugOnly = false + public let channel: LogChannel + public let fields: [String: LogFieldValue] + public let operationID: String? + public var reference: LogRecordReference { + LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) + } + + public init(`error`: any Error, `plugin`: LogSegment, operationID: String? = nil) { + self.operationID = operationID + self.channel = LogChannel(.plugins, segments: [`plugin`, LogSegment("host")!]) + var _logValues: [String: LogFieldValue] = [:] + _logValues["error"] = .error(`error`) + _logValues["plugin"] = .id(`plugin`) + self.fields = _logValues + } +} + public struct PluginsEditorRefreshFailed: LogEvent { public static let id = "plugins.editor.refresh_failed" public static let level: LogLevel = .warn diff --git a/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift b/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift index 7a119413c3..61dbd3ed06 100644 --- a/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift +++ b/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift @@ -69,7 +69,8 @@ struct MonacoWorkbenchSessionLifetimeTests { @Test func readOnlyPreviewRejectsRunActionsAtTheNativeBoundary() { let main = MonacoWorkbenchSession.forModel(UUID()) let preview = MonacoWorkbenchSession.forModel(UUID(), documentID: UUID(), previewID: UUID()) - for message in ["javaRunMarkerAction", "pluginEditorAction", "format", "rename", "executeCodeAction", "setBlameVisibility"] { + for message in ["javaRunMarkerAction", "pluginEditorAction", "pluginEditorProviderCommand", "format", "rename", + "executeCodeAction", "setBlameVisibility"] { #expect(main.allowsMessage(message)) #expect(!preview.allowsMessage(message)) } diff --git a/macos/Tests/LitheTests/PluginEditorActionTests.swift b/macos/Tests/LitheTests/PluginEditorActionTests.swift index 4c557f54fb..25ae4e8395 100644 --- a/macos/Tests/LitheTests/PluginEditorActionTests.swift +++ b/macos/Tests/LitheTests/PluginEditorActionTests.swift @@ -19,7 +19,7 @@ struct PluginEditorActionTests { defer { fixture.tearDown() } let contexts = PluginWorkspaceContexts() let context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) - let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations) + let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations, host: .macOS) let dispatcher = PluginHostServiceDispatcher(contexts: contexts) dispatcher.register(service) let session = dispatcher.beginSession(pluginID: "tool", hostServices: ["lithe/host/editor/registerActions"]) @@ -46,7 +46,7 @@ struct PluginEditorActionTests { defer { fixture.tearDown() } let contexts = PluginWorkspaceContexts() let context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) - let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations) + let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations, host: .macOS) let dispatcher = PluginHostServiceDispatcher(contexts: contexts) dispatcher.register(service) let session = dispatcher.beginSession(pluginID: "tool", hostServices: ["lithe/host/editor/registerActions"]) @@ -71,7 +71,7 @@ struct PluginEditorActionTests { defer { fixture.tearDown() } let contexts = PluginWorkspaceContexts() let context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) - let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations) + let service = PluginEditorActionHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations, host: .macOS) let dispatcher = PluginHostServiceDispatcher(contexts: contexts) dispatcher.register(service) dispatcher.beginSession(pluginID: "tool", hostServices: []) @@ -87,6 +87,75 @@ struct PluginEditorActionTests { #expect(service.registrations(context: context.reference, filename: "a.http").isEmpty) } + // MARK: Version 2: alternatives and reveal + + @Test + func aMarkerOffersItsAlternativesAndTheClickedFunctionsAreAllKnown() throws { + let service = PluginEditorActionHostService( + contexts: PluginWorkspaceContexts(), decoder: DeclarativePluginTestSupport.operations, host: .macOS) + let fixture = try contractFixture("editor/editor-actions-v2.json") + let marker = try #require(fixture.member("cases")?.elements.first) + + let actions = try service.decode( + try #require(marker.member("value")), text: try #require(marker.member("text")?.textValue)) + + let main = try #require(actions.first) + #expect(actions.count == 1) + #expect(main.icon == "run") + #expect(main.alternatives.map(\.id) == ["debug", "test"]) + #expect(main.alternatives.map(\.icon) == ["debug", "test"]) + #expect(main.alternatives.last?.invoke.params == .object([:]), "an alternative without params is still a call") + #expect(main.functionIDs == ["go.markers.invoke", "go.markers.invoke", "go.markers.invoke"]) + #expect(main.range.start.line == 3) + #expect(main.range.start.column == 1) + } + + @Test + func aClickedActionMayRevealLocationsAndNothingElseIsInterpreted() throws { + let service = PluginEditorActionHostService( + contexts: PluginWorkspaceContexts(), decoder: DeclarativePluginTestSupport.operations, host: .macOS) + let cases = try #require(contractFixture("editor/editor-actions-v2.json").member("cases")).elements + func result(_ name: String) throws -> ToolingJSONValue { + try #require(cases.first { $0.member("name")?.textValue?.hasPrefix(name) == true }?.member("value")) + } + + let reveal = try #require(try service.decodeReveal(result("a click reveals"))) + #expect(reveal.locations.map(\.uri) == ["file:///workspace/messages.properties", "file:///workspace/messages_zh.properties"]) + #expect(reveal.locations.first?.range.start.line == 4) + #expect(reveal.locations.first?.range.end.character == 9) + + #expect(try service.decodeReveal(result("other result members")) == nil, "the plugin's own members are not the host's business") + #expect(throws: (any Error).self) { try service.decodeReveal(result("a reveal location needs")) } + } + + @Test + func contractFixtureCasesMatchCore() throws { + let fixture = try contractFixture("editor/editor-actions-v2.json") + let host = try #require(fixture.member("host")) + let options = PluginEditorHostOptions( + actionIcons: try #require(host.member("actionIcons")).elements.compactMap(\.textValue), + actionSourceBytes: try #require(host.member("actionSourceBytes")?.integerValue), + providerTypes: PluginEditorHostOptions.macOS.providerTypes) + #expect(options == .macOS, "the fixture describes the host the macOS app declares") + let operations = DeclarativePluginTestSupport.operations + + for entry in try #require(fixture.member("cases")).elements { + let name = entry.member("name")?.textValue ?? "case" + let kind = try #require(entry.member("kind")?.textValue) + let expected = try #require(entry.member("expected")) + do { + let decoded = try operations.decodeEditorActions( + kind: kind, value: try #require(entry.member("value")), + text: entry.member("text")?.textValue ?? "", host: options) + #expect(expected.member("status")?.textValue == "accepted", "\(name)") + let value = kind == "actions" ? decoded.member("actions") : decoded + #expect(value == expected.member("value"), "\(name)") + } catch { + #expect(expected.member("status")?.textValue == "rejected", "\(name)") + } + } + } + private func request(context: PluginWorkspaceContext, function: String) -> PluginHostRequest { PluginHostRequest(id: "registration", method: "lithe/host/editor/registerActions", service: "editor", params: .object([ "context": .object(["contextID": .string(context.contextID), "generation": .integer(context.generation)]), @@ -95,3 +164,31 @@ struct PluginEditorActionTests { ])) } } + +private func contractFixture(_ name: String) throws -> ToolingJSONValue { + let url = DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/\(name)") + return try JSONDecoder().decode(ToolingJSONValue.self, from: Data(contentsOf: url)) +} + +private extension ToolingJSONValue { + func member(_ key: String) -> ToolingJSONValue? { + if case .object(let object) = self { return object[key] } + return nil + } + + var elements: [ToolingJSONValue] { + if case .array(let array) = self { return array } + return [] + } + + var textValue: String? { + if case .string(let text) = self { return text } + return nil + } + + var integerValue: Int? { + if case .integer(let number) = self { return number } + return nil + } +} diff --git a/macos/Tests/LitheTests/PluginEditorProviderTests.swift b/macos/Tests/LitheTests/PluginEditorProviderTests.swift new file mode 100644 index 0000000000..f65fa14b30 --- /dev/null +++ b/macos/Tests/LitheTests/PluginEditorProviderTests.swift @@ -0,0 +1,552 @@ +import Combine +import Foundation +import LitheCoreContracts +import Testing +@testable import Lithe + +// 这些测试用第二种工具(resource key 在模板与 .properties 之间跳转)验证 Provider 通道: +// 宿主不认识任何语言,只按注册的选择器和类型路由,并把 Core 规范化后的结果交给编辑器。 +@MainActor +struct PluginEditorProviderTests { + private static let properties = PluginEditorProviderDocument( + documentID: "doc-1", version: 3, filename: "app.properties", language: "properties") + + // MARK: Registration + + @Test + func registrationsAreScopedBySelectorAndTypeAndRevokedWithTheirFunctions() async throws { + let harness = ProviderHarness(functions: ["keys.hover", "keys.complete", "keys.usages"]) + defer { harness.tearDown() } + let selector = #"{"languages":["HTML"],"fileExtensions":[".Properties"],"fileNames":["Messages"]}"# + let providers = #"{"hover":{"function":"keys.hover"},"completion":{"function":"keys.complete","triggerCharacters":["."]}}"# + _ = try await harness.register(selector: selector, providers: providers).get() + + #expect(harness.registrations("App.PROPERTIES", "plaintext", "hover").count == 1, "extension, any case") + #expect(harness.registrations("Messages", "plaintext", "hover").count == 1, "file name") + #expect(harness.registrations("index.htm", "html", "completion").count == 1, "language") + #expect(harness.registrations("notes.txt", "plaintext", "hover").isEmpty) + #expect(harness.registrations("app.properties", "properties", "codeLens").isEmpty, "type not provided") + + let registration = try #require(harness.registrations("a.properties", "properties", "completion").first) + #expect(registration.providers["completion"]?.triggerCharacters == ["."]) + #expect(registration.providers["completion"]?.budget == .milliseconds(400)) + #expect(registration.providers["hover"]?.budget == .milliseconds(400)) + #expect(harness.service.contains(registration, functionID: "keys.hover")) + #expect(!harness.service.contains(registration, functionID: "anotherPlugin.hover")) + + harness.setFunctions(["keys.hover", "keys.complete", "keys.usages", "keys.extra"]) + #expect(harness.service.contains(registration, functionID: "keys.hover"), "adding a function must not withdraw bindings") + harness.setFunctions(["keys.hover", "keys.complete"]) + #expect(!harness.service.contains(registration, functionID: "keys.hover"), "withdrawing a function revokes the plugin's bindings") + #expect(harness.registrations("a.properties", "properties", "hover").isEmpty) + } + + @Test + func disposingTheSubscriptionOrClosingTheContextWithdrawsRegistrations() async throws { + let harness = ProviderHarness(functions: ["keys.hover"]) + defer { harness.tearDown() } + let changes = ChangeCounter() + let observation = harness.service.changes.sink { _ in changes.count += 1 } + defer { observation.cancel() } + let providers = #"{"hover":{"function":"keys.hover"}}"# + + let first = try await harness.register(id: "first", providers: providers).get() + _ = try await harness.register(id: "second", providers: providers).get() + #expect(harness.registrations("a.properties", "properties", "hover").count == 2) + #expect(changes.count == 2) + + guard case .object(let value) = first, case .string(let subscription)? = value["subscriptionID"] else { + Issue.record("missing subscription"); return + } + harness.dispatcher.subscriptions.dispose(pluginID: ProviderHarness.pluginID, subscriptionID: subscription) + #expect(harness.registrations("a.properties", "properties", "hover").map(\.id) == ["second"]) + #expect(changes.count == 3, "disposing a registration tells the editor to ask again") + + harness.contexts.close(owner: harness.fixture.window) + #expect(harness.registrations("a.properties", "properties", "hover").isEmpty) + #expect(harness.dispatcher.subscriptions.count(pluginID: ProviderHarness.pluginID) == 0) + } + + @Test + func endingTheSessionWithdrawsEveryRegistration() async throws { + let harness = ProviderHarness(functions: ["keys.hover"]) + defer { harness.tearDown() } + _ = try await harness.register(providers: #"{"hover":{"function":"keys.hover"}}"#).get() + let registration = try #require(harness.registrations("a.properties", "properties", "hover").first) + + harness.dispatcher.endSession(pluginID: ProviderHarness.pluginID) + #expect(!harness.service.contains(registration, functionID: "keys.hover")) + #expect(harness.registrations("a.properties", "properties", "hover").isEmpty) + } + + @Test + func everyProviderTypeTheMacOSHostRoutesIsAccepted() async throws { + let harness = ProviderHarness(functions: ["f.definition", "f.hover", "f.complete", "f.lens", "f.fold", "f.tokens", "f.links"]) + defer { harness.tearDown() } + let providers = """ + {"definition":{"function":"f.definition"},"hover":{"function":"f.hover"}, + "completion":{"function":"f.complete"},"codeLens":{"function":"f.lens"}, + "foldingRange":{"function":"f.fold"}, + "semanticTokens":{"function":"f.tokens","legend":{"tokenTypes":["property"],"tokenModifiers":[]}}, + "documentLink":{"function":"f.links"}} + """ + _ = try await harness.register(providers: providers).get() + + let registration = try #require(harness.registrations("a.properties", "properties", "definition").first) + #expect(Set(registration.providers.keys) == Set(PluginEditorHostOptions.macOS.providerTypes)) + #expect(registration.providers["definition"]?.budget == .milliseconds(1500)) + #expect(registration.providers["codeLens"]?.budget == .milliseconds(2000)) + #expect(registration.providers["semanticTokens"]?.legend != nil) + } + + @Test + func aTypeTheHostDoesNotRouteIsAnUnsupportedOption() async throws { + let harness = ProviderHarness(functions: ["keys.hover", "keys.signature"]) + defer { harness.tearDown() } + + // The contract names a type the macOS host does not route. + let signature = await harness.register(providers: #"{"signatureHelp":{"function":"keys.signature"}}"#) + guard case .failure(let failure) = signature else { Issue.record("signatureHelp must be refused"); return } + #expect(failure.code == "plugin.host.unsupportedOption") + #expect(failure.details == .object(["option": .string("providers.signatureHelp")])) + + // A host that declared fewer types refuses the others with the same code. + let limited = ProviderHarness( + host: PluginEditorHostOptions(actionIcons: [], actionSourceBytes: 1024, providerTypes: ["hover"]), + functions: ["keys.definition"]) + defer { limited.tearDown() } + let definition = await limited.register(providers: #"{"definition":{"function":"keys.definition"}}"#) + guard case .failure(let refused) = definition else { Issue.record("definition must be refused"); return } + #expect(refused.code == "plugin.host.unsupportedOption") + #expect(refused.details == .object(["option": .string("providers.definition")])) + #expect(limited.registrations("a.properties", "properties", "definition").isEmpty) + } + + @Test + func malformedRegistrationsAreInvalidParamsAndCreateNoBinding() async throws { + let harness = ProviderHarness(functions: ["keys.hover", "keys.tokens"]) + defer { harness.tearDown() } + let cases: [(name: String, selector: String, providers: String)] = [ + ("a selector must name something", "{}", #"{"hover":{"function":"keys.hover"}}"#), + ("semantic tokens declare their legend", #"{"fileExtensions":["properties"]}"#, #"{"semanticTokens":{"function":"keys.tokens"}}"#), + ("budgets are the host's", #"{"fileExtensions":["properties"]}"#, #"{"hover":{"function":"keys.hover","budgetMs":5000}}"#), + ("the function must be one the backend announced", #"{"fileExtensions":["properties"]}"#, #"{"hover":{"function":"keys.missing"}}"#), + ] + for item in cases { + let outcome = await harness.register(selector: item.selector, providers: item.providers) + guard case .failure(let failure) = outcome else { Issue.record("\(item.name) must be refused"); continue } + #expect(failure.code == "plugin.host.invalidParams", "\(item.name)") + } + #expect(harness.registrations("a.properties", "properties", "hover").isEmpty) + #expect(harness.dispatcher.subscriptions.count(pluginID: ProviderHarness.pluginID) == 0) + } + + @Test + func aDuplicateIDIsAPreconditionFailureAndEachPluginHasABoundedNumberOfRegistrations() async throws { + let harness = ProviderHarness(functions: ["keys.hover"]) + defer { harness.tearDown() } + let providers = #"{"hover":{"function":"keys.hover"}}"# + _ = try await harness.register(id: "same", providers: providers).get() + guard case .failure(let duplicate) = await harness.register(id: "same", providers: providers) else { + Issue.record("a second registration with the same id must be refused"); return + } + #expect(duplicate.code == "plugin.host.preconditionFailed") + + for number in 1..<32 { _ = try await harness.register(id: "r\(number)", providers: providers).get() } + guard case .failure(let overflow) = await harness.register(id: "one-too-many", providers: providers) else { + Issue.record("the 33rd registration must be refused"); return + } + #expect(overflow.code == "plugin.host.limitExceeded") + } + + // MARK: Queries + + @Test + func aQueryKeepsValidAnswersAndDropsFailedAndMalformedOnes() async throws { + let harness = ProviderHarness(functions: ["a.hover", "b.hover", "c.hover"]) + defer { harness.tearDown() } + for (id, function) in [("a-keys", "a.hover"), ("b-keys", "b.hover"), ("c-keys", "c.hover")] { + _ = try await harness.register(id: id, providers: #"{"hover":{"function":"\#(function)"}}"#).get() + } + let backends = RecordingProviderBackends() + backends.answers["a.hover"] = try json(#"{"contents":[{"language":"properties","value":"app.title=Lithe"},"Defined in messages.properties"]}"#) + backends.answers["b.hover"] = .string("not a hover") + backends.failing = ["c.hover"] + + let answers = await harness.query("hover", Self.properties, position: (0, 7), backends: backends) + + #expect(answers.map(\.registration.id) == ["a-keys"]) + let expected = try json(#"{"contents":[{"kind":"markdown","value":"```properties\napp.title=Lithe\n```"},{"kind":"markdown","value":"Defined in messages.properties"}]}"#) + #expect(answers.first?.result == expected, "Core's normalized shape, not the plugin's raw answer") + #expect(backends.calls.count == 3, "every matching registration is asked") + #expect(backends.calls.allSatisfy { $0.plugin == ProviderHarness.pluginID && $0.context == harness.context.reference }) + let first = try #require(backends.calls.first { $0.function == "a.hover" }) + let expectedParams = try json(#"{"documentID":"doc-1","version":3,"position":{"line":0,"character":7}}"#) + #expect(first.params == expectedParams) + } + + @Test + func eachTypeIsAskedWithinTheBudgetCoreAssignedIt() async throws { + let harness = ProviderHarness(functions: ["f.definition", "f.hover", "f.complete", "f.lens", "f.fold", "f.links"]) + defer { harness.tearDown() } + let providers = """ + {"definition":{"function":"f.definition"},"hover":{"function":"f.hover"}, + "completion":{"function":"f.complete"},"codeLens":{"function":"f.lens"}, + "foldingRange":{"function":"f.fold"},"documentLink":{"function":"f.links"}} + """ + _ = try await harness.register(providers: providers).get() + let backends = RecordingProviderBackends() + + for type in ["definition", "hover", "completion", "codeLens", "foldingRange", "documentLink"] { + _ = await harness.query(type, Self.properties, position: (0, 0), backends: backends) + } + + let budgets = Dictionary(uniqueKeysWithValues: backends.calls.map { ($0.function, $0.timeout) }) + #expect(budgets["f.hover"] == .milliseconds(400)) + #expect(budgets["f.complete"] == .milliseconds(400)) + #expect(budgets["f.definition"] == .milliseconds(1500)) + #expect(budgets["f.lens"] == .milliseconds(2000)) + #expect(budgets["f.fold"] == .milliseconds(2000)) + #expect(budgets["f.links"] == .milliseconds(2000)) + } + + @Test + func anAnswerForADocumentThatMovedOnIsDropped() async throws { + let harness = ProviderHarness(functions: ["keys.hover"]) + defer { harness.tearDown() } + _ = try await harness.register(providers: #"{"hover":{"function":"keys.hover"}}"#).get() + let backends = RecordingProviderBackends() + backends.answers["keys.hover"] = try json(#"{"contents":["late"]}"#) + + let alreadyStale = await harness.query("hover", Self.properties, position: (0, 0), backends: backends, isCurrent: { false }) + #expect(alreadyStale.isEmpty) + + // The version changes while the plugin is still working. + let current = CurrentFlag() + backends.whileCalled = { current.value = false } + let movedOn = await harness.query("hover", Self.properties, position: (0, 0), backends: backends, isCurrent: { current.value }) + #expect(movedOn.isEmpty) + #expect(backends.calls.count == 2, "the plugin was asked both times") + + // The plugin's functions are withdrawn while it is still working. + backends.whileCalled = { harness.setFunctions([]) } + let withdrawn = await harness.query("hover", Self.properties, position: (0, 0), backends: backends) + #expect(withdrawn.isEmpty) + } + + @Test + func aTriggerCharacterOnlyReachesRegistrationsThatAskedForIt() async throws { + let harness = ProviderHarness(functions: ["dot.complete", "any.complete"]) + defer { harness.tearDown() } + _ = try await harness.register(id: "dot", providers: #"{"completion":{"function":"dot.complete","triggerCharacters":["."]}}"#).get() + _ = try await harness.register(id: "any", providers: #"{"completion":{"function":"any.complete"}}"#).get() + let backends = RecordingProviderBackends() + + _ = await harness.query("completion", Self.properties, position: (0, 4), trigger: ".", backends: backends) + let expectedParams = try json(#"{"documentID":"doc-1","version":3,"position":{"line":0,"character":4},"triggerCharacter":"."}"#) + #expect(backends.calls.map(\.function) == ["dot.complete"]) + #expect(backends.calls.first?.params == expectedParams) + + backends.calls.removeAll() + _ = await harness.query("completion", Self.properties, position: (0, 4), trigger: ",", backends: backends) + #expect(backends.calls.isEmpty, "nobody asked for a comma") + + backends.calls.removeAll() + _ = await harness.query("completion", Self.properties, position: (0, 4), backends: backends) + #expect(Set(backends.calls.map(\.function)) == ["dot.complete", "any.complete"], "typing a letter asks everyone") + } + + @Test + func aQueryOnlyReachesRegistrationsForTheFileAndTheType() async throws { + let harness = ProviderHarness(functions: ["keys.hover"]) + defer { harness.tearDown() } + _ = try await harness.register(providers: #"{"hover":{"function":"keys.hover"}}"#).get() + let backends = RecordingProviderBackends() + let other = PluginEditorProviderDocument(documentID: "doc-2", version: 1, filename: "main.go", language: "go") + + let otherFile = await harness.query("hover", other, position: (0, 0), backends: backends) + let otherType = await harness.query("documentLink", Self.properties, backends: backends) + #expect(otherFile.isEmpty) + #expect(otherType.isEmpty) + #expect(backends.calls.isEmpty) + } + + // MARK: Definition merge + + @Test + func coreKeepsTheServersDefinitionsAndOnlySupplementsThem() throws { + let harness = ProviderHarness(functions: []) + defer { harness.tearDown() } + let document = URL(fileURLWithPath: "/work/app.go") + func place(_ path: String, _ line: Int, _ from: Int, _ to: Int) throws -> ToolingJSONValue { + try json(#"{"uri":"file://\#(path)","range":{"start":{"line":\#(line),"character":\#(from)},"end":{"line":\#(line),"character":\#(to)}}}"#) + } + + // The same place from both sides is shown once. + let duplicate = try harness.service.mergeDefinitions( + documentURL: document, line: 9, character: 9, + server: [place("/work/a.go", 1, 0, 3)], + plugin: [place("/work/a.go", 1, 0, 3), place("/work/b.go", 2, 0, 3)]) + #expect(duplicate.server == [0]) + #expect(duplicate.plugin == [1]) + + // A server answer that only points at the symbol itself yields to the plugin. + let own = try place("/work/app.go", 4, 2, 8) + let other = try place("/work/b.go", 2, 0, 3) + let yielded = try harness.service.mergeDefinitions( + documentURL: document, line: 4, character: 5, server: [own], plugin: [other]) + #expect(yielded.server.isEmpty) + #expect(yielded.plugin == [0]) + + // Without a plugin answer the server's own location stands, and the end bound is exclusive. + let alone = try harness.service.mergeDefinitions( + documentURL: document, line: 4, character: 5, server: [own], plugin: []) + #expect(alone.server == [0]) + let atTheEnd = try harness.service.mergeDefinitions( + documentURL: document, line: 4, character: 8, server: [own], plugin: [other]) + #expect(atTheEnd.server == [0]) + #expect(atTheEnd.plugin == [0]) + } + + @Test + func aMalformedLocationFailsTheMerge() throws { + let harness = ProviderHarness(functions: []) + defer { harness.tearDown() } + let empty = try json(#"{"uri":"","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}"#) + #expect(throws: (any Error).self) { + try harness.service.mergeDefinitions( + documentURL: URL(fileURLWithPath: "/work/app.go"), line: 0, character: 0, server: [empty], plugin: []) + } + } + + // MARK: Modifier hover + + @Test + func aNewerHoverCancelsTheRunningDefinitionQueryAndRetiresTheOlderTicket() async { + let hover = PluginDefinitionHover() + let first = hover.begin() + // Stands in for providers still inside their budget; cancellation ends the sleep at once. + let slow = Task<[LanguageServerLocation], Never> { + try? await Task.sleep(for: .seconds(30)) + return [] + } + hover.run(slow) + + let second = hover.begin() + + #expect(slow.isCancelled) + #expect(!hover.isLatest(first), "the older hover's server reply can no longer start providers") + #expect(hover.isLatest(second)) + _ = await slow.value + } + + @Test + func aFinishedDefinitionQueryIsNotCancelledByTheNextHover() async { + let hover = PluginDefinitionHover() + _ = hover.begin() + let done = Task<[LanguageServerLocation], Never> { [] } + hover.run(done) + _ = await done.value + hover.finished(done) + + _ = hover.begin() + + #expect(!done.isCancelled) + } + + // MARK: Contract + + @Test + func theMacOSHostDeclaresTheOptionsTheContractFixtureAssumes() throws { + let fixture = try contractFixture("editor/editor-providers.json") + let types = try #require(fixture.member("host")?.member("providerTypes")) + #expect(types == .array(PluginEditorHostOptions.macOS.providerTypes.map { .string($0) })) + + let encoded = try JSONEncoder().encode(PluginEditorHostOptions.macOS) + let options = try JSONDecoder().decode(ToolingJSONValue.self, from: encoded) + #expect(options.member("providerTypes") == types) + #expect(options.member("actionSourceBytes") == .integer(1024 * 1024)) + #expect(options.member("actionIcons")?.elements.count == 9) + } + + @Test + func contractFixtureRegistrationsAndResultsMatchCore() throws { + let fixture = try contractFixture("editor/editor-providers.json") + let operations = DeclarativePluginTestSupport.operations + let types = try #require(fixture.member("host")?.member("providerTypes")).elements.compactMap(\.textValue) + + for entry in try #require(fixture.member("registrations")).elements { + let name = entry.member("name")?.textValue ?? "registration" + let expected = try #require(entry.member("expected")) + do { + let decoded = try operations.decodeEditorProviderRegistration( + value: try #require(entry.member("params")), types: types) + #expect(expected.member("status")?.textValue == "accepted", "\(name)") + #expect(decoded.member("registration") == expected.member("registration"), "\(name)") + } catch let unsupported as PluginEditorProviderUnsupported { + #expect(expected.member("code")?.textValue == "plugin.host.unsupportedOption", "\(name)") + #expect(expected.member("details")?.member("option")?.textValue == unsupported.option, "\(name)") + } catch { + #expect(expected.member("code")?.textValue == "plugin.host.invalidParams", "\(name)") + } + } + + for entry in try #require(fixture.member("results")).elements { + let name = entry.member("name")?.textValue ?? "result" + let expected = try #require(entry.member("expected")) + do { + let decoded = try operations.decodeEditorProviderResult( + type: try #require(entry.member("type")?.textValue), + value: entry.member("value") ?? .null, legend: entry.member("legend")) + #expect(expected.member("status")?.textValue == "accepted", "\(name)") + #expect(decoded.member("result") == expected.member("value"), "\(name)") + } catch { + #expect(expected.member("status")?.textValue == "rejected", "\(name)") + } + } + } +} + +// MARK: - Test doubles and helpers + +private func json(_ text: String) throws -> ToolingJSONValue { + try JSONDecoder().decode(ToolingJSONValue.self, from: Data(text.utf8)) +} + +private func contractFixture(_ name: String) throws -> ToolingJSONValue { + let url = DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/\(name)") + return try JSONDecoder().decode(ToolingJSONValue.self, from: Data(contentsOf: url)) +} + +private extension ToolingJSONValue { + func member(_ key: String) -> ToolingJSONValue? { + if case .object(let object) = self { return object[key] } + return nil + } + + var elements: [ToolingJSONValue] { + if case .array(let array) = self { return array } + return [] + } + + var textValue: String? { + if case .string(let text) = self { return text } + return nil + } +} + +private final class ChangeCounter { + var count = 0 +} + +private final class CurrentFlag { + var value = true +} + +/// One local window with a workspace and a plugin session that announced `functions`, +/// wired to the real provider service and dispatcher. +@MainActor +private final class ProviderHarness { + static let pluginID = "tool" + + let fixture = PluginHostFixture() + let contexts = PluginWorkspaceContexts() + let context: PluginWorkspaceContext + let service: PluginEditorProviderHostService + let dispatcher: PluginHostServiceDispatcher + let session: String + + init(host: PluginEditorHostOptions = .macOS, functions: [String]) { + context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) + service = PluginEditorProviderHostService( + contexts: contexts, decoder: DeclarativePluginTestSupport.operations, host: host) + dispatcher = PluginHostServiceDispatcher(contexts: contexts) + dispatcher.register(service) + session = dispatcher.beginSession( + pluginID: Self.pluginID, hostServices: ["lithe/host/editor/registerProviders"]) + service.updateFunctions(pluginID: Self.pluginID, sessionID: session, ids: functions) + } + + func tearDown() { + dispatcher.endSession(pluginID: Self.pluginID) + fixture.tearDown() + } + + func setFunctions(_ ids: [String]) { + service.updateFunctions(pluginID: Self.pluginID, sessionID: session, ids: ids) + } + + func registrations(_ filename: String, _ language: String, _ type: String) -> [PluginEditorProviderRegistration] { + service.registrations(context: context.reference, filename: filename, language: language, type: type) + } + + func register( + id: String = "message-keys", selector: String = #"{"fileExtensions":["properties"]}"#, providers: String + ) async -> Result { + guard let selector = try? json(selector), let providers = try? json(providers) else { + preconditionFailure("the test's registration is not JSON") + } + let request = PluginHostRequest( + id: "registration", method: "lithe/host/editor/registerProviders", service: "editor", + params: .object([ + "context": .object([ + "contextID": .string(context.contextID), "generation": .integer(context.generation), + ]), + "id": .string(id), "selector": selector, "providers": providers, + ])) + return await dispatcher.dispatch(request, pluginID: Self.pluginID) + } + + func query( + _ type: String, _ document: PluginEditorProviderDocument, position: (line: Int, character: Int)? = nil, + trigger: String? = nil, backends: RecordingProviderBackends, + isCurrent: @escaping @MainActor () -> Bool = { true } + ) async -> [PluginEditorProviderAnswer] { + await service.query( + type: type, document: document, context: context.reference, position: position, + triggerCharacter: trigger, backends: backends, isCurrent: isCurrent) + } +} + +/// Answers provider functions from a table and records how the host called them. +@MainActor +private final class RecordingProviderBackends: PluginBackendRequesting { + struct Call { + let function: String + let params: ToolingJSONValue + let plugin: String + let context: PluginWorkspaceContextReference? + let timeout: Duration + } + + struct Failure: Error {} + + var answers: [String: ToolingJSONValue] = [:] + var failing: Set = [] + /// Runs inside each call, before it answers: the world changing while a plugin works. + var whileCalled: (() -> Void)? + var calls: [Call] = [] + + func declaresBackend(_: String) -> Bool { true } + func pluginFunctions(ofPlugin _: String) async throws -> [String] { [] } + + func invokePluginFunction( + _ functionID: String, params: ToolingJSONValue, ofPlugin pluginID: String, timeout: Duration, + progress: @escaping @MainActor @Sendable (PluginFunctionProgress) -> Void + ) async throws -> ToolingJSONValue { + try await invokePluginFunction( + functionID, params: params, ofPlugin: pluginID, context: nil, timeout: timeout, progress: progress) + } + + func invokePluginFunction( + _ functionID: String, params: ToolingJSONValue, ofPlugin pluginID: String, + context: PluginWorkspaceContextReference?, timeout: Duration, + progress: @escaping @MainActor @Sendable (PluginFunctionProgress) -> Void + ) async throws -> ToolingJSONValue { + calls.append(Call(function: functionID, params: params, plugin: pluginID, context: context, timeout: timeout)) + whileCalled?() + if failing.contains(functionID) { throw Failure() } + return answers[functionID] ?? .null + } +} diff --git a/rust/lithe-core/src/diagnostics/catalog_generated.rs b/rust/lithe-core/src/diagnostics/catalog_generated.rs index 6a67a717ea..15ec4cd1e6 100644 --- a/rust/lithe-core/src/diagnostics/catalog_generated.rs +++ b/rust/lithe-core/src/diagnostics/catalog_generated.rs @@ -2022,6 +2022,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "Lithe", }, + EventMetadata { + id: "plugins.editor.provider_failed", + channel: "plugins/{plugin}/host", + level: LogLevel::Warn, + message: "Plugin {plugin} editor provider failed", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Error returned while calling the provider function or validating its result", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin id whose editor language-feature provider function failed or answered invalidly", reason: None }, + ], + span: None, + rate: 60, + owner: "Lithe", + }, EventMetadata { id: "plugins.editor.refresh_failed", channel: "plugins", diff --git a/rust/lithe-core/src/lsp/interface/client.rs b/rust/lithe-core/src/lsp/interface/client.rs index 653734d38a..3f1bd61ce3 100644 --- a/rust/lithe-core/src/lsp/interface/client.rs +++ b/rust/lithe-core/src/lsp/interface/client.rs @@ -543,7 +543,14 @@ pub(super) fn client_apply_server_message_for_plugin( ) { // The engine answers once the host has; the request // carries the backend's own ID back to it. - Ok(plugin_function::HostRoute::Answer(result)) => { + Ok(plugin_function::HostRoute::Answer(mut result)) => { + // getCapabilities also reports the options of the + // granted host services. + if let (plugin_function::GET_CAPABILITIES, Some(editor)) = + (method, &state.host_options.editor) + { + editor.report(&mut result, &state.host_services); + } responses.push(json_rpc_result(id, result)?) } Ok(plugin_function::HostRoute::Forward(service)) => { diff --git a/rust/lithe-core/src/lsp/interface/engine.rs b/rust/lithe-core/src/lsp/interface/engine.rs index e088c91cc4..b539c7b752 100644 --- a/rust/lithe-core/src/lsp/interface/engine.rs +++ b/rust/lithe-core/src/lsp/interface/engine.rs @@ -133,6 +133,10 @@ pub struct StartServerRequest { /// requests to the host. #[serde(default)] pub host_services: Vec, + /// Options of the granted host services, such as the icons the host + /// draws for editor actions. Only a plugin-owned session may name any. + #[serde(default)] + pub host_options: super::HostOptions, /// Provider IDs of the plugin's verified manifest. Only a plugin-owned /// session with some is offered `litheToolchains`. #[serde(default)] @@ -2209,6 +2213,7 @@ impl LspEngine { lifecycle: LspLifecycleState::Created, client: LspClientState { host_services: request.host_services.into_iter().collect(), + host_options: request.host_options, ..initialize.state }, pending: BTreeMap::from([( @@ -6634,6 +6639,16 @@ fn validate_start_request(request: &StartServerRequest) -> Result<(), CoreError> { return Err(invalid_field("hostServices")); } + if !request.host_options.is_empty() + && (request.plugin_id.is_none() + || request + .host_options + .editor + .as_ref() + .is_some_and(|editor| editor.validate().is_err())) + { + return Err(invalid_field("hostOptions")); + } if request.executable_path.trim().is_empty() || request.executable_path.contains('\0') || request.working_directory.trim().is_empty() @@ -8698,6 +8713,7 @@ mod tests { plugin_id: None, startup_operation: None, host_services: Vec::new(), + host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), executable_path: "/usr/bin/scripted-server".to_string(), @@ -14194,6 +14210,7 @@ public class Main { plugin_id: None, startup_operation: None, host_services: Vec::new(), + host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), executable_path, @@ -14958,6 +14975,7 @@ public class Main { plugin_id: None, startup_operation: None, host_services: Vec::new(), + host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), executable_path: "/bin/server".to_string(), @@ -17694,6 +17712,79 @@ public class Main { .all(|event| event.kind != "hostRequest")); } + /// Editor options the host declared at start are reported with the + /// methods they belong to, and only when those methods are granted. + #[test] + fn capability_discovery_reports_granted_editor_options() { + use crate::plugins::editor_actions::{EditorHostOptions, REGISTER_PROVIDERS}; + let mut harness = Harness::start(|request| { + request.plugin_id = Some(FUNCTION_PLUGIN.to_string()); + request.host_services = vec![REGISTER_PROVIDERS.to_string()]; + request.host_options.editor = Some(EditorHostOptions { + action_icons: vec!["run".into(), "test-failed".into()], + action_source_bytes: 1024 * 1024, + provider_types: vec!["hover".into(), "codeLens".into()], + }); + }); + harness.server.complete_initialize(json!({ + "experimental": { "litheFunctions": { "version": 3 } } + })); + harness.await_state(LspLifecycleState::Ready); + harness.server.send(json!({ + "jsonrpc": "2.0", "id": "caps", + "method": "lithe/host/getCapabilities" + })); + let reply = await_reply(&harness, "caps"); + let editor = &reply["result"]["services"]["editor"]; + assert_eq!(editor["methods"], json!([REGISTER_PROVIDERS])); + assert_eq!( + editor["options"], + json!({ "providerTypes": ["hover", "codeLens"] }) + ); + assert!(reply["result"]["limits"]["editorActionSourceBytes"].is_null()); + harness.poll(); + assert!(harness + .events + .iter() + .all(|event| event.kind != "hostRequest")); + } + + /// Host options belong to a plugin backend and must be ones Core can + /// enforce. + #[test] + fn start_contract_rejects_unenforceable_host_options() { + use crate::plugins::editor_actions::EditorHostOptions; + let server = ScriptedServer::new(); + let mut request = start_request(&server); + let options = EditorHostOptions { + action_icons: vec!["run".into()], + action_source_bytes: 1024 * 1024, + provider_types: Vec::new(), + }; + request.host_options.editor = Some(options.clone()); + request.plugin_id = None; + assert!(validate_start_request(&request).is_err()); + request.plugin_id = Some(FUNCTION_PLUGIN.to_string()); + assert!(validate_start_request(&request).is_ok()); + for invalid in [ + EditorHostOptions { + action_source_bytes: 2 * 1024 * 1024, + ..options.clone() + }, + EditorHostOptions { + action_icons: vec!["Run Fast".into()], + ..options.clone() + }, + EditorHostOptions { + provider_types: vec!["diagnostics".into()], + ..options.clone() + }, + ] { + request.host_options.editor = Some(invalid); + assert!(validate_start_request(&request).is_err()); + } + } + /// From version 3 a field a method does not define is answered as an /// unsupported option naming it, so a backend can retry without it; the /// host never sees the request. diff --git a/rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs b/rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs index b617b536f5..9ec5af1808 100644 --- a/rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs +++ b/rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs @@ -348,6 +348,7 @@ fn real_start_request( plugin_id: None, startup_operation: None, host_services: Vec::new(), + host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), executable_path: toolchain diff --git a/rust/lithe-core/src/lsp/interface/plugin_function.rs b/rust/lithe-core/src/lsp/interface/plugin_function.rs index 9706189f9f..f80c177344 100644 --- a/rust/lithe-core/src/lsp/interface/plugin_function.rs +++ b/rust/lithe-core/src/lsp/interface/plugin_function.rs @@ -101,6 +101,7 @@ pub(crate) const HOST_PERMISSIONS: &[&str] = &[ "documents.read", "editor.edit", "editor.actions", + "editor.providers", "editor.open", "preview.open", "browser.open", @@ -112,7 +113,7 @@ pub(crate) const HOST_PERMISSIONS: &[&str] = &[ const CREDENTIALS_GET: &str = "lithe/host/credentials/get"; const CREDENTIALS_SET: &str = "lithe/host/credentials/set"; const CREDENTIALS_DELETE: &str = "lithe/host/credentials/delete"; -const GET_CAPABILITIES: &str = "lithe/host/getCapabilities"; +pub(crate) const GET_CAPABILITIES: &str = "lithe/host/getCapabilities"; const SUBSCRIPTIONS_DISPOSE: &str = "lithe/host/subscriptions/dispose"; const WORKSPACE_LIST_CONTEXTS: &str = "lithe/host/workspace/listContexts"; const WORKSPACE_GET_CONTEXT: &str = "lithe/host/workspace/getContext"; @@ -681,6 +682,13 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ since: CONTEXT_VERSION, params: HostParams::Object, }, + HostMethod { + method: "lithe/host/editor/registerProviders", + service: "editor", + permission: Some("editor.providers"), + since: CONTEXT_VERSION, + params: HostParams::Object, + }, HostMethod { method: "lithe/host/editor/getActive", service: "editor", diff --git a/rust/lithe-core/src/lsp/interface/types.rs b/rust/lithe-core/src/lsp/interface/types.rs index 85849c07f9..ea933764e4 100644 --- a/rust/lithe-core/src/lsp/interface/types.rs +++ b/rust/lithe-core/src/lsp/interface/types.rs @@ -106,6 +106,24 @@ pub struct LspDocumentContentChange { pub text: String, } +/// Options a host declares for the services it serves one plugin session, +/// from `lsp.startServer.hostOptions`. Core reports them to the backend +/// through `lithe/host/getCapabilities`, only for granted methods. +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostOptions { + /// Icons, source bound and provider types of the editor service. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub editor: Option, +} + +impl HostOptions { + /// Whether the host declared no options. + pub fn is_empty(&self) -> bool { + self.editor.is_none() + } +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] /// Pure client protocol state carried between JSON command invocations. @@ -151,6 +169,10 @@ pub struct LspClientState { /// `lsp.startServer.hostServices`. Empty for host-owned sessions. #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] pub host_services: BTreeSet, + /// Options the host declared for its granted services, from + /// `lsp.startServer.hostOptions`. + #[serde(default, skip_serializing_if = "HostOptions::is_empty")] + pub host_options: HostOptions, /// The VCS and capabilities a plugin process answered under /// `litheVcs`; `None` when the protocol was not negotiated. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -188,6 +210,7 @@ impl Default for LspClientState { plugin_functions: BTreeSet::new(), plugin_function_version: None, host_services: BTreeSet::new(), + host_options: HostOptions::default(), vcs_provider: None, offered_toolchain_providers: BTreeSet::new(), toolchain_providers: Vec::new(), diff --git a/rust/lithe-core/src/plugins/declarative.rs b/rust/lithe-core/src/plugins/declarative.rs index 06c74182e6..4a7b7613d9 100644 --- a/rust/lithe-core/src/plugins/declarative.rs +++ b/rust/lithe-core/src/plugins/declarative.rs @@ -1612,10 +1612,11 @@ impl DeclarativePluginManifest { "Host API permissions require backend 2.", )); } + // Actions and providers both read the live document they annotate. if self .permissions .iter() - .any(|permission| permission == "editor.actions") + .any(|permission| permission == "editor.actions" || permission == "editor.providers") && !self .permissions .iter() @@ -1623,7 +1624,7 @@ impl DeclarativePluginManifest { { return Err(invalid( "permissions", - "Editor actions require documents.read for live snapshots.", + "Editor actions and providers require documents.read for live snapshots.", )); } for permission in required { diff --git a/rust/lithe-core/src/plugins/editor_actions.rs b/rust/lithe-core/src/plugins/editor_actions.rs index 5ea741b24b..f689989e8d 100644 --- a/rust/lithe-core/src/plugins/editor_actions.rs +++ b/rust/lithe-core/src/plugins/editor_actions.rs @@ -1,7 +1,11 @@ //! Independent editor actions for tool plugins, not language/build/run providers. //! //! Core validates presentation and opaque function bindings. Plugin parsers own -//! their business facts; hosts own document versions, session leases and clicks. +//! their business facts; hosts own document versions, session leases, icon +//! resources and clicks. Version 1 keeps the original two icons and 128 KiB +//! source bound; version 2 takes the icons and bound the host declared in +//! [`EditorHostOptions`](crate::plugins::editor_actions::EditorHostOptions) and adds +//! alternatives and reveal results. use crate::lsp::interface::plugin_function::is_function_id; use crate::protocol::{CoreError, ErrorCode}; @@ -11,6 +15,93 @@ use std::collections::BTreeSet; const MAX_ACTIONS: usize = 1000; const MAX_BYTES: usize = 1024 * 1024; +/// Largest document a host may collect actions for, in UTF-8 bytes. +pub const MAX_SOURCE_BYTES: usize = 1024 * 1024; +const LEGACY_SOURCE_BYTES: usize = 128 * 1024; +const LEGACY_ICONS: [&str; 2] = ["run", "run-all"]; +const MAX_ICONS: usize = 32; +const MAX_ALTERNATIVES: usize = 4; +const MAX_REVEAL_LOCATIONS: usize = 100; +const MAX_URI_BYTES: usize = 4096; +const REGISTER_ACTIONS: &str = "lithe/host/editor/registerActions"; +pub(crate) const REGISTER_PROVIDERS: &str = "lithe/host/editor/registerProviders"; + +/// Editor presentation a host declares at `lsp.startServer.hostOptions.editor`. +/// Core reports it to sessions granted the matching editor methods through +/// `lithe/host/getCapabilities`, so a plugin learns which icons the host +/// draws and which provider types it routes before registering anything. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EditorHostOptions { + /// Icon names the host has resources for; every action and alternative + /// uses one of them. + pub action_icons: Vec, + /// Largest document, in UTF-8 bytes, the host collects actions for. + pub action_source_bytes: usize, + /// Provider types `lithe/host/editor/registerProviders` accepts on this + /// host; a subset of [`super::editor_providers::PROVIDER_TYPES`]. + #[serde(default)] + pub provider_types: Vec, +} + +impl EditorHostOptions { + /// Rejects an empty or oversized icon list, an icon name that is not a + /// lowercase token, a source bound above [`MAX_SOURCE_BYTES`], and + /// provider types Core cannot validate. + pub fn validate(&self) -> Result<(), CoreError> { + let icons: BTreeSet<&String> = self.action_icons.iter().collect(); + if self.action_icons.is_empty() + || self.action_icons.len() > MAX_ICONS + || icons.len() != self.action_icons.len() + || !self.action_icons.iter().all(|icon| icon_name(icon)) + || self.action_source_bytes == 0 + || self.action_source_bytes > MAX_SOURCE_BYTES + { + return Err(invalid("Invalid editor host options.")); + } + let types: BTreeSet<&String> = self.provider_types.iter().collect(); + if types.len() != self.provider_types.len() + || !self + .provider_types + .iter() + .all(|kind| super::editor_providers::PROVIDER_TYPES.contains(&kind.as_str())) + { + return Err(invalid("Unknown editor provider type in host options.")); + } + Ok(()) + } + + /// Adds `services.editor.options` and `limits.editorActionSourceBytes` + /// to a `getCapabilities` answer, each only when the session is granted + /// the editor method it describes. + pub(crate) fn report(&self, answer: &mut Value, granted: &BTreeSet) { + let actions = granted.contains(REGISTER_ACTIONS); + let providers = granted.contains(REGISTER_PROVIDERS) && !self.provider_types.is_empty(); + if !actions && !providers { + return; + } + let mut options = serde_json::Map::new(); + if actions { + options.insert("actionIcons".into(), json!(self.action_icons)); + if let Some(limits) = answer.get_mut("limits").and_then(Value::as_object_mut) { + limits.insert( + "editorActionSourceBytes".into(), + json!(self.action_source_bytes), + ); + } + } + if providers { + options.insert("providerTypes".into(), json!(self.provider_types)); + } + if let Some(editor) = answer + .get_mut("services") + .and_then(|services| services.get_mut("editor")) + .and_then(Value::as_object_mut) + { + editor.insert("options".into(), Value::Object(options)); + } + } +} #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -57,6 +148,16 @@ fn empty_params() -> Value { json!({}) } +/// Another invocation offered on the same marker, shown in a menu. +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Alternative { + id: String, + title: String, + icon: String, + invoke: Invocation, +} + #[derive(Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] struct Action { @@ -66,6 +167,8 @@ struct Action { /// Presentation only; never identifies a Run/Test/Debug domain operation. icon: String, invoke: Invocation, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + alternatives: Vec, } #[derive(Debug, Deserialize)] @@ -74,6 +177,48 @@ struct ResultList { actions: Vec, } +/// Zero-based LSP position: `character` counts UTF-16 code units. +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct LspPosition { + pub(crate) line: u32, + pub(crate) character: u32, +} + +/// Zero-based LSP range with `start <= end`. +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct LspRange { + pub(crate) start: LspPosition, + pub(crate) end: LspPosition, +} + +impl LspRange { + pub(crate) fn ordered(&self) -> bool { + self.start <= self.end + } +} + +/// An LSP `Location`. +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Location { + pub(crate) uri: String, + pub(crate) range: LspRange, +} + +impl Location { + pub(crate) fn valid(&self) -> bool { + uri(&self.uri) && self.range.ordered() + } +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Reveal { + locations: Vec, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Payload { @@ -81,6 +226,56 @@ struct Payload { value: Value, #[serde(default)] text: String, + /// 1 when absent: the original icons and source bound. + #[serde(default = "legacy_version")] + version: u64, + /// Version 2: the icons of the host's [`EditorHostOptions`]. + #[serde(default)] + icons: Vec, + /// Version 2: the host's `actionSourceBytes`. + #[serde(default)] + source_bytes: Option, +} + +fn legacy_version() -> u64 { + 1 +} + +/// What one decode version admits. +struct Rules { + icons: Vec, + source_bytes: usize, + alternatives: bool, +} + +impl Rules { + fn of(payload: &Payload) -> Result { + match payload.version { + 1 if payload.icons.is_empty() && payload.source_bytes.is_none() => Ok(Self { + icons: LEGACY_ICONS.iter().map(ToString::to_string).collect(), + source_bytes: LEGACY_SOURCE_BYTES, + alternatives: false, + }), + 2 => { + let options = EditorHostOptions { + action_icons: payload.icons.clone(), + action_source_bytes: payload.source_bytes.unwrap_or(0), + provider_types: Vec::new(), + }; + options.validate()?; + Ok(Self { + icons: options.action_icons, + source_bytes: options.action_source_bytes, + alternatives: true, + }) + } + _ => Err(invalid("Unsupported editor action validation version.")), + } + } + + fn icon(&self, icon: &str) -> bool { + self.icons.iter().any(|known| known == icon) + } } fn invalid(message: impl Into) -> CoreError { @@ -91,6 +286,36 @@ fn identifier(value: &str) -> bool { !value.is_empty() && value.len() <= 128 && !value.chars().any(char::is_control) } +fn icon_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 32 + && value + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') +} + +fn title(value: &str) -> bool { + !value.trim().is_empty() && value.chars().count() <= 200 && !value.chars().any(char::is_control) +} + +/// An absolute URI: a scheme, a colon, and no control characters. +pub(crate) fn uri(value: &str) -> bool { + let Some((scheme, rest)) = value.split_once(':') else { + return false; + }; + value.len() <= MAX_URI_BYTES + && !rest.is_empty() + && scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + && !value.chars().any(char::is_control) +} + +fn invocation(item: &Invocation) -> bool { + is_function_id(&item.function_id) && item.params.is_object() +} + fn registration(value: Value) -> Result { let mut item: Registration = serde_json::from_value(value) .map_err(|_| invalid("An editor action registration needs id, function and selector."))?; @@ -106,35 +331,43 @@ fn registration(value: Value) -> Result { "An editor selector has 1 to 32 file names/extensions.", )); } - for extension in &mut item.selector.file_extensions { + normalize_names( + &mut item.selector.file_extensions, + &mut item.selector.file_names, + )?; + serde_json::to_value(item).map_err(|_| invalid("Cannot encode editor registration.")) +} + +/// Lowercases, sorts and deduplicates literal file extensions and names; +/// rejects paths and patterns. +pub(crate) fn normalize_names( + extensions: &mut Vec, + names: &mut Vec, +) -> Result<(), CoreError> { + for extension in extensions.iter_mut() { *extension = extension.trim_start_matches('.').to_lowercase(); } - for name in &mut item.selector.file_names { + for name in names.iter_mut() { *name = name.to_lowercase(); } - for name in item - .selector - .file_extensions - .iter() - .chain(&item.selector.file_names) - { + for name in extensions.iter().chain(names.iter()) { if !identifier(name) || name.contains(['/', '\\', '*', '?', ':']) { return Err(invalid( "An editor selector contains literal file names/extensions only.", )); } } - item.selector.file_extensions.sort(); - item.selector.file_extensions.dedup(); - item.selector.file_names.sort(); - item.selector.file_names.dedup(); - serde_json::to_value(item).map_err(|_| invalid("Cannot encode editor registration.")) + extensions.sort(); + extensions.dedup(); + names.sort(); + names.dedup(); + Ok(()) } -fn actions(value: Value, text: &str) -> Result { +fn actions(value: Value, text: &str, rules: &Rules) -> Result { let mut result: ResultList = serde_json::from_value(value) .map_err(|_| invalid("An editor action result is { actions: [...] }."))?; - if result.actions.len() > MAX_ACTIONS || text.len() > 128 * 1024 { + if result.actions.len() > MAX_ACTIONS || text.len() > rules.source_bytes { return Err(invalid( "The editor action result or document exceeds its limit.", )); @@ -162,17 +395,24 @@ fn actions(value: Value, text: &str) -> Result { }; let mut ids = BTreeSet::new(); for item in &result.actions { + let mut alternative_ids = BTreeSet::new(); if !identifier(&item.id) || !ids.insert(&item.id) - || item.title.trim().is_empty() - || item.title.chars().count() > 200 - || item.title.chars().any(char::is_control) - || !["run", "run-all"].contains(&item.icon.as_str()) - || !is_function_id(&item.invoke.function_id) - || !item.invoke.params.is_object() + || !title(&item.title) + || !rules.icon(&item.icon) + || !invocation(&item.invoke) || item.range.start > item.range.end || !valid_position(&item.range.start) || !valid_position(&item.range.end) + || (!rules.alternatives && !item.alternatives.is_empty()) + || item.alternatives.len() > MAX_ALTERNATIVES + || !item.alternatives.iter().all(|alternative| { + identifier(&alternative.id) + && alternative_ids.insert(&alternative.id) + && title(&alternative.title) + && rules.icon(&alternative.icon) + && invocation(&alternative.invoke) + }) { return Err(invalid( "Invalid editor action identity, range, presentation or invocation.", @@ -185,17 +425,40 @@ fn actions(value: Value, text: &str) -> Result { serde_json::to_value(result.actions).map_err(|_| invalid("Cannot encode editor actions.")) } -/// Validates an independent registration (`kind: registration`) or a parser -/// result (`kind: actions`, with its exact text). No I/O or tool parsing occurs. +/// Reads the `reveal` member of an action's function result. Other members +/// stay the plugin's own: a version 1 result had no meaning to the host. +fn invoke_result(value: Value) -> Result { + let Some(reveal) = value.get("reveal").cloned() else { + return Ok(json!({})); + }; + let reveal: Reveal = serde_json::from_value(reveal) + .map_err(|_| invalid("An action reveal is { locations: [{ uri, range }] }."))?; + if reveal.locations.is_empty() + || reveal.locations.len() > MAX_REVEAL_LOCATIONS + || !reveal.locations.iter().all(Location::valid) + { + return Err(invalid( + "An action reveal has 1 to 100 locations with absolute URIs.", + )); + } + Ok(json!({"reveal": {"locations": reveal.locations}})) +} + +/// Validates an independent registration (`kind: registration`), a parser +/// result (`kind: actions`, with its exact text) or, from version 2, the +/// result of a clicked action (`kind: invokeResult`). No I/O or tool parsing +/// occurs. pub fn decode_command(payload: Value) -> Result { let payload: Payload = serde_json::from_value(payload) .map_err(|_| invalid("Invalid editor action validation payload."))?; if payload.value.to_string().len() > MAX_BYTES { return Err(invalid("Editor action data exceeds 1 MiB.")); } + let rules = Rules::of(&payload)?; match payload.kind.as_str() { "registration" => Ok(json!({"registration": registration(payload.value)?})), - "actions" => Ok(json!({"actions": actions(payload.value, &payload.text)?})), + "actions" => Ok(json!({"actions": actions(payload.value, &payload.text, &rules)?})), + "invokeResult" if rules.alternatives => invoke_result(payload.value), _ => Err(invalid("Unknown editor action validation kind.")), } } @@ -204,6 +467,13 @@ pub fn decode_command(payload: Value) -> Result { mod tests { use super::*; + const HOST_ICONS: [&str; 4] = ["run", "debug", "test", "navigate-super"]; + + fn v2(kind: &str, text: &str, value: Value) -> Result { + decode_command(json!({"kind": kind, "version": 2, "icons": HOST_ICONS, + "sourceBytes": MAX_SOURCE_BYTES, "text": text, "value": value})) + } + #[test] fn different_tools_share_registration_and_opaque_invocations() { for (extension, function) in [("http", "requests.send"), ("sql", "queries.execute")] { @@ -247,4 +517,165 @@ mod tests { .is_err() ); } + + #[test] + fn version_one_keeps_the_original_icons_and_bound() { + let item = |icon: &str| { + json!({"actions":[{"id":"a","range":{"start":{"line":1,"column":1},"end":{"line":1,"column":1}}, + "title":"Run","icon":icon,"invoke":{"functionID":"markers.run"}}]}) + }; + assert!( + decode_command(json!({"kind":"actions","text":"x","value":item("debug")})).is_err() + ); + let large = "x".repeat(LEGACY_SOURCE_BYTES + 1); + assert!( + decode_command(json!({"kind":"actions","text":large,"value":item("run")})).is_err() + ); + assert!(v2("actions", &large, item("debug")).is_ok()); + assert!(decode_command(json!({"kind":"invokeResult","value":{}})).is_err()); + // A version 1 payload cannot smuggle host icons. + assert!(decode_command( + json!({"kind":"actions","icons":["debug"],"text":"x","value":item("debug")}) + ) + .is_err()); + } + + #[test] + fn host_icons_bound_actions_and_their_alternatives() { + // A Go source gets a `func main` marker with debug and test + // alternatives; the plugin owns what each params object means. + let text = "package main\n\nfunc main() {}\n"; + let marker = |alternatives: Value| { + json!({"actions":[{"id":"main","range":{"start":{"line":3,"column":1},"end":{"line":3,"column":10}}, + "title":"Run main","icon":"run","invoke":{"functionID":"go.markers.invoke","params":{"entry":"main"}}, + "alternatives":alternatives}]}) + }; + let accepted = v2("actions", text, marker(json!([ + {"id":"debug","title":"Debug main","icon":"debug","invoke":{"functionID":"go.markers.invoke","params":{"debug":true}}}, + {"id":"test","title":"Test package","icon":"test","invoke":{"functionID":"go.markers.invoke"}} + ]))).unwrap(); + assert_eq!( + accepted["actions"][0]["alternatives"][1]["invoke"]["params"], + json!({}) + ); + let alternative = |id: &str, icon: &str| json!({"id":id,"title":"Other","icon":icon,"invoke":{"functionID":"go.markers.invoke"}}); + for alternatives in [ + json!([alternative("a", "test-passed")]), + json!([alternative("a", "test"), alternative("a", "debug")]), + json!((0..5) + .map(|n| alternative(&n.to_string(), "test")) + .collect::>()), + ] { + assert!(v2("actions", text, marker(alternatives)).is_err()); + } + assert!(decode_command( + json!({"kind":"actions","text":text,"value":marker(json!([alternative("a","run")]))}) + ) + .is_err()); + // Icon names are lowercase tokens the host declared. + assert!(decode_command( + json!({"kind":"actions","version":2,"icons":["Run"],"sourceBytes":10,"text":"x", + "value":{"actions":[]}}) + ) + .is_err()); + assert!(decode_command( + json!({"kind":"actions","version":2,"icons":["run"],"sourceBytes":MAX_SOURCE_BYTES + 1, + "text":"x","value":{"actions":[]}}) + ) + .is_err()); + } + + #[test] + fn invoke_results_reveal_bounded_locations_and_keep_other_members_private() { + let location = json!({"uri":"file:///work/messages.properties", + "range":{"start":{"line":4,"character":0},"end":{"line":4,"character":12}}}); + let result = v2( + "invokeResult", + "", + json!({"reveal":{"locations":[location.clone()]},"private":1}), + ) + .unwrap(); + assert_eq!(result, json!({"reveal":{"locations":[location.clone()]}})); + assert_eq!( + v2("invokeResult", "", json!({"started":true})).unwrap(), + json!({}) + ); + assert_eq!(v2("invokeResult", "", Value::Null).unwrap(), json!({})); + for reveal in [ + json!({"locations":[]}), + json!({"locations":vec![location; 101]}), + json!({"locations":[{"uri":"relative/path","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}]}), + json!({"locations":[{"uri":"file:///a","range":{"start":{"line":2,"character":0},"end":{"line":1,"character":0}}}]}), + ] { + assert!(v2("invokeResult", "", json!({"reveal":reveal})).is_err()); + } + } + + #[test] + fn host_options_report_only_granted_editor_methods() { + let options = EditorHostOptions { + action_icons: vec!["run".into(), "debug".into()], + action_source_bytes: MAX_SOURCE_BYTES, + provider_types: vec!["hover".into()], + }; + options.validate().unwrap(); + let answer = || json!({"services":{"editor":{"methods":[]}},"limits":{}}); + let mut granted = BTreeSet::from([REGISTER_ACTIONS.to_string()]); + let mut reported = answer(); + options.report(&mut reported, &granted); + assert_eq!( + reported["services"]["editor"]["options"], + json!({"actionIcons":["run","debug"]}) + ); + assert_eq!( + reported["limits"]["editorActionSourceBytes"], + json!(MAX_SOURCE_BYTES) + ); + granted = BTreeSet::from([REGISTER_PROVIDERS.to_string()]); + let mut reported = answer(); + options.report(&mut reported, &granted); + assert_eq!( + reported["services"]["editor"]["options"], + json!({"providerTypes":["hover"]}) + ); + assert!(reported["limits"].get("editorActionSourceBytes").is_none()); + let mut reported = answer(); + options.report(&mut reported, &BTreeSet::new()); + assert_eq!(reported, answer()); + let mut unknown = options.clone(); + unknown.provider_types = vec!["diagnostics".into()]; + assert!(unknown.validate().is_err()); + } + + /// The shared contract fixture: what a host that declared these icons + /// accepts, normalizes or rejects whole. + #[test] + fn contract_fixture_cases() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../shared/contracts/plugins/v1/fixtures/editor/editor-actions-v2.json" + ))) + .unwrap(); + let host: EditorHostOptions = serde_json::from_value(fixture["host"].clone()).unwrap(); + host.validate().unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let kind = case["kind"].as_str().unwrap(); + let decoded = decode_command(json!({"kind": kind, "version": 2, + "icons": host.action_icons, "sourceBytes": host.action_source_bytes, + "text": case.get("text").cloned().unwrap_or(json!("")), "value": case["value"]})); + match case["expected"]["status"].as_str().unwrap() { + "accepted" => { + let decoded = decoded.unwrap_or_else(|error| panic!("{name}: {error:?}")); + let value = if kind == "actions" { + &decoded["actions"] + } else { + &decoded + }; + assert_eq!(value, &case["expected"]["value"], "{name}"); + } + _ => assert!(decoded.is_err(), "{name}"), + } + } + } } diff --git a/rust/lithe-core/src/plugins/editor_providers.rs b/rust/lithe-core/src/plugins/editor_providers.rs new file mode 100644 index 0000000000..e47db8e1cd --- /dev/null +++ b/rust/lithe-core/src/plugins/editor_providers.rs @@ -0,0 +1,915 @@ +//! Editor language-feature providers a plugin backend registers through +//! `lithe/host/editor/registerProviders`. +//! +//! Core validates registrations and the LSP 3.17 shaped results of each +//! provider function, and owns the per-type answer budgets. Hosts own the +//! document versions, the calls and the merge with language-server results: +//! a language server answers first and a plugin only supplements it. Core +//! never interprets selectors, function names or result payloads beyond +//! their shape, so no tool or language has a branch here. + +use super::editor_actions::{normalize_names, uri, Location, LspPosition, LspRange}; +use crate::lsp::interface::plugin_function::is_function_id; +use crate::protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; + +/// Provider types Core can validate, in the order the contract lists them. +pub const PROVIDER_TYPES: &[&str] = &[ + "definition", + "hover", + "completion", + "codeLens", + "foldingRange", + "semanticTokens", + "documentLink", +]; + +const MAX_BYTES: usize = 1024 * 1024; +const MAX_SELECTOR_ENTRIES: usize = 32; +const MAX_TRIGGER_CHARACTERS: usize = 16; +const MAX_LEGEND_ENTRIES: usize = 64; +const MAX_LOCATIONS: usize = 100; +const MAX_COMPLETION_ITEMS: usize = 5000; +const MAX_CODE_LENSES: usize = 1000; +const MAX_FOLDING_RANGES: usize = 5000; +const MAX_DOCUMENT_LINKS: usize = 1000; +const MAX_HOVER_BYTES: usize = 64 * 1024; +/// Semantic token integers: five per token, 1 MiB of 4-byte integers. +const MAX_SEMANTIC_TOKEN_INTEGERS: usize = 1024 * 1024 / 4; +const MAX_TEXT_CHARS: usize = 4096; + +/// How long the host waits for one provider answer, in milliseconds. A late +/// answer is dropped, like one for an older document version. +fn budget_ms(kind: &str) -> u64 { + match kind { + "hover" | "completion" => 400, + "definition" => 1500, + _ => 2000, + } +} + +fn invalid(message: impl Into) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, message) +} + +fn identifier(value: &str) -> bool { + !value.is_empty() && value.len() <= 128 && !value.chars().any(char::is_control) +} + +fn bounded(value: &str) -> bool { + value.chars().count() <= MAX_TEXT_CHARS +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Selector { + #[serde(default)] + languages: Vec, + #[serde(default)] + file_extensions: Vec, + #[serde(default)] + file_names: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Legend { + token_types: Vec, + #[serde(default)] + token_modifiers: Vec, +} + +/// One provider entry: the plugin function the host calls and the options +/// its type takes. `budgetMs` is Core's output, never the plugin's input. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Provider { + function: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + trigger_characters: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + legend: Option, + #[serde(default, skip_deserializing)] + budget_ms: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Registration { + id: String, + selector: Selector, + providers: Map, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Payload { + kind: String, + value: Value, + /// Provider types the host routes; a registration naming another type + /// is refused as an unsupported option. + #[serde(default)] + types: Vec, + /// For `kind: result`, the provider type that answered. + #[serde(default, rename = "type")] + provider_type: Option, + /// For a semantic tokens result, the legend the provider registered. + #[serde(default)] + legend: Option, +} + +fn registration(value: Value, types: &[String]) -> Result { + if types.is_empty() + || types + .iter() + .any(|kind| !PROVIDER_TYPES.contains(&kind.as_str())) + { + return Err(invalid("Invalid host provider types.")); + } + let mut item: Registration = serde_json::from_value(value).map_err(|_| { + invalid("An editor provider registration needs id, selector and providers.") + })?; + let selector = &mut item.selector; + if !identifier(&item.id) + || selector.languages.len() + selector.file_extensions.len() + selector.file_names.len() + > MAX_SELECTOR_ENTRIES + || selector.languages.is_empty() + && selector.file_extensions.is_empty() + && selector.file_names.is_empty() + || !selector.languages.iter().all(|language| { + identifier(language) && !language.contains(['/', '\\', '*', '?', ':', ' ']) + }) + { + return Err(invalid( + "An editor provider registration has an id and 1 to 32 literal selector entries.", + )); + } + // The contract matches every selector entry case-insensitively, so the + // host only ever compares lowercased language IDs. + for language in selector.languages.iter_mut() { + *language = language.to_lowercase(); + } + selector.languages.sort(); + selector.languages.dedup(); + normalize_names(&mut selector.file_extensions, &mut selector.file_names)?; + if item.providers.is_empty() { + return Err(invalid("An editor provider registration names a provider.")); + } + let mut providers = Map::new(); + for (kind, value) in std::mem::take(&mut item.providers) { + if !types.contains(&kind) { + return Err(CoreError::new( + ErrorCode::NotSupported, + "The host does not route this editor provider type.", + ) + .with_details(format!("providers.{kind}"))); + } + let mut provider: Provider = serde_json::from_value(value) + .map_err(|_| invalid(format!("Invalid {kind} provider.")))?; + let triggers: BTreeSet<&String> = provider.trigger_characters.iter().collect(); + let options_fit = match kind.as_str() { + "completion" => { + provider.legend.is_none() + && provider.trigger_characters.len() <= MAX_TRIGGER_CHARACTERS + && triggers.len() == provider.trigger_characters.len() + && provider.trigger_characters.iter().all(|character| { + character.chars().count() == 1 + && !character + .chars() + .any(|c| c.is_control() || c.is_whitespace()) + }) + } + "semanticTokens" => { + provider.trigger_characters.is_empty() + && provider.legend.as_ref().is_some_and(legend_valid) + } + _ => provider.trigger_characters.is_empty() && provider.legend.is_none(), + }; + if !is_function_id(&provider.function) || !options_fit { + return Err(invalid(format!("Invalid {kind} provider options."))); + } + provider.budget_ms = budget_ms(&kind); + let provider = serde_json::to_value(provider) + .map_err(|_| invalid("Cannot encode editor provider."))?; + providers.insert(kind, provider); + } + item.providers = providers; + serde_json::to_value(item).map_err(|_| invalid("Cannot encode editor provider registration.")) +} + +fn legend_valid(legend: &Legend) -> bool { + let names = |list: &[String]| { + list.len() <= MAX_LEGEND_ENTRIES + && list.iter().collect::>().len() == list.len() + && list.iter().all(|name| { + !name.is_empty() + && name.len() <= 64 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') + }) + }; + !legend.token_types.is_empty() && names(&legend.token_types) && names(&legend.token_modifiers) +} + +fn range(value: &Value) -> Option { + let range: LspRange = serde_json::from_value(value.clone()).ok()?; + range.ordered().then(|| json!(range)) +} + +fn string<'a>(item: &'a Value, key: &str) -> Option<&'a str> { + item.get(key).and_then(Value::as_str) +} + +/// `null`, a `Location`, a `Location[]` or a `LocationLink[]`, normalized +/// to `{ locations }` (a link becomes its target selection). +fn definition(value: Value) -> Result { + let items = match value { + Value::Null => Vec::new(), + Value::Array(items) => items, + item => vec![item], + }; + if items.len() > MAX_LOCATIONS { + return Err(invalid("A definition result has at most 100 locations.")); + } + let mut locations = Vec::with_capacity(items.len()); + for item in items { + let location = if item.get("targetUri").is_some() { + json!({"uri": item["targetUri"], "range": item.get("targetSelectionRange").unwrap_or(&item["targetRange"])}) + } else { + item + }; + let location: Location = serde_json::from_value(location) + .ok() + .filter(Location::valid) + .ok_or_else(|| invalid("Invalid definition location."))?; + locations.push(location); + } + Ok(json!({ "locations": locations })) +} + +/// `null` or a `Hover`, normalized to `{ contents: [{ kind, value }], range? }`. +fn hover(value: Value) -> Result { + if value.is_null() { + return Ok(json!({ "contents": [] })); + } + let failure = || invalid("Invalid hover result."); + let contents = value.get("contents").ok_or_else(failure)?; + let parts: Vec<&Value> = match contents { + Value::Array(parts) => parts.iter().collect(), + part => vec![part], + }; + let mut normalized = Vec::with_capacity(parts.len()); + let mut bytes = 0; + for part in parts { + let (kind, text) = match part { + Value::String(text) => ("markdown", text.clone()), + part => match ( + string(part, "kind"), + string(part, "language"), + string(part, "value"), + ) { + (Some(kind @ ("markdown" | "plaintext")), None, Some(text)) => { + (kind, text.to_string()) + } + // A MarkedString with a language is a fenced code block. + (None, Some(language), Some(text)) + if identifier(language) && !language.contains('`') => + { + ("markdown", format!("```{language}\n{text}\n```")) + } + _ => return Err(failure()), + }, + }; + bytes += text.len(); + normalized.push(json!({ "kind": kind, "value": text })); + } + if bytes > MAX_HOVER_BYTES { + return Err(invalid("A hover result exceeds 64 KiB.")); + } + let mut result = json!({ "contents": normalized }); + if let Some(value) = value.get("range") { + result["range"] = range(value).ok_or_else(failure)?; + } + Ok(result) +} + +fn text_edit(value: &Value) -> Option { + let new_text = string(value, "newText").filter(|text| text.len() <= MAX_BYTES)?; + if let Some(edit_range) = value.get("range") { + return Some(json!({ "range": range(edit_range)?, "newText": new_text })); + } + Some(json!({ + "newText": new_text, + "insert": range(value.get("insert")?)?, + "replace": range(value.get("replace")?)?, + })) +} + +fn documentation(value: &Value) -> Option { + match value { + Value::String(text) => bounded(text).then(|| json!({ "kind": "plaintext", "value": text })), + part => match (string(part, "kind"), string(part, "value")) { + (Some(kind @ ("markdown" | "plaintext")), Some(value)) + if value.len() <= MAX_HOVER_BYTES => + { + Some(json!({ "kind": kind, "value": value })) + } + _ => None, + }, + } +} + +/// `null`, a `CompletionItem[]` or a `CompletionList`, normalized to +/// `{ isIncomplete, items }`. Only presentation and edit fields are kept: +/// there is no resolve round trip and no command. +fn completion(value: Value) -> Result { + let (incomplete, items) = match value { + Value::Null => (false, Vec::new()), + Value::Array(items) => (false, items), + Value::Object(mut list) => ( + list.get("isIncomplete") + .and_then(Value::as_bool) + .unwrap_or(false), + match list.remove("items") { + Some(Value::Array(items)) => items, + _ => return Err(invalid("A completion list has items.")), + }, + ), + _ => return Err(invalid("Invalid completion result.")), + }; + if items.len() > MAX_COMPLETION_ITEMS { + return Err(invalid("A completion result has at most 5000 items.")); + } + let mut normalized = Vec::with_capacity(items.len()); + for item in &items { + let label = string(item, "label") + .filter(|label| !label.is_empty() && bounded(label)) + .ok_or_else(|| invalid("A completion item has a label."))?; + let mut entry = json!({ "label": label }); + for key in ["detail", "sortText", "filterText"] { + if let Some(value) = item.get(key) { + let value = value.as_str().filter(|value| bounded(value)); + entry[key] = + json!(value.ok_or_else(|| invalid(format!("Invalid completion {key}.")))?); + } + } + if let Some(value) = item.get("insertText") { + let value = value.as_str().filter(|value| value.len() <= MAX_BYTES); + entry["insertText"] = + json!(value.ok_or_else(|| invalid("Invalid completion insertText."))?); + } + if let Some(details) = item.get("labelDetails") { + let mut normalized = Map::new(); + for key in ["detail", "description"] { + if let Some(value) = details.get(key) { + let value = value.as_str().filter(|value| bounded(value)); + normalized.insert( + key.into(), + json!(value.ok_or_else(|| invalid("Invalid completion labelDetails."))?), + ); + } + } + entry["labelDetails"] = Value::Object(normalized); + } + if let Some(kind) = item.get("kind") { + entry["kind"] = json!(kind + .as_u64() + .filter(|kind| (1..=25).contains(kind)) + .ok_or_else(|| invalid("Invalid completion kind."))?); + } + if let Some(format) = item.get("insertTextFormat") { + entry["insertTextFormat"] = json!(format + .as_u64() + .filter(|format| matches!(format, 1 | 2)) + .ok_or_else(|| invalid("Invalid completion insertTextFormat."))?); + } + if let Some(tags) = item.get("tags") { + let tags = tags + .as_array() + .filter(|tags| tags.iter().all(|tag| tag.as_u64() == Some(1))); + entry["tags"] = json!(tags.ok_or_else(|| invalid("Invalid completion tags."))?); + } + if let Some(value) = item.get("documentation") { + entry["documentation"] = + documentation(value).ok_or_else(|| invalid("Invalid completion documentation."))?; + } + if let Some(value) = item.get("textEdit") { + entry["textEdit"] = + text_edit(value).ok_or_else(|| invalid("Invalid completion textEdit."))?; + } + if let Some(edits) = item.get("additionalTextEdits") { + let edits = edits + .as_array() + .filter(|edits| edits.len() <= 100) + .and_then(|edits| { + edits + .iter() + .map(|edit| text_edit(edit).filter(|edit| edit.get("range").is_some())) + .collect::>>() + }); + entry["additionalTextEdits"] = + json!(edits.ok_or_else(|| invalid("Invalid completion additionalTextEdits."))?); + } + if let Some(characters) = item.get("commitCharacters") { + let characters = characters.as_array().filter(|list| { + list.len() <= MAX_TRIGGER_CHARACTERS + && list + .iter() + .all(|c| c.as_str().is_some_and(|c| c.chars().count() == 1)) + }); + entry["commitCharacters"] = + json!(characters.ok_or_else(|| invalid("Invalid completion commitCharacters."))?); + } + normalized.push(entry); + } + Ok(json!({ "isIncomplete": incomplete, "items": normalized })) +} + +/// `null` or a `CodeLens[]`. Every lens carries its `command`: `command` is +/// a function of the registering plugin and `arguments` holds at most one +/// params object for it. +fn code_lens(value: Value) -> Result { + let items = list(value, MAX_CODE_LENSES, "code lens")?; + let mut lenses = Vec::with_capacity(items.len()); + for item in &items { + let failure = + || invalid("A code lens has a range and a command { title, command, arguments? }."); + let command = item.get("command").ok_or_else(failure)?; + let title = string(command, "title") + .filter(|title| { + !title.trim().is_empty() + && title.chars().count() <= 200 + && !title.chars().any(char::is_control) + }) + .ok_or_else(failure)?; + let function = string(command, "command") + .filter(|id| is_function_id(id)) + .ok_or_else(failure)?; + let params = match command.get("arguments") { + None => json!({}), + Some(Value::Array(arguments)) if arguments.is_empty() => json!({}), + Some(Value::Array(arguments)) if arguments.len() == 1 && arguments[0].is_object() => { + arguments[0].clone() + } + _ => return Err(failure()), + }; + let lens_range = item.get("range").and_then(range).ok_or_else(failure)?; + lenses.push(json!({ "range": lens_range, "command": { "title": title, "command": function, "arguments": [params] } })); + } + Ok(json!({ "lenses": lenses })) +} + +fn folding_range(value: Value) -> Result { + let items = list(value, MAX_FOLDING_RANGES, "folding range")?; + let mut ranges = Vec::with_capacity(items.len()); + for item in &items { + let failure = || invalid("A folding range has startLine <= endLine."); + let line = |key: &str| { + item.get(key) + .map(|value| value.as_u64().filter(|n| *n <= u64::from(u32::MAX))) + }; + let (Some(Some(start)), Some(Some(end))) = (line("startLine"), line("endLine")) else { + return Err(failure()); + }; + if start > end { + return Err(failure()); + } + let mut entry = json!({ "startLine": start, "endLine": end }); + if let Some(kind) = item.get("kind") { + entry["kind"] = json!(kind + .as_str() + .filter(|kind| identifier(kind)) + .ok_or_else(failure)?); + } + ranges.push(entry); + } + Ok(json!({ "ranges": ranges })) +} + +fn semantic_tokens(value: Value, legend: Option<&Legend>) -> Result { + let legend = legend.ok_or_else(|| invalid("A semantic tokens result needs its legend."))?; + if value.is_null() { + return Ok(json!({ "data": [] })); + } + let failure = || invalid("Invalid semantic tokens data."); + let data = value + .get("data") + .and_then(Value::as_array) + .ok_or_else(failure)?; + if data.len() % 5 != 0 || data.len() > MAX_SEMANTIC_TOKEN_INTEGERS { + return Err(failure()); + } + let mut integers = Vec::with_capacity(data.len()); + for (index, value) in data.iter().enumerate() { + let value = value + .as_u64() + .filter(|n| *n <= u64::from(u32::MAX)) + .ok_or_else(failure)?; + let valid = match index % 5 { + 3 => (value as usize) < legend.token_types.len(), + 4 => legend.token_modifiers.len() >= 32 || value >> legend.token_modifiers.len() == 0, + _ => true, + }; + if !valid { + return Err(failure()); + } + integers.push(value); + } + Ok(json!({ "data": integers })) +} + +fn document_link(value: Value) -> Result { + let items = list(value, MAX_DOCUMENT_LINKS, "document link")?; + let mut links = Vec::with_capacity(items.len()); + for item in &items { + let failure = || invalid("A document link has a range and an absolute target URI."); + let target = string(item, "target") + .filter(|target| uri(target)) + .ok_or_else(failure)?; + let mut entry = json!({ "range": item.get("range").and_then(range).ok_or_else(failure)?, "target": target }); + if let Some(tooltip) = item.get("tooltip") { + entry["tooltip"] = json!(tooltip + .as_str() + .filter(|value| bounded(value)) + .ok_or_else(failure)?); + } + links.push(entry); + } + Ok(json!({ "links": links })) +} + +fn list(value: Value, limit: usize, what: &str) -> Result, CoreError> { + match value { + Value::Null => Ok(Vec::new()), + Value::Array(items) if items.len() <= limit => Ok(items), + Value::Array(_) => Err(invalid(format!("A {what} result exceeds {limit} items."))), + _ => Err(invalid(format!("A {what} result is an array."))), + } +} + +/// The inputs of the definition merge: the requested place and the two +/// answers, each a list of validated locations. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DefinitionMerge { + document_uri: String, + position: LspPosition, + #[serde(default)] + server: Vec, + #[serde(default)] + plugin: Vec, +} + +/// Merges the language server's definitions with the plugins' as the +/// indices each side keeps. The server's answer comes first and plugins only +/// add to it: a plugin location that repeats one already kept is dropped, and +/// a server location that is the requested place itself (the caret already +/// sits on the declaration) yields when a plugin answered. +fn merge_definitions(value: Value) -> Result { + let merge: DefinitionMerge = serde_json::from_value(value) + .map_err(|_| invalid("A definition merge has documentUri, position, server and plugin."))?; + let places = merge.server.iter().chain(merge.plugin.iter()); + if !uri(&merge.document_uri) + || merge.server.len() > MAX_LOCATIONS + || merge.plugin.len() > MAX_LOCATIONS + || !places.into_iter().all(Location::valid) + { + return Err(invalid("Invalid definition merge.")); + } + let own_place = |location: &Location| { + location.uri == merge.document_uri + && location.range.start <= merge.position + && merge.position < location.range.end + }; + let yields = !merge.plugin.is_empty(); + let server: Vec = (0..merge.server.len()) + .filter(|&index| !(yields && own_place(&merge.server[index]))) + .collect(); + let mut plugin: Vec = Vec::new(); + for (index, location) in merge.plugin.iter().enumerate() { + let repeats = server.iter().any(|&kept| merge.server[kept] == *location) + || plugin.iter().any(|&kept| merge.plugin[kept] == *location); + if !repeats { + plugin.push(index); + } + } + Ok(json!({ "server": server, "plugin": plugin })) +} + +/// Validates a provider registration (`kind: registration`, with the +/// host's `types`) or one provider function's result (`kind: result`, with +/// its `type` and, for semantic tokens, the registered `legend`). Results +/// come back normalized. `kind: mergeDefinitions` applies the merge rule of +/// definitions. No I/O occurs. +pub fn decode_command(payload: Value) -> Result { + let payload: Payload = serde_json::from_value(payload) + .map_err(|_| invalid("Invalid editor provider validation payload."))?; + if payload.value.to_string().len() > MAX_BYTES { + return Err(invalid("Editor provider data exceeds 1 MiB.")); + } + match (payload.kind.as_str(), payload.provider_type.as_deref()) { + ("registration", None) => { + Ok(json!({ "registration": registration(payload.value, &payload.types)? })) + } + ("mergeDefinitions", None) => merge_definitions(payload.value), + ("result", Some(kind)) => Ok(json!({ "result": match kind { + "definition" => definition(payload.value)?, + "hover" => hover(payload.value)?, + "completion" => completion(payload.value)?, + "codeLens" => code_lens(payload.value)?, + "foldingRange" => folding_range(payload.value)?, + "semanticTokens" => semantic_tokens(payload.value, payload.legend.as_ref())?, + "documentLink" => document_link(payload.value)?, + _ => return Err(invalid("Unknown editor provider type.")), + }})), + _ => Err(invalid("Unknown editor provider validation kind.")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn types() -> Vec<&'static str> { + PROVIDER_TYPES.to_vec() + } + + #[test] + fn registrations_normalize_selectors_and_report_budgets() { + // A second tool: resource-key navigation in `.properties` and template files. + let decoded = decode_command(json!({"kind":"registration","types":types(),"value":{ + "id":"keys","selector":{"languages":["HTML","html"],"fileExtensions":[".Properties"],"fileNames":["Messages"]}, + "providers":{"definition":{"function":"keys.definition"}, + "completion":{"function":"keys.complete","triggerCharacters":["."]}, + "semanticTokens":{"function":"keys.tokens","legend":{"tokenTypes":["property"],"tokenModifiers":["declaration"]}}} + }})).unwrap(); + let registration = &decoded["registration"]; + assert_eq!(registration["selector"]["languages"], json!(["html"])); + assert_eq!( + registration["selector"]["fileExtensions"], + json!(["properties"]) + ); + assert_eq!(registration["selector"]["fileNames"], json!(["messages"])); + assert_eq!( + registration["providers"]["completion"]["budgetMs"], + json!(400) + ); + assert_eq!( + registration["providers"]["definition"]["budgetMs"], + json!(1500) + ); + assert_eq!( + registration["providers"]["semanticTokens"]["legend"]["tokenTypes"], + json!(["property"]) + ); + } + + #[test] + fn unknown_or_unrouted_types_are_unsupported_options() { + for providers in [ + json!({"diagnostics":{"function":"keys.check"}}), + json!({"hover":{"function":"keys.hover"}}), + ] { + let error = decode_command( + json!({"kind":"registration","types":["definition"],"value":{ + "id":"keys","selector":{"fileExtensions":["properties"]},"providers":providers}}), + ) + .unwrap_err(); + assert!(matches!(error.code, ErrorCode::NotSupported)); + assert!(error.details.unwrap().starts_with("providers.")); + } + } + + #[test] + fn registrations_reject_wrong_options_and_empty_selectors() { + for value in [ + json!({"id":"k","selector":{},"providers":{"hover":{"function":"keys.hover"}}}), + json!({"id":"k","selector":{"languages":["a/b"]},"providers":{"hover":{"function":"keys.hover"}}}), + json!({"id":"k","selector":{"fileExtensions":["x"]},"providers":{}}), + json!({"id":"k","selector":{"fileExtensions":["x"]},"providers":{"hover":{"function":"keys.hover","triggerCharacters":["."]}}}), + json!({"id":"k","selector":{"fileExtensions":["x"]},"providers":{"completion":{"function":"keys.complete","triggerCharacters":["ab"]}}}), + json!({"id":"k","selector":{"fileExtensions":["x"]},"providers":{"semanticTokens":{"function":"keys.tokens"}}}), + json!({"id":"k","selector":{"fileExtensions":["x"]},"providers":{"hover":{"function":"keys.hover","budgetMs":10}}}), + ] { + assert!( + decode_command(json!({"kind":"registration","types":types(),"value":value})) + .is_err() + ); + } + } + + fn place(uri: &str, line: u32, from: u32, to: u32) -> Value { + json!({"uri":uri,"range":{"start":{"line":line,"character":from},"end":{"line":line,"character":to}}}) + } + + fn merged(server: Vec, plugin: Vec, line: u32, character: u32) -> Value { + decode_command(json!({"kind":"mergeDefinitions","value":{ + "documentUri":"file:///work/app.go","position":{"line":line,"character":character}, + "server":server,"plugin":plugin}})) + .unwrap() + } + + #[test] + fn definition_merge_keeps_the_server_first_and_dedupes() { + let kept = merged( + vec![place("file:///work/a.go", 1, 0, 3)], + vec![ + place("file:///work/a.go", 1, 0, 3), + place("file:///work/b.go", 2, 0, 3), + ], + 9, + 9, + ); + assert_eq!(kept, json!({"server":[0],"plugin":[1]})); + } + + #[test] + fn definition_merge_yields_a_server_self_location_to_plugins() { + let own = place("file:///work/app.go", 4, 2, 8); + let kept = merged( + vec![own.clone()], + vec![place("file:///work/b.go", 2, 0, 3)], + 4, + 5, + ); + assert_eq!(kept, json!({"server":[],"plugin":[0]})); + // Without a plugin answer the server's answer stands, and an end bound is exclusive. + assert_eq!( + merged(vec![own.clone()], vec![], 4, 5), + json!({"server":[0],"plugin":[]}) + ); + assert_eq!( + merged(vec![own], vec![place("file:///work/b.go", 2, 0, 3)], 4, 8), + json!({"server":[0],"plugin":[0]}) + ); + } + + #[test] + fn definition_merge_rejects_invalid_locations() { + for value in [ + json!({"documentUri":"file:///work/app.go","position":{"line":0,"character":0}, + "server":[{"uri":"","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}]}), + json!({"documentUri":"file:///work/app.go","position":{"line":0,"character":0},"extra":1}), + json!({"documentUri":"","position":{"line":0,"character":0}}), + ] { + assert!(decode_command(json!({"kind":"mergeDefinitions","value":value})).is_err()); + } + } + + fn result(kind: &str, value: Value) -> Result { + decode_command(json!({"kind":"result","type":kind,"value":value, + "legend":{"tokenTypes":["property","string"],"tokenModifiers":["declaration"]}})) + .map(|value| value["result"].clone()) + } + + #[test] + fn results_normalize_lsp_shapes() { + let span = json!({"start":{"line":1,"character":2},"end":{"line":1,"character":8}}); + let link = json!({"targetUri":"file:///w/messages.properties","targetRange":span,"targetSelectionRange":span}); + assert_eq!( + result("definition", json!([link])).unwrap()["locations"][0]["uri"], + "file:///w/messages.properties" + ); + assert_eq!( + result("definition", Value::Null).unwrap(), + json!({"locations":[]}) + ); + let hover = result( + "hover", + json!({"contents":[{"language":"properties","value":"a=b"},"plain"]}), + ) + .unwrap(); + assert_eq!(hover["contents"][0]["value"], "```properties\na=b\n```"); + let completion = result("completion", json!({"isIncomplete":true,"items":[ + {"label":"app.title","kind":10,"data":{"private":1},"command":{"title":"x","command":"y"}, + "textEdit":{"newText":"app.title","insert":span,"replace":span}}]})).unwrap(); + assert_eq!(completion["isIncomplete"], true); + assert!( + completion["items"][0].get("data").is_none() + && completion["items"][0].get("command").is_none() + ); + let lenses = result("codeLens", json!([{"range":span,"command":{"title":"3 usages","command":"keys.usages","arguments":[{"key":"app.title"}]}}])).unwrap(); + assert_eq!( + lenses["lenses"][0]["command"]["arguments"], + json!([{"key":"app.title"}]) + ); + assert_eq!( + result( + "foldingRange", + json!([{"startLine":0,"endLine":3,"kind":"region"}]) + ) + .unwrap()["ranges"][0]["endLine"], + 3 + ); + assert_eq!( + result("semanticTokens", json!({"resultId":"1","data":[0,0,3,1,1]})).unwrap(), + json!({"data":[0,0,3,1,1]}) + ); + assert_eq!( + result( + "documentLink", + json!([{"range":span,"target":"https://example.com/keys"}]) + ) + .unwrap()["links"][0]["target"], + "https://example.com/keys" + ); + } + + #[test] + fn results_outside_their_limits_are_rejected_whole() { + let span = json!({"start":{"line":2,"character":0},"end":{"line":1,"character":0}}); + let lens = json!({"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}},"command":{"title":"Run","command":"keys.run"}}); + for (kind, value) in [ + ("definition", json!([{"uri":"file:///a","range":span}])), + ( + "definition", + json!(vec![ + json!({"uri":"file:///a","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}); + 101 + ]), + ), + ("hover", json!({"contents":"x".repeat(MAX_HOVER_BYTES + 1)})), + ( + "completion", + json!(vec![json!({"label":"a"}); MAX_COMPLETION_ITEMS + 1]), + ), + ("completion", json!([{"label":"a","kind":26}])), + ( + "codeLens", + json!([{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}]), + ), + ( + "codeLens", + json!([lens.clone(), {"range":lens["range"],"command":{"title":"Run","command":"keys.run","arguments":[1,2]}}]), + ), + ("foldingRange", json!([{"startLine":4,"endLine":1}])), + ("semanticTokens", json!({"data":[0,0,3,2,0]})), + ("semanticTokens", json!({"data":[0,0,3,0,2]})), + ("semanticTokens", json!({"data":[0,0,3]})), + ( + "documentLink", + json!([{"range":lens["range"],"target":"relative"}]), + ), + ("documentLink", json!([{"range":lens["range"]}])), + ("signatureHelp", json!(null)), + ] { + assert!(result(kind, value.clone()).is_err(), "{kind}: {value}"); + } + } + + /// The shared contract fixture. Registration failures name the host + /// code they become: Core's `not_supported` is `unsupportedOption` + /// with `details.option`, any other refusal is `invalidParams`. + #[test] + fn contract_fixture_cases() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../shared/contracts/plugins/v1/fixtures/editor/editor-providers.json" + ))) + .unwrap(); + let types = &fixture["host"]["providerTypes"]; + assert_eq!(types, &json!(PROVIDER_TYPES)); + for case in fixture["registrations"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let decoded = + decode_command(json!({"kind":"registration","types":types,"value":case["params"]})); + let expected = &case["expected"]; + match (expected["status"].as_str().unwrap(), decoded) { + ("accepted", Ok(decoded)) => { + assert_eq!(decoded["registration"], expected["registration"], "{name}") + } + ("rejected", Err(error)) => { + let unsupported = matches!(error.code, ErrorCode::NotSupported); + let code = if unsupported { + "plugin.host.unsupportedOption" + } else { + "plugin.host.invalidParams" + }; + assert_eq!(expected["code"], code, "{name}"); + let details = error.details.map(|option| json!({ "option": option })); + assert_eq!(expected.get("details"), details.as_ref(), "{name}"); + } + (status, decoded) => panic!("{name}: expected {status}, got {decoded:?}"), + } + } + for case in fixture["results"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let mut payload = json!({"kind":"result","type":case["type"],"value":case["value"]}); + if let Some(legend) = case.get("legend") { + payload["legend"] = legend.clone(); + } + let decoded = decode_command(payload); + match case["expected"]["status"].as_str().unwrap() { + "accepted" => assert_eq!( + decoded.unwrap_or_else(|error| panic!("{name}: {error:?}"))["result"], + case["expected"]["value"], + "{name}" + ), + _ => assert!(decoded.is_err(), "{name}"), + } + } + } +} diff --git a/rust/lithe-core/src/plugins/mod.rs b/rust/lithe-core/src/plugins/mod.rs index 0ccdacbd88..f97ed37c39 100644 --- a/rust/lithe-core/src/plugins/mod.rs +++ b/rust/lithe-core/src/plugins/mod.rs @@ -5,6 +5,7 @@ pub mod capabilities; pub mod declarative; /// Independent, host-rendered editor actions of ordinary tool plugins. pub mod editor_actions; +pub mod editor_providers; pub(crate) mod executables; pub(crate) mod grammar; pub(crate) mod keymap_import; diff --git a/rust/lithe-core/src/protocol/command.rs b/rust/lithe-core/src/protocol/command.rs index 6677e0cf63..035ee14266 100644 --- a/rust/lithe-core/src/protocol/command.rs +++ b/rust/lithe-core/src/protocol/command.rs @@ -132,6 +132,8 @@ pub enum CoreCommand { PluginsDeclarativeDecodeGrammar, /// Validates independent editor action registration or results. PluginsEditorActionsDecode, + /// Validates editor provider registrations and provider results. + PluginsEditorProvidersDecode, /// Validates a normalized shortcut import against the host's action catalog. KeymapDecodeImport, /// Plans the selected provider's declared shortcut source inputs. @@ -765,6 +767,7 @@ impl CoreCommand { } "plugins.declarative.decodeGrammar" => Some(Self::PluginsDeclarativeDecodeGrammar), "plugins.editorActions.decode" => Some(Self::PluginsEditorActionsDecode), + "plugins.editorProviders.decode" => Some(Self::PluginsEditorProvidersDecode), "keymap.decodeImport" => Some(Self::KeymapDecodeImport), "keymap.planImportSources" => Some(Self::KeymapPlanImportSources), "keymap.planImportBindings" => Some(Self::KeymapPlanImportBindings), diff --git a/rust/lithe-core/src/runtime/dispatcher.rs b/rust/lithe-core/src/runtime/dispatcher.rs index 9fa4c01d44..d32fbebcf5 100644 --- a/rust/lithe-core/src/runtime/dispatcher.rs +++ b/rust/lithe-core/src/runtime/dispatcher.rs @@ -317,6 +317,11 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { parsed.payload, crate::plugins::editor_actions::decode_command, ), + CoreCommand::PluginsEditorProvidersDecode => plugin_response( + id, + parsed.payload, + crate::plugins::editor_providers::decode_command, + ), CoreCommand::KeymapDecodeImport => plugin_response( id, parsed.payload, diff --git a/rust/lithe-core/src/tests/declarative_plugins.rs b/rust/lithe-core/src/tests/declarative_plugins.rs index 23f7eb6952..15d3c5e645 100644 --- a/rust/lithe-core/src/tests/declarative_plugins.rs +++ b/rust/lithe-core/src/tests/declarative_plugins.rs @@ -49,6 +49,8 @@ const DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE: &str = const DEBUG_ADAPTER_REJECTIONS: &str = contract_file!("fixtures/debug-adapters/debug-adapter-rejections.json"); const EDITOR_ACTIONS_FIXTURE: &str = contract_file!("fixtures/editor/editor-actions.plugin.json"); +const EDITOR_PROVIDERS_FIXTURE: &str = + contract_file!("fixtures/editor/editor-providers.plugin.json"); const GRAMMAR_FIXTURE: &str = contract_file!("fixtures/languages/language-grammar.plugin.json"); const PROJECT_GENERATOR_FIXTURE: &str = contract_file!("fixtures/project-generators/project-generator.plugin.json"); @@ -83,6 +85,7 @@ fn fixture(name: &str) -> Value { "debug-adapter-language-server.plugin.json" => DEBUG_ADAPTER_LANGUAGE_SERVER_FIXTURE, "debug-adapter-remote-attach.plugin.json" => DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE, "language-grammar.plugin.json" => GRAMMAR_FIXTURE, + "editor-providers.plugin.json" => EDITOR_PROVIDERS_FIXTURE, "project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE, "project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE, other => panic!("unknown fixture {other}"), @@ -110,6 +113,7 @@ fn contract_fixtures_and_official_plugins_validate() { DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE, GRAMMAR_FIXTURE, EDITOR_ACTIONS_FIXTURE, + EDITOR_PROVIDERS_FIXTURE, PROJECT_GENERATOR_TOOL_FIXTURE, OFFICIAL_JAVA, ] { diff --git a/rust/lithe-core/src/tests/toolchain_resolution.rs b/rust/lithe-core/src/tests/toolchain_resolution.rs index b644af9cc2..ca442b8a44 100644 --- a/rust/lithe-core/src/tests/toolchain_resolution.rs +++ b/rust/lithe-core/src/tests/toolchain_resolution.rs @@ -1,6 +1,8 @@ //! Exercises shared tool selection through production commands and inert native facts. -use super::toolchain_vectors::{local_pins, query_request, query_response, HOME, WORKSPACE}; +use super::toolchain_vectors::{ + local_pins, query_request, query_response, HOME, MANUAL_HOME, WORKSPACE, +}; use crate::toolchain::{ candidates_command, check_version_command, discovery_plan_command, failure_reply_command, resolve_command, @@ -202,7 +204,7 @@ fn consumer_fixed_choices_reject_ambiguous_relative_and_authority_smuggling_fiel #[test] fn toolchain_resolution_pins_inherit_nearest_ancestor_without_sibling_prefixes() { let mut value = input(); - let manual = "/opt/lithe-fixtures/manual/java/17.0.12"; + let manual = MANUAL_HOME; installation(&mut value, HOME, "21.0.4"); installation(&mut value, manual, "17.0.12"); value["local"] = local_pins(); diff --git a/rust/lithe-core/src/tests/toolchain_vectors.rs b/rust/lithe-core/src/tests/toolchain_vectors.rs index 4a84810844..05ab7d1164 100644 --- a/rust/lithe-core/src/tests/toolchain_vectors.rs +++ b/rust/lithe-core/src/tests/toolchain_vectors.rs @@ -6,12 +6,30 @@ use serde_json::{json, Value}; -/// Java home that the query reply reports and the root pin selects. -pub(super) const HOME: &str = "/opt/lithe-fixtures/installs/java/21.0.4"; +/// Tool-definition fixture whose single tool every vector queries and pins. +const TOOL_DEFINITION: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../shared/contracts/plugins/v1/fixtures/toolchains/tool-definition.plugin.json" +)); + +/// Home of the tool that the query reply reports and the root pin selects. +pub(super) const HOME: &str = "/opt/lithe-fixtures/installs/tool/21.0.4"; /// Workspace root that the query request names. pub(super) const WORKSPACE: &str = "/opt/lithe-fixtures/workspace"; /// Manually pinned home for `apps/web`, older than [`HOME`]. -const MANUAL_HOME: &str = "/opt/lithe-fixtures/manual/java/17.0.12"; +pub(super) const MANUAL_HOME: &str = "/opt/lithe-fixtures/manual/tool/17.0.12"; + +/// Returns the tool ID that [`TOOL_DEFINITION`] declares. +/// +/// The vectors read the ID from the fixture instead of repeating it, so host +/// test code names no specific tool and stays in step with the fixture. +fn tool() -> String { + let fixture: Value = serde_json::from_str(TOOL_DEFINITION).unwrap(); + fixture["toolDefinitions"][0]["id"] + .as_str() + .unwrap() + .to_owned() +} /// Builds a local pins document with a root pin, a manual pin on `apps/web` /// and a pin on the hidden `.config/tools` directory. @@ -19,31 +37,34 @@ const MANUAL_HOME: &str = "/opt/lithe-fixtures/manual/java/17.0.12"; /// The nested pins let tests check that a directory inherits its nearest /// ancestor and that a sibling sharing a name prefix does not. pub(super) fn local_pins() -> Value { + let tool = tool(); json!({"version":1,"toolchains":{},"pins":{ - ".":{"java":{"home":HOME,"version":"21.0.4","provider":"dev.lithe.fixture.mise:mise"}}, - "apps/web":{"java":{"home":MANUAL_HOME,"version":"17.0.12","provider":"host:manual"}}, - ".config/tools":{"java":{"home":HOME,"version":"21.0.4","provider":"dev.lithe.fixture.mise:mise"}} + ".":{tool.as_str():{"home":HOME,"version":"21.0.4","provider":"dev.lithe.fixture.mise:mise"}}, + "apps/web":{tool.as_str():{"home":MANUAL_HOME,"version":"17.0.12","provider":"host:manual"}}, + ".config/tools":{tool.as_str():{"home":HOME,"version":"21.0.4","provider":"dev.lithe.fixture.mise:mise"}} }}) } /// Builds the `toolchains/query` request a host sends to the `mise` provider -/// for Java in the workspace root. +/// for the fixture tool in the workspace root. pub(super) fn query_request() -> Value { + let tool = tool(); json!({"jsonrpc":"2.0","id":1,"method":"toolchains/query","params":{ "operationID":"query-1","generation":1,"providerID":"mise","authority":{"kind":"local"}, "context":{"contextID":"context-1","generation":1}, - "workspace":{"rootID":"root-1","root":WORKSPACE,"directory":"."},"tools":["java"]}}) + "workspace":{"rootID":"root-1","root":WORKSPACE,"directory":"."},"tools":[tool]}}) } /// Builds a valid reply to [`query_request`]: one installed home and the /// project requirement in `mise.toml` that selects it. pub(super) fn query_response() -> Value { + let tool = tool(); json!({"jsonrpc":"2.0","id":1,"result":{ "operationID":"query-1","generation":1,"providerID":"mise", - "installations":[{"tool":"java","version":"21.0.4","home":HOME}], - "statements":[{"tool":"java","scope":"project","source":format!("{WORKSPACE}/mise.toml"), + "installations":[{"tool":tool,"version":"21.0.4","home":HOME}], + "statements":[{"tool":tool,"scope":"project","source":format!("{WORKSPACE}/mise.toml"), "request":"21","installation":HOME,"kind":"declaration","reader":"native"}], - "watch":[format!("{WORKSPACE}/mise.toml"),"/opt/lithe-fixtures/installs/java"]}}) + "watch":[format!("{WORKSPACE}/mise.toml"),"/opt/lithe-fixtures/installs/tool"]}}) } /// Builds one JSON-RPC error reply per stable toolchain failure. diff --git a/scripts/architecture/language-specifics-baseline.json b/scripts/architecture/language-specifics-baseline.json index 1a44cd9013..a5d3fb2525 100644 --- a/scripts/architecture/language-specifics-baseline.json +++ b/scripts/architecture/language-specifics-baseline.json @@ -1,7 +1,6 @@ { "description": "Per-file counts of language and build-tool names in host code. Counts may only go down; regenerate with --update-baseline after removing names. Deleted by the final Java extraction PR (#1495), which switches to --strict.", "files": { - "frontend/editor/src/plugin-editor-actions.ts": {"words":2}, "frontend/editor/src/workbench.ts": {"words":97,"nameComparisons":8}, "macos/Sources/Lithe/Application/Composition/AppModelFeatureGraph.swift": {"words":26}, "macos/Sources/Lithe/Application/Composition/AppModelObservationBinder.swift": {"words":1}, @@ -297,7 +296,7 @@ "rust/lithe-core/src/tests/support.rs": {"words":1}, "rust/lithe-core/src/tests/toolchain_pins.rs": {"words":33}, "rust/lithe-core/src/tests/toolchain_queries.rs": {"words":15,"nameComparisons":1}, - "rust/lithe-core/src/tests/toolchain_resolution.rs": {"words":90,"nameComparisons":1}, + "rust/lithe-core/src/tests/toolchain_resolution.rs": {"words":89,"nameComparisons":1}, "rust/lithe-core/src/tests/vcs.rs": {"words":1}, "rust/lithe-core/src/toolchain/pins.rs": {"words":1}, "rust/lithe-core/src/vcs/model.rs": {"words":1}, diff --git a/scripts/architecture/verify-editor-boundaries.mjs b/scripts/architecture/verify-editor-boundaries.mjs index 1bdf6f7b33..fd0cd4a18b 100644 --- a/scripts/architecture/verify-editor-boundaries.mjs +++ b/scripts/architecture/verify-editor-boundaries.mjs @@ -32,5 +32,13 @@ if (!/^linker\s*=\s*"isolated"/m.test(bunConfig)) { if (windows.dependencies["monaco-editor"] !== shared.dependencies["monaco-editor"]) { failures.push("Both hosts must use the exact same Monaco version"); } +// The macOS host offers plugins gutter icon names (API-27); each needs an SVG in the web editor. +const hostOptions = readFileSync(join(root, "macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift"), "utf8"); +const offered = /actionIcons:\s*\[([^\]]*)\]/.exec(hostOptions)?.[1].match(/"[a-z0-9-]+"/g)?.map(name => name.slice(1, -1)) ?? []; +const frontend = readFileSync(join(root, "macos/EditorFrontend/main.ts"), "utf8"); +const drawn = new Set((/editorActionIcons:\s*\{([^}]*)\}/.exec(frontend)?.[1].match(/"?[a-z][a-z0-9-]*"?(?=\s*:)/g) ?? []) + .map(name => name.replaceAll('"', ""))); +if (!offered.length) failures.push("macOS plugin editor action icons could not be read from the host options"); +for (const name of offered) if (!drawn.has(name)) failures.push(`macOS plugin editor action icon "${name}" has no SVG in macos/EditorFrontend/main.ts`); if (failures.length) { console.error(failures.join("\n")); process.exitCode = 1; } else console.log("Shared editor boundaries and Monaco version verified"); diff --git a/scripts/architecture/verify-shared-contracts.sh b/scripts/architecture/verify-shared-contracts.sh index 68bb2d84f9..060f099c3c 100755 --- a/scripts/architecture/verify-shared-contracts.sh +++ b/scripts/architecture/verify-shared-contracts.sh @@ -255,6 +255,33 @@ done abort "function protocol fixture uses an undocumented code #{code}" unless documented.include?(code) end abort "function protocol fixture contains a machine path" if JSON.generate(functions).match?(%r{/(?:Users|home|var/folders|private/var)/|[A-Za-z]:\\\\}) + # Editor actions (version 2) and editor providers: Core decodes every case. + actions = JSON.parse(File.read(File.join(fixtures, "editor", "editor-actions-v2.json"))) + abort "editor action fixture schema must be 1" unless actions.fetch("schemaVersion") == 1 + action_names = actions.fetch("cases").map { |item| item.fetch("name") } + abort "editor action case names must be unique" unless action_names.uniq.length == action_names.length + actions.fetch("cases").each do |item| + abort "editor action case #{item.fetch("name")} uses an unknown kind" unless %w[actions invokeResult].include?(item.fetch("kind")) + abort "editor action case #{item.fetch("name")} uses an unknown status" unless %w[accepted rejected].include?(item.fetch("expected").fetch("status")) + end + providers = JSON.parse(File.read(File.join(fixtures, "editor", "editor-providers.json"))) + abort "editor provider fixture schema must be 1" unless providers.fetch("schemaVersion") == 1 + provider_types = providers.fetch("host").fetch("providerTypes") + provider_names = (providers.fetch("registrations") + providers.fetch("results")).map { |item| item.fetch("name") } + abort "editor provider case names must be unique" unless provider_names.uniq.length == provider_names.length + providers.fetch("registrations").each do |item| + code = item.fetch("expected")["code"] + abort "editor provider case #{item.fetch("name")} uses an undocumented code" unless code.nil? || documented.include?(code) + end + providers.fetch("results").each do |item| + abort "editor provider case #{item.fetch("name")} uses an unknown type" unless provider_types.include?(item.fetch("type")) + end + provider_types.each do |type| + abort "editor provider type #{type} is undocumented" unless readme.include?("`#{type}`") + end + [actions, providers].each do |fixture| + abort "editor fixture contains a machine path" if JSON.generate(fixture).match?(%r{/(?:Users|home|var/folders|private/var)/|[A-Za-z]:\\\\}) + end index_schema = JSON.parse(File.read(File.join(root, "plugin-index.schema.json"))) abort "plugin index schema ID mismatch" unless index_schema.fetch("$id") == "#{published_base}/plugin-index.schema.json" abort "plugin indexes must use schemaVersion 1" unless index_schema.fetch("properties").fetch("schemaVersion").fetch("const") == 1 diff --git a/shared/contracts/plugins/v1/README.md b/shared/contracts/plugins/v1/README.md index 412388f88b..08a03e7b99 100644 --- a/shared/contracts/plugins/v1/README.md +++ b/shared/contracts/plugins/v1/README.md @@ -21,7 +21,7 @@ This directory is the cross-platform source of truth: | `fixtures/manifest/` | `hello-lithe.plugin.json`, the smallest UI plugin, and `invalid-manifests.json`: edits to a valid manifest and the rejection code every host must report | | `fixtures/languages/` | Language support: packaged, system-command, and host-integration language servers, `node-runtime` for a discovered runtime, and `language-grammar` with `grammars/`; `command-plans.json` holds golden run/test command expansions and language-server launch plans, `runtime-versions.json` the golden outcomes of the launch runtime version check | | `fixtures/backend/` | Plugin backends (`backend`, `backend-workspace`, `command-backend`, `terminal-backend`); `function-protocol.json` holds golden plugin-function negotiation, registration, invocation, outcome, progress, and refusal cases, `plugin-logging.json` the golden `litheLogging` negotiation and notifications | -| `fixtures/editor/` | Editor actions served by a backend | +| `fixtures/editor/` | Editor actions served by a backend: `editor-actions.plugin.json`, version 2 icons, alternatives and click results in `editor-actions-v2.json`; editor providers in `editor-providers.plugin.json` with registration and result cases in `editor-providers.json` | | `fixtures/ui/` | Native controls, forms, and panels, and a web panel | | `fixtures/settings/` | Plugin settings declared with `settings: 2` | | `fixtures/build-systems/` | Level 3 build systems (`build-*`: static file, command output, host integration, instance options, model producer and consumer, tool path, toolchains); `build-plans.json` holds golden build-system plans and decoded outputs | @@ -228,9 +228,9 @@ activation event, and a plugin may consist of grammars alone. explicit contract; an arbitrary new `kind` string cannot supply one. - This contribution does not register completion, hover, definition, symbol, formatting, rename, or Code Action providers backed by ordinary plugin - functions. Those independent provider bindings are not implemented; existing - LSP support and `editor/registerActions` are separate capabilities, not a - substitute for them. + functions. A backend binds the provider types a host routes with + [`editor/registerProviders`](#editor-language-feature-providers-protocol-version-3); + existing LSP support and `editor/registerActions` are separate capabilities. - `grammar.path` is a package-relative file that stays inside the package. Hosts read it read-only from the installed package, pass its text to `plugins.declarative.decodeGrammar`, and hand the returned object to the @@ -770,6 +770,7 @@ Rules for publishing across levels and capability versions: | `credentials.store` | the backend uses the [credentials host service](#host-services-protocol-version-2); refused without a `backend` | | `workspace.metadata` | the backend uses the [workspace host service](#workspace-contexts-and-capability-discovery-protocol-version-3); refused without `backend` 2 | | `editor.actions` | the backend registers independent editor actions; requires `backend` 2 and `documents.read`, grants only `editor/registerActions`, not document edits or domain execution | +| `editor.providers` | the backend supplies [editor language features](#editor-language-feature-providers-protocol-version-3) for matching files; requires `backend` 2 and `documents.read`, grants only `editor/registerProviders`, not document edits | | `terminal.create` | the backend creates and manages its own [native terminals](#plugin-owned-native-terminals-function-protocol-3), including bounded display history for reopen; requires `backend` 2 | | Activation event | Meaning | @@ -2445,6 +2446,14 @@ notifications. `functionResultBytes`, `hostRequestBytes`, `hostResultBytes`, `errorMessageBytes` (the cut of a host failure's message), `errorDetailsBytes`, and `notificationBytes`. A backend must check `services` instead of assuming a method from the version. +- A service entry may also carry `options`: what the host declared for that + service. When `editor/registerActions` is granted, `services.editor.options` + has `actionIcons` (the icon tokens the host draws) and `limits` gains + `editorActionSourceBytes` (the largest document the host sends a + collector). When `editor/registerProviders` is granted, + `services.editor.options.providerTypes` lists the provider types the host + routes. A host that omits `actionIcons` accepts only the first editor-action + shape. - A context is one open workspace in one window: ```json @@ -2635,6 +2644,7 @@ methods. Unknown options fail before side effects with `unsupportedOption`. | `documents/list` | `documents.read` | none | `{documents:[]}` | | `documents/getSnapshot` | `documents.read` | `documentID` | `{document:, text}` from the dirty live buffer | | `editor/registerActions` | `editor.actions` (+ `documents.read`) | `id,function,selector` | `{subscriptionID}`; independent editor actions, see below | +| `editor/registerProviders` | `editor.providers` (+ `documents.read`) | `id,selector,providers` | `{subscriptionID}`; editor language-feature providers, see below | | `editor/getActive` | `documents.read` | none | summary of the foreground text tab, or `null` | | `editor/getSelections` | `documents.read` | `documentID` | `{documentID,version,selections:[{anchor,active}],primaryIndex}` | | `editor/applyEdits` | `editor.edit` | `documentID,expectedVersion,edits:[{range,text}]` | `{documentID,version,applied}` | @@ -2746,8 +2756,10 @@ workspace context: - The host invokes the collection function via existing `lithe/function/invoke` with workspace context and `{document:{documentID,version,path},text}`. Version is the same public buffer version as `documents/getSnapshot`, not a WebView - revision. Source is the dirty live buffer, capped at 128 KiB. Remote workspaces - and read-only preview surfaces are not served by this first implementation. + revision. Source is the dirty live buffer, capped at the host's + `limits.editorActionSourceBytes` (1 MiB on macOS; 128 KiB when the host does + not report the limit). Remote workspaces and read-only preview surfaces are not + served by this first implementation. - Collection is read-only by contract: no network request or business execution. Edits invalidate the old actions immediately and cancel older collection work; the host debounces fresh collection and rejects stale or withdrawn results. @@ -2758,20 +2770,42 @@ workspace context: invoke:{functionID,params?}}]}`. Positions are one-based UTF-16, half-open and cannot split surrogate pairs. Each range stays in the exact input document. `id` is 1 to 128 bytes without controls, unique per answer; `title` is 1 to 200 - characters on one line. `icon` is `run` or `run-all`, a host-owned presentation - token. At most 1000 actions and 1 MiB serialized; malformed answers are refused - whole. Same-line actions share a menu rather than silently replacing each other. + characters on one line. `icon` is a host-owned presentation token from + `services.editor.options.actionIcons` (`run` or `run-all` when the host does not + report the list). At most 1000 actions and 1 MiB serialized; malformed answers + are refused whole. Same-line actions share a menu rather than silently replacing + each other. +- An action may carry `alternatives`: at most 4 `{id,title,icon,invoke}` entries + with the same rules and IDs unique within the action, offered in the action's + menu after the action itself (for example Debug or Test beside Run). Hosts that + omit `actionIcons` refuse an answer with alternatives. +- The macOS host draws `run`, `run-all`, `debug`, `test`, `test-passed`, + `test-failed`, `test-skipped`, `navigate-super` and `navigate-implementations`. + An icon names a picture, not an operation: a test icon does not make the + action a test, and the host never starts anything because of an icon. - Each invocation target is a currently registered function of the same plugin; `params` is a plugin-private JSON object. The host stores it behind an opaque per-batch action key, never accepts invocation payloads from the web editor, and validates document/context/session/registration again on click. It calls the function with `{documentID,expectedVersion,actionID,data:}` through the - ordinary invocation lifecycle. The plugin validates/re-reads the live document - before side effects. Click executions are not cancelled by unrelated re-parsing; + ordinary invocation lifecycle; a chosen alternative adds `alternativeID` and + passes that alternative's `params` as `data`. The plugin validates/re-reads the + live document before side effects. +- A click result may carry `{reveal:{locations:[{uri,range}]}}`: 1 to 100 + absolute URIs with zero-based LSP ranges. The host opens a single location and + lists several in its navigation results. Other result members stay the + plugin's own. Hosts that omit `actionIcons` ignore the result. +- A click that runs or debugs code starts it through the host's run and debug + methods (`lithe/host/run/start`, `lithe/host/debug/start`) once + `getCapabilities` lists them, so the run appears in the host's Run and Debug + windows. A private process started by the plugin is not a substitute. Click executions are not cancelled by unrelated re-parsing; withdrawing the binding, ending its session/context or tearing down the owning editor cancels them. The host never retries side effects automatically. - Registration/collection validation is shared Core command - `plugins.editorActions.decode`; public host failures retain protocol 3's existing + `plugins.editorActions.decode`; `version: 2` with the host's icons and source + bound admits alternatives and click results (`kind: invokeResult`), and version 1 + keeps the first shape. Cases: `fixtures/editor/editor-actions-v2.json`. Public host + failures retain protocol 3's existing distinct codes (`invalidParams`, `permissionDenied`, `versionConflict`, etc.). No tool-private error or result is interpreted as a build/test result. - Existing `commands/didRun {commandID,context?}` is unchanged. A command-palette @@ -2782,6 +2816,84 @@ workspace context: older host that does not recognize that permission, rather than silently granted. Grammar capability admission is separate. SDK/contract mirrors still need sync. +### Editor language-feature providers (protocol version 3) + +A provider adds a language feature the file's language server does not +supply: a cross-file fact only the plugin knows, such as a key in a template +that names an entry in a message bundle, or a framework declaration in a +configuration file that names a method in source. It never replaces the +language server. Where a language server answers, its answer comes first and +plugin results only add to it; a plugin that repeats what the server already +says shows the user the same thing twice. + +A backend declares `backend: 2`, `documents.read` and `editor.providers`, +finds `lithe/host/editor/registerProviders` and +`services.editor.options.providerTypes` with `getCapabilities`, then registers +per workspace context: + +```json +{ + "context": {"contextID": "w1", "generation": 1}, + "id": "message-keys", + "selector": {"languages": ["html"], "fileExtensions": ["properties"], "fileNames": []}, + "providers": { + "definition": {"function": "keys.definition"}, + "hover": {"function": "keys.hover"}, + "completion": {"function": "keys.complete", "triggerCharacters": ["."]}, + "semanticTokens": {"function": "keys.tokens", + "legend": {"tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"]}} + } +} +``` + +- Registration returns `{subscriptionID}`; dispose it with the subscription + API. Ending the session, the context or the plugin's activation withdraws + every registration it made, and a plugin activated later registers again. + Each named function must already be registered on that session. +- A selector has 1 to 32 entries in total: language IDs, literal extensions + (optional leading dot) and literal file names, matched case-insensitively. + A document matches when any entry matches. At most 32 registrations per + plugin across contexts; duplicate IDs in a context are refused. +- `providers` maps a provider type to `{function}`. The macOS host routes + `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, + `semanticTokens` and `documentLink`. Completion may add 1 to 16 + single-character `triggerCharacters`; semantic tokens must add their + `legend` (at most 64 types and 64 modifiers). A type outside the host's + `providerTypes` fails with `unsupportedOption` and + `details.option: "providers."` before anything is registered. + Diagnostics are not a provider type. +- The host calls the function through `lithe/function/invoke` with the + workspace context and `{documentID,version}`; definition, hover and + completion add `position: {line,character}` (zero-based, UTF-16), and + completion adds `triggerCharacter` when typing started it. The plugin reads + the text with `documents/getSnapshot` and answers for that version. +- Results use the LSP 3.17 shapes of the matching request: definition + `Location | Location[] | LocationLink[] | null`, `Hover | null`, + `CompletionItem[] | CompletionList | null` (no `data`, `command` or resolve + round trip), `CodeLens[] | null`, `FoldingRange[] | null`, + `SemanticTokens | null` indexed by the registered legend, and + `DocumentLink[] | null` with absolute targets. Every code lens carries its + `command`, whose `command` is a function of the same plugin and whose + `arguments` holds at most one params object; a click calls that function + with `{documentID,expectedVersion,data:}`. A malformed result is + dropped whole. +- Budgets are the host's: hover and completion 400 ms, definition 1500 ms, + the rest 2000 ms. A late answer, or one for an older document version, is + dropped without an error. A registration cannot set its own budget. +- The host merges: hover sections and completion items follow the language + server's; definitions add plugin locations to the server's (a location at + the requested position itself yields to the plugin's); code lenses, folding + ranges and links are added; semantic tokens apply only to files whose + language server has none. A plugin location equal to one already kept is + dropped. The merge is Core command `plugins.editorProviders.decode` with + `kind: "mergeDefinitions"`, so every host merges definitions alike. +- Validation is shared Core command `plugins.editorProviders.decode`. Cases: + `fixtures/editor/editor-providers.json`. Example package: + `fixtures/editor/editor-providers.plugin.json`. +- This is an additive host method within protocol 3, not a version bump. A + package requiring `editor.providers` is refused by an older host that does + not recognize the permission. + ### Compatibility - Packages of every API level are unchanged: functions add no manifest field. diff --git a/shared/contracts/plugins/v1/fixtures/editor/editor-actions-v2.json b/shared/contracts/plugins/v1/fixtures/editor/editor-actions-v2.json new file mode 100644 index 0000000000..f008386927 --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/editor/editor-actions-v2.json @@ -0,0 +1,118 @@ +{ + "schemaVersion": 1, + "description": "Version 2 editor action validation. `host` is what the host declared in getCapabilities (`services.editor.options.actionIcons` and `limits.editorActionSourceBytes`); `kind` is `actions` for a collector result (one-based UTF-16 positions in `text`) or `invokeResult` for the result of a clicked action or alternative. Accepted cases list the normalized value; rejected cases reject the whole result.", + "host": { + "actionIcons": ["run", "run-all", "debug", "test", "test-passed", "test-failed", "test-skipped", "navigate-super", "navigate-implementations"], + "actionSourceBytes": 1048576 + }, + "cases": [ + { + "name": "a Go main marker offers debug and test alternatives", + "kind": "actions", + "text": "package main\n\nfunc main() {}\n", + "value": { + "actions": [ + { + "id": "main", + "range": { "start": { "line": 3, "column": 1 }, "end": { "line": 3, "column": 10 } }, + "title": "Run main", + "icon": "run", + "invoke": { "functionID": "go.markers.invoke", "params": { "entry": "main" } }, + "alternatives": [ + { "id": "debug", "title": "Debug main", "icon": "debug", "invoke": { "functionID": "go.markers.invoke", "params": { "entry": "main", "debug": true } } }, + { "id": "test", "title": "Test package", "icon": "test", "invoke": { "functionID": "go.markers.invoke" } } + ] + } + ] + }, + "expected": { + "status": "accepted", + "value": [ + { + "id": "main", + "range": { "start": { "line": 3, "column": 1 }, "end": { "line": 3, "column": 10 } }, + "title": "Run main", + "icon": "run", + "invoke": { "functionID": "go.markers.invoke", "params": { "entry": "main" } }, + "alternatives": [ + { "id": "debug", "title": "Debug main", "icon": "debug", "invoke": { "functionID": "go.markers.invoke", "params": { "entry": "main", "debug": true } } }, + { "id": "test", "title": "Test package", "icon": "test", "invoke": { "functionID": "go.markers.invoke", "params": {} } } + ] + } + ] + } + }, + { + "name": "a Go test function shows its last outcome", + "kind": "actions", + "text": "func TestParse(t *testing.T) {}\n", + "value": { + "actions": [ + { "id": "TestParse", "range": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 15 } }, "title": "Run TestParse", "icon": "test-failed", "invoke": { "functionID": "go.markers.invoke", "params": { "test": "TestParse" } } } + ] + }, + "expected": { + "status": "accepted", + "value": [ + { "id": "TestParse", "range": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 15 } }, "title": "Run TestParse", "icon": "test-failed", "invoke": { "functionID": "go.markers.invoke", "params": { "test": "TestParse" } } } + ] + } + }, + { + "name": "an icon the host did not declare", + "kind": "actions", + "text": "x", + "value": { "actions": [ { "id": "a", "range": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 1 } }, "title": "Run", "icon": "rocket", "invoke": { "functionID": "go.markers.invoke" } } ] }, + "expected": { "status": "rejected" } + }, + { + "name": "at most four alternatives", + "kind": "actions", + "text": "x", + "value": { "actions": [ { "id": "a", "range": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 1 } }, "title": "Run", "icon": "run", "invoke": { "functionID": "go.markers.invoke" }, + "alternatives": [ + { "id": "1", "title": "One", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } }, + { "id": "2", "title": "Two", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } }, + { "id": "3", "title": "Three", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } }, + { "id": "4", "title": "Four", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } }, + { "id": "5", "title": "Five", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } } + ] } ] }, + "expected": { "status": "rejected" } + }, + { + "name": "alternative IDs are unique within their action", + "kind": "actions", + "text": "x", + "value": { "actions": [ { "id": "a", "range": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 1 } }, "title": "Run", "icon": "run", "invoke": { "functionID": "go.markers.invoke" }, + "alternatives": [ + { "id": "same", "title": "Debug", "icon": "debug", "invoke": { "functionID": "go.markers.invoke" } }, + { "id": "same", "title": "Test", "icon": "test", "invoke": { "functionID": "go.markers.invoke" } } + ] } ] }, + "expected": { "status": "rejected" } + }, + { + "name": "a click reveals resource-key definitions", + "kind": "invokeResult", + "value": { "reveal": { "locations": [ + { "uri": "file:///workspace/messages.properties", "range": { "start": { "line": 4, "character": 0 }, "end": { "line": 4, "character": 9 } } }, + { "uri": "file:///workspace/messages_zh.properties", "range": { "start": { "line": 2, "character": 0 }, "end": { "line": 2, "character": 9 } } } + ] }, "started": true }, + "expected": { "status": "accepted", "value": { "reveal": { "locations": [ + { "uri": "file:///workspace/messages.properties", "range": { "start": { "line": 4, "character": 0 }, "end": { "line": 4, "character": 9 } } }, + { "uri": "file:///workspace/messages_zh.properties", "range": { "start": { "line": 2, "character": 0 }, "end": { "line": 2, "character": 9 } } } + ] } } } + }, + { + "name": "other result members stay the plugin's own", + "kind": "invokeResult", + "value": { "runID": "r1" }, + "expected": { "status": "accepted", "value": {} } + }, + { + "name": "a reveal location needs an absolute URI", + "kind": "invokeResult", + "value": { "reveal": { "locations": [ { "uri": "messages.properties", "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } } } ] } }, + "expected": { "status": "rejected" } + } + ] +} diff --git a/shared/contracts/plugins/v1/fixtures/editor/editor-providers.json b/shared/contracts/plugins/v1/fixtures/editor/editor-providers.json new file mode 100644 index 0000000000..671aaea004 --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/editor/editor-providers.json @@ -0,0 +1,132 @@ +{ + "schemaVersion": 1, + "description": "lithe/host/editor/registerProviders validation. `host.providerTypes` is what the host declared in getCapabilities (`services.editor.options.providerTypes`). Registration cases carry the method params without `context`; result cases carry one provider function's LSP 3.17 shaped result and the normalized value the host merges after the language server's own answer. Positions are zero-based LSP positions. A rejected registration names the host failure code; a rejected result is dropped whole.", + "host": { + "providerTypes": ["definition", "hover", "completion", "codeLens", "foldingRange", "semanticTokens", "documentLink"] + }, + "registrations": [ + { + "name": "resource keys navigate from templates to message bundles", + "params": { + "id": "message-keys", + "selector": { "languages": ["html"], "fileExtensions": [".Properties"], "fileNames": ["Messages"] }, + "providers": { + "definition": { "function": "keys.definition" }, + "hover": { "function": "keys.hover" }, + "completion": { "function": "keys.complete", "triggerCharacters": ["."] }, + "codeLens": { "function": "keys.usages" }, + "semanticTokens": { "function": "keys.tokens", "legend": { "tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"] } } + } + }, + "expected": { + "status": "accepted", + "registration": { + "id": "message-keys", + "selector": { "languages": ["html"], "fileExtensions": ["properties"], "fileNames": ["messages"] }, + "providers": { + "codeLens": { "function": "keys.usages", "budgetMs": 2000 }, + "completion": { "function": "keys.complete", "triggerCharacters": ["."], "budgetMs": 400 }, + "definition": { "function": "keys.definition", "budgetMs": 1500 }, + "hover": { "function": "keys.hover", "budgetMs": 400 }, + "semanticTokens": { "function": "keys.tokens", "legend": { "tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"] }, "budgetMs": 2000 } + } + } + } + }, + { + "name": "a provider type the host does not route", + "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "signatureHelp": { "function": "keys.signature" } } }, + "expected": { "status": "rejected", "code": "plugin.host.unsupportedOption", "details": { "option": "providers.signatureHelp" } } + }, + { + "name": "diagnostics are not a provider", + "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "diagnostics": { "function": "keys.check" } } }, + "expected": { "status": "rejected", "code": "plugin.host.unsupportedOption", "details": { "option": "providers.diagnostics" } } + }, + { + "name": "a selector names at least one language, extension or file", + "params": { "id": "message-keys", "selector": {}, "providers": { "hover": { "function": "keys.hover" } } }, + "expected": { "status": "rejected", "code": "plugin.host.invalidParams" } + }, + { + "name": "semantic tokens declare their legend", + "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "semanticTokens": { "function": "keys.tokens" } } }, + "expected": { "status": "rejected", "code": "plugin.host.invalidParams" } + }, + { + "name": "budgets are the host's", + "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "hover": { "function": "keys.hover", "budgetMs": 5000 } } }, + "expected": { "status": "rejected", "code": "plugin.host.invalidParams" } + } + ], + "results": [ + { + "name": "a definition link becomes its target selection", + "type": "definition", + "value": [ { "targetUri": "file:///workspace/messages.properties", "targetRange": { "start": { "line": 3, "character": 0 }, "end": { "line": 3, "character": 30 } }, "targetSelectionRange": { "start": { "line": 3, "character": 0 }, "end": { "line": 3, "character": 9 } } } ], + "expected": { "status": "accepted", "value": { "locations": [ { "uri": "file:///workspace/messages.properties", "range": { "start": { "line": 3, "character": 0 }, "end": { "line": 3, "character": 9 } } } ] } } + }, + { + "name": "no definition", + "type": "definition", + "value": null, + "expected": { "status": "accepted", "value": { "locations": [] } } + }, + { + "name": "a hover with a code block", + "type": "hover", + "value": { "contents": [ { "language": "properties", "value": "app.title=Lithe" }, "Defined in messages.properties" ], "range": { "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 16 } } }, + "expected": { "status": "accepted", "value": { "contents": [ { "kind": "markdown", "value": "```properties\napp.title=Lithe\n```" }, { "kind": "markdown", "value": "Defined in messages.properties" } ], "range": { "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 16 } } } } + }, + { + "name": "completion keeps presentation and edits only", + "type": "completion", + "value": { "isIncomplete": false, "items": [ { "label": "app.title", "kind": 10, "detail": "Lithe", "data": { "cursor": 1 }, "command": { "title": "Resolve", "command": "keys.resolve" } } ] }, + "expected": { "status": "accepted", "value": { "isIncomplete": false, "items": [ { "label": "app.title", "kind": 10, "detail": "Lithe" } ] } } + }, + { + "name": "a code lens calls a function of its plugin", + "type": "codeLens", + "value": [ { "range": { "start": { "line": 3, "character": 0 }, "end": { "line": 3, "character": 9 } }, "command": { "title": "2 usages", "command": "keys.usages.reveal", "arguments": [ { "key": "app.title" } ] } } ], + "expected": { "status": "accepted", "value": { "lenses": [ { "range": { "start": { "line": 3, "character": 0 }, "end": { "line": 3, "character": 9 } }, "command": { "title": "2 usages", "command": "keys.usages.reveal", "arguments": [ { "key": "app.title" } ] } } ] } } + }, + { + "name": "a code lens without a command", + "type": "codeLens", + "value": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } } } ], + "expected": { "status": "rejected" } + }, + { + "name": "folding ranges keep their kind", + "type": "foldingRange", + "value": [ { "startLine": 0, "endLine": 4, "kind": "region", "collapsedText": "..." } ], + "expected": { "status": "accepted", "value": { "ranges": [ { "startLine": 0, "endLine": 4, "kind": "region" } ] } } + }, + { + "name": "semantic tokens index the registered legend", + "type": "semanticTokens", + "legend": { "tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"] }, + "value": { "resultId": "1", "data": [0, 0, 9, 0, 1, 0, 10, 5, 1, 0] }, + "expected": { "status": "accepted", "value": { "data": [0, 0, 9, 0, 1, 0, 10, 5, 1, 0] } } + }, + { + "name": "a semantic token type outside the legend", + "type": "semanticTokens", + "legend": { "tokenTypes": ["property"], "tokenModifiers": [] }, + "value": { "data": [0, 0, 9, 1, 0] }, + "expected": { "status": "rejected" } + }, + { + "name": "a document link needs an absolute target", + "type": "documentLink", + "value": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 4 } }, "target": "messages.properties" } ], + "expected": { "status": "rejected" } + }, + { + "name": "a document link to a bundle", + "type": "documentLink", + "value": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 4 } }, "target": "file:///workspace/messages.properties", "tooltip": "Open bundle" } ], + "expected": { "status": "accepted", "value": { "links": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 4 } }, "target": "file:///workspace/messages.properties", "tooltip": "Open bundle" } ] } } + } + ] +} diff --git a/shared/contracts/plugins/v1/fixtures/editor/editor-providers.plugin.json b/shared/contracts/plugins/v1/fixtures/editor/editor-providers.plugin.json new file mode 100644 index 0000000000..0a3dd906bb --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/editor/editor-providers.plugin.json @@ -0,0 +1,36 @@ +{ + "schemaVersion": 2, + "id": "dev.lithe.fixture.editorproviders", + "displayName": "Editor Providers", + "version": "1.0.0", + "pluginAPIVersion": 3, + "requires": { + "backend": 2, + "serverProcess": 1 + }, + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "backend.launch", + "documents.read", + "editor.providers", + "workspace.metadata" + ], + "activationEvents": [ + "onWorkspaceOpen" + ], + "languages": [], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/backend" + }, + "arguments": [ + "--state", + "${stateDir}" + ] + } +} diff --git a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json index 65ce2362f5..ea6647ec3f 100644 --- a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json @@ -1055,6 +1055,7 @@ {"name": "a grammar names a known engine", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/grammar/kind", "value": "textmate"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a grammar file stays in the package", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/grammar/path", "value": "../http.monarch.json"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a comment delimiter is one short line", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/configuration/lineComment", "value": "#\n"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "editor providers read the documents they answer for", "base": "editor-providers.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["backend.launch", "editor.providers", "workspace.metadata"]}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a tool field needs projectGenerators 2", "base": "project-generator.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/1", "value": {"id": "sdk", "type": "tool", "title": "SDK", "tool": "python"}}], "expectedCode": "plugin.manifest.invalid"}, {"name": "projectGenerators 2 has no runtime field", "base": "project-generator.plugin.json", "edits": [{"op": "set", "path": "/requires/projectGenerators", "value": 2}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a tool field names a tool definition ID", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/0/tool", "value": "Python Interpreter"}], "expectedCode": "plugin.manifest.invalid"}, diff --git a/shared/contracts/plugins/v1/plugin-manifest.schema.json b/shared/contracts/plugins/v1/plugin-manifest.schema.json index 3122ad9262..dfb7ef9292 100644 --- a/shared/contracts/plugins/v1/plugin-manifest.schema.json +++ b/shared/contracts/plugins/v1/plugin-manifest.schema.json @@ -79,6 +79,7 @@ "documents.read", "editor.edit", "editor.actions", + "editor.providers", "editor.open", "preview.open", "toolchains.provide", diff --git a/shared/contracts/rust-core-api.md b/shared/contracts/rust-core-api.md index 869f006d6d..f199c5a805 100644 --- a/shared/contracts/rust-core-api.md +++ b/shared/contracts/rust-core-api.md @@ -1376,7 +1376,8 @@ package manager owns the download and Lithe does not infer bytes from logs. | `toolchains.discoveryPlan` | Return platform-filtered definition-owned scan declarations, layouts, probes, PATH entries, login-shell home variables and budgets; never scans native directories | | `toolchains.candidates` | List one tool's login-shell homes and host-scanned installations with checked executables, versions or skip reasons, and the automatic-layer choice; never starts a probe | | `plugins.declarative.decodeGrammar` | Validate independent static editor resources (`languages` 2) | -| `plugins.editorActions.decode` | Validate independent action registration or collection results | +| `plugins.editorActions.decode` | Validate independent action registration, collection or click results | +| `plugins.editorProviders.decode` | Validate editor provider registrations and provider function results | | `build.detect` | Find every build-system instance the enabled plugins declare in a workspace, with models that need no process | | `build.resolveStoredOptions` | `{ document, local: { version: 1, document, emptySelections?: { : { : [optionID] } } } }`, without a manifest | `storage: { document, local, emptySelections }`: checked team/local merge; local values override matching keys, unrelated systems/roots/choices stay intact. No filesystem I/O. Local documents are machine/workspace preferences, not team files or plugin-native configuration. Their storage syntax is [build-local-options-v1.schema.json](build-local-options-v1.schema.json), with additional cross-field membership and byte limits checked by Core. | | `build.editStoredOption` | `{ document, local, root, optionID, value, modelValues? }` in the standard manifest/build-system envelope | `edit: { local, options }`: changes one declared local preference. `null` removes the local override and restores team/declaration inheritance. Invalid or partially accepted edits reject before persistence. Workspace multi-selections preserve sibling-only values; explicit per-root empty markers apply only to workspace multi-select declarations. Platforms compare both native source revisions, atomically write only the local document and read back. | @@ -3060,7 +3061,11 @@ directory, initialization options, optional runtime executable, optional `pluginId` of the plugin that owns the process, its optional `workspaceConfiguration` (an object, plugin-owned sessions only), its optional `hostServices` (the launch plan's `backend.hostServices`; -plugin-owned sessions only; legacy service grants or full public host-method names Core defines), plus +plugin-owned sessions only; legacy service grants or full public host-method names Core defines), +its optional `hostOptions` (plugin-owned sessions only; `editor:{actionIcons, +actionSourceBytes, providerTypes}` declares the icons, collector source bound and +provider types the host implements, reported through `lithe/host/getCapabilities` +to sessions granted the matching editor methods), plus initialize, post-initialize readiness, request, Java project build (`javaBuildTimeoutMilliseconds`), and shutdown deadlines. Java callers may also provide the versioned `mavenContext` accepted by @@ -4892,9 +4897,30 @@ languages return `grammar:null` and require no file read. Core reads no files. `plugins.editorActions.decode` accepts `{kind:"registration",value}` or `{kind:"actions",value,text}` and returns `{registration}` or `{actions}`. Core validates literal selectors, one-based UTF-16 ranges and bounded opaque -function bindings. Hosts enforce permission, live document versions and session -ownership; HTTP/SQL business semantics stay with plugins. See the plugin -contract's independent editor actions section. +function bindings. Version 1 (the default) admits the icons `run` and +`run-all` and a 128 KiB source. `version: 2` with the host's `icons` and +`sourceBytes` also admits `alternatives` and `{kind:"invokeResult",value}`, +which returns `{}` or `{reveal:{locations}}` for a clicked action. Hosts enforce +permission, live document versions and session ownership; HTTP/SQL business +semantics stay with plugins. See the plugin contract's independent editor +actions section. + +`plugins.editorProviders.decode` accepts `{kind:"registration",value,types}` +(the provider types the host routes) and returns `{registration}` with +lowercased literal selectors and Core's per-type `budgetMs`; a type outside +`types` is `not_supported` with details `providers.`. It also accepts +`{kind:"result",type,value,legend?}` (one provider function's LSP 3.17 shaped +result; semantic tokens need the registered legend) and returns `{result}` +normalized to `{locations}`, `{contents,range?}`, `{isIncomplete,items}`, +`{lenses}`, `{ranges}`, `{data}` or `{links}`. Hosts own calls, budgets, +stale-version drops and the merge after language-server answers; see the +plugin contract's editor language-feature providers section. The definition +merge is Core's too: `{kind:"mergeDefinitions",value:{documentUri,position,server,plugin}}` +takes the language server's and the plugins' validated `Location[]` and returns +the indices each side keeps as `{server,plugin}`. The server's answer comes +first; a plugin location equal to one already kept is dropped, and a server +location that covers the requested position itself (the caret already sits on +the declaration) yields when a plugin answered. The `plugins.marketplace.*` commands are equally pure: hosts fetch indexes and diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 2d62b92f02..c405169dbf 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -9758,6 +9758,7 @@ "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx35941b6a99": "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/`, `/*` or `/**` to hide a folder and everything in it; start with `**/` to match at any depth. A pattern without a trailing slash only hides files: `.lithe` hides a file named .lithe, not the folder.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/**` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe list starts with the built-in patterns. Delete one to show those files again; type it back to hide them.", "history.clearFailed": "Could not clear this project's local history. Check storage permissions and try again.", "native.addClickableActionsBesideDocumentText": "Add clickable actions beside document text", + "native.addEditorProvidersForMatchingFiles": "Add definitions, hovers, completions and other editor features for matching files", "native.lspStatusLabel": "LSP", "native.restartServer": "Restart Server", "native.stopServer": "Stop Server", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index d6a40d02c5..ab1e0ef9ec 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -9758,6 +9758,7 @@ "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx35941b6a99": "每行一条规则,不区分大小写。规则使用通配符,是正则表达式的简化写法:`*` 匹配任意字符,`?` 匹配单个字符。\n以 `/`、`/*` 或 `/**` 结尾表示隐藏整个文件夹及其内容,以 `**/` 开头表示匹配任意层级。不带结尾斜杠的规则只隐藏文件:`.lithe` 隐藏名为 .lithe 的文件,而不是文件夹。\n示例:\n`**/dist/` — 任意层级的 dist 文件夹\n`.lithe/**` — 项目根目录下的 .lithe 文件夹\n`*.log` — 所有 .log 文件\n`docs/*.md` — docs 下的 Markdown 文件\n列表开头是内置规则。删掉一行即可重新显示这些文件,再输入回来就会重新隐藏。", "history.clearFailed": "无法清空此项目的本地历史。请检查存储目录权限后重试。", "native.addClickableActionsBesideDocumentText": "在文档文本旁添加可点击的操作", + "native.addEditorProvidersForMatchingFiles": "为匹配的文件添加定义跳转、悬停提示、补全等编辑器功能", "native.lspStatusLabel": "LSP", "native.restartServer": "重启服务器", "native.stopServer": "停止服务器", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index ed65c9bde1..cfbebc6122 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -93537,6 +93537,17 @@ "arguments": [] } }, + { + "id": "native.addEditorProvidersForMatchingFiles", + "description": "Native UI: editor provider contribution permission", + "platforms": [ + "macos" + ], + "macos": { + "key": "Add definitions, hovers, completions and other editor features for matching files", + "arguments": [] + } + }, { "id": "native.lspStatusLabel", "description": "Native LSP status and log viewer", diff --git a/shared/logging/events/plugins.json b/shared/logging/events/plugins.json index c052e406d9..d8647dfe5f 100644 --- a/shared/logging/events/plugins.json +++ b/shared/logging/events/plugins.json @@ -77,6 +77,26 @@ "rate": 60, "owner": "Lithe" }, + { + "id": "plugins.editor.provider_failed", + "channel": "plugins/{plugin}/host", + "level": "warn", + "message": "Plugin {plugin} editor provider failed", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin id whose editor language-feature provider function failed or answered invalidly" + }, + "error": { + "type": "error", + "required": true, + "description": "Error returned while calling the provider function or validating its result" + } + }, + "rate": 60, + "owner": "Lithe" + }, { "id": "plugins.editor.refresh_failed", "channel": "plugins", diff --git a/shared/platform-feature-matrix/features/plugin-editor-actions.json b/shared/platform-feature-matrix/features/plugin-editor-actions.json index d24951cba7..12f7b28da3 100644 --- a/shared/platform-feature-matrix/features/plugin-editor-actions.json +++ b/shared/platform-feature-matrix/features/plugin-editor-actions.json @@ -2,15 +2,19 @@ "id": "plugin-editor-actions", "area": "扩展", "group": "插件与主题", - "capability": "普通工具插件的独立编辑器动作:运行期注册文件选择器,收集文档范围与同插件函数绑定,点击复用普通 invocation;不接 LSP/Build/Run/Debug", + "capability": "普通工具插件的独立编辑器动作:运行期注册文件选择器,收集文档范围与同插件函数绑定,点击复用普通 invocation;版本 2 支持行首多图标(运行/调试/测试状态/导航)、同一标记的备选项和点击后展示位置;不接 LSP/Build/Run/Debug", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", "evidence": [ "rust/lithe-core/src/plugins/editor_actions.rs", "macos/Sources/Lithe/Application/Features/PluginEditorActionHostService.swift", + "macos/Sources/Lithe/Platform/MacOS/Plugins/PluginEditorHostOptions+macOS.swift", "frontend/editor/src/plugin-editor-actions.ts", - "shared/contracts/plugins/v1/fixtures/editor/editor-actions.plugin.json" + "frontend/editor/src/plugin-editor-action-rules.ts", + "macos/Tests/LitheTests/PluginEditorActionTests.swift", + "shared/contracts/plugins/v1/fixtures/editor/editor-actions.plugin.json", + "shared/contracts/plugins/v1/fixtures/editor/editor-actions-v2.json" ] }, "windows": { @@ -21,6 +25,6 @@ ] }, "owner": "Extensions", - "verification": "用 HTTP 与 SQL 两种解析函数注册动作;验证当前脏文档版本、同一行多动作、明确点击执行、编辑取消旧解析、撤回/关闭/会话替换清理,不自动重试副作用。慢收集保持未完成时刷新立即确认,仍能输入并完成保存屏障;整批只使用八秒预算。", + "verification": "用 HTTP 与 SQL 两种解析函数注册动作;验证当前脏文档版本、同一行多动作、明确点击执行、编辑取消旧解析、撤回/关闭/会话替换清理,不自动重试副作用。慢收集保持未完成时刷新立即确认,仍能输入并完成保存屏障;整批只使用八秒预算。版本 2:同一行运行车道与导航车道各自排列且折叠箭头随之让位;备选项各自调用自己的函数;点击后返回的 reveal 位置由宿主展示,插件自己的返回成员不被解释;宿主图标表之外的图标名被 Core 拒绝,且与网页图标键一致。", "notes": "当前仅 macOS 接线;真机和完整用户流程仍待验证。共享校验通过不代表 Windows 已实现。" } diff --git a/shared/platform-feature-matrix/features/plugin-editor-grammars.json b/shared/platform-feature-matrix/features/plugin-editor-grammars.json index 389940b2c3..90bb261197 100644 --- a/shared/platform-feature-matrix/features/plugin-editor-grammars.json +++ b/shared/platform-feature-matrix/features/plugin-editor-grammars.json @@ -23,5 +23,5 @@ }, "owner": "Extensions", "verification": "安装纯语法插件后打开 .http;验证即时出现、停用撤回、配置独立应用、病态语法不阻塞输入和保存;安装目录哈希不变。语法源文本经 Core/Swift/worker 往返保持 cases 顺序并显式默认 root;properties 等仅配置别名保留高亮、撤回不销毁基础 tokenizer;模块状态观察回调不持有运行时。", - "notes": "当前仅 macOS 接线,只接受清单与包内 JSON 静态资源,grammar.kind 仅支持 monarch;没有运行期传 JSON 注册/替换/释放高亮 Provider 的公共方法,也未开放独立语言语义 Provider 的普通函数绑定。静态插件生命周期即时更新不等于动态注册 API。高亮超过 128 Ki UTF-16 单位或 10,000 行时保持普通文本,嵌入语言按普通文本处理;SDK 新能力封装/发布和真实插件完整安装验收仍待完成。共享校验通过不代表 Windows 已实现。" + "notes": "当前仅 macOS 接线,只接受清单与包内 JSON 静态资源,grammar.kind 仅支持 monarch;没有运行期传 JSON 注册/替换/释放高亮 Provider 的公共方法,补全、悬浮、跳转等语言功能的普通函数绑定见 plugin-editor-providers,它们补充语言服务器而不替代 grammar。静态插件生命周期即时更新不等于动态注册 API。高亮超过 128 Ki UTF-16 单位或 10,000 行时保持普通文本,嵌入语言按普通文本处理;SDK 新能力封装/发布和真实插件完整安装验收仍待完成。共享校验通过不代表 Windows 已实现。" } diff --git a/shared/platform-feature-matrix/features/plugin-editor-providers.json b/shared/platform-feature-matrix/features/plugin-editor-providers.json new file mode 100644 index 0000000000..f31c78fdbc --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-editor-providers.json @@ -0,0 +1,31 @@ +{ + "id": "plugin-editor-providers", + "area": "扩展", + "group": "插件与主题", + "capability": "普通工具插件的编辑器语言功能:运行期把跳转、悬浮、补全、CodeLens、折叠、语义着色、文档链接绑定到同插件函数;语言服务器先答,插件只补充;不接 LSP/Build/Run/Debug", + "macos": { + "implementationStatus": "partial", + "verificationStatus": "pending", + "evidence": [ + "rust/lithe-core/src/plugins/editor_providers.rs", + "macos/Sources/Lithe/Application/Features/PluginEditorProviderHostService.swift", + "macos/Sources/Lithe/Models/AppModel/AppModel+PluginDefinitions.swift", + "macos/Sources/Lithe/Platform/MacOS/MonacoPluginEditorProviders.swift", + "frontend/editor/src/plugin-editor-providers.ts", + "frontend/editor/src/plugin-editor-provider-rules.ts", + "macos/Tests/LitheTests/PluginEditorProviderTests.swift", + "shared/contracts/plugins/v1/fixtures/editor/editor-providers.json", + "shared/contracts/plugins/v1/fixtures/editor/editor-providers.plugin.json" + ] + }, + "windows": { + "implementationStatus": "missing", + "verificationStatus": "not-applicable", + "evidence": [ + "shared/contracts/plugins/v1/README.md" + ] + }, + "owner": "Extensions", + "verification": "用一个资源 key 在模板与 .properties 之间跳转的第二工具插件注册 definition、hover、completion、codeLens、semanticTokens;验证语言服务器的答案先出现、插件的位置只追加、重复位置只显示一次、服务器只指回自身时让位;悬浮和补全超过期限、文档已变化、注册被撤回时安静丢弃;触发字符只问声明过它的注册;点击 CodeLens 与文档链接只回传宿主生成的键,command: 链接不会被执行,工作区外的 file: 目标不会打开;只读预览不询问插件;停用、卸载、关闭项目后旧结果不再出现。", + "notes": "当前仅 macOS 接线,真机和完整用户流程仍待验证。需要 editor.providers 权限,每个插件最多 32 个注册;诊断(API-26)、符号、格式化、重命名、Code Action、签名帮助、内联提示未做,对应类型返回 unsupportedOption。共享校验通过不代表 Windows 已实现。" +}