diff --git a/.agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md b/.agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md new file mode 100644 index 0000000000..af6e124a8a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md @@ -0,0 +1,122 @@ +# Agent 笔记:插件自有语言服务器会话与后端决定启动方式 + +状态:已实现 + +## 先说结论 + +语言插件现在可以拥有自己的语言服务器:插件后端在每次启动时告诉 Lithe 用哪个程序、带什么参数,之后由后端通过三个宿主方法(`lithe/host/languageServer/request|notify|setStatus`)向这个服务器发请求、发通知并上报“准备到哪一步了”。请求能不能发、要不要排队、等多久、远程能不能用,全部由 Rust Core 按插件声明的会话策略(session policy,插件写在清单里的规则)裁决;Swift 只负责把请求送进去、把进程启动起来、把状态显示出来。 + +这是为了让 Java 这类语言的特殊逻辑能整体搬进插件仓库,宿主不再按语言名写分支。本篇只建立基础设施,不删除任何旧的 JDT 路径,Windows 仍走旧路径。开发者以后新增“某语言服务器需要特殊启动或准备”的需求时,应该先扩展这条通用通道,而不是在宿主里认出语言名。 + +## 问题 + +旧做法里,宿主为 Java 内置了一整套东西:用 `hostIntegration: jdt` 选启动方式,Java 专属的工作区状态目录与清理,Java 项目准备状态条,以及判断 Maven/Gradle 命令来串行请求。这些逻辑只对一种语言成立,却写在通用的会话管理里,插件无法复制,也无法在不改宿主的前提下换语言。 + +要让它们变成插件自己的东西,缺三样公共能力:插件后端没有办法在每次启动时决定怎么启动服务器;没有办法向自己的服务器发请求并受宿主管控;没有办法在准备期间(导入构建、建索引,往往比任何一次调用都长)向用户汇报进度。 + +## 决策 + +### 后端经三个宿主方法使用服务器,规则由 Core 执行 + +- 后端发 `lithe/host/languageServer/request`(带请求方法、参数、可选超时)得到 `{value}`,发 `notify` 得到 `{delivered}`,发 `setStatus` 得到 `{}`。清单权限 `languageServer.request` 展开成这三个具体方法的授权;未授权的方法返回 `plugin.host.permissionDenied`,不认识的参数返回 `plugin.host.unsupportedOption`。 +- 一个服务器的 ID 就是它的语言 ID。后端只能操作自己插件声明的服务器;操作别人的服务器得到“不是你的贡献”。 +- Core 在会话里执行策略:请求方法白名单、门控(gates,服务器没准备好时拒绝请求)、串行命令(同一类命令一次只跑一个,后来者合并等待)、超时(默认 60000 毫秒,最长 300000)、排队上限(128 个,之后返回 `busy`),以及 `remote: "unsupported"` 的远程拒绝。Swift 不复制这些规则,也不认识任何语言的方法名。 +- 新增四个错误码,一码一义:`-32022` 服务器不可用、`-32023` 服务器自己报错(原始错误放 `details`)、`-32024` 方法未在清单声明、`-32026` 不是你的贡献。超时、取消、`busy`、超限、前置条件失败复用已有码。`-32025` 属于运行调试 API,`-32027` 到 `-32030` 属于另一个 PR,本篇不使用。Swift 侧对应 `plugin.host.languageServerUnavailable|languageServerError|methodNotDeclared|foreignContribution`;宿主不认识的码到后端时变成 `plugin.host.failed`。 +- 版本:`languageServers` 升到 3(会话字段),`serverProcess` 升到 3(`launch.kind:"backend"`),`pluginAPIVersion` 保持 4。 + +### 会话代际(generation)和中继 + +服务器每次启动是一代。`PluginLanguageServerRelay` 为每个服务器记住当前活着的那一代,把状态变化(`starting`、`running`、`stopped`、`crashed`)和服务器转发的通知以 `lithe/host/languageServer/didChangeState` 与 `didReceiveNotification` 送给后端;旧一代进程晚到的消息直接丢弃,所以后端不会把已经被替换的进程的消息当成现在的。是否真的送达,仍由后端的权限授权决定。 + +### 准备状态用 `setStatus`,不复用进度 + +`lithe/function/progress` 属于一次正在运行的函数调用,调用结束它就没了。而准备(导入构建、索引)可能在任何调用之外持续很久。所以 `setStatus` 是服务器级的:状态 `preparing|ready|degraded|failed`、一段不超过 1024 UTF-8 字节的文字(按字符边界截断)和 0 到 100 的百分比。状态随该进程结束,不留到下一代;服务器不在运行时调用 `setStatus` 会得到 `languageServerUnavailable`,调用别人的服务器得到 `foreignContribution`。宿主界面(`PluginServerStatusView`)只显示插件自己写的文字,插件没写时才用宿主的中性兜底文案,经 i18n 输出,不含任何语言或工具名。 + +首版不提供 `actions`(状态上的按钮)和 `{done,total}` 进度,只有百分比。 + +### 后端决定启动方式:两步,Core 在两步里都把关 + +1. `plugins.declarative.languageServerLaunchPlan` 返回“问题”:要调用的后端函数、超时(默认 30000)、`resolveParams`(服务器 ID、平台、各个宿主目录、设置)和必须先创建的目录。宿主创建目录,调用后端函数,参数里再加上 `context`。 +2. `plugins.languageServers.decodeLaunch` 把后端的回答交给 Core 校验:可执行文件必须是包内文件(`packaged`)或清单声明过的工具(`tool`),路径不得越出插件包,可写路径必须在宿主允许的目录内,参数、环境、初始化选项有字节上限。拒绝时给出 `plugin.launch.invalidResult|outsidePackage|undeclaredTool|unwritablePath|invalidRequest|unavailable|notBackend` 之一。 + +校验放在 Core 而不是 Swift,是因为这些规则不含平台差异,Windows 将来会用同一份。宿主只做它必须做的 I/O:创建目录、调后端、按 Core 给的计划启动进程。 + +- 工具类可执行文件通过宿主已有的工具链解析(工程内代码提供的工具被拒绝,不会从项目目录里启动程序)。包内文件在启动前确认存在且可执行。 +- 每次启动的临时目录在会话结束或启动失败时回收;启动期间工作区上下文已失效则以取消结束。 +- 远程工作区:Core 对声明 `remote: "unsupported"` 的服务器拒绝;后端启动的服务器在 macOS 上目前一律拒绝远程根,避免在远端用本机路径。 +- 服务器本体随插件包签名分发,运行时不下载、不解压到应用包内,遵守发行包只读边界。 + +### 内容提供者(API-12)取代专属虚拟文档 + +语言服务器返回的 jar 内源码等虚拟文档地址,旧做法是宿主里写死的 Java 虚拟文档。现在插件后端用 `lithe/host/documents/registerContentProvider`(权限 `documents.contentProvider`)为一个 scheme 注册一个函数,宿主打开该 scheme 的地址时调用 `{context, uri}`,答案是字符串或 `{content}`,不超过 1 MiB,由 Core(`plugins.contentProviders.decode`)校验。每个窗口每个 scheme 只能有一个提供者。 + +### 工作区状态与回收(API-20) + +服务器的每个工作区状态目录在 `Application Support/Lithe/PluginState/<插件>/<语言>/workspaces/<工作区路径的 SHA-256>/`,不在包内也不在缓存里,禁用或更新插件后保留。Core 决定回收哪些:宿主把“目录名与最后使用时间”列给 `plugins.languageServers.stateRetention`,Core 按插件声明的 `state.retention`(`maxEntries`、`maxAgeDays`)返回过期名字,打开中的工作区永远不回收,不是单个路径分量的名字被忽略。Swift(`MacPluginLanguageServerWorkspaceState`)只列真实目录、删除 Core 点名且自己列过的名字,文件和符号链接不算状态,不会跟随删除。 + +“最后使用时间”只用目录自身的修改时间:服务器写的是更深层的文件,不会更新它,所以每次由后端启动服务器时宿主会刷新一次。回收在启动之后后台运行,失败只是不回收,不影响这次启动,下次启动会重新清理。插件没有声明 `retention` 就什么都不删。 + +另有 `reset`(丢弃一个工作区的状态,服务器下次启动重建)。目前它只有引擎入口 `rebuildWorkspaceState`,没有面向用户的菜单或确认界面。 + +### 旧 JDT 路径与新通道的对应 + +这些旧路径本篇全部保留,由后续 E1 移除,Windows 由 W2 迁移。 + +| 旧 JDT 专属做法 | 新通用通道 | +| --- | --- | +| Java 虚拟文档(jar 内源码) | 内容提供者(API-12) | +| `is_java_build_command` 判断串行 | 会话策略的串行命令 | +| `java_configuration_running` 拒绝请求 | 会话策略的门控 | +| Java 项目准备状态条 | `setStatus`(API-22)和通用状态视图 | +| 引擎里按名字 `java` 的远程检查 | 清单 `remote: "unsupported"` | +| `MacJdtWorkspaceState` 与 `jdtCacheRetention` | `state.retention` 与 `plugins.languageServers.stateRetention` | +| `hostIntegration: jdt` 启动 | `launch.kind:"backend"` 的后端启动 | + +## 考虑过的备选方案 + +- 继续按语言加 `hostIntegration` 值:每种有特殊准备的语言都要改宿主,违背“插件专属逻辑不进宿主”,拒绝。 +- 让后端直接连服务器的管道:绕过 Core 的白名单、门控、串行与代际检查,也让取消和超时无处执行,拒绝。 +- 复用 `lithe/function/progress` 报准备状态:它随调用结束而消失,准备过程不属于任何调用,拒绝。 +- 在 Swift 里校验后端的启动回答:规则无平台差异,Windows 会重写一份并漂移,改放 Core。 +- 回收规则放 Swift:同样会在两个平台各写一次;改为 Core 决定、平台只做目录 I/O。 +- 用清单字段 `virtualDocuments` 声明虚拟文档:声明不了“内容怎么取”,最终还要函数,所以直接做成注册内容提供者。 +- 运行时下载服务器:改写发行包基线,破坏代码签名和 Sparkle 增量更新,违反只读边界,拒绝;服务器随插件包构建期固定。 + +## 后果 + +收益:语言插件可以用同一套通道准备、启动、使用自己的服务器,宿主代码里没有语言或工具的名字;规则在 Core 一处,Windows 迁移时直接复用;插件包签名之外没有运行时写入发行目录。 + +代价与已知缺口: + +- 宿主多了一条后端到服务器的转发路径,需要保持代际和授权检查正确。 +- 远程工作区上由后端启动的服务器暂不支持;转发通知很多时可能撑满后端的 128 项队列;后端晚于服务器启动时不会补发一次 `running`。 +- 服务器关闭超时也按 `crashed` 上报;内容提供者每次导航都重新取;取消串行命令的领头请求也会取消并入的请求。 +- 宿主附带 `tools` 参数尚未发送;工程内选择的工具会使工具类启动失败而不是回退;LSP 控制中心与工具设置不显示后端启动服务器的可执行文件。 +- 没有用户可见的“重置语言服务器状态”入口;回收只在后端启动时触发,失败静默。 +- 本篇不删除任何 JDT 专属代码,旧路径与新通道会并存到 E1。 + +## 验证 + +- `cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib` 按 `plugin_server`、`plugin_function`、`language_server_sessions`、`content_providers`、`declarative` 过滤:会话策略、逐方法授权、启动问题与回答的往返、七类拒绝码、回收判定。 +- `scripts/macos/test/test-macos.sh --filter 'PluginLanguageServerHostServiceTests|PluginBackendLaunchTests|PluginContentProviderTests|MacPluginLanguageServerWorkspaceStateTests'`,以及 `LitheLanguageIntelligenceModuleTests` 中的 `PluginLanguageServerRelayTests`:参数边界、错误码映射、启动流程、代际丢弃、状态随进程结束、回收不触碰打开中的工作区和非目录项。测试用 Metals 与 rust-analyzer 的桩,不含 Java 词汇。 +- `scripts/macos/verify/verify-runtime-bundle-immutability.sh`:启动后包内文件不变。 +- `scripts/architecture/verify-shared-contracts.sh`、`scripts/architecture/verify-service-boundaries.sh`、`scripts/architecture/verify-java-semantic-ownership.mjs`。 +- `scripts/agent-notes/verify-agent-notes.sh`、`scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`。 + +原生验收(安装示例插件、观察状态栏文字、用 `pgrep` 确认进程不残留)不由单元测试替代,功能矩阵按真实证据维护。 + +## 适用范围 + +- `rust/lithe-core/src/lsp/interface/plugin_server.rs` +- `rust/lithe-core/src/lsp/interface/plugin_function.rs` +- `rust/lithe-core/src/plugins/language_server_sessions.rs` +- `rust/lithe-core/src/plugins/content_providers.rs` +- `shared/contracts/plugins/v1/README.md` +- `macos/Sources/Lithe/Application/Features/PluginLanguageServerHostService.swift` +- `macos/Sources/Lithe/Application/Features/PluginContentProviderHostService.swift` +- `macos/Sources/Lithe/Models/AppModel/AppModel+PluginLanguageServers.swift` +- `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift` +- `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerWorkspaceState.swift` +- `macos/Sources/LitheLanguageIntelligenceModule/Services/PluginLanguageServerRelay.swift` +- `macos/Sources/Lithe/Views/Workbench/PluginServerStatusView.swift` +- `docs/development/macos-plugin-api-plan.md` diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 622e0dcf93..95461bff80 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -34,7 +34,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-09 | 已公开 | documents/list/getSnapshot、editor/getActive/getSelections,含 dirty/版本/编码/EOL | | API-10 | 已公开 | applyEdits/replaceSelections/insertText;版本校验、IME/只读拒绝、一次 Undo | | API-11 | 未做 | 公共 save/saveAs/close 与工作区文件变更接口未接入 | -| API-12 | 未做 | 公共多文件 edit、content provider、showDiff 未接入;Java 拆分计划(C-LS):先交付按 URI scheme 注册的只读 content provider,承载 `jdt://` | +| API-12 | 部分完成 | 已公开 `documents/registerContentProvider`(只读内容,≤1 MiB,每窗口每 scheme 一个,仅 macOS);公共多文件 edit、showDiff 未接入 | | API-13 | 部分完成 | 既有 ui:3 原生 Tree/List/Form;通用独立后端数据源/懒加载未做 | | API-14 | 部分完成 | 既有包内网页 bridge、状态/生命周期;通用双向页面消息未做 | | API-15 | 部分完成 | editor/open/reveal 返回 documentID/version;range 只起点光标,替换预览标签未做 | @@ -42,12 +42,12 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-17 | 部分完成 | 三类窗口消息和按钮/取消;通用 QuickPick/InputBox/授权文件句柄未做 | | API-18 | 未做 | 通用剪贴板与 revealInFinder API 未开放 | | API-19 | 部分完成 | 已有声明式设置 1/2;通用 settings.get/inspect/update/events 未做;Java 拆分计划(M1、D1):Maven 插件按真实配置读取、回显、写回 settings | -| API-20 | 部分完成 | global/backend/workspace 可写目录与网页状态;统一 KV/配额/session API 未做;Java 拆分计划(C-LS):复用现有可写目录,仅新增 temporaryDirectory | +| API-20 | 部分完成 | global/backend/workspace 可写目录与网页状态;语言服务器的按工作区状态目录按 `state.retention` 后台回收(Core 决定,仅 macOS,无用户可见重置入口);统一 KV/配额/session API 未做 | | API-21 | 既有能力 | 协议 2 credentials/get/set/delete;权限与插件隔离不变 | -| API-22 | 部分完成 | 既有函数进度与取消;独立 output channel、通用 log/progress API 未做;Java 拆分计划(C-LS、C-RUN):语言服务器准备状态 setStatus、输出链接匹配器 | +| API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);独立 output channel、通用 log/progress API 未做;Java 拆分计划(C-RUN):输出链接匹配器 | | 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;新增宿主方法 `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-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增 `languageServers:3` 与 `serverProcess:3`:后端经 `languageServer/request\|notify\|setStatus` 使用自己的服务器、后端启动(`launch.kind:"backend"`),会话策略由 Core 执行(仅 macOS,远程后端启动未支持,见 Agent Note 2026-11-04-plugin-owned-language-server-sessions);新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;符号、格式化、重命名、Code Action、签名帮助、内联提示和运行期传入 JSON 动态注册高亮未做,详见下方范围说明;Java 拆分计划(C-EDIT):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/保存/撤销/恢复未开放 | diff --git a/macos/Resources/en.lproj/Localizable.strings b/macos/Resources/en.lproj/Localizable.strings index 4f94470e84..23409e4623 100644 --- a/macos/Resources/en.lproj/Localizable.strings +++ b/macos/Resources/en.lproj/Localizable.strings @@ -17,6 +17,7 @@ "%@ already exists. Choose another name or location." = "%@ already exists. Choose another name or location."; "%@ answered with status %lld. %@" = "%@ answered with status %lld. %@"; "%@ build files changed" = "%@ build files changed"; +"%@ cannot start in a remote workspace yet." = "%@ cannot start in a remote workspace yet."; "%@ could not be reached. Check your internet, proxy, or VPN connection and try again." = "%@ could not be reached. Check your internet, proxy, or VPN connection and try again."; "%@ debug adapter is unavailable." = "%@ debug adapter is unavailable."; "%@ did not answer: %@" = "%@ did not answer: %@"; @@ -46,12 +47,15 @@ "%@ keeps no workspace state that Lithe can reset." = "%@ keeps no workspace state that Lithe can reset."; "%@ language server (inside the plugin)" = "%@ language server (inside the plugin)"; "%@ language server (installed on this Mac)" = "%@ language server (installed on this Mac)"; +"%@ language server (started by the plugin)" = "%@ language server (started by the plugin)"; "%@ memory" = "%@ memory"; +"%@ needs a launch this build of Lithe cannot resolve." = "%@ needs a launch this build of Lithe cannot resolve."; "%@ now follows your local %@ configuration." = "%@ now follows your local %@ configuration."; "%@ of %@ is handled by %@." = "%@ of %@ is handled by %@."; "%@ options" = "%@ options"; "%@ provider (inside the plugin)" = "%@ provider (inside the plugin)"; "%@ provider (installed on this Mac)" = "%@ provider (installed on this Mac)"; +"%@ resolves to a program inside the project, which a language server cannot start." = "%@ resolves to a program inside the project, which a language server cannot start."; "%@ returned HTTP %@." = "%@ returned HTTP %@."; "%@ returned an invalid language-server provider." = "%@ returned an invalid language-server provider."; "%@ returned an unexpected response." = "%@ returned an unexpected response."; @@ -861,6 +865,7 @@ "Comma-separated glob patterns. Empty searches every file." = "Comma-separated glob patterns. Empty searches every file."; "Command" = "Command"; "Command Palette Actions" = "Command Palette Actions"; +"Command chosen by: %@" = "Command chosen by: %@"; "Command details" = "Command details"; "Commands an AI Agent started that are still running, for example a deployment, a database migration or a dev server. Each one is asked about separately because ending one halfway can leave data or services inconsistent. What the Agent needs for itself, such as its MCP servers, always ends with the Agent." = "Commands an AI Agent started that are still running, for example a deployment, a database migration or a dev server. Each one is asked about separately because ending one halfway can leave data or services inconsistent. What the Agent needs for itself, such as its MCP servers, always ends with the Agent."; "Comment" = "Comment"; @@ -2654,6 +2659,7 @@ "No navigation results" = "No navigation results"; "No new commits. Pushing creates the remote branch." = "No new commits. Pushing creates the remote branch."; "No notifications" = "No notifications"; +"No open window shows this workspace, so the plugin cannot choose how to start its language server." = "No open window shows this workspace, so the plugin cannot choose how to start its language server."; "No paths" = "No paths"; "No paths resolved for this service" = "No paths resolved for this service"; "No place to look yet. Open the file you want to debug, or choose the program yourself." = "No place to look yet. Open the file you want to debug, or choose the program yourself."; @@ -3027,6 +3033,7 @@ "Preflight" = "Preflight"; "Preparing conversation…" = "Preparing conversation…"; "Preparing download…" = "Preparing download…"; +"Preparing the language server" = "Preparing the language server"; "Preparing…" = "Preparing…"; "Preserves every commit and adds a merge commit to the base branch." = "Preserves every commit and adds a merge commit to the base branch."; "Press shortcut…" = "Press shortcut…"; @@ -3726,6 +3733,7 @@ "Send a message to %@" = "Send a message to %@"; "Send input to debuggee" = "Send input to debuggee"; "Send program input" = "Send program input"; +"Send requests and commands to its language server for your project" = "Send requests and commands to its language server for your project"; "Sending…" = "Sending…"; "Sensitive files are not sent to an AI provider." = "Sensitive files are not sent to an AI provider."; "Separate arguments with spaces; quote an argument that contains spaces." = "Separate arguments with spaces; quote an argument that contains spaces."; @@ -3989,6 +3997,7 @@ "Start this configuration to see its output here." = "Start this configuration to see its output here."; "Start time" = "Start time"; "Start with an action verb, without a type prefix" = "Start with an action verb, without a type prefix"; +"Started by the plugin" = "Started by the plugin"; "Started in Claude Desktop" = "Started in Claude Desktop"; "Starting" = "Starting"; "Starting Interactive Rebase" = "Starting Interactive Rebase"; @@ -4067,6 +4076,7 @@ "Suggested" = "Suggested"; "Suggested replies" = "Suggested replies"; "Supplementary message cancelled." = "Supplementary message cancelled."; +"Supply the text of read-only documents it opens in the editor" = "Supply the text of read-only documents it opens in the editor"; "Supported keyboard commands are mapped; unknown keymaps, mouse shortcuts and chords are skipped." = "Supported keyboard commands are mapped; unknown keymaps, mouse shortcuts and chords are skipped."; "Supported placeholders: {summary}, {changes}, {testing}, {risks}." = "Supported placeholders: {summary}, {changes}, {testing}, {risks}."; "Svelte Support" = "Svelte Support"; @@ -4328,7 +4338,10 @@ "The interface language changes immediately. English is the default." = "The interface language changes immediately. English is the default."; "The item can be recovered from the macOS Trash." = "The item can be recovered from the macOS Trash."; "The language server could not apply this setting. Restart it to use the new value." = "The language server could not apply this setting. Restart it to use the new value."; +"The language server could not get ready" = "The language server could not get ready"; +"The language server is not running." = "The language server is not running."; "The language server is still stopping. Try again after it has stopped." = "The language server is still stopping. Try again after it has stopped."; +"The language server runs with limited features" = "The language server runs with limited features"; "The language server this build system uses is not available. Open a file of the language and try again." = "The language server this build system uses is not available. Open a file of the language and try again."; "The language service that hosts the debug adapter is unavailable." = "The language service that hosts the debug adapter is unavailable."; "The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release." = "The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release."; @@ -4561,6 +4574,7 @@ "This configuration contains unsupported or invalid settings." = "This configuration contains unsupported or invalid settings."; "This configuration has no supported explicit editor settings to import." = "This configuration has no supported explicit editor settings to import."; "This configuration is larger than 1 MiB and is not edited by Lithe." = "This configuration is larger than 1 MiB and is not edited by Lithe."; +"This content scheme already has a provider." = "This content scheme already has a provider."; "This conversation is no longer available. Choose another conversation." = "This conversation is no longer available. Choose another conversation."; "This debug session requires an external terminal, which is not supported." = "This debug session requires an external terminal, which is not supported."; "This debug session requires shell-interpreted terminal arguments." = "This debug session requires shell-interpreted terminal arguments."; @@ -5803,6 +5817,7 @@ "native.cannotEncodeHookConfiguration" = "Cannot encode Hook configuration."; "native.cannotEncodeTheHookLibrary" = "Cannot encode the Hook library."; "native.cannotLocateTheAgentUserDirectory" = "Cannot locate the Agent user directory."; +"native.cannotStartInARemoteWorkspaceYet" = "%1$@ cannot start in a remote workspace yet."; "native.cannotUseUsingTheProjectJDKInstead" = "Cannot use %1$@; using the project JDK instead."; "native.category" = "Category"; "native.changeTheValuesStoredInTheSelectedScopeChooseInheritToRemoveAnOverride" = "Change the values stored in the selected scope. Choose Inherit to remove an override."; @@ -6062,6 +6077,7 @@ "native.commaSeparatedGlobPatternsEGJavaKt" = "Comma-separated glob patterns, e.g. *.java, *.kt"; "native.commaSeparatedGlobPatternsEmptySearchesEveryFile" = "Comma-separated glob patterns. Empty searches every file."; "native.command" = "Command"; +"native.commandChosenBy" = "Command chosen by: %1$@"; "native.commandDetails" = "Command details"; "native.commandPaletteActions" = "Command Palette Actions"; "native.commandsAnAIAgentStartedThatAreStillRunningForExampleADeploymentADatabaseMigradd876f8a4a" = "Commands an AI Agent started that are still running, for example a deployment, a database migration or a dev server. Each one is asked about separately because ending one halfway can leave data or services inconsistent. What the Agent needs for itself, such as its MCP servers, always ends with the Agent."; @@ -7322,6 +7338,7 @@ "native.languageServerReturnedOverlappingTextEdits" = "Language server returned overlapping text edits."; "native.languageServerSessionStoppedBeforeTheRequestCompleted" = "Language server session stopped before the request completed."; "native.languageServerSettingsAction" = "Language Server Settings..."; +"native.languageServerStartedByThePlugin" = "%1$@ language server (started by the plugin)"; "native.languageServerStillStopping" = "The language server is still stopping. Try again after it has stopped."; "native.languageServerToolConfigurationChanged" = "Language server tool configuration changed"; "native.languageServers" = "Language servers"; @@ -7746,6 +7763,7 @@ "native.navigateToTheNextEditorLocation" = "Navigate to the next editor location"; "native.navigateToThePreviousEditorLocation" = "Navigate to the previous editor location"; "native.navigation" = "Navigation"; +"native.needsALaunchThisBuildOfLitheCannotResolve" = "%1$@ needs a launch this build of Lithe cannot resolve."; "native.needsNoExtraPermissions" = "Needs no extra permissions."; "native.needsRestart" = "Needs restart"; "native.nestedException" = "Nested exception"; @@ -7887,6 +7905,7 @@ "native.noNavigationResults" = "No navigation results"; "native.noNewCommitsPushingCreatesTheRemoteBranch" = "No new commits. Pushing creates the remote branch."; "native.noNotifications" = "No notifications"; +"native.noOpenWindowShowsThisWorkspaceSoThePluginCannotChooseHowToStartItsLanguageServer" = "No open window shows this workspace, so the plugin cannot choose how to start its language server."; "native.noPaths" = "No paths"; "native.noPathsResolvedForThisService" = "No paths resolved for this service"; "native.noPlaceToLookYetOpenTheFileYouWantToDebugOrChooseTheProgramYourself" = "No place to look yet. Open the file you want to debug, or choose the program yourself."; @@ -8220,6 +8239,7 @@ "native.preparing" = "Preparing…"; "native.preparingConversation" = "Preparing conversation…"; "native.preparingDownload" = "Preparing download…"; +"native.preparingTheLanguageServer" = "Preparing the language server"; "native.preservesEveryCommitAndAddsAMergeCommitToTheBaseBranch" = "Preserves every commit and adds a merge commit to the base branch."; "native.pressShortcut" = "Press shortcut…"; "native.previewBackgroundImage" = "Preview background image"; @@ -8584,6 +8604,7 @@ "native.resizeDialog" = "Resize dialog, %1$@"; "native.resolveLldConflictedFileSStageTheResultThenContinue" = "Resolve %1$lld conflicted file(s), stage the result, then continue."; "native.resolveLldConflictedFileSStageThemThenContinue" = "Resolve %1$lld conflicted file(s), stage them, then continue."; +"native.resolvesToAProgramInsideTheProjectWhichALanguageServerCannotStart" = "%1$@ resolves to a program inside the project, which a language server cannot start."; "native.resolvingDependencies" = "Resolving dependencies..."; "native.resolvingPushDestination" = "Resolving push destination…"; "native.resolvingServicePaths" = "Resolving service paths..."; @@ -8859,6 +8880,7 @@ "native.sendAMessageTo" = "Send a message to %1$@"; "native.sendInputToDebuggee" = "Send input to debuggee"; "native.sendProgramInput" = "Send program input"; +"native.sendRequestsAndCommandsToItsLanguageServerForYourProject" = "Send requests and commands to its language server for your project"; "native.sending" = "Sending…"; "native.sensitiveFilesAreNotSentToAnAIProvider" = "Sensitive files are not sent to an AI provider."; "native.separateArgumentsWithSpacesQuoteAnArgumentThatContainsSpaces" = "Separate arguments with spaces; quote an argument that contains spaces."; @@ -9089,6 +9111,7 @@ "native.startThisConfigurationToSeeItsOutputHere" = "Start this configuration to see its output here."; "native.startWithAnActionVerbWithoutATypePrefix" = "Start with an action verb, without a type prefix"; "native.startedATaskThatIsStillRunning" = "%1$@ started a task that is still running"; +"native.startedByThePlugin" = "Started by the plugin"; "native.startedInClaudeDesktop" = "Started in Claude Desktop"; "native.starting" = "Starting"; "native.startingCommitOptional" = "Starting commit (optional)"; @@ -9160,6 +9183,7 @@ "native.suggested" = "Suggested"; "native.suggestedReplies" = "Suggested replies"; "native.supplementaryMessageCancelled" = "Supplementary message cancelled."; +"native.supplyTheTextOfReadOnlyDocumentsItOpensInTheEditor" = "Supply the text of read-only documents it opens in the editor"; "native.supportedPlaceholdersSummaryChangesTestingRisks" = "Supported placeholders: {summary}, {changes}, {testing}, {risks}."; "native.svelteSupport" = "Svelte Support"; "native.svgViewMode" = "SVG view mode"; @@ -9362,9 +9386,12 @@ "native.theJavaTestResultListenerDidNotBecome" = "The Java test result listener did not become ready in time."; "native.theLanguageProviderIsNotInstalled" = "The %1$@ language provider is not installed."; "native.theLanguageServerCouldNotApplyThisSetting" = "The language server could not apply this setting. Restart it to use the new value."; +"native.theLanguageServerCouldNotGetReady" = "The language server could not get ready"; "native.theLanguageServerIsDisabledInThisWorkspace" = "The %1$@ language server is disabled in this workspace. Enable it in Settings > LSP."; +"native.theLanguageServerIsNotRunning" = "The language server is not running."; "native.theLanguageServerOfThisPluginIsNotAvailable" = "The %1$@ language server of this plugin is not available."; "native.theLanguageServerReturnedAnInvalidTcpPortForItsDebugAdapter" = "The %1$@ language server returned an invalid TCP port for its debug adapter."; +"native.theLanguageServerRunsWithLimitedFeatures" = "The language server runs with limited features"; "native.theLanguageServerThisBuildSystemUsesIsNotAvailable" = "The language server this build system uses is not available. Open a file of the language and try again."; "native.theLanguageServiceThatHostsTheDebugAdapterIsUnavailable" = "The language service that hosts the debug adapter is unavailable."; "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisAutoBuildAfterYouConbfd63f6a8e" = "The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release."; @@ -9556,6 +9583,7 @@ "native.thisComputer" = "This computer"; "native.thisComputerThisProject" = "This computer · This project"; "native.thisConfigurationIsLargerThan1MibAnd" = "This configuration is larger than 1 MiB and is not edited by Lithe."; +"native.thisContentSchemeAlreadyHasAProvider" = "This content scheme already has a provider."; "native.thisConversationIsNoLongerAvailableChooseAnotherConversation" = "This conversation is no longer available. Choose another conversation."; "native.thisDebugSessionRequiresAnExternalTerminalWhich" = "This debug session requires an external terminal, which is not supported."; "native.thisDebugSessionRequiresShellInterpretedTerminalArguments" = "This debug session requires shell-interpreted terminal arguments."; diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 48de02c69c..9418c24136 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -17,6 +17,7 @@ "%@ already exists. Choose another name or location." = "%@ 已存在,请更换名称或位置。"; "%@ answered with status %lld. %@" = "%1$@ 返回状态 %2$lld。%3$@"; "%@ build files changed" = "%@ 构建文件已更改"; +"%@ cannot start in a remote workspace yet." = "%@ 暂时还不能在远程工作区中启动。"; "%@ could not be reached. Check your internet, proxy, or VPN connection and try again." = "无法连接 %@。请检查网络、代理或 VPN 后重试。"; "%@ debug adapter is unavailable." = "%@ 调试适配器不可用。"; "%@ did not answer: %@" = "%@ 未回答:%@"; @@ -46,12 +47,15 @@ "%@ keeps no workspace state that Lithe can reset." = "%@ 没有 Lithe 可以重置的工作区状态。"; "%@ language server (inside the plugin)" = "%@ 语言服务器(插件内置)"; "%@ language server (installed on this Mac)" = "%@ 语言服务器(本机已安装)"; +"%@ language server (started by the plugin)" = "%@ 语言服务器(由插件启动)"; "%@ memory" = "%@ 内存"; +"%@ needs a launch this build of Lithe cannot resolve." = "%@ 需要一种当前版本的 Lithe 还无法解析的启动方式。"; "%@ now follows your local %@ configuration." = "%@ 现在跟随你本机的 %@ 配置。"; "%@ of %@ is handled by %@." = "%2$@ 的 %1$@ 由 %3$@ 处理。"; "%@ options" = "%@ 选项"; "%@ provider (inside the plugin)" = "%@ Provider(插件内置)"; "%@ provider (installed on this Mac)" = "%@ Provider(使用本机已安装的程序)"; +"%@ resolves to a program inside the project, which a language server cannot start." = "%@ 解析到了项目内的程序,语言服务器不能用它启动。"; "%@ returned HTTP %@." = "%@ 返回了 HTTP %@。"; "%@ returned an invalid language-server provider." = "%@ 返回了无效的语言服务器 Provider。"; "%@ returned an unexpected response." = "%@ 返回了无法识别的响应。"; @@ -861,6 +865,7 @@ "Comma-separated glob patterns. Empty searches every file." = "以逗号分隔的 glob 模式。留空则搜索所有文件。"; "Command" = "命令"; "Command Palette Actions" = "命令面板入口"; +"Command chosen by: %@" = "命令由 %@ 决定"; "Command details" = "命令详情"; "Commands an AI Agent started that are still running, for example a deployment, a database migration or a dev server. Each one is asked about separately because ending one halfway can leave data or services inconsistent. What the Agent needs for itself, such as its MCP servers, always ends with the Agent." = "AI Agent 启动后仍在运行的命令,例如部署、数据库迁移或开发服务器。由于中途结束可能导致数据或服务不一致,每个任务都会单独确认。Agent 自身需要的进程(例如它的 MCP 服务)总是随 Agent 一起结束。"; "Comment" = "评论"; @@ -2654,6 +2659,7 @@ "No navigation results" = "没有导航结果"; "No new commits. Pushing creates the remote branch." = "没有新的提交。推送会创建远程分支。"; "No notifications" = "暂无通知"; +"No open window shows this workspace, so the plugin cannot choose how to start its language server." = "没有已打开的窗口显示这个工作区,插件无法决定如何启动它的语言服务器。"; "No paths" = "没有路径"; "No paths resolved for this service" = "此服务没有已解析的路径"; "No place to look yet. Open the file you want to debug, or choose the program yourself." = "还没有可查找的位置。请打开要调试的文件,或自行选择程序。"; @@ -3027,6 +3033,7 @@ "Preflight" = "预检"; "Preparing conversation…" = "正在准备对话…"; "Preparing download…" = "正在准备下载…"; +"Preparing the language server" = "正在准备语言服务器"; "Preparing…" = "正在准备…"; "Preserves every commit and adds a merge commit to the base branch." = "保留全部提交,并在目标分支中添加一个合并提交。"; "Press shortcut…" = "请按下快捷键…"; @@ -3726,6 +3733,7 @@ "Send a message to %@" = "向 %@ 发送消息"; "Send input to debuggee" = "向调试进程发送输入"; "Send program input" = "发送程序输入"; +"Send requests and commands to its language server for your project" = "为你的项目向它的语言服务器发送请求和命令"; "Sending…" = "发送中…"; "Sensitive files are not sent to an AI provider." = "敏感文件不会发送给 AI 服务商。"; "Separate arguments with spaces; quote an argument that contains spaces." = "参数之间用空格分隔;包含空格的参数请加引号。"; @@ -3989,6 +3997,7 @@ "Start this configuration to see its output here." = "启动此配置后,输出将显示在这里。"; "Start time" = "开始时间"; "Start with an action verb, without a type prefix" = "以动作动词开头,不添加类型前缀"; +"Started by the plugin" = "由插件启动"; "Started in Claude Desktop" = "已在 Claude Desktop 中开始"; "Starting" = "正在启动"; "Starting Interactive Rebase" = "正在开始交互式变基"; @@ -4067,6 +4076,7 @@ "Suggested" = "建议"; "Suggested replies" = "建议的回复"; "Supplementary message cancelled." = "补充消息已取消。"; +"Supply the text of read-only documents it opens in the editor" = "为它在编辑器中打开的只读文档提供文本"; "Supported keyboard commands are mapped; unknown keymaps, mouse shortcuts and chords are skipped." = "映射受支持的键盘命令;跳过未知键位方案、鼠标快捷键和连续按键。"; "Supported placeholders: {summary}, {changes}, {testing}, {risks}." = "支持的占位符:{summary}、{changes}、{testing}、{risks}。"; "Svelte Support" = "Svelte 支持"; @@ -4328,7 +4338,10 @@ "The interface language changes immediately. English is the default." = "界面语言会立即生效。默认语言为英文。"; "The item can be recovered from the macOS Trash." = "可以从 macOS 废纸篓中恢复此项目。"; "The language server could not apply this setting. Restart it to use the new value." = "语言服务器无法应用此设置。请重启它以使用新值。"; +"The language server could not get ready" = "语言服务器未能就绪"; +"The language server is not running." = "语言服务器没有运行。"; "The language server is still stopping. Try again after it has stopped." = "语言服务器仍在停止。请在停止完成后重试。"; +"The language server runs with limited features" = "语言服务器功能受限"; "The language server this build system uses is not available. Open a file of the language and try again." = "此构建系统使用的语言服务器不可用。请打开该语言的文件后重试。"; "The language service that hosts the debug adapter is unavailable." = "承载调试适配器的语言服务不可用。"; "The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release." = "将全量下载最新正式版,在你确认安装后替换当前 AutoBuild。项目和设置会保留,但 AutoBuild 专有的设置可能无法在正式版中使用。"; @@ -4561,6 +4574,7 @@ "This configuration contains unsupported or invalid settings." = "此配置包含不支持或无效的设置。"; "This configuration has no supported explicit editor settings to import." = "此配置中没有可导入的、受支持的显式编辑器设置。"; "This configuration is larger than 1 MiB and is not edited by Lithe." = "此配置超过 1 MiB,Lithe 不会编辑它。"; +"This content scheme already has a provider." = "这个内容方案已经有提供者了。"; "This conversation is no longer available. Choose another conversation." = "此会话已不可用,请选择其他会话。"; "This debug session requires an external terminal, which is not supported." = "此调试会话需要外部终端,目前不支持。"; "This debug session requires shell-interpreted terminal arguments." = "此调试会话需要由 Shell 解释的终端参数。"; @@ -5803,6 +5817,7 @@ "native.cannotEncodeHookConfiguration" = "无法编码 Hook 配置。"; "native.cannotEncodeTheHookLibrary" = "无法编码 Hook 资源库。"; "native.cannotLocateTheAgentUserDirectory" = "无法定位 Agent 的用户目录。"; +"native.cannotStartInARemoteWorkspaceYet" = "%1$@ 暂时还不能在远程工作区中启动。"; "native.cannotUseUsingTheProjectJDKInstead" = "无法使用 %1$@,已改用项目 JDK。"; "native.category" = "分类"; "native.changeTheValuesStoredInTheSelectedScopeChooseInheritToRemoveAnOverride" = "修改所选范围中保存的值。选择“继承”即可移除覆盖。"; @@ -6062,6 +6077,7 @@ "native.commaSeparatedGlobPatternsEGJavaKt" = "以逗号分隔的 glob 模式,例如 *.java、*.kt"; "native.commaSeparatedGlobPatternsEmptySearchesEveryFile" = "以逗号分隔的 glob 模式。留空则搜索所有文件。"; "native.command" = "命令"; +"native.commandChosenBy" = "命令由 %1$@ 决定"; "native.commandDetails" = "命令详情"; "native.commandPaletteActions" = "命令面板入口"; "native.commandsAnAIAgentStartedThatAreStillRunningForExampleADeploymentADatabaseMigradd876f8a4a" = "AI Agent 启动后仍在运行的命令,例如部署、数据库迁移或开发服务器。由于中途结束可能导致数据或服务不一致,每个任务都会单独确认。Agent 自身需要的进程(例如它的 MCP 服务)总是随 Agent 一起结束。"; @@ -7322,6 +7338,7 @@ "native.languageServerReturnedOverlappingTextEdits" = "语言服务器返回了重叠的文本编辑。"; "native.languageServerSessionStoppedBeforeTheRequestCompleted" = "语言服务器会话在请求完成前已停止。"; "native.languageServerSettingsAction" = "语言服务器设置..."; +"native.languageServerStartedByThePlugin" = "%1$@ 语言服务器(由插件启动)"; "native.languageServerStillStopping" = "语言服务器仍在停止。请在停止完成后重试。"; "native.languageServerToolConfigurationChanged" = "语言服务器工具配置已更改"; "native.languageServers" = "语言服务器"; @@ -7746,6 +7763,7 @@ "native.navigateToTheNextEditorLocation" = "跳转到下一个编辑器位置"; "native.navigateToThePreviousEditorLocation" = "跳转到上一个编辑器位置"; "native.navigation" = "导航"; +"native.needsALaunchThisBuildOfLitheCannotResolve" = "%1$@ 需要一种当前版本的 Lithe 还无法解析的启动方式。"; "native.needsNoExtraPermissions" = "不需要额外权限。"; "native.needsRestart" = "需重启"; "native.nestedException" = "嵌套异常"; @@ -7887,6 +7905,7 @@ "native.noNavigationResults" = "没有导航结果"; "native.noNewCommitsPushingCreatesTheRemoteBranch" = "没有新的提交。推送会创建远程分支。"; "native.noNotifications" = "暂无通知"; +"native.noOpenWindowShowsThisWorkspaceSoThePluginCannotChooseHowToStartItsLanguageServer" = "没有已打开的窗口显示这个工作区,插件无法决定如何启动它的语言服务器。"; "native.noPaths" = "没有路径"; "native.noPathsResolvedForThisService" = "此服务没有已解析的路径"; "native.noPlaceToLookYetOpenTheFileYouWantToDebugOrChooseTheProgramYourself" = "还没有可查找的位置。请打开要调试的文件,或自行选择程序。"; @@ -8220,6 +8239,7 @@ "native.preparing" = "正在准备…"; "native.preparingConversation" = "正在准备对话…"; "native.preparingDownload" = "正在准备下载…"; +"native.preparingTheLanguageServer" = "正在准备语言服务器"; "native.preservesEveryCommitAndAddsAMergeCommitToTheBaseBranch" = "保留全部提交,并在目标分支中添加一个合并提交。"; "native.pressShortcut" = "请按下快捷键…"; "native.previewBackgroundImage" = "预览背景图片"; @@ -8584,6 +8604,7 @@ "native.resizeDialog" = "调整对话框大小,%1$@"; "native.resolveLldConflictedFileSStageTheResultThenContinue" = "请解决 %1$lld 个文件的冲突,暂存结果后再继续。"; "native.resolveLldConflictedFileSStageThemThenContinue" = "请解决 %1$lld 个冲突文件并暂存,然后继续。"; +"native.resolvesToAProgramInsideTheProjectWhichALanguageServerCannotStart" = "%1$@ 解析到了项目内的程序,语言服务器不能用它启动。"; "native.resolvingDependencies" = "正在解析依赖…"; "native.resolvingPushDestination" = "正在确定推送目标…"; "native.resolvingServicePaths" = "正在解析服务路径…"; @@ -8859,6 +8880,7 @@ "native.sendAMessageTo" = "向 %1$@ 发送消息"; "native.sendInputToDebuggee" = "向调试进程发送输入"; "native.sendProgramInput" = "发送程序输入"; +"native.sendRequestsAndCommandsToItsLanguageServerForYourProject" = "为你的项目向它的语言服务器发送请求和命令"; "native.sending" = "发送中…"; "native.sensitiveFilesAreNotSentToAnAIProvider" = "敏感文件不会发送给 AI 服务商。"; "native.separateArgumentsWithSpacesQuoteAnArgumentThatContainsSpaces" = "参数之间用空格分隔;包含空格的参数请加引号。"; @@ -9089,6 +9111,7 @@ "native.startThisConfigurationToSeeItsOutputHere" = "启动此配置后,输出将显示在这里。"; "native.startWithAnActionVerbWithoutATypePrefix" = "以动作动词开头,不添加类型前缀"; "native.startedATaskThatIsStillRunning" = "%1$@ 启动的任务仍在运行"; +"native.startedByThePlugin" = "由插件启动"; "native.startedInClaudeDesktop" = "已在 Claude Desktop 中开始"; "native.starting" = "正在启动"; "native.startingCommitOptional" = "起始提交(可选)"; @@ -9160,6 +9183,7 @@ "native.suggested" = "建议"; "native.suggestedReplies" = "建议的回复"; "native.supplementaryMessageCancelled" = "补充消息已取消。"; +"native.supplyTheTextOfReadOnlyDocumentsItOpensInTheEditor" = "为它在编辑器中打开的只读文档提供文本"; "native.supportedPlaceholdersSummaryChangesTestingRisks" = "支持的占位符:{summary}、{changes}、{testing}、{risks}。"; "native.svelteSupport" = "Svelte 支持"; "native.svgViewMode" = "SVG 视图模式"; @@ -9362,9 +9386,12 @@ "native.theJavaTestResultListenerDidNotBecome" = "Java 测试结果监听器未能及时就绪。"; "native.theLanguageProviderIsNotInstalled" = "%1$@ 语言 Provider 尚未安装。"; "native.theLanguageServerCouldNotApplyThisSetting" = "语言服务器无法应用此设置。请重启它以使用新值。"; +"native.theLanguageServerCouldNotGetReady" = "语言服务器未能就绪"; "native.theLanguageServerIsDisabledInThisWorkspace" = "此工作区已停用 %1$@ 语言服务器。请在“设置 > LSP”中启用它。"; +"native.theLanguageServerIsNotRunning" = "语言服务器没有运行。"; "native.theLanguageServerOfThisPluginIsNotAvailable" = "此插件的 %1$@ 语言服务器不可用。"; "native.theLanguageServerReturnedAnInvalidTcpPortForItsDebugAdapter" = "%1$@ 语言服务器为其调试适配器返回了无效的 TCP 端口。"; +"native.theLanguageServerRunsWithLimitedFeatures" = "语言服务器功能受限"; "native.theLanguageServerThisBuildSystemUsesIsNotAvailable" = "此构建系统使用的语言服务器不可用。请打开该语言的文件后重试。"; "native.theLanguageServiceThatHostsTheDebugAdapterIsUnavailable" = "承载调试适配器的语言服务不可用。"; "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisAutoBuildAfterYouConbfd63f6a8e" = "将全量下载最新正式版,在你确认安装后替换当前 AutoBuild。项目和设置会保留,但 AutoBuild 专有的设置可能无法在正式版中使用。"; @@ -9556,6 +9583,7 @@ "native.thisComputer" = "本机"; "native.thisComputerThisProject" = "本机 · 此项目"; "native.thisConfigurationIsLargerThan1MibAnd" = "此配置超过 1 MiB,Lithe 不会编辑它。"; +"native.thisContentSchemeAlreadyHasAProvider" = "这个内容方案已经有提供者了。"; "native.thisConversationIsNoLongerAvailableChooseAnotherConversation" = "此会话已不可用,请选择其他会话。"; "native.thisDebugSessionRequiresAnExternalTerminalWhich" = "此调试会话需要外部终端,目前不支持。"; "native.thisDebugSessionRequiresShellInterpretedTerminalArguments" = "此调试会话需要由 Shell 解释的终端参数。"; diff --git a/macos/Sources/Lithe/Application/Composition/AppServices.swift b/macos/Sources/Lithe/Application/Composition/AppServices.swift index 6d780df849..05240e72ee 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 pluginContentProviders: PluginContentProviderHostService? var pluginEditorProviders: PluginEditorProviderHostService? /// Static plugin editor resources; `nil` when /// the platform loads no plugins. diff --git a/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift b/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift index c221e0a31d..5fa32b2321 100644 --- a/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift @@ -13,10 +13,13 @@ final class LanguageToolingFeatureModel: ObservableObject { @Published private(set) var catalogSnapshot: LanguageProviderCatalogSnapshot @Published private(set) var disabledProviderIDs: Set = [] @Published private(set) var projectPreparation: ProjectPreparationSnapshot? + /// What plugin-owned language servers report with `setStatus`, by server ID. + @Published private(set) var pluginServerStatuses: [String: PluginServerStatus] = [:] @Published private(set) var serverRuntimeSnapshot = LanguageServerRuntimeSnapshot() let projectUsage = LSPProjectUsageModel() private var preparationObservation: AnyCancellable? private var statusObservation: AnyCancellable? + private var pluginStatusObservation: AnyCancellable? private(set) var startupFailures: [String: String] = [:] private let catalogSource: any LanguageProviderCatalogSource @@ -90,6 +93,9 @@ final class LanguageToolingFeatureModel: ObservableObject { preparationObservation = sessions.$projectPreparation.removeDuplicates().sink { [weak self] snapshot in self?.projectPreparation = snapshot } + pluginStatusObservation = sessions.$pluginServerStatuses.removeDuplicates().sink { [weak self] statuses in + self?.pluginServerStatuses = statuses + } } func resetWorkspaceState() { diff --git a/macos/Sources/Lithe/Application/Features/PluginContentProviderHostService.swift b/macos/Sources/Lithe/Application/Features/PluginContentProviderHostService.swift new file mode 100644 index 0000000000..fd25b144bf --- /dev/null +++ b/macos/Sources/Lithe/Application/Features/PluginContentProviderHostService.swift @@ -0,0 +1,126 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +// Note: 插件自有语言服务器会话与宿主方法的决策见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +/// One URI scheme a plugin backend serves in one workspace window. +struct PluginContentProviderRegistration: Equatable { + let lease: UUID + let pluginID: String + let sessionID: String + let context: PluginWorkspaceContextReference + let scheme: String + let functionID: String +} + +/// `lithe/host/documents/registerContentProvider` (plan API-12): a plugin +/// backend serves the read-only text of documents that have no file, such as +/// the source of a library class its language server decompiles. +/// +/// Registration only records the binding; it never calls the backend while +/// the backend awaits this answer. The scheme's grammar and reserved names +/// are checked by Rust Core before the request reaches the service. The +/// provider belongs to the backend session and the window: ending the +/// session, closing the context, disposing the subscription, or withdrawing +/// the function removes it. +@MainActor +final class PluginContentProviderHostService: PluginHostServiceHandling { + let service = "documents" + let methods: Set = ["lithe/host/documents/registerContentProvider"] + private let contexts: PluginWorkspaceContexts + private let decoder: any PluginContentDecoding + private var providers: [UUID: PluginContentProviderRegistration] = [:] + private var withdrawals: [UUID: @MainActor () -> Void] = [:] + /// The functions each backend session has registered; a provider needs one. + private var functions: [String: (session: String, ids: Set)] = [:] + + init(contexts: PluginWorkspaceContexts, decoder: any PluginContentDecoding) { + self.contexts = contexts + self.decoder = decoder + } + + /// The provider that serves `scheme` in the window, if one is registered. + func provider(forScheme scheme: String, context: PluginWorkspaceContextReference) -> PluginContentProviderRegistration? { + providers.values.first { $0.scheme == scheme && $0.context == context } + } + + /// The document text of a provider's answer, or the reason Core refused it. + func content(of answer: ToolingJSONValue) throws -> String { + try decoder.decodeContent(answer) + } + + // MARK: Registration + + func answer(_ call: PluginHostCall) async -> Result { + do { + let scope = try PluginHostAPIContext(call, contexts: contexts) + let arguments = try PluginHostArguments(call.params, allowed: ["context", "scheme", "function"]) + let scheme = try arguments.string("scheme") + let functionID = try arguments.string("function") + guard functions[call.pluginID]?.session == call.sessionID, + functions[call.pluginID]?.ids.contains(functionID) == true else { + throw PluginHostArguments.invalid + } + guard provider(forScheme: scheme, context: scope.workspace.reference) == nil else { + throw PluginHostServiceError(.preconditionFailed, L10n.string("This content scheme already has a provider.")) + } + let registration = PluginContentProviderRegistration( + lease: UUID(), pluginID: call.pluginID, sessionID: call.sessionID, + context: scope.workspace.reference, scheme: scheme, functionID: functionID + ) + return .success(.object(["subscriptionID": .string(add(registration, to: call.subscriptions))])) + } catch { + var failure = PluginHostAPIValues.failure(error) + failure.logError = error + return .failure(failure) + } + } + + /// Records the provider and returns the subscription that removes it. + private func add(_ registration: PluginContentProviderRegistration, to subscriptions: PluginHostSubscriptions) -> String { + let lease = registration.lease + let subscriptionID = subscriptions.add( + pluginID: registration.pluginID, contextID: registration.context.contextID + ) { [weak self] in + self?.providers[lease] = nil + self?.withdrawals[lease] = nil + } + providers[lease] = registration + let pluginID = registration.pluginID + withdrawals[lease] = { [weak subscriptions] in + subscriptions?.dispose(pluginID: pluginID, subscriptionID: subscriptionID) + } + return subscriptionID + } + + // MARK: Lifecycle + + /// A withdrawn function takes its providers with it. Registering again + /// is explicit; a reused function ID must not revive an old provider. + func updateFunctions(pluginID: String, sessionID: String, ids: [String]) { + let ids = Set(ids) + let previous = functions[pluginID] + functions[pluginID] = (sessionID, ids) + let stillRegistered = previous.map { $0.session == sessionID && $0.ids.isSubset(of: ids) } ?? true + if !stillRegistered { withdrawProviders(ofPlugin: pluginID) } + } + + func endSession(pluginID: String, sessionID: String) { + guard functions[pluginID]?.session == sessionID else { return } + functions[pluginID] = nil + withdrawProviders(ofPlugin: pluginID) + } + + func closeContext(_ contextID: String) { + for provider in Array(providers.values) where provider.context.contextID == contextID { + withdrawals[provider.lease]?() + } + } + + private func withdrawProviders(ofPlugin pluginID: String) { + for provider in Array(providers.values) where provider.pluginID == pluginID { + withdrawals[provider.lease]?() + } + } +} diff --git a/macos/Sources/Lithe/Application/Features/PluginHostScope.swift b/macos/Sources/Lithe/Application/Features/PluginHostScope.swift index 33ff623942..995e6fb809 100644 --- a/macos/Sources/Lithe/Application/Features/PluginHostScope.swift +++ b/macos/Sources/Lithe/Application/Features/PluginHostScope.swift @@ -122,9 +122,13 @@ protocol PluginHostWindowPort: AnyObject { var hostMessages: PluginHostMessageFeatureModel { get } /// Tells the user that `pluginName` sent more messages than the host shows. func hostNoteMessageLimit(pluginName: String) + /// The window's language server sessions; nil while the language + /// capability is not loaded, when no server can be running. + var hostLanguageServers: (any PluginLanguageServerRouting)? { get } } extension PluginHostWindowPort { + var hostLanguageServers: (any PluginLanguageServerRouting)? { nil } var hostDocumentService: (any EditorDocumentServicing)? { nil } var hostVisibilityRules: FileVisibilityRules { .default } func hostSetHTMLPresentation(at url: URL, previewOnly: Bool) throws { throw PluginHostError.unsupportedOption } diff --git a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift index 731bd7d4ae..277beae35c 100644 --- a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift +++ b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift @@ -14,6 +14,15 @@ protocol PluginBackendActivating: AnyObject { /// starts when it declares `onCommand:`, and the running backend /// receives `lithe/host/commands/didRun` with the window's context. func runCommand(_ commandID: String, owner: ModuleID, context: PluginWorkspaceContextReference?) + /// Tells the plugin's running backend about a language server the plugin + /// owns: `lithe/host/languageServer/didChangeState` or + /// `didReceiveNotification`. A backend that holds no `languageServer` + /// host method grant does not receive it. + func notifyLanguageServer(pluginID: String, method: String, params: ToolingJSONValue) +} + +extension PluginBackendActivating { + func notifyLanguageServer(pluginID _: String, method _: String, params _: ToolingJSONValue) {} } /// How a host service failed, as a function protocol 3 backend sees it. @@ -52,6 +61,17 @@ enum PluginHostErrorCode: String, Sendable, CaseIterable { /// The backend went away while the host worked on its request. case backendExited = "plugin.backend.exited" case failed = "plugin.host.failed" + /// The plugin's language server is not running (stopped, still starting, + /// or never started with a session policy). + case languageServerUnavailable = "plugin.host.languageServerUnavailable" + /// The language server answered the request with a JSON-RPC error; the + /// server's own `{ code, message }` is in the details. + case languageServerError = "plugin.host.languageServerError" + /// The method, or the `workspace/executeCommand` command, is not one the + /// plugin's manifest declares for the server. + case methodNotDeclared = "plugin.host.methodNotDeclared" + /// The server or document scheme belongs to another plugin. + case foreignContribution = "plugin.host.foreignContribution" } /// A failed host service request. The message reaches the backend, so it @@ -77,6 +97,19 @@ struct PluginHostServiceError: Error, Equatable, Sendable { var failure: PluginHostRequestFailure { PluginHostRequestFailure(message: message, code: code.rawValue, details: details.map { .object($0) }) } + + /// An answer Rust Core or a session already put into the backend's + /// shape. A code this host does not know reaches the backend as `failed`, + /// as it would from Core. + init(_ failure: PluginHostRequestFailure) { + var details: [String: ToolingJSONValue]? + if case .object(let members)? = failure.details { details = members } + self.init( + failure.code.flatMap(PluginHostErrorCode.init(rawValue:)) ?? .failed, + failure.message, + details: details + ) + } } /// One host request a service answers. Core has already checked the @@ -325,10 +358,15 @@ final class PluginHostServiceDispatcher { contextID = Self.contextReference(value)?.contextID } else { contextID = nil } // User-choice messages have no clock deadline; their session, context - // and cancellation own dismissal. Machine operations are locally bounded. - let waitsForUser = request.method.hasPrefix("lithe/host/window/show") - || ["lithe/host/terminal/create", "lithe/host/terminal/reopen"].contains(request.method) - let deadline: Task? = waitsForUser ? nil : Task { @MainActor [weak self] in + // and cancellation own dismissal. A language server request ends by the + // timeout Core enforces (default 60 s, at most 300 s), which the 30 s + // host deadline would cut short. Other machine operations are locally bounded. + let hasOwnDeadline = request.method.hasPrefix("lithe/host/window/show") + || [ + "lithe/host/terminal/create", "lithe/host/terminal/reopen", + "lithe/host/languageServer/request", + ].contains(request.method) + let deadline: Task? = hasOwnDeadline ? nil : Task { @MainActor [weak self] in // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 do { try await Task.sleep(for: .seconds(30)) } catch { return } guard let self, self.sessionIDs[pluginID] == currentSession, diff --git a/macos/Sources/Lithe/Application/Features/PluginLanguageServerHostService.swift b/macos/Sources/Lithe/Application/Features/PluginLanguageServerHostService.swift new file mode 100644 index 0000000000..bae2bc1282 --- /dev/null +++ b/macos/Sources/Lithe/Application/Features/PluginLanguageServerHostService.swift @@ -0,0 +1,149 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI +import LitheLanguageIntelligenceModule + +// Note: 插件自有语言服务器会话与宿主方法的决策见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +/// The language server sessions of one window, as the `languageServer` host +/// service reaches them. The session manager implements it; the service never +/// sees a session, so it cannot reach a server the manager did not hand out. +@MainActor +protocol PluginLanguageServerRouting: AnyObject { + func requestPluginServer( + pluginID: String, serverID: String, method: String, params: ToolingJSONValue, timeout: TimeInterval? + ) async -> Result + + func notifyPluginServer( + pluginID: String, serverID: String, method: String, params: ToolingJSONValue + ) async -> Result + + func setPluginServerStatus( + _ status: PluginServerStatus, serverID: String, pluginID: String + ) -> Result +} + +extension LanguageToolingSessionManager: PluginLanguageServerRouting {} + +/// `lithe/host/languageServer/request`, `notify` and `setStatus` (plan +/// API-25): a plugin backend talks to the language servers its own plugin +/// declares. +/// +/// The service only finds the window's session and passes the call on. Rust +/// Core decides whether the server belongs to the plugin, whether the method +/// or command is declared, and enforces gates, serialization and timeouts; +/// its answer reaches the backend unchanged. +@MainActor +final class PluginLanguageServerHostService: PluginHostServiceHandling { + private enum Method { + static let request = "lithe/host/languageServer/request" + static let notify = "lithe/host/languageServer/notify" + static let setStatus = "lithe/host/languageServer/setStatus" + } + + let service = "languageServer" + let methods: Set = [Method.request, Method.notify, Method.setStatus] + private let contexts: PluginWorkspaceContexts + + init(contexts: PluginWorkspaceContexts) { self.contexts = contexts } + + func answer(_ call: PluginHostCall) async -> Result { + do { + let scope = try PluginHostAPIContext(call, contexts: contexts) + guard let servers = scope.window.hostLanguageServers else { throw Self.unavailable } + switch call.request.method { + case Method.request: return .success(try await request(call, on: servers)) + case Method.notify: return .success(try await notify(call, on: servers)) + case Method.setStatus: return .success(try setStatus(call, on: servers)) + default: throw PluginHostArguments.invalid + } + } catch { + var failure = PluginHostAPIValues.failure(error) + failure.logError = error + return .failure(failure) + } + } + + private func request(_ call: PluginHostCall, on servers: any PluginLanguageServerRouting) async throws + -> ToolingJSONValue { + let arguments = try PluginHostArguments( + call.params, allowed: ["context", "serverID", "method", "params", "timeoutMilliseconds"] + ) + let outcome = await servers.requestPluginServer( + pluginID: call.pluginID, + serverID: try arguments.string("serverID"), + method: try arguments.string("method"), + params: try Self.serverParams(arguments), + timeout: try Self.timeout(arguments) + ) + return .object(["value": try Self.value(of: outcome)]) + } + + private func notify(_ call: PluginHostCall, on servers: any PluginLanguageServerRouting) async throws + -> ToolingJSONValue { + let arguments = try PluginHostArguments(call.params, allowed: ["context", "serverID", "method", "params"]) + let outcome = await servers.notifyPluginServer( + pluginID: call.pluginID, + serverID: try arguments.string("serverID"), + method: try arguments.string("method"), + params: try Self.serverParams(arguments) + ) + return .object(["delivered": .bool(try Self.value(of: outcome))]) + } + + private func setStatus(_ call: PluginHostCall, on servers: any PluginLanguageServerRouting) throws + -> ToolingJSONValue { + let arguments = try PluginHostArguments( + call.params, allowed: ["context", "serverID", "state", "message", "percentage"] + ) + let outcome = servers.setPluginServerStatus( + try Self.status(arguments), serverID: try arguments.string("serverID"), pluginID: call.pluginID + ) + _ = try Self.value(of: outcome) + return .object([:]) + } + + // MARK: Params + + /// The JSON-RPC params; an object, `{}` when the backend sent none. + private static func serverParams(_ arguments: PluginHostArguments) throws -> ToolingJSONValue { + guard arguments.values["params"] != nil else { return .object([:]) } + return .object(try arguments.object("params")) + } + + private static func timeout(_ arguments: PluginHostArguments) throws -> TimeInterval? { + guard arguments.values["timeoutMilliseconds"] != nil else { return nil } + let milliseconds = try arguments.integer("timeoutMilliseconds") + guard (1...300_000).contains(milliseconds) else { throw PluginHostArguments.invalid } + return TimeInterval(milliseconds) / 1000 + } + + private static func status(_ arguments: PluginHostArguments) throws -> PluginServerStatus { + guard let state = PluginServerStatus.State(rawValue: try arguments.string("state")) else { + throw PluginHostArguments.invalid + } + var percentage: Int? + if arguments.values["percentage"] != nil { + percentage = try arguments.integer("percentage") + guard (0...100).contains(percentage ?? 0) else { throw PluginHostArguments.invalid } + } + return PluginServerStatus(state: state, message: try arguments.optionalString("message"), percentage: percentage) + } + + // MARK: Outcomes + + /// A window whose language capability is not loaded runs no server. + private static var unavailable: PluginHostServiceError { + PluginHostServiceError(.languageServerUnavailable, L10n.string("The language server is not running.")) + } + + /// The value of a session's answer, or its failure in the backend's shape. + private static func value(of outcome: Result) throws -> Value { + switch outcome { + case .success(let value): + return value + case .failure(let failure): + throw PluginHostServiceError(failure) + } + } +} diff --git a/macos/Sources/Lithe/Application/Features/PluginManagement.swift b/macos/Sources/Lithe/Application/Features/PluginManagement.swift index a75db699c2..71c9a106d4 100644 --- a/macos/Sources/Lithe/Application/Features/PluginManagement.swift +++ b/macos/Sources/Lithe/Application/Features/PluginManagement.swift @@ -180,6 +180,8 @@ struct PluginCapability: Equatable, Sendable, Identifiable { /// Started by a runtime; `packagedRuntime` when the plugin ships it. case runtimeServer(tool: String, packagedRuntime: Bool) case systemServer(commands: [String]) + /// The plugin's backend chooses the command each time it starts. + case backendServer /// Lithe's own implementation serves the capability; the plugin only /// turns it on for its language. case hostIntegration @@ -216,6 +218,7 @@ struct PluginCapability: Equatable, Sendable, Identifiable { case .packaged?: .packagedServer case .runtime(let tool, _, let packagedRuntime)?: .runtimeServer(tool: tool, packagedRuntime: packagedRuntime != nil) case .systemCommand(let commands)?: .systemServer(commands: commands) + case .backend?: .backendServer case nil: .none } result.append(PluginCapability( diff --git a/macos/Sources/Lithe/Application/Features/PluginWorkspaceContexts.swift b/macos/Sources/Lithe/Application/Features/PluginWorkspaceContexts.swift index 5d721f4d7e..87228533d9 100644 --- a/macos/Sources/Lithe/Application/Features/PluginWorkspaceContexts.swift +++ b/macos/Sources/Lithe/Application/Features/PluginWorkspaceContexts.swift @@ -97,6 +97,18 @@ final class PluginWorkspaceContexts { return .success(context) } + /// The local context whose workspace is the folder at `url`. Work that + /// starts from a folder, such as a language server's launch, uses it to + /// speak to a plugin backend in the window that shows the folder. Two + /// windows on one folder give the first in context ID order. + func localContext(forFolder url: URL) -> PluginWorkspaceContext? { + // Paths, not URLs: "/a/b" and "/a/b/" are one folder. + let path = url.standardizedFileURL.path + return contexts.first { context in + context.authority == .local && context.folders.contains { $0.localURL.standardizedFileURL.path == path } + } + } + /// Opens or replaces the window's context. The same workspace again /// keeps the context unchanged, or moves it to the next generation when /// its folders or authority changed. Another workspace closes the old diff --git a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift index 9ea15a6138..f81e50b7ea 100644 --- a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift +++ b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift @@ -1888,6 +1888,10 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let toolchainProviders: [String]? /// Shortcut import providers offered to a plugin backend; omitted when none. let keymapImportProviders: [String]? + /// What the plugin backend may do with this server through the host + /// (plan API-25), exactly as `plugins.declarative.languageServerLaunchPlan` + /// returned it. Omitted when the plugin declares none. + let sessionPolicy: ToolingJSONValue? let runtimeExecutablePath: String? let jdtlsLaunchResources: LspJdtlsLaunchResourcesRequest? let cacheDirectory: String? @@ -2083,6 +2087,25 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let context: Context? } + /// A request the plugin backend sent to its own language server. + private struct LspPluginServerRequest: Encodable { + let sessionId: String + let pluginId: String + let serverID: String + let method: String + let params: ToolingJSONValue + /// Omitted when nil, so Core applies its default deadline. + let timeoutMilliseconds: Int? + } + + private struct LspPluginServerNotifyRequest: Encodable { + let sessionId: String + let pluginId: String + let serverID: String + let method: String + let params: ToolingJSONValue + } + private struct LspHostResponseRequest: Encodable { struct Failure: Encodable { let message: String @@ -2157,6 +2180,9 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let processExitCode: Int? let javaBuildReport: JavaBuildReport? let pluginErrorCode: String? + /// Facts of a failed plugin-server request, such as the server's own + /// error code and message. + let details: ToolingJSONValue? } struct LspServerInfoPayload: Decodable, Sendable { @@ -3853,6 +3879,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { editorOptions: PluginEditorHostOptions? = nil, toolchainProviders: [String] = [], keymapImportProviders: [String] = [], + sessionPolicy: ToolingJSONValue? = nil, runtimeExecutableURL: URL? = nil, jdtlsLaunchResources: JDTLSLaunchResources? = nil, cacheDirectoryURL: URL? = nil, @@ -3881,6 +3908,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { hostOptions: editorOptions.map(LspHostOptions.init), toolchainProviders: toolchainProviders.isEmpty ? nil : toolchainProviders, keymapImportProviders: keymapImportProviders.isEmpty ? nil : keymapImportProviders, + sessionPolicy: sessionPolicy, runtimeExecutablePath: runtimeExecutableURL?.standardizedFileURL.path, jdtlsLaunchResources: jdtlsLaunchResources.map { LspJdtlsLaunchResourcesRequest( @@ -4246,6 +4274,48 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { ) } + /// Sends one LSP request of a plugin backend to its own server. Core + /// applies the plugin's whitelist, gates and timeout; the answer arrives as + /// the `requestCompleted` event of the returned operation. + func lspPluginServerRequest( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) -> Result { + executeResult( + command: "lsp.pluginServerRequest", + payload: LspPluginServerRequest( + sessionId: sessionID, pluginId: pluginID, serverID: serverID, method: method, params: params, + timeoutMilliseconds: timeout.map { max(1, Self.milliseconds($0)) } + ) + ) + } + + private struct LspPluginServerNotifyResponse: Decodable { + let delivered: Bool + } + + /// Sends one LSP notification of a plugin backend to its own server. + /// `false` when the server is not initialized yet and will read the stored + /// configuration with its `initialized` notification instead. + func lspPluginServerNotify( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) -> Result { + executeResult( + command: "lsp.pluginServerNotify", + payload: LspPluginServerNotifyRequest( + sessionId: sessionID, pluginId: pluginID, serverID: serverID, method: method, params: params + ) + ).map { (response: LspPluginServerNotifyResponse) in response.delivered } + } + /// Answers one `hostRequest` event of a plugin backend. func lspHostResponse( sessionID: String, diff --git a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift index cad8f56bea..ff6e2a731b 100644 --- a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift +++ b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift @@ -7,7 +7,8 @@ import LitheModuleAPI /// translates payloads and outcomes. struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, DeclarativeExecutionPlanning, DeclarativeLanguageServerLaunchPlanning, DeclarativePluginSettingsResolving, LanguageServerRuntimeVersionChecking, - DeclarativeEditorContributionDecoding, PluginEditorActionDecoding, PluginEditorProviderDecoding { + DeclarativeEditorContributionDecoding, PluginEditorActionDecoding, PluginContentDecoding, + PluginEditorProviderDecoding { let core: RustCoreBridge func validateNativeNodes(ui: PluginNativeUI, data: ToolingJSONValue) throws -> [PluginNativeUI.Node] { @@ -117,6 +118,52 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec )) } + func decodeLaunch( + manifest: Data, + languageID: String, + request: DeclarativeLanguageServerLaunchRequest, + result: ToolingJSONValue + ) throws -> DeclarativeLanguageServerLaunchPlan { + let outcome: Outcome = try execute( + "plugins.languageServers.decodeLaunch", + payload: DecodeLaunchPayload( + manifest: try Self.json(manifest), + languageID: languageID, + request: LaunchRequest(request), + result: result + ) + ) + return try Self.launchPlan(from: outcome.value.plan) + } + + func expiredLanguageServerStateNames( + retention: DeclarativeLanguageServer.StateRetention, + nowUnixSeconds: Int, + entries: [LanguageServerStateEntry], + activeNames: [String] + ) throws -> [String] { + // This command answers with its data only, without a status. + let result: Result = core.executeResult( + command: "plugins.languageServers.stateRetention", + payload: StateRetentionPayload( + retention: .init(maxEntries: retention.maxEntries, maxAgeDays: retention.maxAgeDays), + nowUnixSeconds: nowUnixSeconds, + entries: entries.map { + .init(name: $0.name, lastModifiedUnixSeconds: $0.lastModifiedUnixSeconds) + }, + activeNames: activeNames + ) + ) + do { + return try result.get().expiredNames + } catch { + throw DeclarativePluginRejection( + code: "plugin.launch.invalidRequest", + message: "Lithe could not select the expired language server state: \(error.localizedDescription)" + ) + } + } + func buildProviderLaunchPlan( manifest: Data, buildSystemID: String, @@ -236,7 +283,12 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec "plugins.declarative.languageServerLaunchPlan", payload: payload ) - let plan = outcome.value.plan + return try Self.launchPlan(from: outcome.value.plan) + } + + /// Maps Core's wire plan, from either step of a launch, to the plan the + /// host works with. + private static func launchPlan(from plan: LaunchPlan) throws -> DeclarativeLanguageServerLaunchPlan { var result = DeclarativeLanguageServerLaunchPlan( arguments: plan.arguments, validationArguments: plan.validationArguments, @@ -271,6 +323,9 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec } ) result.workspaceConfiguration = plan.workspaceConfiguration + result.backendResolution = plan.backendResolution + result.resolvedLaunch = plan.resolvedLaunch + result.sessionPolicy = plan.sessionPolicy result.vcsProvider = plan.vcsProvider.map { .init( vcs: $0.vcs, @@ -328,6 +383,16 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec return result } + func decodeContent(_ answer: ToolingJSONValue) throws -> String { + struct Payload: Encodable { let result: ToolingJSONValue } + struct Decoded: Decodable { let content: String } + // This command answers with its data only, without a status. + let decoded: Decoded = try core.executeResult( + command: "plugins.contentProviders.decode", payload: Payload(result: answer) + ).get() + return decoded.content + } + 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( @@ -505,6 +570,8 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec private struct LaunchRequest: Encodable { let logDirectory: String? + /// Omitted unless the plugin backend resolves the launch. + let temporaryDirectory: String? let pluginDirectory: String let stateDirectory: String /// Omitted for a process bound to no workspace. @@ -515,6 +582,7 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec init(_ request: DeclarativeLanguageServerLaunchRequest) { logDirectory = request.logDirectory?.path + temporaryDirectory = request.temporaryDirectory?.path pluginDirectory = request.pluginDirectory.path stateDirectory = request.stateDirectory.path workspaceStateDirectory = request.workspaceStateDirectory?.path @@ -539,6 +607,9 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec let packagedRuntime: String? let minimumVersion: String? let versionArguments: [String]? + /// `backend` launches: the function to call and its timeout. + let function: String? + let timeoutMilliseconds: Int? var executable: DeclarativeLanguageServerLaunchPlan.Executable? { switch kind { @@ -591,6 +662,36 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec let vcsProvider: VcsProvider? let backend: Backend? let debugAdapter: DebugAdapter? + /// First step of a backend-resolved launch. + let resolveParams: [String: ToolingJSONValue]? + /// Second step of a backend-resolved launch. + let environment: [String: String]? + let writablePaths: [String]? + let sessionPolicy: ToolingJSONValue? + + /// The question of the first step, when the plan asks one. + var backendResolution: DeclarativeLanguageServerLaunchPlan.BackendResolution? { + guard launch.kind == "backend", let function = launch.function, let resolveParams else { return nil } + return .init( + function: function, + timeoutMilliseconds: launch.timeoutMilliseconds ?? 30_000, + resolveParams: resolveParams + ) + } + + /// The answer the second step decoded, when the plan holds one. Only + /// a decoded answer carries `writablePaths`, which tells it apart + /// from the ordinary plan of a packaged server. + var resolvedLaunch: DeclarativeLanguageServerLaunchPlan.ResolvedLaunch? { + guard let writablePaths else { return nil } + let program: DeclarativeLanguageServerLaunchPlan.ResolvedLaunch.Program + switch (launch.kind, launch.path, launch.tool) { + case ("packaged", let path?, _): program = .packaged(path) + case ("tool", _, let tool?): program = .tool(tool) + default: return nil + } + return .init(program: program, environment: environment ?? [:], writablePaths: writablePaths) + } struct DebugAdapter: Decodable { struct Selector: Decodable { @@ -687,6 +788,34 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec let request: LaunchRequest } + private struct DecodeLaunchPayload: Encodable { + let manifest: ToolingJSONValue + let languageID: String + let request: LaunchRequest + let result: ToolingJSONValue + } + + private struct StateRetentionPayload: Encodable { + struct Retention: Encodable { + let maxEntries: Int + let maxAgeDays: Int + } + + struct Entry: Encodable { + let name: String + let lastModifiedUnixSeconds: Int + } + + let retention: Retention + let nowUnixSeconds: Int + let entries: [Entry] + let activeNames: [String] + } + + private struct StateRetentionResult: Decodable { + let expiredNames: [String] + } + private struct DebugStartArgumentsPayload: Encodable { struct Facts: Encodable { struct Registration: Encodable { diff --git a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift index 528279d05d..8103c163ce 100644 --- a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift +++ b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift @@ -332,6 +332,45 @@ extension RustCoreBridge: LanguageServerRuntimeCore { }.mapError(Self.runtimeFailure) } + func startPluginLanguageServer( + pluginID: String, + providerID: String, + executableURL: URL, + arguments: [String], + environment: [String: String], + rootURL: URL, + initializationOptions: ToolingJSONValue?, + workspaceConfiguration: ToolingJSONValue?, + sessionPolicy: ToolingJSONValue, + hostServices: [String], + cacheDirectoryURL: URL?, + workspaceFingerprint: String?, + initializeTimeout: TimeInterval, + requestTimeout: TimeInterval, + shutdownTimeout: TimeInterval + ) -> Result { + lspStartServer( + providerID: providerID, + pluginID: pluginID, + executableURL: executableURL, + arguments: arguments, + environment: environment, + rootURL: rootURL, + workingDirectoryURL: rootURL, + initializationOptions: initializationOptions, + workspaceConfiguration: workspaceConfiguration, + hostServices: hostServices, + sessionPolicy: sessionPolicy, + cacheDirectoryURL: cacheDirectoryURL, + workspaceFingerprint: workspaceFingerprint, + initializeTimeout: initializeTimeout, + requestTimeout: requestTimeout, + shutdownTimeout: shutdownTimeout + ).map { + LanguageServerRuntimeStart(sessionID: $0.sessionId, state: $0.state, processID: $0.processId) + }.mapError(Self.runtimeFailure) + } + func requestToolchainProvider( sessionID: String, params: ToolingJSONValue, @@ -501,6 +540,33 @@ extension RustCoreBridge: LanguageServerRuntimeCore { .mapError(Self.runtimeFailure) } + func pluginServerRequest( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) -> Result { + lspPluginServerRequest( + sessionID: sessionID, pluginID: pluginID, serverID: serverID, method: method, params: params, + timeout: timeout + ).map { LanguageServerRuntimeOperation(operationID: $0.operationId) } + .mapError(Self.runtimeFailure) + } + + func pluginServerNotify( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) -> Result { + lspPluginServerNotify( + sessionID: sessionID, pluginID: pluginID, serverID: serverID, method: method, params: params + ).mapError(Self.runtimeFailure) + } + func cancelLanguageServerOperation(sessionID: String, operationID: String) { lspCancelOperation(sessionID: sessionID, operationID: operationID) } @@ -522,7 +588,8 @@ extension RustCoreBridge: LanguageServerRuntimeCore { underlyingMessage: $0.underlyingMessage, processExitCode: $0.processExitCode, javaBuildReport: $0.javaBuildReport, - pluginErrorCode: $0.pluginErrorCode + pluginErrorCode: $0.pluginErrorCode, + details: $0.details ) }, capabilities: event.capabilities, diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift index 88bc7e3703..fc95fa88d9 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift @@ -304,6 +304,9 @@ extension AppModel { return } let departure = recordsHistory ? currentEditorNavigationLocation() : nil + if openFromPluginContentProvider( + location, recordsHistory: recordsHistory, departure: departure, onFailure: onFailure + ) { return } let providerID = location.virtualProviderID ?? virtualDocumentProviderIDs[location.url] ?? services.pluginCatalog.languageSupport(forVirtualDocumentURL: location.url)?.declaration.id diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift index 92c6fb3d32..e0c2754c6e 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift @@ -31,6 +31,7 @@ extension AppModel { func bindLanguageIntelligenceCapability(_ capability: LanguageIntelligenceCapability) { languageToolingFeature.bindProjectPreparation(capability.sessions) + bindPluginLanguageServers(capability.sessions.pluginServers) cacheModuleCapability( capability, id: .languageIntelligence, diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginContentProviders.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginContentProviders.swift new file mode 100644 index 0000000000..b557329c6d --- /dev/null +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginContentProviders.swift @@ -0,0 +1,81 @@ +import Foundation +import LitheCoreContracts + +// Note: 插件自有语言服务器会话与宿主方法的决策见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +extension AppModel { + /// How long a plugin backend may take to produce a document's text. + private static let pluginContentTimeout: Duration = .seconds(30) + + /// Opens `location` from the plugin content provider that serves its URI + /// scheme in this window (plan API-12). Returns false when no provider + /// does, so the caller falls through to the language server path. + func openFromPluginContentProvider( + _ location: EditorNavigationLocation, + recordsHistory: Bool, + departure: EditorNavigationLocation?, + onFailure: (() -> Void)? + ) -> Bool { + guard !location.url.isFileURL, let scheme = location.url.scheme?.lowercased(), + let context = pluginWebWorkspaceContext, + let providers = services.pluginContentProviders, + let provider = providers.provider(forScheme: scheme, context: context), + let backends = pluginWebBackends else { return false } + Task { @MainActor [weak self] in + do { + let text = try await Self.pluginContent(of: location.url, from: provider, context: context, backends: backends, providers: providers) + // The window may have moved on while the plugin was working. + guard let self, self.pluginWebWorkspaceContext == context, + providers.provider(forScheme: scheme, context: context) == provider else { return } + self.showPluginContent(text, at: location, recordsHistory: recordsHistory, departure: departure) + // log-exempt: 用户取消:窗口关闭或调用方取消时不代表读取失败 + } catch is CancellationError { + return + } catch { + onFailure?() + self?.showNotification( + error.localizedDescription, + logReference: self?.notificationFailure(error, operation: "plugin_content_provider") + ) + } + } + return true + } + + /// Asks the provider's function for the document and has Core check the answer. + private static func pluginContent( + of url: URL, + from provider: PluginContentProviderRegistration, + context: PluginWorkspaceContextReference, + backends: any PluginBackendRequesting, + providers: PluginContentProviderHostService + ) async throws -> String { + let answer = try await backends.invokePluginFunction( + provider.functionID, + params: .object(["uri": .string(url.absoluteString)]), + ofPlugin: provider.pluginID, + context: context, + timeout: pluginContentTimeout, + progress: { _ in } + ) + return try providers.content(of: answer) + } + + /// Opens the text read-only and moves to the target, like any virtual document. + private func showPluginContent( + _ text: String, + at location: EditorNavigationLocation, + recordsHistory: Bool, + departure: EditorNavigationLocation? + ) { + if recordsHistory { navigationHistoryFeature.recordJump(from: departure, to: location) } + editorTabOrderFeature.repositoryDiffSelected = false + documentFeature.openVirtualDocument(location.url, text: text, displayPath: location.displayPath) + editorNavigationTarget = EditorNavigationTarget( + url: location.url.standardizedFileURL, + line: location.line, + utf16Column: location.utf16Column, + selectsWholeLine: location.selectsWholeLine + ) + } +} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift index 47eb89735e..e4d8b77e3d 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift @@ -32,6 +32,8 @@ extension AppModel: PluginHostWindowPort { var hostMessages: PluginHostMessageFeatureModel { featureGraph.pluginMessages } + var hostLanguageServers: (any PluginLanguageServerRouting)? { languageToolingSessionsIfActive } + func hostDocumentState(at url: URL, flushingEditor: Bool) async -> PluginHostDocumentState? { guard currentWorkspaceIdentity != nil else { return nil } let normalized = url.standardizedFileURL diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginLanguageServers.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginLanguageServers.swift new file mode 100644 index 0000000000..4a61468d0e --- /dev/null +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginLanguageServers.swift @@ -0,0 +1,51 @@ +import Foundation +import LitheCoreContracts +import LitheLanguageIntelligenceModule + +// Note: 插件自有语言服务器会话与宿主方法的决策见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +extension AppModel { + /// Delivers what happens to plugin-owned language servers to the owning + /// plugin's backend: the server's state changes and the notifications its + /// manifest forwards (plan API-25). The backend names this window by its + /// workspace context, so one backend can serve several windows. + func bindPluginLanguageServers(_ relay: PluginLanguageServerRelay) { + relay.onStateChange = { [weak self] change in + self?.notifyPluginBackend( + pluginID: change.pluginID, + method: "lithe/host/languageServer/didChangeState", + members: [ + "serverID": .string(change.serverID), + "state": .string(change.state.rawValue), + "generation": .integer(change.generation), + ] + ) + } + relay.onNotification = { [weak self] received in + var members: [String: ToolingJSONValue] = [ + "serverID": .string(received.serverID), + "generation": .integer(received.generation), + "method": .string(received.notification.method), + ] + if let params = received.notification.params { members["params"] = params } + if received.notification.truncated { members["truncated"] = .bool(true) } + self?.notifyPluginBackend( + pluginID: received.pluginID, + method: "lithe/host/languageServer/didReceiveNotification", + members: members + ) + } + } + + private func notifyPluginBackend(pluginID: String, method: String, members: [String: ToolingJSONValue]) { + guard let context = pluginWebWorkspaceContext else { return } + var params = members + params["context"] = .object([ + "contextID": .string(context.contextID), + "generation": .integer(context.generation), + ]) + services.pluginBackendActivation?.notifyLanguageServer( + pluginID: pluginID, method: method, params: .object(params) + ) + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift index d5d8ec94c3..1fb4dec7f3 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift @@ -220,6 +220,12 @@ final class MacServiceContainer { try logStore?.pluginFilesDirectory(pluginID: pluginID) } ) + // What the plugins' language servers keep per workspace: pruned by + // each plugin's own retention, and discarded on the user's request. + let pluginWorkspaceState = MacPluginLanguageServerWorkspaceState( + directories: MacPluginStateDirectories(fileStorage: fileStorage), + planner: declarativePluginOperations + ) let debugExecutableResolver = MacPluginDebugExecutableResolver( planner: declarativePluginOperations, settings: pluginSettings @@ -471,9 +477,12 @@ final class MacServiceContainer { hostDispatcher.register(workspaceHost) hostDispatcher.register(PluginDocumentHostService(contexts: .shared)) hostDispatcher.register(PluginTerminalHostService(contexts: .shared, metadata: workspaceHost)) + hostDispatcher.register(PluginLanguageServerHostService(contexts: .shared)) let editorActions = PluginEditorActionHostService( contexts: .shared, decoder: declarativePluginOperations, host: .macOS) hostDispatcher.register(editorActions) + let contentProviders = PluginContentProviderHostService(contexts: .shared, decoder: declarativePluginOperations) + hostDispatcher.register(contentProviders) let editorProviders = PluginEditorProviderHostService( contexts: .shared, decoder: declarativePluginOperations, host: .macOS, logSink: logSink) hostDispatcher.register(editorProviders) @@ -510,6 +519,7 @@ final class MacServiceContainer { hostDispatcher: hostDispatcher ) sessions.editorActions = editorActions + sessions.contentProviders = contentProviders sessions.editorProviders = editorProviders sessions.onActivationFailure = { pluginID, error in if let plugin = LogSegment(pluginID) { logSink?.emit(PluginsBackendActivationFailed(error: error, plugin: plugin)) } @@ -569,6 +579,14 @@ final class MacServiceContainer { settingsStore: MacLanguageToolSettingsStore(store: store), versionChecker: declarativePluginOperations ) + // Servers whose plugin backend names the process each + // start; the preparer asks that backend, so it shares + // the application's backends. + let backendLaunches = MacPluginBackendLaunchPreparer( + backends: pluginBackends, contexts: .shared, resolver: pluginLaunchResolver, + tools: providerTools, runtime: runtimeService, core: rustCore, + workspaceState: pluginWorkspaceState + ) let runtimeFactory = StdioLanguageProviderRuntimeFactory( runtimeService: runtimeService, languageServerCore: rustCore, @@ -585,6 +603,9 @@ final class MacServiceContainer { tools: providerTools, versionChecker: declarativePluginOperations) }, core: rustCore, processRegistry: processRegistry, pluginID: descriptor.launchSource?.pluginID, role: .languageServer) }, + backendLaunchPreparer: { source, root in + try await backendLaunches.prepare(source, workspaceURL: root) + }, processRegistry: processRegistry ) let runtimes = languagePackDefinitions.packs @@ -620,6 +641,13 @@ final class MacServiceContainer { }, workspaceStateResetter: { descriptor, workspaceRootURL, fingerprint in guard !remoteWorkspaces.contains(workspaceRootURL) else { throw CocoaError(.featureUnsupported) } + // A server without a native integration keeps its + // state where the host created it for the plugin. + if let launch = descriptor.languageServerLaunch, launch.hostIntegrationID == nil, + let source = launch.launchSource { + try pluginWorkspaceState.reset(source, workspaceRootURL: workspaceRootURL) + return + } try languageServerHostIntegrations.resetWorkspaceState( for: descriptor, workspaceRootURL: workspaceRootURL, @@ -1221,6 +1249,7 @@ final class MacServiceContainer { } } services.pluginEditorActions = pluginBackends.editorActions + services.pluginContentProviders = pluginBackends.contentProviders services.pluginEditorProviders = pluginBackends.editorProviders services.pluginEditorLanguages = MacPluginEditorLanguages( launchRegistered: pluginStartup.registeredPlugins, @@ -1477,7 +1506,9 @@ final class MacServiceContainer { pluginID: descriptor.id.rawValue, languageID: server.languageID, manifest: descriptor.normalizedManifest, - packageURL: installed.packageURL + packageURL: installed.packageURL, + resolvesLaunchWithBackend: server.backendLaunch != nil, + stateRetention: server.stateRetention ) : nil // An unexpandable probe is left empty, so the server is found diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift new file mode 100644 index 0000000000..824814f95e --- /dev/null +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift @@ -0,0 +1,169 @@ +import Foundation +import LitheCoreContracts +import LitheLanguageIntelligenceModule +import LitheModuleAPI + +// Note: 插件自有语言服务器会话与后端决定启动方式见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +/// Prepares the process of a plugin-owned language server whose plugin +/// backend decides what to start (`serverProcess` 3). Two steps surround the +/// backend call, and Rust Core does both: it builds the question, and it +/// bounds and checks the answer. This class only moves them between the +/// plugin's backend, the file system and the tool resolver. +/// +/// The scratch directory of one start lives in the temporary area. The +/// returned `release` removes it once the process ends, and a failed start +/// removes it here, so no start leaves files behind. Nothing is written +/// into the app bundle or the plugin package. +@MainActor +final class MacPluginBackendLaunchPreparer { + enum PrepareError: LocalizedError, Equatable { + case workspaceNotOpen + case toolRunsProjectCode(String) + + var errorDescription: String? { + switch self { + case .workspaceNotOpen: + L10n.string("No open window shows this workspace, so the plugin cannot choose how to start its language server.") + case .toolRunsProjectCode(let tool): + L10n.string("\(tool) resolves to a program inside the project, which a language server cannot start.") + } + } + } + + private let backends: any PluginBackendRequesting + private let contexts: PluginWorkspaceContexts + private let resolver: MacPluginLanguageServerLaunchResolver + private let tools: any BuildToolResolving + private let runtime: any LanguageToolRuntimePort + private let core: any LanguageServerRuntimeCore + private let workspaceState: MacPluginLanguageServerWorkspaceState? + + init( + backends: any PluginBackendRequesting, + contexts: PluginWorkspaceContexts, + resolver: MacPluginLanguageServerLaunchResolver, + tools: any BuildToolResolving, + runtime: any LanguageToolRuntimePort, + core: any LanguageServerRuntimeCore, + workspaceState: MacPluginLanguageServerWorkspaceState? = nil + ) { + self.backends = backends + self.contexts = contexts + self.resolver = resolver + self.tools = tools + self.runtime = runtime + self.core = core + self.workspaceState = workspaceState + } + + func prepare( + _ source: DeclarativeLanguageServerLaunchSource, + workspaceURL: URL + ) async throws -> PreparedLanguageServerProcess { + guard let context = contexts.localContext(forFolder: workspaceURL) else { + throw PrepareError.workspaceNotOpen + } + let question = try resolver.backendLaunchQuestion(for: source, workspaceRootURL: workspaceURL) + maintainState(of: source, workspaceURL: workspaceURL) + do { + let process = try await decide(source, question: question, context: context) + let target = try await resolveTarget(of: process.program, workspaceURL: workspaceURL) + // The backend call and the tool lookup take time; a workspace + // that changed meanwhile must not start this process. + try ensureCurrent(context) + let scratch = question.scratchDirectory + return PreparedLanguageServerProcess( + executableURL: target.url, + environment: target.environment.merging(process.environment) { _, planned in planned }, + launch: process.launch, + core: core, + release: { Self.removeScratch(scratch) } + ) + } catch { + Self.removeScratch(question.scratchDirectory) + throw error + } + } + + /// Asks the plugin's backend and lets Rust Core check the answer. + private func decide( + _ source: DeclarativeLanguageServerLaunchSource, + question: MacPluginLanguageServerLaunchResolver.BackendLaunchQuestion, + context: PluginWorkspaceContext + ) async throws -> MacPluginLanguageServerLaunchResolver.BackendLaunchProcess { + let answer = try await backends.invokePluginFunction( + question.function, + params: .object(question.resolveParams), + ofPlugin: source.pluginID, + context: context.reference, + timeout: .milliseconds(question.timeoutMilliseconds), + progress: { _ in } + ) + try Task.checkCancellation() + try ensureCurrent(context) + return try resolver.backendLaunchProcess(for: source, question: question, answer: answer) + } + + /// The program to start and the environment the host gives it. + private struct Target { + let url: URL + let environment: [String: String] + } + + private func resolveTarget( + of program: MacPluginLanguageServerLaunchResolver.BackendLaunchProcess.Program, + workspaceURL: URL + ) async throws -> Target { + switch program { + case .file(let url): + return Target(url: url, environment: runtime.languageToolProcessEnvironment()) + case .tool(let tool): + return try await resolveTool(tool, workspaceURL: workspaceURL) + } + } + + /// A tool of the plugin's own definitions, found the way every other + /// plugin tool is: the user's choice, then discovery. A program inside + /// the project is refused, since opening a project must not run it. + private func resolveTool(_ tool: String, workspaceURL: URL) async throws -> Target { + let resolved = try await tools.resolve( + BuildInvocation(executables: [.toolchain(id: tool, root: ".")]), + displayName: tool, + workspaceURL: workspaceURL, + checkVersion: { _, _ in BuildVersionCheck(satisfied: true, version: nil) } + ) + guard !resolved.executesProjectCode else { + throw PrepareError.toolRunsProjectCode(tool) + } + return Target(url: resolved.executableURL, environment: resolved.environment) + } + + /// Marks this workspace's state as used and deletes the state of + /// workspaces the plugin's retention lets go. Removing an old index can + /// take long, so it runs in the background and never delays the start. It + /// only frees disk space, so a failure does not stop the server either. + private func maintainState(of source: DeclarativeLanguageServerLaunchSource, workspaceURL: URL) { + guard let workspaceState else { return } + let open = contexts.contexts + .filter { $0.authority == .local } + .flatMap { $0.folders.map(\.localURL) } + [workspaceURL] + Task.detached(priority: .utility) { + do { + try workspaceState.markUsed(source, workspaceRootURL: workspaceURL) + try workspaceState.prune(source, openWorkspaceURLs: open) + } catch { + // log-exempt: 状态清理只回收磁盘空间,失败不影响本次启动,下次启动会重新清理 + } + } + } + + private func ensureCurrent(_ context: PluginWorkspaceContext) throws { + guard case .success = contexts.resolve(context.reference) else { throw CancellationError() } + } + + private nonisolated static func removeScratch(_ directory: URL) { + // log-exempt: 临时目录位于系统临时区,删不掉只占用磁盘,系统会自行回收 + try? FileManager.default.removeItem(at: directory) + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift index ee4bfe2e50..b4dea48ae3 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 contentProviders: PluginContentProviderHostService? var editorProviders: PluginEditorProviderHostService? var onActivationFailure: (@MainActor (_ pluginID: String, _ error: Error) -> Void)? private static let maximumBackgroundStarts = 2 @@ -487,6 +488,16 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi } } + /// Tells a running backend about a language server its plugin owns. + /// Core refuses these notifications to a session without a + /// `languageServer` method grant, and a refused notification stops the + /// backend, so they are only sent to one that holds one. + func notifyLanguageServer(pluginID: String, method: String, params: ToolingJSONValue) { + guard let entry = running[pluginID], + entry.hostServices.contains(where: { $0.hasPrefix("lithe/host/languageServer/") }) else { return } + notify(pluginID: pluginID, method: method, params: params) + } + /// Sends a host notification to the plugin's running backend, after the /// ones sent before it. A backend that is not running, or negotiated a /// protocol without the notification, does not receive it. @@ -751,6 +762,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?.contentProviders?.updateFunctions(pluginID: pluginID, sessionID: sessionToken, ids: ids) self?.editorProviders?.updateFunctions(pluginID: pluginID, sessionID: sessionToken, ids: ids) } session.onHostRequest = { [weak session] request in diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift index b0afe56e03..abaf66bc66 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift @@ -11,14 +11,33 @@ import LitheLanguageIntelligenceModule /// read-only, and is removed with the plugin that owns it. struct MacPluginStateDirectories: Sendable { let rootURL: URL + /// Holds the scratch directory of each start of a backend-launched + /// server. Scratch files are disposable, so they live in the temporary + /// area, not beside the state a plugin keeps. + let temporaryRootURL: URL - init(rootURL: URL) { + init(rootURL: URL, temporaryRootURL: URL? = nil) { self.rootURL = rootURL.standardizedFileURL + self.temporaryRootURL = (temporaryRootURL ?? Self.defaultTemporaryRoot(FileManager.default.temporaryDirectory)) + .standardizedFileURL } init(fileStorage: any FileStorage) { - self.init(rootURL: fileStorage.applicationSupportDirectory() - .appendingPathComponent("Lithe/PluginState", isDirectory: true)) + self.init( + rootURL: fileStorage.applicationSupportDirectory() + .appendingPathComponent("Lithe/PluginState", isDirectory: true), + temporaryRootURL: Self.defaultTemporaryRoot(fileStorage.temporaryDirectory()) + ) + } + + private static func defaultTemporaryRoot(_ temporaryDirectory: URL) -> URL { + temporaryDirectory.appendingPathComponent("lithe-plugin-launch", isDirectory: true) + } + + /// `${temporaryDirectory}` of one start of a backend-launched server: a + /// fresh directory whose owner removes it when the process ends. + func launchScratchDirectory() -> URL { + temporaryRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) } /// Everything the plugin's servers have written, for every language. @@ -31,11 +50,16 @@ struct MacPluginStateDirectories: Sendable { pluginDirectory(pluginID: pluginID).appendingPathComponent(languageID, isDirectory: true) } + /// Holds one `${workspaceStateDir}` per workspace of one language server. + func workspaceStatesDirectory(pluginID: String, languageID: String) -> URL { + stateDirectory(pluginID: pluginID, languageID: languageID) + .appendingPathComponent("workspaces", isDirectory: true) + } + /// `${workspaceStateDir}`: keyed by the workspace root so two projects /// never share an index, without putting the user's path in a file name. func workspaceStateDirectory(pluginID: String, languageID: String, workspaceRootURL: URL) -> URL { - stateDirectory(pluginID: pluginID, languageID: languageID) - .appendingPathComponent("workspaces", isDirectory: true) + workspaceStatesDirectory(pluginID: pluginID, languageID: languageID) .appendingPathComponent(Self.workspaceDigest(workspaceRootURL), isDirectory: true) } @@ -174,10 +198,123 @@ struct MacPluginLanguageServerLaunchResolver { return ResolvedLanguageServerLaunch( arguments: plan.arguments, initializationOptions: plan.initializationOptions, - workspaceConfiguration: plan.workspaceConfiguration + workspaceConfiguration: plan.workspaceConfiguration, + sessionPolicy: plan.sessionPolicy + ) + } + + // MARK: Backend-resolved launches (`serverProcess` 3) + + /// The first step of a launch the plugin's backend decides: what to ask + /// the backend, with the directories this start owns. The second step + /// needs the same request, so the question carries it. + struct BackendLaunchQuestion: Equatable { + let function: String + let timeoutMilliseconds: Int + /// Params of the function; the host adds the workspace `context`. + let resolveParams: [String: ToolingJSONValue] + /// Removed by the owner of the process once it ends. + let scratchDirectory: URL + let request: DeclarativeLanguageServerLaunchRequest + } + + /// What the backend's answer asks the host to start, after Core bounded + /// it and the package paths were verified. + struct BackendLaunchProcess: Equatable { + enum Program: Equatable { + /// A runnable file inside the plugin package. + case file(URL) + /// A tool definition of the plugin, resolved by the host. + case tool(String) + } + + let program: Program + let environment: [String: String] + let launch: ResolvedLanguageServerLaunch + } + + func backendLaunchQuestion( + for source: DeclarativeLanguageServerLaunchSource, + workspaceRootURL: URL + ) throws -> BackendLaunchQuestion { + let scratch = directories.launchScratchDirectory() + let request = request(for: source, workspaceRootURL: workspaceRootURL, temporaryDirectory: scratch) + do { + let plan = try planner.languageServerLaunchPlan( + manifest: source.manifest, languageID: source.languageID, request: request + ) + guard let resolution = plan.backendResolution else { + throw DeclarativePluginRejection( + code: "plugin.launch.notBackend", + message: "Rust Core returned a launch plan without a question for the plugin backend." + ) + } + try createRequiredDirectories(of: plan, request: request) + return BackendLaunchQuestion( + function: resolution.function, + timeoutMilliseconds: resolution.timeoutMilliseconds, + resolveParams: resolution.resolveParams, + scratchDirectory: scratch, + request: request + ) + } catch { + // The caller gets no question to clean up after, so the + // directory the plan may already have created goes here. + // log-exempt: 清理只是尽力而为,调用方要处理的是上面抛出的原始错误 + try? fileManager.removeItem(at: scratch) + throw error + } + } + + /// Has Rust Core check the backend's answer, then verifies the files it + /// names and creates the parents of the paths the process writes. + func backendLaunchProcess( + for source: DeclarativeLanguageServerLaunchSource, + question: BackendLaunchQuestion, + answer: ToolingJSONValue + ) throws -> BackendLaunchProcess { + let plan = try planner.decodeLaunch( + manifest: source.manifest, languageID: source.languageID, request: question.request, result: answer + ) + guard let resolved = plan.resolvedLaunch else { + throw DeclarativePluginRejection( + code: "plugin.launch.invalidResult", + message: "Rust Core returned a decoded launch without a program." + ) + } + let program = try backendProgram(resolved.program, packageURL: source.packageURL) + for path in resolved.writablePaths { + try fileManager.createDirectory( + at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true + ) + } + return BackendLaunchProcess( + program: program, + environment: resolved.environment, + launch: ResolvedLanguageServerLaunch( + arguments: plan.arguments, + initializationOptions: plan.initializationOptions, + workspaceConfiguration: plan.workspaceConfiguration, + sessionPolicy: plan.sessionPolicy + ) ) } + /// A packaged program must be a runnable file inside the package; a tool + /// is only a name here, because the host resolves it later. + private func backendProgram( + _ program: DeclarativeLanguageServerLaunchPlan.ResolvedLaunch.Program, + packageURL: URL + ) throws -> BackendLaunchProcess.Program { + switch program { + case .packaged(let path): + let file = try packagedExecutable(path, packageURL: packageURL.standardizedFileURL) + return .file(file) + case .tool(let tool): + return .tool(tool) + } + } + /// How a build system's provider answers, after Core expanded its launch. enum BuildProviderLaunch: Equatable { /// The language server of the same plugin answers; no process starts. @@ -536,7 +673,8 @@ struct MacPluginLanguageServerLaunchResolver { private func request( for source: DeclarativeLanguageServerLaunchSource, - workspaceRootURL: URL + workspaceRootURL: URL, + temporaryDirectory: URL? = nil ) -> DeclarativeLanguageServerLaunchRequest { DeclarativeLanguageServerLaunchRequest( pluginDirectory: source.packageURL.standardizedFileURL, @@ -554,7 +692,8 @@ struct MacPluginLanguageServerLaunchResolver { projectSettings: settings.projectValues(forPlugin: source.pluginID, projectRoot: workspaceRootURL), // Log storage is optional unless the template requires it. Core // rejects a missing logDirectory only for a launch using ${logDir}. - logDirectory: try? logDirectory(source.pluginID) + logDirectory: try? logDirectory(source.pluginID), + temporaryDirectory: temporaryDirectory ) } @@ -570,6 +709,7 @@ struct MacPluginLanguageServerLaunchResolver { case .log: request.logDirectory case .state: request.stateDirectory case .workspaceState: request.workspaceStateDirectory + case .temporary: request.temporaryDirectory } guard let url else { throw DeclarativePluginRejection( diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerWorkspaceState.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerWorkspaceState.swift new file mode 100644 index 0000000000..32049a83d9 --- /dev/null +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerWorkspaceState.swift @@ -0,0 +1,95 @@ +import Foundation +import LitheCoreContracts + +// Note: 插件自有语言服务器会话与后端决定启动方式见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +/// The per-workspace state of a plugin-owned language server (plan API-20). +/// The server writes into the `${workspaceStateDir}` the host created for the +/// workspace; this type keeps those directories bounded and lets the user +/// discard one. +/// +/// Rust Core decides which directories to delete from the plugin's declared +/// retention; this type only lists what is on disk, hands Core the facts, and +/// removes the names Core returns. It touches nothing outside the host's own +/// plugin state area: never the app bundle, a plugin package, or a project. +struct MacPluginLanguageServerWorkspaceState: Sendable { + private let directories: MacPluginStateDirectories + private let planner: any DeclarativeLanguageServerLaunchPlanning + private let now: @Sendable () -> Date + + init( + directories: MacPluginStateDirectories, + planner: any DeclarativeLanguageServerLaunchPlanning, + now: @escaping @Sendable () -> Date = { Date() } + ) { + self.directories = directories + self.planner = planner + self.now = now + } + + /// Records that the server starts for this workspace now. A directory's + /// own modification time is the only "last used" the host can see, and + /// the server writes deeper than that, so each start refreshes it. + func markUsed(_ source: DeclarativeLanguageServerLaunchSource, workspaceRootURL: URL) throws { + let directory = workspaceDirectory(of: source, workspaceRootURL: workspaceRootURL) + guard FileManager.default.fileExists(atPath: directory.path) else { return } + try FileManager.default.setAttributes([.modificationDate: now()], ofItemAtPath: directory.path) + } + + /// Deletes the workspaces' state the plugin's retention says to drop and + /// returns their names. A workspace in `openWorkspaceURLs` is never + /// deleted; a plugin that declares no retention keeps everything. + @discardableResult + func prune( + _ source: DeclarativeLanguageServerLaunchSource, + openWorkspaceURLs: [URL] + ) throws -> [String] { + guard let retention = source.stateRetention else { return [] } + let parent = directories.workspaceStatesDirectory(pluginID: source.pluginID, languageID: source.languageID) + let entries = try observedEntries(in: parent) + guard !entries.isEmpty else { return [] } + let expired = try planner.expiredLanguageServerStateNames( + retention: retention, + nowUnixSeconds: max(0, Int(now().timeIntervalSince1970)), + entries: entries, + activeNames: openWorkspaceURLs.map(MacPluginStateDirectories.workspaceDigest) + ) + // Only a directory this call listed is deleted, whatever Core names. + let listed = Set(entries.map(\.name)) + let removable = expired.filter(listed.contains) + for name in removable { + try FileManager.default.removeItem(at: parent.appendingPathComponent(name, isDirectory: true)) + } + return removable + } + + /// Discards the state of one workspace. The server rebuilds it the next + /// time it starts; the host recreates the directory then. + func reset(_ source: DeclarativeLanguageServerLaunchSource, workspaceRootURL: URL) throws { + let directory = workspaceDirectory(of: source, workspaceRootURL: workspaceRootURL) + guard FileManager.default.fileExists(atPath: directory.path) else { return } + try FileManager.default.removeItem(at: directory) + } + + private func workspaceDirectory(of source: DeclarativeLanguageServerLaunchSource, workspaceRootURL: URL) -> URL { + directories.workspaceStateDirectory( + pluginID: source.pluginID, languageID: source.languageID, workspaceRootURL: workspaceRootURL + ) + } + + /// The real directories under `parent` and when each was last used. A + /// file or a link is not state the host created, so it is not listed. + private func observedEntries(in parent: URL) throws -> [LanguageServerStateEntry] { + guard FileManager.default.fileExists(atPath: parent.path) else { return [] } + let keys: Set = [.isDirectoryKey, .isSymbolicLinkKey, .contentModificationDateKey] + let children = try FileManager.default.contentsOfDirectory(at: parent, includingPropertiesForKeys: Array(keys), options: []) + return try children.compactMap { child -> LanguageServerStateEntry? in + let values = try child.resourceValues(forKeys: keys) + guard values.isDirectory == true, values.isSymbolicLink != true, + let modified = values.contentModificationDate else { return nil } + return LanguageServerStateEntry( + name: child.lastPathComponent, lastModifiedUnixSeconds: max(0, Int(modified.timeIntervalSince1970)) + ) + } + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift index 1773db3f73..e6cf1dd06b 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift @@ -172,10 +172,12 @@ final class MacPluginManager: PluginManaging { switch server.launch { case .packaged, .systemCommand: executableNames = server.executableNames - case .runtime: - // A runtime such as java/node is not the server's name. Reuse the - // descriptive launch metadata already associated with this language; - // it supplies a name only after the enabled plugin supplies the row. + case .runtime, .backend: + // A runtime such as java/node is not the server's name, and a + // backend names its executable only when the server starts. Reuse + // the descriptive launch metadata already associated with this + // language; it supplies a name only after the enabled plugin + // supplies the row. executableNames = catalog.descriptors.first { $0.id == server.languageID }? .languageServerLaunch?.executableNames ?? [] } diff --git a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift index 57d264e1ea..08722d0b56 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift @@ -165,7 +165,9 @@ final class MacRemotePluginLaunchPreparer { switch directory { case .state: url = state case .workspaceState: url = workspaceState - case .log: throw CocoaError(.featureUnsupported) + // A remote workspace never runs a plugin-resolved launch, which + // is the only one that asks for log or scratch directories. + case .log, .temporary: throw CocoaError(.featureUnsupported) } _ = try await host.pluginRequest("fs.createDir", params: .object([ "path": .string(url.path), "recursive": .bool(true), "mode": .integer(0o700)]), session: binding.sessionID) diff --git a/macos/Sources/Lithe/Views/App/PluginDetailView.swift b/macos/Sources/Lithe/Views/App/PluginDetailView.swift index 7cf20e5970..d0cb999055 100644 --- a/macos/Sources/Lithe/Views/App/PluginDetailView.swift +++ b/macos/Sources/Lithe/Views/App/PluginDetailView.swift @@ -508,6 +508,7 @@ struct PluginDetailView: View { String(format: localized(packagedRuntime ? "Runs on %@ shipped with the plugin" : "Runs on %@ installed on this Mac"), tool) case .systemServer(let commands): String(format: localized("Installed on this Mac: %@"), commands.joined(separator: " | ")) + case .backendServer: localized("Started by the plugin") case .hostIntegration: localized("Provided by Lithe for this language") case .tasks(let count): String(format: localized("Tasks: %d"), count) } diff --git a/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift b/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift index 88daaa7041..ac95833389 100644 --- a/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift +++ b/macos/Sources/Lithe/Views/App/PluginMarketplaceView.swift @@ -771,6 +771,10 @@ enum PluginMarketplacePresentation { 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 "languageServer.request": + L10n.string("Send requests and commands to its language server for your project") + case "documents.contentProvider": + L10n.string("Supply the text of read-only documents it opens in the editor") case "keymaps.provide": L10n.string("Offer shortcut mappings for import") case "keymaps.readSelectedSources": @@ -816,6 +820,13 @@ enum PluginMarketplacePresentation { String(format: localized("%@ language server (installed on this Mac)", locale: locale), language), serverDetail([program.commands.joined(separator: " | ")]) ) + case .backendLanguageServer: + // The command line is the plugin's to choose at every start, so + // the approval shows who chooses it, not a fixed command. + return ( + String(format: localized("%@ language server (started by the plugin)", locale: locale), language), + labeled("Command chosen by: %@", [program.function ?? ""]) + ) case .runtime: return ( localized("Runtime used by the language server (installed on this Mac)", locale: locale), diff --git a/macos/Sources/Lithe/Views/Workbench/PluginServerStatusView.swift b/macos/Sources/Lithe/Views/Workbench/PluginServerStatusView.swift new file mode 100644 index 0000000000..25030bbdff --- /dev/null +++ b/macos/Sources/Lithe/Views/Workbench/PluginServerStatusView.swift @@ -0,0 +1,64 @@ +import SwiftUI +import LitheLanguageIntelligenceModule +import LitheModuleAPI + +// Note: 插件自有语言服务器会话与后端决定启动方式见 .agents/notes/implemented/architecture/2026-11-04-plugin-owned-language-server-sessions.md + +/// How far the plugin-owned language servers say they are from usable. A +/// server that reports `ready` shows nothing; one that is preparing, limited +/// or failed shows the plugin's own text, because only the plugin knows what +/// it is waiting for. The host adds no wording about any language or tool. +struct PluginServerStatusView: View { + @EnvironmentObject private var model: AppModel + + var body: some View { + PluginServerStatusContent(feature: model.languageToolingFeature) + } +} + +private struct PluginServerStatusContent: View { + /// Observed so that a language change redraws the fallback texts. + @EnvironmentObject private var settings: AppSettings + @ObservedObject var feature: LanguageToolingFeatureModel + + /// The servers that are not ready, in a stable order. + private var pending: [(serverID: String, status: PluginServerStatus)] { + feature.pluginServerStatuses + .filter { $0.value.state != .ready } + .sorted { $0.key < $1.key } + .map { (serverID: $0.key, status: $0.value) } + } + + var body: some View { + if let first = pending.first { + HStack(spacing: 6) { + if first.status.state == .preparing { + ProgressView().controlSize(.mini) + } else { + Image(systemName: "exclamationmark.triangle") + } + Text(verbatim: text(for: first.status)).lineLimit(1) + } + .font(LitheTheme.uiFont(size: 11)) + .help(pending.map { text(for: $0.status) }.joined(separator: "\n")) + } + } + + /// The plugin's message, or a neutral sentence when it sent none. + private func text(for status: PluginServerStatus) -> String { + let base = status.message.flatMap { $0.isEmpty ? nil : $0 } ?? fallback(for: status.state) + guard let percentage = status.percentage else { return base } + return "\(base) \(percentage)%" + } + + private func fallback(for state: PluginServerStatus.State) -> String { + switch state { + case .preparing, .ready: + L10n.string("Preparing the language server") + case .degraded: + L10n.string("The language server runs with limited features") + case .failed: + L10n.string("The language server could not get ready") + } + } +} diff --git a/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift b/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift index cb2e1d54b1..7d1c034914 100644 --- a/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift +++ b/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift @@ -1829,6 +1829,7 @@ struct WorkbenchView: View { model.activeDocument?.isReadOnly == true ? "Read-only document" : "Save" )) ProjectPreparationStatusView(compact: true) + PluginServerStatusView() LanguageServerStatusView() MemoryUsageStatusView() FrameRateStatusView() @@ -1840,6 +1841,7 @@ struct WorkbenchView: View { HStack(spacing: 10) { EditorCaretPositionLabel(chrome: model.editorChrome) { model.showGoToLine() } ProjectPreparationStatusView(compact: true) + PluginServerStatusView() LanguageServerStatusView() MemoryUsageStatusView() FrameRateStatusView() diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift index 6ebecd959f..c319b57ec9 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift @@ -215,6 +215,9 @@ package struct LanguageServerRuntimeError: Equatable, Sendable { /// Plugin-defined code of a failed plugin function, for the plugin's own /// UI only; the host never branches on it. package let pluginErrorCode: String? + /// Structured facts of a failed plugin-server request. They travel to the + /// calling backend unchanged as the failure's details. + package let details: ToolingJSONValue? package init( code: String, @@ -223,7 +226,8 @@ package struct LanguageServerRuntimeError: Equatable, Sendable { underlyingMessage: String?, processExitCode: Int?, javaBuildReport: JavaBuildReport? = nil, - pluginErrorCode: String? = nil + pluginErrorCode: String? = nil, + details: ToolingJSONValue? = nil ) { self.code = code self.stage = stage @@ -232,6 +236,7 @@ package struct LanguageServerRuntimeError: Equatable, Sendable { self.processExitCode = processExitCode self.javaBuildReport = javaBuildReport self.pluginErrorCode = pluginErrorCode + self.details = details } } @@ -584,6 +589,27 @@ package protocol LanguageServerRuntimeCore: Sendable { requestTimeout: TimeInterval, shutdownTimeout: TimeInterval ) -> Result + /// Starts a plugin-owned server together with the policy that lets the + /// plugin's backend reach it through the host (plan API-25). Core enforces + /// `sessionPolicy`: the requests the backend may send, the gates they wait + /// for and the server notifications it receives. + func startPluginLanguageServer( + pluginID: String, + providerID: String, + executableURL: URL, + arguments: [String], + environment: [String: String], + rootURL: URL, + initializationOptions: ToolingJSONValue?, + workspaceConfiguration: ToolingJSONValue?, + sessionPolicy: ToolingJSONValue, + hostServices: [String], + cacheDirectoryURL: URL?, + workspaceFingerprint: String?, + initializeTimeout: TimeInterval, + requestTimeout: TimeInterval, + shutdownTimeout: TimeInterval + ) -> Result /// Starts a plugin backend that may request the host services named in /// `hostServices` (function protocol 2). Core checks every request /// against them before publishing a `hostRequest` event. @@ -648,6 +674,28 @@ package protocol LanguageServerRuntimeCore: Sendable { context: PluginWorkspaceContextReference?, timeout: TimeInterval ) -> Result + /// Sends one LSP request of a plugin backend to its own server + /// (`lsp.pluginServerRequest`). Core checks the plugin's whitelist and + /// gates; the outcome arrives as one `requestCompleted` event with the + /// server's result under `result.value`. `timeout` nil keeps Core's default. + func pluginServerRequest( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) -> Result + /// Sends one LSP notification of a plugin backend to its own server. + /// `true` when Core wrote it; `false` when the server is not initialized + /// yet and reads the stored configuration with `initialized` instead. + func pluginServerNotify( + sessionID: String, + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) -> Result func cancelLanguageServerOperation(sessionID: String, operationID: String) func pollLanguageServerEvents(sessionID: String) -> [LanguageServerRuntimeEvent] func destroyLanguageServer(sessionID: String) @@ -877,6 +925,34 @@ package extension LanguageServerRuntimeCore { ) } + /// Runtimes that cannot enforce a session policy start the process as a + /// plain plugin backend: without the policy, so the plugin's backend has + /// no route to the server, and without workspace configuration. + func startPluginLanguageServer( + pluginID: String, + providerID: String, + executableURL: URL, + arguments: [String], + environment: [String: String], + rootURL: URL, + initializationOptions: ToolingJSONValue?, + workspaceConfiguration _: ToolingJSONValue?, + sessionPolicy _: ToolingJSONValue, + hostServices: [String], + cacheDirectoryURL _: URL?, + workspaceFingerprint _: String?, + initializeTimeout: TimeInterval, + requestTimeout: TimeInterval, + shutdownTimeout: TimeInterval + ) -> Result { + startPluginLanguageServer( + pluginID: pluginID, providerID: providerID, executableURL: executableURL, arguments: arguments, + environment: environment, rootURL: rootURL, initializationOptions: initializationOptions, + hostServices: hostServices, + initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout + ) + } + /// Runtimes without plugin configuration support ignore it. func startPluginLanguageServer( pluginID: String, @@ -1010,6 +1086,33 @@ package extension LanguageServerRuntimeCore { message: "Plugin functions are not supported by this runtime." )) } + + func pluginServerRequest( + sessionID _: String, + pluginID _: String, + serverID _: String, + method _: String, + params _: ToolingJSONValue, + timeout _: TimeInterval? + ) -> Result { + .failure(LanguageServerRuntimeFailure( + code: "not_supported", + message: "Plugin language server requests are not supported by this runtime." + )) + } + + func pluginServerNotify( + sessionID _: String, + pluginID _: String, + serverID _: String, + method _: String, + params _: ToolingJSONValue + ) -> Result { + .failure(LanguageServerRuntimeFailure( + code: "not_supported", + message: "Plugin language server notifications are not supported by this runtime." + )) + } } /// A host-service request a plugin backend sent, after Core checked its @@ -1048,6 +1151,51 @@ package struct PluginHostRequestFailure: Error, Equatable, Sendable { } } +package extension PluginHostRequestFailure { + /// The backend's own server is not there to answer: stopped, still + /// starting, or never started with a session policy. + static let languageServerUnavailable = PluginHostRequestFailure( + message: "The language server is not running.", code: "plugin.host.languageServerUnavailable" + ) + + /// The server the backend named belongs to another plugin. A plugin may + /// only talk to the servers its own package declares. + static let foreignContribution = PluginHostRequestFailure( + message: "The language server belongs to another plugin.", code: "plugin.host.foreignContribution" + ) + + /// Core refused the call before it reached the server. Core puts the + /// stable `plugin.host.*` code in `details`; any other diagnostic there + /// never becomes the code the backend sees. + init(refusal failure: LanguageServerRuntimeFailure) { + let code = failure.details.flatMap { $0.hasPrefix("plugin.host.") ? $0 : nil } + self.init(message: failure.message, code: code ?? "plugin.host.languageServerUnavailable") + } + + /// The server's answer was an error. Core already mapped its code to a + /// `plugin.host.*` code and put the server's own `{ code, message }` in + /// `details`; the backend receives both unchanged. + init(completion error: LanguageServerRuntimeError, message: String) { + let code = error.code.hasPrefix("plugin.host.") ? error.code : "plugin.host.languageServerUnavailable" + self.init(message: message, code: code, details: error.details) + } +} + +/// A server notification Rust Core forwarded because the plugin's manifest +/// lists its method in `forwardNotifications`. `params` is nil when the +/// payload was too large; the backend then asks the server for the state. +package struct PluginServerNotification: Equatable, Sendable { + package let method: String + package let params: ToolingJSONValue? + package let truncated: Bool + + package init(method: String, params: ToolingJSONValue?, truncated: Bool) { + self.method = method + self.params = params + self.truncated = truncated + } +} + /// One generation of one workspace context, as a call or a host request /// names it (function protocol 3). Only the host decides whether it is /// still current. diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift index 7fb305b6f3..845023e501 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift @@ -852,6 +852,9 @@ package protocol LanguageServerSession: AnyObject { /// Sessions that never start a declarative process ignore it. func observePluginStartup(_ attempt: PluginOperationAttempt) var onProjectPreparation: ((ProjectPreparationSnapshot) -> Void)? { get set } + /// Called with each server notification Core forwards to the owning + /// plugin's backend (plan API-25). + var onPluginServerNotification: ((PluginServerNotification) -> Void)? { get set } var onMavenProfileTask: ((String) -> Void)? { get set } var onMavenProfileProject: ((MavenProfileProjectResult) -> Void)? { get set } var isRunning: Bool { get } @@ -1064,6 +1067,30 @@ package extension LanguageServerSession { @discardableResult func updateWorkspaceConfigurationAsync(_: ToolingJSONValue) async -> WorkspaceConfigurationUpdateResult { .failed } + /// Sends one request of the owning plugin's backend to this server. Core + /// checks the plugin's whitelist and gates before it reaches the server. + func requestPluginServer( + pluginID _: String, + serverID _: String, + method _: String, + params _: ToolingJSONValue, + timeout _: TimeInterval? + ) async -> Result { + .failure(.languageServerUnavailable) + } + + /// Sends one notification of the owning plugin's backend to this server. + /// `true` when it was written; `false` when the server is not initialized + /// yet and reads the stored configuration with `initialized` instead. + func notifyPluginServer( + pluginID _: String, + serverID _: String, + method _: String, + params _: ToolingJSONValue + ) async -> Result { + .failure(.languageServerUnavailable) + } + func buildRequest(method _: String, params _: ToolingJSONValue, timeout _: TimeInterval) async throws -> ToolingJSONValue { throw LanguageServerRuntimeFailure( @@ -1083,6 +1110,10 @@ package extension LanguageServerSession { get { nil } set {} } + var onPluginServerNotification: ((PluginServerNotification) -> Void)? { + get { nil } + set {} + } var onMavenProfileTask: ((String) -> Void)? { get { nil } set {} diff --git a/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift b/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift index 5437d5c478..b79ebc6105 100644 --- a/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift +++ b/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift @@ -44,6 +44,11 @@ public struct DeclarativeLanguageServer: Equatable, Sendable { /// runtime the plugin ships, for example `runtime/${arch}/bin/java`; /// `nil` means the host discovers the tool. case runtime(tool: String, entryRelativePath: String, packagedRuntime: String?) + /// The plugin's backend chooses the executable and arguments each + /// time the server starts (`serverProcess` 3). `function` is the + /// backend function the host calls; the host waits at most + /// `timeoutMilliseconds` for its answer. + case backend(function: String, timeoutMilliseconds: Int) } public let languageID: String @@ -60,6 +65,21 @@ public struct DeclarativeLanguageServer: Equatable, Sendable { /// enables that integration for this server instead of matching on its /// language ID. public let hostIntegrationID: String? + /// How long the server's per-workspace state is kept (`languageServers` + /// 3), or nil when the plugin declares none and the host keeps its own + /// bounds. + public let stateRetention: StateRetention? + + /// The bounds a plugin puts on the per-workspace state of its server. + public struct StateRetention: Hashable, Sendable { + public let maxEntries: Int + public let maxAgeDays: Int + + public init(maxEntries: Int, maxAgeDays: Int) { + self.maxEntries = maxEntries + self.maxAgeDays = maxAgeDays + } + } /// Tool of a runtime launch, such as `node`. The executable the host /// starts for this server is that runtime, and the server's own child @@ -86,6 +106,20 @@ public struct DeclarativeLanguageServer: Equatable, Sendable { // The runtime is the process the host starts; the entry file is // an argument of the expanded launch plan. [tool] + case .backend: + // The backend names the executable at start time, so there is + // nothing to look up or display beforehand. + [] + } + } + + /// The backend function and timeout of a server whose launch the plugin + /// resolves, or nil for every other launch. + public var backendLaunch: (function: String, timeoutMilliseconds: Int)? { + if case .backend(let function, let timeoutMilliseconds) = launch { + (function, timeoutMilliseconds) + } else { + nil } } } @@ -99,12 +133,27 @@ public struct DeclarativeLanguageServerLaunchSource: Hashable, Sendable { public let manifest: Data /// Root of the installed, read-only plugin package. public let packageURL: URL + /// True when the plugin's backend names the process at each start + /// (`serverProcess` 3), so the host has no executable to look up first. + public let resolvesLaunchWithBackend: Bool + /// How long the server's per-workspace state is kept, or nil when the + /// plugin declares no bounds and the host deletes nothing. + public let stateRetention: DeclarativeLanguageServer.StateRetention? - public init(pluginID: String, languageID: String, manifest: Data, packageURL: URL) { + public init( + pluginID: String, + languageID: String, + manifest: Data, + packageURL: URL, + resolvesLaunchWithBackend: Bool = false, + stateRetention: DeclarativeLanguageServer.StateRetention? = nil + ) { self.pluginID = pluginID self.languageID = languageID self.manifest = manifest self.packageURL = packageURL + self.resolvesLaunchWithBackend = resolvesLaunchWithBackend + self.stateRetention = stateRetention } } @@ -151,6 +200,9 @@ public struct DeclarativeLanguageServerLaunchRequest: Equatable, Sendable { public let settings: [String: ToolingJSONValue] /// The workspace's overrides of project-scoped settings. public let projectSettings: [String: ToolingJSONValue] + /// Scratch directory of one start of the server. Only a launch the + /// plugin backend resolves needs it; Core refuses that launch without. + public let temporaryDirectory: URL? public init( pluginDirectory: URL, @@ -159,8 +211,10 @@ public struct DeclarativeLanguageServerLaunchRequest: Equatable, Sendable { architecture: String, settings: [String: ToolingJSONValue] = [:], projectSettings: [String: ToolingJSONValue] = [:], - logDirectory: URL? = nil + logDirectory: URL? = nil, + temporaryDirectory: URL? = nil ) { + self.temporaryDirectory = temporaryDirectory self.logDirectory = logDirectory self.pluginDirectory = pluginDirectory self.stateDirectory = stateDirectory @@ -405,6 +459,7 @@ public struct DeclarativeLanguageServerLaunchPlan: Equatable, Sendable { case log case state case workspaceState + case temporary } public struct RuntimeRequirement: Equatable, Sendable { @@ -460,6 +515,52 @@ public struct DeclarativeLanguageServerLaunchPlan: Equatable, Sendable { public var backend: Backend? = nil /// Set when the plan was selected by debug adapter. public var debugAdapter: DebugAdapter? = nil + /// Set on the first step of a server whose backend resolves the launch. + public var backendResolution: BackendResolution? = nil + /// Set on the second step: what the backend's answer asks the host to + /// start, already checked by Rust Core. + public var resolvedLaunch: ResolvedLaunch? = nil + /// The session policy Rust Core enforces for a plugin-owned server, + /// passed to `lsp.startServer` unchanged. The host never reads it. + public var sessionPolicy: ToolingJSONValue? = nil + + /// The question of the first step: which backend function to call and + /// with what, before the host knows what to start (`serverProcess` 3). + public struct BackendResolution: Equatable, Sendable { + public let function: String + public let timeoutMilliseconds: Int + /// Params of the function apart from `context` and `tools`, which + /// the host attaches. + public let resolveParams: [String: ToolingJSONValue] + + public init(function: String, timeoutMilliseconds: Int, resolveParams: [String: ToolingJSONValue]) { + self.function = function + self.timeoutMilliseconds = timeoutMilliseconds + self.resolveParams = resolveParams + } + } + + /// The answer of the backend's launch function after Rust Core bounded + /// and checked it. + public struct ResolvedLaunch: Equatable, Sendable { + public enum Program: Equatable, Sendable { + /// File inside the plugin package, relative to its root. + case packaged(String) + /// One of the plugin's tool definitions; the host resolves it. + case tool(String) + } + + public let program: Program + public let environment: [String: String] + /// Absolute paths inside the host directories the process may write. + public let writablePaths: [String] + + public init(program: Program, environment: [String: String], writablePaths: [String]) { + self.program = program + self.environment = environment + self.writablePaths = writablePaths + } + } /// What the host needs besides the process: the identity the adapter /// registers under and the DAP `adapterID` its requests carry. @@ -689,7 +790,10 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { validationArguments: server.validationArguments, runtimeTools: server.runtimeDependencies.map(\.tool), expandsLaunchTemplates: decoded.pluginAPIVersion >= 2, - hostIntegrationID: server.hostIntegration?.id + hostIntegrationID: server.hostIntegration?.id, + stateRetention: server.state?.retention.map { + DeclarativeLanguageServer.StateRetention(maxEntries: $0.maxEntries, maxAgeDays: $0.maxAgeDays) + } ) } executionProviders = decoded.executionProviders.map { provider in @@ -919,6 +1023,10 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { && modules.allSatisfy { live.contains($0.manifest.id) && $0.contributions.isEmpty } } + /// How long the host waits for a backend launch function when the + /// manifest names no timeout; the same default Rust Core applies. + private static let defaultBackendLaunchTimeoutMilliseconds = 30_000 + private static func launch(_ launch: NormalizedManifest.Launch) -> DeclarativeLanguageServer.Launch { switch launch.kind { case "packaged": @@ -929,6 +1037,11 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { entryRelativePath: launch.entry ?? "", packagedRuntime: launch.packagedRuntime ) + case "backend": + .backend( + function: launch.function ?? "", + timeoutMilliseconds: launch.timeoutMilliseconds ?? Self.defaultBackendLaunchTimeoutMilliseconds + ) default: .systemCommand(launch.commands ?? []) } @@ -997,6 +1110,8 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { let tool: String? let entry: String? let packagedRuntime: String? + let function: String? + let timeoutMilliseconds: Int? } struct RuntimeDependency: Decodable { let tool: String @@ -1013,6 +1128,17 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { let validationArguments: [String] let runtimeDependencies: [RuntimeDependency] let hostIntegration: HostIntegration? + let state: SessionState? + + /// `state` of a plugin-owned session (`languageServers` 3). + struct SessionState: Decodable { + struct Retention: Decodable { + let maxEntries: Int + let maxAgeDays: Int + } + + let retention: Retention? + } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) @@ -1023,11 +1149,12 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { validationArguments = try values.decodeIfPresent([String].self, forKey: .validationArguments) ?? [] runtimeDependencies = try values.decodeIfPresent([RuntimeDependency].self, forKey: .runtimeDependencies) ?? [] hostIntegration = try values.decodeIfPresent(HostIntegration.self, forKey: .hostIntegration) + state = try values.decodeIfPresent(SessionState.self, forKey: .state) } private enum CodingKeys: String, CodingKey { case languageID, languageIdentifier, launch, arguments, validationArguments, runtimeDependencies - case hostIntegration + case hostIntegration, state } } struct Setting: Decodable { @@ -1681,6 +1808,23 @@ public protocol DeclarativeLanguageServerLaunchPlanning: Sendable { languageID: String, request: DeclarativeLanguageServerLaunchRequest ) throws -> DeclarativeLanguageServerLaunchPlan + /// The second step of a server whose backend resolves its launch: Rust + /// Core bounds and checks the backend function's answer and returns the + /// plan the host starts, with `resolvedLaunch` and `sessionPolicy` set. + func decodeLaunch( + manifest: Data, + languageID: String, + request: DeclarativeLanguageServerLaunchRequest, + result: ToolingJSONValue + ) throws -> DeclarativeLanguageServerLaunchPlan + /// Names of the per-workspace state directories of a server that its + /// retention bounds say to delete. Active directories are never named. + func expiredLanguageServerStateNames( + retention: DeclarativeLanguageServer.StateRetention, + nowUnixSeconds: Int, + entries: [LanguageServerStateEntry], + activeNames: [String] + ) throws -> [String] /// The launch plan of a build system's provider. A provider that shares /// a language server gets that server's plan with /// `buildProvider.languageServer` set. @@ -1725,7 +1869,42 @@ public protocol DeclarativeLanguageServerLaunchPlanning: Sendable { ) throws -> DeclarativeDebugExecutablePlan? } +/// One per-workspace state directory and when it was last used. +public struct LanguageServerStateEntry: Equatable, Sendable { + public let name: String + public let lastModifiedUnixSeconds: Int + + public init(name: String, lastModifiedUnixSeconds: Int) { + self.name = name + self.lastModifiedUnixSeconds = lastModifiedUnixSeconds + } +} + public extension DeclarativeLanguageServerLaunchPlanning { + func decodeLaunch( + manifest _: Data, + languageID _: String, + request _: DeclarativeLanguageServerLaunchRequest, + result _: ToolingJSONValue + ) throws -> DeclarativeLanguageServerLaunchPlan { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "This host cannot decode plugin-resolved launches." + ) + } + + func expiredLanguageServerStateNames( + retention _: DeclarativeLanguageServer.StateRetention, + nowUnixSeconds _: Int, + entries _: [LanguageServerStateEntry], + activeNames _: [String] + ) throws -> [String] { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "This host cannot select expired language server state." + ) + } + func buildProviderLaunchPlan( manifest _: Data, buildSystemID _: String, diff --git a/macos/Sources/LitheCoreContracts/Plugins/PluginContentProviderContracts.swift b/macos/Sources/LitheCoreContracts/Plugins/PluginContentProviderContracts.swift new file mode 100644 index 0000000000..0c6854e418 --- /dev/null +++ b/macos/Sources/LitheCoreContracts/Plugins/PluginContentProviderContracts.swift @@ -0,0 +1,9 @@ +import Foundation + +/// Rust Core checks what a plugin content provider answers (plan API-12), so +/// every host opens the same text under the same limit. +public protocol PluginContentDecoding: Sendable { + /// The document text of the answer. Throws when Core refuses the answer: + /// a shape other than a string or `{content}`, or more than 1 MiB. + func decodeContent(_ answer: ToolingJSONValue) throws -> String +} diff --git a/macos/Sources/LitheCoreContracts/Plugins/PluginMarketplaceContracts.swift b/macos/Sources/LitheCoreContracts/Plugins/PluginMarketplaceContracts.swift index 870d1ef5dc..4a4047d84e 100644 --- a/macos/Sources/LitheCoreContracts/Plugins/PluginMarketplaceContracts.swift +++ b/macos/Sources/LitheCoreContracts/Plugins/PluginMarketplaceContracts.swift @@ -238,6 +238,9 @@ public struct PluginProgram: Equatable, Hashable, Sendable { public enum Kind: String, Sendable { case packagedLanguageServer case systemLanguageServer + /// A server whose plugin backend chooses the command line each time + /// it starts; the review names the function that does. + case backendLanguageServer case runtime case run case test @@ -265,6 +268,8 @@ public struct PluginProgram: Equatable, Hashable, Sendable { public var languageID: String? { string("languageID") } public var path: String? { string("path") } public var tool: String? { string("tool") } + /// Backend function a `backendLanguageServer` program asks to resolve its launch. + public var function: String? { string("function") } public var commands: [String] { strings("commands") } public var arguments: [String] { strings("arguments") } diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift index 6ee3aeb14c..34d444c8f6 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift @@ -10,15 +10,20 @@ package struct ResolvedLanguageServerLaunch: Equatable, Sendable { /// What the server reads through `workspace/configuration`; plugin /// settings with `effect: immediate` change it without a restart. package let workspaceConfiguration: ToolingJSONValue? + /// What the plugin lets its backend ask of the running server. Rust Core + /// built it and enforces it; the host passes it to `lsp.startServer`. + package let sessionPolicy: ToolingJSONValue? package init( arguments: [String], initializationOptions: ToolingJSONValue?, - workspaceConfiguration: ToolingJSONValue? = nil + workspaceConfiguration: ToolingJSONValue? = nil, + sessionPolicy: ToolingJSONValue? = nil ) { self.arguments = arguments self.initializationOptions = initializationOptions self.workspaceConfiguration = workspaceConfiguration + self.sessionPolicy = sessionPolicy } } @@ -52,6 +57,15 @@ package typealias LanguageServerLaunchResolver = @MainActor ( URL ) throws -> ResolvedLanguageServerLaunch +/// Asks the plugin that owns a server what to start for one workspace root, +/// when its backend names the process (`serverProcess` 3). The answer is a +/// complete process with the resources that must outlive it, like the one +/// the remote preparer returns. +package typealias BackendLanguageServerLaunchPreparer = @MainActor ( + DeclarativeLanguageServerLaunchSource, + URL +) async throws -> PreparedLanguageServerProcess + @MainActor package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { package let descriptor: LanguageProviderDescriptor @@ -63,6 +77,7 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { private let languageServerLaunchResolver: LanguageServerLaunchResolver? private let languageServerCacheDirectory: URL? private let workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? + private let backendLaunchPreparer: BackendLanguageServerLaunchPreparer? private weak var processRegistry: (any LanguageServerProcessRegistry)? private let moduleID: ModuleID private var runtimeUnavailableMessage: String? @@ -87,6 +102,7 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { languageServerLaunchResolver: LanguageServerLaunchResolver? = nil, languageServerCacheDirectory: URL? = nil, workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? = nil, + backendLaunchPreparer: BackendLanguageServerLaunchPreparer? = nil, processRegistry: (any LanguageServerProcessRegistry)? = nil, moduleID: ModuleID = .languageIntelligence ) { @@ -99,6 +115,7 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { self.languageServerLaunchResolver = languageServerLaunchResolver self.languageServerCacheDirectory = languageServerCacheDirectory self.workspaceSessionFactory = workspaceSessionFactory + self.backendLaunchPreparer = backendLaunchPreparer self.processRegistry = processRegistry self.moduleID = moduleID } @@ -106,6 +123,9 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { package func makeLanguageServerSession() -> (any LanguageServerSession)? { runtimeUnavailableMessage = nil guard let languageServerLaunch else { return nil } + if let source = languageServerLaunch.launchSource, source.resolvesLaunchWithBackend { + return makeBackendLaunchedSession(source) + } let executableURL = if let languageServerExecutableResolver { languageServerExecutableResolver(descriptor) } else if let pinned = languageServerLaunch.executableURL { @@ -171,11 +191,45 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { package func makeLanguageServerSession(rootURL: URL) -> (any LanguageServerSession)? { if languageServerCore.requiresBackgroundLanguageServerStart(rootURL: rootURL), let workspaceSessionFactory, let languageServerLaunch { + // A remote workspace is prepared from the package on the remote + // host, which has no backend to answer the launch question. + if languageServerLaunch.launchSource?.resolvesLaunchWithBackend == true { + runtimeUnavailableMessage = L10n.string( + "\(descriptor.displayName) cannot start in a remote workspace yet." + ) + return nil + } return workspaceSessionFactory(languageServerLaunch, rootURL) } return makeLanguageServerSession() } + /// The session of a server whose plugin backend names the process. No + /// executable exists to look up beforehand, so the session starts with a + /// placeholder that `prepareProcess` replaces on every start. + private func makeBackendLaunchedSession( + _ source: DeclarativeLanguageServerLaunchSource + ) -> (any LanguageServerSession)? { + guard let backendLaunchPreparer else { + runtimeUnavailableMessage = L10n.string( + "\(descriptor.displayName) needs a launch this build of Lithe cannot resolve." + ) + return nil + } + return LanguageServerRuntimeSession( + providerID: descriptor.id, + executableURL: source.packageURL, + arguments: [], + environment: [:], + prepareProcess: { rootURL in try await backendLaunchPreparer(source, rootURL) }, + core: languageServerCore, + processRegistry: processRegistry, + moduleID: moduleID, + pluginID: source.pluginID, + role: .languageServer + ) + } + } @MainActor @@ -187,6 +241,7 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime private let languageServerLaunchResolver: LanguageServerLaunchResolver? private let languageServerCacheDirectory: URL? private let workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? + private let backendLaunchPreparer: BackendLanguageServerLaunchPreparer? private weak var processRegistry: (any LanguageServerProcessRegistry)? private let moduleID: ModuleID @@ -198,6 +253,7 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime languageServerLaunchResolver: LanguageServerLaunchResolver? = nil, languageServerCacheDirectory: URL? = nil, workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? = nil, + backendLaunchPreparer: BackendLanguageServerLaunchPreparer? = nil, processRegistry: (any LanguageServerProcessRegistry)? = nil, moduleID: ModuleID = .languageIntelligence ) { @@ -208,6 +264,7 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime self.languageServerLaunchResolver = languageServerLaunchResolver self.languageServerCacheDirectory = languageServerCacheDirectory self.workspaceSessionFactory = workspaceSessionFactory + self.backendLaunchPreparer = backendLaunchPreparer self.processRegistry = processRegistry self.moduleID = moduleID } @@ -229,6 +286,7 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime languageServerLaunchResolver: languageServerLaunchResolver, languageServerCacheDirectory: languageServerCacheDirectory, workspaceSessionFactory: workspaceSessionFactory, + backendLaunchPreparer: backendLaunchPreparer, processRegistry: processRegistry, moduleID: moduleID ) @@ -249,6 +307,7 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime languageServerLaunchResolver: languageServerLaunchResolver, languageServerCacheDirectory: languageServerCacheDirectory, workspaceSessionFactory: workspaceSessionFactory, + backendLaunchPreparer: backendLaunchPreparer, processRegistry: processRegistry, moduleID: ownerModuleID ) diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift index 3a1badf21e..da03f97076 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift @@ -36,6 +36,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { private var environment: [String: String] private var initializationOptions: ToolingJSONValue? private var preparedWorkspaceConfiguration: ToolingJSONValue? + private var preparedSessionPolicy: ToolingJSONValue? private let prepareProcess: (@MainActor (URL) async throws -> PreparedLanguageServerProcess)? private var preparationTask: Task? private var startingPreparedProcess = false @@ -126,6 +127,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { package var releaseResources: (@Sendable () async -> Void)? package var onDiagnostics: ((URL, [LanguageServerDiagnostic]) -> Void)? + package var onPluginServerNotification: ((PluginServerNotification) -> Void)? package var onCoreLog: ((CoreLogRecord) -> Void)? package var onLog: ((LanguageServerLogLevel, String, String?, String?) -> Void)? package var onLogIssue: ((Bool, String, String, Int?, String?) -> Void)? @@ -264,6 +266,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { self.environment = prepared.environment self.initializationOptions = prepared.launch.initializationOptions self.preparedWorkspaceConfiguration = prepared.launch.workspaceConfiguration + self.preparedSessionPolicy = prepared.launch.sessionPolicy self.core = prepared.core.loggingRuntime(role: self.logRole, logSubject: self.logSubject, pluginID: self.pluginID) self.releaseResources = prepared.release self.startingPreparedProcess = true @@ -294,12 +297,14 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { var arguments = arguments var initializationOptions = initializationOptions var workspaceConfiguration = preparedWorkspaceConfiguration + var sessionPolicy = preparedSessionPolicy if let launchResolver { do { let resolved = try launchResolver(normalizedRoot) arguments = resolved.arguments initializationOptions = resolved.initializationOptions workspaceConfiguration = resolved.workspaceConfiguration + sessionPolicy = resolved.sessionPolicy } catch { endStartupAttempt(throwing: error) let message = "Language server launch could not be prepared: \(error.localizedDescription)" @@ -339,6 +344,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { let resolvedArguments = arguments let resolvedOptions = initializationOptions let resolvedConfiguration = workspaceConfiguration + let resolvedPolicy = sessionPolicy let launch: @Sendable () -> Result = { if let pluginID, !offeredKeymapImportProviders.isEmpty { core.startPluginKeymapImportBackend( @@ -363,6 +369,26 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout ) + } else if let pluginID, let resolvedPolicy, hostIntegrationLaunch == nil { + // A server with session fields belongs to its plugin; a host + // integration keeps the start below and is not exposed. + core.startPluginLanguageServer( + pluginID: pluginID, + providerID: providerID, + executableURL: executableURL, + arguments: resolvedArguments, + environment: environment, + rootURL: normalizedRoot, + initializationOptions: resolvedOptions, + workspaceConfiguration: resolvedConfiguration, + sessionPolicy: resolvedPolicy, + hostServices: hostServices, + cacheDirectoryURL: cacheDirectoryURL, + workspaceFingerprint: workspaceFingerprint, + initializeTimeout: initializeTimeout, + requestTimeout: requestTimeout, + shutdownTimeout: shutdownTimeout + ) } else if let pluginID { core.startPluginLanguageServer( pluginID: pluginID, @@ -1094,6 +1120,78 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { } } + /// Sends one request of the owning plugin's backend to this server + /// (plan API-25). Core enforces the manifest's whitelist, gates and + /// timeout, and cancelling the calling task cancels the request. + package func requestPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) async -> Result { + guard let sessionID, state == .ready else { return .failure(.languageServerUnavailable) } + let operation: LanguageServerRuntimeOperation + switch await send(timeout: timeout ?? requestTimeout, { core in + core.pluginServerRequest( + sessionID: sessionID, pluginID: pluginID, serverID: serverID, + method: method, params: params, timeout: timeout + ) + }) { + case .success(let started): operation = started + case .failure(let refusal): + sendsInFlight -= 1 + return .failure(PluginHostRequestFailure(refusal: refusal)) + } + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + registerPendingOperation(operation, name: method) { result in + continuation.resume(returning: Self.pluginServerOutcome(of: result)) + } + sendsInFlight -= 1 + } + } onCancel: { + Task { @MainActor [weak self] in self?.cancelOffMain(operation.operationID) } + } + } + + /// Sends one notification of the owning plugin's backend to this server. + package func notifyPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) async -> Result { + guard let sessionID, state == .ready else { return .failure(.languageServerUnavailable) } + let result = await send(timeout: requestTimeout) { core in + core.pluginServerNotify( + sessionID: sessionID, pluginID: pluginID, serverID: serverID, method: method, params: params + ) + } + sendsInFlight -= 1 + return result.mapError { PluginHostRequestFailure(refusal: $0) } + } + + /// What a plugin-server request completed with, in the shape the backend + /// gets. A session that stopped first leaves the backend without a server. + private static func pluginServerOutcome( + of result: Result + ) -> Result { + switch result { + case .success(let event): + guard case .object(let object)? = event.result else { return .success(.null) } + return .success(object["value"] ?? .null) + case .failure(let error as LanguageServerRequestFailure): + return .failure(PluginHostRequestFailure( + completion: error.runtimeError, message: error.errorDescription ?? error.runtimeError.message + )) + case .failure(is CancellationError): + return .failure(PluginHostRequestFailure(message: "The request was cancelled.", code: "plugin.host.cancelled")) + case .failure: + return .failure(.languageServerUnavailable) + } + } + /// Answers a host-service request. Core writes the answer to the /// backend's input, which a backend that stopped reading can block, so /// it is sent off the main actor like a request. @@ -1190,6 +1288,12 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { terminateProcess?() } + private static func pluginServerNotification(of event: LanguageServerRuntimeEvent) -> PluginServerNotification? { + guard case .object(let object)? = event.result, case .string(let method)? = object["method"] else { return nil } + let truncated: Bool = if case .bool(true)? = object["truncated"] { true } else { false } + return PluginServerNotification(method: method, params: object["params"], truncated: truncated) + } + private static func functionFailure(_ error: Error) -> Error { guard let failure = error as? LanguageServerRequestFailure else { return error } let runtimeError = failure.runtimeError @@ -1656,6 +1760,9 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { respond(to: id, with: .failure(PluginHostRequestFailure(message: "The host serves no requests of this process."))) } return false + case "pluginServerNotification": + if let notification = Self.pluginServerNotification(of: event) { onPluginServerNotification?(notification) } + return false case "functionProviderStartRequired": if case .object(let object)? = event.result, case .string(let pluginID)? = object["pluginID"] { onFunctionProviderStartRequired?(pluginID) diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift b/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift index 7e2c3819cf..23b0e203b1 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift @@ -54,10 +54,18 @@ package final class LanguageToolingSessionManager: ObservableObject, private var javaDependencyRefreshTask: Task? private var javaDependencyChangeTask: Task? @Published package private(set) var mavenProfileProjectResults: [URL: MavenProfileProjectResult] = [:] - @Published package private(set) var languageServerStates: [String: LanguageServerSessionState] = [:] + @Published package private(set) var languageServerStates: [String: LanguageServerSessionState] = [:] { + // Every start, crash, stop and restart passes through this one + // property, so the plugin relay cannot miss a transition. + didSet { relayPluginServerStates(from: oldValue) } + } @Published package private(set) var languageServerInfos: [String: LanguageServerInfo] = [:] @Published package private(set) var languageServerOperationIDs: [String: UUID] = [:] package var onLanguageServerStateChange: ((String, LanguageServerSessionState, UUID?) -> Void)? + /// What plugin backends learn about the servers their plugins own (API-25). + package let pluginServers = PluginLanguageServerRelay() + /// The preparation status each plugin reported for its running server. + @Published package private(set) var pluginServerStatuses: [String: PluginServerStatus] = [:] private let logSink: (any LogSink)? private let resolveLogSubject: (String) throws -> LogSegment? // Cache both success and failure; diagnostics must not change startup behavior. @@ -131,6 +139,7 @@ package final class LanguageToolingSessionManager: ObservableObject, BuiltinLanguageFeatureProvider(core: builtinCore ?? UnavailableBuiltinLanguageFeatureCore()) ] runtimesByID = Dictionary(uniqueKeysWithValues: runtimes.map { ($0.descriptor.id, $0) }) + pluginServers.onStatusesChange = { [weak self] statuses in self?.pluginServerStatuses = statuses } } package var activeLanguageServerIDs: Set { @@ -297,7 +306,10 @@ package final class LanguageToolingSessionManager: ObservableObject, let configuration = provider.configuration guard configuration.languageID == support.id, let ownerModuleID = support.languageServerModuleID, - !configuration.executableNames.isEmpty, + // A server its plugin backend launches names no executable + // until it starts. + !configuration.executableNames.isEmpty + || configuration.launchSource?.resolvesLaunchWithBackend == true, // The module that owns this provider already stopped it. !provider.lifecycle.isRetired, let runtimeFactory else { return false } @@ -1603,6 +1615,60 @@ package final class LanguageToolingSessionManager: ObservableObject, return await session.updateWorkspaceConfigurationAsync(configuration) } + // MARK: Plugin-owned language servers (API-25) + + /// Sends one request of `pluginID`'s backend to the language server + /// `serverID`. Rust Core decides whether the server belongs to the plugin + /// and whether the method is declared; this only finds the session. + package func requestPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) async -> Result { + guard let session = languageServers[serverID] else { return .failure(.languageServerUnavailable) } + return await session.requestPluginServer( + pluginID: pluginID, serverID: serverID, method: method, params: params, timeout: timeout + ) + } + + /// Sends one notification of `pluginID`'s backend to the language server + /// `serverID`; `true` when it was written. + package func notifyPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) async -> Result { + guard let session = languageServers[serverID] else { return .failure(.languageServerUnavailable) } + return await session.notifyPluginServer( + pluginID: pluginID, serverID: serverID, method: method, params: params + ) + } + + /// Records the preparation status `pluginID` reports for its server. + /// Core never sees this call, so ownership is checked by the relay. + package func setPluginServerStatus( + _ status: PluginServerStatus, + serverID: String, + pluginID: String + ) -> Result { + pluginServers.setStatus(status, serverID: serverID, pluginID: pluginID) + } + + private func relayPluginServerStates(from previous: [String: LanguageServerSessionState]) { + for serverID in Set(previous.keys).union(languageServerStates.keys) { + let state = languageServerStates[serverID] + guard state != previous[serverID] else { continue } + pluginServers.serverStateChanged( + serverID: serverID, + owner: runtimesByID[serverID]?.descriptor.languageServerLaunch?.pluginID, + to: state + ) + } + } + package func resolveVirtualDocument( providerID: String, uri: URL, @@ -2183,6 +2249,14 @@ package final class LanguageToolingSessionManager: ObservableObject, self.recordLogIssue(providerID, operationID ?? self.languageServerOperationIDs[providerID]?.uuidString, warning, stage, code, exitCode) } + // The relay raised the generation when this session's state first + // became `startingProcess`, just before these callbacks are bound. + if let generation = pluginServers.liveGeneration(of: providerID) { + session.onPluginServerNotification = { [weak self] notification in + guard let self, self.languageServerSessionIdentities[providerID] == sessionIdentity else { return } + self.pluginServers.receive(notification, serverID: providerID, generation: generation) + } + } session.onStateChange = { [weak self] state in self?.handleLanguageServerState( state, diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Services/PluginLanguageServerRelay.swift b/macos/Sources/LitheLanguageIntelligenceModule/Services/PluginLanguageServerRelay.swift new file mode 100644 index 0000000000..e525896515 --- /dev/null +++ b/macos/Sources/LitheLanguageIntelligenceModule/Services/PluginLanguageServerRelay.swift @@ -0,0 +1,186 @@ +import Foundation +import LitheCoreContracts + +/// What a plugin backend learns about the language server its own plugin owns +/// (plan API-25), and the preparation status the backend reports in return. +/// +/// The relay keeps one fact per server: the generation of the process that is +/// running now. A backend must be able to tell a state or a notification of a +/// replaced process from the current one, so every message carries the +/// generation it belongs to and the relay drops a message whose generation is +/// no longer the live one. +/// +/// It holds no session and sends nothing itself. The session manager feeds it +/// state changes and server notifications; the window delivers its outward +/// callbacks to the backend. +@MainActor +package final class PluginLanguageServerRelay { + /// The state the contract reports; coarser than the session's own states. + package enum ServerState: String, Equatable, Sendable { + case starting, running, stopped, crashed + } + + package struct StateChange: Equatable, Sendable { + package let pluginID: String + package let serverID: String + package let state: ServerState + package let generation: Int + } + + package struct ReceivedNotification: Equatable, Sendable { + package let pluginID: String + package let serverID: String + package let generation: Int + package let notification: PluginServerNotification + } + + /// The process that is starting or running for a server ID. + private struct LiveServer { + let pluginID: String + let generation: Int + var state: ServerState + } + + /// Longest status message shown, in UTF-8 bytes (README, "Language server + /// host methods"). + package static let maximumMessageBytes = 1024 + + /// Raised on every start and never reset, so a generation never repeats + /// within the window even after the server stopped. + private var latestGenerations: [String: Int] = [:] + private var liveServers: [String: LiveServer] = [:] + + /// The newest status each live server's plugin reported. + package private(set) var statuses: [String: PluginServerStatus] = [:] { + didSet { if statuses != oldValue { onStatusesChange?(statuses) } } + } + + package var onStateChange: ((StateChange) -> Void)? + package var onNotification: ((ReceivedNotification) -> Void)? + package var onStatusesChange: (([String: PluginServerStatus]) -> Void)? + + package init() {} + + // MARK: Session lifecycle + + /// Follows one server through the session manager's states. `owner` is + /// the plugin whose package launched the server, nil for a server no + /// plugin owns; `sessionState` is nil once the session is gone. + package func serverStateChanged( + serverID: String, + owner: String?, + to sessionState: LanguageServerSessionState? + ) { + switch sessionState { + case .startingProcess, .initializing: + if let owner { began(serverID: serverID, owner: owner) } + case .ready: + reachedRunning(serverID: serverID) + case .stopped, nil: + ended(serverID: serverID, as: .stopped) + case .failed: + ended(serverID: serverID, as: .crashed) + case .stopping: + // The process is still there; `stopped` follows when it is gone. + break + } + } + + /// The generation of the process that is starting or running, if any. + package func liveGeneration(of serverID: String) -> Int? { + liveServers[serverID]?.generation + } + + private func began(serverID: String, owner: String) { + if let live = liveServers[serverID] { + // The same process moving from one starting step to the next. + if live.state == .starting { return } + // A start without a stop in between replaces the earlier process. + ended(serverID: serverID, as: .stopped) + } + let generation = (latestGenerations[serverID] ?? 0) + 1 + latestGenerations[serverID] = generation + liveServers[serverID] = LiveServer(pluginID: owner, generation: generation, state: .starting) + statuses[serverID] = nil + onStateChange?(StateChange(pluginID: owner, serverID: serverID, state: .starting, generation: generation)) + } + + private func reachedRunning(serverID: String) { + guard var live = liveServers[serverID], live.state != .running else { return } + live.state = .running + liveServers[serverID] = live + onStateChange?(StateChange( + pluginID: live.pluginID, serverID: serverID, state: .running, generation: live.generation + )) + } + + private func ended(serverID: String, as state: ServerState) { + guard let live = liveServers.removeValue(forKey: serverID) else { return } + statuses[serverID] = nil + onStateChange?(StateChange( + pluginID: live.pluginID, serverID: serverID, state: state, generation: live.generation + )) + } + + // MARK: Notifications from the server + + /// Passes a forwarded server notification on, unless the process that + /// sent it has been replaced or has ended. + package func receive(_ notification: PluginServerNotification, serverID: String, generation: Int) { + guard let live = liveServers[serverID], live.generation == generation else { return } + onNotification?(ReceivedNotification( + pluginID: live.pluginID, serverID: serverID, generation: generation, notification: notification + )) + } + + // MARK: Status from the backend + + /// Records the status `pluginID`'s backend reports for one of its servers. + package func setStatus( + _ status: PluginServerStatus, + serverID: String, + pluginID: String + ) -> Result { + // Preparation (importing a build, indexing) starts before the server + // can answer, so a starting server accepts a status as well. + guard let live = liveServers[serverID] else { return .failure(.languageServerUnavailable) } + guard live.pluginID == pluginID else { return .failure(.foreignContribution) } + statuses[serverID] = status.limitingMessage(toUTF8Bytes: Self.maximumMessageBytes) + return .success(()) + } +} + +/// How far a plugin says its language server is from usable. The host shows +/// it next to the server; it never decides what the server may do. +package struct PluginServerStatus: Equatable, Sendable { + package enum State: String, Sendable { + case preparing, ready, degraded, failed + } + + package let state: State + /// User-facing text of the plugin, shown as given. + package let message: String? + /// A whole number from 0 to 100. + package let percentage: Int? + + package init(state: State, message: String? = nil, percentage: Int? = nil) { + self.state = state + self.message = message + self.percentage = percentage + } + + /// Cuts the message on a character boundary, so a plugin cannot fill the + /// status line with text the host has no room for. + fileprivate func limitingMessage(toUTF8Bytes limit: Int) -> PluginServerStatus { + guard let message, message.utf8.count > limit else { return self } + var kept = "" + var usedBytes = 0 + for character in message { + let size = String(character).utf8.count + if usedBytes + size > limit { break } + kept.append(character) + usedBytes += size + } + return PluginServerStatus(state: state, message: kept, percentage: percentage) + } +} diff --git a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift index 661b721e05..64021c052e 100644 --- a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift +++ b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift @@ -526,10 +526,10 @@ public struct PluginManifest: Equatable, Codable, Sendable { "buildProviders": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "buildModelInputs": [1], "buildSystems": [1, 2, 3, 4], "debugAdapters": [1, 2], "executableResolution": [1, 2], "executionProviders": [1], - "languageServers": [1, 2], + "languageServers": [1, 2, 3], "languages": [1, 2], "projectGenerators": [1, 2], - "serverProcess": [1], + "serverProcess": [1, 3], "settings": [1, 2], "toolDefinitions": [1], "toolchainProviders": [1], diff --git a/macos/Tests/LitheLanguageIntelligenceModuleTests/PluginLanguageServerRelayTests.swift b/macos/Tests/LitheLanguageIntelligenceModuleTests/PluginLanguageServerRelayTests.swift new file mode 100644 index 0000000000..642ab0f386 --- /dev/null +++ b/macos/Tests/LitheLanguageIntelligenceModuleTests/PluginLanguageServerRelayTests.swift @@ -0,0 +1,212 @@ +import Foundation +import LitheCoreContracts +@testable import LitheLanguageIntelligenceModule +import Testing + +/// What a plugin backend learns about its own language server (plan API-25): +/// one generation per process, states in order, and nothing from a process +/// that was replaced. +@MainActor +struct PluginLanguageServerRelayTests { + private let relay = PluginLanguageServerRelay() + private let states = StateLog() + + init() { + let states = states + relay.onStateChange = { states.changes.append($0) } + } + + private func change(_ state: PluginLanguageServerRelay.ServerState, generation: Int) -> PluginLanguageServerRelay.StateChange { + .init(pluginID: "tool", serverID: "scala", state: state, generation: generation) + } + + /// `Result` is not `Equatable`, so the tests compare the failure. + private func failure(of outcome: Result) -> PluginHostRequestFailure? { + if case .failure(let failure) = outcome { return failure } + return nil + } + + // MARK: States + + @Test + func aStartRunsThroughStartingToRunningUnderOneGeneration() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .initializing) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + + // The two starting steps and the repeated ready are one process. + #expect(states.changes == [change(.starting, generation: 1), change(.running, generation: 1)]) + #expect(relay.liveGeneration(of: "scala") == 1) + } + + @Test + func aStoppedServerReportsStoppedAndTheNextStartGetsANewGeneration() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .stopped) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + #expect(states.changes == [ + change(.starting, generation: 1), change(.stopped, generation: 1), change(.starting, generation: 2), + ]) + #expect(relay.liveGeneration(of: "scala") == 2) + } + + @Test + func aFailureReportsCrashedAndLeavesNoLiveProcess() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .failed(LanguageServerSessionFailure(code: "exited"))) + // The session going away after a failure adds nothing. + relay.serverStateChanged(serverID: "scala", owner: "tool", to: nil) + + #expect(states.changes.last == change(.crashed, generation: 1)) + #expect(states.changes.count == 3) + #expect(relay.liveGeneration(of: "scala") == nil) + } + + @Test + func aStartWithoutAStopReplacesTheEarlierProcess() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + #expect(Array(states.changes.suffix(2)) == [change(.stopped, generation: 1), change(.starting, generation: 2)]) + } + + @Test + func aStoppingServerIsStillTheSameProcess() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .stopping) + + #expect(states.changes.count == 2) + #expect(relay.liveGeneration(of: "scala") == 1) + } + + @Test + func aServerNoPluginOwnsReportsNothing() { + relay.serverStateChanged(serverID: "scala", owner: nil, to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: nil, to: .ready) + + #expect(states.changes.isEmpty) + #expect(relay.liveGeneration(of: "scala") == nil) + } + + // MARK: Notifications + + @Test + func aNotificationOfTheLiveProcessIsPassedOn() { + let received = NotificationLog() + relay.onNotification = { received.items.append($0) } + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + let notification = PluginServerNotification(method: "metals/status", params: .object(["text": .string("ok")]), truncated: false) + + relay.receive(notification, serverID: "scala", generation: 1) + + #expect(received.items == [.init(pluginID: "tool", serverID: "scala", generation: 1, notification: notification)]) + } + + @Test + func aNotificationOfAReplacedOrEndedProcessIsDropped() { + let received = NotificationLog() + relay.onNotification = { received.items.append($0) } + let notification = PluginServerNotification(method: "metals/status", params: nil, truncated: true) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .stopped) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + relay.receive(notification, serverID: "scala", generation: 1) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .stopped) + relay.receive(notification, serverID: "scala", generation: 2) + + #expect(received.items.isEmpty) + } + + // MARK: Status + + @Test + func aServersPluginCanReportItsStatusWhileTheServerStarts() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + let outcome = relay.setStatus(PluginServerStatus(state: .preparing, message: "Importing", percentage: 10), serverID: "scala", pluginID: "tool") + + #expect(failure(of: outcome) == nil) + #expect(relay.statuses["scala"] == PluginServerStatus(state: .preparing, message: "Importing", percentage: 10)) + } + + @Test + func aStatusForAServerThatIsNotLiveIsUnavailable() { + let outcome = relay.setStatus(PluginServerStatus(state: .ready), serverID: "scala", pluginID: "tool") + + #expect(failure(of: outcome) == .languageServerUnavailable) + #expect(relay.statuses.isEmpty) + } + + @Test + func aPluginCannotReportTheStatusOfAnotherPluginsServer() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + let outcome = relay.setStatus(PluginServerStatus(state: .failed), serverID: "scala", pluginID: "other") + + #expect(failure(of: outcome) == .foreignContribution) + #expect(relay.statuses.isEmpty) + } + + @Test + func aLongMessageIsCutOnACharacterBoundary() throws { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + // Each character takes three bytes, so the cut falls between two. + let long = String(repeating: "进", count: 400) + + _ = relay.setStatus(PluginServerStatus(state: .degraded, message: long), serverID: "scala", pluginID: "tool") + + let kept = try #require(relay.statuses["scala"]?.message) + #expect(kept.utf8.count <= PluginLanguageServerRelay.maximumMessageBytes) + #expect(kept.utf8.count == 1023) + #expect(long.hasPrefix(kept)) + } + + @Test + func aStatusEndsWithTheProcessItDescribed() { + let seen = StatusLog() + relay.onStatusesChange = { seen.maps.append($0) } + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + _ = relay.setStatus(PluginServerStatus(state: .preparing), serverID: "scala", pluginID: "tool") + + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .stopped) + + #expect(relay.statuses.isEmpty) + #expect(seen.maps.last?.isEmpty == true) + #expect(seen.maps.count == 2) + } + + @Test + func aReplacedProcessTakesItsStatusWithIt() { + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .ready) + _ = relay.setStatus(PluginServerStatus(state: .degraded), serverID: "scala", pluginID: "tool") + + // A start without a stop replaces the process; its status described + // the old one. + relay.serverStateChanged(serverID: "scala", owner: "tool", to: .startingProcess) + + #expect(relay.statuses["scala"] == nil) + #expect(relay.liveGeneration(of: "scala") == 2) + } +} + +@MainActor +private final class StateLog { + var changes: [PluginLanguageServerRelay.StateChange] = [] +} + +@MainActor +private final class NotificationLog { + var items: [PluginLanguageServerRelay.ReceivedNotification] = [] +} + +@MainActor +private final class StatusLog { + var maps: [[String: PluginServerStatus]] = [] +} diff --git a/macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift b/macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift index 6b6d630a16..0af0fd59eb 100644 --- a/macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift +++ b/macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift @@ -59,7 +59,9 @@ struct OfficialPluginVerifier { if let directory = packagedRuntime.split(separator: "/").first { runtimeDirectories.append(String(directory)) } - case .systemCommand: + case .systemCommand, .backend: + // The backend chooses the command when the server starts, so + // there is no file to check in the package yet. continue } } diff --git a/macos/Tests/LitheTests/MacPluginLanguageServerWorkspaceStateTests.swift b/macos/Tests/LitheTests/MacPluginLanguageServerWorkspaceStateTests.swift new file mode 100644 index 0000000000..1b9287e097 --- /dev/null +++ b/macos/Tests/LitheTests/MacPluginLanguageServerWorkspaceStateTests.swift @@ -0,0 +1,213 @@ +import Foundation +@testable import Lithe +import LitheCoreContracts +import Testing + +/// The per-workspace state of a plugin-owned language server (plan API-20): +/// what the host deletes to keep it bounded, and what it never touches. The +/// plugin is a Metals stub; Rust Core decides which directories expire. +struct MacPluginLanguageServerWorkspaceStateTests { + private static let now = Date(timeIntervalSince1970: 1_800_000_000) + private static let day: TimeInterval = 86_400 + + // MARK: prune + + @Test + func aWorkspaceNotUsedForLongerThanTheRetentionIsDeleted() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 8, maxAgeDays: 30)) + defer { fixture.remove() } + let stale = try fixture.makeState(for: "/work/stale", usedDaysAgo: 40) + let recent = try fixture.makeState(for: "/work/recent", usedDaysAgo: 1) + + let removed = try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(removed == [stale.lastPathComponent]) + #expect(!fixture.exists(stale)) + #expect(fixture.exists(recent)) + } + + @Test + func onlyTheNewestWorkspacesFitUnderTheEntryLimit() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 2, maxAgeDays: 365)) + defer { fixture.remove() } + let oldest = try fixture.makeState(for: "/work/a", usedDaysAgo: 3) + let middle = try fixture.makeState(for: "/work/b", usedDaysAgo: 2) + let newest = try fixture.makeState(for: "/work/c", usedDaysAgo: 1) + + try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(!fixture.exists(oldest)) + #expect(fixture.exists(middle)) + #expect(fixture.exists(newest)) + } + + @Test + func anOpenWorkspaceIsNeverDeletedEvenWhenItIsTheOldest() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 8, maxAgeDays: 30)) + defer { fixture.remove() } + let open = try fixture.makeState(for: "/work/open", usedDaysAgo: 90) + + let removed = try fixture.state.prune(fixture.source, openWorkspaceURLs: [URL(fileURLWithPath: "/work/open")]) + + #expect(removed.isEmpty) + #expect(fixture.exists(open)) + } + + @Test + func aPluginThatDeclaresNoRetentionKeepsEverything() throws { + let fixture = try Fixture.make(retention: nil) + defer { fixture.remove() } + let old = try fixture.makeState(for: "/work/old", usedDaysAgo: 400) + + let removed = try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(removed.isEmpty) + #expect(fixture.exists(old)) + } + + @Test + func aFileOrALinkInTheStateAreaIsNotStateAndStaysPut() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 8, maxAgeDays: 1)) + defer { fixture.remove() } + let area = fixture.workspaceStates + try FileManager.default.createDirectory(at: area, withIntermediateDirectories: true) + let file = area.appendingPathComponent("not-a-workspace.txt") + try Data("x".utf8).write(to: file) + let outside = fixture.root.appendingPathComponent("outside", isDirectory: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let link = area.appendingPathComponent("link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside) + for url in [file, outside] { + try FileManager.default.setAttributes( + [.modificationDate: Self.now.addingTimeInterval(-100 * Self.day)], ofItemAtPath: url.path + ) + } + + let removed = try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(removed.isEmpty) + #expect(fixture.exists(file)) + #expect(fixture.exists(outside)) + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: link.path)) != nil) + } + + @Test + func anotherLanguagesStateIsNotPruned() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 8, maxAgeDays: 30)) + defer { fixture.remove() } + let other = try fixture.makeState(for: "/work/other", usedDaysAgo: 90, languageID: "kotlin") + + try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(fixture.exists(other)) + } + + // MARK: markUsed + + @Test + func startingTheServerRefreshesWhenItsWorkspaceWasLastUsed() throws { + let fixture = try Fixture.make(retention: .init(maxEntries: 8, maxAgeDays: 30)) + defer { fixture.remove() } + let workspace = URL(fileURLWithPath: "/work/project") + let directory = try fixture.makeState(for: workspace.path, usedDaysAgo: 90) + + try fixture.state.markUsed(fixture.source, workspaceRootURL: workspace) + let removed = try fixture.state.prune(fixture.source, openWorkspaceURLs: []) + + #expect(removed.isEmpty) + #expect(fixture.exists(directory)) + } + + @Test + func markingAWorkspaceThatHasNoStateYetDoesNothing() throws { + let fixture = try Fixture.make(retention: nil) + defer { fixture.remove() } + + try fixture.state.markUsed(fixture.source, workspaceRootURL: URL(fileURLWithPath: "/work/new")) + + #expect(!FileManager.default.fileExists(atPath: fixture.workspaceStates.path)) + } + + // MARK: reset + + @Test + func resettingDiscardsOnlyThatWorkspacesState() throws { + let fixture = try Fixture.make(retention: nil) + defer { fixture.remove() } + let target = try fixture.makeState(for: "/work/target", usedDaysAgo: 1) + let neighbour = try fixture.makeState(for: "/work/neighbour", usedDaysAgo: 1) + + try fixture.state.reset(fixture.source, workspaceRootURL: URL(fileURLWithPath: "/work/target")) + + #expect(!fixture.exists(target)) + #expect(fixture.exists(neighbour)) + } + + @Test + func resettingAWorkspaceWithoutStateIsNotAnError() throws { + let fixture = try Fixture.make(retention: nil) + defer { fixture.remove() } + + try fixture.state.reset(fixture.source, workspaceRootURL: URL(fileURLWithPath: "/work/none")) + } + + // MARK: Fixture + + private struct Fixture { + let root: URL + let source: DeclarativeLanguageServerLaunchSource + let directories: MacPluginStateDirectories + let state: MacPluginLanguageServerWorkspaceState + + var workspaceStates: URL { + directories.workspaceStatesDirectory(pluginID: source.pluginID, languageID: source.languageID) + } + + static func make(retention: DeclarativeLanguageServer.StateRetention?) throws -> Fixture { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-workspace-state-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let operations = DeclarativePluginTestSupport.operations + let manifest = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json")) + let descriptor = try operations.validate(manifest: manifest) + let directories = MacPluginStateDirectories( + rootURL: root.appendingPathComponent("state", isDirectory: true), + temporaryRootURL: root.appendingPathComponent("scratch", isDirectory: true) + ) + return Fixture( + root: root, + source: DeclarativeLanguageServerLaunchSource( + pluginID: descriptor.id.rawValue, languageID: "scala", + manifest: descriptor.normalizedManifest, packageURL: root.appendingPathComponent("package"), + resolvesLaunchWithBackend: true, stateRetention: retention + ), + directories: directories, + state: MacPluginLanguageServerWorkspaceState( + directories: directories, planner: operations, now: { MacPluginLanguageServerWorkspaceStateTests.now } + ) + ) + } + + /// The state a server of `languageID` wrote for the workspace at + /// `path`, last used `days` ago. + func makeState(for path: String, usedDaysAgo days: Double, languageID: String = "scala") throws -> URL { + let directory = directories.workspaceStateDirectory( + pluginID: source.pluginID, languageID: languageID, workspaceRootURL: URL(fileURLWithPath: path) + ) + try FileManager.default.createDirectory( + at: directory.appendingPathComponent("index", isDirectory: true), withIntermediateDirectories: true + ) + // Set last: writing into the directory would move its time. + try FileManager.default.setAttributes( + [.modificationDate: MacPluginLanguageServerWorkspaceStateTests.now.addingTimeInterval(-days * MacPluginLanguageServerWorkspaceStateTests.day)], + ofItemAtPath: directory.path + ) + return directory + } + + func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) } + + func remove() { try? FileManager.default.removeItem(at: root) } + } +} diff --git a/macos/Tests/LitheTests/PluginBackendLaunchTests.swift b/macos/Tests/LitheTests/PluginBackendLaunchTests.swift new file mode 100644 index 0000000000..6e18dba9bd --- /dev/null +++ b/macos/Tests/LitheTests/PluginBackendLaunchTests.swift @@ -0,0 +1,529 @@ +import Foundation +@testable import Lithe +import LitheCoreContracts +import LitheLanguageIntelligenceModule +import LitheModuleAPI +import Testing + +/// A server whose plugin backend names the process (`serverProcess` 3). The +/// plugin is a Metals stub: Rust Core builds the question and bounds the +/// answer, the host runs the backend call, resolves the program, and keeps +/// every file outside the package. +@MainActor +struct PluginBackendLaunchTests { + // MARK: Resolver: the question + + @Test + func theQuestionNamesTheBackendFunctionAndCreatesThisStartsDirectories() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + + let question = try fixture.resolver.backendLaunchQuestion( + for: fixture.source, workspaceRootURL: fixture.workspaceURL + ) + + #expect(question.function == "metals.resolveLaunch") + #expect(question.timeoutMilliseconds == 30_000) + #expect(question.resolveParams["serverID"] == .string("scala")) + #expect(question.resolveParams["temporaryDirectory"] == .string(question.scratchDirectory.path)) + #expect(question.request.temporaryDirectory == question.scratchDirectory) + #expect(isDirectory(question.scratchDirectory)) + #expect(isDirectory(question.request.stateDirectory)) + #expect(question.request.workspaceStateDirectory.map(isDirectory) == true) + #expect(!question.scratchDirectory.path.hasPrefix(fixture.source.packageURL.path + "/")) + } + + @Test + func everyStartGetsItsOwnScratchDirectory() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + + let first = try fixture.resolver.backendLaunchQuestion(for: fixture.source, workspaceRootURL: fixture.workspaceURL) + let second = try fixture.resolver.backendLaunchQuestion(for: fixture.source, workspaceRootURL: fixture.workspaceURL) + + #expect(first.scratchDirectory != second.scratchDirectory) + } + + @Test + func aServerTheBackendDoesNotResolveGetsNoQuestionAndLeavesNoScratch() throws { + let fixture = try Fixture.make(manifest: "language-packaged-server.plugin.json", languageID: "php") + defer { fixture.remove() } + + let code = rejectionCode { + _ = try fixture.resolver.backendLaunchQuestion(for: fixture.source, workspaceRootURL: fixture.workspaceURL) + } + + #expect(code == "plugin.launch.notBackend") + #expect(fixture.scratchEntries().isEmpty) + } + + // MARK: Resolver: the answer + + @Test + func aPackagedAnswerBecomesAFileProgramWithItsSessionPolicy() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let question = try fixture.question() + let cache = question.scratchDirectory.appendingPathComponent("coursier/cache") + + let process = try fixture.resolver.backendLaunchProcess( + for: fixture.source, + question: question, + answer: Fixture.packagedAnswer(writing: cache) + ) + + #expect(process.program == .file(fixture.metalsURL)) + #expect(process.environment == ["COURSIER_CACHE": cache.path]) + #expect(process.launch.arguments == ["-Dmetals.client=lithe"]) + #expect(process.launch.initializationOptions == .object(["isHttpEnabled": .bool(false)])) + let policy = try #require(process.launch.sessionPolicy) + guard case .object(let fields) = policy else { throw PolicyShapeError() } + #expect(fields["serverID"] == .string("scala")) + #expect(fields["gates"] != nil) + // The host makes the place the server writes to, never the files in it. + #expect(isDirectory(cache.deletingLastPathComponent())) + #expect(!FileManager.default.fileExists(atPath: cache.path)) + } + + @Test + func aToolAnswerStaysANameForTheHostToResolve() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let question = try fixture.question() + + let process = try fixture.resolver.backendLaunchProcess( + for: fixture.source, question: question, answer: Fixture.toolAnswer("coursier") + ) + + #expect(process.program == .tool("coursier")) + } + + @Test + func aPathOutsideThePackageIsRejectedByCore() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let question = try fixture.question() + + let code = rejectionCode { + _ = try fixture.resolver.backendLaunchProcess( + for: fixture.source, question: question, answer: Fixture.packagedAnswer(path: "../outside") + ) + } + + #expect(code == "plugin.launch.outsidePackage") + } + + @Test + func aToolThePluginDoesNotDefineIsRejectedByCore() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let question = try fixture.question() + + let code = rejectionCode { + _ = try fixture.resolver.backendLaunchProcess( + for: fixture.source, question: question, answer: Fixture.toolAnswer("ghost") + ) + } + + #expect(code == "plugin.launch.undeclaredTool") + } + + @Test + func aWritablePathOutsideTheHostDirectoriesIsRejectedByCore() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let question = try fixture.question() + + let code = rejectionCode { + _ = try fixture.resolver.backendLaunchProcess( + for: fixture.source, + question: question, + answer: Fixture.packagedAnswer(writing: URL(fileURLWithPath: "/etc/metals")) + ) + } + + #expect(code == "plugin.launch.unwritablePath") + } + + @Test + func aPackagedFileThatIsNotExecutableIsNotStarted() throws { + let fixture = try Fixture.make(executable: false) + defer { fixture.remove() } + let question = try fixture.question() + + #expect(throws: MacPluginLanguageServerLaunchResolver.ResolutionError.packagedExecutableNotRunnable("bin/metals")) { + _ = try fixture.resolver.backendLaunchProcess( + for: fixture.source, question: question, answer: Fixture.packagedAnswer() + ) + } + } + + // MARK: Preparer + + @Test + func aPackagedAnswerPreparesTheProcessAndTheReleaseRemovesTheScratch() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + let context = fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { params in + Fixture.packagedAnswer(writing: Fixture.scratch(of: params).appendingPathComponent("coursier")) + } + let tools = ScriptedTools() + let preparer = fixture.preparer(backends: backends, tools: tools) + + let prepared = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + + let call = try #require(backends.calls.first) + #expect(backends.calls.count == 1) + #expect(call.function == "metals.resolveLaunch") + #expect(call.pluginID == fixture.source.pluginID) + #expect(call.context == context.reference) + #expect(call.timeout == .milliseconds(30_000)) + #expect(prepared.executableURL == fixture.metalsURL) + #expect(prepared.launch.arguments == ["-Dmetals.client=lithe"]) + #expect(prepared.environment["COURSIER_CACHE"] != nil) + #expect(tools.invocations.isEmpty) + #expect(fixture.scratchEntries().count == 1) + + await prepared.release() + + #expect(fixture.scratchEntries().isEmpty) + fixture.contexts.close(owner: window) + } + + @Test + func aToolAnswerIsResolvedAsTheToolchainOfTheOpenedRoot() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.toolAnswer("coursier") } + let tools = ScriptedTools(result: ResolvedBuildTool( + executableURL: URL(fileURLWithPath: "/host/bin/cs"), environment: ["PATH": "/host/bin"], + executesProjectCode: false, version: "2.1.0" + )) + let preparer = fixture.preparer(backends: backends, tools: tools) + + let prepared = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + + #expect(tools.invocations.map(\.executables) == [[.toolchain(id: "coursier", root: ".")]]) + #expect(prepared.executableURL == URL(fileURLWithPath: "/host/bin/cs")) + #expect(prepared.environment["PATH"] == "/host/bin") + await prepared.release() + fixture.contexts.close(owner: window) + } + + @Test + func aToolInsideTheProjectIsRefusedAndTheScratchGoes() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.toolAnswer("coursier") } + let tools = ScriptedTools(result: ResolvedBuildTool( + executableURL: fixture.workspaceURL.appendingPathComponent("cs"), environment: [:], + executesProjectCode: true, version: nil + )) + let preparer = fixture.preparer(backends: backends, tools: tools) + + await #expect(throws: MacPluginBackendLaunchPreparer.PrepareError.toolRunsProjectCode("coursier")) { + _ = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + } + + #expect(fixture.scratchEntries().isEmpty) + fixture.contexts.close(owner: window) + } + + @Test + func aFailingBackendEndsTheStartAndTheScratchGoes() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends(failure: BackendFailure()) + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools()) + + await #expect(throws: BackendFailure.self) { + _ = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + } + + #expect(fixture.scratchEntries().isEmpty) + fixture.contexts.close(owner: window) + } + + @Test + func aRejectedAnswerEndsTheStartWithCoresCode() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.toolAnswer("ghost") } + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools()) + + do { + _ = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + Issue.record("An undeclared tool must not start") + } catch let rejection as DeclarativePluginRejection { + #expect(rejection.code == "plugin.launch.undeclaredTool") + } + + #expect(fixture.scratchEntries().isEmpty) + fixture.contexts.close(owner: window) + } + + @Test + func aWorkspaceThatChangedWhileTheBackendWorkedDoesNotStartTheProcess() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.packagedAnswer() } + // The window moves to another workspace while the backend answers. + backends.onInvoke = { [contexts = fixture.contexts] in + contexts.open(owner: window, rootURL: URL(fileURLWithPath: "/tmp/other-workspace"), remote: nil) + } + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools()) + + await #expect(throws: CancellationError.self) { + _ = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + } + + #expect(fixture.scratchEntries().isEmpty) + fixture.contexts.close(owner: window) + } + + @Test + func aFolderNoWindowShowsIsRefusedBeforeAnythingStarts() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let backends = ScriptedBackends { _ in Fixture.packagedAnswer() } + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools()) + + await #expect(throws: MacPluginBackendLaunchPreparer.PrepareError.workspaceNotOpen) { + _ = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + } + + #expect(backends.calls.isEmpty) + #expect(fixture.scratchEntries().isEmpty) + } + + // MARK: Context lookup + + @Test + func aLocalContextIsFoundByItsFolderAndARemoteOneIsNot() { + let contexts = PluginWorkspaceContexts() + let local = NSObject() + let remote = NSObject() + let opened = contexts.open(owner: local, rootURL: URL(fileURLWithPath: "/tmp/orders"), remote: nil) + contexts.open( + owner: remote, rootURL: URL(fileURLWithPath: "/tmp/remote-mirror"), + remote: (connectionID: "c-1", remoteRoot: "/srv/app") + ) + + #expect(contexts.localContext(forFolder: URL(fileURLWithPath: "/tmp/orders/")) == opened) + #expect(contexts.localContext(forFolder: URL(fileURLWithPath: "/tmp/remote-mirror")) == nil) + #expect(contexts.localContext(forFolder: URL(fileURLWithPath: "/tmp/other")) == nil) + contexts.close(owner: local) + contexts.close(owner: remote) + } + + // MARK: Helpers + + private func isDirectory(_ url: URL) -> Bool { + (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + } + + private func rejectionCode(_ body: () throws -> Void) -> String? { + do { + try body() + return nil + } catch let rejection as DeclarativePluginRejection { + return rejection.code + } catch { + return "other: \(error)" + } + } +} + +private struct PolicyShapeError: Error {} +private struct BackendFailure: Error {} + +// MARK: Fixture + +/// The Metals stub: an installed package with a launcher script, a state +/// root, and a workspace folder, all in one temporary directory. +@MainActor +private struct Fixture { + let root: URL + let source: DeclarativeLanguageServerLaunchSource + let directories: MacPluginStateDirectories + let resolver: MacPluginLanguageServerLaunchResolver + let workspaceURL: URL + let contexts = PluginWorkspaceContexts() + + var metalsURL: URL { source.packageURL.appendingPathComponent("bin/metals").standardizedFileURL } + + static func make( + manifest: String = "language-server-backend-launch.plugin.json", + languageID: String = "scala", + executable: Bool = true + ) throws -> Fixture { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-backend-launch-\(UUID().uuidString)", isDirectory: true) + let package = root.appendingPathComponent("package", isDirectory: true) + let launcher = package.appendingPathComponent("bin/metals") + try FileManager.default.createDirectory(at: launcher.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("#!/bin/sh\n".utf8).write(to: launcher) + try FileManager.default.setAttributes([.posixPermissions: executable ? 0o755 : 0o644], ofItemAtPath: launcher.path) + + let operations = DeclarativePluginTestSupport.operations + let manifestData = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/languages") + .appendingPathComponent(manifest)) + let descriptor = try operations.validate(manifest: manifestData) + let directories = MacPluginStateDirectories( + rootURL: root.appendingPathComponent("state", isDirectory: true), + temporaryRootURL: root.appendingPathComponent("scratch", isDirectory: true) + ) + let logs = root.appendingPathComponent("logs", isDirectory: true) + let workspace = root.appendingPathComponent("workspace", isDirectory: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + return Fixture( + root: root, + source: DeclarativeLanguageServerLaunchSource( + pluginID: descriptor.id.rawValue, languageID: languageID, + manifest: descriptor.normalizedManifest, packageURL: package, + resolvesLaunchWithBackend: true + ), + directories: directories, + resolver: MacPluginLanguageServerLaunchResolver( + planner: operations, directories: directories, settings: InMemoryPluginSettings(), + logDirectory: { _ in logs } + ), + workspaceURL: workspace.standardizedFileURL + ) + } + + func remove() { try? FileManager.default.removeItem(at: root) } + + func question() throws -> MacPluginLanguageServerLaunchResolver.BackendLaunchQuestion { + try resolver.backendLaunchQuestion(for: source, workspaceRootURL: workspaceURL) + } + + /// Directories a start left in the scratch area. + func scratchEntries() -> [String] { + (try? FileManager.default.contentsOfDirectory(atPath: directories.temporaryRootURL.path)) ?? [] + } + + func preparer(backends: ScriptedBackends, tools: ScriptedTools) -> MacPluginBackendLaunchPreparer { + MacPluginBackendLaunchPreparer( + backends: backends, contexts: contexts, resolver: resolver, tools: tools, + runtime: NoToolRuntime(), core: RustCoreBridge() + ) + } + + /// The scratch directory the host named in the function's params. + static func scratch(of params: ToolingJSONValue) -> URL { + guard case .object(let fields) = params, case .string(let path)? = fields["temporaryDirectory"] else { + return URL(fileURLWithPath: "/missing-scratch") + } + return URL(fileURLWithPath: path) + } + + /// What the stub's `metals.resolveLaunch` answers for a packaged start. + static func packagedAnswer(path: String = "bin/metals", writing writable: URL? = nil) -> ToolingJSONValue { + var fields: [String: ToolingJSONValue] = [ + "executable": .object(["kind": .string("packaged"), "path": .string(path)]), + "arguments": .array([.string("-Dmetals.client=lithe")]), + "initializationOptions": .object(["isHttpEnabled": .bool(false)]) + ] + if let writable { + fields["environment"] = .object(["COURSIER_CACHE": .string(writable.path)]) + fields["writablePaths"] = .array([.string(writable.path)]) + } + return .object(fields) + } + + static func toolAnswer(_ tool: String) -> ToolingJSONValue { + .object(["executable": .object(["kind": .string("tool"), "tool": .string(tool)])]) + } +} + +// MARK: Doubles + +@MainActor +private final class ScriptedBackends: PluginBackendRequesting { + struct Call { + let function: String + let params: ToolingJSONValue + let pluginID: String + let context: PluginWorkspaceContextReference? + let timeout: Duration + } + + private let answer: (ToolingJSONValue) -> ToolingJSONValue + private let failure: (any Error)? + private(set) var calls: [Call] = [] + var onInvoke: (() -> Void)? + + init(answer: @escaping (ToolingJSONValue) -> ToolingJSONValue) { + self.answer = answer + failure = nil + } + + init(failure: any Error) { + answer = { _ in .null } + self.failure = failure + } + + func declaresBackend(_: String) -> Bool { true } + func pluginFunctions(ofPlugin _: String) async throws -> [String] { ["metals.resolveLaunch"] } + + func invokePluginFunction( + _: String, params _: ToolingJSONValue, ofPlugin _: String, timeout _: Duration, + progress _: @escaping @MainActor @Sendable (PluginFunctionProgress) -> Void + ) async throws -> ToolingJSONValue { + throw BackendFailure() + } + + 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, pluginID: pluginID, context: context, timeout: timeout)) + onInvoke?() + if let failure { throw failure } + return answer(params) + } +} + +@MainActor +private final class ScriptedTools: BuildToolResolving { + private let result: ResolvedBuildTool + private(set) var invocations: [BuildInvocation] = [] + + init(result: ResolvedBuildTool = ResolvedBuildTool( + executableURL: URL(fileURLWithPath: "/host/bin/unused"), environment: [:], executesProjectCode: false, version: nil + )) { + self.result = result + } + + func resolve( + _ invocation: BuildInvocation, displayName _: String, workspaceURL _: URL, + checkVersion _: @escaping @Sendable (String?, String) throws -> BuildVersionCheck + ) async throws -> ResolvedBuildTool { + invocations.append(invocation) + return result + } +} + +@MainActor +private final class NoToolRuntime: LanguageToolRuntimePort { + func executableOnPath(_: String) -> URL? { nil } + func executableURL(at path: String) -> URL? { URL(fileURLWithPath: path) } + func executableCandidates(_: String) -> [RuntimeToolCandidate] { [] } + func languageToolProcessEnvironment(runtimeTools _: [String]) -> [String: String] { [:] } + func missingLanguageToolMessage(_ name: String) -> String { "\(name) is missing." } +} diff --git a/macos/Tests/LitheTests/PluginContentProviderTests.swift b/macos/Tests/LitheTests/PluginContentProviderTests.swift new file mode 100644 index 0000000000..3662a8f35b --- /dev/null +++ b/macos/Tests/LitheTests/PluginContentProviderTests.swift @@ -0,0 +1,135 @@ +import Foundation +import LitheCoreContracts +import Testing +@testable import Lithe + +/// Content providers of plugin backends (plan API-12): the binding, its +/// lifecycle, and Core's check of the answer. +@MainActor +struct PluginContentProviderTests { + private static let method = "lithe/host/documents/registerContentProvider" + + @MainActor + private struct Harness { + let fixture = PluginHostFixture() + let contexts = PluginWorkspaceContexts() + let context: PluginWorkspaceContext + let service: PluginContentProviderHostService + let dispatcher: PluginHostServiceDispatcher + let session: String + + init(grants: [String] = [PluginContentProviderTests.method]) { + context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) + service = PluginContentProviderHostService(contexts: contexts, decoder: DeclarativePluginTestSupport.operations) + dispatcher = PluginHostServiceDispatcher(contexts: contexts) + dispatcher.register(service) + session = dispatcher.beginSession(pluginID: "tool", hostServices: grants) + service.updateFunctions(pluginID: "tool", sessionID: session, ids: ["documents.read"]) + } + + func tearDown() { + dispatcher.endSession(pluginID: "tool") + fixture.tearDown() + } + + func register(scheme: String, function: String = "documents.read") async -> Result { + await dispatcher.dispatch( + PluginHostRequest(id: "registration", method: PluginContentProviderTests.method, service: "documents", params: .object([ + "context": .object(["contextID": .string(context.contextID), "generation": .integer(context.generation)]), + "scheme": .string(scheme), + "function": .string(function), + ])), + pluginID: "tool" + ) + } + } + + @Test + func aRegisteredSchemeIsServedByItsFunctionInThisWindowOnly() async throws { + let harness = Harness() + defer { harness.tearDown() } + + _ = try await harness.register(scheme: "metals-library").get() + + let provider = try #require(harness.service.provider(forScheme: "metals-library", context: harness.context.reference)) + #expect(provider.pluginID == "tool") + #expect(provider.functionID == "documents.read") + #expect(harness.service.provider(forScheme: "other", context: harness.context.reference) == nil) + let elsewhere = PluginWorkspaceContextReference(contextID: "another", generation: 1) + #expect(harness.service.provider(forScheme: "metals-library", context: elsewhere) == nil) + } + + @Test + func aSchemeHasOneProviderPerWindow() async throws { + let harness = Harness() + defer { harness.tearDown() } + _ = try await harness.register(scheme: "metals-library").get() + + guard case .failure(let error) = await harness.register(scheme: "metals-library") else { + Issue.record("a second provider for the scheme must be refused"); return + } + #expect(error.code == "plugin.host.preconditionFailed") + } + + @Test + func aFunctionTheSessionDidNotRegisterCreatesNoProvider() async { + let harness = Harness() + defer { harness.tearDown() } + + guard case .failure(let error) = await harness.register(scheme: "metals-library", function: "unknown.function") else { + Issue.record("an unknown function must be refused"); return + } + #expect(error.code == "plugin.host.invalidParams") + #expect(harness.service.provider(forScheme: "metals-library", context: harness.context.reference) == nil) + } + + @Test + func withoutTheGrantNothingIsRegistered() async { + let harness = Harness(grants: []) + defer { harness.tearDown() } + + guard case .failure(let error) = await harness.register(scheme: "metals-library") else { + Issue.record("the grant is required"); return + } + #expect(error.code == "plugin.host.permissionDenied") + } + + @Test + func disposingWithdrawingAndClosingTheContextRemoveTheProvider() async throws { + let harness = Harness() + defer { harness.tearDown() } + let context = harness.context.reference + + // Disposing the subscription. + let result = try await harness.register(scheme: "metals-library").get() + guard case .object(let value) = result, case .string(let subscription)? = value["subscriptionID"] else { + Issue.record("missing subscription"); return + } + harness.dispatcher.subscriptions.dispose(pluginID: "tool", subscriptionID: subscription) + #expect(harness.service.provider(forScheme: "metals-library", context: context) == nil) + + // Withdrawing the function; a reused function ID must not revive it. + _ = try await harness.register(scheme: "metals-library").get() + harness.service.updateFunctions(pluginID: "tool", sessionID: harness.session, ids: []) + #expect(harness.service.provider(forScheme: "metals-library", context: context) == nil) + harness.service.updateFunctions(pluginID: "tool", sessionID: harness.session, ids: ["documents.read"]) + #expect(harness.service.provider(forScheme: "metals-library", context: context) == nil) + + // Closing the window's context. + _ = try await harness.register(scheme: "metals-library").get() + harness.contexts.close(owner: harness.fixture.window) + #expect(harness.service.provider(forScheme: "metals-library", context: context) == nil) + #expect(harness.dispatcher.subscriptions.count(pluginID: "tool") == 0) + } + + @Test + func coreAcceptsAStringOrAContentObjectAndRefusesTheRest() throws { + let service = PluginContentProviderHostService(contexts: PluginWorkspaceContexts(), decoder: DeclarativePluginTestSupport.operations) + + #expect(try service.content(of: .string("class A {}")) == "class A {}") + #expect(try service.content(of: .object(["content": .string("class A {}")])) == "class A {}") + #expect(throws: (any Error).self) { try service.content(of: .integer(7)) } + #expect(throws: (any Error).self) { try service.content(of: .object(["content": .integer(7)])) } + #expect(throws: (any Error).self) { try service.content(of: .string(String(repeating: "a", count: 1024 * 1024 + 1))) } + } +} diff --git a/macos/Tests/LitheTests/PluginHostTestSupport.swift b/macos/Tests/LitheTests/PluginHostTestSupport.swift index 7b5bba49da..5fc4906100 100644 --- a/macos/Tests/LitheTests/PluginHostTestSupport.swift +++ b/macos/Tests/LitheTests/PluginHostTestSupport.swift @@ -44,6 +44,7 @@ final class FakePluginHostWindow: PluginHostWindowPort { var snapshot: PluginHostWindowSnapshot? var hostDocumentService: (any EditorDocumentServicing)? + var hostLanguageServers: (any PluginLanguageServerRouting)? var htmlPreviewOnly: [String: Bool] = [:] func hostSetHTMLPresentation(at url: URL, previewOnly: Bool) throws { htmlPreviewOnly[url.path] = previewOnly diff --git a/macos/Tests/LitheTests/PluginLanguageServerHostServiceTests.swift b/macos/Tests/LitheTests/PluginLanguageServerHostServiceTests.swift new file mode 100644 index 0000000000..6bba14d6b9 --- /dev/null +++ b/macos/Tests/LitheTests/PluginLanguageServerHostServiceTests.swift @@ -0,0 +1,289 @@ +import Foundation +@testable import Lithe +import LitheCoreContracts +import LitheLanguageIntelligenceModule +import Testing + +/// `lithe/host/languageServer/request`, `notify` and `setStatus` (plan +/// API-25) as a backend reaches them: the params that cross into the +/// session, and the failures that come back in the backend's shape. Rust +/// Core decides what a server may be asked; these tests use a recording +/// session and check only what the host adds. +@MainActor +struct PluginLanguageServerHostServiceTests { + private static let methods = [ + "lithe/host/languageServer/request", + "lithe/host/languageServer/notify", + "lithe/host/languageServer/setStatus", + ] + + @MainActor + private struct Harness { + let fixture = PluginHostFixture() + let contexts = PluginWorkspaceContexts() + let context: PluginWorkspaceContext + let dispatcher: PluginHostServiceDispatcher + let servers = RecordingServers() + + init(grants: [String] = PluginLanguageServerHostServiceTests.methods, withSessions: Bool = true) { + context = contexts.open(owner: fixture.window, rootURL: PluginHostFixture.workspaceURL, remote: nil) + fixture.window.hostLanguageServers = withSessions ? servers : nil + dispatcher = PluginHostServiceDispatcher(contexts: contexts) + dispatcher.register(PluginLanguageServerHostService(contexts: contexts)) + _ = dispatcher.beginSession(pluginID: "tool", hostServices: grants) + } + + func tearDown() { + dispatcher.endSession(pluginID: "tool") + fixture.tearDown() + } + + func call( + _ method: String, _ params: [String: ToolingJSONValue] + ) async -> Result { + var withContext = params + withContext["context"] = .object([ + "contextID": .string(context.contextID), "generation": .integer(context.generation), + ]) + return await dispatcher.dispatch( + PluginHostRequest(id: "call", method: method, service: "languageServer", params: .object(withContext)), + pluginID: "tool" + ) + } + + func request(_ params: [String: ToolingJSONValue] = [:]) async -> Result { + await call(PluginLanguageServerHostServiceTests.methods[0], base(params)) + } + + func notify(_ params: [String: ToolingJSONValue] = [:]) async -> Result { + await call(PluginLanguageServerHostServiceTests.methods[1], base(params)) + } + + func setStatus(_ params: [String: ToolingJSONValue]) async -> Result { + await call(PluginLanguageServerHostServiceTests.methods[2], ["serverID": .string("scala")].merging(params) { $1 }) + } + + private func base(_ params: [String: ToolingJSONValue]) -> [String: ToolingJSONValue] { + ["serverID": .string("scala"), "method": .string("textDocument/definition")].merging(params) { $1 } + } + } + + // MARK: request + + @Test + func aRequestReachesTheSessionAndItsValueComesBack() async throws { + let harness = Harness() + defer { harness.tearDown() } + harness.servers.requestOutcome = .success(.array([.string("Main.scala")])) + + let answer = try await harness.request([ + "params": .object(["position": .integer(3)]), "timeoutMilliseconds": .integer(2_500), + ]).get() + + #expect(answer == .object(["value": .array([.string("Main.scala")])])) + #expect(harness.servers.requests == [.init( + pluginID: "tool", serverID: "scala", method: "textDocument/definition", + params: .object(["position": .integer(3)]), timeout: 2.5 + )]) + } + + @Test + func aRequestWithoutParamsOrTimeoutLeavesBothToTheEngine() async throws { + let harness = Harness() + defer { harness.tearDown() } + + _ = try await harness.request().get() + + #expect(harness.servers.requests.first?.params == .object([:])) + #expect(harness.servers.requests.first?.timeout == nil) + } + + @Test + func aTimeoutOutsideTheContractedRangeNeverReachesTheSession() async { + let harness = Harness() + defer { harness.tearDown() } + + for milliseconds in [0, -1, 300_001] { + guard case .failure(let failure) = await harness.request(["timeoutMilliseconds": .integer(milliseconds)]) else { + Issue.record("\(milliseconds) ms must be refused"); continue + } + #expect(failure.code == "plugin.host.invalidParams") + } + #expect(harness.servers.requests.isEmpty) + } + + @Test + func aParameterTheContractDoesNotDefineIsRefused() async { + let harness = Harness() + defer { harness.tearDown() } + + guard case .failure(let failure) = await harness.request(["workspaceFolder": .string("/x")]) else { + Issue.record("an unknown parameter must be refused"); return + } + + #expect(failure.code == "plugin.host.unsupportedOption") + #expect(harness.servers.requests.isEmpty) + } + + // MARK: notify + + @Test + func aNotificationReportsWhetherTheServerGotIt() async throws { + let harness = Harness() + defer { harness.tearDown() } + + harness.servers.notifyOutcome = .success(true) + #expect(try await harness.notify().get() == .object(["delivered": .bool(true)])) + harness.servers.notifyOutcome = .success(false) + #expect(try await harness.notify().get() == .object(["delivered": .bool(false)])) + } + + // MARK: setStatus + + @Test + func aStatusIsRecordedForTheServerAndAnswersEmpty() async throws { + let harness = Harness() + defer { harness.tearDown() } + + let answer = try await harness.setStatus([ + "state": .string("preparing"), "message": .string("Importing build"), "percentage": .integer(40), + ]).get() + + #expect(answer == .object([:])) + #expect(harness.servers.statuses == [.init( + status: PluginServerStatus(state: .preparing, message: "Importing build", percentage: 40), + serverID: "scala", pluginID: "tool" + )]) + } + + @Test + func aStatusOutsideTheContractIsRefused() async { + let harness = Harness() + defer { harness.tearDown() } + + for params: [String: ToolingJSONValue] in [ + ["state": .string("booting")], + ["state": .string("preparing"), "percentage": .integer(101)], + ["state": .string("preparing"), "percentage": .integer(-1)], + [:], + ] { + guard case .failure(let failure) = await harness.setStatus(params) else { + Issue.record("\(params) must be refused"); continue + } + #expect(failure.code == "plugin.host.invalidParams") + } + // The first version of the contract has no status actions. + guard case .failure(let option) = await harness.setStatus(["state": .string("preparing"), "actions": .array([])]) else { + Issue.record("status actions must be refused"); return + } + #expect(option.code == "plugin.host.unsupportedOption") + #expect(harness.servers.statuses.isEmpty) + } + + // MARK: failures + + @Test + func theSessionsFailuresReachTheBackendWithTheirStableCodes() async { + let harness = Harness() + defer { harness.tearDown() } + let serverError = PluginHostRequestFailure( + message: "Server refused", code: "plugin.host.languageServerError", + details: .object(["code": .integer(-32_001), "message": .string("no build")]) + ) + let outcomes: [PluginHostRequestFailure] = [ + .languageServerUnavailable, .foreignContribution, serverError, + ] + + for outcome in outcomes { + harness.servers.requestOutcome = .failure(outcome) + guard case .failure(let failure) = await harness.request() else { + Issue.record("\(outcome.code ?? "") must fail"); continue + } + #expect(failure.code == outcome.code) + #expect(failure.message == outcome.message) + #expect(failure.details == outcome.details) + } + } + + @Test + func aCodeTheHostDoesNotKnowReachesTheBackendAsFailed() async { + let harness = Harness() + defer { harness.tearDown() } + harness.servers.requestOutcome = .failure(PluginHostRequestFailure(message: "?", code: "plugin.host.somethingNew")) + + guard case .failure(let failure) = await harness.request() else { + Issue.record("the outcome must fail"); return + } + + #expect(failure.code == "plugin.host.failed") + } + + @Test + func aWindowWithoutLanguageSessionsHasNoServerToAsk() async { + let harness = Harness(withSessions: false) + defer { harness.tearDown() } + + for result in [await harness.request(), await harness.notify(), await harness.setStatus(["state": .string("ready")])] { + guard case .failure(let failure) = result else { + Issue.record("a window without sessions must refuse"); continue + } + #expect(failure.code == "plugin.host.languageServerUnavailable") + } + } + + @Test + func aMethodTheManifestDidNotGrantIsDeniedBeforeTheSessionIsAsked() async { + let harness = Harness(grants: [Self.methods[0]]) + defer { harness.tearDown() } + + guard case .failure(let failure) = await harness.setStatus(["state": .string("ready")]) else { + Issue.record("setStatus without a grant must be denied"); return + } + + #expect(failure.code == "plugin.host.permissionDenied") + #expect(harness.servers.statuses.isEmpty) + } +} + +/// The window's language sessions, recording what the host passed on. +@MainActor +private final class RecordingServers: PluginLanguageServerRouting { + struct Request: Equatable { + let pluginID: String + let serverID: String + let method: String + let params: ToolingJSONValue + let timeout: TimeInterval? + } + + struct StatusCall: Equatable { + let status: PluginServerStatus + let serverID: String + let pluginID: String + } + + var requestOutcome: Result = .success(.null) + var notifyOutcome: Result = .success(true) + private(set) var requests: [Request] = [] + private(set) var statuses: [StatusCall] = [] + + func requestPluginServer( + pluginID: String, serverID: String, method: String, params: ToolingJSONValue, timeout: TimeInterval? + ) async -> Result { + requests.append(Request(pluginID: pluginID, serverID: serverID, method: method, params: params, timeout: timeout)) + return requestOutcome + } + + func notifyPluginServer( + pluginID: String, serverID: String, method: String, params: ToolingJSONValue + ) async -> Result { + notifyOutcome + } + + func setPluginServerStatus( + _ status: PluginServerStatus, serverID: String, pluginID: String + ) -> Result { + statuses.append(StatusCall(status: status, serverID: serverID, pluginID: pluginID)) + return .success(()) + } +} diff --git a/rust/lithe-core/src/lsp/interface/client.rs b/rust/lithe-core/src/lsp/interface/client.rs index 77f7199f3d..9a83e40bf8 100644 --- a/rust/lithe-core/src/lsp/interface/client.rs +++ b/rust/lithe-core/src/lsp/interface/client.rs @@ -564,7 +564,10 @@ pub(super) fn client_apply_server_message_for_plugin( result: Some(json!({ "id": id, "service": service, - "params": message.get("params").cloned().unwrap_or(Value::Null), + "params": plugin_function::forwarded_host_params( + method, + message.get("params"), + ), })), error: None, }) diff --git a/rust/lithe-core/src/lsp/interface/engine.rs b/rust/lithe-core/src/lsp/interface/engine.rs index 991350a99b..0c08036115 100644 --- a/rust/lithe-core/src/lsp/interface/engine.rs +++ b/rust/lithe-core/src/lsp/interface/engine.rs @@ -7,6 +7,7 @@ use super::client::{ use super::engine_logging::{ EngineLog, EngineLogInput, SessionLogIdentity, SessionRole, StderrFact, StderrLines, }; +use super::plugin_server::{self, Admission, Arrival, PluginServerState}; use super::process::{LspProcessHandle, LspProcessLauncher, LspProcessSpec, SystemProcessLauncher}; use super::{ client_change_document, client_close_document, client_feature_request_canonical, @@ -50,6 +51,10 @@ use crate::lsp::languages::jdt_build::{JavaBuildMarkerScope, JavaBuildRecovery}; use crate::lsp::languages::jdt_navigation::{JavaNavigationMarkerBatch, MAX_JAVA_NAVIGATION_TASKS}; use crate::lsp::languages::jdt_progress::JavaPreparationDiagnostics; use crate::lsp::languages::{prepare_jdt_configuration_area, prepare_jdt_workspace}; +use crate::plugins::language_server_sessions::{ + RemoteSupport, DEFAULT_REQUEST_TIMEOUT_MILLISECONDS, DID_CHANGE_CONFIGURATION, + MAX_REQUEST_TIMEOUT_MILLISECONDS, +}; use crate::protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -148,6 +153,12 @@ pub struct StartServerRequest { /// Shortcut import providers declared by this plugin's verified manifest. #[serde(default)] pub keymap_import_providers: Vec, + /// What the plugin backend may do with this plugin-owned language server + /// (plan API-25): the requests it may send, the gates they wait for, and + /// the notifications it receives. Only a plugin-owned session has one; + /// without it the backend cannot reach the server through the host. + #[serde(default)] + pub session_policy: Option, pub executable_path: String, #[serde(default)] pub arguments: Vec, @@ -628,6 +639,54 @@ fn empty_object() -> Value { json!({}) } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// One request a plugin backend sent to its own language server through the +/// host (plan API-25). The reply arrives as a `requestCompleted` event whose +/// `result.value` is the server's result; failures carry a `plugin.host.*` +/// code as `error.code`. +pub struct PluginServerRequest { + /// The plugin-owned language-server session the host resolved. + pub session_id: String, + #[serde(default)] + pub operation_id: Option, + /// The plugin and server the backend named. Core checks that the + /// session really is that contribution, so a stale or mistaken + /// resolution can never reach another plugin's server. + pub plugin_id: String, + #[serde(rename = "serverID")] + pub server_id: String, + /// An LSP request method the plugin declared in `requestMethods`. + pub method: String, + #[serde(default = "empty_object")] + pub params: Value, + /// Deadline in milliseconds, 60000 when absent and at most 300000. + #[serde(default)] + pub timeout_milliseconds: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// One notification a plugin backend sent to its own language server. +pub struct PluginServerNotify { + pub session_id: String, + pub plugin_id: String, + #[serde(rename = "serverID")] + pub server_id: String, + pub method: String, + #[serde(default = "empty_object")] + pub params: Value, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +/// Whether the notification reached the server. `false` means the server +/// was not initialized yet and will receive the stored configuration with +/// its `initialized` notification instead. +pub struct PluginServerNotifyResponse { + pub delivered: bool, +} + #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] /// Correlation identifier used to receive or cancel an asynchronous result. @@ -762,6 +821,11 @@ pub struct LspRuntimeError { /// passed through for the plugin's own UI; Lithe never branches on it. #[serde(skip_serializing_if = "Option::is_none")] pub plugin_error_code: Option, + /// Structured facts of a failed plugin-server request, such as the + /// server's own error `code` and `message`, passed to the backend as the + /// failure's details. Only `lsp.pluginServerRequest` sets it. + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option, } #[cfg(test)] @@ -807,6 +871,9 @@ enum PendingKind { /// Java Debug Server workspace build shared by the callers that /// `JavaBuildCoordinator` tracks; it carries no operation ID of its own. JavaBuild, + /// Request a plugin backend sent to its own language server through + /// `lsp.pluginServerRequest`; the answer reaches the backend verbatim. + PluginServer, /// Shutdown handshake after which the engine sends `exit`. Shutdown, } @@ -903,6 +970,9 @@ struct SessionState { deadline_cancellations: Vec, /// Bounds an outbound maintenance write independently of caller deadlines. maintenance_write_deadline: Option, + /// Policy and waiting requests of a plugin-owned language server; `None` + /// for every other session. + plugin_server: Option, /// Bounds one write the function relay's lane makes to this session, so a /// backend that stops reading its stdin cannot hold the lane forever. relay_write_deadline: Option, @@ -1747,6 +1817,28 @@ pub fn plugin_function_request( Ok(OperationResponse { operation_id }) } +/// Sends one request of a plugin backend to the plugin's own language server. +pub fn plugin_server_request(request: PluginServerRequest) -> Result { + let operation_id = request + .operation_id + .clone() + .unwrap_or_else(|| engine().next_operation_id()); + engine() + .session(&request.session_id)? + .plugin_server_request(request, operation_id.clone())?; + Ok(OperationResponse { operation_id }) +} + +/// Sends one notification of a plugin backend to the plugin's own language server. +pub fn plugin_server_notify( + request: PluginServerNotify, +) -> Result { + let delivered = engine() + .session(&request.session_id)? + .plugin_server_notify(request)?; + Ok(PluginServerNotifyResponse { delivered }) +} + /// Replaces the host's view of the enabled plugins and live workspace /// contexts that the cross-plugin function relay checks calls against. Calls /// in flight that the new view forbids end with an error. @@ -1988,6 +2080,17 @@ impl LspEngine { "Remote Java language servers require a host-compatible plugin launch plan", )); } + if crate::remote::workspace::is_remote() + && request + .session_policy + .as_ref() + .is_some_and(|policy| policy.remote == RemoteSupport::Unsupported) + { + return Err(CoreError::new( + ErrorCode::NotSupported, + "The plugin's language server does not support remote workspaces", + )); + } // Initial provider settings must include native Git decisions even when // no session or inventory warm-up has run. Never scan under registry locks. let indexing_root = canonical_workspace_path(&request.root_uri); @@ -2208,6 +2311,7 @@ impl LspEngine { let java_startup_detail = java_preparation .as_ref() .map(JavaPreparationDiagnostics::startup_detail); + let plugin_server = request.session_policy.map(PluginServerState::new); let session = Arc::new(RuntimeSession { startup_attempt: Arc::clone(attempt), id: session_id.clone(), @@ -2285,6 +2389,7 @@ impl LspEngine { java_build_timeout, deadline_cancellations: Vec::new(), maintenance_write_deadline: None, + plugin_server, relay_write_deadline: None, host_requests: BTreeMap::new(), next_host_request_id: 1, @@ -3544,6 +3649,94 @@ impl RuntimeSession { Ok(true) } + /// Admits a backend's request to its language server: it is sent now, + /// held behind a gate, or joined to a command that already runs. + fn plugin_server_request( + &self, + request: PluginServerRequest, + operation_id: String, + ) -> Result<(), CoreError> { + let outbound_order = self.lock_outbound_order()?; + let (messages, request_id) = { + let mut state = self.lock_state()?; + if state.request_by_operation.contains_key(&operation_id) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The language-server operation ID is already pending.", + )); + } + let server = plugin_server_target( + &mut state, + self.plugin_id.as_deref(), + &request.plugin_id, + &request.server_id, + )?; + let now = Instant::now(); + let deadline = now + plugin_server_timeout(request.timeout_milliseconds); + let admission = server.admit_request(Arrival { + operation_id: &operation_id, + method: &request.method, + params: &request.params, + now, + deadline, + })?; + if admission != Admission::Send { + // Held and joined requests are written later, or never. + return Ok(()); + } + match register_plugin_server_request( + &mut state, + &operation_id, + &request.method, + request.params, + now, + deadline, + ) { + Ok(registered) => registered, + Err(error) => { + if let Some(server) = state.plugin_server.as_mut() { + server.finish(&operation_id); + } + return Err(error); + } + } + }; + self.send_request_or_fail(&outbound_order, messages, &request_id) + } + + /// Sends a backend's notification to its language server. Returns whether + /// it was sent now. + fn plugin_server_notify(&self, request: PluginServerNotify) -> Result { + { + let mut state = self.lock_state()?; + let server = plugin_server_target( + &mut state, + self.plugin_id.as_deref(), + &request.plugin_id, + &request.server_id, + )?; + server.admit_notification(&request.method, &request.params)?; + } + if request.method == DID_CHANGE_CONFIGURATION { + // The settings also answer the server's own `workspace/configuration` + // requests, so they go through the plugin configuration. + let settings = request + .params + .get("settings") + .filter(|settings| settings.is_object()) + .cloned() + .ok_or_else(|| { + CoreError::new(ErrorCode::InvalidRequest, "settings must be an object.") + .with_details(super::plugin_function::codes::HOST_INVALID_PARAMS) + })?; + return Ok(self.update_plugin_configuration(settings)?.sent); + } + let message = json_rpc_notification(&request.method, request.params)?; + let outbound_order = self.lock_outbound_order()?; + self.send_messages_or_fail(&outbound_order, vec![message], "pluginServerNotify")?; + Ok(true) + } + fn request_with_kind( &self, request: SemanticRequest, @@ -3918,6 +4111,14 @@ impl RuntimeSession { "requestCancel", ); } + if state + .plugin_server + .as_ref() + .is_some_and(|server| server.is_unsent(operation_id)) + { + cancel_unsent_plugin_server_request(self, &mut state, operation_id); + return Ok(()); + } let request_id = state .request_by_operation .remove(operation_id) @@ -4612,10 +4813,30 @@ impl RuntimeSession { None, ) }); - let result = normalize_provider_navigation_result( - &self.provider_id, - event.and_then(|event| event.result.clone()), + let result = event.and_then(|event| event.result.clone()); + // A plugin-owned server has no provider-specific + // rule; it only marks locations that are not files. + let result = if state.plugin_server.is_some() { + plugin_server::normalize_navigation_result(result) + } else { + normalize_provider_navigation_result(&self.provider_id, result) + }; + push_request_event( + self, + &mut state, + operation_id, + &pending.method, + result, + error, ); + } + } + } + Some(PendingKind::PluginServer) => { + if let Some(pending) = pending_before.as_ref() { + if let Some(operation_id) = &pending.operation_id { + let (result, error) = + plugin_server_answer(self, &pending.method, &value); push_request_event( self, &mut state, @@ -5231,6 +5452,14 @@ impl RuntimeSession { } for event in reduced.events { + if event.kind == "notification" { + outbound.extend(observe_plugin_server_notification( + self, + &mut state, + event.method.as_deref(), + event.result.as_ref(), + )); + } if event.kind == "semanticTokensRefresh" { push_semantic_tokens_refresh_event(self, &mut state); } else if event.kind == "functionsChanged" { @@ -6147,6 +6376,7 @@ impl RuntimeSession { | PendingKind::JavaNavigationMarkers | PendingKind::JavaNavigationMarkerResolve | PendingKind::JavaResolveNavigation + | PendingKind::PluginServer ) && now >= pending.deadline }) .map(|(id, _)| id.clone()) @@ -6183,6 +6413,32 @@ impl RuntimeSession { } cancellations.push(request_id); } + let held_expired = state + .plugin_server + .as_ref() + .map(|server| server.expired_held(now)) + .unwrap_or_default(); + for waiter in held_expired { + // Nothing was sent, so there is nothing to cancel on the wire. + let error = runtime_error( + self, + "requestTimeout", + "request", + Some(&waiter.method), + None, + "Language-server request timed out waiting for the server to become ready.", + None, + None, + ); + push_request_event( + self, + &mut state, + &waiter.operation_id, + &waiter.method, + None, + Some(error), + ); + } let maven_profiles_running = state.maven_profile_status == MavenProfileTaskStatus::Running; let departure = state.java_builds.expire(maven_profiles_running, now); @@ -6700,6 +6956,9 @@ fn validate_start_request(request: &StartServerRequest) -> Result<(), CoreError> { return Err(invalid_field("hostServices")); } + if let Some(policy) = &request.session_policy { + policy.validate(request.plugin_id.as_deref())?; + } if !request.host_options.is_empty() && (request.plugin_id.is_none() || request @@ -7352,6 +7611,14 @@ fn push_request_event( result: Option, error: Option, ) { + if state + .plugin_server + .as_ref() + .is_some_and(|server| server.owns(operation_id)) + { + complete_plugin_server_request(session, state, operation_id, method, result, error); + return; + } // No host operation waits for a relayed call: the relay answers the // calling plugin, so the event never reaches the host. if relay_hub::is_relayed_operation(operation_id, method) { @@ -7443,6 +7710,51 @@ fn push_request_event( } else { (result, error) }; + enqueue_request_completed(session, state, operation_id, method, result, error); +} + +/// Ends a request the backend sent to its plugin-owned language server. This +/// is the only place where the session policy releases such an operation, so +/// every way a request can end (answer, cancel, timeout, session failure) +/// leaves the policy consistent. Requests that joined a running command +/// finish with the same result or error. +fn complete_plugin_server_request( + session: &RuntimeSession, + state: &mut SessionState, + operation_id: &str, + method: &str, + result: Option, + mut error: Option, +) { + if let Some(error) = error.as_mut() { + error.code = plugin_server::host_error_code(&error.code).to_string(); + } + let joined = state + .plugin_server + .as_mut() + .map(|server| server.finish(operation_id)) + .unwrap_or_default(); + for waiter in joined { + enqueue_request_completed( + session, + state, + &waiter.operation_id, + &waiter.method, + result.clone(), + error.clone(), + ); + } + enqueue_request_completed(session, state, operation_id, method, result, error); +} + +fn enqueue_request_completed( + session: &RuntimeSession, + state: &mut SessionState, + operation_id: &str, + method: &str, + result: Option, + error: Option, +) { let sequence = take_sequence(state); enqueue_runtime_event( session, @@ -7944,6 +8256,200 @@ fn function_runtime_error( error } +/// The plugin-owned server a call targets, after checking that the session +/// is that contribution and can take requests now. +fn plugin_server_target<'a>( + state: &'a mut SessionState, + session_plugin_id: Option<&str>, + plugin_id: &str, + server_id: &str, +) -> Result<&'a mut PluginServerState, CoreError> { + let ready = state.lifecycle == LspLifecycleState::Ready && state.client.initialized; + let server = state + .plugin_server + .as_mut() + .ok_or_else(plugin_server::foreign_contribution)?; + server.check_owner(session_plugin_id, plugin_id, server_id)?; + if !ready { + return Err(plugin_server::unavailable()); + } + Ok(server) +} + +fn plugin_server_timeout(requested: Option) -> Duration { + let milliseconds = requested + .unwrap_or(DEFAULT_REQUEST_TIMEOUT_MILLISECONDS) + .clamp(1, MAX_REQUEST_TIMEOUT_MILLISECONDS); + Duration::from_millis(milliseconds) +} + +/// Allocates the JSON-RPC request of an admitted operation and records it as +/// pending. Returns the messages to write and the request ID. +fn register_plugin_server_request( + state: &mut SessionState, + operation_id: &str, + method: &str, + params: Value, + created_at: Instant, + deadline: Instant, +) -> Result<(Vec, String), CoreError> { + let response = allocate_raw_request(state.client.clone(), method, params)?; + let request_id = (response.state.next_request_id - 1).to_string(); + state.client = response.state; + state.pending.insert( + request_id.clone(), + PendingRequest { + kind: PendingKind::PluginServer, + operation_id: Some(operation_id.to_string()), + method: method.to_string(), + document_uri: None, + document_version: None, + created_at, + deadline, + }, + ); + state + .request_by_operation + .insert(operation_id.to_string(), request_id.clone()); + Ok((response.messages, request_id)) +} + +/// Applies a notification the server sent to a plugin-owned session: it may +/// open gates, and the backend may have asked to receive it. Returns the +/// messages of the requests that waited for those gates. +fn observe_plugin_server_notification( + session: &RuntimeSession, + state: &mut SessionState, + method: Option<&str>, + params: Option<&Value>, +) -> Vec { + let (Some(method), Some(server)) = (method, state.plugin_server.as_mut()) else { + return Vec::new(); + }; + let observation = server.observe(method, params.unwrap_or(&Value::Null)); + if let Some(forwarded) = observation.forward { + push_negotiated_provider_event(session, state, forwarded, "pluginServerNotification"); + } + observation + .released + .into_iter() + .flat_map(|held| release_held_plugin_server_request(session, state, held)) + .collect() +} + +/// Sends a request whose gates opened. It keeps the deadline it was +/// admitted with, so the time spent waiting counts against its timeout. +fn release_held_plugin_server_request( + session: &RuntimeSession, + state: &mut SessionState, + held: plugin_server::HeldRequest, +) -> Vec { + let registered = register_plugin_server_request( + state, + &held.operation_id, + &held.method, + held.params, + held.created_at, + held.deadline, + ); + match registered { + Ok((messages, _)) => messages, + Err(error) => { + let failure = runtime_error( + session, + "transportFailed", + "request", + Some(&held.method), + None, + "Could not encode the language-server request.", + Some(&error.message), + None, + ); + push_request_event( + session, + state, + &held.operation_id, + &held.method, + None, + Some(failure), + ); + Vec::new() + } + } +} + +/// Cancels a plugin-server request that never reached the server, because it +/// waits behind a gate or joined a running command. Nothing is written. +fn cancel_unsent_plugin_server_request( + session: &RuntimeSession, + state: &mut SessionState, + operation_id: &str, +) { + let method = state + .plugin_server + .as_ref() + .and_then(|server| server.method_of(operation_id)) + .unwrap_or_default() + .to_string(); + let error = runtime_error( + session, + "requestCancelled", + "request", + Some(&method), + None, + "Language-server request was cancelled.", + None, + None, + ); + push_request_event(session, state, operation_id, &method, None, Some(error)); +} + +/// What the backend receives for a plugin-owned server's reply: the result +/// untouched, so no Lithe normalizer reinterprets the server's own protocol, +/// or the server's error code and message as details of +/// `plugin.host.languageServerError`. +fn plugin_server_answer( + session: &RuntimeSession, + method: &str, + reply: &Value, +) -> (Option, Option) { + use super::plugin_function::{bounded_host_message, codes, MAX_RESULT_BYTES}; + let failure = |code: &str, message: &str| { + runtime_error( + session, + code, + "request", + Some(method), + None, + message, + None, + None, + ) + }; + if let Some(upstream) = reply.get("error") { + let mut error = failure( + codes::HOST_LANGUAGE_SERVER_ERROR, + "The language server returned an error.", + ); + let message = upstream + .get("message") + .and_then(Value::as_str) + .map(bounded_host_message); + error.details = Some(json!({ "code": upstream.get("code"), "message": message })); + return (None, Some(error)); + } + let result = reply.get("result").cloned().unwrap_or(Value::Null); + let size = serde_json::to_vec(&result).map_or(usize::MAX, |bytes| bytes.len()); + if size > MAX_RESULT_BYTES { + let error = failure( + codes::HOST_LIMIT_EXCEEDED, + "The language server's result is too large.", + ); + return (None, Some(error)); + } + (Some(json!({ "value": result })), None) +} + fn normalize_provider_navigation_result( provider_id: &str, mut result: Option, @@ -8498,6 +9004,7 @@ fn runtime_error( process_exit_code, java_build_report: None, plugin_error_code: None, + details: None, } } @@ -8543,6 +9050,7 @@ fn fail_feature_requests( | PendingKind::JavaNavigationMarkers | PendingKind::JavaNavigationMarkerResolve | PendingKind::JavaResolveNavigation + | PendingKind::PluginServer ) }) .map(|(request_id, pending)| (request_id.clone(), pending.clone())) @@ -8575,6 +9083,32 @@ fn fail_feature_requests( ); } } + // Requests held behind a gate have no pending entry, so they end here. + let held = state + .plugin_server + .as_ref() + .map(|server| server.all_held()) + .unwrap_or_default(); + for waiter in held { + let error = runtime_error( + session, + code, + stage, + Some(&waiter.method), + None, + message, + None, + exit_code, + ); + push_request_event( + session, + state, + &waiter.operation_id, + &waiter.method, + None, + Some(error), + ); + } let (build_operation_ids, build_request_id) = state.java_builds.drain(); if let Some(request_id) = build_request_id { state.pending.remove(&request_id); @@ -8795,6 +9329,7 @@ mod tests { host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), + session_policy: None, executable_path: "/usr/bin/scripted-server".to_string(), arguments: vec!["--stdio".to_string()], environment: BTreeMap::new(), @@ -14292,6 +14827,7 @@ public class Main { host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), + session_policy: None, executable_path, arguments: Vec::new(), environment: BTreeMap::from([( @@ -15057,6 +15593,7 @@ public class Main { host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), + session_policy: None, executable_path: "/bin/server".to_string(), arguments: Vec::new(), environment: BTreeMap::new(), @@ -18090,4 +18627,549 @@ public class Main { json!({ "contextID": "w1", "generation": 2 }) ); } + + /// Requests and notifications of a plugin backend to its own language + /// server (plan API-25). The stub servers are Metals-like (a gate and a + /// command that runs one at a time) and rust-analyzer-like (neither), so + /// no case depends on one language. + mod plugin_owned_server { + use super::*; + + const PLUGIN: &str = "dev.lithe.metals"; + const SERVER: &str = "metals"; + const STATUS: &str = "metals/status"; + + /// The policy of the Metals-like server. `gated` adds the gate that + /// holds requests until the server reports it is ready. + fn metals_policy(gated: bool) -> Value { + let mut policy = json!({ + "serverID": SERVER, + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand", + "metals/slow", + "metals/didFocus" + ], + "commands": ["build-import", "build-connect"], + "serializedCommands": ["build-import"], + "forwardNotifications": [STATUS], + }); + if gated { + policy["gates"] = json!([{ + "id": "imported", + "until": "notification", + "method": STATUS, + "match": { "text": "ready" } + }]); + } + policy + } + + /// A rust-analyzer-like server: no gate, no serialized command. + fn rust_analyzer_policy() -> Value { + json!({ + "serverID": SERVER, + "requestMethods": ["experimental/runnables"], + }) + } + + fn start(policy: Value) -> Harness { + let mut harness = Harness::start(move |request| { + request.plugin_id = Some(PLUGIN.to_string()); + request.session_policy = + Some(serde_json::from_value(policy).expect("the policy should decode")); + }); + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + harness + } + + /// The `lsp.pluginServerRequest` payload the host sends. + fn wire(harness: &Harness, operation_id: &str, method: &str, params: Value) -> Value { + json!({ + "sessionId": harness.session_id, + "operationId": operation_id, + "pluginId": PLUGIN, + "serverID": SERVER, + "method": method, + "params": params, + }) + } + + fn send(harness: &Harness, wire: Value) -> Result<(), CoreError> { + let operation_id = wire["operationId"].as_str().unwrap().to_string(); + let request: PluginServerRequest = + serde_json::from_value(wire).expect("documented wire shape"); + harness + .session() + .plugin_server_request(request, operation_id) + } + + fn call( + harness: &Harness, + operation_id: &str, + method: &str, + params: Value, + ) -> Result<(), CoreError> { + send(harness, wire(harness, operation_id, method, params)) + } + + fn run_command( + harness: &Harness, + operation_id: &str, + command: &str, + ) -> Result<(), CoreError> { + call( + harness, + operation_id, + "workspace/executeCommand", + json!({ "command": command, "arguments": [] }), + ) + } + + fn notify(harness: &Harness, method: &str, params: Value) -> Result { + let request: PluginServerNotify = serde_json::from_value(json!({ + "sessionId": harness.session_id, + "pluginId": PLUGIN, + "serverID": SERVER, + "method": method, + "params": params, + })) + .expect("documented wire shape"); + harness.session().plugin_server_notify(request) + } + + /// The server reports `text` through its status notification. + fn report_status(harness: &Harness, text: &str) { + harness.server.send(json!({ + "jsonrpc": "2.0", + "method": STATUS, + "params": { "text": text } + })); + } + + /// Waits until Core has applied the status notification of `text`. The + /// notification is forwarded to the backend, so the forwarded event + /// proves the engine already processed it. + fn await_status_seen(harness: &mut Harness, text: &str) { + harness.await_event(|event| { + event.kind == "pluginServerNotification" + && event + .result + .as_ref() + .is_some_and(|result| result["params"]["text"] == text) + }); + } + + fn reply(harness: &Harness, request_id: &str, result: Value) { + harness.server.send(json!({ + "jsonrpc": "2.0", "id": request_id, "result": result + })); + } + + fn completed(harness: &mut Harness, operation_id: &str) -> LspRuntimeEvent { + harness + .await_event(|event| { + event.kind == "requestCompleted" + && event.operation_id.as_deref() == Some(operation_id) + }) + .clone() + } + + fn error_code(event: &LspRuntimeEvent) -> &str { + &event.error.as_ref().expect("the request failed").code + } + + fn written(harness: &Harness, method: &str) -> usize { + harness + .server + .messages() + .iter() + .filter(|message| message["method"] == method) + .count() + } + + fn refusal_code(error: CoreError) -> String { + error.details.expect("a refusal names its plugin.host code") + } + + /// The server's result reaches the backend untouched, even for a + /// method whose result Lithe normalizes for its own editor. + #[test] + fn a_declared_request_returns_the_servers_own_result() { + let mut harness = start(metals_policy(false)); + call( + &harness, + "def-1", + "textDocument/definition", + json!({ "textDocument": { "uri": "file:///workspace/A.scala" } }), + ) + .expect("a declared method is sent"); + let request_id = harness + .server + .await_request("textDocument/definition") + .expect("the request should reach the server"); + let location = json!({ + "uri": "jar:file:///cache/lib.jar!/Lib.scala", + "range": { + "start": { "line": 1, "character": 2 }, + "end": { "line": 1, "character": 5 } + } + }); + reply(&harness, &request_id, json!([location])); + + let event = completed(&mut harness, "def-1"); + assert_eq!(event.result, Some(json!({ "value": [location] }))); + assert!(event.error.is_none()); + } + + #[test] + fn a_server_without_gates_or_commands_sends_at_once() { + let mut harness = start(rust_analyzer_policy()); + call(&harness, "run-1", "experimental/runnables", json!({})) + .expect("a declared method is sent"); + let request_id = harness + .server + .await_request("experimental/runnables") + .expect("nothing holds the request"); + reply(&harness, &request_id, json!([])); + assert_eq!( + completed(&mut harness, "run-1").result, + Some(json!({ "value": [] })) + ); + } + + #[test] + fn a_server_error_keeps_its_code_and_message_as_details() { + let mut harness = start(metals_policy(false)); + call(&harness, "slow-1", "metals/slow", json!({})).unwrap(); + let request_id = harness.server.await_request("metals/slow").unwrap(); + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": request_id, + "error": { "code": -32001, "message": "Build server is not connected." } + })); + + let event = completed(&mut harness, "slow-1"); + assert_eq!(error_code(&event), "plugin.host.languageServerError"); + assert_eq!( + event.error.unwrap().details, + Some(json!({ "code": -32001, "message": "Build server is not connected." })) + ); + } + + #[test] + fn a_method_the_plugin_did_not_declare_never_reaches_the_server() { + let harness = start(metals_policy(false)); + let error = call(&harness, "bad-1", "textDocument/rename", json!({})) + .expect_err("an undeclared method is refused"); + assert_eq!(refusal_code(error), "plugin.host.methodNotDeclared"); + + let error = run_command(&harness, "bad-2", "wipe-workspace") + .expect_err("an undeclared command is refused"); + assert_eq!(refusal_code(error), "plugin.host.methodNotDeclared"); + assert_eq!(written(&harness, "textDocument/rename"), 0); + assert_eq!(written(&harness, "workspace/executeCommand"), 0); + } + + /// The host resolves the session, so a call that names another plugin + /// or server, or a session without a policy, is the host's mistake and + /// must not reach any server. + #[test] + fn a_session_of_another_contribution_is_refused() { + let harness = start(metals_policy(false)); + for (plugin_id, server_id) in [("dev.lithe.other", SERVER), (PLUGIN, "other-server")] { + let mut foreign = wire(&harness, "foreign-1", "metals/slow", json!({})); + foreign["pluginId"] = json!(plugin_id); + foreign["serverID"] = json!(server_id); + let error = send(&harness, foreign).expect_err("a foreign contribution is refused"); + assert_eq!(refusal_code(error), "plugin.host.foreignContribution"); + } + assert_eq!(written(&harness, "metals/slow"), 0); + + let plain = Harness::ready(); + let error = call(&plain, "plain-1", "metals/slow", json!({})) + .expect_err("a session without a policy is no plugin server"); + assert_eq!(refusal_code(error), "plugin.host.foreignContribution"); + } + + #[test] + fn requests_wait_for_the_gate_and_are_sent_in_order() { + let mut harness = start(metals_policy(true)); + call(&harness, "first", "metals/slow", json!({ "n": 1 })).unwrap(); + call( + &harness, + "second", + "textDocument/definition", + json!({ "n": 2 }), + ) + .unwrap(); + assert_eq!(written(&harness, "metals/slow"), 0); + + // A status that does not match the gate leaves it closed. + report_status(&harness, "importing"); + await_status_seen(&mut harness, "importing"); + assert_eq!(written(&harness, "metals/slow"), 0); + assert_eq!(written(&harness, "textDocument/definition"), 0); + + report_status(&harness, "ready"); + let first = harness.server.await_request("metals/slow").unwrap(); + let second = harness + .server + .await_request("textDocument/definition") + .unwrap(); + let messages = harness.server.messages(); + let position = |id: &str| messages.iter().position(|message| message["id"] == id); + assert!( + position(&first) < position(&second), + "arrival order is kept" + ); + + reply(&harness, &first, json!("one")); + assert_eq!( + completed(&mut harness, "first").result, + Some(json!({ "value": "one" })) + ); + } + + #[test] + fn a_held_request_can_be_cancelled_without_touching_the_server() { + let mut harness = start(metals_policy(true)); + call(&harness, "held-1", "metals/slow", json!({})).unwrap(); + harness + .session() + .cancel_operation("held-1") + .expect("a held request can be cancelled"); + + let event = completed(&mut harness, "held-1"); + assert_eq!(error_code(&event), "plugin.host.cancelled"); + + // Opening the gate afterwards sends nothing: the request is gone. + report_status(&harness, "ready"); + await_status_seen(&mut harness, "ready"); + assert_eq!(written(&harness, "metals/slow"), 0); + assert_eq!(written(&harness, "$/cancelRequest"), 0); + } + + #[test] + fn a_held_request_times_out_while_it_waits() { + let mut harness = start(metals_policy(true)); + let mut held = wire(&harness, "held-1", "metals/slow", json!({})); + held["timeoutMilliseconds"] = json!(1); + send(&harness, held).unwrap(); + + let event = completed(&mut harness, "held-1"); + assert_eq!(error_code(&event), "plugin.host.timeout"); + assert_eq!(written(&harness, "metals/slow"), 0); + } + + #[test] + fn a_sent_request_times_out_and_is_cancelled_on_the_server() { + let mut harness = start(metals_policy(false)); + let mut slow = wire(&harness, "slow-1", "metals/slow", json!({})); + slow["timeoutMilliseconds"] = json!(1); + send(&harness, slow).unwrap(); + let request_id = harness.server.await_request("metals/slow").unwrap(); + + let event = completed(&mut harness, "slow-1"); + assert_eq!(error_code(&event), "plugin.host.timeout"); + let cancel = harness + .server + .await_notification_at("$/cancelRequest", 0) + .expect("the server is told to stop"); + assert_eq!(cancel["params"]["id"], json!(request_id)); + } + + /// A second request for a serialized command does not start a second + /// run; both finish with the answer of the one that runs. + #[test] + fn a_serialized_command_joins_the_one_that_runs() { + let mut harness = start(metals_policy(false)); + run_command(&harness, "import-1", "build-import").unwrap(); + let request_id = harness + .server + .await_request("workspace/executeCommand") + .unwrap(); + run_command(&harness, "import-2", "build-import").unwrap(); + // A command that is not serialized is independent of the first. + run_command(&harness, "connect-1", "build-connect").unwrap(); + harness + .server + .await_request_at("workspace/executeCommand", 1) + .expect("an independent command is sent"); + assert_eq!(written(&harness, "workspace/executeCommand"), 2); + + reply(&harness, &request_id, json!({ "imported": 3 })); + for operation_id in ["import-1", "import-2"] { + let event = completed(&mut harness, operation_id); + assert_eq!(event.result, Some(json!({ "value": { "imported": 3 } }))); + } + assert!(!harness + .events + .iter() + .any(|event| event.operation_id.as_deref() == Some("connect-1"))); + + // The command can run again once the first run is over. + run_command(&harness, "import-3", "build-import").unwrap(); + harness + .server + .await_request_at("workspace/executeCommand", 2) + .expect("a finished command can run again"); + } + + #[test] + fn cancelling_a_joiner_leaves_the_running_command_alone() { + let mut harness = start(metals_policy(false)); + run_command(&harness, "import-1", "build-import").unwrap(); + let request_id = harness + .server + .await_request("workspace/executeCommand") + .unwrap(); + run_command(&harness, "import-2", "build-import").unwrap(); + harness.session().cancel_operation("import-2").unwrap(); + assert_eq!( + error_code(&completed(&mut harness, "import-2")), + "plugin.host.cancelled" + ); + assert_eq!(written(&harness, "$/cancelRequest"), 0); + + reply(&harness, &request_id, json!(null)); + assert_eq!( + completed(&mut harness, "import-1").result, + Some(json!({ "value": null })) + ); + } + + #[test] + fn only_declared_server_notifications_are_forwarded() { + let mut harness = start(metals_policy(false)); + harness.server.send(json!({ + "jsonrpc": "2.0", + "method": "metals/unlisted", + "params": { "text": "private" } + })); + report_status(&harness, "indexing"); + await_status_seen(&mut harness, "indexing"); + + let forwarded: Vec<_> = harness + .events + .iter() + .filter(|event| event.kind == "pluginServerNotification") + .collect(); + assert_eq!(forwarded.len(), 1); + assert_eq!( + forwarded[0].result, + Some(json!({ + "serverID": SERVER, + "method": STATUS, + "params": { "text": "indexing" } + })) + ); + } + + #[test] + fn a_declared_notification_is_sent_and_a_command_is_not_a_notification() { + let harness = start(metals_policy(false)); + let sent = notify( + &harness, + "metals/didFocus", + json!({ "uri": "file:///A.scala" }), + ); + assert!(sent.expect("a declared notification is sent")); + let message = harness + .server + .await_notification_at("metals/didFocus", 0) + .expect("the server receives it"); + assert_eq!(message["params"], json!({ "uri": "file:///A.scala" })); + + let error = notify(&harness, "workspace/executeCommand", json!({})) + .expect_err("commands run as requests only"); + assert_eq!(refusal_code(error), "plugin.host.methodNotDeclared"); + let error = notify(&harness, "metals/unlisted", json!({})) + .expect_err("an undeclared notification is refused"); + assert_eq!(refusal_code(error), "plugin.host.methodNotDeclared"); + } + + /// New settings replace the stored configuration, so they also answer + /// the server's own `workspace/configuration` requests. + #[test] + fn changed_configuration_goes_through_the_plugin_configuration() { + let harness = start(metals_policy(false)); + let settings = json!({ "metals": { "scalafmt": true } }); + let sent = notify( + &harness, + "workspace/didChangeConfiguration", + json!({ "settings": settings }), + ); + assert!(sent.expect("the change is accepted")); + let change = harness + .server + .await_notification_at("workspace/didChangeConfiguration", 0) + .expect("the server receives the change"); + assert_eq!(change["params"]["settings"], settings); + + let error = notify( + &harness, + "workspace/didChangeConfiguration", + json!({ "settings": 1 }), + ) + .expect_err("settings must be an object"); + assert_eq!(refusal_code(error), "plugin.host.invalidParams"); + } + + #[test] + fn a_stopped_server_fails_what_is_in_flight_and_refuses_new_calls() { + let mut harness = start(metals_policy(false)); + call(&harness, "slow-1", "metals/slow", json!({})).unwrap(); + call(&harness, "focus-1", "metals/didFocus", json!({})).unwrap(); + harness.server.await_request("metals/slow").unwrap(); + harness.server.await_request("metals/didFocus").unwrap(); + + harness.server.exit(Some(1)); + harness.await_state(LspLifecycleState::Failed); + for operation_id in ["slow-1", "focus-1"] { + let event = completed(&mut harness, operation_id); + assert_eq!(error_code(&event), "plugin.host.languageServerUnavailable"); + } + + let error = call(&harness, "late-1", "metals/slow", json!({})) + .expect_err("a stopped server takes no requests"); + assert_eq!(refusal_code(error), "plugin.host.languageServerUnavailable"); + } + + #[test] + fn a_gated_request_still_waiting_fails_when_the_server_stops() { + let mut harness = start(metals_policy(true)); + call(&harness, "held-1", "metals/slow", json!({})).unwrap(); + + harness.server.exit(Some(1)); + harness.await_state(LspLifecycleState::Failed); + let event = completed(&mut harness, "held-1"); + assert_eq!(error_code(&event), "plugin.host.languageServerUnavailable"); + } + + #[test] + fn an_invalid_policy_is_refused_at_start() { + let refused = |plugin_id: Option<&str>, policy: Value| { + let server = ScriptedServer::new(); + let engine = LspEngine::with_launcher(server.launcher()); + let mut request = start_request(&server); + request.plugin_id = plugin_id.map(ToString::to_string); + request.session_policy = Some(serde_json::from_value(policy).unwrap()); + match engine.start_server(request) { + Err(error) => matches!(error.code, ErrorCode::InvalidRequest), + Ok(_) => false, + } + }; + // The server ID is no protocol name. + assert!(refused(Some(PLUGIN), json!({ "serverID": "" }))); + // A serialized command must also be a declared command. + assert!(refused( + Some(PLUGIN), + json!({ "serverID": SERVER, "serializedCommands": ["build-import"] }) + )); + // A host-owned server has no backend, so it cannot have a policy. + assert!(refused(None, metals_policy(false))); + } + } } 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 9ec5af1808..1dedf37c4e 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 @@ -351,6 +351,7 @@ fn real_start_request( host_options: Default::default(), toolchain_providers: Vec::new(), keymap_import_providers: Vec::new(), + session_policy: None, executable_path: toolchain .root .join("bin") diff --git a/rust/lithe-core/src/lsp/interface/mod.rs b/rust/lithe-core/src/lsp/interface/mod.rs index 93ddd99f41..3998cf31d3 100644 --- a/rust/lithe-core/src/lsp/interface/mod.rs +++ b/rust/lithe-core/src/lsp/interface/mod.rs @@ -9,6 +9,7 @@ mod function_relay; mod keymap_provider; pub(crate) mod plugin_function; mod plugin_logging; +mod plugin_server; pub(crate) mod process; pub(crate) mod remote_process; #[cfg(test)] diff --git a/rust/lithe-core/src/lsp/interface/plugin_function.rs b/rust/lithe-core/src/lsp/interface/plugin_function.rs index 57a31f428f..c8641e4677 100644 --- a/rust/lithe-core/src/lsp/interface/plugin_function.rs +++ b/rust/lithe-core/src/lsp/interface/plugin_function.rs @@ -12,6 +12,7 @@ //! The rules live in the plugin contract //! (`shared/contracts/plugins/v1/README.md`, "Plugin functions"). +use crate::plugins::language_server_sessions::{self, is_protocol_name}; use crate::protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; @@ -121,8 +122,18 @@ pub(crate) const HOST_PERMISSIONS: &[&str] = &[ "window.messages", "terminal.create", "keymaps.readSelectedSources", + PERMISSION_LANGUAGE_SERVER_REQUEST, + PERMISSION_DOCUMENTS_CONTENT_PROVIDER, ]; +/// Permission of the `languageServer` host service (plan API-25): a backend +/// may send requests and notifications to, and report the status of, the +/// language servers its own plugin declares. +pub(crate) const PERMISSION_LANGUAGE_SERVER_REQUEST: &str = "languageServer.request"; +/// Permission of `documents/registerContentProvider` (plan API-12): the +/// backend supplies the read-only text of URIs of a scheme it registers. +pub(crate) const PERMISSION_DOCUMENTS_CONTENT_PROVIDER: &str = "documents.contentProvider"; + const CREDENTIALS_GET: &str = "lithe/host/credentials/get"; const CREDENTIALS_SET: &str = "lithe/host/credentials/set"; const CREDENTIALS_DELETE: &str = "lithe/host/credentials/delete"; @@ -219,6 +230,18 @@ pub(crate) mod codes { /// The plugin made too many requests of this kind recently; the same /// request may succeed after a while. pub const HOST_RATE_LIMITED: &str = "plugin.host.rateLimited"; + /// The language server a `languageServer` request names is not running + /// in the context: it is starting, stopped, crashed, or not started. + pub const HOST_LANGUAGE_SERVER_UNAVAILABLE: &str = "plugin.host.languageServerUnavailable"; + /// The language server answered a forwarded request with an error; the + /// failure's `details` carry the server's `code` and `message`. + pub const HOST_LANGUAGE_SERVER_ERROR: &str = "plugin.host.languageServerError"; + /// The method or command is not in the language server's declared + /// `requestMethods`, `commands`, or allowed notifications. + pub const HOST_METHOD_NOT_DECLARED: &str = "plugin.host.methodNotDeclared"; + /// The request names a contribution, such as a language server, that + /// another plugin owns. + pub const HOST_FOREIGN_CONTRIBUTION: &str = "plugin.host.foreignContribution"; /// A page's call or a host operation ended because the backend process /// exited. Reported by hosts to pages, never sent to a backend. pub const BACKEND_EXITED: &str = "plugin.backend.exited"; @@ -528,6 +551,17 @@ pub(crate) enum HostParams { Context, /// Snapshot source listing or one bounded chunk from a selected source. KeymapSnapshot { chunk: bool }, + /// `{ context, serverID, method, params?, timeoutMilliseconds? }`: one + /// request to the plugin's own language server (plan API-25). + LanguageServerRequest, + /// `{ context, serverID, method, params? }`: one notification to it. + LanguageServerNotify, + /// `{ context, serverID, state, message?, percentage? }`: the plugin's + /// preparation status of the server. + LanguageServerStatus, + /// `{ context, scheme, function }`: the function that supplies the text + /// of a URI scheme (plan API-12). + ContentProvider, /// Exactly `{ functionID }`, a well-formed function ID. FunctionProviders, /// `{ pluginID, functionID, context, params?, timeoutMilliseconds? }`. @@ -840,8 +874,57 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ since: CONTEXT_VERSION, params: HostParams::Object, }, + // Plan API-25: the plugin's own language servers. The host resolves + // `{ context, serverID }` to the session and Core's + // `lsp.pluginServerRequest` enforces the declared session policy. + HostMethod { + method: LANGUAGE_SERVER_REQUEST, + service: HOST_SERVICE_LANGUAGE_SERVER, + permission: Some(PERMISSION_LANGUAGE_SERVER_REQUEST), + since: CONTEXT_VERSION, + params: HostParams::LanguageServerRequest, + }, + HostMethod { + method: LANGUAGE_SERVER_NOTIFY, + service: HOST_SERVICE_LANGUAGE_SERVER, + permission: Some(PERMISSION_LANGUAGE_SERVER_REQUEST), + since: CONTEXT_VERSION, + params: HostParams::LanguageServerNotify, + }, + HostMethod { + method: LANGUAGE_SERVER_SET_STATUS, + service: HOST_SERVICE_LANGUAGE_SERVER, + permission: Some(PERMISSION_LANGUAGE_SERVER_REQUEST), + since: CONTEXT_VERSION, + params: HostParams::LanguageServerStatus, + }, + // Plan API-12: read-only text of a URI scheme the backend serves. + HostMethod { + method: DOCUMENTS_REGISTER_CONTENT_PROVIDER, + service: "documents", + permission: Some(PERMISSION_DOCUMENTS_CONTENT_PROVIDER), + since: CONTEXT_VERSION, + params: HostParams::ContentProvider, + }, ]; +/// Host service of the plugin's own language servers (plan API-25). +pub(crate) const HOST_SERVICE_LANGUAGE_SERVER: &str = "languageServer"; +/// Forwards one declared request to the plugin's language server. +pub(crate) const LANGUAGE_SERVER_REQUEST: &str = "lithe/host/languageServer/request"; +/// Forwards one notification to the plugin's language server. +pub(crate) const LANGUAGE_SERVER_NOTIFY: &str = "lithe/host/languageServer/notify"; +/// Reports the plugin's preparation state of a language server to the user. +pub(crate) const LANGUAGE_SERVER_SET_STATUS: &str = "lithe/host/languageServer/setStatus"; +/// Registers a backend function as the content provider of a URI scheme. +pub(crate) const DOCUMENTS_REGISTER_CONTENT_PROVIDER: &str = + "lithe/host/documents/registerContentProvider"; +/// Lifecycle of a language server the plugin declares. +const LANGUAGE_SERVER_DID_CHANGE_STATE: &str = "lithe/host/languageServer/didChangeState"; +/// A server notification the language server's `forwardNotifications` lists. +const LANGUAGE_SERVER_DID_RECEIVE_NOTIFICATION: &str = + "lithe/host/languageServer/didReceiveNotification"; + /// Services every plugin-owned session of their version has without a /// permission: they reveal nothing beyond the session's own grants. fn is_implicit_service(service: &str) -> bool { @@ -914,6 +997,21 @@ pub(crate) fn host_request( Ok(HostRoute::Forward(entry.service)) } +/// The params the host receives for an accepted request: the backend's own, +/// except that a status message is cut to the bound a progress message has, +/// so a hostile backend cannot inflate every event that carries it. +pub(crate) fn forwarded_host_params(method: &str, params: Option<&Value>) -> Value { + let mut forwarded = params.cloned().unwrap_or(Value::Null); + if method == LANGUAGE_SERVER_SET_STATUS { + if let Some(message) = forwarded.get_mut("message") { + if let Some(text) = message.as_str() { + *message = Value::String(bounded_message(text)); + } + } + } + forwarded +} + /// The answer to `lithe/host/getCapabilities`: the negotiated version, the /// services and methods this session may call, where the backend runs, and /// the bounds Core enforces. It lists only what the session is granted, so @@ -942,10 +1040,10 @@ pub(crate) fn capabilities_answer(version: u64, granted: &BTreeSet) -> V }) { add(entry.service, "methods", entry.method); } - for entry in HOST_NOTIFICATIONS - .iter() - .filter(|entry| version >= entry.since && admitted(entry.service)) - { + for entry in HOST_NOTIFICATIONS.iter().filter(|entry| { + version >= entry.since + && (is_implicit_service(entry.service) || holds_service(entry.service, granted)) + }) { add(entry.service, "notifications", entry.method); } json!({ @@ -978,6 +1076,12 @@ pub(crate) enum NotificationParams { /// `{ commandID, context? }`: one of the plugin's own commands and the /// workspace context of the window it ran in. Command, + /// `{ context, serverID, state, generation }`: a lifecycle change of one + /// of the plugin's language servers. + LanguageServerState, + /// `{ context, serverID, generation, method, params? | truncated }`: a + /// forwarded server notification, without params when too large. + LanguageServerNotification, } /// One row of the host-notification table. @@ -1019,8 +1123,34 @@ pub(crate) const HOST_NOTIFICATIONS: &[HostNotification] = &[ since: CONTEXT_VERSION, params: NotificationParams::Command, }, + HostNotification { + method: LANGUAGE_SERVER_DID_CHANGE_STATE, + service: HOST_SERVICE_LANGUAGE_SERVER, + since: CONTEXT_VERSION, + params: NotificationParams::LanguageServerState, + }, + HostNotification { + method: LANGUAGE_SERVER_DID_RECEIVE_NOTIFICATION, + service: HOST_SERVICE_LANGUAGE_SERVER, + since: CONTEXT_VERSION, + params: NotificationParams::LanguageServerNotification, + }, ]; +/// Whether the session holds a service: its aggregate grant, or, for a +/// service granted per method, any of its methods. +fn holds_service(service: &str, granted: &BTreeSet) -> bool { + granted.contains(service) + || HOST_METHODS.iter().any(|entry| { + entry.service == service && entry.permission.is_some() && granted.contains(entry.method) + }) +} + +/// A language server state a `didChangeState` notification may carry. +fn is_language_server_state(value: &str) -> bool { + matches!(value, "starting" | "running" | "stopped" | "crashed") +} + /// Whether a host notification reaches this session. `Ok(false)` means the /// backend negotiated a version without it, so the host may skip it; a /// method outside the table, one whose service the session was not @@ -1048,7 +1178,7 @@ pub(crate) fn host_notification( codes::HOST_UNAVAILABLE, )); }; - if !is_implicit_service(entry.service) && !granted.contains(entry.service) { + if !is_implicit_service(entry.service) && !holds_service(entry.service, granted) { return Err(refusal( ErrorCode::InvalidRequest, "The session was not granted the service of this notification.", @@ -1089,6 +1219,45 @@ pub(crate) fn host_notification( .is_some_and(is_command_id) && object.get("context").map_or(true, is_context_reference) } + NotificationParams::LanguageServerState => { + only(&["context", "serverID", "state", "generation"]) + && object.get("context").is_some_and(is_context_reference) + && object + .get("serverID") + .and_then(Value::as_str) + .is_some_and(is_protocol_name) + && object + .get("state") + .and_then(Value::as_str) + .is_some_and(is_language_server_state) + && positive("generation") + } + NotificationParams::LanguageServerNotification => { + let truncated = object.get("truncated"); + only(&[ + "context", + "serverID", + "generation", + "method", + "params", + "truncated", + ]) && object.get("context").is_some_and(is_context_reference) + && object + .get("serverID") + .and_then(Value::as_str) + .is_some_and(is_protocol_name) + && object + .get("method") + .and_then(Value::as_str) + .is_some_and(is_protocol_name) + && positive("generation") + // A truncated notification drops its params entirely. + && match truncated { + None => true, + Some(Value::Bool(true)) => !object.contains_key("params"), + Some(_) => false, + } + } }; if !well_formed { return Err(invalid( @@ -1149,6 +1318,18 @@ fn check_host_params( "offset", "maximumBytes", ], + HostParams::LanguageServerRequest => &[ + "context", + "serverID", + "method", + "params", + "timeoutMilliseconds", + ], + HostParams::LanguageServerNotify => &["context", "serverID", "method", "params"], + HostParams::LanguageServerStatus => { + &["context", "serverID", "state", "message", "percentage"] + } + HostParams::ContentProvider => &["context", "scheme", "function"], HostParams::Object => { return match params.get("context") { Some(context) if !is_context_reference(context) => { @@ -1252,11 +1433,103 @@ fn check_host_params( )); } } + HostParams::LanguageServerRequest + | HostParams::LanguageServerNotify + | HostParams::LanguageServerStatus => { + check_language_server_params(rule, params, &invalid)?; + } + HostParams::ContentProvider => { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + let scheme = params.get("scheme").and_then(Value::as_str); + if !scheme.is_some_and(is_content_scheme) { + return Err(invalid( + "A content scheme is 1-64 lowercase ASCII letters, digits, '+', '-' or '.', starts with a letter, and is not a scheme the host owns.", + )); + } + if !params + .get("function") + .and_then(Value::as_str) + .is_some_and(is_function_id) + { + return Err(invalid( + "The content function must be a plugin function ID.", + )); + } + } HostParams::Empty | HostParams::Object => {} } Ok(()) } +/// Checks the params the `languageServer` host methods share: the context, +/// the server, the method, and each method's own fields. Whether the server +/// belongs to the plugin and the method is declared is the engine's answer, +/// since only it holds the session policy. +fn check_language_server_params( + rule: HostParams, + params: &serde_json::Map, + invalid: &dyn Fn(&'static str) -> HostRequestRefusal, +) -> Result<(), HostRequestRefusal> { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + if !params + .get("serverID") + .and_then(Value::as_str) + .is_some_and(is_protocol_name) + { + return Err(invalid( + "serverID must name one of the plugin's language servers.", + )); + } + if rule == HostParams::LanguageServerStatus { + if !params + .get("state") + .and_then(Value::as_str) + .is_some_and(is_status_state) + { + return Err(invalid( + "state is one of preparing, ready, degraded, or failed.", + )); + } + if params + .get("message") + .is_some_and(|message| !message.is_string()) + { + return Err(invalid("message must be a string.")); + } + if params + .get("percentage") + .is_some_and(|value| !value.as_u64().is_some_and(|percentage| percentage <= 100)) + { + return Err(invalid("percentage is a whole number from 0 to 100.")); + } + return Ok(()); + } + if !params + .get("method") + .and_then(Value::as_str) + .is_some_and(is_protocol_name) + { + return Err(invalid("method must be a non-empty LSP method name.")); + } + if rule == HostParams::LanguageServerRequest + && params.get("timeoutMilliseconds").is_some_and(|value| { + !value.as_u64().is_some_and(|milliseconds| { + (1..=language_server_sessions::MAX_REQUEST_TIMEOUT_MILLISECONDS) + .contains(&milliseconds) + }) + }) + { + return Err(invalid( + "timeoutMilliseconds is a whole number from 1 to 300000.", + )); + } + Ok(()) +} + const FUNCTION_ID_MESSAGE: &str = "A function ID is dot-separated lowerCamelCase segments of at most 128 bytes."; @@ -1314,6 +1587,44 @@ fn check_function_invoke_params( Ok(()) } +/// A preparation state a plugin may report for its language server. +fn is_status_state(value: &str) -> bool { + matches!(value, "preparing" | "ready" | "degraded" | "failed") +} + +/// Schemes the host or the platform resolves itself. A plugin that served +/// one would replace what the user expects the URI to open. +const RESERVED_CONTENT_SCHEMES: &[&str] = &[ + "about", + "blob", + "data", + "file", + "ftp", + "http", + "https", + "javascript", + "lithe", + "mailto", + "untitled", + "ws", + "wss", +]; + +/// A URI scheme a plugin may serve (RFC 3986, lowercase, bounded). +fn is_content_scheme(value: &str) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= 64 + && characters.all(|character| { + character.is_ascii_lowercase() + || character.is_ascii_digit() + || matches!(character, '+' | '-' | '.') + }) + && !RESERVED_CONTENT_SCHEMES.contains(&value) +} + const CONTEXT_REFERENCE_MESSAGE: &str = "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, '.', '_', ':' or '-', and a positive generation."; @@ -1405,6 +1716,10 @@ pub(crate) fn host_rpc_code(code: &str) -> i64 { codes::HOST_PRECONDITION_FAILED => -32019, codes::HOST_BUSY => -32020, codes::HOST_RATE_LIMITED => -32021, + codes::HOST_LANGUAGE_SERVER_UNAVAILABLE => -32022, + codes::HOST_LANGUAGE_SERVER_ERROR => -32023, + codes::HOST_METHOD_NOT_DECLARED => -32024, + codes::HOST_FOREIGN_CONTRIBUTION => -32026, codes::NOT_DECLARED => -32027, codes::NOT_EXPORTED => -32028, codes::PROVIDER_DISABLED => -32029, @@ -1457,6 +1772,10 @@ pub(crate) fn host_failure(code: Option<&str>) -> (&'static str, i64) { Some(codes::HOST_PRECONDITION_FAILED) => codes::HOST_PRECONDITION_FAILED, Some(codes::HOST_BUSY) => codes::HOST_BUSY, Some(codes::HOST_RATE_LIMITED) => codes::HOST_RATE_LIMITED, + Some(codes::HOST_LANGUAGE_SERVER_UNAVAILABLE) => codes::HOST_LANGUAGE_SERVER_UNAVAILABLE, + Some(codes::HOST_LANGUAGE_SERVER_ERROR) => codes::HOST_LANGUAGE_SERVER_ERROR, + Some(codes::HOST_METHOD_NOT_DECLARED) => codes::HOST_METHOD_NOT_DECLARED, + Some(codes::HOST_FOREIGN_CONTRIBUTION) => codes::HOST_FOREIGN_CONTRIBUTION, // A backend exit is reported to pages, never to the backend itself. _ => codes::HOST_FAILED, }; @@ -2054,6 +2373,65 @@ mod tests { assert_eq!(failure.code, codes::INVALID_RESULT); } + /// A status message is cut at the progress bound before it reaches the + /// host, at a character boundary; other methods pass untouched. + #[test] + fn forwarded_status_messages_are_bounded() { + let message = format!("{}é", "a".repeat(MAX_MESSAGE_BYTES - 1)); + let params = json!({ "serverID": "metals", "state": "preparing", "message": message }); + let forwarded = forwarded_host_params(LANGUAGE_SERVER_SET_STATUS, Some(¶ms)); + assert_eq!(forwarded["message"], "a".repeat(MAX_MESSAGE_BYTES - 1)); + assert_eq!(forwarded["state"], "preparing"); + let request = json!({ "method": "x", "message": "m".repeat(MAX_MESSAGE_BYTES + 1) }); + assert_eq!( + forwarded_host_params(LANGUAGE_SERVER_REQUEST, Some(&request)), + request + ); + assert_eq!( + forwarded_host_params(LANGUAGE_SERVER_REQUEST, None), + Value::Null + ); + } + + /// A content scheme is a lowercase RFC 3986 scheme the host does not own. + #[test] + fn content_schemes_exclude_host_owned_ones() { + for accepted in ["metals-library", "rust-std", "a", "x1+y.z"] { + assert!(is_content_scheme(accepted), "{accepted}"); + } + for refused in [ + "", "File", "1abc", "-abc", "a b", "a_b", "file", "https", "data", "lithe", "untitled", + ] { + assert!(!is_content_scheme(refused), "{refused}"); + } + assert!(is_content_scheme(&"a".repeat(64))); + assert!(!is_content_scheme(&"a".repeat(65))); + } + + /// Only a session granted the language server methods lists them, and a + /// session without the grant still lists nothing of the service. + #[test] + fn capabilities_list_language_server_methods_only_when_granted() { + let services = |granted: &[&str]| { + let granted = granted.iter().map(|method| method.to_string()).collect(); + capabilities_answer(3, &granted)["services"].clone() + }; + assert!(services(&[]).get(HOST_SERVICE_LANGUAGE_SERVER).is_none()); + let granted = services(&[LANGUAGE_SERVER_REQUEST, LANGUAGE_SERVER_SET_STATUS]); + let entry = &granted[HOST_SERVICE_LANGUAGE_SERVER]; + assert_eq!( + entry["methods"], + json!([LANGUAGE_SERVER_REQUEST, LANGUAGE_SERVER_SET_STATUS]) + ); + assert_eq!( + entry["notifications"], + json!([ + LANGUAGE_SERVER_DID_CHANGE_STATE, + LANGUAGE_SERVER_DID_RECEIVE_NOTIFICATION + ]) + ); + } + #[test] fn the_registry_is_bounded() { let current: BTreeSet = (0..MAX_FUNCTIONS) diff --git a/rust/lithe-core/src/lsp/interface/plugin_server.rs b/rust/lithe-core/src/lsp/interface/plugin_server.rs new file mode 100644 index 0000000000..866dd197f4 --- /dev/null +++ b/rust/lithe-core/src/lsp/interface/plugin_server.rs @@ -0,0 +1,933 @@ +//! Session policy of a plugin-owned language server (plan API-25). +//! +//! A plugin backend reaches its own language server only through the host: +//! it asks for `lithe/host/languageServer/request` or `notify`, and the host +//! passes the call to Core. This module is the policy those calls obey. It +//! decides, without touching the process or the clock, whether a call may +//! be sent, must wait for a gate, or joins a command that already runs, and +//! it tracks which operations it owns until the engine completes them. +//! +//! The engine stays the only writer to the server: it asks this module for a +//! verdict under its session lock, then allocates the JSON-RPC request, +//! registers the pending entry, and sends it. Ownership of an operation ends +//! in exactly one place, `finish`, which the engine calls when it publishes +//! the operation's `requestCompleted` event. Cancelling, timing out, and +//! failing the session therefore only pick the operations to complete. + +use super::plugin_function::{codes, MAX_HOST_NOTIFICATION_BYTES}; +use crate::plugins::language_server_sessions::{ + is_protocol_name, matches_pattern, Gate, RemoteSupport, DID_CHANGE_CONFIGURATION, + EXECUTE_COMMAND, +}; +use crate::protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::time::Instant; + +/// Most requests that may wait at once, held behind a gate or joined to a +/// running command. More would only queue work behind a server that has not +/// reached the state the plugin asked to wait for. +const MAX_WAITING_REQUESTS: usize = 128; + +/// Bounds of a policy received from the host. Core derives the policy from +/// a validated manifest and a launch answer, but `lsp.startServer` is also a +/// public command, so the engine bounds it again. +const MAX_REQUEST_METHODS: usize = 64; +const MAX_COMMANDS: usize = 128; +const MAX_FORWARD_NOTIFICATIONS: usize = 32; +const MAX_GATES: usize = 8; + +/// What the engine enforces for one plugin-owned server. It arrives as +/// `sessionPolicy` of `lsp.startServer`, built from the plugin's declaration +/// and, for a backend launch, the gates of the launch answer. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionPolicy { + /// The server's ID in the plugin's manifest; the key a backend uses. + #[serde(rename = "serverID")] + pub server_id: String, + /// Requests and notifications the backend may send to the server. + #[serde(default)] + pub request_methods: BTreeSet, + /// Commands the backend may run through `workspace/executeCommand`. + #[serde(default)] + pub commands: BTreeSet, + /// Commands that run one at a time; a second request joins the first. + #[serde(default)] + pub serialized_commands: BTreeSet, + /// Server notifications forwarded to the backend. + #[serde(default)] + pub forward_notifications: BTreeSet, + /// Whether the server may serve a remote workspace. + #[serde(default)] + pub remote: RemoteSupport, + /// Notifications the server must send before requests are sent. + #[serde(default)] + pub gates: Vec, + /// Retention of the server's state directories. The host keeps and + /// prunes the directories, so the engine only accepts the field. + #[serde(default, rename = "state")] + _state: Option, +} + +impl SessionPolicy { + /// Checks the bounds of a policy that a plugin-owned session received. + pub(super) fn validate(&self, plugin_id: Option<&str>) -> Result<(), CoreError> { + let invalid = |field: &str| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid language-server start request.", + ) + .with_details(format!("sessionPolicy/{field}")) + }; + if plugin_id.is_none() || !is_protocol_name(&self.server_id) { + return Err(invalid("serverID")); + } + let names_ok = |names: &BTreeSet, limit: usize| { + names.len() <= limit && names.iter().all(|name| is_protocol_name(name)) + }; + if !names_ok(&self.request_methods, MAX_REQUEST_METHODS) { + return Err(invalid("requestMethods")); + } + if !names_ok(&self.commands, MAX_COMMANDS) { + return Err(invalid("commands")); + } + if !names_ok(&self.serialized_commands, MAX_COMMANDS) + || !self.serialized_commands.is_subset(&self.commands) + { + return Err(invalid("serializedCommands")); + } + if !names_ok(&self.forward_notifications, MAX_FORWARD_NOTIFICATIONS) { + return Err(invalid("forwardNotifications")); + } + let gate_ids: BTreeSet<&str> = self.gates.iter().map(|gate| gate.id.as_str()).collect(); + if self.gates.len() > MAX_GATES + || gate_ids.len() != self.gates.len() + || self + .gates + .iter() + .any(|gate| !is_protocol_name(&gate.method)) + { + return Err(invalid("gates")); + } + Ok(()) + } +} + +/// A request that waits for its gates to open. Core allocates the JSON-RPC +/// request only when the gates open, so cancelling it writes nothing. +#[derive(Debug, Clone)] +pub(super) struct HeldRequest { + pub operation_id: String, + pub method: String, + pub params: Value, + pub created_at: Instant, + pub deadline: Instant, +} + +/// An operation that must be completed, with the method its event names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Waiter { + pub operation_id: String, + pub method: String, +} + +/// What the engine does with an admitted request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Admission { + /// Allocate the request and write it to the server now. + Send, + /// The request waits in the policy until a gate opens. + Held, + /// A serialized command is already running; this request completes with + /// the same result or error as the first one. + Joined, +} + +/// One request being admitted. +pub(super) struct Arrival<'a> { + pub operation_id: &'a str, + pub method: &'a str, + pub params: &'a Value, + pub now: Instant, + pub deadline: Instant, +} + +/// What a server notification changed in the policy. +#[derive(Debug, Default)] +pub(super) struct Observation { + /// The `pluginServerNotification` result to publish for the backend. + pub forward: Option, + /// Requests whose gates are now open, in arrival order. + pub released: Vec, +} + +/// An operation the policy owns until the engine finishes it. +#[derive(Debug)] +struct Owned { + method: String, + /// The serialized command the operation runs or joined, if any. + serialized_command: Option, +} + +/// The first request of a serialized command and the ones that joined it. +#[derive(Debug)] +struct RunningCommand { + leader: String, + joiners: Vec, +} + +/// Mutable part of the policy: gates opened so far, requests waiting for +/// them, and serialized commands in flight. +#[derive(Debug)] +pub(super) struct PluginServerState { + policy: SessionPolicy, + open_gates: BTreeSet, + held: VecDeque, + running: BTreeMap, + owned: BTreeMap, +} + +impl PluginServerState { + pub(super) fn new(policy: SessionPolicy) -> Self { + Self { + policy, + open_gates: BTreeSet::new(), + held: VecDeque::new(), + running: BTreeMap::new(), + owned: BTreeMap::new(), + } + } + + /// Refuses a call that names another plugin or another server than the + /// one this session runs. The host resolves the server by ID, so a + /// mismatch means it resolved a session of a different contribution. + pub(super) fn check_owner( + &self, + session_plugin_id: Option<&str>, + plugin_id: &str, + server_id: &str, + ) -> Result<(), CoreError> { + if session_plugin_id == Some(plugin_id) && self.policy.server_id == server_id { + return Ok(()); + } + Err(foreign_contribution()) + } + + /// Decides what happens to a request the backend sent to the server. + pub(super) fn admit_request(&mut self, arrival: Arrival<'_>) -> Result { + if !self.policy.request_methods.contains(arrival.method) { + return Err(not_declared("The language-server method is not declared.")); + } + if byte_size(arrival.params) > MAX_HOST_NOTIFICATION_BYTES { + return Err(too_large()); + } + let serialized = self.serialized_command(arrival.method, arrival.params)?; + let joins = serialized + .as_ref() + .is_some_and(|command| self.running.contains_key(command)); + let gated = !self.gates_open(); + if (joins || gated) && self.waiting() >= MAX_WAITING_REQUESTS { + return Err(refusal( + ErrorCode::Unknown, + "Too many language-server requests are waiting.", + codes::HOST_BUSY, + )); + } + self.owned.insert( + arrival.operation_id.to_string(), + Owned { + method: arrival.method.to_string(), + serialized_command: serialized.clone(), + }, + ); + if let Some(command) = serialized { + if let Some(running) = self.running.get_mut(&command) { + running.joiners.push(arrival.operation_id.to_string()); + return Ok(Admission::Joined); + } + self.running.insert( + command, + RunningCommand { + leader: arrival.operation_id.to_string(), + joiners: Vec::new(), + }, + ); + } + if gated { + self.held.push_back(HeldRequest { + operation_id: arrival.operation_id.to_string(), + method: arrival.method.to_string(), + params: arrival.params.clone(), + created_at: arrival.now, + deadline: arrival.deadline, + }); + return Ok(Admission::Held); + } + Ok(Admission::Send) + } + + /// Decides whether a notification may be sent. Gates never hold a + /// notification: it carries no answer a backend waits for, and the + /// configuration notification may be exactly what opens a gate. + pub(super) fn admit_notification(&self, method: &str, params: &Value) -> Result<(), CoreError> { + // A command is only run as a request, where it is checked against + // the declared commands. + let declared = method == DID_CHANGE_CONFIGURATION + || (method != EXECUTE_COMMAND && self.policy.request_methods.contains(method)); + if !declared { + return Err(not_declared("The language-server method is not declared.")); + } + if byte_size(params) > MAX_HOST_NOTIFICATION_BYTES { + return Err(too_large()); + } + Ok(()) + } + + /// Applies a notification the server sent: it may open gates and may + /// be one the backend asked to receive. + pub(super) fn observe(&mut self, method: &str, params: &Value) -> Observation { + for gate in &self.policy.gates { + if gate.method == method && matches_pattern(params, &gate.pattern) { + self.open_gates.insert(gate.id.clone()); + } + } + let released: Vec = if self.gates_open() { + self.held.drain(..).collect() + } else { + Vec::new() + }; + let forward = self + .policy + .forward_notifications + .contains(method) + .then(|| self.forwarded(method, params)); + Observation { forward, released } + } + + /// Whether the operation has no request on the wire: it waits behind a + /// gate or joined another request. Cancelling it only completes it. + pub(super) fn is_unsent(&self, operation_id: &str) -> bool { + if self + .held + .iter() + .any(|held| held.operation_id == operation_id) + { + return true; + } + self.owned + .get(operation_id) + .and_then(|owned| owned.serialized_command.as_ref()) + .and_then(|command| self.running.get(command)) + .is_some_and(|running| running.leader != operation_id) + } + + /// Whether the operation came through `admit_request` and is not done. + pub(super) fn owns(&self, operation_id: &str) -> bool { + self.owned.contains_key(operation_id) + } + + /// Requests whose deadline passed while they waited for a gate. Their + /// ownership ends when the engine finishes them. + pub(super) fn expired_held(&self, now: Instant) -> Vec { + self.held + .iter() + .filter(|held| now >= held.deadline) + .map(HeldRequest::waiter) + .collect() + } + + /// Every request still waiting for a gate, for a session that ended. + pub(super) fn all_held(&self) -> Vec { + self.held.iter().map(HeldRequest::waiter).collect() + } + + /// Ends the policy's ownership of an operation the engine completes and + /// returns the requests that joined it, which complete the same way. A + /// joiner that finishes on its own (cancelled) just leaves the list. + pub(super) fn finish(&mut self, operation_id: &str) -> Vec { + self.held.retain(|held| held.operation_id != operation_id); + let Some(owned) = self.owned.remove(operation_id) else { + return Vec::new(); + }; + let Some(command) = owned.serialized_command else { + return Vec::new(); + }; + let leads = self + .running + .get(&command) + .is_some_and(|running| running.leader == operation_id); + if !leads { + if let Some(running) = self.running.get_mut(&command) { + running.joiners.retain(|joiner| joiner != operation_id); + } + return Vec::new(); + } + let Some(running) = self.running.remove(&command) else { + return Vec::new(); + }; + running + .joiners + .into_iter() + .filter_map(|joiner| { + self.owned.remove(&joiner).map(|owned| Waiter { + operation_id: joiner, + method: owned.method, + }) + }) + .collect() + } + + /// The method a finished operation was admitted with. + pub(super) fn method_of(&self, operation_id: &str) -> Option<&str> { + self.owned + .get(operation_id) + .map(|owned| owned.method.as_str()) + } + + /// The command of an `executeCommand` request that must be serialized. + fn serialized_command( + &self, + method: &str, + params: &Value, + ) -> Result, CoreError> { + if method != EXECUTE_COMMAND { + return Ok(None); + } + let command = params + .get("command") + .and_then(Value::as_str) + .filter(|command| self.policy.commands.contains(*command)) + .ok_or_else(|| not_declared("The language-server command is not declared."))?; + Ok(self + .policy + .serialized_commands + .contains(command) + .then(|| command.to_string())) + } + + fn gates_open(&self) -> bool { + self.policy + .gates + .iter() + .all(|gate| self.open_gates.contains(&gate.id)) + } + + /// Requests that wait without being on the wire. + fn waiting(&self) -> usize { + self.held.len() + + self + .running + .values() + .map(|running| running.joiners.len()) + .sum::() + } + + /// The result a forwarded notification carries. An oversized payload + /// keeps only the fact that it happened, so the backend can ask for + /// the state it needs instead of receiving a truncated message. + fn forwarded(&self, method: &str, params: &Value) -> Value { + if byte_size(params) > MAX_HOST_NOTIFICATION_BYTES { + return json!({ + "serverID": self.policy.server_id, + "method": method, + "truncated": true, + }); + } + json!({ + "serverID": self.policy.server_id, + "method": method, + "params": params, + }) + } +} + +impl HeldRequest { + fn waiter(&self) -> Waiter { + Waiter { + operation_id: self.operation_id.clone(), + method: self.method.clone(), + } + } +} + +/// The `plugin.host.*` code a backend sees for a failure the engine reports +/// with its own runtime code. Anything that ends a request without an +/// answer from the server means the server is not usable now. +pub(super) fn host_error_code(runtime_code: &str) -> &str { + match runtime_code { + "requestTimeout" => codes::HOST_TIMEOUT, + "requestCancelled" => codes::HOST_CANCELLED, + code if code.starts_with("plugin.host.") => code, + _ => codes::HOST_LANGUAGE_SERVER_UNAVAILABLE, + } +} + +/// Marks locations that are not files as read-only and gives them a path to +/// show. The host opens such a location through the plugin's content +/// provider, so it can never write the document back. +pub(super) fn normalize_navigation_result(mut result: Option) -> Option { + let locations = result + .as_mut() + .and_then(|result| result.get_mut("locations")) + .and_then(Value::as_array_mut); + for location in locations.into_iter().flatten() { + let Some(uri) = location + .get("uri") + .and_then(Value::as_str) + .map(str::to_string) + else { + continue; + }; + if is_file_uri(&uri) { + continue; + } + location["isReadOnly"] = Value::Bool(true); + location["displayPath"] = display_path(&uri).map_or(Value::Null, Value::String); + } + result +} + +fn is_file_uri(uri: &str) -> bool { + uri.split_once(':') + .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("file")) +} + +/// The path of a URI as people read it: without scheme, authority, query, +/// or fragment, and with escapes decoded. +fn display_path(uri: &str) -> Option { + let (_, remainder) = uri.split_once(':')?; + let path = match remainder.strip_prefix("//") { + Some(with_authority) => &with_authority[with_authority.find('/')? + 1..], + None => remainder.trim_start_matches('/'), + }; + let path = path.split(['?', '#']).next().unwrap_or(path); + let decoded = super::client::percent_decode(path); + let components: Vec<&str> = decoded + .split('/') + .filter(|component| !component.is_empty()) + .collect(); + (!components.is_empty()).then(|| components.join("/")) +} + +fn byte_size(value: &Value) -> usize { + serde_json::to_vec(value).map_or(usize::MAX, |bytes| bytes.len()) +} + +/// The refusal for a call that reached a session of another contribution, +/// or a session that is no plugin-owned language server at all. +pub(super) fn foreign_contribution() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "The language server belongs to another contribution.", + codes::HOST_FOREIGN_CONTRIBUTION, + ) +} + +/// The refusal for a call to a server that is not running yet or any more. +pub(super) fn unavailable() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "The language server is not ready.", + codes::HOST_LANGUAGE_SERVER_UNAVAILABLE, + ) +} + +fn not_declared(message: &str) -> CoreError { + refusal( + ErrorCode::PermissionDenied, + message, + codes::HOST_METHOD_NOT_DECLARED, + ) +} + +fn too_large() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "The language-server message is too large.", + codes::HOST_LIMIT_EXCEEDED, + ) +} + +fn refusal(category: ErrorCode, message: &str, code: &str) -> CoreError { + CoreError::new(category, message).with_details(code) +} + +#[cfg(test)] +mod tests { + //! Policies of two unrelated servers, so no case depends on one + //! language: a Metals-like server with a build command that must run + //! one at a time and a gate, and a rust-analyzer-like server without + //! either. + + use super::*; + use std::time::Duration; + + fn metals() -> SessionPolicy { + serde_json::from_value(json!({ + "serverID": "metals", + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand", + ], + "commands": ["build-import", "build-connect"], + "serializedCommands": ["build-import"], + "forwardNotifications": ["metals/status"], + "remote": "unsupported", + "gates": [{ + "id": "imported", + "until": "notification", + "method": "metals/status", + "match": { "text": "ready" }, + }], + })) + .unwrap() + } + + fn rust_analyzer() -> SessionPolicy { + serde_json::from_value(json!({ + "serverID": "rust-analyzer", + "requestMethods": ["experimental/runnables", "textDocument/definition"], + })) + .unwrap() + } + + fn arrival<'a>(operation_id: &'a str, method: &'a str, params: &'a Value) -> Arrival<'a> { + let now = Instant::now(); + Arrival { + operation_id, + method, + params, + now, + deadline: now + Duration::from_secs(60), + } + } + + fn command(name: &str) -> Value { + json!({ "command": name, "arguments": [] }) + } + + fn open_gate(state: &mut PluginServerState) -> Observation { + state.observe("metals/status", &json!({ "text": "ready", "level": 1 })) + } + + fn detail(error: CoreError) -> String { + error.details.unwrap_or_default() + } + + #[test] + fn declared_request_is_sent_without_gates() { + let mut state = PluginServerState::new(rust_analyzer()); + let params = json!({}); + let admission = state + .admit_request(arrival("op-1", "experimental/runnables", ¶ms)) + .unwrap(); + assert_eq!(admission, Admission::Send); + assert!(state.owns("op-1")); + } + + #[test] + fn undeclared_method_is_refused() { + let mut state = PluginServerState::new(rust_analyzer()); + let params = json!({}); + let error = state + .admit_request(arrival("op-1", "textDocument/rename", ¶ms)) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_METHOD_NOT_DECLARED); + assert!(!state.owns("op-1")); + } + + #[test] + fn undeclared_command_is_refused() { + let mut state = PluginServerState::new(metals()); + open_gate(&mut state); + let params = command("build-clean"); + let error = state + .admit_request(arrival("op-1", EXECUTE_COMMAND, ¶ms)) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_METHOD_NOT_DECLARED); + let missing = json!({}); + let error = state + .admit_request(arrival("op-2", EXECUTE_COMMAND, &missing)) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_METHOD_NOT_DECLARED); + } + + #[test] + fn another_contribution_is_foreign() { + let state = PluginServerState::new(metals()); + assert!(state + .check_owner(Some("a.plugin"), "a.plugin", "metals") + .is_ok()); + for (session, plugin, server) in [ + (Some("a.plugin"), "b.plugin", "metals"), + (Some("a.plugin"), "a.plugin", "rust-analyzer"), + (None, "a.plugin", "metals"), + ] { + let error = state.check_owner(session, plugin, server).unwrap_err(); + assert_eq!(detail(error), codes::HOST_FOREIGN_CONTRIBUTION); + } + } + + #[test] + fn requests_wait_for_the_gate_in_order() { + let mut state = PluginServerState::new(metals()); + let params = json!({}); + for operation in ["op-1", "op-2"] { + let admission = state + .admit_request(arrival(operation, "textDocument/definition", ¶ms)) + .unwrap(); + assert_eq!(admission, Admission::Held); + } + // A status that does not match the pattern leaves the gate closed. + let early = state.observe("metals/status", &json!({ "text": "importing" })); + assert!(early.released.is_empty()); + assert!(early.forward.is_some(), "the backend still sees the status"); + let released = open_gate(&mut state).released; + let order: Vec<&str> = released + .iter() + .map(|held| held.operation_id.as_str()) + .collect(); + assert_eq!(order, ["op-1", "op-2"]); + let later = state + .admit_request(arrival("op-3", "textDocument/definition", ¶ms)) + .unwrap(); + assert_eq!(later, Admission::Send); + } + + #[test] + fn notifications_are_not_held_by_gates() { + let state = PluginServerState::new(metals()); + let params = json!({ "settings": {} }); + assert!(state + .admit_notification(DID_CHANGE_CONFIGURATION, ¶ms) + .is_ok()); + assert!(state + .admit_notification("textDocument/definition", ¶ms) + .is_ok()); + } + + #[test] + fn commands_are_never_notifications() { + let state = PluginServerState::new(metals()); + let error = state + .admit_notification(EXECUTE_COMMAND, &command("build-import")) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_METHOD_NOT_DECLARED); + let error = state + .admit_notification("textDocument/rename", &json!({})) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_METHOD_NOT_DECLARED); + } + + #[test] + fn oversized_notification_is_refused() { + let state = PluginServerState::new(rust_analyzer()); + let params = json!({ "text": "x".repeat(MAX_HOST_NOTIFICATION_BYTES) }); + let error = state + .admit_notification("textDocument/definition", ¶ms) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_LIMIT_EXCEEDED); + } + + #[test] + fn oversized_request_is_refused_before_it_is_owned() { + let mut state = PluginServerState::new(rust_analyzer()); + let params = json!({ "text": "x".repeat(MAX_HOST_NOTIFICATION_BYTES) }); + let error = state + .admit_request(arrival("op-1", "textDocument/definition", ¶ms)) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_LIMIT_EXCEEDED); + assert!(!state.owns("op-1")); + } + + #[test] + fn serialized_command_joins_the_running_one() { + let mut state = PluginServerState::new(metals()); + open_gate(&mut state); + let params = command("build-import"); + let first = state + .admit_request(arrival("op-1", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + let second = state + .admit_request(arrival("op-2", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + assert_eq!((first, second), (Admission::Send, Admission::Joined)); + // A command that is not serialized always starts on its own. + let other = command("build-connect"); + for operation in ["op-3", "op-4"] { + let admission = state + .admit_request(arrival(operation, EXECUTE_COMMAND, &other)) + .unwrap(); + assert_eq!(admission, Admission::Send); + } + let joiners = state.finish("op-1"); + assert_eq!( + joiners, + [Waiter { + operation_id: "op-2".into(), + method: EXECUTE_COMMAND.into() + }] + ); + assert!(!state.owns("op-1") && !state.owns("op-2")); + // The command can run again once the first request is done. + let third = state + .admit_request(arrival("op-5", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + assert_eq!(third, Admission::Send); + } + + #[test] + fn cancelling_a_joiner_leaves_the_leader_running() { + let mut state = PluginServerState::new(metals()); + open_gate(&mut state); + let params = command("build-import"); + state + .admit_request(arrival("op-1", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + state + .admit_request(arrival("op-2", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + assert!(state.is_unsent("op-2")); + assert!(!state.is_unsent("op-1")); + assert!(state.finish("op-2").is_empty()); + assert!(state.owns("op-1")); + assert!(state.finish("op-1").is_empty(), "no joiner is left"); + } + + #[test] + fn a_held_leader_takes_its_joiners_with_it() { + let mut state = PluginServerState::new(metals()); + let params = command("build-import"); + let first = state + .admit_request(arrival("op-1", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + let second = state + .admit_request(arrival("op-2", EXECUTE_COMMAND, ¶ms)) + .unwrap(); + assert_eq!((first, second), (Admission::Held, Admission::Joined)); + assert!( + state.is_unsent("op-1"), + "held requests have no wire request" + ); + let joiners = state.finish("op-1"); + assert_eq!(joiners.len(), 1); + assert!(state.all_held().is_empty()); + assert!(open_gate(&mut state).released.is_empty()); + } + + #[test] + fn held_requests_expire_at_their_deadline() { + let mut state = PluginServerState::new(metals()); + let params = json!({}); + let start = Instant::now(); + state + .admit_request(Arrival { + operation_id: "op-1", + method: "textDocument/definition", + params: ¶ms, + now: start, + deadline: start + Duration::from_secs(5), + }) + .unwrap(); + assert!(state + .expired_held(start + Duration::from_secs(4)) + .is_empty()); + let expired = state.expired_held(start + Duration::from_secs(5)); + assert_eq!(expired.len(), 1); + assert_eq!(expired[0].operation_id, "op-1"); + state.finish("op-1"); + assert!(state.all_held().is_empty()); + } + + #[test] + fn waiting_requests_are_bounded() { + let mut state = PluginServerState::new(metals()); + let params = json!({}); + for index in 0..MAX_WAITING_REQUESTS { + let operation = format!("op-{index}"); + state + .admit_request(arrival(&operation, "textDocument/definition", ¶ms)) + .unwrap(); + } + let error = state + .admit_request(arrival("op-over", "textDocument/definition", ¶ms)) + .unwrap_err(); + assert_eq!(detail(error), codes::HOST_BUSY); + assert!(!state.owns("op-over")); + } + + #[test] + fn forwarded_notification_is_bounded() { + let mut state = PluginServerState::new(metals()); + let small = state.observe("metals/status", &json!({ "text": "x" })); + assert_eq!( + small.forward.unwrap(), + json!({ "serverID": "metals", "method": "metals/status", "params": { "text": "x" } }) + ); + let large = state.observe( + "metals/status", + &json!({ "text": "x".repeat(MAX_HOST_NOTIFICATION_BYTES) }), + ); + assert_eq!( + large.forward.unwrap(), + json!({ "serverID": "metals", "method": "metals/status", "truncated": true }) + ); + assert!(state + .observe("window/logMessage", &json!({})) + .forward + .is_none()); + } + + #[test] + fn policy_bounds_are_enforced() { + assert!(metals().validate(Some("a.plugin")).is_ok()); + assert!( + metals().validate(None).is_err(), + "a host-owned session has no policy" + ); + let mut policy = metals(); + policy.serialized_commands.insert("build-clean".into()); + assert!(policy.validate(Some("a.plugin")).is_err()); + let mut policy = metals(); + policy.request_methods = (0..=MAX_REQUEST_METHODS) + .map(|n| format!("m/{n}")) + .collect(); + assert!(policy.validate(Some("a.plugin")).is_err()); + let mut policy = metals(); + policy.gates.push(policy.gates[0].clone()); + assert!( + policy.validate(Some("a.plugin")).is_err(), + "gate IDs are unique" + ); + } + + #[test] + fn runtime_codes_map_to_host_codes() { + assert_eq!(host_error_code("requestTimeout"), codes::HOST_TIMEOUT); + assert_eq!(host_error_code("requestCancelled"), codes::HOST_CANCELLED); + assert_eq!( + host_error_code("processExited"), + codes::HOST_LANGUAGE_SERVER_UNAVAILABLE + ); + assert_eq!( + host_error_code(codes::HOST_LANGUAGE_SERVER_ERROR), + codes::HOST_LANGUAGE_SERVER_ERROR + ); + } + + #[test] + fn locations_that_are_not_files_become_read_only() { + let result = json!({ "locations": [ + { "uri": "file:///work/src/lib.rs", "isReadOnly": false, "displayPath": null }, + { "uri": "metals-jar://host/a%20b/Main.scala?x=1#L2", "isReadOnly": false }, + ]}); + let normalized = normalize_navigation_result(Some(result)).unwrap(); + let locations = normalized["locations"].as_array().unwrap(); + assert_eq!(locations[0]["isReadOnly"], false); + assert_eq!(locations[1]["isReadOnly"], true); + assert_eq!(locations[1]["displayPath"], "a b/Main.scala"); + assert!(normalize_navigation_result(None).is_none()); + } +} diff --git a/rust/lithe-core/src/plugins/capabilities.rs b/rust/lithe-core/src/plugins/capabilities.rs index 8131621584..aae7a16600 100644 --- a/rust/lithe-core/src/plugins/capabilities.rs +++ b/rust/lithe-core/src/plugins/capabilities.rs @@ -26,9 +26,14 @@ pub(crate) const CAPABILITIES_API_VERSION: u32 = 3; /// declarative `grammar` and an editing `configuration`; see `super::grammar`. pub(crate) const LANGUAGES: &str = "languages"; /// `languageServers[]` apart from their launch fields. Version 2 adds -/// `workspaceConfiguration`. +/// `workspaceConfiguration`. Version 3 adds the session fields a plugin +/// backend uses to talk to its own server: `requestMethods`, `commands`, +/// `serializedCommands`, `forwardNotifications`, `state`, and `remote`. pub(crate) const LANGUAGE_SERVERS: &str = "languageServers"; /// The launch fields language servers and own build providers share. +/// Version 2 adds `runSelectedRuntime` for debug adapters; version 3 adds +/// `launch.kind: "backend"`, a language server whose command line the +/// plugin backend resolves. pub(crate) const SERVER_PROCESS: &str = "serverProcess"; /// `vendor.bundledSignatureRequirement`: origin-scoped host-seal trust for a /// package whose independently installed versions require a publisher signature. @@ -92,12 +97,12 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (EXECUTION_PROVIDERS, &[1]), (EXECUTABLE_RESOLUTION, &[1, 2]), (KEYMAP_IMPORT_PROVIDERS, &[1]), - (LANGUAGE_SERVERS, &[1, 2]), + (LANGUAGE_SERVERS, &[1, 2, 3]), (LANGUAGES, &[1, 2]), (PACKAGE_TRUST, &[1]), (PLUGIN_FUNCTIONS, &[1]), (PROJECT_GENERATORS, &[1, 2]), - (SERVER_PROCESS, &[1, 2]), + (SERVER_PROCESS, &[1, 2, 3]), (SETTINGS, &[1, 2]), (TOOL_DEFINITIONS, &[1]), (TOOLCHAIN_PROVIDERS, &[1]), diff --git a/rust/lithe-core/src/plugins/content_providers.rs b/rust/lithe-core/src/plugins/content_providers.rs new file mode 100644 index 0000000000..24aafafeec --- /dev/null +++ b/rust/lithe-core/src/plugins/content_providers.rs @@ -0,0 +1,85 @@ +//! Content providers of plugin backends (plan API-12). +//! +//! A backend whose server hands out documents that have no file serves them +//! as a URI scheme. The host calls the backend function the scheme is bound +//! to and shows the answer read-only. Core checks that answer, so every host +//! opens the same text under the same limit and refuses the same shapes. + +use super::declarative::decode_payload; +use crate::protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; + +/// Longest document text a provider may answer, in UTF-8 bytes. +pub(crate) const MAX_CONTENT_BYTES: usize = 1024 * 1024; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DecodeRequest { + result: Value, +} + +/// `plugins.contentProviders.decode`: returns `{content}` for a provider +/// answer that is a string or `{content: string}` within the byte limit, and +/// refuses anything else so the host opens nothing. +pub fn decode_content_command(payload: Value) -> Result { + let request: DecodeRequest = decode_payload(payload, "plugins.contentProviders.decode")?; + let content = answer_text(&request.result).ok_or_else(|| { + refused("The content provider must answer a string or an object with only `content`.") + })?; + if content.len() > MAX_CONTENT_BYTES { + return Err(refused("The content provider answered more than 1 MiB.")); + } + Ok(json!({ "content": content })) +} + +fn answer_text(result: &Value) -> Option<&str> { + match result { + Value::String(text) => Some(text), + Value::Object(members) if members.len() == 1 => members.get("content")?.as_str(), + _ => None, + } +} + +fn refused(message: &str) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, message) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_string_and_a_content_object_are_the_same_answer() { + let plain = decode_content_command(json!({ "result": "class A {}" })).unwrap(); + let wrapped = + decode_content_command(json!({ "result": { "content": "class A {}" } })).unwrap(); + assert_eq!(plain, json!({ "content": "class A {}" })); + assert_eq!(wrapped, plain); + } + + #[test] + fn other_shapes_are_refused() { + for result in [ + json!(null), + json!(7), + json!(["text"]), + json!({}), + json!({ "content": 7 }), + json!({ "content": "text", "mime": "text/plain" }), + ] { + let error = decode_content_command(json!({ "result": result })).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest), "{result}"); + } + } + + #[test] + fn the_limit_counts_utf8_bytes() { + let largest = "a".repeat(MAX_CONTENT_BYTES); + assert!(decode_content_command(json!({ "result": largest })).is_ok()); + + // Two bytes per character: half as many characters already exceed it. + let too_large = "é".repeat(MAX_CONTENT_BYTES / 2 + 1); + assert!(decode_content_command(json!({ "result": too_large })).is_err()); + } +} diff --git a/rust/lithe-core/src/plugins/declarative.rs b/rust/lithe-core/src/plugins/declarative.rs index 31ad1199ce..da0149c945 100644 --- a/rust/lithe-core/src/plugins/declarative.rs +++ b/rust/lithe-core/src/plugins/declarative.rs @@ -12,6 +12,7 @@ //! payload is a Core `invalid_request` failure. use super::capabilities::{self, HostCapabilities, Requires, CAPABILITIES_API_VERSION}; +use super::language_server_sessions; pub(crate) use super::settings::is_setting_identifier; use super::settings::{ DeclaredSettings, ResolvedSetting, SettingAction, SettingDeclaration, SettingLayers, @@ -484,6 +485,10 @@ struct LanguageServerDeclaration { /// is `immediate`. `languageServers` 2. #[serde(default, skip_serializing_if = "Option::is_none")] workspace_configuration: Option, + /// Fields of `languageServers` 3 that govern what the plugin backend may + /// send to its own server and how the host keeps the server's state. + #[serde(flatten)] + session: language_server_sessions::SessionDeclaration, } /// How the host starts a process that speaks the LSP base protocol. A @@ -600,6 +605,22 @@ enum LanguageServerLaunch { /// Entry file inside the package: a JAR for `java`, a script for `node`. entry: String, }, + /// The plugin backend resolves the command line each time the server + /// starts: the host calls `function` and passes its answer to + /// `plugins.languageServers.decodeLaunch`. Language servers only, + /// `serverProcess` 3. + Backend { + /// ID of a function the plugin backend registers. + function: String, + /// How long the host waits for the function, within + /// `language_server_sessions::RESOLVE_TIMEOUT_MILLISECONDS`. + #[serde( + default, + rename = "timeoutMilliseconds", + skip_serializing_if = "Option::is_none" + )] + timeout_milliseconds: Option, + }, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -1122,10 +1143,16 @@ impl DeclarativePluginManifest { .activation_events .iter() .any(|event| event == super::backend::ON_WORKSPACE_OPEN), - // An exported function starts the backend when another plugin - // calls it, so it needs no page, command or workspace event. + // A language server the backend launches starts the backend + // when the host asks it for the server's command line; an + // exported function starts it when another plugin calls it. + // Neither needs a page, command or workspace event. provider_query_trigger: !self.toolchain_providers.is_empty() || !self.keymap_import_providers.is_empty() + || self + .language_servers + .iter() + .any(|server| server.process.is_backend_launch()) || self.plugin_functions.as_ref().is_some_and( super::plugin_functions::PluginFunctionsDeclaration::exports_any, ), @@ -1273,17 +1300,51 @@ impl DeclarativePluginManifest { )); } if self.plugin_api_version >= CAPABILITIES_API_VERSION { - // serverProcess 2 exists for the selected-runtime launch alone, so - // a host without it never accepts an adapter it cannot start. - let selected = crate::debug::adapters::uses_selected_runtime(&self.debug_adapters); - let version = self.requires.get(capabilities::SERVER_PROCESS).copied(); - if selected != (version == Some(2)) { + self.validate_server_process_version()?; + } + Ok(()) + } + + /// Checks that `requires.serverProcess` is the lowest version covering + /// the launches the manifest uses. Versions are cumulative: 2 adds the + /// selected-runtime launch of an adapter and 3 the launch a plugin + /// backend resolves, so a host without a version never accepts a + /// process it cannot start. + fn validate_server_process_version(&self) -> Validation<()> { + let backend_launch = self + .language_servers + .iter() + .any(|server| server.process.is_backend_launch()); + let selected = crate::debug::adapters::uses_selected_runtime(&self.debug_adapters); + let declared = self + .requires + .get(capabilities::SERVER_PROCESS) + .copied() + .unwrap_or(1); + if backend_launch { + if declared != 3 { return Err(PluginRejection::at( "plugin.manifest.invalid", "requires.serverProcess", - "serverProcess 2 is required exactly when an adapter runs on the selected runtime.", + "serverProcess 3 is required exactly when a language server is launched by the plugin backend.", )); } + // Only a backend 2 process receives the workspace context the + // launch function needs. + if self.backend.is_none() || self.backend_version() < 2 { + return Err(invalid( + "backend", + "A language server launched by the plugin backend requires backend 2.", + )); + } + return Ok(()); + } + if selected != (declared == 2) || declared > 2 { + return Err(PluginRejection::at( + "plugin.manifest.invalid", + "requires.serverProcess", + "serverProcess 2 is required exactly when an adapter runs on the selected runtime.", + )); } Ok(()) } @@ -1663,6 +1724,28 @@ impl DeclarativePluginManifest { "Editor actions and providers require documents.read for live snapshots.", )); } + // The backend reaches only the servers whose session fields expose + // them; the grant without one would show the user a capability + // nothing exercises. + let language_server_request = + crate::lsp::interface::plugin_function::PERMISSION_LANGUAGE_SERVER_REQUEST; + if self.language_server_version() >= 3 + && self + .language_servers + .iter() + .any(|server| server.session.exposes_server()) + { + required.insert(language_server_request); + } else if self + .permissions + .iter() + .any(|permission| permission == language_server_request) + { + return Err(invalid( + "permissions", + "languageServer.request is used by a languageServers 3 server that lists requestMethods or forwardNotifications; declare one or remove the permission.", + )); + } for permission in required { if !self .permissions @@ -1853,6 +1936,14 @@ impl DeclarativePluginManifest { .unwrap_or(1) } + /// `requires.languageServers`, or 1 for a manifest that does not list it. + pub(crate) fn language_server_version(&self) -> u32 { + self.requires + .get(capabilities::LANGUAGE_SERVERS) + .copied() + .unwrap_or(1) + } + /// Checks the declared settings, sorts them by ID, and returns the IDs /// launch templates may refer to. fn validate_settings(&mut self) -> Validation { @@ -2138,6 +2229,13 @@ impl LanguageServerDeclaration { declared_settings, ServerRole::LanguageServer, )?; + self.session.validate(field, capability_version)?; + if self.process.is_backend_launch() && self.host_integration.is_some() { + return Err(invalid( + format!("{field}.hostIntegration"), + "A language server started through the plugin backend has no host integration.", + )); + } if let Some(configuration) = &self.workspace_configuration { let field = format!("{field}.workspaceConfiguration"); if capability_version < 2 { @@ -2320,10 +2418,17 @@ impl ServerProcess { } files } - LanguageServerLaunch::SystemCommand { .. } => Vec::new(), + LanguageServerLaunch::SystemCommand { .. } | LanguageServerLaunch::Backend { .. } => { + Vec::new() + } } } + /// Whether the plugin backend resolves the command line at start. + pub(crate) fn is_backend_launch(&self) -> bool { + matches!(self.launch, LanguageServerLaunch::Backend { .. }) + } + /// Checks the launch, its arguments and probe, the initialization /// options, and the runtime dependencies. Level 1 arguments are literal /// text; templates are parsed from level 2 on. @@ -2411,6 +2516,18 @@ impl ServerProcess { )); } } + LanguageServerLaunch::Backend { + function, + timeout_milliseconds, + } => { + return self.validate_backend_launch( + field, + api_version, + function, + *timeout_milliseconds, + role, + ); + } } if self .arguments @@ -2479,6 +2596,61 @@ impl ServerProcess { Ok(()) } + /// Checks a launch the plugin backend resolves (`serverProcess` 3). Only + /// a language server may use it, and its command line, probe, options, + /// and runtimes all come from the backend's answer, so the manifest + /// declares none of them. + fn validate_backend_launch( + &self, + field: &str, + api_version: u32, + function: &str, + timeout_milliseconds: Option, + role: ServerRole, + ) -> Validation<()> { + if role != ServerRole::LanguageServer { + return Err(invalid( + format!("{field}.launch.kind"), + format!( + "A {} cannot be started through the plugin backend.", + role.noun() + ), + )); + } + if api_version < capabilities::DEBUG_ADAPTERS_API_VERSION { + return Err(invalid( + format!("{field}.launch.kind"), + "A backend launch requires pluginAPIVersion 4 and serverProcess 3.", + )); + } + if !crate::lsp::interface::plugin_function::is_function_id(function) { + return Err(invalid( + format!("{field}.launch.function"), + "The launch function must be a plugin function ID.", + )); + } + language_server_sessions::validate_resolve_timeout( + timeout_milliseconds, + &format!("{field}.launch.timeoutMilliseconds"), + )?; + let declared = [ + ("arguments", !self.arguments.is_empty()), + ("validationArguments", !self.validation_arguments.is_empty()), + ("runtimeDependencies", !self.runtime_dependencies.is_empty()), + ( + "initializationOptions", + self.initialization_options.is_some(), + ), + ]; + if let Some((name, _)) = declared.iter().find(|(_, present)| *present) { + return Err(invalid( + format!("{field}.{name}"), + "A backend launch takes its command line and options from the backend's answer.", + )); + } + Ok(()) + } + /// Install-review entry of the process, without its owner's ID: the /// executable, its arguments and probe, and the initialization options. pub(crate) fn program(&self, role: ServerRole) -> Value { @@ -2517,6 +2689,17 @@ impl ServerProcess { "arguments": self.arguments, "validationArguments": self.validation_arguments, }), + // The backend chooses the command line when the server starts, + // so the review shows the function that will choose it. + LanguageServerLaunch::Backend { + function, + timeout_milliseconds, + } => json!({ + "kind": format!("backend{suffix}"), + "function": function, + "timeoutMilliseconds": timeout_milliseconds + .unwrap_or(language_server_sessions::RESOLVE_TIMEOUT_MILLISECONDS), + }), }; // Initialization options can name code the server loads (JDT LS // bundles, for example), so changing them is a new program too. @@ -3285,6 +3468,10 @@ pub struct LanguageServerLaunchPlanRequest { /// outside installed resources; Core never infers a writable path. #[serde(default)] log_directory: Option, + /// Absolute writable scratch directory for one start of the server. Only + /// a launch the backend resolves (`serverProcess` 3) needs it. + #[serde(default)] + temporary_directory: Option, /// Host CPU architecture, one of `KNOWN_ARCHITECTURES`. architecture: String, /// Values the user stored for the plugin's settings, by setting ID. A @@ -3304,6 +3491,31 @@ impl LanguageServerLaunchPlanRequest { project: &self.project_settings, } } + + /// The four writable directories a backend-resolved launch receives. + /// Each is required, because the answer may name paths in any of them. + fn backend_launch_directories( + &self, + ) -> Validation> { + fn required<'a>(value: Option<&'a String>, name: &str) -> Validation<&'a str> { + match value { + Some(directory) => launch_directory(directory, name), + None => Err(PluginRejection::new( + "plugin.launch.invalidRequest", + format!("The launch request has no usable {name}."), + )), + } + } + Ok(language_server_sessions::LaunchDirectories { + state: launch_directory(&self.state_directory, "stateDirectory")?, + workspace_state: required( + self.workspace_state_directory.as_ref(), + "workspaceStateDirectory", + )?, + log: required(self.log_directory.as_ref(), "logDirectory")?, + temporary: required(self.temporary_directory.as_ref(), "temporaryDirectory")?, + }) + } } /// Validated substitution values of one launch plan. @@ -3342,21 +3554,151 @@ fn language_server_launch_plan( format!("The plugin does not provide a language server for {language_id}."), ) })?; - let mut plan = server_launch_plan( - manifest, - &server.process, - server.host_integration.as_ref(), - request, - )?; + let mut plan = match &server.process.launch { + LanguageServerLaunch::Backend { + function, + timeout_milliseconds, + } => backend_resolved_launch_plan( + manifest, + &server.language_id, + function, + *timeout_milliseconds, + request, + )?, + _ => server_launch_plan( + manifest, + &server.process, + server.host_integration.as_ref(), + request, + )?, + }; if let Some(configuration) = &server.workspace_configuration { plan["workspaceConfiguration"] = expand_configuration( configuration, &manifest.effective_settings(request.layers()), ); } + // The engine enforces the session fields; a server below version 3 + // has none, so its plan stays as it was. + if manifest.language_server_version() >= 3 { + plan["sessionPolicy"] = server.session.policy(&server.language_id); + } Ok(plan) } +/// The first step of a language server whose backend resolves its launch +/// (`serverProcess` 3): the function to call and its params. The host calls +/// the function and passes the answer to `plugins.languageServers.decodeLaunch`, +/// whose plan it then starts like any other. +fn backend_resolved_launch_plan( + manifest: &DeclarativePluginManifest, + server_id: &str, + function: &str, + timeout_milliseconds: Option, + request: &LanguageServerLaunchPlanRequest, +) -> Validation { + let directories = request.backend_launch_directories()?; + if !KNOWN_ARCHITECTURES.contains(&request.architecture.as_str()) { + return Err(PluginRejection::new( + "plugin.launch.invalidRequest", + format!( + "The architecture {} is not supported.", + request.architecture + ), + )); + } + let settings = manifest.effective_settings(request.layers()); + let mut plan = json!({ + "launch": { + "kind": "backend", + "function": function, + "timeoutMilliseconds": timeout_milliseconds + .unwrap_or(language_server_sessions::RESOLVE_TIMEOUT_MILLISECONDS), + }, + "resolveParams": language_server_sessions::resolve_params( + server_id, + &request.architecture, + &directories, + &settings, + ), + "arguments": [], + "validationArguments": [], + "runtimeRequirements": [], + "requiredDirectories": ["state", "workspaceState", "log", "temporary"], + "requiredPackagePaths": [], + }); + if !settings.is_empty() { + plan["settings"] = json!(settings); + } + Ok(plan) +} + +/// `plugins.languageServers.decodeLaunch`: checks a launch function's answer +/// against the server's declaration and the directories of this start, and +/// returns the plan the host starts. A server whose launch is not resolved +/// by the backend is refused, so a host never runs an answer it did not ask +/// for. +pub fn decode_language_server_launch_command(payload: Value) -> Result { + const COMMAND: &str = "plugins.languageServers.decodeLaunch"; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Payload { + manifest: Value, + #[serde(rename = "languageID")] + language_id: String, + request: LanguageServerLaunchPlanRequest, + result: Value, + } + let payload: Payload = decode_payload(payload, COMMAND)?; + Ok(outcome(validate_manifest_value(payload.manifest).and_then( + |manifest| { + let server = manifest + .language_servers + .iter() + .find(|server| server.language_id == payload.language_id) + .ok_or_else(|| { + PluginRejection::new( + "plugin.launch.unavailable", + format!( + "The plugin does not provide a language server for {}.", + payload.language_id + ), + ) + })?; + if !server.process.is_backend_launch() { + return Err(PluginRejection::new( + "plugin.launch.notBackend", + format!( + "The language server for {} is not launched by the plugin backend.", + payload.language_id + ), + )); + } + let directories = payload.request.backend_launch_directories()?; + let tool_ids: BTreeSet<&str> = manifest + .tool_definitions + .iter() + .filter_map(|definition| definition["id"].as_str()) + .collect(); + let (mut plan, gates) = + language_server_sessions::decode_answer(payload.result, &directories, &tool_ids)?; + let settings = manifest.effective_settings(payload.request.layers()); + if !settings.is_empty() { + plan["settings"] = json!(settings); + } + if plan.get("workspaceConfiguration").is_none() { + if let Some(configuration) = &server.workspace_configuration { + plan["workspaceConfiguration"] = expand_configuration(configuration, &settings); + } + } + let mut policy = server.session.policy(&server.language_id); + policy["gates"] = json!(gates); + plan["sessionPolicy"] = policy; + Ok(("plan", plan)) + }, + ))) +} + /// Whether any string in a JSON value names a variable other than a setting. fn mentions_launch_directory(value: &Value) -> bool { match value { @@ -3774,6 +4116,14 @@ fn server_launch_plan( } launch } + // Validation admits a backend launch only for a language server, + // whose plan `backend_resolved_launch_plan` builds instead. + LanguageServerLaunch::Backend { .. } => { + return Err(PluginRejection::new( + "plugin.launch.unavailable", + "This process is launched by the plugin backend.", + )); + } }; arguments.extend(expand_all(&process.arguments, &mut requirements)); let validation_arguments = expand_all(&process.validation_arguments, &mut requirements); diff --git a/rust/lithe-core/src/plugins/language_server_sessions.rs b/rust/lithe-core/src/plugins/language_server_sessions.rs new file mode 100644 index 0000000000..1d24ad6077 --- /dev/null +++ b/rust/lithe-core/src/plugins/language_server_sessions.rs @@ -0,0 +1,781 @@ +//! Plugin-owned language server sessions (plan API-25, with API-20 state). +//! +//! A plugin whose backend drives its own language server declares, at +//! `languageServers` 3, which requests and notifications the backend may +//! send to that server, which `workspace/executeCommand` commands run one at +//! a time, which server notifications reach the backend, how long per- +//! workspace state is kept, and whether the server works on a remote +//! workspace. At `serverProcess` 3 the backend may also resolve the command +//! line each time the server starts (`launch.kind: "backend"`). +//! +//! Core validates those declarations, turns them into the session policy +//! the LSP engine enforces, decodes the backend's launch answer, and selects +//! state directories to prune. The host calls the function, creates the +//! directories, and starts the process; it never interprets the answer. + +use super::declarative::{ + decode_payload, invalid, is_safe_relative_path, PluginRejection, Validation, +}; +use crate::protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +/// How long the host waits for a launch function by default, in +/// milliseconds; a manifest may choose a value within the bounds below. +pub(crate) const RESOLVE_TIMEOUT_MILLISECONDS: u64 = 30_000; +const MIN_RESOLVE_TIMEOUT_MILLISECONDS: u64 = 1_000; +const MAX_RESOLVE_TIMEOUT_MILLISECONDS: u64 = 120_000; + +/// How long a forwarded request may take when the backend names no timeout, +/// and the longest timeout it may name, in milliseconds. +pub(crate) const DEFAULT_REQUEST_TIMEOUT_MILLISECONDS: u64 = 60_000; +pub(crate) const MAX_REQUEST_TIMEOUT_MILLISECONDS: u64 = 300_000; + +/// Most request or notification methods one server may expose to its +/// backend. Bounded so the policy stays a short list the engine scans. +const MAX_REQUEST_METHODS: usize = 64; +/// Most `workspace/executeCommand` commands one server may expose. +const MAX_COMMANDS: usize = 128; +/// Most server notifications forwarded to the backend. +const MAX_FORWARD_NOTIFICATIONS: usize = 32; +/// Longest method or command name, in UTF-8 bytes. +const MAX_NAME_BYTES: usize = 256; +/// Bounds of `state.retention`. +const MAX_RETENTION_ENTRIES: u32 = 64; +const MAX_RETENTION_DAYS: u32 = 365; +const SECONDS_PER_DAY: u64 = 86_400; + +/// Bounds of one launch answer. An answer is an untrusted value from the +/// plugin backend, so every list and text it carries has a limit. +const MAX_ARGUMENTS: usize = 1024; +const MAX_ARGUMENT_BYTES: usize = 32 * 1024; +const MAX_ENVIRONMENT: usize = 256; +const MAX_ENVIRONMENT_VALUE_BYTES: usize = 32 * 1024; +const MAX_OPTIONS_BYTES: usize = 1024 * 1024; +const MAX_GATES: usize = 8; +const MAX_GATE_MATCH_BYTES: usize = 4 * 1024; +const MAX_WRITABLE_PATHS: usize = 32; + +/// The request that carries server commands. +pub(crate) const EXECUTE_COMMAND: &str = "workspace/executeCommand"; +/// The notification that replaces the server's settings. A backend may +/// always send it, because only the backend knows the server's settings. +pub(crate) const DID_CHANGE_CONFIGURATION: &str = "workspace/didChangeConfiguration"; + +/// Methods the host sends itself to keep the session and the open documents +/// consistent. A backend sending one of them would desynchronize the host's +/// view of the server, so no declaration may name them. +const HOST_OWNED_METHODS: &[&str] = &[ + "initialize", + "initialized", + "shutdown", + "exit", + "textDocument/didOpen", + "textDocument/didChange", + "textDocument/didClose", + "textDocument/didSave", + "textDocument/willSave", + "textDocument/willSaveWaitUntil", + "workspace/didChangeWorkspaceFolders", +]; + +/// Whether a method belongs to the host's own session management. `$/` +/// methods are protocol plumbing such as cancellation and progress. +pub(crate) fn is_host_owned_method(method: &str) -> bool { + method.starts_with("$/") || HOST_OWNED_METHODS.contains(&method) +} + +/// The `languageServers` 3 session fields, flattened into the server's +/// declaration. Every field is optional so a version 1 or 2 manifest that +/// names one can be refused with the field it used. +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct SessionDeclaration { + /// Requests and notifications the backend may send to the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + request_methods: Option>, + /// Commands the backend may run through `workspace/executeCommand`. + #[serde(default, skip_serializing_if = "Option::is_none")] + commands: Option>, + /// Commands that run one at a time; a request for a command already + /// running joins it instead of starting it again. + #[serde(default, skip_serializing_if = "Option::is_none")] + serialized_commands: Option>, + /// Server notifications forwarded to the backend. + #[serde(default, skip_serializing_if = "Option::is_none")] + forward_notifications: Option>, + /// How the host keeps the server's per-workspace state. + #[serde(default, skip_serializing_if = "Option::is_none")] + state: Option, + /// Whether the server works on a remote workspace; supported when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + remote: Option, +} + +/// `state` of a language server: the host prunes its per-workspace state +/// directories by `retention` and offers to reset the current one. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StateDeclaration { + scope: StateScope, + retention: Retention, +} + +/// What one state directory belongs to. Only workspaces exist today; the +/// field is explicit so another scope can be added without guessing. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +enum StateScope { + Workspace, +} + +/// How many inactive state directories are kept, and for how long. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Retention { + max_entries: u32, + max_age_days: u32, +} + +impl Retention { + fn validate(&self) -> Result<(), &'static str> { + if !(1..=MAX_RETENTION_ENTRIES).contains(&self.max_entries) { + return Err("maxEntries must be between 1 and 64."); + } + if !(1..=MAX_RETENTION_DAYS).contains(&self.max_age_days) { + return Err("maxAgeDays must be between 1 and 365."); + } + Ok(()) + } +} + +/// Whether the host may start the server for a remote workspace. +#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum RemoteSupport { + #[default] + Supported, + Unsupported, +} + +impl SessionDeclaration { + /// The first session field the manifest names, for refusing it below + /// `languageServers` 3. + fn first_declared(&self) -> Option<&'static str> { + [ + ("requestMethods", self.request_methods.is_some()), + ("commands", self.commands.is_some()), + ("serializedCommands", self.serialized_commands.is_some()), + ("forwardNotifications", self.forward_notifications.is_some()), + ("state", self.state.is_some()), + ("remote", self.remote.is_some()), + ] + .into_iter() + .find_map(|(name, present)| present.then_some(name)) + } + + /// Whether the backend may talk to the server, which needs the + /// `languageServer.request` permission. + pub(crate) fn exposes_server(&self) -> bool { + self.request_methods.as_ref().is_some_and(|m| !m.is_empty()) + || self + .forward_notifications + .as_ref() + .is_some_and(|m| !m.is_empty()) + } + + /// Checks the session fields of the server at `field`. + pub(crate) fn validate(&self, field: &str, capability_version: u32) -> Validation<()> { + if capability_version < 3 { + return match self.first_declared() { + Some(name) => Err(invalid( + format!("{field}.{name}"), + "Language server session fields require languageServers 3.", + )), + None => Ok(()), + }; + } + let methods = unique_names( + self.request_methods.as_deref(), + &format!("{field}.requestMethods"), + MAX_REQUEST_METHODS, + )?; + if let Some(method) = methods.iter().find(|method| is_host_owned_method(method)) { + return Err(invalid( + format!("{field}.requestMethods"), + format!("The host sends {method} itself; a plugin backend cannot."), + )); + } + let commands = unique_names( + self.commands.as_deref(), + &format!("{field}.commands"), + MAX_COMMANDS, + )?; + // A command list without the request that carries it, or the + // request without a list, would declare a grant nothing can use. + if commands.is_empty() == methods.contains(EXECUTE_COMMAND) { + return Err(invalid( + format!("{field}.commands"), + "commands are declared exactly when requestMethods lists workspace/executeCommand.", + )); + } + let serialized = unique_names( + self.serialized_commands.as_deref(), + &format!("{field}.serializedCommands"), + MAX_COMMANDS, + )?; + if let Some(command) = serialized + .iter() + .find(|command| !commands.contains(*command)) + { + return Err(invalid( + format!("{field}.serializedCommands"), + format!("The serialized command {command} is not listed in commands."), + )); + } + let forwarded = unique_names( + self.forward_notifications.as_deref(), + &format!("{field}.forwardNotifications"), + MAX_FORWARD_NOTIFICATIONS, + )?; + if let Some(method) = forwarded.iter().find(|method| is_host_owned_method(method)) { + return Err(invalid( + format!("{field}.forwardNotifications"), + format!("The host consumes {method} itself and cannot forward it."), + )); + } + if let Some(state) = &self.state { + state + .retention + .validate() + .map_err(|message| invalid(format!("{field}.state.retention"), message))?; + } + Ok(()) + } + + /// The session policy the LSP engine enforces for this server, in the + /// shape `lsp.startServer` accepts as `sessionPolicy`. Lists are sorted + /// so equal declarations give equal policies. + pub(crate) fn policy(&self, server_id: &str) -> Value { + let sorted = |values: &Option>| { + values + .iter() + .flatten() + .cloned() + .collect::>() + }; + let mut policy = json!({ + "serverID": server_id, + "requestMethods": sorted(&self.request_methods), + "commands": sorted(&self.commands), + "serializedCommands": sorted(&self.serialized_commands), + "forwardNotifications": sorted(&self.forward_notifications), + "remote": self.remote.unwrap_or_default(), + "gates": [], + }); + if let Some(state) = &self.state { + policy["state"] = json!(state); + } + policy + } +} + +/// Accepts an optional list of method or command names: at most `limit`, +/// each non-empty, without whitespace or control characters, and unique. +fn unique_names<'a>( + values: Option<&'a [String]>, + field: &str, + limit: usize, +) -> Validation> { + let values = values.unwrap_or_default(); + if values.len() > limit { + return Err(invalid( + field, + format!("At most {limit} entries are allowed."), + )); + } + let mut names = BTreeSet::new(); + for value in values { + if !is_protocol_name(value) { + return Err(invalid( + field, + "Entries must be non-empty names without whitespace.", + )); + } + if !names.insert(value.as_str()) { + return Err(invalid(field, format!("{value} is listed twice."))); + } + } + Ok(names) +} + +/// A method or command name: short text without whitespace or controls. +pub(crate) fn is_protocol_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_NAME_BYTES + && !value + .chars() + .any(|character| character.is_whitespace() || character.is_control()) +} + +/// Checks `launch.timeoutMilliseconds` of a backend launch. +pub(crate) fn validate_resolve_timeout(value: Option, field: &str) -> Validation<()> { + match value { + Some(milliseconds) + if !(MIN_RESOLVE_TIMEOUT_MILLISECONDS..=MAX_RESOLVE_TIMEOUT_MILLISECONDS) + .contains(&milliseconds) => + { + Err(invalid( + field, + "timeoutMilliseconds must be between 1000 and 120000.", + )) + } + _ => Ok(()), + } +} + +/// Writable host directories of one start, each already trimmed of a +/// trailing separator. Every path a launch answer may write lies in one. +pub(crate) struct LaunchDirectories<'a> { + pub(crate) state: &'a str, + pub(crate) workspace_state: &'a str, + pub(crate) log: &'a str, + pub(crate) temporary: &'a str, +} + +impl LaunchDirectories<'_> { + fn contains(&self, path: &str) -> bool { + [self.state, self.workspace_state, self.log, self.temporary] + .into_iter() + .filter(|directory| !directory.is_empty()) + .any(|directory| is_within(path, directory)) + } +} + +/// Whether `path` is `directory` or lies below it, compared as text. +/// Components `.` and `..` are refused, so text containment is real +/// containment once the host joins nothing further. +fn is_within(path: &str, directory: &str) -> bool { + if path.contains('\0') + || path + .split(['/', '\\']) + .any(|component| component == "." || component == "..") + { + return false; + } + match path.strip_prefix(directory) { + Some("") => true, + Some(rest) => rest.starts_with(['/', '\\']), + None => false, + } +} + +/// Params of the launch function, apart from `context` and `tools`, which +/// the host attaches: the server, the machine, the writable directories, +/// and the plugin's effective settings. +pub(crate) fn resolve_params( + server_id: &str, + architecture: &str, + directories: &LaunchDirectories<'_>, + settings: &BTreeMap, +) -> Value { + json!({ + "serverID": server_id, + "platform": { "os": std::env::consts::OS, "arch": architecture }, + "stateDirectory": directories.state, + "workspaceStateDirectory": directories.workspace_state, + "logDirectory": directories.log, + "temporaryDirectory": directories.temporary, + "settings": settings, + }) +} + +/// The launch function's answer. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LaunchAnswer { + executable: AnsweredExecutable, + #[serde(default)] + arguments: Vec, + #[serde(default)] + environment: BTreeMap, + #[serde(default)] + initialization_options: Option, + #[serde(default)] + workspace_configuration: Option, + #[serde(default)] + gates: Vec, + #[serde(default)] + writable_paths: Vec, +} + +/// The program the host starts: a file inside the plugin package, or the +/// executable the host resolved for one of the plugin's tool definitions. +#[derive(Debug, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +enum AnsweredExecutable { + Packaged { path: String }, + Tool { tool: String }, +} + +/// A condition the server must reach before the backend's requests are +/// sent: until then the engine holds them in order. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Gate { + pub(crate) id: String, + until: GateCondition, + pub(crate) method: String, + #[serde(rename = "match")] + pub(crate) pattern: Map, +} + +/// What opens a gate. Only a server notification does today. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +enum GateCondition { + Notification, +} + +fn invalid_answer(message: impl Into) -> PluginRejection { + PluginRejection::new("plugin.launch.invalidResult", message) +} + +fn serialized_bytes(value: &Value) -> usize { + serde_json::to_vec(value).map_or(usize::MAX, |bytes| bytes.len()) +} + +/// Decodes and bounds a launch answer. The result is the start plan the +/// host runs, in the shape of a declarative launch plan, plus the gates +/// that join the session policy. +pub(crate) fn decode_answer( + answer: Value, + directories: &LaunchDirectories<'_>, + tool_ids: &BTreeSet<&str>, +) -> Validation<(Value, Vec)> { + let answer: LaunchAnswer = serde_json::from_value(answer) + .map_err(|error| invalid_answer(format!("The launch answer is malformed: {error}")))?; + let mut package_paths = Vec::new(); + let launch = match answer.executable { + AnsweredExecutable::Packaged { path } => { + if !is_safe_relative_path(&path) { + return Err(PluginRejection::new( + "plugin.launch.outsidePackage", + "The packaged executable must stay inside the plugin package.", + )); + } + package_paths.push(path.clone()); + json!({ "kind": "packaged", "path": path }) + } + AnsweredExecutable::Tool { tool } => { + if !tool_ids.contains(tool.as_str()) { + return Err(PluginRejection::new( + "plugin.launch.undeclaredTool", + format!("The plugin declares no tool definition {tool}."), + )); + } + json!({ "kind": "tool", "tool": tool }) + } + }; + if answer.arguments.len() > MAX_ARGUMENTS + || answer + .arguments + .iter() + .any(|argument| argument.len() > MAX_ARGUMENT_BYTES || argument.contains('\0')) + { + return Err(invalid_answer( + "At most 1024 arguments of at most 32 KiB each, without NUL, are allowed.", + )); + } + if answer.environment.len() > MAX_ENVIRONMENT + || answer.environment.iter().any(|(name, value)| { + name.is_empty() + || name.contains(['=', '\0']) + || value.contains('\0') + || value.len() > MAX_ENVIRONMENT_VALUE_BYTES + }) + { + return Err(invalid_answer( + "At most 256 environment variables with names without '=' and values of at most 32 KiB are allowed.", + )); + } + for (name, options) in [ + ("initializationOptions", &answer.initialization_options), + ("workspaceConfiguration", &answer.workspace_configuration), + ] { + if let Some(options) = options { + if !options.is_object() || serialized_bytes(options) > MAX_OPTIONS_BYTES { + return Err(invalid_answer(format!( + "{name} must be a JSON object of at most 1 MiB." + ))); + } + } + } + if answer.gates.len() > MAX_GATES { + return Err(invalid_answer("At most 8 gates are allowed.")); + } + let mut gate_ids = BTreeSet::new(); + for gate in &answer.gates { + if !is_protocol_name(&gate.id) || !gate_ids.insert(gate.id.as_str()) { + return Err(invalid_answer("Gate IDs must be unique non-empty names.")); + } + if !is_protocol_name(&gate.method) + || serialized_bytes(&Value::Object(gate.pattern.clone())) > MAX_GATE_MATCH_BYTES + { + return Err(invalid_answer( + "A gate names a notification method and a match object of at most 4 KiB.", + )); + } + } + if answer.writable_paths.len() > MAX_WRITABLE_PATHS { + return Err(invalid_answer("At most 32 writable paths are allowed.")); + } + if let Some(path) = answer + .writable_paths + .iter() + .find(|path| !directories.contains(path)) + { + return Err(PluginRejection::new( + "plugin.launch.unwritablePath", + format!("{path} is not inside a directory the host provides for the server."), + )); + } + let mut plan = json!({ + "launch": launch, + "arguments": answer.arguments, + "validationArguments": [], + "runtimeRequirements": [], + "environment": answer.environment, + "writablePaths": answer.writable_paths.iter().collect::>(), + "requiredDirectories": [], + "requiredPackagePaths": package_paths, + }); + if let Some(options) = answer.initialization_options { + plan["initializationOptions"] = options; + } + if let Some(configuration) = answer.workspace_configuration { + plan["workspaceConfiguration"] = configuration; + } + Ok((plan, answer.gates)) +} + +/// Whether a notification's params satisfy a gate's match object: every +/// member of the pattern is present with an equal value, and nested +/// objects match the same way. +pub(crate) fn matches_pattern(params: &Value, pattern: &Map) -> bool { + let Some(params) = params.as_object() else { + return pattern.is_empty(); + }; + pattern + .iter() + .all(|(key, expected)| match (params.get(key), expected) { + (Some(actual @ Value::Object(_)), Value::Object(expected)) => { + matches_pattern(actual, expected) + } + (Some(actual), expected) => actual == expected, + (None, _) => false, + }) +} + +/// `plugins.languageServers.stateRetention` request: the per-workspace +/// state directories of one server and the ones in use. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StateRetentionRequest { + retention: Retention, + now_unix_seconds: u64, + entries: Vec, + /// Directories of workspaces that are open; they are never pruned. + #[serde(default)] + active_names: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StateEntry { + name: String, + last_modified_unix_seconds: u64, +} + +/// A directory name the host may delete: one path component. +fn is_state_entry_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 255 + && name != "." + && name != ".." + && !name.contains(['/', '\\', '\0']) +} + +/// `plugins.languageServers.stateRetention`: selects the inactive state +/// directories to delete. A directory older than `maxAgeDays` goes, and of +/// the rest only the newest fill the `maxEntries` the active ones leave. +/// Duplicate observations keep the newest time so a stale event never +/// deletes a directory that was reused since. +pub fn state_retention_command(payload: Value) -> Result { + let request: StateRetentionRequest = + decode_payload(payload, "plugins.languageServers.stateRetention")?; + request + .retention + .validate() + .map_err(|message| CoreError::new(ErrorCode::InvalidRequest, message.to_string()))?; + let active: BTreeSet<&str> = request.active_names.iter().map(String::as_str).collect(); + let mut newest: BTreeMap<&str, u64> = BTreeMap::new(); + for entry in &request.entries { + if !is_state_entry_name(&entry.name) { + continue; + } + let time = newest.entry(entry.name.as_str()).or_insert(0); + *time = (*time).max(entry.last_modified_unix_seconds); + } + let kept_active = newest.keys().filter(|name| active.contains(*name)).count(); + let mut inactive: Vec<(&str, u64)> = newest + .into_iter() + .filter(|(name, _)| !active.contains(name)) + .collect(); + // Newest first; equal times fall back to the name so the result is stable. + inactive.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(right.0))); + let slots = (request.retention.max_entries as usize).saturating_sub(kept_active); + let max_age = u64::from(request.retention.max_age_days) * SECONDS_PER_DAY; + let mut expired: Vec<&str> = inactive + .iter() + .enumerate() + .filter(|(index, (_, time))| { + *index >= slots || request.now_unix_seconds.saturating_sub(*time) > max_age + }) + .map(|(_, (name, _))| *name) + .collect(); + expired.sort_unstable(); + Ok(json!({ "expiredNames": expired })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn directories() -> LaunchDirectories<'static> { + LaunchDirectories { + state: "/state/metals", + workspace_state: "/state/metals/workspaces/abc", + log: "/logs/plugin", + temporary: "/tmp/plugin", + } + } + + fn tools() -> BTreeSet<&'static str> { + BTreeSet::from(["coursier"]) + } + + #[test] + fn writable_paths_stay_in_host_directories() { + let dirs = directories(); + assert!(dirs.contains("/state/metals/workspaces/abc/index")); + assert!(dirs.contains("/tmp/plugin")); + assert!(!dirs.contains("/state/metalsx")); + assert!(!dirs.contains("/state/metals/../other")); + assert!(!dirs.contains("/home/user/.cache")); + } + + #[test] + fn a_packaged_answer_becomes_a_launch_plan() { + let (plan, gates) = decode_answer( + json!({ + "executable": {"kind": "packaged", "path": "server/bin/metals"}, + "arguments": ["-Dmetals.client=lithe"], + "environment": {"COURSIER_CACHE": "/tmp/plugin/coursier"}, + "initializationOptions": {"isHttpEnabled": false}, + "gates": [{"id": "indexed", "until": "notification", + "method": "metals/status", "match": {"text": "Indexing complete"}}], + "writablePaths": ["/tmp/plugin/coursier"], + }), + &directories(), + &tools(), + ) + .expect("answer decodes"); + assert_eq!( + plan["launch"], + json!({"kind": "packaged", "path": "server/bin/metals"}) + ); + assert_eq!(plan["requiredPackagePaths"], json!(["server/bin/metals"])); + assert_eq!(plan["writablePaths"], json!(["/tmp/plugin/coursier"])); + assert_eq!(gates.len(), 1); + } + + #[test] + fn answers_outside_their_bounds_are_refused() { + let refused = |answer: Value| { + decode_answer(answer, &directories(), &tools()) + .expect_err("answer is refused") + .code + }; + assert_eq!( + refused(json!({"executable": {"kind": "packaged", "path": "../bin/metals"}})), + "plugin.launch.outsidePackage" + ); + assert_eq!( + refused(json!({"executable": {"kind": "tool", "tool": "sbt"}})), + "plugin.launch.undeclaredTool" + ); + assert_eq!( + refused(json!({"executable": {"kind": "tool", "tool": "coursier"}, + "writablePaths": ["/home/user/.metals"]})), + "plugin.launch.unwritablePath" + ); + assert_eq!( + refused(json!({"executable": {"kind": "tool", "tool": "coursier"}, + "arguments": vec!["x"; MAX_ARGUMENTS + 1]})), + "plugin.launch.invalidResult" + ); + assert_eq!( + refused(json!({"executable": {"kind": "tool", "tool": "coursier"}, + "initializationOptions": ["not", "an", "object"]})), + "plugin.launch.invalidResult" + ); + assert_eq!( + refused(json!({"executable": {"kind": "tool", "tool": "coursier"}, + "directories": {}})), + "plugin.launch.invalidResult" + ); + } + + #[test] + fn gate_patterns_match_nested_members() { + let pattern = json!({"type": "Started", "detail": {"phase": "ready"}}); + let pattern = pattern.as_object().expect("object"); + assert!(matches_pattern( + &json!({"type": "Started", "detail": {"phase": "ready", "extra": 1}}), + pattern + )); + assert!(!matches_pattern(&json!({"type": "Starting"}), pattern)); + } + + #[test] + fn retention_keeps_active_and_newest_state() { + let day = SECONDS_PER_DAY; + let response = state_retention_command(json!({ + "retention": {"maxEntries": 2, "maxAgeDays": 30}, + "nowUnixSeconds": 100 * day, + "entries": [ + {"name": "open", "lastModifiedUnixSeconds": day}, + {"name": "recent", "lastModifiedUnixSeconds": 99 * day}, + {"name": "older", "lastModifiedUnixSeconds": 98 * day}, + {"name": "stale", "lastModifiedUnixSeconds": 10 * day}, + {"name": "../escape", "lastModifiedUnixSeconds": 0}, + ], + "activeNames": ["open"], + })) + .expect("retention runs"); + assert_eq!(response["expiredNames"], json!(["older", "stale"])); + } + + #[test] + fn retention_bounds_are_checked() { + let error = state_retention_command(json!({ + "retention": {"maxEntries": 0, "maxAgeDays": 30}, + "nowUnixSeconds": 0, + "entries": [], + })) + .expect_err("zero entries is refused"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } +} diff --git a/rust/lithe-core/src/plugins/mod.rs b/rust/lithe-core/src/plugins/mod.rs index 666690582c..956fb1744a 100644 --- a/rust/lithe-core/src/plugins/mod.rs +++ b/rust/lithe-core/src/plugins/mod.rs @@ -2,6 +2,8 @@ pub(crate) mod backend; pub mod capabilities; +/// Read-only documents a plugin backend serves as a URI scheme. +pub(crate) mod content_providers; pub mod declarative; /// Independent, host-rendered editor actions of ordinary tool plugins. pub mod editor_actions; @@ -9,6 +11,9 @@ pub mod editor_providers; pub(crate) mod executables; pub(crate) mod grammar; pub(crate) mod keymap_import; +/// Session fields of plugin-owned language servers and the launch their +/// backend resolves. +pub(crate) mod language_server_sessions; pub mod marketplace; pub(crate) mod native_ui; pub(crate) mod plugin_functions; diff --git a/rust/lithe-core/src/protocol/command.rs b/rust/lithe-core/src/protocol/command.rs index 49867208d8..d31c139f2e 100644 --- a/rust/lithe-core/src/protocol/command.rs +++ b/rust/lithe-core/src/protocol/command.rs @@ -109,6 +109,12 @@ pub enum CoreCommand { PluginsDeclarativeTestPlan, /// Expands a declarative plugin's language-server launch (`plugins.declarative.languageServerLaunchPlan`). PluginsDeclarativeLanguageServerLaunchPlan, + /// Checks a plugin backend's language-server launch answer (`plugins.languageServers.decodeLaunch`). + PluginsLanguageServersDecodeLaunch, + /// Picks the stored language-server state the host may delete (`plugins.languageServers.stateRetention`). + PluginsLanguageServersStateRetention, + /// Checks a plugin content provider's answer (`plugins.contentProviders.decode`). + PluginsContentProvidersDecode, /// Checks a debug start and returns the adapter's DAP arguments (`debug.adapters.startArguments`). DebugAdaptersStartArguments, /// Validates an IDE-to-DAP TCP endpoint, not an attach target. @@ -452,6 +458,10 @@ pub enum CoreCommand { LspHostResponse, /// Sends a plugin backend one host notification (`lsp.hostNotify`). LspHostNotify, + /// Sends a plugin-owned language server one request of its backend (`lsp.pluginServerRequest`). + LspPluginServerRequest, + /// Sends a plugin-owned language server one notification of its backend (`lsp.pluginServerNotify`). + LspPluginServerNotify, /// Queues shared Java gutter marker resolution (`java.navigationMarkers`). JavaNavigationMarkers, /// Queues shared Java entry selection, build and classpath preparation (`java.prepareLaunch`). @@ -755,6 +765,13 @@ impl CoreCommand { "plugins.declarative.languageServerLaunchPlan" => { Some(Self::PluginsDeclarativeLanguageServerLaunchPlan) } + "plugins.languageServers.decodeLaunch" => { + Some(Self::PluginsLanguageServersDecodeLaunch) + } + "plugins.languageServers.stateRetention" => { + Some(Self::PluginsLanguageServersStateRetention) + } + "plugins.contentProviders.decode" => Some(Self::PluginsContentProvidersDecode), "debug.adapters.startArguments" => Some(Self::DebugAdaptersStartArguments), "debug.validateAdapterEndpoint" => Some(Self::DebugValidateAdapterEndpoint), "debug.adapters.executablePlan" => Some(Self::DebugAdaptersExecutablePlan), @@ -930,6 +947,8 @@ impl CoreCommand { "lsp.configureFunctionRelay" => Some(Self::LspConfigureFunctionRelay), "lsp.hostResponse" => Some(Self::LspHostResponse), "lsp.hostNotify" => Some(Self::LspHostNotify), + "lsp.pluginServerRequest" => Some(Self::LspPluginServerRequest), + "lsp.pluginServerNotify" => Some(Self::LspPluginServerNotify), "java.resolveNavigation" => Some(Self::JavaResolveNavigation), "java.prepareLaunch" => Some(Self::JavaPrepareLaunch), "lsp.cancelOperation" => Some(Self::LspCancelOperation), @@ -1095,6 +1114,11 @@ mod tests { "lsp.configureFunctionRelay", "lsp.hostResponse", "lsp.hostNotify", + "lsp.pluginServerRequest", + "lsp.pluginServerNotify", + "plugins.languageServers.decodeLaunch", + "plugins.languageServers.stateRetention", + "plugins.contentProviders.decode", "lsp.cancelOperation", "lsp.pollEvents", "lsp.waitEvents", diff --git a/rust/lithe-core/src/runtime/dispatcher.rs b/rust/lithe-core/src/runtime/dispatcher.rs index 42f8c647dd..ddac6954e8 100644 --- a/rust/lithe-core/src/runtime/dispatcher.rs +++ b/rust/lithe-core/src/runtime/dispatcher.rs @@ -260,6 +260,21 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { parsed.payload, crate::plugins::declarative::language_server_launch_plan_command, ), + CoreCommand::PluginsLanguageServersDecodeLaunch => plugin_response( + id, + parsed.payload, + crate::plugins::declarative::decode_language_server_launch_command, + ), + CoreCommand::PluginsLanguageServersStateRetention => plugin_response( + id, + parsed.payload, + crate::plugins::language_server_sessions::state_retention_command, + ), + CoreCommand::PluginsContentProvidersDecode => plugin_response( + id, + parsed.payload, + crate::plugins::content_providers::decode_content_command, + ), CoreCommand::DebugValidateAdapterEndpoint => { match crate::debug::validate_adapter_endpoint(parsed.payload) { Ok(data) => CoreResponse::success(id, data), @@ -2338,6 +2353,44 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { Err(error) => CoreResponse::failure(id, error), } } + CoreCommand::LspPluginServerRequest => { + match serde_json::from_value::(parsed.payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin language-server request", + ) + .with_details(error.to_string()) + }) + .and_then(crate::lsp::plugin_server_request) + { + Ok(data) => CoreResponse::success( + id, + serde_json::to_value(data) + .expect("Plugin language-server response should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } + CoreCommand::LspPluginServerNotify => { + match serde_json::from_value::(parsed.payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin language-server notification", + ) + .with_details(error.to_string()) + }) + .and_then(crate::lsp::plugin_server_notify) + { + Ok(data) => CoreResponse::success( + id, + serde_json::to_value(data) + .expect("Plugin language-server notification response should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } CoreCommand::LspCancelOperation => { match serde_json::from_value::(parsed.payload) .map_err(|error| { diff --git a/rust/lithe-core/src/tests/declarative_plugins.rs b/rust/lithe-core/src/tests/declarative_plugins.rs index 4cc1172897..8f8e1eea1c 100644 --- a/rust/lithe-core/src/tests/declarative_plugins.rs +++ b/rust/lithe-core/src/tests/declarative_plugins.rs @@ -53,6 +53,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 LANGUAGE_SERVER_BACKEND_FIXTURE: &str = + contract_file!("fixtures/languages/language-server-backend-launch.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"); @@ -91,6 +93,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, + "language-server-backend-launch.plugin.json" => LANGUAGE_SERVER_BACKEND_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, @@ -121,6 +124,7 @@ fn contract_fixtures_and_official_plugins_validate() { DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE, GRAMMAR_FIXTURE, EDITOR_ACTIONS_FIXTURE, + LANGUAGE_SERVER_BACKEND_FIXTURE, EDITOR_PROVIDERS_FIXTURE, PROJECT_GENERATOR_TOOL_FIXTURE, OFFICIAL_JAVA, diff --git a/rust/lithe-core/src/tests/language_server_sessions.rs b/rust/lithe-core/src/tests/language_server_sessions.rs new file mode 100644 index 0000000000..625f7320ba --- /dev/null +++ b/rust/lithe-core/src/tests/language_server_sessions.rs @@ -0,0 +1,215 @@ +//! Contract tests for plugin-owned language server sessions (API-25). +//! +//! The manifest fixture and the launch-resolution golden live in +//! `shared/contracts/plugins/v1/fixtures/` so the plugin documentation +//! repository and other hosts run the same cases. + +use crate::plugins::declarative::{ + decode_language_server_launch_command, language_server_launch_plan_command, validate_command, +}; +use crate::plugins::marketplace::install_review_command; +use serde_json::{json, Value}; + +macro_rules! contract_file { + ($path:literal) => { + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../shared/contracts/plugins/v1/", + $path + )) + }; +} + +const BACKEND_LAUNCH_FIXTURE: &str = + contract_file!("fixtures/languages/language-server-backend-launch.plugin.json"); +const PACKAGED_SERVER_FIXTURE: &str = + contract_file!("fixtures/languages/language-packaged-server.plugin.json"); +const LAUNCH_RESOLUTION: &str = + contract_file!("fixtures/languages/language-server-launch-resolution.json"); + +fn parse(source: &str) -> Value { + serde_json::from_str(source).expect("fixture is valid JSON") +} + +/// Capability versions of a host that runs the backend-launch fixture. +fn full_host() -> Value { + json!({ + "backend": [1, 2], + "executableResolution": [1, 2], + "languageServers": [1, 2, 3], + "languages": [1], + "serverProcess": [1, 3], + "toolDefinitions": [1], + }) +} + +#[test] +fn backend_launch_fixture_keeps_its_session_declaration() { + let outcome = validate_command(json!({ "manifest": parse(BACKEND_LAUNCH_FIXTURE) })).unwrap(); + assert_eq!(outcome["status"], "ok", "{outcome}"); + + let server = &outcome["plugin"]["languageServers"][0]; + assert_eq!(server["launch"]["kind"], "backend"); + assert_eq!(server["launch"]["function"], "metals.resolveLaunch"); + assert_eq!( + server["requestMethods"], + json!(["textDocument/definition", "workspace/executeCommand"]) + ); + assert_eq!(server["serializedCommands"], json!(["build-import"])); + assert_eq!( + server["forwardNotifications"], + json!(["metals/executeClientCommand", "metals/status"]) + ); + assert_eq!(server["state"]["retention"]["maxEntries"], 8); + assert_eq!(server["remote"], "unsupported"); +} + +#[test] +fn backend_launch_needs_a_host_that_runs_server_process_3() { + let manifest = parse(BACKEND_LAUNCH_FIXTURE); + + let mut old_host = full_host(); + old_host["serverProcess"] = json!([1, 2]); + let refused = + validate_command(json!({ "manifest": manifest, "hostCapabilities": old_host })).unwrap(); + assert_eq!( + refused["error"]["code"], "plugin.api.unsupported", + "{refused}" + ); + assert_eq!(refused["error"]["field"], "requires.serverProcess"); + + let accepted = + validate_command(json!({ "manifest": manifest, "hostCapabilities": full_host() })).unwrap(); + assert_eq!(accepted["status"], "ok", "{accepted}"); +} + +#[test] +fn install_review_names_the_function_that_chooses_the_command_line() { + let outcome = + install_review_command(json!({ "manifest": parse(BACKEND_LAUNCH_FIXTURE) })).unwrap(); + assert_eq!(outcome["status"], "ok", "{outcome}"); + + let programs = outcome["review"]["programs"].as_array().unwrap(); + let program = programs + .iter() + .find(|program| program["kind"] == "backendLanguageServer") + .unwrap_or_else(|| panic!("no backend language server program in {programs:?}")); + assert_eq!(program["function"], "metals.resolveLaunch"); + assert_eq!(program["timeoutMilliseconds"], 30_000); +} + +/// Applies a `set` or `remove` edit to one member of the request object. +fn edit_request(request: &mut Value, edit: &Value) { + let path = edit["path"].as_str().unwrap(); + let key = path + .strip_prefix('/') + .unwrap_or_else(|| panic!("edit path {path} is not a JSON Pointer")); + let members = request.as_object_mut().unwrap(); + match edit["op"].as_str().unwrap() { + "set" => { + members.insert(key.to_string(), edit["value"].clone()); + } + "remove" => { + members.remove(key); + } + other => panic!("unknown edit op {other}"), + } +} + +/// The manifest a golden names by file; only the fixtures these tests use +/// are embedded. +fn manifest_named(file: &str) -> Value { + match file { + "language-server-backend-launch.plugin.json" => parse(BACKEND_LAUNCH_FIXTURE), + "language-packaged-server.plugin.json" => parse(PACKAGED_SERVER_FIXTURE), + other => panic!("the golden names an unknown plugin {other}"), + } +} + +/// Builds the command payload one golden case describes. A case runs +/// against the fixture's plugin and language unless it names its own. +fn case_payload(fixture: &Value, case: &Value) -> Value { + let mut request = fixture["request"].clone(); + for edit in case["requestEdits"].as_array().into_iter().flatten() { + edit_request(&mut request, edit); + } + let plugin = case.get("plugin").unwrap_or(&fixture["plugin"]); + let mut payload = json!({ + "manifest": manifest_named(plugin.as_str().unwrap()), + "languageID": case.get("languageID").unwrap_or(&fixture["languageID"]), + "request": request, + }); + if let Some(result) = case.get("result") { + payload["result"] = result.clone(); + } + payload +} + +/// The operating system is the machine running the test, so no golden +/// can name it. +fn without_host_os(mut data: Value) -> Value { + if let Some(platform) = data.pointer_mut("/plan/resolveParams/platform") { + platform.as_object_mut().unwrap().remove("os"); + } + data +} + +/// What a case compares: the data object of an accepted command, or the +/// stable code of a rejected one. +fn observed(outcome: Value) -> Value { + match outcome["status"].as_str() { + Some("ok") => without_host_os(outcome), + Some("rejected") => json!({ + "status": "rejected", + "code": outcome["error"]["code"], + }), + _ => panic!("unexpected outcome {outcome}"), + } +} + +#[test] +fn launch_resolution_cases_match_the_contract_golden() { + let fixture = parse(LAUNCH_RESOLUTION); + let cases = fixture["cases"].as_array().unwrap(); + assert!(!cases.is_empty()); + + for case in cases { + let name = case["name"].as_str().unwrap(); + let payload = case_payload(&fixture, case); + let outcome = match case["operation"].as_str().unwrap() { + "languageServerLaunchPlan" => language_server_launch_plan_command(payload), + "decodeLaunch" => decode_language_server_launch_command(payload), + other => panic!("{name}: unknown operation {other}"), + } + .unwrap_or_else(|error| panic!("{name}: command failed: {error:?}")); + + assert_eq!( + observed(outcome), + without_host_os(case["expected"].clone()), + "{name}" + ); + } +} + +#[test] +fn a_server_launched_without_a_backend_has_no_answer_to_decode() { + let fixture = parse(LAUNCH_RESOLUTION); + let mut payload = json!({ + "manifest": parse(PACKAGED_SERVER_FIXTURE), + "languageID": "php", + "request": fixture["request"], + "result": { "executable": { "kind": "packaged", "path": "server/bin/metals" } }, + }); + let outcome = decode_language_server_launch_command(payload.clone()).unwrap(); + assert_eq!( + outcome["error"]["code"], "plugin.launch.notBackend", + "{outcome}" + ); + + // The first step of a server that is not resolved by a backend is the + // ordinary launch plan, which has no `resolveParams`. + payload.as_object_mut().unwrap().remove("result"); + let plan = language_server_launch_plan_command(payload).unwrap(); + assert_eq!(plan["status"], "ok", "{plan}"); + assert!(plan["plan"].get("resolveParams").is_none(), "{plan}"); +} diff --git a/rust/lithe-core/src/tests/mod.rs b/rust/lithe-core/src/tests/mod.rs index 665ea794a0..200b1d6989 100644 --- a/rust/lithe-core/src/tests/mod.rs +++ b/rust/lithe-core/src/tests/mod.rs @@ -18,6 +18,7 @@ mod git_repository_setup; mod git_untracked_directories; mod git_workspace_commit; mod github; +mod language_server_sessions; mod languages; mod marketplace_plugins; mod mybatis; diff --git a/scripts/architecture/verify-shared-contracts.sh b/scripts/architecture/verify-shared-contracts.sh index 187ebc51fc..3740dd56ab 100755 --- a/scripts/architecture/verify-shared-contracts.sh +++ b/scripts/architecture/verify-shared-contracts.sh @@ -214,6 +214,17 @@ done abort "plan case #{item.fetch("name")} uses an undocumented code" unless documented.include?(expected.fetch("code")) end end + resolution = JSON.parse(File.read(File.join(fixtures, "languages", "language-server-launch-resolution.json"))) + abort "language server launch resolution fixture schema must be 1" unless resolution.fetch("schemaVersion") == 1 + resolution.fetch("cases").each do |item| + abort "launch resolution case #{item.fetch("name")} uses an unknown operation" unless %w[languageServerLaunchPlan decodeLaunch].include?(item.fetch("operation")) + abort "launch resolution case #{item.fetch("name")} needs a result" if item.fetch("operation") == "decodeLaunch" && !item.key?("result") + abort "launch resolution case #{item.fetch("name")} uses an unknown plugin" if item.key?("plugin") && !fixture_names.include?(item.fetch("plugin")) + expected = item.fetch("expected") + if expected.fetch("status") == "rejected" + abort "launch resolution case #{item.fetch("name")} uses an undocumented code" unless documented.include?(expected.fetch("code")) + end + end # A project plan case runs against the version 1 generator fixture unless it names another. JSON.parse(File.read(File.join(fixtures, "project-generators", "project-plans.json"))).fetch("cases").each do |item| next unless item.key?("manifest") diff --git a/shared/contracts/plugins/v1/README.md b/shared/contracts/plugins/v1/README.md index 6b7e235d8c..ee997d5ef9 100644 --- a/shared/contracts/plugins/v1/README.md +++ b/shared/contracts/plugins/v1/README.md @@ -19,7 +19,7 @@ This directory is the cross-platform source of truth: | Fixture folder | Contents | | --- | --- | | `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/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; `language-server-backend-launch.plugin.json` is a language server whose backend resolves the launch and a session policy (`languageServers` 3, `serverProcess` 3), and `language-server-launch-resolution.json` holds its golden first-step plans and decoded answers | | `fixtures/backend/` | Plugin backends (`backend`, `backend-workspace`, `command-backend`, `terminal-backend`); cross-plugin calls (`plugin-functions-exporter`, `plugin-functions-caller`); `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: `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 | @@ -269,13 +269,14 @@ activation event, and a plugin may consist of grammars alone. | --- | --- | | `languageID` | A declared language. | | `languageIdentifier` | LSP `languageId` for documents; defaults to `languageID`. | -| `launch` | `{"kind": "packaged", "path": …}` runs an executable inside the package. `{"kind": "systemCommand", "commands": [...]}` lists bare command names the host resolves with its tool discovery (PATH, project toolchains, user overrides). API 2 adds `{"kind": "runtime", …}`; see Runtime launch. | +| `launch` | `{"kind": "packaged", "path": …}` runs an executable inside the package. `{"kind": "systemCommand", "commands": [...]}` lists bare command names the host resolves with its tool discovery (PATH, project toolchains, user overrides). API 2 adds `{"kind": "runtime", …}`; see Runtime launch. `serverProcess` 3 adds `{"kind": "backend", …}`, whose command line the plugin backend answers at each start; see [Backend-resolved launch](#backend-resolved-launch-serverprocess-3). | | `arguments` | Arguments passed to the server. Literal text at API 1; launch templates at API 2. | | `validationArguments` | Probe that must exit with status 0 before a candidate is used; empty means the host trusts the candidate and lets the LSP handshake decide. | | `runtimeDependencies` | Runtimes the host must discover and pass to the server. API 1 tools are `node` and `go`; API 2 adds `java`. The host exports each path as `LITHE__PATH` (`LITHE_NODE_PATH`, `LITHE_GO_PATH`; a user-set value takes precedence) and prepends its directory to the server's `PATH`, because servers such as gopls run the tool themselves and an app opened from the Dock does not inherit the shell `PATH`. A project-local copy is never chosen, since servers start automatically when a file opens. | | `initializationOptions` | API 2. A JSON object sent as the LSP `initializationOptions`. Every string value inside it is a launch template. | | `hostIntegration` | API 2, official plugins only. A named integration implemented in the host, with the package resources it reads; see Host integrations. | +| `requestMethods`, `commands`, `serializedCommands`, `forwardNotifications`, `state`, `remote` | `languageServers` 3. What the plugin backend may ask of the running server and how the host keeps its state; see [Plugin-owned sessions](#plugin-owned-sessions-languageservers-3). | The host owns the language-server process lifecycle, the LSP session, and stopping the process when the provider is disabled. An API 3 build provider is @@ -381,21 +382,24 @@ contains a machine path, and the host decides where state lives. host selects the process with exactly one of `languageID` (a language server), `buildSystemID` (a build provider), `vcsProviderID` (a VCS provider), and `backend: true` (the [plugin backend](#plugin-backend)), passes `{pluginDirectory, -stateDirectory, workspaceStateDirectory?, logDirectory?, architecture, settings?}`, and -receives. `workspaceStateDirectory` may be omitted only when the selected +stateDirectory, workspaceStateDirectory?, logDirectory?, temporaryDirectory?, architecture, +settings?}`, and receives. `workspaceStateDirectory` may be omitted only when the selected process does not use `${workspaceStateDir}`; otherwise the request is `plugin.launch.invalidRequest`. The same error applies when a template uses `${logDir}` but `logDirectory` is absent, empty, or not absolute. | Field | Meaning | | --- | --- | -| `launch` | `{kind: "packaged", path}`, `{kind: "systemCommand", commands}`, or `{kind: "runtime", tool, entry, packagedRuntime?, minimumVersion?, versionArguments?}`: what the host resolves to an executable. `packagedRuntime` is the expanded package-relative path of a shipped runtime. `minimumVersion` and `versionArguments` appear together when a discovered runtime must meet a minimum version. | +| `launch` | `{kind: "packaged", path}`, `{kind: "systemCommand", commands}`, or `{kind: "runtime", tool, entry, packagedRuntime?, minimumVersion?, versionArguments?}`: what the host resolves to an executable. `packagedRuntime` is the expanded package-relative path of a shipped runtime. `minimumVersion` and `versionArguments` appear together when a discovered runtime must meet a minimum version. A [backend-resolved launch](#backend-resolved-launch-serverprocess-3) returns `{kind: "backend", function, timeoutMilliseconds}` here, and `{kind: "tool", tool}` appears in the plan `plugins.languageServers.decodeLaunch` returns. | | `arguments` | Complete argument list after the executable, including `-jar` and the entry of a runtime launch. | | `validationArguments` | Expanded probe arguments. | | `runtimeRequirements` | `{tool, minimumVersion?}` for every runtime the host must discover, a discovered launch tool included, sorted by tool. A packaged runtime is not listed. Only the launch tool can carry a minimum version. | | `initializationOptions` | Expanded options; absent when the server declares none. | -| `requiredDirectories` | `state`, `workspaceState`, and/or `log`: the directories the host must create before starting the server. | +| `requiredDirectories` | `state`, `workspaceState`, `log`, and/or `temporary`: the directories the host must create before starting the server. | | `requiredPackagePaths` | Sorted package-relative paths the launch points at. The host verifies each is inside the package and not a symbolic link before starting the server. | | `settings` | Effective value of every declared setting that produced this plan; absent when the plugin declares none. | +| `resolveParams` | Present only for a backend-resolved launch: the params of the launch function, without the `context` and the optional `tools` the host adds. | +| `environment`, `writablePaths` | Present only in the plan `decodeLaunch` returns: the variables of the process, and the paths it writes. | +| `sessionPolicy` | Present for a language server of `languageServers` 3: the [session policy](#plugin-owned-sessions-languageservers-3) the host passes to `lsp.startServer` unchanged. | | `buildProvider` | Present only for a `buildSystemID` selection: `{buildSystemID, executesProjectCode, mayUseNetwork, languageServer?}`. `languageServer` names the language whose server is the provider; the rest of the plan is then that server's plan, and the host reuses its running session instead of starting a second process. | | `vcsProvider` | Present only for a `vcsProviderID` selection: the [provider descriptor](https://github.com/1lck/Lithe-IDEA/blob/preview/shared/contracts/vcs-provider-v1.md#provider-descriptor) the host keeps for the session. | | `backend` | Present only for a `backend` selection: `{hostServices}`, the sorted [host services](#host-services-protocol-version-2) the plugin's permissions grant, plus `version: 2` for a [`backend` 2](#backend-2-workspace-contexts) process. The host passes `hostServices` to `lsp.startServer.hostServices` unchanged. | @@ -595,6 +599,181 @@ requests by section path from it, and sends value with `lsp.updateWorkspaceConfiguration` when an `immediate` setting changes; the running server receives it without a restart. +#### Backend-resolved launch (`serverProcess` 3) + +A server whose command line depends on what the plugin finds when it starts +(a version it resolves, a tool it bootstraps, options it derives from the +project) lets the plugin backend answer the command line each time instead of +declaring one: + +```json +"launch": {"kind": "backend", "function": "launch.resolve", "timeoutMilliseconds": 30000} +``` + +- Only a language server can use it. `requires.serverProcess` is exactly `3` + (the lowest version covering it), the plugin declares a `backend` of + version 2 or later, and `pluginAPIVersion` is at least 4. `function` is a + plugin function ID. `timeoutMilliseconds` is 1000 to 120000 and defaults to + 30000. +- The server declares none of `arguments`, `validationArguments`, + `runtimeDependencies`, `initializationOptions`, or `hostIntegration`: the + answer carries the first four, and a host integration is host code, which + this launch exists to avoid. `workspaceConfiguration` stays declarative + unless the answer carries its own. +- `plugins.declarative.languageServerLaunchPlan` for such a server returns the + first step, not a command line: `launch: {kind: "backend", function, + timeoutMilliseconds}`, `resolveParams`, `requiredDirectories` (always + `state`, `workspaceState`, `log`, and `temporary`), `settings`, and + `sessionPolicy`. Its request adds `temporaryDirectory`, an absolute scratch + directory of this start; the launch needs all four directories, so a request + without one is `plugin.launch.invalidRequest`. +- The host creates the directories, starts the plugin backend if it is not + running, and calls `function` through `lithe/function/invoke` with + `resolveParams` and the workspace `context`. A host may also send `tools`, + `{: {executable, home, version}}`, the resolution of each tool it + could find; Core does not validate it. The macOS host does not send `tools` + yet, so a function must not require it: it answers `{kind: "tool"}` and + lets the host resolve the tool. A failed or timed-out call, or an answer + for a context whose generation has changed, ends this start without a + process. +- The host passes `{manifest, languageID, request, result}` to + `plugins.languageServers.decodeLaunch`, which returns `{status: "ok", plan}` + or a rejection. The plan is an ordinary launch plan (`launch` is `packaged` + or `tool`) whose `sessionPolicy` also carries the answer's `gates`; the host + starts it like any other. A server that is not launched by the backend is + `plugin.launch.notBackend`, so a host never runs an answer it did not ask + for. + +`resolveParams`: + +| Field | Meaning | +| --- | --- | +| `serverID` | The server's `languageID`; also its ID in the `languageServer` host methods. | +| `platform` | `{os, arch}`: the host operating system and CPU architecture (`arm64` or `x86_64`). | +| `stateDirectory`, `workspaceStateDirectory`, `logDirectory`, `temporaryDirectory` | The writable directories of this start, absolute and outside the package and the application bundle. | +| `settings` | The effective value of every declared plugin setting. | + +The answer is an object with these fields; an unknown field is refused. + +| Field | Meaning | +| --- | --- | +| `executable` | `{kind: "packaged", path}` is a file inside the plugin package, read-only, listed in the plan's `requiredPackagePaths`. `{kind: "tool", tool}` names a tool definition of the plugin; the host resolves it like any tool launch. | +| `arguments` | At most 1024 strings of at most 32 KiB, without NUL. | +| `environment` | At most 256 variables; a name is non-empty without `=`, a value is at most 32 KiB. | +| `initializationOptions`, `workspaceConfiguration` | JSON objects of at most 1 MiB each. | +| `gates` | At most 8; see [Plugin-owned sessions](#plugin-owned-sessions-languageservers-3). | +| `writablePaths` | At most 32 paths the server writes. Each lies inside one of the four directories; `.` and `..` components are refused. The plan carries them sorted, and the host creates their parent directories before the start. | + +Rejections: `plugin.launch.invalidResult` for a malformed or oversized answer +or gate, `plugin.launch.outsidePackage` for a packaged path that leaves the +package, `plugin.launch.undeclaredTool` for a tool the plugin does not +define, `plugin.launch.unwritablePath` for a writable path outside the host +directories, `plugin.launch.invalidRequest` for a request without a usable +directory, `plugin.launch.unavailable` for a language without a server, and +`plugin.launch.notBackend`. See `fixtures/languages/language-server-backend-launch.plugin.json` +and `fixtures/languages/language-server-launch-resolution.json`. + +Host limits of the macOS host today: a `{kind: "tool"}` answer is resolved +with the user's tool choice and discovery, and a program that lies inside the +project is refused, because opening a project must not run it; a server whose +launch the backend resolves does not start in a remote workspace; and the +scratch `temporaryDirectory` is removed when the server process ends. + +#### Plugin-owned sessions (`languageServers` 3) + +A plugin backend drives its own server only through what the server +declares. With `requires.languageServers: 3` a server may declare: + +| Field | Meaning | +| --- | --- | +| `requestMethods` | LSP methods the backend may send with `languageServer/request` or `languageServer/notify`; at most 64. | +| `commands` | The `workspace/executeCommand` commands the backend may run; at most 128. Declared exactly when `requestMethods` lists `workspace/executeCommand`. | +| `serializedCommands` | A subset of `commands` that runs one at a time: a request for a command already running joins it and receives the same answer. | +| `forwardNotifications` | Server notifications the host forwards to the backend; at most 32. | +| `state` | `{scope: "workspace", retention: {maxEntries, maxAgeDays}}`. The host prunes the server's per-workspace state directories (see below). `maxEntries` is 1 to 64, `maxAgeDays` 1 to 365. | +| `remote` | `supported` (default) or `unsupported`. | + +- A name is non-empty text of at most 256 bytes without whitespace or control + characters, unique within its list. Names the host sends itself + (`initialize`, `initialized`, `shutdown`, `exit`, `textDocument/didOpen`, + `didChange`, `didClose`, `didSave`, `willSave`, `willSaveWaitUntil`, + `workspace/didChangeWorkspaceFolders`, and every `$/` method) cannot appear + in `requestMethods` or `forwardNotifications`. +- Below `languageServers` 3 each of these fields is `plugin.manifest.invalid`. + A server that lists `requestMethods` or `forwardNotifications` requires the + `languageServer.request` permission; declaring the permission without such a + server is `plugin.manifest.invalid`. +- The launch plan's `sessionPolicy` is these fields as sorted lists plus + `serverID` (the `languageID`) and `gates`. The host sends it unchanged as + `lsp.startServer.sessionPolicy`; Core's LSP engine enforces it, so a host + cannot widen it and a backend cannot step outside it. +- A server with `remote: "unsupported"` is not started for a remote + workspace: `lsp.startServer` answers `not_supported`. + +What the engine enforces on `lsp.pluginServerRequest` and +`lsp.pluginServerNotify`, the two commands behind the host methods: + +- A request must be in `requestMethods`, and a `workspace/executeCommand` + must carry a `params.command` in `commands`; anything else is + `plugin.host.methodNotDeclared`. A notification may be + `workspace/didChangeConfiguration` (the backend always knows the server's + settings; the value also becomes the settings the server reads through + `workspace/configuration`) or a `requestMethods` entry other than + `workspace/executeCommand`. The host's own methods stay refused. +- The session must belong to the calling plugin + (`plugin.host.foreignContribution` otherwise) and be running + (`plugin.host.languageServerUnavailable` otherwise, including every request + still pending when the process stops, crashes, restarts, or the plugin is + disabled). +- A request waits at most `timeoutMilliseconds` (default 60000, at most + 300000) and ends with `plugin.host.timeout`; cancelling it sends the server + `$/cancelRequest` and ends it with `plugin.host.cancelled`. A server's JSON-RPC + error is `plugin.host.languageServerError` with `details: {code, message}`; + the server's `data` is not forwarded. A result over the host's result bound + is `plugin.host.limitExceeded`. +- A **gate** is `{id, until: "notification", method, match}`, declared by the + launch answer. It opens when the server sends a notification with that + `method` whose params contain every member of `match` (nested objects match + the same way). Until every gate has opened, `request` calls wait in order, + at most 128; the 129th is `plugin.host.busy`. A waiting request still obeys + its timeout and cancellation. Notifications are never held. +- The first request for a `serializedCommands` command runs; a later request + for the same command, while the first is running or waiting, joins it and is + answered with the first one's outcome. Cancelling the first request ends the + joined requests with it. +- `forwardNotifications` reach the backend as + `lithe/host/languageServer/didReceiveNotification`. + `workspace/didChangeConfiguration` is the only notification Core consumes + itself. + +**State and retention.** The host keeps one state directory per workspace for +each server, under the plugin's storage (never under the package or application +bundle), and gives the server its own as `workspaceStateDirectory`. The +directories survive disabling and updating the plugin. The plugin chooses the +sub-directory names inside its `workspaceStateDirectory`; the host chooses the +names of the per-workspace directories themselves and never looks inside them. + +The host refreshes a workspace directory's modification time on every start of +the server and sweeps in the background after a start. It asks +`plugins.languageServers.stateRetention` with `{retention, nowUnixSeconds, +entries: [{name, lastModifiedUnixSeconds}], activeNames}`, where `entries` are +the per-workspace directories it found and `activeNames` are those of open +workspaces, and deletes the `expiredNames` it returns: a directory older than +`maxAgeDays` and, of the rest, all but the newest `maxEntries` that open +workspaces leave free. A workspace that is open is never pruned. Names that are +not a single path component are ignored, and the host deletes only names it +listed. A plugin that declares no `state.retention` keeps everything. + +The host can also discard the state of one workspace; the server rebuilds it +the next time it starts. In this version that is an engine path only, with no +user-facing action yet. + +**Preparation status.** `languageServer/setStatus` reports how ready the +server is. It exists because `lithe/function/progress` belongs to a call that +is running, while preparation (importing a build, indexing) outlives any call. + +Example package: `fixtures/languages/language-server-backend-launch.plugin.json`. + ### Execution providers `run` and `test` each name an `executable`: exactly one of a bare `command` @@ -663,8 +842,8 @@ hosts. Level 3 versions each section on its own. A level 3 manifest lists in | --- | --- | --- | | `languages` | `languages[]` | `1`, `2` (adds [`grammar` and `configuration`](#grammars-and-editor-configuration-languages-2)) | | `packageTrust` | `vendor.bundledSignatureRequirement`: origin-scoped trust for a host-sealed bundled copy of a publisher-signed plugin | `1` | -| `languageServers` | `languageServers[]` apart from their launch fields | `1`, `2` (adds [`workspaceConfiguration`](#workspace-configuration-languageservers-2)) | -| `serverProcess` | The launch fields of language servers, of build providers with a process of their own, of VCS providers, and of the plugin backend: `launch`, `arguments`, `validationArguments`, `runtimeDependencies`, `initializationOptions` | `1`, `2` (adds `runSelectedRuntime` for [debug adapters](#api-level-4-debug-adapters); level 4; v2 Core only, macOS and Windows advertise `1`) | +| `languageServers` | `languageServers[]` apart from their launch fields | `1`, `2` (adds [`workspaceConfiguration`](#workspace-configuration-languageservers-2)), `3` (adds the [session fields](#plugin-owned-sessions-languageservers-3)) | +| `serverProcess` | The launch fields of language servers, of build providers with a process of their own, of VCS providers, and of the plugin backend: `launch`, `arguments`, `validationArguments`, `runtimeDependencies`, `initializationOptions` | `1`, `2` (adds `runSelectedRuntime` for [debug adapters](#api-level-4-debug-adapters); level 4; v2 Core only), `3` (adds the [backend-resolved launch](#backend-resolved-launch-serverprocess-3) of a language server). macOS advertises `1` and `3`, Windows `1` | | `executionProviders` | `executionProviders[]` | `1` | | `settings` | `settings[]` and `settingActions[]` | `1`, `2` (adds [placement, scope, effect, page buttons](#settings-v2-placement-scope-effect-and-page-buttons)) | | `ui` | `ui` | `1`, `2` (web content), `3` (native controls), `4` ([backend-only commands](#backend-only-commands-ui-4)) | @@ -774,6 +953,8 @@ Rules for publishing across levels and capability versions: | `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 | +| `languageServer.request` | a `languageServers` 3 server lists `requestMethods` or `forwardNotifications`, and only then; requires `backend` 2. Grants the [`languageServer` host methods](#language-server-host-methods) for the plugin's own servers and their two notifications, nothing else | +| `documents.contentProvider` | the backend registers a [content provider](#content-providers); requires `backend` 2. Grants `documents/registerContentProvider` only, not reading or editing documents | | Activation event | Meaning | | --- | --- | @@ -2006,8 +2187,11 @@ process starts and what it learns about workspaces. - It may start without a page. It needs at least one way to start: a web tool window (first page call, as in version 1), a `ui.commands[]` entry - (its `onCommand:` also starts the backend), or the `onWorkspaceOpen` - event. A backend 2 with none of them is `plugin.manifest.invalid`. + (its `onCommand:` also starts the backend), the `onWorkspaceOpen` + event, or a provider the host queries: a toolchain or keymap import + provider, or a language server with `launch.kind: "backend"`, whose start + asks the backend for its command line. A backend 2 with none of them is + `plugin.manifest.invalid`. - It is still one process per plugin, shared by every open workspace and window, on the machine that runs Lithe, also for remote workspaces. No workspace is process state: each call names its workspace explicitly @@ -2541,6 +2725,10 @@ notifications. | `plugin.host.preconditionFailed` | `-32019` | A state the request requires does not hold, such as a missing user confirmation | | `plugin.host.busy` | `-32020` | The resource is in use; retry later | | `plugin.host.rateLimited` | `-32021` | Too many requests in a period; retry after `details.retryAfterMilliseconds` when given | + | `plugin.host.languageServerUnavailable` | `-32022` | The plugin's language server is not running for the context, or stopped while the request was in flight | + | `plugin.host.languageServerError` | `-32023` | The language server answered with a JSON-RPC error; `details` is `{code, message}` | + | `plugin.host.methodNotDeclared` | `-32024` | The method, or the `workspace/executeCommand` command, is not in the server's declared session | + | `plugin.host.foreignContribution` | `-32026` | The named server or contribution belongs to another plugin | JSON-RPC reserves `-32768` to `-32000` for the protocol and lets implementations define `-32099` to `-32000` as server errors. `-32000` @@ -2574,6 +2762,8 @@ then never sees them. | `lithe/host/workspace/didChangeContexts` | `{ revision }` | `workspace.metadata` | | `lithe/host/subscriptions/notify` | `{ subscriptionID, sequence, event }` | every plugin-owned session | | `lithe/host/commands/didRun` | `{ commandID, context? }` | every plugin-owned session | +| `lithe/host/languageServer/didChangeState` | `{ context, serverID, state, generation }` | `languageServer.request` | +| `lithe/host/languageServer/didReceiveNotification` | `{ context, serverID, generation, method, params?, truncated? }` | `languageServer.request` | - `didChangeContexts` follows every change `revision` of `listContexts` counts; the backend calls `listContexts` for the contexts. A backend that @@ -2714,6 +2904,98 @@ On `versionConflict`, reread and recompute; on `contextExpired`, resolve the original target again, never substitute the focused window. `busy`/`rateLimited` may be retried with bounds; `permissionDenied`/`readOnly` need user intervention. +### Language server host methods + +The `languageServer` host service lets a plugin backend talk to the language +servers its own plugin declares. It is granted by the `languageServer.request` +permission, only for a `languageServers` 3 server that lists `requestMethods` +or `forwardNotifications`, and each method is granted by its full name. +`getCapabilities` lists the methods this host implements. Windows does not +advertise `backend` support. + +Every method takes `context: {contextID, generation}` and `serverID`, the +`languageID` of one of the calling plugin's servers. A server of another +plugin is `plugin.host.foreignContribution`. + +| Methods (prefix `lithe/host/languageServer/`) | Params in addition to `context`, `serverID` | Result | +| --- | --- | --- | +| `request` | `method`, `params?` (an object, default `{}`), `timeoutMilliseconds?` (1 to 300000, default 60000) | `{value}`: the server's JSON-RPC `result`, which may be `null`. | +| `notify` | `method`, `params?` | `{delivered}`. `false` only for `workspace/didChangeConfiguration` sent before the server is initialized; the value is then sent with `initialized`. | +| `setStatus` | `state` (`preparing`, `ready`, `degraded`, or `failed`), `message?`, `percentage?` (a whole number from 0 to 100) | `{}` | + +- `request` and `notify` are checked by the [session policy](#plugin-owned-sessions-languageservers-3): + `plugin.host.methodNotDeclared` for a method or command the server did not + declare, `plugin.host.languageServerUnavailable` when the server is not + running for this context, `plugin.host.languageServerError` when the server + answers with an error (`details: {code, message}`), `plugin.host.timeout`, + `plugin.host.cancelled`, `plugin.host.busy` for the 129th waiting request, + and `plugin.host.limitExceeded` for a result over the host's result bound. + Cancelling the host request (`$/cancelRequest`) cancels the server request. +- `setStatus` shows the plugin's own preparation state next to the server in + the host's status UI: `preparing` with an optional `message` and + `percentage` while the plugin imports a project or indexes, `ready` when the + server can answer, `degraded` when it works with reduced results, and + `failed` when it cannot. `message` is user-facing text of the plugin, shown + as given and cut to 1024 bytes on a character boundary. The latest status + replaces the earlier one of the same server; a new + server `generation` starts without one, and the host removes it when the + server stops. It is not `lithe/function/progress`, which belongs to the + function call that is running, while preparation outlives every call. +- The language server keeps no state of its own in the host: when the process + stops or crashes, every request in flight ends with + `plugin.host.languageServerUnavailable`, and the backend asks again after + `didChangeState` reports `running` with a new `generation`. + +Notifications to the backend, granted by the same permission: + +| Notification | Params | Meaning | +| --- | --- | --- | +| `lithe/host/languageServer/didChangeState` | `{context, serverID, state, generation}` | `state` is `starting`, `running`, `stopped`, or `crashed`. | +| `lithe/host/languageServer/didReceiveNotification` | `{context, serverID, generation, method, params?, truncated?}` | A notification the server sent and `forwardNotifications` lists. | + +`generation` is a positive integer the host raises each time it starts the +server for this context, so a backend can tell which process a state or a +notification belongs to; the host never delivers one of a replaced process +after the new one has started. A forwarded notification larger than +`limits.notificationBytes` is delivered once with `truncated: true` and +without `params`. Core enforces the request policy (whitelist, gates, +serialization, timeouts) when it relays a request, and +`fixtures/backend/function-protocol.json` holds the request, response, and +notification shapes every host must reproduce. + +### Content providers + +A plugin whose server hands out documents that have no file (for example the +decompiled source of a library class) serves them as a URI scheme: + +```json +{ + "context": {"contextID": "w1", "generation": 1}, + "scheme": "metals-library", + "function": "documents.read" +} +``` + +`lithe/host/documents/registerContentProvider`, granted by +`documents.contentProvider`, returns `{subscriptionID}`; dispose it with the +existing subscription API. Registration only records the binding and never +calls the backend; the function must already be registered on the session. + +- A scheme is 1 to 64 lowercase ASCII letters, digits, `+`, `-`, or `.`, and + starts with a letter. The schemes the host or the platform resolves are + refused: `about`, `blob`, `data`, `file`, `ftp`, `http`, `https`, + `javascript`, `lithe`, `mailto`, `untitled`, `ws`, and `wss`. A scheme has + one provider per workspace window; registering it again is + `plugin.host.preconditionFailed`. +- When a document whose URI has that scheme is opened, the host calls the + function through `lithe/function/invoke` with the workspace `context` and + `{uri}`. The answer is a string, or `{content: string}`, of at most 1 MiB. + The document opens read-only; any other answer, a failure, or a timeout + (the host waits 30 seconds) shows the user an error and opens nothing. +- The provider is the only source of the text. The host keeps no copy once + the document closes, and it asks again when the document is reopened. + Ending the session or closing the context withdraws the provider. + ### Backend-only commands (`ui` 4) `requires.ui:4` permits `ui.commands` without `toolWindowID` and allows an empty @@ -3266,6 +3548,11 @@ command payload is a Core `invalid_request` failure instead. | `plugin.build.invalidSelection` | Core | A build request selects a scope, target, filter, or argument the declaration does not allow, or misses a required path | | `plugin.build.invalidOutput` | Core | Build-tool output or a report does not fit its decoder | | `plugin.launch.invalidRequest` | Core | A launch plan request has an unusable directory or an unknown architecture | +| `plugin.launch.notBackend` | Core | `decodeLaunch` named a language server that the plugin backend does not launch | +| `plugin.launch.invalidResult` | Core | A [backend-resolved launch](#backend-resolved-launch-serverprocess-3) answer is malformed, unknown in a field, or over a bound | +| `plugin.launch.outsidePackage` | Core | The answer's packaged executable leaves the plugin package | +| `plugin.launch.undeclaredTool` | Core | The answer's tool is not one of the plugin's tool definitions | +| `plugin.launch.unwritablePath` | Core | The answer writes outside the state, workspace state, log, and temporary directories | | `plugin.grammar.invalid` | Core | A language's grammar file is not a Monarch grammar Core accepts; `field` names the failing part | | `plugin.grammar.unavailable` | Core | The plugin declares no grammar for the language | | `plugin.vcs.reserved` | Core | A VCS provider claims the ID of the built-in Git support | @@ -3316,6 +3603,10 @@ command payload is a Core `invalid_request` failure instead. | `plugin.host.preconditionFailed` | Host | A state the request requires does not hold | | `plugin.host.busy` | Host | The resource is in use; retry later | | `plugin.host.rateLimited` | Host | Too many requests in a period | +| `plugin.host.languageServerUnavailable` | Core | The plugin's language server is not running for the context, or stopped while a request was in flight | +| `plugin.host.languageServerError` | Core | The language server answered a forwarded request with an error; `details` is `{code, message}` | +| `plugin.host.methodNotDeclared` | Core | A forwarded method or command is not in the server's declared session | +| `plugin.host.foreignContribution` | Core | The named language server belongs to another plugin | | `plugin.backend.exited` | Host | A page's call, or a host operation for the backend, ended because the backend process exited | Host-facing plugin states are `notInstalled`, `installed` (enabled or diff --git a/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json b/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json index e77c105f5d..00fd496fd2 100644 --- a/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json +++ b/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json @@ -549,6 +549,39 @@ {"name": "an older protocol cannot create a native terminal", "version": 2, "hostServices": ["lithe/host/terminal/create"], "method": "lithe/host/terminal/create", "params": {}, "expected": {"code": "plugin.host.unavailable", "rpcCode": -32601}}, {"name": "terminal reopen is granted on protocol 3", "version": 3, "hostServices": ["lithe/host/terminal/reopen"], "method": "lithe/host/terminal/reopen", "params": {"context": {"contextID": "w-terminal", "generation": 1}, "terminalID": "owned"}, "expected": {"forward": "terminal"}}, {"name": "terminal dispose is granted on protocol 3", "version": 3, "hostServices": ["lithe/host/terminal/dispose"], "method": "lithe/host/terminal/dispose", "params": {"context": {"contextID": "w-terminal", "generation": 1}, "terminalID": "owned"}, "expected": {"forward": "terminal"}}, + {"name": "a language server request is forwarded when languageServer.request is granted", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun", "params": {"verbose": true}}, "expected": {"forward": "languageServer"}}, + {"name": "a language server request may bound its own timeout", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "rust-analyzer", "method": "rust-analyzer/expandMacro", "params": {}, "timeoutMilliseconds": 300000}, "expected": {"forward": "languageServer"}}, + {"name": "a language server request may run a declared command", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "workspace/executeCommand", "params": {"command": "metals.build-import"}}, "expected": {"forward": "languageServer"}}, + {"name": "a language server notification is forwarded", "version": 3, "hostServices": ["lithe/host/languageServer/notify"], "method": "lithe/host/languageServer/notify", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "workspace/didChangeConfiguration", "params": {"settings": {}}}, "expected": {"forward": "languageServer"}}, + {"name": "a language server status is forwarded", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "preparing", "message": "Importing build", "percentage": 40}, "expected": {"forward": "languageServer"}}, + {"name": "a language server status may omit the message and the percentage", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "rust-analyzer", "state": "ready"}, "expected": {"forward": "languageServer"}}, + {"name": "a language server request needs the languageServer.request grant", "version": 3, "hostServices": [], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "another service's grant never authorizes a language server request", "version": 3, "hostServices": ["workspace"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "the aggregate service name never authorizes a language server request", "version": 3, "hostServices": ["languageServer"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "a notify grant never authorizes a language server request", "version": 3, "hostServices": ["lithe/host/languageServer/notify"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "a language server request is unavailable before protocol 3", "version": 2, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32601, "code": "plugin.host.unavailable"}}, + {"name": "a language server request needs a context", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"serverID": "metals", "method": "metals/doctorRun"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request names a server", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "method": "metals/doctorRun"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request names a method", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request refuses an empty method", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": ""}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request timeout is positive", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun", "timeoutMilliseconds": 0}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request timeout has an upper bound", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun", "timeoutMilliseconds": 300001}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server request names the option it does not support", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/request", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/doctorRun", "workspaceFolder": "/tmp"}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "workspaceFolder"}}}, + {"name": "a language server notification takes no timeout", "version": 3, "hostServices": ["lithe/host/languageServer/notify"], "method": "lithe/host/languageServer/notify", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "workspace/didChangeConfiguration", "timeoutMilliseconds": 5}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "timeoutMilliseconds"}}}, + {"name": "a language server status state is a closed set", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "importing"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server status percentage stops at one hundred", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "preparing", "percentage": 101}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server status percentage is a whole number", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "preparing", "percentage": 12.5}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server status message is text", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "failed", "message": {"text": "x"}}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a language server status has no method field", "version": 3, "hostServices": ["lithe/host/languageServer/setStatus"], "method": "lithe/host/languageServer/setStatus", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "ready", "method": "x"}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "method"}}}, + {"name": "a content provider is registered with the documents.contentProvider grant", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "metals-library", "function": "documents.read"}, "expected": {"forward": "documents"}}, + {"name": "the aggregate documents name never authorizes a content provider", "version": 3, "hostServices": ["documents"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "metals-library", "function": "documents.read"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "a content provider needs its own grant", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "metals-library", "function": "documents.read"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "a content provider cannot serve a scheme the host owns", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "file", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a content provider cannot serve the lithe scheme", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "lithe", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a content scheme is lowercase", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "Metals", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a content scheme starts with a letter", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "1metals", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a content provider names a plugin function", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "metals-library", "function": "not a function"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a content provider needs a context", "version": 3, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"scheme": "metals-library", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a declared caller lists the providers of a function", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/providers", "params": {"functionID": "languageImport.settings"}, "expected": {"relay": true}}, {"name": "a declared caller invokes another plugin's function through the relay", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000}, "expected": {"relay": true}}, {"name": "a nested invocation names the relayed call it belongs to", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000, "parentOperationID": "17"}, "expected": {"relay": true}}, @@ -670,7 +703,11 @@ { "name": "the host is busy and the request may be retried", "code": "plugin.host.busy", "expected": { "code": "plugin.host.busy", "rpcCode": -32020 } }, { "name": "the plugin sent requests too often", "code": "plugin.host.rateLimited", "expected": { "code": "plugin.host.rateLimited", "rpcCode": -32021 } }, { "name": "a host cannot borrow a function code", "code": "plugin.function.unknown", "expected": { "code": "plugin.host.failed", "rpcCode": -32603 } }, - { "name": "a host cannot report a backend exit to the backend", "code": "plugin.backend.exited", "expected": { "code": "plugin.host.failed", "rpcCode": -32603 } } + { "name": "a host cannot report a backend exit to the backend", "code": "plugin.backend.exited", "expected": { "code": "plugin.host.failed", "rpcCode": -32603 } }, + {"name": "the plugin's language server is not running", "code": "plugin.host.languageServerUnavailable", "expected": {"code": "plugin.host.languageServerUnavailable", "rpcCode": -32022}}, + {"name": "the language server answered with an error", "code": "plugin.host.languageServerError", "expected": {"code": "plugin.host.languageServerError", "rpcCode": -32023}}, + {"name": "the method is not in the language server's declared session", "code": "plugin.host.methodNotDeclared", "expected": {"code": "plugin.host.methodNotDeclared", "rpcCode": -32024}}, + {"name": "the server belongs to another plugin", "code": "plugin.host.foreignContribution", "expected": {"code": "plugin.host.foreignContribution", "rpcCode": -32026}} ], "hostNotifications": [ { "name": "changed contexts reach a workspace session", "version": 3, "hostServices": ["workspace"], "method": "lithe/host/workspace/didChangeContexts", "params": { "revision": 4 }, "expected": { "delivered": true } }, @@ -682,6 +719,18 @@ { "name": "a command run in a window", "version": 3, "hostServices": [], "method": "lithe/host/commands/didRun", "params": { "commandID": "db.refresh", "context": { "contextID": "w1", "generation": 2 } }, "expected": { "delivered": true } }, { "name": "a command without a window", "version": 3, "hostServices": [], "method": "lithe/host/commands/didRun", "params": { "commandID": "db.refresh" }, "expected": { "delivered": true } }, { "name": "extra command params are refused", "version": 3, "hostServices": [], "method": "lithe/host/commands/didRun", "params": { "commandID": "db.refresh", "path": "/etc" }, "expected": { "code": "plugin.host.invalidParams" } }, - { "name": "the host cannot call the backend's own protocol", "version": 3, "hostServices": [], "method": "lithe/functions/invoke", "params": {}, "expected": { "code": "plugin.host.unavailable" } } + { "name": "the host cannot call the backend's own protocol", "version": 3, "hostServices": [], "method": "lithe/functions/invoke", "params": {}, "expected": { "code": "plugin.host.unavailable" } }, + {"name": "a language server changed state", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "running", "generation": 3}, "expected": {"delivered": true}}, + {"name": "a language server state is a closed set", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "ready", "generation": 3}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a language server state names its generation", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "stopped"}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a language server state generation is positive", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "crashed", "generation": 0}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a language server state needs the languageServer.request grant", "version": 3, "hostServices": [], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "running", "generation": 1}, "expected": {"code": "plugin.host.permissionDenied"}}, + {"name": "a version 2 backend skips language server state", "version": 2, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didChangeState", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "state": "running", "generation": 1}, "expected": {"delivered": false}}, + {"name": "a forwarded server notification carries its params", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "generation": 2, "method": "metals/status", "params": {"text": "Importing"}}, "expected": {"delivered": true}}, + {"name": "an oversized server notification is marked truncated without params", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "generation": 2, "method": "metals/status", "truncated": true}, "expected": {"delivered": true}}, + {"name": "a truncated server notification drops its params", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "generation": 2, "method": "metals/status", "params": {}, "truncated": true}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a server notification names its method", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "generation": 2}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a server notification names its generation", "version": 3, "hostServices": ["lithe/host/languageServer/request"], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "method": "metals/status", "params": {}}, "expected": {"code": "plugin.host.invalidParams"}}, + {"name": "a server notification needs the languageServer.request grant", "version": 3, "hostServices": [], "method": "lithe/host/languageServer/didReceiveNotification", "params": {"context": {"contextID": "w1", "generation": 1}, "serverID": "metals", "generation": 2, "method": "metals/status", "params": {}}, "expected": {"code": "plugin.host.permissionDenied"}} ] } diff --git a/shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json b/shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json new file mode 100644 index 0000000000..2bc42b5d54 --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json @@ -0,0 +1,116 @@ +{ + "schemaVersion": 2, + "id": "dev.lithe.fixture.language-server-backend-launch", + "displayName": "Backend Launched Language Server Fixture", + "version": "0.1.0", + "pluginAPIVersion": 4, + "requires": { + "backend": 2, + "executableResolution": 2, + "languageServers": 3, + "languages": 1, + "serverProcess": 3, + "toolDefinitions": 1 + }, + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "backend.launch", + "languageServer.launch", + "languageServer.request" + ], + "activationEvents": [ + "onLanguage:scala" + ], + "languages": [ + { + "id": "scala", + "displayName": "Scala", + "fileExtensions": [ + "scala", + "sc" + ], + "projectFileNames": [ + "build.sbt" + ] + } + ], + "toolDefinitions": [ + { + "id": "coursier", + "displayName": "Coursier", + "executableLayouts": [ + { + "path": "bin/cs" + } + ], + "executables": [ + { + "id": "shell", + "kind": "command", + "command": "cs" + } + ], + "version": { + "arguments": [ + "--version" + ], + "pattern": "(\\d+(?:\\.\\d+)*)" + }, + "commands": [ + "cs" + ], + "launch": [ + "${executable}", + "${arguments}" + ] + } + ], + "languageServers": [ + { + "languageID": "scala", + "launch": { + "kind": "backend", + "function": "metals.resolveLaunch", + "timeoutMilliseconds": 30000 + }, + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand" + ], + "commands": [ + "build-connect", + "build-import", + "doctor-run" + ], + "serializedCommands": [ + "build-import" + ], + "forwardNotifications": [ + "metals/executeClientCommand", + "metals/status" + ], + "state": { + "scope": "workspace", + "retention": { + "maxEntries": 8, + "maxAgeDays": 30 + } + }, + "remote": "unsupported" + } + ], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/backend" + }, + "arguments": [ + "--state", + "${stateDir}" + ] + } +} diff --git a/shared/contracts/plugins/v1/fixtures/languages/language-server-launch-resolution.json b/shared/contracts/plugins/v1/fixtures/languages/language-server-launch-resolution.json new file mode 100644 index 0000000000..97637f2141 --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/languages/language-server-launch-resolution.json @@ -0,0 +1,490 @@ +{ + "schemaVersion": 1, + "description": "Golden launch of a language server whose backend resolves the command line (serverProcess 3). `languageServerLaunchPlan` is the first step: Core names the function to call and its params. `decodeLaunch` is the second step: Core bounds the function's `result` and returns the plan the host starts. A case runs against `plugin` and `languageID` unless it names its own, with `request` changed by `requestEdits` (JSON Pointer `set` or `remove`). `expected` is the command's data object, or `{status: \"rejected\", code}` for the stable rejection code. `resolveParams.platform.os` is the host's operating system and is not compared.", + "plugin": "language-server-backend-launch.plugin.json", + "languageID": "scala", + "request": { + "pluginDirectory": "/plugins/metals", + "stateDirectory": "/state/metals", + "workspaceStateDirectory": "/state/metals/workspaces/abc", + "logDirectory": "/logs/metals", + "temporaryDirectory": "/tmp/metals", + "architecture": "arm64" + }, + "cases": [ + { + "name": "the first step asks the backend to resolve the launch", + "operation": "languageServerLaunchPlan", + "expected": { + "status": "ok", + "plan": { + "launch": { + "kind": "backend", + "function": "metals.resolveLaunch", + "timeoutMilliseconds": 30000 + }, + "resolveParams": { + "serverID": "scala", + "platform": { + "arch": "arm64" + }, + "stateDirectory": "/state/metals", + "workspaceStateDirectory": "/state/metals/workspaces/abc", + "logDirectory": "/logs/metals", + "temporaryDirectory": "/tmp/metals", + "settings": {} + }, + "arguments": [], + "validationArguments": [], + "runtimeRequirements": [], + "requiredDirectories": [ + "state", + "workspaceState", + "log", + "temporary" + ], + "requiredPackagePaths": [], + "sessionPolicy": { + "serverID": "scala", + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand" + ], + "commands": [ + "build-connect", + "build-import", + "doctor-run" + ], + "serializedCommands": [ + "build-import" + ], + "forwardNotifications": [ + "metals/executeClientCommand", + "metals/status" + ], + "remote": "unsupported", + "gates": [], + "state": { + "scope": "workspace", + "retention": { + "maxEntries": 8, + "maxAgeDays": 30 + } + } + } + } + } + }, + { + "name": "the first step needs the temporary directory", + "operation": "languageServerLaunchPlan", + "requestEdits": [ + { + "op": "remove", + "path": "/temporaryDirectory" + } + ], + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidRequest" + } + }, + { + "name": "the first step refuses an unknown architecture", + "operation": "languageServerLaunchPlan", + "requestEdits": [ + { + "op": "set", + "path": "/architecture", + "value": "sparc" + } + ], + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidRequest" + } + }, + { + "name": "a packaged answer becomes a start plan with its gates", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "arguments": [ + "-Dmetals.client=lithe" + ], + "environment": { + "COURSIER_CACHE": "/tmp/metals/coursier" + }, + "initializationOptions": { + "isHttpEnabled": false + }, + "workspaceConfiguration": { + "metals": { + "showInferredType": true + } + }, + "gates": [ + { + "id": "build-imported", + "until": "notification", + "method": "metals/status", + "match": { + "text": "Indexing complete" + } + } + ], + "writablePaths": [ + "/tmp/metals/coursier", + "/state/metals/workspaces/abc/.bloop" + ] + }, + "expected": { + "status": "ok", + "plan": { + "launch": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "arguments": [ + "-Dmetals.client=lithe" + ], + "validationArguments": [], + "runtimeRequirements": [], + "environment": { + "COURSIER_CACHE": "/tmp/metals/coursier" + }, + "writablePaths": [ + "/state/metals/workspaces/abc/.bloop", + "/tmp/metals/coursier" + ], + "requiredDirectories": [], + "requiredPackagePaths": [ + "server/bin/metals" + ], + "initializationOptions": { + "isHttpEnabled": false + }, + "workspaceConfiguration": { + "metals": { + "showInferredType": true + } + }, + "sessionPolicy": { + "serverID": "scala", + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand" + ], + "commands": [ + "build-connect", + "build-import", + "doctor-run" + ], + "serializedCommands": [ + "build-import" + ], + "forwardNotifications": [ + "metals/executeClientCommand", + "metals/status" + ], + "remote": "unsupported", + "gates": [ + { + "id": "build-imported", + "until": "notification", + "method": "metals/status", + "match": { + "text": "Indexing complete" + } + } + ], + "state": { + "scope": "workspace", + "retention": { + "maxEntries": 8, + "maxAgeDays": 30 + } + } + } + } + } + }, + { + "name": "a tool answer names a declared tool definition", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "tool", + "tool": "coursier" + }, + "arguments": [ + "launch", + "metals" + ] + }, + "expected": { + "status": "ok", + "plan": { + "launch": { + "kind": "tool", + "tool": "coursier" + }, + "arguments": [ + "launch", + "metals" + ], + "validationArguments": [], + "runtimeRequirements": [], + "environment": {}, + "writablePaths": [], + "requiredDirectories": [], + "requiredPackagePaths": [], + "sessionPolicy": { + "serverID": "scala", + "requestMethods": [ + "textDocument/definition", + "workspace/executeCommand" + ], + "commands": [ + "build-connect", + "build-import", + "doctor-run" + ], + "serializedCommands": [ + "build-import" + ], + "forwardNotifications": [ + "metals/executeClientCommand", + "metals/status" + ], + "remote": "unsupported", + "gates": [], + "state": { + "scope": "workspace", + "retention": { + "maxEntries": 8, + "maxAgeDays": 30 + } + } + } + } + } + }, + { + "name": "an executable outside the package is refused", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "../bin/metals" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.outsidePackage" + } + }, + { + "name": "a tool the plugin does not define is refused", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "tool", + "tool": "sbt" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.undeclaredTool" + } + }, + { + "name": "a writable path outside the host directories is refused", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "writablePaths": [ + "/home/user/.metals" + ] + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.unwritablePath" + } + }, + { + "name": "a writable path cannot climb out of a host directory", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "writablePaths": [ + "/state/metals/../other" + ] + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.unwritablePath" + } + }, + { + "name": "an unknown member of the answer is refused", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "directories": {} + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidResult" + } + }, + { + "name": "initialization options are an object", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "initializationOptions": [ + "not", + "an", + "object" + ] + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidResult" + } + }, + { + "name": "an argument cannot contain NUL", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "arguments": [ + "a\u0000b" + ] + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidResult" + } + }, + { + "name": "an environment name cannot contain an equals sign", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "environment": { + "A=B": "x" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidResult" + } + }, + { + "name": "gate IDs are unique", + "operation": "decodeLaunch", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + }, + "gates": [ + { + "id": "build-imported", + "until": "notification", + "method": "metals/status", + "match": { + "text": "Indexing complete" + } + }, + { + "id": "build-imported", + "until": "notification", + "method": "metals/status", + "match": { + "text": "Indexing complete" + } + } + ] + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidResult" + } + }, + { + "name": "a server the backend does not launch has no answer to decode", + "operation": "decodeLaunch", + "plugin": "language-packaged-server.plugin.json", + "languageID": "php", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.notBackend" + } + }, + { + "name": "a language without a server has no answer to decode", + "operation": "decodeLaunch", + "languageID": "hack", + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.unavailable" + } + }, + { + "name": "decoding needs the same directories the first step did", + "operation": "decodeLaunch", + "requestEdits": [ + { + "op": "remove", + "path": "/logDirectory" + } + ], + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.invalidRequest" + } + } + ] +} diff --git a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json index 6e2c416541..18061a1e99 100644 --- a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json @@ -1055,6 +1055,25 @@ {"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": "session fields need languageServers 3", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/requires/languageServers", "value": 2}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend launch needs serverProcess 3", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/requires/serverProcess", "value": 2}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "serverProcess 3 needs pluginAPIVersion 4", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/pluginAPIVersion", "value": 3}], "expectedCode": "plugin.api.unsupported"}, + {"name": "a backend launch needs a backend", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "remove", "path": "/backend"}, {"op": "remove", "path": "/requires/backend"}, {"op": "set", "path": "/permissions", "value": ["languageServer.launch", "languageServer.request"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend launch needs backend 2", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/requires/backend", "value": 1}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend launch takes its arguments from the answer", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/arguments", "value": ["--stdio"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend launch function is a function ID", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/launch/function", "value": "Resolve Launch"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend launch timeout stays in range", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/launch/timeoutMilliseconds", "value": 100}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "request methods need the request permission", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["backend.launch", "languageServer.launch"]}], "expectedCode": "plugin.permission.undeclared"}, + {"name": "the request permission needs a server to reach", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "remove", "path": "/languageServers/0/requestMethods"}, {"op": "remove", "path": "/languageServers/0/commands"}, {"op": "remove", "path": "/languageServers/0/serializedCommands"}, {"op": "remove", "path": "/languageServers/0/forwardNotifications"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "executeCommand needs a command list", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "remove", "path": "/languageServers/0/commands"}, {"op": "remove", "path": "/languageServers/0/serializedCommands"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a serialized command is a listed command", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/serializedCommands", "value": ["build-reset"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a request method is listed once", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/requestMethods", "value": ["workspace/executeCommand", "workspace/executeCommand"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend cannot send what the host sends", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/requestMethods", "value": ["textDocument/didOpen", "workspace/executeCommand"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend cannot forward protocol plumbing", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/forwardNotifications", "value": ["$/progress"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "state retention keeps a workspace for a day at least", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/state/retention/maxAgeDays", "value": 0}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "state belongs to a known scope", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/state/scope", "value": "user"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "remote support is supported or unsupported", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/remote", "value": "partial"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a content provider needs backend 2", "base": "backend.plugin.json", "edits": [{"op": "set", "path": "/permissions/1", "value": "documents.contentProvider"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export states its calling context", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "remove", "path": "/pluginFunctions/exports/0/context"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export names a context Lithe knows", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0/context", "value": "remote"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export is an object, not a bare function ID", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0", "value": "document.format"}], "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 2e2baff2d5..8be08fe831 100644 --- a/shared/contracts/plugins/v1/plugin-manifest.schema.json +++ b/shared/contracts/plugins/v1/plugin-manifest.schema.json @@ -23,7 +23,9 @@ {"if": {"required": ["pluginFunctions"]}, "then": {"required": ["backend"], "properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["pluginFunctions", "backend", "serverProcess"], "properties": {"backend": {"const": 2}}}}}}, {"if": {"required": ["keymapImportProviders"]}, "then": {"required": ["backend", "permissions"], "properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["keymapImportProviders", "backend", "serverProcess"], "properties": {"backend": {"const": 2}}}, "permissions": {"allOf": [{"contains": {"const": "keymaps.provide"}}, {"contains": {"const": "keymaps.readSelectedSources"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["requires"], "properties": {"requires": {"required": ["settings"], "properties": {"settings": {"const": 2}}}}}, "else": {"properties": {"settings": {"items": {"$ref": "#/$defs/settingVersion1"}}, "settingActions": {"maxItems": 0}}}}, - {"if": {"required": ["requires"], "properties": {"requires": {"required": ["languageServers"], "properties": {"languageServers": {"const": 2}}}}}, "else": {"properties": {"languageServers": {"items": {"properties": {"workspaceConfiguration": false}}}}}} + {"if": {"required": ["requires"], "properties": {"requires": {"required": ["languageServers"], "properties": {"languageServers": {"minimum": 2}}}}}, "else": {"properties": {"languageServers": {"items": {"properties": {"workspaceConfiguration": false}}}}}}, + {"if": {"required": ["requires"], "properties": {"requires": {"required": ["languageServers"], "properties": {"languageServers": {"const": 3}}}}}, "else": {"properties": {"languageServers": {"items": {"properties": {"requestMethods": false, "commands": false, "serializedCommands": false, "forwardNotifications": false, "state": false, "remote": false}}}}}}, + {"if": {"required": ["languageServers"], "properties": {"languageServers": {"contains": {"required": ["launch"], "properties": {"launch": {"required": ["kind"], "properties": {"kind": {"const": "backend"}}}}}}}}, "then": {"required": ["backend"], "properties": {"pluginAPIVersion": {"minimum": 4}, "requires": {"required": ["backend", "serverProcess"], "properties": {"backend": {"const": 2}, "serverProcess": {"const": 3}}}}}} ], "properties": { "schemaVersion": { "const": 2 }, @@ -44,11 +46,11 @@ "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Version 2 adds bounded target argument and environment bindings. The DAP session itself is negotiated by the adapter in initialize.", "enum": [1, 2] }, "executableResolution": { "enum": [1, 2], "description": "Shared executable candidate ordering and strict selection." }, "executionProviders": { "enum": [1] }, - "languageServers": { "description": "Required exactly when languageServers is non-empty. Version 2 adds languageServers[].workspaceConfiguration.", "enum": [1, 2] }, + "languageServers": { "description": "Required exactly when languageServers is non-empty. Version 2 adds languageServers[].workspaceConfiguration. Version 3 adds the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote.", "enum": [1, 2, 3] }, "languages": { "description": "Version 2 adds languages[].grammar and languages[].configuration and is required exactly when one of them is used.", "enum": [1, 2] }, "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [1] }, "projectGenerators": { "description": "Entries of the New Project window: fields, requirements, and steps. Version 2 adds the tool field and retires the runtime field.", "enum": [1, 2] }, - "serverProcess": { "description": "The launch fields of language servers, of build providers that start their own process, of VCS providers, of debug adapters, and of the plugin backend. Version 2 adds runSelectedRuntime and is required exactly when a debug adapter uses it (pluginAPIVersion 4).", "enum": [1, 2] }, + "serverProcess": { "description": "The launch fields of language servers, of build providers that start their own process, of VCS providers, of debug adapters, and of the plugin backend. Version 2 adds runSelectedRuntime and is required exactly when a debug adapter uses it (pluginAPIVersion 4). Version 3 adds the backend-resolved launch of a language server and is required exactly when one uses it (pluginAPIVersion 4, backend 2).", "enum": [1, 2, 3] }, "settings": { "description": "Required exactly when settings or settingActions is non-empty. Version 1 is the API level 2 section: integer, enum, and boolean options. Version 2 adds scope, effect, page, section, the multiSelect, text, file, and directory types, and settingActions.", "enum": [1, 2] }, "toolDefinitions": { "const": 1 }, "toolchainProviders": { "const": 1 }, @@ -89,7 +91,9 @@ "keymaps.readSelectedSources", "browser.open", "window.messages", - "terminal.create"] } + "terminal.create", + "languageServer.request", + "documents.contentProvider"] } }, "activationEvents": { "type": "array", @@ -1301,11 +1305,24 @@ "maxItems": 2, "items": { "$ref": "#/$defs/editorDelimiter" } }, + "protocolName": { + "description": "An LSP method or command name: non-empty text of at most 256 bytes without whitespace or control characters.", + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+$" + }, "languageServer": { "type": "object", "$ref": "#/$defs/serverProcess", "unevaluatedProperties": false, "required": ["languageID"], + "allOf": [ + { + "if": { "required": ["launch"], "properties": { "launch": { "required": ["kind"], "properties": { "kind": { "const": "backend" } } } } }, + "then": { "properties": { "arguments": false, "validationArguments": false, "runtimeDependencies": false, "initializationOptions": false }, "not": { "required": ["hostIntegration"] } } + } + ], "properties": { "languageID": { "type": "string" }, "languageIdentifier": { "type": "string", "minLength": 1 }, @@ -1313,6 +1330,56 @@ "description": "languageServers 2: what the server reads through workspace/configuration and receives again in workspace/didChangeConfiguration. String leaves may be ${setting:} templates, including settings whose effect is immediate, and no other variable.", "type": "object" }, + "requestMethods": { + "description": "languageServers 3: LSP methods the plugin backend may send with languageServer/request or languageServer/notify. The methods the host sends itself are refused. Requires the languageServer.request permission.", + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { "$ref": "#/$defs/protocolName" } + }, + "commands": { + "description": "languageServers 3: workspace/executeCommand commands the backend may run. Declared exactly when requestMethods lists workspace/executeCommand.", + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { "$ref": "#/$defs/protocolName" } + }, + "serializedCommands": { + "description": "languageServers 3: commands that run one at a time; a later request for a running command joins it. Each is also listed in commands.", + "type": "array", + "maxItems": 128, + "uniqueItems": true, + "items": { "$ref": "#/$defs/protocolName" } + }, + "forwardNotifications": { + "description": "languageServers 3: server notifications the host forwards to the backend. Requires the languageServer.request permission.", + "type": "array", + "maxItems": 32, + "uniqueItems": true, + "items": { "$ref": "#/$defs/protocolName" } + }, + "state": { + "description": "languageServers 3: how the host keeps the server's per-workspace state directories.", + "type": "object", + "additionalProperties": false, + "required": ["scope", "retention"], + "properties": { + "scope": { "const": "workspace" }, + "retention": { + "type": "object", + "additionalProperties": false, + "required": ["maxEntries", "maxAgeDays"], + "properties": { + "maxEntries": { "type": "integer", "minimum": 1, "maximum": 64 }, + "maxAgeDays": { "type": "integer", "minimum": 1, "maximum": 365 } + } + } + } + }, + "remote": { + "description": "languageServers 3: whether the server works on a remote workspace. Supported when absent.", + "enum": ["supported", "unsupported"] + }, "hostIntegration": { "description": "pluginAPIVersion 2, official plugins only: a named host integration and the package resources it reads.", "type": "object", @@ -1381,6 +1448,17 @@ "runtimeArguments": { "type": "array", "items": { "type": "string" } }, "entry": { "type": "string", "minLength": 1 } } + }, + { + "description": "serverProcess 3, language servers only: the plugin backend answers the command line each time the server starts. Core refuses it in any other process.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "function"], + "properties": { + "kind": { "const": "backend" }, + "function": { "description": "Plugin function ID: dot-separated lowerCamelCase segments.", "type": "string", "maxLength": 128, "pattern": "^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])" }, + "timeoutMilliseconds": { "type": "integer", "minimum": 1000, "maximum": 120000 } + } } ] }, diff --git a/shared/contracts/rust-core-api.md b/shared/contracts/rust-core-api.md index 8aa74f381f..823e8e9ac2 100644 --- a/shared/contracts/rust-core-api.md +++ b/shared/contracts/rust-core-api.md @@ -1236,6 +1236,8 @@ package manager owns the download and Lithe does not infer bytes from logs. | `lsp.functionRequest` | Invoke one registered plugin function on a session its plugin started | | `lsp.hostResponse` | Answer one host-service request a plugin backend sent | | `lsp.hostNotify` | Send one host notification to a plugin backend that negotiated it | +| `lsp.pluginServerRequest` | Send one request of a plugin backend to the plugin's own language server, under the plugin's declared session policy | +| `lsp.pluginServerNotify` | Send one notification of a plugin backend to the plugin's own language server | | `lsp.configureFunctionRelay` | Replace the enabled plugins and live workspace contexts Core's plugin-to-plugin function relay checks calls against | | `lsp.toolchainRequest` | Send one `toolchains/query` to a plugin backend that negotiated the provider | | `lsp.keymapImportRequest` | Send one shortcut import request to a negotiated plugin provider | @@ -1361,6 +1363,9 @@ package manager owns the download and Lithe does not infer bytes from logs. | `plugins.declarative.discoverTests` | List a declarative plugin's workspace and file test items | | `plugins.declarative.testPlan` | Expand a declarative plugin's test template for a workspace, file, or test case | | `plugins.declarative.languageServerLaunchPlan` | Expand a declarative plugin's language-server, build-provider, VCS-provider, backend, or debug-adapter launch with host directories and architecture | +| `plugins.languageServers.decodeLaunch` | Bound the answer of a plugin backend that resolved a language server's launch and return the plan the host starts | +| `plugins.languageServers.stateRetention` | Choose which inactive per-workspace state directories of a plugin language server the host deletes | +| `plugins.contentProviders.decode` | Bound the answer of a plugin content provider function and return the document text | | `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments | | `debug.adapters.executablePlan` | Say where to look for the program a launch debugs: the user's setting and the adapter's candidate paths | | `plugins.declarative.resolveSettings` | Merge a plugin's stored global and project setting layers into effective values with their source | @@ -3513,6 +3518,43 @@ ungranted service, malformed or oversized params, a session that is not plugin-owned, or one that is not ready is `invalid_request` with the `plugin.host.*` code in `details`. +`lsp.pluginServerRequest` accepts `{ sessionId, operationId?, pluginId, +serverID, method, params?, timeoutMilliseconds? }` and returns `{ operationId }`; +`params` defaults to `{}` and the deadline to 60000 milliseconds (at most +300000). The host resolves `{context, serverID}` of a backend's +`lithe/host/languageServer/request` to the session and calls this command; Core +checks that the session belongs to `pluginId` and `serverID` and enforces the +server's declared session policy: the `requestMethods` whitelist, the +`commands` of `workspace/executeCommand`, `serializedCommands` (a request for a +command already running joins it), and `gates` (a request waits, in order, until +every gate has seen its notification; at most 128 wait, then the request fails +as `plugin.host.busy`). The answer arrives as a `requestCompleted` event whose +`result.value` is the server's result. A failure carries its `plugin.host.*` +code as the event's `error.code` and its details as `error.details`; the host +returns both to the backend unchanged. The codes are +`plugin.host.languageServerUnavailable` (-32022: the session is not ready or +has stopped), `plugin.host.languageServerError` (-32023: the server answered +with an error, in `details.code` and `details.message`), +`plugin.host.methodNotDeclared` (-32024), `plugin.host.foreignContribution` +(-32026), `plugin.host.timeout`, `plugin.host.cancelled`, `plugin.host.busy`, +and `plugin.host.limitExceeded`. The +[plugin contract](plugins/v1/README.md#language-server-host-methods) owns their +meaning. + +`lsp.pluginServerNotify` accepts `{ sessionId, pluginId, serverID, method, +params? }` and returns `{ delivered }`. It sends `workspace/didChangeConfiguration` +and every declared `requestMethods` entry except `workspace/executeCommand`; a +notification is never held behind a gate. `delivered: false` means the server +was not initialized yet and receives the stored configuration with its +`initialized` notification instead. A notification the server sends and +`forwardNotifications` lists is queued as a `pluginServerNotification` event +with `result: { serverID, method, params? }` for the host to relay as +`lithe/host/languageServer/didReceiveNotification`. + +`lsp.startServer` for a plugin-owned server whose manifest declares +`remote: "unsupported"` fails with `not_supported` when the workspace is +remote, before any process is started. + A session that negotiated `litheFunctions` version 4 and holds the `functions` grant may call another plugin's exported function through the [plugin-to-plugin relay](plugins/v1/README.md#cross-plugin-calls-protocol-version-4). @@ -4843,6 +4885,51 @@ architecture or an empty directory is refused with build system, and a build system without a provider with `plugin.launch.unavailable`. +A language server declared with `launch.kind: "backend"` (`serverProcess` 3) has +no command line in its manifest; the plugin's backend chooses it. The plan this +command returns is then only the first step: `launch` is `{ kind: "backend", +function, timeoutMilliseconds }` (30000 when absent) and `resolveParams` is the +params the host sends to that backend function, `{ serverID, platform: { os, +arch }, stateDirectory, workspaceStateDirectory, logDirectory, +temporaryDirectory, settings }`; the host adds `context` and, when the plugin +declares tool definitions, `tools`. The request must carry all four of +`stateDirectory`, `workspaceStateDirectory`, `logDirectory`, and +`temporaryDirectory`, and the plan lists them in `requiredDirectories`. A server +below `languageServers` 3 has no `sessionPolicy`; a version 3 plan carries it +(`serverID`, `requestMethods`, `commands`, `serializedCommands`, +`forwardNotifications`, `remote`, `gates`, `state`) for the engine to enforce. + +`plugins.languageServers.decodeLaunch` is the second step. It accepts +`{ manifest, languageID, request, result }`, where `request` is the first +step's request and `result` is what the backend function returned, and answers +`{ status: "ok", plan }` with the plan the host starts like any other (launch +`packaged` or `tool`, `arguments`, `environment`, `writablePaths`, +`requiredDirectories`, `initializationOptions?`, `workspaceConfiguration?`, and +`sessionPolicy` with the answer's `gates`) or `{ status: "rejected", error }`. +Refusals are `plugin.launch.unavailable` (no such server), +`plugin.launch.notBackend` (the server is not launched by a backend), +`plugin.launch.invalidRequest` (a missing directory), and +`plugin.launch.invalidResult`, `plugin.launch.outsidePackage`, +`plugin.launch.undeclaredTool`, and `plugin.launch.unwritablePath` for the +answer. The golden cases are +`shared/contracts/plugins/v1/fixtures/languages/language-server-launch-resolution.json`. + +`plugins.languageServers.stateRetention` accepts `{ retention: { maxEntries, +maxAgeDays }, nowUnixSeconds, entries: [{ name, lastModifiedUnixSeconds }], +activeNames }` and returns `{ expiredNames }`: the inactive per-workspace state +directories the host deletes. Directories used by a running session +(`activeNames`) are never listed and count against `maxEntries`; of the others, +those older than `maxAgeDays` and those beyond the newest that fit are listed. +The host lists and deletes only directories under its own state storage, never +inside an app bundle or installation directory. + +`plugins.contentProviders.decode` accepts `{ result }`, the value a plugin +function returned for a document of its content scheme, and returns +`{ content }`. `result` is a string, or an object whose only member is +`content: string`; anything else is `invalid_request`, and so is text of more +than 1 MiB (1,048,576 UTF-8 bytes). The host opens `content` as a read-only +document and never interprets it. + A `debugAdapterID` selects a `debugAdapters[]` entry with a `serverProcess` or a `tcpLanguageServer` transport (naming it together with another selector is the same `invalid_request` failure); the plan adds `debugAdapter: { id, diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index c405169dbf..3e83e78770 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -3671,6 +3671,7 @@ "native.cannotBeUsed": "Cannot be used: {arg1}", "native.cannotCopyADirectoryIntoItself": "Cannot copy a directory into itself", "native.cannotCreateANewConversation": "Cannot create a new conversation: {arg1}", + "native.cannotStartInARemoteWorkspaceYet": "{arg1} cannot start in a remote workspace yet.", "native.cannotUseUsingTheProjectJDKInstead": "Cannot use {arg1}; using the project JDK instead.", "native.category": "Category", "native.changeTheValuesStoredInTheSelectedScopeChooseInheritToRemoveAnOverride": "Change the values stored in the selected scope. Choose Inherit to remove an override.", @@ -3874,6 +3875,7 @@ "native.combinedCommitMessage": "Combined commit message", "native.combinesThePullRequestIntoOneCommitOnTheBaseBranch": "Combines the pull request into one commit on the base branch.", "native.command": "Command", + "native.commandChosenBy": "Command chosen by: {arg1}", "native.commandDetails": "Command details", "native.commandPaletteActions": "Command Palette Actions", "native.commandsAnAIAgentStartedThatAreStillRunningForExampleADeploymentADatabaseMigradd876f8a4a": "Commands an AI Agent started that are still running, for example a deployment, a database migration or a dev server. Each one is asked about separately because ending one halfway can leave data or services inconsistent. What the Agent needs for itself, such as its MCP servers, always ends with the Agent.", @@ -4766,6 +4768,7 @@ "native.languageServerInsideThePlugin": "{arg1} language server (inside the plugin)", "native.languageServerInstalledOnThisMac": "{arg1} language server (installed on this Mac)", "native.languageServerLogLevel": "Language server log level", + "native.languageServerStartedByThePlugin": "{arg1} language server (started by the plugin)", "native.languageServers": "Language servers", "native.languageService": "Language Service", "native.languageServiceForThisProject": "Language service for this project", @@ -5091,6 +5094,7 @@ "native.navigateToTheNextEditorLocation": "Navigate to the next editor location", "native.navigateToThePreviousEditorLocation": "Navigate to the previous editor location", "native.navigation": "Navigation", + "native.needsALaunchThisBuildOfLitheCannotResolve": "{arg1} needs a launch this build of Lithe cannot resolve.", "native.needsNoExtraPermissions": "Needs no extra permissions.", "native.needsRestart": "Needs restart", "native.nestedException": "Nested exception", @@ -5203,6 +5207,7 @@ "native.noModelsAvailable": "No models available", "native.noNewCommitsPushingCreatesTheRemoteBranch": "No new commits. Pushing creates the remote branch.", "native.noNotifications": "No notifications", + "native.noOpenWindowShowsThisWorkspaceSoThePluginCannotChooseHowToStartItsLanguageServer": "No open window shows this workspace, so the plugin cannot choose how to start its language server.", "native.noPaths": "No paths", "native.noPathsResolvedForThisService": "No paths resolved for this service", "native.noPlaceToLookYetOpenTheFileYouWantToDebugOrChooseTheProgramYourself": "No place to look yet. Open the file you want to debug, or choose the program yourself.", @@ -5460,6 +5465,7 @@ "native.preflight": "Preflight", "native.preparingConversation": "Preparing conversation…", "native.preparingDownload": "Preparing download…", + "native.preparingTheLanguageServer": "Preparing the language server", "native.preservesEveryCommitAndAddsAMergeCommitToTheBaseBranch": "Preserves every commit and adds a merge commit to the base branch.", "native.pressShortcut": "Press shortcut…", "native.previewBackgroundImage": "Preview background image", @@ -5750,6 +5756,7 @@ "native.residentMemoryOfTheLitheProcess": "Resident memory of the Lithe process", "native.resolveLldConflictedFileSStageTheResultThenContinue": "Resolve {arg1} conflicted file(s), stage the result, then continue.", "native.resolveLldConflictedFileSStageThemThenContinue": "Resolve {arg1} conflicted file(s), stage them, then continue.", + "native.resolvesToAProgramInsideTheProjectWhichALanguageServerCannotStart": "{arg1} resolves to a program inside the project, which a language server cannot start.", "native.resolvingDependencies": "Resolving dependencies...", "native.resolvingPushDestination": "Resolving push destination…", "native.resolvingServicePaths": "Resolving service paths...", @@ -5966,6 +5973,7 @@ "native.sendAMessageTo": "Send a message to {arg1}", "native.sendInputToDebuggee": "Send input to debuggee", "native.sendProgramInput": "Send program input", + "native.sendRequestsAndCommandsToItsLanguageServerForYourProject": "Send requests and commands to its language server for your project", "native.sending": "Sending…", "native.sensitiveFilesAreNotSentToAnAIProvider": "Sensitive files are not sent to an AI provider.", "native.separateArgumentsWithSpacesQuoteAnArgumentThatContainsSpaces": "Separate arguments with spaces; quote an argument that contains spaces.", @@ -6137,6 +6145,7 @@ "native.startThisConfigurationToSeeItsOutputHere": "Start this configuration to see its output here.", "native.startWithAnActionVerbWithoutATypePrefix": "Start with an action verb, without a type prefix", "native.startedATaskThatIsStillRunning": "{arg1} started a task that is still running", + "native.startedByThePlugin": "Started by the plugin", "native.starting": "Starting", "native.startingCommitOptional": "Starting commit (optional)", "native.startingInteractiveRebase": "Starting Interactive Rebase", @@ -6197,6 +6206,7 @@ "native.submittingReview": "Submitting review…", "native.succeeded": "Succeeded", "native.supplementaryMessageCancelled": "Supplementary message cancelled.", + "native.supplyTheTextOfReadOnlyDocumentsItOpensInTheEditor": "Supply the text of read-only documents it opens in the editor", "native.supportedPlaceholdersSummaryChangesTestingRisks": "Supported placeholders: {summary}, {changes}, {testing}, {risks}.", "native.svelteSupport": "Svelte Support", "native.swapDirection": "Swap Direction", @@ -6295,6 +6305,9 @@ "native.theJVMDoesNotExposeSupportedHeapCountersThroughJstat": "The JVM does not expose supported heap counters through jstat.", "native.theJavaLanguageServerDidNotTakeTheMavenConfiguration": "The Java language server did not take the Maven configuration: {arg1}", "native.theJavaLanguageServiceFailedToPrepareTheProject": "The Java language service failed to prepare the project.", + "native.theLanguageServerCouldNotGetReady": "The language server could not get ready", + "native.theLanguageServerIsNotRunning": "The language server is not running.", + "native.theLanguageServerRunsWithLimitedFeatures": "The language server runs with limited features", "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisAutoBuildAfterYouConbfd63f6a8e": "The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release.", "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisPreviewAfterYouConfic01b41840e": "The latest stable release will be downloaded in full and replace this preview after you confirm installation. Projects and settings are kept, but preview-only settings may not work in the stable release.", "native.theLocalAdapterIsAtOrAboveTheVerifiedVersion": "The local adapter is at or above the verified version.", @@ -6374,6 +6387,7 @@ "native.thisBuildSystemAnswersThroughAProviderProcessWhichLitheForMacOSDoesNotRunYet": "This build system answers through a provider process, which Lithe for macOS does not run yet.", "native.thisComputer": "This computer", "native.thisComputerThisProject": "This computer · This project", + "native.thisContentSchemeAlreadyHasAProvider": "This content scheme already has a provider.", "native.thisConversationIsNoLongerAvailableChooseAnotherConversation": "This conversation is no longer available. Choose another conversation.", "native.thisDiffHasTooManyLinesForComparisonShowingTheReportedBeforeAndAfterText": "This diff has too many lines for comparison. Showing the reported before and after text.", "native.thisDocumentIsReadOnly": "This document is read-only", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index ab1e0ef9ec..6af679ffe0 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -3671,6 +3671,7 @@ "native.cannotBeUsed": "无法使用:{arg1}", "native.cannotCopyADirectoryIntoItself": "不能将目录复制到其自身或子目录中", "native.cannotCreateANewConversation": "无法新建对话:{arg1}", + "native.cannotStartInARemoteWorkspaceYet": "{arg1} 暂时还不能在远程工作区中启动。", "native.cannotUseUsingTheProjectJDKInstead": "无法使用 {arg1},已改用项目 JDK。", "native.category": "分类", "native.changeTheValuesStoredInTheSelectedScopeChooseInheritToRemoveAnOverride": "修改所选范围中保存的值。选择“继承”即可移除覆盖。", @@ -3874,6 +3875,7 @@ "native.combinedCommitMessage": "合并后的提交消息", "native.combinesThePullRequestIntoOneCommitOnTheBaseBranch": "将拉取请求压缩为目标分支上的一个提交。", "native.command": "命令", + "native.commandChosenBy": "命令由 {arg1} 决定", "native.commandDetails": "命令详情", "native.commandPaletteActions": "命令面板入口", "native.commandsAnAIAgentStartedThatAreStillRunningForExampleADeploymentADatabaseMigradd876f8a4a": "AI Agent 启动后仍在运行的命令,例如部署、数据库迁移或开发服务器。由于中途结束可能导致数据或服务不一致,每个任务都会单独确认。Agent 自身需要的进程(例如它的 MCP 服务)总是随 Agent 一起结束。", @@ -4766,6 +4768,7 @@ "native.languageServerInsideThePlugin": "{arg1} 语言服务器(插件内置)", "native.languageServerInstalledOnThisMac": "{arg1} 语言服务器(本机已安装)", "native.languageServerLogLevel": "语言服务器日志级别", + "native.languageServerStartedByThePlugin": "{arg1} 语言服务器(由插件启动)", "native.languageServers": "语言服务器", "native.languageService": "语言服务", "native.languageServiceForThisProject": "为此项目启用语言服务", @@ -5091,6 +5094,7 @@ "native.navigateToTheNextEditorLocation": "跳转到下一个编辑器位置", "native.navigateToThePreviousEditorLocation": "跳转到上一个编辑器位置", "native.navigation": "导航", + "native.needsALaunchThisBuildOfLitheCannotResolve": "{arg1} 需要一种当前版本的 Lithe 还无法解析的启动方式。", "native.needsNoExtraPermissions": "不需要额外权限。", "native.needsRestart": "需重启", "native.nestedException": "嵌套异常", @@ -5203,6 +5207,7 @@ "native.noModelsAvailable": "暂无可用模型", "native.noNewCommitsPushingCreatesTheRemoteBranch": "没有新的提交。推送会创建远程分支。", "native.noNotifications": "暂无通知", + "native.noOpenWindowShowsThisWorkspaceSoThePluginCannotChooseHowToStartItsLanguageServer": "没有已打开的窗口显示这个工作区,插件无法决定如何启动它的语言服务器。", "native.noPaths": "没有路径", "native.noPathsResolvedForThisService": "此服务没有已解析的路径", "native.noPlaceToLookYetOpenTheFileYouWantToDebugOrChooseTheProgramYourself": "还没有可查找的位置。请打开要调试的文件,或自行选择程序。", @@ -5460,6 +5465,7 @@ "native.preflight": "预检", "native.preparingConversation": "正在准备对话…", "native.preparingDownload": "正在准备下载…", + "native.preparingTheLanguageServer": "正在准备语言服务器", "native.preservesEveryCommitAndAddsAMergeCommitToTheBaseBranch": "保留全部提交,并在目标分支中添加一个合并提交。", "native.pressShortcut": "请按下快捷键…", "native.previewBackgroundImage": "预览背景图片", @@ -5750,6 +5756,7 @@ "native.residentMemoryOfTheLitheProcess": "Lithe 进程的常驻内存", "native.resolveLldConflictedFileSStageTheResultThenContinue": "请解决 {arg1} 个文件的冲突,暂存结果后再继续。", "native.resolveLldConflictedFileSStageThemThenContinue": "请解决 {arg1} 个冲突文件并暂存,然后继续。", + "native.resolvesToAProgramInsideTheProjectWhichALanguageServerCannotStart": "{arg1} 解析到了项目内的程序,语言服务器不能用它启动。", "native.resolvingDependencies": "正在解析依赖…", "native.resolvingPushDestination": "正在确定推送目标…", "native.resolvingServicePaths": "正在解析服务路径…", @@ -5966,6 +5973,7 @@ "native.sendAMessageTo": "向 {arg1} 发送消息", "native.sendInputToDebuggee": "向调试进程发送输入", "native.sendProgramInput": "发送程序输入", + "native.sendRequestsAndCommandsToItsLanguageServerForYourProject": "为你的项目向它的语言服务器发送请求和命令", "native.sending": "发送中…", "native.sensitiveFilesAreNotSentToAnAIProvider": "敏感文件不会发送给 AI 服务商。", "native.separateArgumentsWithSpacesQuoteAnArgumentThatContainsSpaces": "参数之间用空格分隔;包含空格的参数请加引号。", @@ -6137,6 +6145,7 @@ "native.startThisConfigurationToSeeItsOutputHere": "启动此配置后,输出将显示在这里。", "native.startWithAnActionVerbWithoutATypePrefix": "以动作动词开头,不添加类型前缀", "native.startedATaskThatIsStillRunning": "{arg1} 启动的任务仍在运行", + "native.startedByThePlugin": "由插件启动", "native.starting": "正在启动", "native.startingCommitOptional": "起始提交(可选)", "native.startingInteractiveRebase": "正在开始交互式变基", @@ -6197,6 +6206,7 @@ "native.submittingReview": "正在提交审查…", "native.succeeded": "成功", "native.supplementaryMessageCancelled": "补充消息已取消。", + "native.supplyTheTextOfReadOnlyDocumentsItOpensInTheEditor": "为它在编辑器中打开的只读文档提供文本", "native.supportedPlaceholdersSummaryChangesTestingRisks": "支持的占位符:{summary}、{changes}、{testing}、{risks}。", "native.svelteSupport": "Svelte 支持", "native.swapDirection": "交换方向", @@ -6295,6 +6305,9 @@ "native.theJVMDoesNotExposeSupportedHeapCountersThroughJstat": "当前 JVM 未通过 jstat 提供受支持的堆计数器。", "native.theJavaLanguageServerDidNotTakeTheMavenConfiguration": "Java 语言服务器未能应用 Maven 配置:{arg1}", "native.theJavaLanguageServiceFailedToPrepareTheProject": "Java 语言服务未能完成项目准备。", + "native.theLanguageServerCouldNotGetReady": "语言服务器未能就绪", + "native.theLanguageServerIsNotRunning": "语言服务器没有运行。", + "native.theLanguageServerRunsWithLimitedFeatures": "语言服务器功能受限", "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisAutoBuildAfterYouConbfd63f6a8e": "将全量下载最新正式版,在你确认安装后替换当前 AutoBuild。项目和设置会保留,但 AutoBuild 专有的设置可能无法在正式版中使用。", "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisPreviewAfterYouConfic01b41840e": "将全量下载最新正式版,在你确认安装后替换当前预览版。项目和设置会保留,但预览版专有的设置可能无法在正式版中使用。", "native.theLocalAdapterIsAtOrAboveTheVerifiedVersion": "本地适配器版本等于或高于已核验版本。", @@ -6374,6 +6387,7 @@ "native.thisBuildSystemAnswersThroughAProviderProcessWhichLitheForMacOSDoesNotRunYet": "此构建系统通过 provider 进程响应,macOS 版 Lithe 暂不支持运行 provider 进程。", "native.thisComputer": "本机", "native.thisComputerThisProject": "本机 · 此项目", + "native.thisContentSchemeAlreadyHasAProvider": "这个内容方案已经有提供者了。", "native.thisConversationIsNoLongerAvailableChooseAnotherConversation": "此会话已不可用,请选择其他会话。", "native.thisDiffHasTooManyLinesForComparisonShowingTheReportedBeforeAndAfterText": "差异行数过多,显示 Agent 上报的修改前后文本。", "native.thisDocumentIsReadOnly": "此文档为只读", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index cfbebc6122..202e8a20ce 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -29233,6 +29233,22 @@ "arg1": "string" } }, + { + "id": "native.cannotStartInARemoteWorkspaceYet", + "description": "Native UI: %@ cannot start in a remote workspace yet.", + "platforms": [ + "macos" + ], + "macos": { + "key": "%@ cannot start in a remote workspace yet.", + "arguments": [ + "arg1" + ] + }, + "parameters": { + "arg1": "string" + } + }, { "id": "native.cannotUseUsingTheProjectJDKInstead", "description": "Native UI: Cannot use %@; using the project JDK instead.", @@ -31474,6 +31490,22 @@ "arguments": [] } }, + { + "id": "native.commandChosenBy", + "description": "Native UI: Command chosen by: %@", + "platforms": [ + "macos" + ], + "macos": { + "key": "Command chosen by: %@", + "arguments": [ + "arg1" + ] + }, + "parameters": { + "arg1": "string" + } + }, { "id": "native.commandDetails", "description": "Native UI: Command details", @@ -42166,6 +42198,22 @@ "arguments": [] } }, + { + "id": "native.languageServerStartedByThePlugin", + "description": "Native UI: %@ language server (started by the plugin)", + "platforms": [ + "macos" + ], + "macos": { + "key": "%@ language server (started by the plugin)", + "arguments": [ + "arg1" + ] + }, + "parameters": { + "arg1": "string" + } + }, { "id": "native.languageServers", "description": "Native UI: Language servers", @@ -46061,6 +46109,22 @@ "arguments": [] } }, + { + "id": "native.needsALaunchThisBuildOfLitheCannotResolve", + "description": "Native UI: %@ needs a launch this build of Lithe cannot resolve.", + "platforms": [ + "macos" + ], + "macos": { + "key": "%@ needs a launch this build of Lithe cannot resolve.", + "arguments": [ + "arg1" + ] + }, + "parameters": { + "arg1": "string" + } + }, { "id": "native.needsNoExtraPermissions", "description": "Native UI: Needs no extra permissions.", @@ -47270,6 +47334,17 @@ "arguments": [] } }, + { + "id": "native.noOpenWindowShowsThisWorkspaceSoThePluginCannotChooseHowToStartItsLanguageServer", + "description": "Native UI: No open window shows this workspace, so the plugin cannot choose how to start its language server.", + "platforms": [ + "macos" + ], + "macos": { + "key": "No open window shows this workspace, so the plugin cannot choose how to start its language server.", + "arguments": [] + } + }, { "id": "native.noPaths", "description": "Native UI: No paths", @@ -50196,6 +50271,17 @@ "arguments": [] } }, + { + "id": "native.preparingTheLanguageServer", + "description": "Native UI: Preparing the language server", + "platforms": [ + "macos" + ], + "macos": { + "key": "Preparing the language server", + "arguments": [] + } + }, { "id": "native.preservesEveryCommitAndAddsAMergeCommitToTheBaseBranch", "description": "Native UI: Preserves every commit and adds a merge commit to the base branch.", @@ -53544,6 +53630,22 @@ "arg1": "integer" } }, + { + "id": "native.resolvesToAProgramInsideTheProjectWhichALanguageServerCannotStart", + "description": "Native UI: %@ resolves to a program inside the project, which a language server cannot start.", + "platforms": [ + "macos" + ], + "macos": { + "key": "%@ resolves to a program inside the project, which a language server cannot start.", + "arguments": [ + "arg1" + ] + }, + "parameters": { + "arg1": "string" + } + }, { "id": "native.resolvingDependencies", "description": "Native UI: Resolving dependencies...", @@ -55998,6 +56100,17 @@ "arguments": [] } }, + { + "id": "native.sendRequestsAndCommandsToItsLanguageServerForYourProject", + "description": "Native UI: Send requests and commands to its language server for your project", + "platforms": [ + "macos" + ], + "macos": { + "key": "Send requests and commands to its language server for your project", + "arguments": [] + } + }, { "id": "native.sending", "description": "Native UI: Sending…", @@ -57881,6 +57994,17 @@ "arg1": "string" } }, + { + "id": "native.startedByThePlugin", + "description": "Native UI: Started by the plugin", + "platforms": [ + "macos" + ], + "macos": { + "key": "Started by the plugin", + "arguments": [] + } + }, { "id": "native.starting", "description": "Native UI: Starting", @@ -58537,6 +58661,17 @@ "arguments": [] } }, + { + "id": "native.supplyTheTextOfReadOnlyDocumentsItOpensInTheEditor", + "description": "Native UI: Supply the text of read-only documents it opens in the editor", + "platforms": [ + "macos" + ], + "macos": { + "key": "Supply the text of read-only documents it opens in the editor", + "arguments": [] + } + }, { "id": "native.supportedPlaceholdersSummaryChangesTestingRisks", "description": "Native UI: Supported placeholders: {summary}, {changes}, {testing}, {risks}.", @@ -59657,6 +59792,39 @@ "arguments": [] } }, + { + "id": "native.theLanguageServerCouldNotGetReady", + "description": "Native UI: The language server could not get ready", + "platforms": [ + "macos" + ], + "macos": { + "key": "The language server could not get ready", + "arguments": [] + } + }, + { + "id": "native.theLanguageServerIsNotRunning", + "description": "Native UI: The language server is not running.", + "platforms": [ + "macos" + ], + "macos": { + "key": "The language server is not running.", + "arguments": [] + } + }, + { + "id": "native.theLanguageServerRunsWithLimitedFeatures", + "description": "Native UI: The language server runs with limited features", + "platforms": [ + "macos" + ], + "macos": { + "key": "The language server runs with limited features", + "arguments": [] + } + }, { "id": "native.theLatestStableReleaseWillBeDownloadedInFullAndReplaceThisAutoBuildAfterYouConbfd63f6a8e", "description": "Native UI: The latest stable release will be downloaded in full and replace this AutoBuild after you confirm installation. Projects and settings are kept, but AutoBuild-only settings may not work in the stable release.", @@ -60545,6 +60713,17 @@ "arguments": [] } }, + { + "id": "native.thisContentSchemeAlreadyHasAProvider", + "description": "Native UI: This content scheme already has a provider.", + "platforms": [ + "macos" + ], + "macos": { + "key": "This content scheme already has a provider.", + "arguments": [] + } + }, { "id": "native.thisConversationIsNoLongerAvailableChooseAnotherConversation", "description": "Native UI: This conversation is no longer available. Choose another conversation.", diff --git a/shared/platform-feature-matrix/features/plugin-language-server-sessions.json b/shared/platform-feature-matrix/features/plugin-language-server-sessions.json new file mode 100644 index 0000000000..78e26b5d09 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-language-server-sessions.json @@ -0,0 +1,42 @@ +{ + "id": "plugin-language-server-sessions", + "area": "扩展", + "group": "插件与主题", + "capability": "插件自有语言服务器会话与后端决定启动方式:声明 languageServers 3 的插件,其后端经 lithe/host/languageServer/request|notify|setStatus 向自己的服务器发请求、通知并上报准备状态(preparing/ready/degraded/failed,随进程结束),收到 didChangeState 与 didReceiveNotification;会话策略(请求白名单、门控、串行命令、超时与排队上限、远程不支持)由 Rust Core 执行;serverProcess 3 的 launch.kind:backend 由后端函数在每次启动时给出可执行文件(包内文件或声明的工具)、参数、环境与初始化选项,Core 校验后宿主才启动;documents.contentProvider 让插件为自定义 scheme 提供只读文档(如 jar 内源码);宿主按 state.retention 在后台回收每个工作区的服务器状态目录;状态栏显示插件自己上报的准备状态", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "rust/lithe-core/src/lsp/interface/plugin_server.rs", + "rust/lithe-core/src/lsp/interface/plugin_function.rs", + "rust/lithe-core/src/plugins/language_server_sessions.rs", + "rust/lithe-core/src/plugins/content_providers.rs", + "rust/lithe-core/src/tests/language_server_sessions.rs", + "shared/contracts/plugins/v1/README.md", + "shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json", + "shared/contracts/plugins/v1/fixtures/languages/language-server-launch-resolution.json", + "macos/Sources/Lithe/Application/Features/PluginLanguageServerHostService.swift", + "macos/Sources/Lithe/Application/Features/PluginContentProviderHostService.swift", + "macos/Sources/Lithe/Models/AppModel/AppModel+PluginLanguageServers.swift", + "macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift", + "macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerWorkspaceState.swift", + "macos/Sources/LitheLanguageIntelligenceModule/Services/PluginLanguageServerRelay.swift", + "macos/Sources/Lithe/Views/Workbench/PluginServerStatusView.swift", + "macos/Tests/LitheTests/PluginLanguageServerHostServiceTests.swift", + "macos/Tests/LitheTests/PluginBackendLaunchTests.swift", + "macos/Tests/LitheTests/PluginContentProviderTests.swift", + "macos/Tests/LitheTests/MacPluginLanguageServerWorkspaceStateTests.swift", + "macos/Tests/LitheLanguageIntelligenceModuleTests/PluginLanguageServerRelayTests.swift" + ] + }, + "windows": { + "implementationStatus": "missing", + "verificationStatus": "not-applicable", + "evidence": [ + "shared/contracts/plugins/v1/README.md" + ] + }, + "owner": "Extensions", + "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core,过滤 plugin_server、plugin_function、language_server_sessions、content_providers、declarative,核对 language-server-launch-resolution.json 的启动问题与答案、decodeLaunch 的七类拒绝码、会话策略(白名单、门控、串行、超时、128 个排队后 busy、远程 not_supported)。macOS 宿主:scripts/macos/test/test-macos.sh --filter \"PluginLanguageServerHostServiceTests|PluginBackendLaunchTests|PluginContentProviderTests|MacPluginLanguageServerWorkspaceStateTests\",以及 LitheLanguageIntelligenceModuleTests 中的 PluginLanguageServerRelayTests。scripts/macos/verify/verify-runtime-bundle-immutability.sh 确认启动后 bundle 内文件清单不变。macOS 原生验收:debug 应用安装一个声明 languageServers 3、serverProcess 3 与 documents.contentProvider 的示例插件(语言服务器用 Metals 或 rust-analyzer 的桩),打开本地工作区后确认后端被调用并返回可执行文件、服务器启动且进程在应用目录之外;后端调用 languageServer/request 得到服务器答案,setStatus 的文字显示在状态栏并随服务器停止消失;关闭窗口后用 pgrep 确认服务器与后端不残留;把一个工作区状态目录的时间改到 40 天前并重新启动,确认它被回收而正在打开的工作区的目录保留;打开远程工作区确认该服务器被拒绝启动。", + "notes": "本条覆盖 #1495 计划的 API-25,并包含 API-12(内容提供者)、API-20(按工作区的服务器状态与回收)和 API-22(准备状态)。宿主只做 I/O:请求白名单、门控、超时与排队由 Core 的会话策略执行,状态目录的回收由 Core 的 plugins.languageServers.stateRetention 决定、Swift 只列目录并删除 Core 点名的目录。setStatus 不复用 lithe/function/progress,因为准备过程比任何一次调用都长;动作按钮(actions)与 done/total 进度暂未提供,只有 percentage。内容提供者的答案上限是 1 MiB。远程工作区暂不支持由后端启动的服务器。宿主附带的 tools 参数尚未发送。没有面向用户的“重置语言服务器状态”入口,只有引擎路径(rebuildWorkspaceState)。旧的 hostIntegration 路径与 Java 专属的 JDT 代码仍在,由后续 E1 与 Windows 的 W2 移除。Windows/Tauri 尚无插件后端宿主,仍走旧路径。" +}