diff --git a/.agents/notes/implemented/architecture/2026-09-13-module-runtime-boundaries-and-lifecycle.md b/.agents/notes/implemented/architecture/2026-09-13-module-runtime-boundaries-and-lifecycle.md index a801772954..6ea8f00bfb 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-module-runtime-boundaries-and-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-09-13-module-runtime-boundaries-and-lifecycle.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 模块的启动、停止、资源持有和故障恢复由统一运行时负责,模块本身只使用被授予的能力。禁用模块不能偷偷启动进程或 watcher;模块启动失败后,运行时必须能记录状态并支持后续恢复。 @@ -338,7 +340,7 @@ SQL 执行状态栏沿同版 `EditorMarkupModelImpl` 的共享几何:右侧 14 - `macos/Sources/LitheApplicationKernel/Registry/ModuleRegistry.swift` - `macos/Sources/Lithe/` - `macos/Sources/Lithe*Module/` -- `Plugins/mac/Official/` +- 已迁出:原 `Plugins/mac/Official/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `macos/Tests/LitheApplicationKernelTests/` - `scripts/architecture/verify-module-boundaries.sh` diff --git a/.agents/notes/implemented/architecture/2026-09-18-php-support-plugin-ownership-and-plans.md b/.agents/notes/implemented/architecture/2026-09-18-php-support-plugin-ownership-and-plans.md index 2d337dd774..7ff1847652 100644 --- a/.agents/notes/implemented/architecture/2026-09-18-php-support-plugin-ownership-and-plans.md +++ b/.agents/notes/implemented/architecture/2026-09-18-php-support-plugin-ownership-and-plans.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 PHP 支持由用户选择安装和启用,主程序不携带 PHP 插件包、Node/Bun 或 Intelephense。Intelephense 是通过语言服务器协议(LSP)与编辑器通信的第三方 PHP 分析服务;PHP 解释器只负责运行程序和 PHPUnit 测试。插件禁用后必须停止自己启动的任务和进程,不能影响其他语言或删除用户自行安装的工具。 @@ -72,7 +74,7 @@ Windows 休眠的 Run Actions 宿主不再扫描其他语言的 manifest 或自 - `node scripts/plugins/test-official-plugin-distribution.mjs`:默认分发名单不含 PHP,未知插件不会意外打入主程序。 - `./scripts/macos/verify/verify-macos-package.sh`:实际组装产物不得含 PHP 插件。 -- `./scripts/plugins/verify-official-plugins.sh`:独立包兼容性与签名验证。 +- 官方插件包的组装与校验(原 verify-official-plugins 脚本:独立包兼容性与签名验证。)已随插件移出本仓库,由各插件仓库的 CI 负责(#1495)。 - `MacPluginPackageDownloaderTests`:验证 stable/preview 发行资产 URL 按 App 发布版本和架构确定性生成。 - `LanguageExtensionProcessLifecycleTests.packagedServersArePinnedToTheirOwnPackage`、`LanguageServerToolServiceTests.pinnedExecutableIsTheOnlyCandidate`:验证插件打包的 Intelephense 只从本插件已安装的版本目录启动,不按文件名在 PATH 或其他插件中查找。 - `PluginPackageStoreTests/reinstallCanReplaceTheActiveVersionOnlyAfterValidation`:验证重装不会绕过签名校验,并在校验完成后替换当前版本。 @@ -86,7 +88,7 @@ Windows 休眠的 Run Actions 宿主不再扫描其他语言的 manifest 或自 - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginPackageStore.swift` - `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift` - `Plugins/win/Official/PhpSupport/` -- `scripts/plugins/build-official-plugins.sh` +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `scripts/macos/package/package-app.sh` - `windows/tauri/src/extensions/` - `windows/tauri/src/features/run-actions/` diff --git a/.agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md b/.agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md index 528d4b19c0..24e4241677 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md +++ b/.agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 “哪个 Java 类能运行”“哪个方法是测试”由 JDT(Eclipse 的 Java 语言服务, @@ -252,7 +254,7 @@ JDT 尚未完成发现时,已有确认入口可沿用上次生成结果;没 精确运行这两个非传统命名测试并检查执行标记。 - 真实 JDT 测试 `real_jdtls_lists_entrypoints_and_classpaths_behind_a_symbolic_link` 通过符号链接打开工作区,要求仍然列出入口;去掉作用域解析后它会得到空列表。 -- `scripts/architecture/verify-java-semantic-ownership.mjs` 阻止已删除的本地入口/测试扫描标识符 +- `scripts/architecture/verify-no-host-language-specifics.mjs` 阻止已删除的本地入口/测试扫描标识符 回到 Rust、macOS 或 Windows 产品源码。 - Windows 和 macOS 打包同一份上游 `contributes.javaExtensions` bundle 列表; Windows CI 的独立真实 JDT 任务只在 Java/JDT 相关路径变化时运行。 @@ -291,11 +293,11 @@ JDT 尚未完成发现时,已有确认入口可沿用上次生成结果;没 ## 适用范围 -- `rust/lithe-core/src/languages/` +- 已迁出:原 `rust/lithe-core/src/languages/`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `rust/lithe-core/src/lsp/languages/` - `rust/lithe-core/src/execution/configuration.rs` - `third_party/jdtls/manifest.json` -- `scripts/macos/prepare/prepare-jdtls.sh` +- 已迁出:原 `scripts/macos/prepare/prepare-jdtls.sh`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `scripts/windows/prepare/prepare-jdtls.ps1` - `windows/tauri/src/features/run/` - `windows/tauri/src/platform/lsp-core-adapter.ts` diff --git a/.agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md b/.agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md index fc53429074..3272bc5aad 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md +++ b/.agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`;Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495);宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Issue #790 要求像 IDEA 一样在 Java 编辑器行号旁显示运行按钮:`main` 方法旁一个 ▶, @@ -145,12 +147,12 @@ intellij-community 的 `runConfigurations/testState` 图标(Apache 2.0)。 ## 适用范围 -- `rust/lithe-core/src/lsp/languages/java_main_methods.rs` -- `rust/lithe-core/src/lsp/languages/java_run_markers.rs` -- `rust/lithe-core/src/project/maven_test_reports.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/languages/java_main_methods.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 +- 已迁出:原 `rust/lithe-core/src/lsp/languages/java_run_markers.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 +- 已迁出:原 `rust/lithe-core/src/project/maven_test_reports.rs`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 - `windows/tauri/src/features/run/services/java-run-markers.ts` - `windows/tauri/src/features/editor/engines/monaco/java-run-markers.ts` - `frontend/editor/src/run-markers.ts` -- `macos/Sources/Lithe/Models/AppModel/AppModel+JavaRunMarkers.swift` +- 已迁出:原 `macos/Sources/Lithe/Models/AppModel/AppModel+JavaRunMarkers.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift` - `shared/fixtures/build-provider/test-results-v1.json` diff --git a/.agents/notes/implemented/architecture/2026-09-26-maven-dependency-tree-output-file.md b/.agents/notes/implemented/architecture/2026-09-26-maven-dependency-tree-output-file.md index 35ecc88eb6..6c52f59f71 100644 --- a/.agents/notes/implemented/architecture/2026-09-26-maven-dependency-tree-output-file.md +++ b/.agents/notes/implemented/architecture/2026-09-26-maven-dependency-tree-output-file.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Windows 现存 Maven 依赖树继续通过独立输出文件读取,避免控制台日志挤掉合法依赖数据。 @@ -141,8 +143,8 @@ m2e 内嵌的 Maven,而不是用户配置的 Maven 或 mvnd,违反“依赖 ## 适用范围 -- `rust/lithe-core/src/project/maven_dependency_tree.rs` -- `rust/lithe-core/src/project/maven.rs` +- 已迁出:原 `rust/lithe-core/src/project/maven_dependency_tree.rs`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 +- 已迁出:原 `rust/lithe-core/src/project/maven.rs`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 - `shared/contracts/rust-core-api.md` - `shared/fixtures/maven/dependency-tree-v2.json` - `windows/tauri/src-tauri/src/maven.rs` diff --git a/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md b/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md index da0b0add22..dc20b71c2c 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md +++ b/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 以后新增或修改带语言服务器(Language Server,负责通过 LSP 提供补全、诊断和跳转能力的进程)的官方插件,都必须沿用这里的构建方式(最早由 PHP Support 验证):插件声明固定版本和校验值,构建阶段下载、校验并把语言服务器放入插件包,插件包完成签名后再分发。主程序不再为插件维护第二套语言服务器路径,也不在运行时改写已安装的 app bundle。 @@ -83,7 +85,7 @@ macOS 使用声明式插件包和 publisher Ed25519 包签名;Windows 使用 ## 验证 -- `./scripts/plugins/verify-official-plugins.sh`:检查官方插件组装、语言服务器清单、启动器、包内无原生代码和包签名。 +- 官方插件包的组装与校验(原 verify-official-plugins 脚本:检查官方插件组装、语言服务器清单、启动器、包内无原生代码和包签名。)已随插件移出本仓库,由各插件仓库的 CI 负责(#1495)。 - `./scripts/macos/verify/verify-runtime-bundle-immutability.sh`:确认典型启动和插件工作流不会改写已安装 bundle。 - `node scripts/resources/test-reuse-worktree-resources.mjs`:确认语言服务器下载和插件包不能跨工作树复用。 - `./scripts/agent-notes/verify-agent-notes.sh`:确认本笔记格式、路径和验证命令有效。 @@ -92,8 +94,8 @@ macOS 使用声明式插件包和 publisher Ed25519 包签名;Windows 使用 ## 适用范围 -- `Plugins/mac/Official/` -- `scripts/plugins/build-official-plugins.sh` +- 已迁出:原 `Plugins/mac/Official/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `macos/Sources/Lithe/Platform/MacOS/Plugins/` - `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift` - `macos/Sources/LitheLanguageIntelligenceModule/` diff --git a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md index 2b7faccea6..c7be3f199a 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 官方语言插件(Go、PHP)不再是"在 Lithe 进程里加载的 Swift Bundle",而是声明式插件包:包里只有 `plugin.json` 和它声明的资源(例如打包好的 Intelephense)。Lithe 读取声明,由 Rust Core 校验并展开运行/测试命令,再由宿主自己启动语言服务器和运行进程。插件不在宿主进程内执行任何代码,所以插件包不再依赖宿主二进制,Lithe 每次发版也不用重新编译插件,之后可以把插件拆到独立仓库维护。Go 和 PHP 后来确实拆成了 Lithe Store 社区插件,见 [Go 与 PHP 改为 Lithe Store 社区插件](2026-10-20-go-php-community-plugins.md)。 @@ -98,7 +100,7 @@ gopls 把 `fmt.Println` 的定义指向 `GOROOT/src/fmt/print.go`,Intelephense - `cargo test --manifest-path rust/lithe-core/Cargo.toml --lib declarative_plugins`:合法样例、非法样例错误码、命令展开标准答案,以及仓库里的官方 `plugin.json`。 - `./scripts/architecture/verify-shared-contracts.sh`:契约目录自洽(schema、fixture 引用、错误码均已在 README 中登记)。 -- `./scripts/plugins/verify-official-plugins.sh`:组装官方包并用 `LitheOfficialPluginVerifier` 检查信任策略、打包入口和"包内无 Mach-O"。 +- 官方插件包的组装与校验(原 verify-official-plugins 脚本:组装官方包并用 `LitheOfficialPluginVerifier` 检查信任策略、打包入口和"包内无 Mach-O"。)已随插件移出本仓库,由各插件仓库的 CI 负责(#1495)。 - `./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'Plugin|LanguageExtensionProcessLifecycleTests|LanguageServerToolServiceTests|LanguageNavigationCoordinatorTests|ExternalNavigationTests'`:包校验、旧包过渡、签名、启停与进程清理、打包入口固定、跨工作区跳转边界。 - `LITHE_RUN_PHP_INTEGRATION=1 ./scripts/macos/test/test-macos.sh --filter RealPhpIntegrationTests`:真实 Intelephense 与 PHPUnit。 - `node scripts/resources/test-reuse-worktree-resources.mjs`:磁盘快照、安装状态和审批记录禁止跨工作树复制。 @@ -116,5 +118,5 @@ gopls 把 `fmt.Println` 的定义指向 `GOROOT/src/fmt/print.go`,Intelephense - `macos/Sources/Lithe/Application/Features/DocumentFeatureModel.swift` - `macos/Sources/LitheExecutionModule/Modules/BundledLanguageExecutionModule.swift` - `macos/Sources/LitheLanguageIntelligenceModule/Modules/BundledLanguageServerModule.swift` -- `Plugins/mac/Official/` -- `scripts/plugins/build-official-plugins.sh` +- 已迁出:原 `Plugins/mac/Official/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md b/.agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md index ea2c4b1fbf..0962dc226a 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md +++ b/.agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护;宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Java 的语言服务器 JDT LS(Eclipse 的 Java 语言服务器,提供补全、诊断和跳转)不再是 Lithe.app 里写死的一部分,而是官方插件 Java Support(`dev.lithe.plugin.java-support`)。插件包拥有 JDT LS、Lombok、调试和测试扩展,以及它运行所用的 JDK;`plugin.json` 声明这些文件在包内的位置和启动方式。过渡期随应用发行、默认启用,用户可以卸载和恢复;完整双架构官方下载上架后默认应用省去资源,迁移与安装引导由[后续分发决策](2026-10-25-java-plugin-distribution-foundation.md)规定。 @@ -203,7 +205,7 @@ dev.lithe.plugin.java-support/ ## 验证 - `cargo test --manifest-path rust/lithe-core/Cargo.toml --lib plugins`:API 2 的合法与非法清单、启动计划标准答案、运行时版本判定,以及仓库里的官方 `plugin.json`。 -- `./scripts/plugins/verify-official-plugins.sh`:组装三个官方包并校验入口、自带运行时、符号链接和原生代码的位置。 +- 官方插件包的组装与校验(原 verify-official-plugins 脚本:组装三个官方包并校验入口、自带运行时、符号链接和原生代码的位置。)已随插件移出本仓库,由各插件仓库的 CI 负责(#1495)。 - `./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'Plugin|LanguageExtensionProcessLifecycleTests|LanguageServerToolServiceTests|JavaLanguageServerRuntimeTests|MacJdtWorkspaceStateTests|MacJdtHostIntegrationStateTests|LanguageToolEnvironmentTests'`:按声明定位资源、路径固定在包内、版本过滤、默认启用、移除与恢复;卸载后 JDT 的索引和 Equinox 配置区被删除(扫描失败或插件被拒绝时保留);运行时启动的服务器 `PATH` 上先找到宿主选中的运行时。 - `LITHE_RUN_JAVA_DEBUG_INTEGRATION=1 ./scripts/macos/test/test-macos.sh --filter RealJavaDebugIntegrationTests`:从组装好的插件包启动真实的 JDT LS 并完成 Spring Boot 断点调试。迁移初版时它因 `java.project.getClasspaths` 在服务端抛空指针而失败(迁移前的代码同样失败),该问题已随入口发现的修复一并解决,见 [Java 入口由 JDT 判定](2026-09-21-java-entrypoints-owned-by-jdt.md)。这组测试直接组装调试会话,不验证应用里的能力目录。 - `./scripts/macos/test/test-macos.sh --filter '(LanguageProviderCatalogSourceTests|RunWorkflowCoordinatorTests|RunConfigurationIntegrationTests)'`:用仓库里的官方 Java 清单验证能力目录保留运行、测试、调试;未声明的插件得不到任何宿主能力;注册表只为声明的能力创建内置工具;声明了 `run` 的语言不要求执行模块。 @@ -216,18 +218,18 @@ dev.lithe.plugin.java-support/ - `shared/contracts/plugins/v1/` - `rust/lithe-core/src/plugins/declarative.rs` -- `Plugins/mac/Official/JavaSupport/` -- `scripts/plugins/build-official-plugins.sh` +- 已迁出:原 `Plugins/mac/Official/JavaSupport/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `scripts/macos/package/package-app.sh` - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift` -- `macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/` +- 已迁出:原 `macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/Lithe/Core/Language/PluginLanguageProviderCatalogSource.swift` - `macos/Sources/Lithe/Services/Language/LanguagePackRegistry.swift` - `macos/Sources/Lithe/Application/Features/RunWorkflowCoordinator.swift` - `macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift` -- `macos/Sources/LitheCoreContracts/Language/LanguageServerHostIntegrationContracts.swift` +- 已迁出:原 `macos/Sources/LitheCoreContracts/Language/LanguageServerHostIntegrationContracts.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginPackageStore.swift` - `macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift` -- `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift` +- 已迁出:原 `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageServerToolService.swift` - `macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift` diff --git a/.agents/notes/implemented/architecture/2026-10-20-go-php-community-plugins.md b/.agents/notes/implemented/architecture/2026-10-20-go-php-community-plugins.md index 2beadb1758..641ad4d02c 100644 --- a/.agents/notes/implemented/architecture/2026-10-20-go-php-community-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-20-go-php-community-plugins.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 macOS 的 Go Support 和 PHP Support 不再是 Lithe 官方插件。它们搬到各自的社区仓库(`Lithe-IDEA/lithe-plugin-go`、`Lithe-IDEA/lithe-plugin-php`),用新 ID `io.github.lithe-idea.go-support` 和 `io.github.lithe-idea.php-support` 发布,并列在 Lithe Store 社区源里,版本从 0.1.0 开始。主仓库不再构建或发布这两个包,官方索引目前是空的。 @@ -101,5 +103,5 @@ Go/PHP 插件可以独立迭代和发布,不占用主仓库 CI,也不需要 - `macos/Tests/LitheTests/Fixtures/RetiredOfficialPlugins/` - `Plugins/mac/README.md` - `Plugins/marketplace/` -- `scripts/plugins/official-plugin-releases.mjs` -- `scripts/plugins/build-official-plugins.sh` +- 已迁出:原 `scripts/plugins/official-plugin-releases.mjs`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 diff --git a/.agents/notes/implemented/architecture/2026-10-25-java-plugin-distribution-foundation.md b/.agents/notes/implemented/architecture/2026-10-25-java-plugin-distribution-foundation.md index 8b0fe92c26..1b3d062b0e 100644 --- a/.agents/notes/implemented/architecture/2026-10-25-java-plugin-distribution-foundation.md +++ b/.agents/notes/implemented/architecture/2026-10-25-java-plugin-distribution-foundation.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Java Support 的同一份清单现在区分两种来源:随应用发行的副本可以依靠宿主签名,用户下载安装的副本必须有 Lithe 发布者签名。两种来源使用同一插件 ID,经过校验的用户安装版本替代内置版本,不重复登记 Java 语言服务。官方发布工具能记录 ARM64、Intel 两个归档及各自哈希,并从发布标签读取对应 API 和能力声明;迁移保留启用选择并提供按需安装入口;主包只在完整双架构官方下载进入索引后移除资源。自动上架仍暂停,真实发布包按[独立分发提案](../../proposed/architecture/2026-10-24-java-support-independent-distribution.md)继续验收。 @@ -101,24 +103,24 @@ JDT LS、JDK、Lombok、Debug 和 Test 扩展保持当前锁定版本。资源 - `node --test scripts/plugins/official-plugin-releases.test.mjs`:双架构索引、部分归档拒绝、历史标签元数据以及上游输入变更约束。 - `node scripts/resources/test-reuse-worktree-resources.mjs`、`./scripts/macos/verify/verify-runtime-bundle-immutability.sh`:生成资源拒绝复用、发行目录只读边界。 - `./.agents/skills/write-stable-tests/scripts/verify-test-stability.sh` 和 macOS 计时入口:相关测试必须有单项时长与 HTML/JUnit 结果。 -- `.github/workflows/release-official-plugins.yml` 用 actionlint 校验;本地组装两种架构资源,验证 JDK 原生签名和发布归档的完整性。 +- 已迁出:原 `.github/workflows/release-official-plugins.yml`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 上述验证不能替代正式发布者私钥签名、真实市场下载、Intel 真机及全部 Java 产品工作流。上线前继续按独立分发提案的退出条件执行,不能靠测试公钥通过就开放发布。 ## 适用范围 -- `Plugins/mac/Official/JavaSupport/` -- `Plugins/marketplace/official-plugins.json` +- 已迁出:原 `Plugins/mac/Official/JavaSupport/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `Plugins/marketplace/official-plugins.json`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `shared/contracts/plugins/v1/` - `rust/lithe-core/src/plugins/` - `macos/Sources/LitheModuleAPI/` - `macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift` - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginPackageStore.swift` -- `macos/Tests/LitheTests/PluginBundledPublisherTrustTests.swift` +- 已迁出:原 `macos/Tests/LitheTests/PluginBundledPublisherTrustTests.swift`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `macos/Tests/LitheOfficialPluginVerifier/OfficialPluginVerifier.swift` -- `scripts/plugins/build-official-plugins.sh` -- `scripts/plugins/official-plugin-releases.mjs` -- `.github/workflows/release-official-plugins.yml` +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/official-plugin-releases.mjs`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `.github/workflows/release-official-plugins.yml`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `scripts/resources/worktree-resources.json` - `scripts/resources/reuse-worktree-resources.mjs` - `docs/ci-builds.md` diff --git a/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md b/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md index 266eea2c89..1728163dad 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md +++ b/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 以前 Lithe 识别出项目能运行的入口后,会把结果写进用户工程的 @@ -204,4 +206,4 @@ v1 文档在发布时整体转换字段形状,无关 Java 条目保留原身 - `windows/tauri/src/features/run/` - `macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunConfigurationStore.swift` - `macos/Sources/LitheExecutionModule/Services/RunService.swift` -- `macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenRunConfigurationMigration.swift` +- 已迁出:原 `macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenRunConfigurationMigration.swift`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 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 index af6e124a8a..6c21d31a01 100644 --- 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 @@ -100,7 +100,7 @@ - `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/architecture/verify-shared-contracts.sh`、`scripts/architecture/verify-service-boundaries.sh`、`scripts/architecture/verify-no-host-language-specifics.mjs`。 - `scripts/agent-notes/verify-agent-notes.sh`、`scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`。 原生验收(安装示例插件、观察状态栏文字、用 `pgrep` 确认进程不残留)不由单元测试替代,功能矩阵按真实证据维护。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-22-run-panel-fingerprint-loading.md b/.agents/notes/implemented/bug-fix/2026-09-22-run-panel-fingerprint-loading.md index f5a9642671..4fc791c41f 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-22-run-panel-fingerprint-loading.md +++ b/.agents/notes/implemented/bug-fix/2026-09-22-run-panel-fingerprint-loading.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Windows 运行面板先读取并解析配置文档,展示已有配置后再检查项目文件是否变化。 @@ -141,4 +143,4 @@ JDT 就绪后才出现,JDT 不可用时这一项没有提示(其他输入照 - `rust/lithe-core/src/execution/configuration.rs` - `shared/contracts/run-configuration-v2.schema.json` - `macos/Sources/LitheExecutionModule/Services/RunService.swift` -- `macos/Sources/Lithe/Models/AppModel/AppModel+JavaEntrypoints.swift` +- 已迁出:原 `macos/Sources/Lithe/Models/AppModel/AppModel+JavaEntrypoints.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-24-jdtls-project-metadata-outside-workspace.md b/.agents/notes/implemented/bug-fix/2026-09-24-jdtls-project-metadata-outside-workspace.md index 62d76ce4c8..8ffa4ad6ec 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-24-jdtls-project-metadata-outside-workspace.md +++ b/.agents/notes/implemented/bug-fix/2026-09-24-jdtls-project-metadata-outside-workspace.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 打开 Maven/Gradle 项目后,Java 语言服务 JDT LS 以前会在每个模块根目录写入 @@ -105,8 +107,8 @@ JDT LS 自带一个文件系统插件 `org.eclipse.jdt.ls.filesystem`。它根 ## 适用范围 -- `rust/lithe-core/src/lsp/languages/jdt.rs` -- `rust/lithe-core/src/lsp/languages/jdt_project_metadata.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt_project_metadata.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `rust/lithe-core/src/lsp/interface/engine.rs` - `rust/lithe-core/src/git/mod.rs` - `shared/contracts/rust-core-api.md` diff --git a/.agents/notes/implemented/bug-fix/2026-09-25-runtime-bundle-immutability-and-update-delta.md b/.agents/notes/implemented/bug-fix/2026-09-25-runtime-bundle-immutability-and-update-delta.md index 956ed55a43..6852df7b3d 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-25-runtime-bundle-immutability-and-update-delta.md +++ b/.agents/notes/implemented/bug-fix/2026-09-25-runtime-bundle-immutability-and-update-delta.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Sparkle 增量更新(differential update,只下载两个版本之间差异的更新包)依赖上一版 @@ -115,9 +117,9 @@ Equinox(JDT LS 使用的 OSGi 框架,负责加载插件)会往 `-configura ## 适用范围 -- `rust/lithe-core/src/lsp/languages/jdt_configuration.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt_configuration.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `rust/lithe-core/src/lsp/interface/engine.rs` -- `rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `shared/contracts/rust-core-api.md` - `scripts/macos/verify/verify-runtime-bundle-immutability.sh` - `scripts/macos/verify/verify-macos-app-build-safety.sh` diff --git a/.agents/notes/implemented/bug-fix/2026-10-09-jdtls-heap-ceiling-and-duplicate-maven-coordinates.md b/.agents/notes/implemented/bug-fix/2026-10-09-jdtls-heap-ceiling-and-duplicate-maven-coordinates.md index 149f90777d..360cfcb80f 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-09-jdtls-heap-ceiling-and-duplicate-maven-coordinates.md +++ b/.agents/notes/implemented/bug-fix/2026-10-09-jdtls-heap-ceiling-and-duplicate-maven-coordinates.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Lithe 在两条启动路径上都用 `-Xmx1024m` 启动内置 Java 语言服务 JDT LS。JDT LS 发现 @@ -119,6 +121,6 @@ Lithe 在两条启动路径上都用 `-Xmx1024m` 启动内置 Java 语言服务 ## 适用范围 -- `rust/lithe-core/src/lsp/languages/jdt.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `rust/lithe-core/src/lsp/interface/engine.rs` - `third_party/jdtls/manifest.json` diff --git a/.agents/notes/implemented/bug-fix/2026-10-14-java-debug-uses-the-run-jdk.md b/.agents/notes/implemented/bug-fix/2026-10-14-java-debug-uses-the-run-jdk.md index 378da9518a..e6d7b74d0c 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-14-java-debug-uses-the-run-jdk.md +++ b/.agents/notes/implemented/bug-fix/2026-10-14-java-debug-uses-the-run-jdk.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 macOS 上 Java 调试启动的 JVM 现在就是“运行”会用的那个 JDK。调试不保存自己的 JDK 配置:它只说明“我要调试的是哪类目标”,再向运行所用的同一条选择链取 `java` 路径,写进调试启动参数 `javaExec`。所以改运行配置的 JDK、项目 JDK 或 `JAVA_HOME`,调试自动跟着变。 @@ -51,7 +53,7 @@ macOS 上 Java 调试启动的 JVM 现在就是“运行”会用的那个 JDK ## 适用范围 - `macos/Sources/Lithe/Services/Debug/DebugLaunchConfigurationResolver.swift` -- `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift` +- 已迁出:原 `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift` - `macos/Tests/LitheTests/RunConfigurationIntegrationTests.swift` - `shared/platform-feature-matrix/features/debug-java-runtime.json` diff --git a/.agents/notes/implemented/bug-fix/2026-10-19-spring-index-concurrency-boundaries.md b/.agents/notes/implemented/bug-fix/2026-10-19-spring-index-concurrency-boundaries.md index 26d3116650..e9a6431ea8 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-19-spring-index-concurrency-boundaries.md +++ b/.agents/notes/implemented/bug-fix/2026-10-19-spring-index-concurrency-boundaries.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 持续编辑大项目时,Windows 端以前会为每一次编辑派发一份完整的 Spring 全量索引。 @@ -133,7 +135,7 @@ ## 适用范围 -- `rust/lithe-core/src/languages/spring.rs` +- 已迁出:原 `rust/lithe-core/src/languages/spring.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `windows/tauri/src/features/spring/hooks/use-spring-index.ts` - `windows/tauri/src/features/spring/hooks/use-spring-index.test.tsx` - `windows/tauri/src/features/spring/api/spring-index-api.ts` diff --git a/.agents/notes/implemented/bug-fix/2026-10-25-run-launch-path-for-node-launchers.md b/.agents/notes/implemented/bug-fix/2026-10-25-run-launch-path-for-node-launchers.md index b20e25812d..98b077fb4c 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-25-run-launch-path-for-node-launchers.md +++ b/.agents/notes/implemented/bug-fix/2026-10-25-run-launch-path-for-node-launchers.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 从 Finder / Dock 启动的 Lithe 继承 launchd 的最小环境,`PATH` 只有 @@ -121,7 +123,7 @@ pnpm 在 /opt/homebrew/bin,node 在 fnm 的默认别名目录 ## 适用范围 -- `macos/Sources/Lithe/Services/Java/RunLaunchEnvironment.swift` -- `macos/Sources/Lithe/Services/Java/RunExecutableResolver.swift` +- 已迁出:原 `macos/Sources/Lithe/Services/Java/RunLaunchEnvironment.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 +- 已迁出:原 `macos/Sources/Lithe/Services/Java/RunExecutableResolver.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Tests/LitheTests/RunLaunchEnvironmentTests.swift` - 对照实现:`windows/tauri/src-tauri/src/run.rs` 中的 `append_runtime_paths` diff --git a/.agents/notes/implemented/bug-fix/2026-10-30-login-shell-environment-and-jdk-selection.md b/.agents/notes/implemented/bug-fix/2026-10-30-login-shell-environment-and-jdk-selection.md index 77e2ba35d0..7d1f2eaed0 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-30-login-shell-environment-and-jdk-selection.md +++ b/.agents/notes/implemented/bug-fix/2026-10-30-login-shell-environment-and-jdk-selection.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`;宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 很多“项目跑不起来”的 Issue 来自两个共同原因。第一,从 Finder / Dock 启动的 @@ -137,8 +139,8 @@ Maven 安装目录。做法参考 OpenIDEA(Apache-2.0),出处写在仓库 ## 适用范围 - `macos/Sources/Lithe/Platform/MacOS/Runtime/MacLoginShellEnvironment.swift` -- `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift` +- 已迁出:原 `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/Lithe/Platform/MacOS/MacApplicationEntryPoint.swift` -- `rust/lithe-core/src/execution/java_selection.rs` +- 已迁出:原 `rust/lithe-core/src/execution/java_selection.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `windows/tauri/src-tauri/src/run.rs` - `NOTICE` diff --git a/.agents/notes/implemented/feature/2026-10-11-gradle-project-import-settings.md b/.agents/notes/implemented/feature/2026-10-11-gradle-project-import-settings.md index 1d3ab11a9f..b36aeb1c72 100644 --- a/.agents/notes/implemented/feature/2026-10-11-gradle-project-import-settings.md +++ b/.agents/notes/implemented/feature/2026-10-11-gradle-project-import-settings.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Lithe 打包的 JDT LS 已内置 Buildship,因此 Gradle 工程本就能被导入、索引与补全。本次改动不改这条链路,只把原本依赖 Buildship 默认值的 Gradle 导入显式化:平台侧探测工作区根是否声明 Gradle、是否带 wrapper 描述文件,Rust Core 据此在 `settings.java` 下发 `java.import.gradle`,并把 Gradle 工程的结构文件和 wrapper 的 Gradle 版本纳入工作区指纹。下发的两个开关与上游默认值相同,对今天的导入结果是空操作,它固定的是 Lithe 依赖的行为前提,并让 Gradle 与 Maven 走同一套「平台探测 → Core 组装 → JDT LS」结构。 @@ -58,7 +60,7 @@ Gradle 与 Maven 在导入设置上结构对称,行为可预期、可扩展。 ## 适用范围 -- `rust/lithe-core/src/lsp/languages/jdt.rs` +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `rust/lithe-core/src/lsp/interface/engine.rs` - `windows/tauri/src-tauri/src/lsp.rs` - `windows/tauri/src-tauri/src/lsp/jdt_workspace.rs` diff --git a/.agents/notes/implemented/feature/2026-10-12-plugin-marketplace.md b/.agents/notes/implemented/feature/2026-10-12-plugin-marketplace.md index 250cd0542f..57f939cdac 100644 --- a/.agents/notes/implemented/feature/2026-10-12-plugin-marketplace.md +++ b/.agents/notes/implemented/feature/2026-10-12-plugin-marketplace.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Lithe 的插件管理改成和 IntelliJ IDEA 一样的“插件市场 / 已安装”两个标签。插件从“插件仓库源”(一个 JSON 索引文件)里列出:默认源是主仓库的 `Plugins/marketplace/index.json`;另外预置一个社区源 Lithe Store(`Lithe-IDEA/Lithe-store` 仓库,默认开启、可删除);用户还能添加第三方源(HTTPS 索引地址,或 GitHub 仓库地址,自动指向仓库根目录的 `lithe-plugin-index.json`)。 @@ -119,8 +121,8 @@ Lithe 的插件管理改成和 IntelliJ IDEA 一样的“插件市场 / 已安 - `shared/contracts/plugins/v1/` - `rust/lithe-core/src/plugins/marketplace.rs` - `Plugins/marketplace/` -- `scripts/plugins/official-plugin-releases.mjs` -- `.github/workflows/release-official-plugins.yml` +- 已迁出:原 `scripts/plugins/official-plugin-releases.mjs`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `.github/workflows/release-official-plugins.yml`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `macos/Sources/LitheCoreContracts/Plugins/PluginMarketplaceContracts.swift` - `macos/Sources/Lithe/Application/Features/PluginMarketplace.swift` - `macos/Sources/Lithe/Platform/MacOS/Plugins/` diff --git a/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md b/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md index 4412e8002f..89bff7cec3 100644 --- a/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md +++ b/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护;Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 声明式插件的 settings v1 可以在 `plugin.json` 里声明“用户可调的选项”,比如早期 Java Support 使用的 JDT LS 最大堆内存和日志级别。这个 Note 只保留 v1 的兼容规则;当前的页面注册、项目/全局分层、文本/路径类型和即时生效方式见 `.agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md`。 @@ -82,9 +84,9 @@ cargo test --manifest-path rust/lithe-core/Cargo.toml jdt ## 适用范围 - `rust/lithe-core/src/plugins/declarative.rs`:声明校验、`effective_settings`、模板代入。 -- `rust/lithe-core/src/lsp/languages/jdt.rs`:`-Xmx`、`-Dlog.level=` 的插件优先规则。 +- 已迁出:原 `rust/lithe-core/src/lsp/languages/jdt.rs`。Java/JDT LS/Spring 专属逻辑已从 Core 移入 Java 插件后端([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) 的 `backend/`),Core 只保留通用能力(#1495);Windows 过渡期副本在 `windows/tauri/crates/lithe-legacy-tooling/`。 - `macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift`:`DeclarativePluginSetting`、`PluginSettingsStoring`。 - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginSettingsStore.swift`:保存。 - `macos/Sources/Lithe/Views/App/PluginSettingsSection.swift`:插件页上的控件。 -- `Plugins/mac/Official/JavaSupport/plugin.json`:首批选项 `heapMaxMB`、`logLevel`。 +- 已迁出:原 `Plugins/mac/Official/JavaSupport/plugin.json`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `shared/contracts/plugins/v1/README.md`:对外契约。 diff --git a/.agents/notes/implemented/feature/2026-10-14-local-jvm-performance-monitoring.md b/.agents/notes/implemented/feature/2026-10-14-local-jvm-performance-monitoring.md index 9c44d0e492..73f95781cc 100644 --- a/.agents/notes/implemented/feature/2026-10-14-local-jvm-performance-monitoring.md +++ b/.agents/notes/implemented/feature/2026-10-14-local-jvm-performance-monitoring.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-07 更新:本文提到的部分文件已不存在。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Performance 展示 Lithe 启动的目标 Java 进程的真实 CPU 和 JVM 堆数据。 @@ -143,7 +145,7 @@ Windows 当前没有对应 UI/采集实现,矩阵明确标记缺失。完整 - `macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPerformanceSampler.swift` - `macos/Sources/Lithe/Views/Debug/DebugPerformancePane.swift` - `macos/Tests/LitheTests/DebugPerformanceSamplingTests.swift` -- `macos/Tests/LitheTests/JVMPerformanceIntegrationTests.swift` +- 已迁出:原 `macos/Tests/LitheTests/JVMPerformanceIntegrationTests.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 审核回归增加非 Maven 成功/失败/取消、停止失败后重试、隐藏期间报告成功/失败与录制 启动失败。Gradle 真实集成测试显式设置 LITHE_TEST_GRADLE_EXECUTABLE、 diff --git a/.agents/notes/implemented/feature/2026-10-17-settings-info-tips.md b/.agents/notes/implemented/feature/2026-10-17-settings-info-tips.md index 10945d396a..5fb05d5ec0 100644 --- a/.agents/notes/implemented/feature/2026-10-17-settings-info-tips.md +++ b/.agents/notes/implemented/feature/2026-10-17-settings-info-tips.md @@ -24,7 +24,7 @@ Issue #1316 的截图里,通用、Git 和 Agent 管理页在几乎每个控件 - 用户可修改的配置处于自动、默认或继承状态时,不得只显示“自动”“默认”“继承”,必须在括号中写出实际生效值,例如 `自动(JDK 21)`、`继承(main)`、`Automatic (JDK 21)`;没有生效值时写明原因,例如 `自动(未找到)`、`自动(检测中)`。原因是只写“自动”时,用户看不出最终用的是哪个值,出问题时也无法判断是否需要手动指定。括号中的值必须来自 Core 返回的、运行时实际使用的同一个解析结果,界面不另写推测逻辑;文案使用带参数的词条(`自动({value})`),不拼接字符串。规则正文在 `develop-lithe` Skill 第五节“显示实际生效值,不只写‘自动’”。 - 编辑器字体页提供实时预览:示例代码使用当前选中字体和字号渲染;切换字体后旧字体保留约 2.5 秒,和新字体上下并列,随后淡出,方便比较字形。`accessibilityReduceMotion` 开启时取消动画。 - Git 行为配置行用 `ViewThatFits` 优先排成一行:设置名、当前生效值、下拉框、重置和应用按钮并排;`LitheSettingsSelect` 的触发宽度按该字段最长选项文案在 150–240 pt 内取值,避免短选项占着 220 pt 的空白框,长选项仍由 `expandsToFitOptions` 撑开弹层。窗口过窄时回退到第二行显示当前生效值,按钮保持完整。 -- 运行时的生效值不再用一整行等宽文本:`EffectiveRuntimeLabel` 用卡片展示模式徽标、来源、运行时名称和可选择复制的路径,警告与错误使用同一卡片形状和警示色。 +- 运行时的生效值不再用一整行等宽文本,而是用卡片展示模式徽标、来源、运行时名称和可选择复制的路径,警告与错误使用同一卡片形状和警示色。该卡片最初由内置 Java Support 的 `EffectiveRuntimeLabel` 实现;2026-11 内置 Java Support 随 #1495 移出本仓库后,运行时与工具由插件注入的工具定义驻留在 `ContributedSettingsPageView` 渲染的插件设置页里,规则不变。 - Git 标签继承回显只消费 Core 的规范化布尔值:Core 用 Git 自己的 `--type=bool --get` 解释 `fetch.pruneTags` 与远程覆盖,识别 `yes/on/1`、无值和假值等写法;远程显式假值仍优先于全局真值。选中文件的原始编辑值不变,避免保存时因规范化导致误报冲突。所有远程模式下 Fetch 会跳过 `remote..skipFetchAll` 为真的远程,标签回显也必须排除它们;Core 同样用 Git 布尔解析归一化该键,显式选中某个远程时不受 skipFetchAll 影响。不要在 Swift 再写一份布尔解析器,否则界面会与真实 fetch 行为漂移。 - Git 身份输入框回显当前生效值(包括继承值),保存按钮只在草稿与显示值不同时启用;清除覆盖后输入框回到继承的生效值。这样用户看到的就是 Git 实际会使用的值,不需要从下方的小字里对照。 - Maven 的 `settings.xml` 与 `Local Repository` 既有输入框在未设置覆盖时,用有效路径作为占位文本:先看已配置值,再看 `~/.m2/settings.xml`、Maven 安装的 `conf/settings.xml` 和 `~/.m2/repository`;都不存在时显示“Not found”,不再显示无信息量的“Automatic”。这只是当时实现的占位提示,不是后续设置交互的目标:新增或修改这类配置编辑时,按 [设置读取真实来源并确认写回](../architecture/2026-10-25-settings-native-configuration-editing.md) 回显可编辑当前值、确认写回并重新读取;本次规则更新不代表 Maven 页面已迁移。 @@ -99,12 +99,12 @@ Issue 举的是通用、Git 和 Agent 管理三个页面,但同类常驻说明 - `macos/Sources/Lithe/Views/App/GitExecutionSettingsView.swift` - `macos/Sources/Lithe/Views/App/GitFetchSettingsView.swift` - `macos/Sources/Lithe/Views/App/PluginSettingsSection.swift` -- `macos/Sources/Lithe/Views/App/EffectiveRuntimeLabel.swift` +- `macos/Sources/Lithe/Views/App/ContributedSettingsPageView.swift` - `macos/Sources/Lithe/Views/App/McpSettingsView.swift` - `macos/Sources/Lithe/Application/Features/AgentSetupDiagnostics.swift` - `macos/Sources/LitheGitModule/Application/GitRepositorySetupFeatureModel.swift` - `macos/Sources/Lithe/Views/Agent/AgentPanelSettingsView.swift` - `macos/Sources/Lithe/Views/Agent/AgentProviderConfigurationView.swift` -- `macos/Sources/Lithe/Views/Run/JavaRunConfigurationEditorView.swift` +- `macos/Sources/Lithe/Views/Run/RunConfigurationEditorView.swift` - `macos/Resources/en.lproj/Localizable.strings` - `macos/Resources/zh-Hans.lproj/Localizable.strings` diff --git a/.agents/notes/implemented/feature/2026-10-23-plugin-project-generators.md b/.agents/notes/implemented/feature/2026-10-23-plugin-project-generators.md index 0575ccfd16..1e0e73f3fd 100644 --- a/.agents/notes/implemented/feature/2026-10-23-plugin-project-generators.md +++ b/.agents/notes/implemented/feature/2026-10-23-plugin-project-generators.md @@ -29,7 +29,7 @@ | 契约与标准答案 | 共享契约 | `shared/contracts/plugins/v1/README.md` 的 Project generators 一节,`fixtures/project-generators/project-generator.plugin.json`、`fixtures/project-generators/project-plans.json` | | 窗口、名称、位置、Git、空项目、启用插件提示 | macOS 宿主 | `NewProjectView`、`NewProjectFeatureModel` | | 执行计划:临时目录、写文件、跑命令、下载、移动到位 | macOS 宿主 | `ProjectGenerationService`(编排)+ `MacProjectGenerationPlatform`(平台操作) | -| Java、Maven Archetype、Spring Boot 的字段、模板和步骤 | 插件 | `Plugins/mac/Official/JavaSupport/`(`plugin.json` 的 `projectGenerators`、`icons/`、`templates/`) | +| Java、Maven Archetype、Spring Boot 的字段、模板和步骤 | 插件 | 组织插件仓库 `Lithe-IDEA/lithe-plugin-java`(`java`、`spring-boot`)与 `Lithe-IDEA/lithe-plugin-maven`(Maven Archetype),各自 `plugin.json` 的 `projectGenerators`、`icons/`、`templates/`;2026-11 起本仓库不再内置任何插件(#1495) | 宿主里没有任何生成器 ID 分支。项目打开后由已有的 `build.detect` 按 markers 识别 Maven、Gradle,生成器不声明「按什么导入」。 @@ -171,7 +171,6 @@ pin 写失败不会让项目创建失败:项目已经生成并移动到位, cargo test --manifest-path rust/Cargo.toml -p lithe-core project_generators ./scripts/architecture/verify-shared-contracts.sh ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'ProjectGenerationTests|ProjectToolAdaptersTests|PluginManagerTests|PluginLiveActivationTests' -./scripts/plugins/verify-official-plugins.sh ./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh ``` @@ -181,7 +180,6 @@ cargo test --manifest-path rust/Cargo.toml -p lithe-core project_generators - `rust/lithe-core/src/plugins/declarative.rs` - `rust/lithe-core/src/plugins/capabilities.rs` - `shared/contracts/plugins/v1/` -- `Plugins/mac/Official/JavaSupport/` - `macos/Sources/Lithe/Views/Workspace/NewProjectView.swift` - `macos/Sources/Lithe/Application/Features/NewProjectFeatureModel.swift` - `macos/Sources/Lithe/Services/ProjectGeneration/` diff --git a/.agents/notes/implemented/process/2026-09-13-ci-build-cache-and-artifact-strategy.md b/.agents/notes/implemented/process/2026-09-13-ci-build-cache-and-artifact-strategy.md index 2872b89d99..01c2058f92 100644 --- a/.agents/notes/implemented/process/2026-09-13-ci-build-cache-and-artifact-strategy.md +++ b/.agents/notes/implemented/process/2026-09-13-ci-build-cache-and-artifact-strategy.md @@ -489,8 +489,6 @@ Swift 测试已经编译完整 Lithe 目标。再生成两个 DMG 会在普通 - `./scripts/macos/build/build-macos.sh --configuration debug --triple arm64-apple-macosx` - `node --test scripts/macos/build/build-macos.test.mjs scripts/resources/test-reuse-worktree-resources.mjs`:离线工具替身验证 scratch 清理与编译参数一致、按架构失效、旧策略迁移、失败不误记成功、继续编译、默认布局和资源复用拒绝。 - `./scripts/macos/build/build-macos.sh --configuration debug --triple x86_64-apple-macosx` -- `./scripts/plugins/build-official-plugins.sh --configuration debug --triple arm64-apple-macosx` -- `./scripts/plugins/build-official-plugins.sh --configuration debug --triple x86_64-apple-macosx` - `./scripts/rust-core/verify-rust-core.sh` - `./scripts/windows/verify/verify-windows-boundaries.sh` - `node .agents/skills/write-stable-tests/scripts/run-bun-tests-with-timing.mjs --working-directory . --max-ms 30000 --report .artifacts/test-stability/windows-dependency-install.json -- scripts/windows/build/windows-frontend-install.test.ts`:Windows 无网络夹具用 IPC 确认子进程占用目录,再让安装失败,验证清理后冷重试成功、永久失败仍报错、成功退出也不留子进程、超时触发本地期限,且不清除有效缓存。 @@ -517,7 +515,6 @@ Swift 测试已经编译完整 Lithe 目标。再生成两个 DMG 会在普通 - `scripts/resources/worktree-resources.json` - `scripts/resources/reuse-worktree-resources.mjs` - `scripts/resources/test-reuse-worktree-resources.mjs` -- `scripts/plugins/build-official-plugins.sh` - `scripts/rust-core/verify-rust-core.sh` - `scripts/macos/build/MacOS13SDKCompatibility.h` - `rust/` diff --git a/.agents/notes/implemented/process/2026-09-13-macos-update-signing-and-release-strategy.md b/.agents/notes/implemented/process/2026-09-13-macos-update-signing-and-release-strategy.md index 637df614a8..3bab001ecc 100644 --- a/.agents/notes/implemented/process/2026-09-13-macos-update-signing-and-release-strategy.md +++ b/.agents/notes/implemented/process/2026-09-13-macos-update-signing-and-release-strategy.md @@ -84,8 +84,10 @@ v1→v2 那次一样让旧包立刻失效。同一个 key ID 永远不能换成 v1 包在新版本里仍会被拒绝,需要重新下载 v2 包。多 key 表是为以后的轮换准备的, 并没有恢复 v1 兼容性。 -构建侧对应 `scripts/plugins/build-official-plugins.sh --development-unsigned`,只在 debug -配置下可用,用来在没有私钥时产出这种开发包;release 配置传入该参数会直接失败。 +构建侧原本由本仓库的官方插件构建脚本以 `--development-unsigned` 产出开发包,只在 debug +配置下可用;release 配置传入该参数会直接失败。2026-11 内置官方插件连同该脚本和 +`release-official-plugins` 工作流一起移出本仓库(#1495),插件包由各插件仓库 +(`Lithe-IDEA/lithe-plugin-*`)自己的发布流程产出,客户端这里的验证规则不变。 官方插件由组织仓库 `Lithe-IDEA/Lithe-IDEA` 的独立插件发布工作流使用 `LITHE_PLUGIN_PACKAGE_PRIVATE_KEY` 签名,该私钥必须匹配客户端内置 v2 公钥。 @@ -431,7 +433,6 @@ node .agents/skills/write-stable-tests/scripts/run-bun-tests-with-timing.mjs --r ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh --max-seconds 60 -- --filter StableRollbackDiskImageIntegrationTests ./scripts/macos/test/test-macos.sh ./scripts/macos/verify/verify-macos-package.sh -./scripts/plugins/verify-official-plugins.sh ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'PluginLocalDevelopmentTests|PluginPackageSignatureTests|PluginPackageStoreTests' sparkle_tools=$(zsh scripts/release/sparkle/prepare-sparkle-tools.sh) ruby scripts/release/sparkle/test-sparkle-update.rb "$sparkle_tools" @@ -467,7 +468,6 @@ Sparkle 版本间升级、缺失/损坏的 delta、下载中断、权限不足 - `.github/workflows/release-macos.yml` - `.github/workflows/release-preview-macos.yml` - `.github/workflows/release-preview-windows.yml` -- `scripts/plugins/build-official-plugins.sh` - `macos/Sources/LithePluginPackageSigning/` - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginPackageStore.swift` - `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift` diff --git a/.agents/notes/implemented/process/2026-10-09-release-signing-key-reset.md b/.agents/notes/implemented/process/2026-10-09-release-signing-key-reset.md index 4314c750b2..3aa6f3b075 100644 --- a/.agents/notes/implemented/process/2026-10-09-release-signing-key-reset.md +++ b/.agents/notes/implemented/process/2026-10-09-release-signing-key-reset.md @@ -47,7 +47,7 @@ - 运行 `./scripts/agent-notes/verify-agent-notes.sh`。 - 运行 `node --test scripts/release/sparkle/verify-release-signature.test.mjs`,确认篡改文件、错误公钥和截断签名被拒绝。 - 发布工作流安装到独立临时目录,验证版本、公钥、启动及安装目录 SHA-256 清单不变,并有界终止自身应用进程、卸载或删除临时安装。 -- 发布前运行 `./scripts/plugins/verify-official-plugins.sh`、`./scripts/macos/verify/verify-macos-package.sh` 和 Windows 更新器对应测试。 +- 发布前运行 `./scripts/macos/verify/verify-macos-package.sh` 和 Windows 更新器对应测试;官方插件包的校验已随插件移出本仓库(#1495),由各插件仓库的发布流程负责。 - 在真实发布前完成旧版本到新版本的安装、Sparkle 验签、Tauri 更新器验签和官方插件安装验证;普通 CI 成功不能替代这些检查。 ## 适用范围 diff --git a/.agents/notes/proposed/architecture/2026-09-13-module-runtime-extraction-roadmap.md b/.agents/notes/proposed/architecture/2026-09-13-module-runtime-extraction-roadmap.md index 60bae329ba..8930ebbd7b 100644 --- a/.agents/notes/proposed/architecture/2026-09-13-module-runtime-extraction-roadmap.md +++ b/.agents/notes/proposed/architecture/2026-09-13-module-runtime-extraction-roadmap.md @@ -2,6 +2,8 @@ 状态:提议中 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 这是一份逐步完成模块边界的路线图,不代表所有功能现在都已经抽取完成。后续每一步都要先证明模块有真实的所有权和独立测试价值,不能为了目录看起来整齐而制造空壳 target 或包装层。 @@ -113,7 +115,7 @@ command、DTO、错误码、取消或陈旧结果语义。因此先保持 Rust - `macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift` - `macos/Sources/LitheCoreContracts/` - `macos/Sources/Lithe*Module/` -- `Plugins/mac/Official/` +- 已迁出:原 `Plugins/mac/Official/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `scripts/architecture/verify-module-boundaries.sh` - `macos/Tests/LitheApplicationKernelTests/` - 各功能模块的对应测试 target diff --git a/.agents/notes/proposed/architecture/2026-10-17-build-system-provider-api.md b/.agents/notes/proposed/architecture/2026-10-17-build-system-provider-api.md index 4bf92ba3d2..e03d853e65 100644 --- a/.agents/notes/proposed/architecture/2026-10-17-build-system-provider-api.md +++ b/.agents/notes/proposed/architecture/2026-10-17-build-system-provider-api.md @@ -2,6 +2,8 @@ 状态:提议中 +> 2026-11-07 更新:本文提到的部分文件已不存在。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495);宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Lithe 对构建工具的支持原本分散在三处:Rust Core 里写死的运行入口探测器、一整套 Maven 专用类型和工具窗口,以及只认“语言”的声明式插件契约。新增一个构建工具或构建插件(例如 Issue #10 里 Gradle 的 Loom/NeoForge 任务)都要改 Core 代码。 @@ -338,16 +340,16 @@ Core 契约部分的验收已在已实现的 Note 里完成。剩下的工作按 - `rust/lithe-core/src/plugins/declarative.rs` - `rust/lithe-core/src/execution/detectors/` - `rust/lithe-core/src/execution/types.rs` -- `rust/lithe-core/src/project/maven.rs` +- 已迁出:原 `rust/lithe-core/src/project/maven.rs`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 - `rust/lithe-core/src/execution/configuration.rs` - `rust/lithe-core/src/lsp/interface/engine.rs` - `rust/lithe-core/src/runtime/dispatcher.rs` - `shared/contracts/rust-core-api.md` -- `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift` -- `macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenConfigurationMigration.swift` +- 已迁出:原 `macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 +- 已迁出:原 `macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenConfigurationMigration.swift`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 - `macos/Sources/LitheExecutionModule/Services/BuildSystemService.swift` - `macos/Sources/LitheExecutionModule/Services/StandardLanguageTestProvider.swift` -- `macos/Sources/LitheCoreContracts/Execution/MavenContracts.swift` +- 已迁出:原 `macos/Sources/LitheCoreContracts/Execution/MavenContracts.swift`。Maven 专属逻辑已从 Core 与宿主移入 Maven 插件([lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven))(#1495)。 - `macos/Sources/Lithe/Views/Run/BuildSystemToolWindowView.swift` - `windows/tauri/src/features/maven/` - `windows/tauri/src/features/run/` diff --git a/.agents/notes/proposed/architecture/2026-10-24-java-support-independent-distribution.md b/.agents/notes/proposed/architecture/2026-10-24-java-support-independent-distribution.md index 750deb85c6..92fda88e9a 100644 --- a/.agents/notes/proposed/architecture/2026-10-24-java-support-independent-distribution.md +++ b/.agents/notes/proposed/architecture/2026-10-24-java-support-independent-distribution.md @@ -2,6 +2,8 @@ 状态:提议中 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护;宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Java Support 已经是声明式插件,JDT LS、JDK、Lombok 和调试、测试扩展都由插件包拥有,本提案不重复做插件化。建议下一步把它从“随 Lithe.app 发行”改成“独立发布、按需安装”,让不使用 Java 的用户不再下载这部分资源。先完成安装、版本匹配拒绝和用户配置迁移,再从主安装包移除资源。现有 `jdt` 宿主集成与 Java 运行、测试、调试是分发提案的当前边界;完整领域后端迁移由 [#1495 清单](2026-10-26-maven-java-domain-plugin-migration.md)继续推进,完成后删除这些宿主专属实现。 @@ -210,10 +212,10 @@ node scripts/architecture/verify-java-semantic-ownership.mjs ## 适用范围 -- `Plugins/mac/Official/JavaSupport/` +- 已迁出:原 `Plugins/mac/Official/JavaSupport/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `Plugins/marketplace/` -- `scripts/plugins/build-official-plugins.sh` -- `scripts/plugins/official-plugin-releases.mjs` +- 已迁出:原 `scripts/plugins/build-official-plugins.sh`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 +- 已迁出:原 `scripts/plugins/official-plugin-releases.mjs`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `scripts/macos/package/package-app.sh` - `scripts/macos/verify/verify-macos-package.sh` - `scripts/resources/worktree-resources.json` @@ -223,7 +225,7 @@ node scripts/architecture/verify-java-semantic-ownership.mjs - `third_party/jdk/manifest.json` - `macos/Sources/LitheModuleAPI/Catalog/BuiltInModuleCatalog.swift` - `macos/Sources/Lithe/Platform/MacOS/Plugins/` -- `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift` +- 已迁出:原 `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/LithePluginPackageSigning/` - `rust/lithe-core/src/lsp/languages/` - `shared/contracts/plugins/v1/` diff --git a/.agents/notes/proposed/architecture/2026-10-26-maven-java-domain-plugin-migration.md b/.agents/notes/proposed/architecture/2026-10-26-maven-java-domain-plugin-migration.md index fab5cb65c8..20de7de49b 100644 --- a/.agents/notes/proposed/architecture/2026-10-26-maven-java-domain-plugin-migration.md +++ b/.agents/notes/proposed/architecture/2026-10-26-maven-java-domain-plugin-migration.md @@ -2,6 +2,8 @@ 状态:提议中 +> 2026-11-07 更新:本文提到的部分文件已不存在。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 Java Support 已拥有语言服务器资源,Maven 也已有插件后端,但宿主和 Rust Core 仍执行一部分 Maven/Java 专属业务。本提案按 [Issue #1495](https://github.com/1lck/Lithe-IDEA/issues/1495) 固定当前入口、调用关系、数据和删除条件:后续迁移必须让同一用户流程全部使用插件结果,再删除被替代的生产路径。只支持迁移后的最新宿主与匹配插件,保留用户数据迁移,不保留旧业务回退。 @@ -219,7 +221,7 @@ git diff --check - `macos/Sources/Lithe/Application/`、`macos/Sources/Lithe/Models/AppModel/`、`macos/Sources/Lithe/Services/` - `macos/Sources/Lithe/Platform/MacOS/`、`macos/Sources/LitheExecutionModule/`、`macos/Sources/LitheLanguageIntelligenceModule/` - `rust/lithe-core/src/build/`、`rust/lithe-core/src/project/`、`rust/lithe-core/src/execution/`、`rust/lithe-core/src/lsp/`、`rust/lithe-core/src/debug/` -- `Plugins/mac/Official/JavaSupport/`、`third_party/jdtls/manifest.json`、`third_party/jdk/manifest.json` +- 已迁出:原 `Plugins/mac/Official/JavaSupport/`。官方插件的源码、组装与发布已移出本仓库(#1495),改由各插件仓库自行构建发布([lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)、[lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven)、[lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle)),Store 索引由 Lithe Store 维护。 - `shared/contracts/`、`shared/fixtures/`、`shared/platform-feature-matrix/features/` - `windows/tauri/src/features/`、`windows/tauri/src/platform/`、`windows/tauri/src-tauri/src/` - 外部 Maven 后端:[`Lithe-IDEA/lithe-plugin-maven`][maven-plugin] diff --git a/.agents/notes/proposed/architecture/2026-10-31-plugin-injected-toolchains.md b/.agents/notes/proposed/architecture/2026-10-31-plugin-injected-toolchains.md index 0e5c09b3c5..d337f6cc33 100644 --- a/.agents/notes/proposed/architecture/2026-10-31-plugin-injected-toolchains.md +++ b/.agents/notes/proposed/architecture/2026-10-31-plugin-injected-toolchains.md @@ -2,6 +2,8 @@ 状态:提议中 +> 2026-11-07 更新:本文提到的部分文件已不存在。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。下文保留当时的决策与理由,路径以“适用范围”里标注的去向为准。 + ## 先说结论 从 Dock 启动时找不到版本管理器安装的运行时、项目要求的版本未生效,不能靠宿主逐个补目录和版本文件解析器解决。本方案把工具定义、安装事实提供方和使用方分开:插件说明工具是什么,版本管理器回答当前事实,宿主只提供统一选择、查询和环境展示框架;Java、Maven 等定义全部由插件贡献,不保留宿主内置定义表或兼容别名。当前已实现 Core 基础切片及 macOS 只读设置页;macOS 设置页已按声明式路线真实扫描本机安装、运行定义的版本探测并交 Core 选择,并通过插件后端查询提供方、监听其输入后整份重查;每行哪一层生效由 Core `toolchains.resolve` 用页面展示的同一份事实决定,Swift 不自己排优先级。macOS 已补已接通 Build 使用方的本机偏好编辑,目录 pin 保存、选择版本管理器等写入操作尚未实现;阶段 D 已补两端 Build 运行前消费者、Windows 操作内查询及通用偏好基础,完整 Windows 产品准入和旧默认转换仍未接通。完整方案仍在本提案中跟踪,不能把页面出现解释成产品已能使用 mise 或已经完成工具迁移。 @@ -189,7 +191,7 @@ macOS 的声明式路线由 `MacToolchainDiscovery` 执行,宿主不认识任 - `shared/contracts/toolchain-local-v1.schema.json` - `rust/lithe-core/src/plugins/` - `rust/lithe-core/src/execution/` -- `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift` +- 已迁出:原 `macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift`。宿主侧 Java 专属代码已删除(#1495);运行、调试、入口标记与工具链改走通用插件 API(`run/start`、`debug/start`、`editor/registerActions`、`toolDefinitions`),实现见 [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java)。 - `macos/Sources/Lithe/Platform/MacOS/Runtime/` - `macos/Sources/Lithe/Platform/MacOS/Plugins/` - `windows/tauri/src/platform/` diff --git a/.agents/notes/proposed/architecture/2026-11-04-java-extraction-generic-apis-and-gate.md b/.agents/notes/proposed/architecture/2026-11-04-java-extraction-generic-apis-and-gate.md index 9416ffffed..db6fc1bcb8 100644 --- a/.agents/notes/proposed/architecture/2026-11-04-java-extraction-generic-apis-and-gate.md +++ b/.agents/notes/proposed/architecture/2026-11-04-java-extraction-generic-apis-and-gate.md @@ -163,13 +163,13 @@ SDK:三份官方后端 SDK(Node、Java、Rust)各自增加发现、调用 ### 六、Windows legacy crate -Windows 现在还通过 Core 的命令调用 Maven 和 Java 功能,而 Windows 宿主尚未实现通用插件接口,不能直接换成插件。所以 W1 新建 `windows/tauri/crates/lithe-legacy-java`(legacy crate,意为过渡用的旧功能库,尚不存在,W1 创建),把 Core 里只有 Windows 使用的 Maven 和 Java 代码搬过去: +Windows 现在还通过 Core 的命令调用 Maven 和 Java 功能,而 Windows 宿主尚未实现通用插件接口,不能直接换成插件。所以 W1 新建 `windows/tauri/crates/lithe-legacy-tooling`(legacy crate,意为过渡用的旧功能库,尚不存在,W1 创建),把 Core 里只有 Windows 使用的 Maven 和 Java 代码搬过去: - 入口是 `try_execute(request) -> Option`,命中旧命令名就处理,否则返回 `None`。`windows/tauri/src-tauri/src/core.rs` 的 `core_execute` 在调用 `execute_for_window(..., lithe_core::execute_json)` 之前,以及 `platform.rs` 的 `platform_invoke` 在 `lithe_core::execute_json` 之前,都先调它。Windows 的 TypeScript 消费者不变。 - W2 增加会话命令,经通用的 `lsp.request`、`lsp.updateWorkspaceConfiguration`、`lsp.waitEvents` 工作。 - 它在 Windows 自己的目录里,不在闸门的扫描根目录内,所以不进白名单;但 Windows 的 TypeScript 和 Rust 消费文件在白名单里,每项的 `issue` 填 #1495,`removeWhen` 写明删除条件。 -**删除条件:** Windows 宿主实现了通用接口,并能安装 `lithe-plugin-java`。到那时整个目录删除,白名单里的 Windows 项一并删除。跟踪 Issue 草稿的标题是“Windows:用 Java 插件取代 lithe-legacy-java”,用户确认后再按 `submit-lithe-issue` Skill 提交。 +**删除条件:** Windows 宿主实现了通用接口,并能安装 `lithe-plugin-java`。到那时整个目录删除,白名单里的 Windows 项一并删除。跟踪 Issue 草稿的标题是“Windows:用 Java 插件取代 lithe-legacy-tooling”,用户确认后再按 `submit-lithe-issue` Skill 提交。 代价:这段时间同一份逻辑同时存在于 Java 插件和 legacy crate。证据要求是 `cargo check --manifest-path windows/tauri/src-tauri/Cargo.toml`、Windows 单元测试和 Parallels 真机冒烟。 diff --git a/.github/actions/prepare-macos-dependency-cache/action.yml b/.github/actions/prepare-macos-dependency-cache/action.yml index c145d7e1d2..569693782f 100644 --- a/.github/actions/prepare-macos-dependency-cache/action.yml +++ b/.github/actions/prepare-macos-dependency-cache/action.yml @@ -18,18 +18,6 @@ inputs: description: Partition compilation caches by arm64, x86_64, or universal packaging. required: false default: "universal" - jdtls: - description: Restore JDTLS and Lombok downloads. - required: false - default: "false" - jdk: - description: Restore the bundled JDTLS runtime JDK download. - required: false - default: "false" - jdk-architecture: - description: Target JDK architecture, arm64, x86_64, or universal for both. - required: false - default: "" restore-only: description: Restore caches without saving them at the end of the job. Cargo compilation outputs are always restore-only here; save them with save-macos-cargo-build-cache. required: false @@ -55,17 +43,6 @@ runs: echo "LITHE_SWIFTPM_CACHE_PATH=$GITHUB_WORKSPACE/.artifacts/swiftpm-cache" } >> "$GITHUB_ENV" - - name: Validate JDK cache inputs - if: inputs.jdk == 'true' - shell: zsh {0} - env: - JDK_ARCHITECTURE: ${{ inputs.jdk-architecture }} - run: | - case "$JDK_ARCHITECTURE" in - arm64|x86_64|universal) ;; - *) print -u2 -- "jdk-architecture must be arm64, x86_64, or universal when the JDK cache is enabled"; exit 2 ;; - esac - - name: Restore SwiftPM repositories id: swiftpm_cache if: inputs.swiftpm == 'true' && inputs.restore-only != 'true' @@ -114,50 +91,6 @@ runs: restore-keys: | macos-cargo-crates-${{ runner.os }}- - - name: Restore JDTLS downloads - id: jdtls_cache - if: inputs.jdtls == 'true' && inputs.restore-only != 'true' - continue-on-error: true - uses: actions/cache@v6 - with: - path: .artifacts/jdtls-downloads - key: macos-jdtls-downloads-${{ runner.os }}-${{ hashFiles('third_party/jdtls/manifest.json') }} - restore-keys: | - macos-jdtls-downloads-${{ runner.os }}- - - - name: Restore JDTLS downloads without saving - id: jdtls_restore - if: inputs.jdtls == 'true' && inputs.restore-only == 'true' - continue-on-error: true - uses: actions/cache/restore@v6 - with: - path: .artifacts/jdtls-downloads - key: macos-jdtls-downloads-${{ runner.os }}-${{ hashFiles('third_party/jdtls/manifest.json') }} - restore-keys: | - macos-jdtls-downloads-${{ runner.os }}- - - - name: Restore JDK downloads - id: jdk_cache - if: inputs.jdk == 'true' && inputs.restore-only != 'true' - continue-on-error: true - uses: actions/cache@v6 - with: - path: .artifacts/jdk-downloads - key: macos-jdk-downloads-${{ runner.os }}-${{ inputs.jdk-architecture }}-${{ hashFiles('third_party/jdk/manifest.json') }} - restore-keys: | - macos-jdk-downloads-${{ runner.os }}-${{ inputs.jdk-architecture }}- - - - name: Restore JDK downloads without saving - id: jdk_restore - if: inputs.jdk == 'true' && inputs.restore-only == 'true' - continue-on-error: true - uses: actions/cache/restore@v6 - with: - path: .artifacts/jdk-downloads - key: macos-jdk-downloads-${{ runner.os }}-${{ inputs.jdk-architecture }}-${{ hashFiles('third_party/jdk/manifest.json') }} - restore-keys: | - macos-jdk-downloads-${{ runner.os }}-${{ inputs.jdk-architecture }}- - - name: Validate restored caches or fall back shell: zsh {0} env: @@ -168,33 +101,21 @@ runs: SWIFTPM_RESTORE_HIT: ${{ steps.swiftpm_restore.outputs.cache-hit }} CARGO_CACHE_OUTCOME: ${{ steps.cargo_cache.outcome }} CARGO_RESTORE_OUTCOME: ${{ steps.cargo_restore.outcome }} - JDTLS_CACHE_OUTCOME: ${{ steps.jdtls_cache.outcome }} - JDTLS_RESTORE_OUTCOME: ${{ steps.jdtls_restore.outcome }} - JDK_CACHE_OUTCOME: ${{ steps.jdk_cache.outcome }} - JDK_RESTORE_OUTCOME: ${{ steps.jdk_restore.outcome }} run: | swiftpm_outcome="$SWIFTPM_CACHE_OUTCOME" swiftpm_hit="$SWIFTPM_CACHE_HIT" cargo_outcome="$CARGO_CACHE_OUTCOME" - jdtls_outcome="$JDTLS_CACHE_OUTCOME" - jdk_outcome="$JDK_CACHE_OUTCOME" if [[ "$RESTORE_ONLY" == "true" ]]; then swiftpm_outcome="$SWIFTPM_RESTORE_OUTCOME" swiftpm_hit="$SWIFTPM_RESTORE_HIT" cargo_outcome="$CARGO_RESTORE_OUTCOME" - jdtls_outcome="$JDTLS_RESTORE_OUTCOME" - jdk_outcome="$JDK_RESTORE_OUTCOME" fi "$GITHUB_WORKSPACE/scripts/macos/prepare/validate-macos-dependency-caches.sh" \ --swiftpm-enabled "${{ inputs.swiftpm }}" \ --swiftpm-outcome "${swiftpm_outcome:-skipped}" \ --swiftpm-hit "${swiftpm_hit:-}" \ --cargo-enabled "${{ inputs.cargo }}" \ - --cargo-outcome "${cargo_outcome:-skipped}" \ - --jdtls-enabled "${{ inputs.jdtls }}" \ - --jdtls-outcome "${jdtls_outcome:-skipped}" \ - --jdk-enabled "${{ inputs.jdk }}" \ - --jdk-outcome "${jdk_outcome:-skipped}" + --cargo-outcome "${cargo_outcome:-skipped}" - name: Resolve SwiftPM dependencies with fallback if: inputs.swiftpm == 'true' diff --git a/.github/workflows/ci-macos.yml b/.github/workflows/ci-macos.yml index 4b07aedc91..80eb1ea4a9 100644 --- a/.github/workflows/ci-macos.yml +++ b/.github/workflows/ci-macos.yml @@ -319,9 +319,6 @@ jobs: uses: ./.github/actions/prepare-macos-dependency-cache with: swiftpm: "true" - jdtls: ${{ needs.changes.outputs.plugins }} - jdk: ${{ needs.changes.outputs.plugins }} - jdk-architecture: arm64 # Compile and discover tests before starting the test execution deadline. # A cold Rust/Swift build still compiling Lithe exceeded 20 minutes in @@ -410,11 +407,6 @@ jobs: timeout-minutes: 17 run: ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh --report .artifacts/test-stability/macos-plugins.json --suite-timeout-seconds 960 -- --skip-build --filter '([Pp]lugin|LanguageExtensionProcessLifecycleTests|LanguageServerToolServiceTests|LinuxDo)' - - name: Build and verify official plugin packages - if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.plugins == 'true' }} - timeout-minutes: 10 - run: ./scripts/plugins/verify-official-plugins.sh - # A failed build cannot produce reports; the build step already fails the # job, so do not stack a second "no reports found" failure on top of it. - name: Generate combined Swift test report @@ -537,9 +529,6 @@ jobs: cargo: "true" cargo-build: "true" cargo-build-architecture: ${{ matrix.architecture }} - jdtls: "true" - jdk: "true" - jdk-architecture: ${{ matrix.architecture }} - name: Check packaging scripts and metadata shell: zsh {0} @@ -563,7 +552,6 @@ jobs: LITHE_DMG_DIAGNOSTICS: "1" run: | ./scripts/macos/verify/verify-macos-package.sh - ./scripts/macos/verify/verify-macos-package.sh --slim - name: Verify Sparkle update packaging run: | @@ -577,8 +565,7 @@ jobs: LITHE_BUILD_NUMBER: ${{ github.run_number }}.${{ github.run_attempt }} shell: bash run: | - # The universal smoke test uses Java fixtures in a temporary folder. - # Assemble again with real tools, reusing its compiled Swift/Rust files. + # Assemble the distributable package, reusing the smoke test's compiled Swift/Rust files. ./scripts/macos/package/package-app.sh ./scripts/macos/package/create-dmg.sh version=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' macos/Resources/Info.plist) @@ -627,7 +614,7 @@ jobs: echo "" echo "Source: $SOURCE_SHA" echo "" - echo "Requires GitHub sign-in. Retained for 14 days. Includes the bundled Java tools." + echo "Requires GitHub sign-in. Retained for 14 days." echo "The app is ad-hoc signed for testing. Check the CI gate for the combined test result." } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/ci-plugins.yml b/.github/workflows/ci-plugins.yml index 5105bf8793..6a1cd207df 100644 --- a/.github/workflows/ci-plugins.yml +++ b/.github/workflows/ci-plugins.yml @@ -139,10 +139,6 @@ jobs: uses: ./.github/actions/prepare-macos-dependency-cache with: swiftpm: "true" - # Java Support is assembled from the pinned JDT LS and JDK. - jdtls: "true" - jdk: "true" - jdk-architecture: arm64 # Compile and discover tests before starting the test execution deadline. # A cold Rust/Swift build exceeded 20 minutes while still compiling Lithe @@ -163,10 +159,6 @@ jobs: timeout-minutes: 17 run: ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh --report .artifacts/test-stability/macos-plugins.json --suite-timeout-seconds 960 -- --skip-build --filter '([Pp]lugin|LanguageExtensionProcessLifecycleTests|LanguageServerToolServiceTests|LinuxDo)' - - name: Build and verify official plugin packages - timeout-minutes: 10 - run: ./scripts/plugins/verify-official-plugins.sh - - name: Generate combined plugin test report if: ${{ !cancelled() }} run: node .agents/skills/write-stable-tests/scripts/generate-test-report.mjs diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.yml index 3b8843aa0f..218d9cfa85 100644 --- a/.github/workflows/release-macos.yml +++ b/.github/workflows/release-macos.yml @@ -116,9 +116,6 @@ jobs: with: swiftpm: "true" cargo: "true" - jdtls: "true" - jdk: "true" - jdk-architecture: ${{ matrix.architecture }} restore-only: "true" - name: Import Developer ID signing identity @@ -133,7 +130,7 @@ jobs: echo "Incomplete Developer ID configuration: provide the certificate or remove the optional identity and password." exit 1 else - echo "Developer ID is not configured; using ad-hoc app signing. Official plugin packages use Lithe Ed25519 signatures." + echo "Developer ID is not configured; using ad-hoc app signing." fi - name: Build and package the App diff --git a/.github/workflows/release-official-plugins.yml b/.github/workflows/release-official-plugins.yml deleted file mode 100644 index 63c051c944..0000000000 --- a/.github/workflows/release-official-plugins.yml +++ /dev/null @@ -1,216 +0,0 @@ -# Releases each official downloadable plugin through its own tag series -# (`plugin--v`), independent of Lithe app releases. Listing a -# release in Plugins/marketplace/index.json is a separate, idempotent job: it -# lists every tagged version the index is missing, so a run whose index pull -# request failed after the release was published recovers on the next run. -# A plugin is only released when its package directory changed and its -# plugin.json declares a version without a tag; pull requests that change a -# released plugin without bumping its version fail the check job. -name: Release Official Plugins - -on: - pull_request: - paths: - - "Plugins/mac/Official/**" - - "Plugins/marketplace/**" - - "scripts/plugins/official-plugin-releases.mjs" - - "scripts/plugins/official-plugin-releases.test.mjs" - - "scripts/plugins/official-plugin-distribution.mjs" - - "scripts/plugins/test-official-plugin-distribution.mjs" - - "scripts/plugins/build-official-plugins.sh" - - "scripts/macos/prepare/prepare-jdtls.sh" - - "scripts/macos/prepare/prepare-jdk.sh" - - "third_party/jdtls/manifest.json" - - "third_party/jdk/manifest.json" - - ".github/workflows/release-official-plugins.yml" - push: - branches: - - preview - paths: - - "Plugins/mac/Official/**" - - "Plugins/marketplace/official-plugins.json" - - "scripts/plugins/build-official-plugins.sh" - - "scripts/macos/prepare/prepare-jdtls.sh" - - "scripts/macos/prepare/prepare-jdk.sh" - - "third_party/jdtls/manifest.json" - - "third_party/jdk/manifest.json" - - ".github/workflows/release-official-plugins.yml" - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: release-official-plugins-${{ github.ref == 'refs/heads/main' && github.run_id || github.event.pull_request.number || github.ref }} - # PRs only validate plans; never interrupt a publishing run. - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - plan: - name: Plan plugin releases - runs-on: ubuntu-latest - outputs: - releases: ${{ steps.plan.outputs.releases }} - - steps: - - name: Check out source with tags - uses: actions/checkout@v7 - with: - fetch-depth: 0 - fetch-tags: true - - - name: Test release planning - run: node --test scripts/plugins/official-plugin-releases.test.mjs scripts/plugins/test-official-plugin-distribution.mjs - - - name: Require a new version for changed plugins - run: node scripts/plugins/official-plugin-releases.mjs check - - - name: Plan untagged plugin versions - id: plan - run: echo "releases=$(node scripts/plugins/official-plugin-releases.mjs plan)" >> "$GITHUB_OUTPUT" - - release: - name: Release ${{ matrix.release.tag }} - needs: plan - if: github.repository == '1lck/Lithe-IDEA' && github.event_name != 'pull_request' && github.ref == 'refs/heads/preview' && needs.plan.outputs.releases != '[]' - runs-on: macos-26 - timeout-minutes: 30 - permissions: - contents: write - pull-requests: write - strategy: - fail-fast: false - max-parallel: 1 - matrix: - release: ${{ fromJSON(needs.plan.outputs.releases) }} - - steps: - - name: Check out source - uses: actions/checkout@v7 - with: - fetch-depth: 0 - fetch-tags: true - - - name: Set up Swift 6.3.3 and Xcode - uses: ./.github/actions/setup-macos-toolchain - - - name: Build, sign, and verify every architecture - env: - LITHE_PLUGIN_PACKAGE_PRIVATE_KEY: ${{ secrets.LITHE_PLUGIN_PACKAGE_PRIVATE_KEY }} - RELEASE_JSON: ${{ toJSON(matrix.release) }} - run: | - set -euo pipefail - test -n "$LITHE_PLUGIN_PACKAGE_PRIVATE_KEY" || { echo "Configure LITHE_PLUGIN_PACKAGE_PRIVATE_KEY before releasing plugins"; exit 1; } - id=$(jq -r .id <<<"$RELEASE_JSON") - version=$(jq -r .version <<<"$RELEASE_JSON") - swift build --product LitheOfficialPluginVerifier - swift_bin=$(swift build --show-bin-path) - jq -c '.assets[]' <<<"$RELEASE_JSON" | while read -r asset; do - name=$(jq -r .assetName <<<"$asset") - arch=$(jq -r '.arch // "arm64"' <<<"$asset") - plugin_root=$(scripts/plugins/build-official-plugins.sh \ - --configuration release --triple arm64-apple-macosx --arch "$arch" \ - --plugin-id "$id" --output "dist/packages/$arch") - ditto -c -k --keepParent "$plugin_root/$id" "dist/$name" - verify="dist/verify/$arch" - mkdir -p "$verify" - ditto -x -k "dist/$name" "$verify" - manifest="$verify/$id/plugin.json" - test "$(plutil -extract id raw "$manifest")" = "$id" - test "$(plutil -extract version raw "$manifest")" = "$version" - "$swift_bin/LitheOfficialPluginVerifier" "$verify/$id" - signer="$(swift build --configuration release --triple arm64-apple-macosx --show-bin-path)/LithePluginPackageSigner" - "$signer" --verify "$verify/$id" - # Preserve the pinned upstream runtime's native signatures. The - # publisher signature alone does not prove macOS can launch it. - runtime="$verify/$id/runtime/$arch" - if [ -d "$runtime" ]; then - lipo "$runtime/bin/java" -verify_arch "$arch" - codesign --verify --strict "$runtime/bin/java" - codesign --verify --strict "$runtime/lib/server/libjvm.dylib" - fi - shasum -a 256 "dist/$name" | cut -d' ' -f1 > "dist/$name.sha256" - done - - - name: Publish all architectures in one release - env: - GH_TOKEN: ${{ github.token }} - RELEASE_JSON: ${{ toJSON(matrix.release) }} - run: | - set -euo pipefail - tag=$(jq -r .tag <<<"$RELEASE_JSON") - id=$(jq -r .id <<<"$RELEASE_JSON") - version=$(jq -r .version <<<"$RELEASE_JSON") - assets=() - while read -r asset; do - assets+=("dist/$asset" "dist/$asset.sha256") - done < <(jq -r '.assets[].assetName' <<<"$RELEASE_JSON") - printf 'Official Lithe plugin %s %s. Each architecture has its own archive and SHA-256 file.\n' "$id" "$version" > dist/release-notes.md - # App update checks own the repository's Latest slot. - gh release create "$tag" "${assets[@]}" --latest=false --target "$GITHUB_SHA" \ - --title "$id $version" --notes-file dist/release-notes.md - - sync-index: - name: List released plugins in the official index - needs: [plan, release] - # Runs after releases (even when one of them failed, since only tagged - # versions are listed), after a skipped release, and on manual reruns, so - # a listing that failed earlier is retried. - if: >- - !cancelled() - && github.repository == '1lck/Lithe-IDEA' - && github.event_name != 'pull_request' - && github.ref == 'refs/heads/preview' - && needs.plan.result == 'success' - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: write - pull-requests: write - - steps: - - name: Check out source with tags - uses: actions/checkout@v7 - with: - fetch-depth: 0 - fetch-tags: true - - - name: Open index pull requests for unlisted releases - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - # Tags created by the release job are not in this checkout yet. - git fetch --force --tags origin - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - pending=$(node scripts/plugins/official-plugin-releases.mjs pending-index) - echo "Pending: $pending" - echo "$pending" | jq -c '.[]' | while read -r release; do - id=$(jq -r .id <<<"$release") - version=$(jq -r .version <<<"$release") - tag=$(jq -r .tag <<<"$release") - branch="automation/plugin-index-$tag" - if [ "$(gh pr list --head "$branch" --state open --json number --jq length)" != "0" ]; then - echo "$tag already has an open index pull request" - continue - fi - # A retry reads the tagged configuration and manifest, and hashes - # every published archive before listing this version atomically. - rm -rf dist && mkdir -p dist - checksums='{}' - while read -r asset; do - gh release download "$tag" --pattern "$asset" --dir dist - sha=$(sha256sum "dist/$asset" | cut -d' ' -f1) - checksums=$(jq -c --arg name "$asset" --arg sha "$sha" '. + {($name): $sha}' <<<"$checksums") - done < <(jq -r '.assets[].assetName' <<<"$release") - released=$(gh release view "$tag" --json publishedAt --jq '.publishedAt[0:10]') - git switch --force-create "$branch" origin/preview - node scripts/plugins/official-plugin-releases.mjs update-index "$id" "$version" "$checksums" "$released" - git add Plugins/marketplace/index.json - git commit -m "chore(plugins): 将 $id $version 加入官方插件索引" - git push --force origin "$branch" - printf '发布流程已发布 %s。本 PR 将该版本全部架构的下载地址、实际归档 SHA-256、API 等级和能力要求写入官方索引。\n' "$tag" > dist/index-pr.md - gh pr create --draft --base preview --head "$branch" \ - --title "chore(plugins): 官方插件索引加入 $id $version" --body-file dist/index-pr.md - done diff --git a/.github/workflows/release-preview-macos.yml b/.github/workflows/release-preview-macos.yml index 02df33e0a3..466a2487c6 100644 --- a/.github/workflows/release-preview-macos.yml +++ b/.github/workflows/release-preview-macos.yml @@ -100,9 +100,6 @@ jobs: cargo: "true" cargo-build: "true" cargo-build-architecture: ${{ matrix.architecture }} - jdtls: "true" - jdk: "true" - jdk-architecture: ${{ matrix.architecture }} - name: Import Developer ID signing identity env: @@ -116,7 +113,7 @@ jobs: echo "Incomplete Developer ID configuration: provide the certificate or remove the optional identity and password." exit 1 else - echo "Developer ID is not configured; the preview app will be ad-hoc signed. Official plugin packages use Lithe Ed25519 signatures." + echo "Developer ID is not configured; the preview app will be ad-hoc signed." fi - name: Build and package the preview app diff --git a/Plugins/mac/Official/JavaSupport/assemble-package.sh b/Plugins/mac/Official/JavaSupport/assemble-package.sh deleted file mode 100755 index f1637ed94c..0000000000 --- a/Plugins/mac/Official/JavaSupport/assemble-package.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/bin/zsh - -set -euo pipefail - -# Assembles the resources of the Java Support plugin package: the pinned -# JDT LS distribution with its Lombok, Debug, and Test extensions, and the -# JDK it runs on. Everything is fetched and checksum-verified by the shared -# prepare scripts; this script only arranges the result in the layout -# plugin.json declares, plus the icons and template directories of the New -# Project entries (Java, Maven Archetype, Spring Boot). The assembled package -# is read-only at runtime; projects are generated in the user's chosen folder. -# See .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md -# and .agents/notes/implemented/feature/2026-10-23-plugin-project-generators.md. - -PLUGIN_DIR="${0:A:h}" -ROOT_DIR="${PLUGIN_DIR:h:h:h:h}" -OUTPUT_DIR="" -ARCH="" - -while [[ $# -gt 0 ]]; do - case "$1" in - --output) OUTPUT_DIR="$2"; shift 2 ;; - --arch) ARCH="$2"; shift 2 ;; - *) print -u2 -- "Usage: $0 --output package-directory --arch arm64|x86_64|universal"; exit 2 ;; - esac -done -[[ -n "$OUTPUT_DIR" ]] || { print -u2 -- "--output is required"; exit 2; } -case "$ARCH" in - arm64|x86_64) runtime_architectures=("$ARCH") ;; - universal) runtime_architectures=(arm64 x86_64) ;; - *) print -u2 -- "Unsupported architecture: $ARCH"; exit 2 ;; -esac - -jdtls_root=$(LITHE_ARCH="$ARCH" "$ROOT_DIR/scripts/macos/prepare/prepare-jdtls.sh") -language_server="$OUTPUT_DIR/language-server" -rm -rf "$language_server" "$OUTPUT_DIR/runtime" "$OUTPUT_DIR/icons" "$OUTPUT_DIR/templates" -cp -R "$PLUGIN_DIR/icons" "$OUTPUT_DIR/icons" -cp -R "$PLUGIN_DIR/templates" "$OUTPUT_DIR/templates" -mkdir -p "$language_server/configuration" - -# Only what a macOS launch reads is packaged. The wrapper scripts and the -# configuration areas of other platforms are left out. -for entry in plugins features lombok java-debug java-test manifest.json LICENSE-EPL-2.0.txt; do - [[ -e "$jdtls_root/$entry" ]] || { - print -u2 -- "JDT LS distribution is missing $entry: $jdtls_root" - exit 1 - } - cp -R "$jdtls_root/$entry" "$language_server/$entry" -done - -# Equinox reads one configuration per architecture. The packaged copy stays -# read-only; Rust Core gives each launch a writable area in the host cache. -for runtime_arch in "${runtime_architectures[@]}"; do - case "$runtime_arch" in - arm64) configuration_name="config_mac_arm" ;; - x86_64) configuration_name="config_mac" ;; - esac - [[ -f "$jdtls_root/$configuration_name/config.ini" ]] || { - print -u2 -- "JDT LS configuration is missing: $jdtls_root/$configuration_name/config.ini" - exit 1 - } - mkdir -p "$language_server/configuration/$runtime_arch" - cp "$jdtls_root/$configuration_name/config.ini" "$language_server/configuration/$runtime_arch/config.ini" - - if [[ "$ARCH" == "universal" ]]; then - override_variable="LITHE_JDK_${runtime_arch:u}_ROOT" - jdk_root=$(LITHE_JDK_ROOT="${(P)override_variable:-}" LITHE_JDK_TARGET_ARCH="$runtime_arch" \ - "$ROOT_DIR/scripts/macos/prepare/prepare-jdk.sh") - else - jdk_root=$(LITHE_JDK_TARGET_ARCH="$runtime_arch" "$ROOT_DIR/scripts/macos/prepare/prepare-jdk.sh") - fi - mkdir -p "$OUTPUT_DIR/runtime" - cp -R "$jdk_root" "$OUTPUT_DIR/runtime/$runtime_arch" -done - -# plugin.json names these files exactly, so a JDT LS upgrade that renames one -# fails here instead of at the user's first Java file. -launcher=$(/usr/bin/plutil -extract languageServers.0.launch.entry raw "$PLUGIN_DIR/plugin.json") -test_runner=$(/usr/bin/plutil -extract languageServers.0.hostIntegration.resources.testRunner raw "$PLUGIN_DIR/plugin.json") -for declared in "$launcher" "$test_runner" language-server/lombok/lombok.jar; do - [[ -f "$OUTPUT_DIR/$declared" ]] || { - print -u2 -- "Java Support declares $declared, which the assembled package does not contain. Update Plugins/mac/Official/JavaSupport/plugin.json for the pinned JDT LS version." - exit 1 - } -done - -# The contract forbids symbolic links inside a package. -if [[ -n "$(find "$OUTPUT_DIR" -type l -print -quit)" ]]; then - print -u2 -- "The Java Support package contains symbolic links: $(find "$OUTPUT_DIR" -type l -print -quit)" - exit 1 -fi diff --git a/Plugins/mac/Official/JavaSupport/icons/LICENSE-APACHE-2.0.txt b/Plugins/mac/Official/JavaSupport/icons/LICENSE-APACHE-2.0.txt deleted file mode 100644 index acb68f57a6..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/LICENSE-APACHE-2.0.txt +++ /dev/null @@ -1,171 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work. - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or Derivative Works - a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works that - You distribute, all copyright, patent, trademark, and attribution - notices from the Source form of the Work, excluding those notices - that do not pertain to any part of the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one of - the following places: within a NOTICE text file distributed as - part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/Plugins/mac/Official/JavaSupport/icons/NOTICE.txt b/Plugins/mac/Official/JavaSupport/icons/NOTICE.txt deleted file mode 100644 index 90eda2571c..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/NOTICE.txt +++ /dev/null @@ -1,6 +0,0 @@ -java.svg, java_dark.svg, maven.svg, and maven_dark.svg are copied from the -JetBrains IntelliJ Platform Community repository -(https://github.com/JetBrains/intellij-community), platform/icons/src/fileTypes -and plugins/maven resources, under the Apache License 2.0 in -LICENSE-APACHE-2.0.txt. spring-boot.svg and spring-boot_dark.svg are original -Lithe artwork. diff --git a/Plugins/mac/Official/JavaSupport/icons/java.svg b/Plugins/mac/Official/JavaSupport/icons/java.svg deleted file mode 100644 index 00e1a4c96f..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/java.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/Plugins/mac/Official/JavaSupport/icons/java_dark.svg b/Plugins/mac/Official/JavaSupport/icons/java_dark.svg deleted file mode 100644 index 155295f592..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/java_dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/Plugins/mac/Official/JavaSupport/icons/maven.svg b/Plugins/mac/Official/JavaSupport/icons/maven.svg deleted file mode 100644 index bb88b7a0af..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/maven.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/Plugins/mac/Official/JavaSupport/icons/maven_dark.svg b/Plugins/mac/Official/JavaSupport/icons/maven_dark.svg deleted file mode 100644 index e26ebc1f5e..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/maven_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/Plugins/mac/Official/JavaSupport/icons/spring-boot.svg b/Plugins/mac/Official/JavaSupport/icons/spring-boot.svg deleted file mode 100644 index 52020b09e3..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/spring-boot.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/Plugins/mac/Official/JavaSupport/icons/spring-boot_dark.svg b/Plugins/mac/Official/JavaSupport/icons/spring-boot_dark.svg deleted file mode 100644 index ffbc5b216c..0000000000 --- a/Plugins/mac/Official/JavaSupport/icons/spring-boot_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/Plugins/mac/Official/JavaSupport/plugin.json b/Plugins/mac/Official/JavaSupport/plugin.json deleted file mode 100644 index 7bcd18bc0f..0000000000 --- a/Plugins/mac/Official/JavaSupport/plugin.json +++ /dev/null @@ -1,670 +0,0 @@ -{ - "schemaVersion": 2, - "id": "dev.lithe.plugin.java-support", - "displayName": "Java Support", - "version": "1.1.0", - "pluginAPIVersion": 4, - "requires": {"debugAdapters": 1, "languages": 1, "languageServers": 1, "serverProcess": 1, "settings": 2, "projectGenerators": 1, "packageTrust": 1, "toolDefinitions": 1, "executableResolution": 2}, - "vendor": { - "id": "dev.lithe", - "displayName": "Lithe", - "signatureRequirement": "publisherPackage", - "bundledSignatureRequirement": "sameTeamAsHost" - }, - "permissions": ["languageServer.launch", "project.generate", "debug.launch", "debug.attach"], - "activationEvents": ["onLanguage:java", "onDebug:java"], - "toolDefinitions": [ - { - "id": "java", - "displayName": "JDK", - "icon": { - "host": "plugin" - }, - "executableLayouts": [ - { - "path": "bin/java", - "platforms": [ - "macos", - "linux" - ] - }, - { - "path": "bin/java.exe", - "platforms": [ - "windows" - ] - } - ], - "executables": [ - { - "id": "pinned", - "kind": "setting", - "settingID": "executable", - "layer": "project" - }, - { - "id": "project-request", - "kind": "toolchain", - "scope": "project" - }, - { - "id": "default", - "kind": "setting", - "settingID": "executable", - "layer": "global" - }, - { - "id": "global-request", - "kind": "toolchain", - "scope": "global" - }, - { - "id": "home", - "kind": "environment", - "variable": "JAVA_HOME", - "path": "bin/java", - "platforms": [ - "macos", - "linux" - ] - }, - { - "id": "home-windows", - "kind": "environment", - "variable": "JAVA_HOME", - "path": "bin/java.exe", - "platforms": [ - "windows" - ] - }, - { - "id": "shell", - "kind": "command", - "command": "java" - }, - { - "id": "detected", - "kind": "toolchain", - "scope": "installed" - } - ], - "version": { - "arguments": [ - "-version" - ], - "pattern": "version \\\"(?:1\\.)?(\\d+(?:\\.\\d+)*)" - }, - "homeLayouts": [ - { - "match": "*.jdk", - "home": "Contents/Home", - "platforms": [ - "macos" - ] - }, - { - "match": "*", - "home": "." - } - ], - "discovery": [ - { - "root": { - "kind": "absolute", - "path": "/Library/Java/JavaVirtualMachines" - }, - "pattern": "*.jdk", - "platforms": [ - "macos" - ] - }, - { - "root": { - "kind": "home" - }, - "pattern": "Library/Java/JavaVirtualMachines/*.jdk", - "platforms": [ - "macos" - ] - } - ], - "homeVariable": "JAVA_HOME", - "commands": [ - "java" - ], - "wrappers": [], - "exports": [ - { - "name": "JAVA_HOME", - "value": "${home}" - }, - { - "name": "LITHE_JAVA_PATH", - "value": "${executable}" - } - ], - "pathPrepend": [ - "${home}/bin" - ], - "launch": [ - "${executable}", - "${runtimeArguments}", - "-jar", - "${entry}", - "${arguments}" - ] - } - ], - "languages": [ - { - "id": "java", - "displayName": "Java", - "fileExtensions": ["java"], - "projectFileNames": ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"] - } - ], - "debugAdapters": [ - { - "id": "java", - "displayName": "Java Debugger", - "adapterID": "java", - "configurationTypes": ["java"], - "requests": ["attach"], - "selectors": [{"targetKinds": ["connection"], "languageIDs": ["java"]}], - "launch": { - "transport": "tcpLanguageServer", - "endpoint": {"languageID": "java", "command": "vscode.java.startDebugSession"} - }, - "configurations": { - "attach": {"targetBindings": {"connection": {"host": "hostName", "port": "port"}}} - } - } - ], - "settings": [ - { - "id": "heapMaxMB", - "type": "integer", - "title": "Maximum memory", - "description": "Upper bound of the Java language server's heap. Raise it for large multi-module projects.", - "default": 2048, - "minimum": 2048, - "maximum": 16384, - "unit": "MB", - "page": {"languageID": "java"}, - "section": "Language server" - }, - { - "id": "logLevel", - "type": "enum", - "title": "Language server log level", - "description": "How much the Java language server writes to its own log. Quieter levels reduce disk writes.", - "default": "WARNING", - "options": [ - { "value": "ALL", "title": "All messages" }, - { "value": "INFO", "title": "Information" }, - { "value": "WARNING", "title": "Warnings" }, - { "value": "SEVERE", "title": "Errors only" } - ], - "page": {"languageID": "java"}, - "section": "Language server" - } - ], - "languageServers": [ - { - "languageID": "java", - "languageIdentifier": "java", - "launch": { - "kind": "runtime", - "tool": "java", - "packagedRuntime": "runtime/${arch}/bin/java", - "runtimeArguments": [ - "-Xmx${setting:heapMaxMB}m", - "-Dlog.level=${setting:logLevel}", - "-Dosgi.logfile=${logDir}/jdt.log", - "-Declipse.log.include.commandline=false", - "-Declipse.log.size.max=1024", - "-Declipse.log.backup.max=2", - "-Declipse.log.level=WARNING" - ], - "entry": "language-server/plugins/org.eclipse.equinox.launcher_1.8.0.v20260804-1928.jar" - }, - "hostIntegration": { - "id": "jdt", - "capabilities": ["debug", "run", "testing"], - "resources": { - "configuration": "language-server/configuration/${arch}", - "lombokAgent": "language-server/lombok/lombok.jar", - "extensionBundleDirectories": [ - "language-server/java-debug", - "language-server/java-test/extensions" - ], - "testRunner": "language-server/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar" - } - } - } - ], - "projectGenerators": [ - { - "id": "java", - "displayName": "Java", - "description": "A Java project with no build tool, Maven, or Gradle.", - "section": "project", - "order": 10, - "icon": {"path": "icons/java.svg", "darkPath": "icons/java_dark.svg", "mode": "original"}, - "fields": [ - { - "id": "buildSystem", - "type": "enum", - "title": "Build system", - "presentation": "segmented", - "default": "maven", - "options": [ - {"value": "none", "title": "Lithe"}, - {"value": "maven", "title": "Maven"}, - {"value": "gradle", "title": "Gradle"} - ] - }, - { - "id": "gradleDsl", - "type": "enum", - "title": "Gradle DSL", - "presentation": "segmented", - "visibleWhen": {"field": "buildSystem", "equals": "gradle"}, - "options": [ - {"value": "kotlin", "title": "Kotlin"}, - {"value": "groovy", "title": "Groovy"} - ] - }, - { - "id": "jdk", - "type": "runtime", - "title": "JDK", - "runtime": "java", - "minimumVersion": "11" - }, - { - "id": "addSampleCode", - "type": "boolean", - "title": "Add sample code", - "default": true - }, - { - "id": "groupId", - "type": "text", - "title": "GroupId", - "description": "Usually the reversed domain name of your organization, such as com.example.", - "advanced": true, - "default": "org.example", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*", - "maxLength": 200, - "visibleWhen": {"field": "buildSystem", "oneOf": ["maven", "gradle"]} - }, - { - "id": "artifactId", - "type": "text", - "title": "ArtifactId", - "description": "The name of the artifact the build produces.", - "advanced": true, - "default": "${project.name}", - "pattern": "[A-Za-z0-9_][A-Za-z0-9_.-]*", - "maxLength": 200, - "visibleWhen": {"field": "buildSystem", "oneOf": ["maven", "gradle"]} - } - ], - "requirements": [ - {"languageID": "java"}, - {"buildSystemID": "maven", "when": {"field": "buildSystem", "equals": "maven"}}, - {"buildSystemID": "gradle", "when": {"field": "buildSystem", "equals": "gradle"}} - ], - "steps": [ - {"kind": "files", "source": "templates/java/plain", "when": {"field": "buildSystem", "equals": "none"}}, - { - "kind": "files", - "source": "templates/java/plain-sample", - "when": [{"field": "buildSystem", "equals": "none"}, {"field": "addSampleCode", "equals": true}] - }, - { - "kind": "files", - "source": "templates/java/plain-empty", - "when": [{"field": "buildSystem", "equals": "none"}, {"field": "addSampleCode", "equals": false}] - }, - {"kind": "files", "source": "templates/java/maven", "when": {"field": "buildSystem", "equals": "maven"}}, - {"kind": "files", "source": "templates/java/gradle-kotlin", "when": [{"field": "buildSystem", "equals": "gradle"}, {"field": "gradleDsl", "equals": "kotlin"}]}, - {"kind": "files", "source": "templates/java/gradle-groovy", "when": [{"field": "buildSystem", "equals": "gradle"}, {"field": "gradleDsl", "equals": "groovy"}]}, - { - "kind": "files", - "source": "templates/java/standard-sample", - "when": [{"field": "buildSystem", "oneOf": ["maven", "gradle"]}, {"field": "addSampleCode", "equals": true}] - }, - { - "kind": "files", - "source": "templates/java/standard-sample-main", - "target": "src/main/java/${field.groupId|package|path}", - "when": [{"field": "buildSystem", "oneOf": ["maven", "gradle"]}, {"field": "addSampleCode", "equals": true}] - }, - { - "kind": "files", - "source": "templates/java/standard-empty", - "when": [{"field": "buildSystem", "oneOf": ["maven", "gradle"]}, {"field": "addSampleCode", "equals": false}] - } - ], - "openFiles": [ - {"path": "src/Main.java", "when": [{"field": "buildSystem", "equals": "none"}, {"field": "addSampleCode", "equals": true}]}, - {"path": "src/main/java/${field.groupId|package|path}/Main.java", "when": [{"field": "buildSystem", "oneOf": ["maven", "gradle"]}, {"field": "addSampleCode", "equals": true}]} - ] - }, - { - "id": "maven-archetype", - "displayName": "Maven Archetype", - "description": "A project generated by Maven from an archetype.", - "section": "generator", - "order": 10, - "icon": {"path": "icons/maven.svg", "darkPath": "icons/maven_dark.svg", "mode": "original"}, - "fields": [ - { - "id": "jdk", - "type": "runtime", - "title": "JDK", - "description": "Maven runs with this JDK, and the new project uses it.", - "runtime": "java", - "minimumVersion": "11" - }, - { - "id": "archetype", - "type": "enum", - "title": "Archetype", - "presentation": "menu", - "default": "maven-archetype-quickstart", - "options": [ - {"value": "maven-archetype-quickstart", "title": "maven-archetype-quickstart"}, - {"value": "maven-archetype-webapp", "title": "maven-archetype-webapp"}, - {"value": "maven-archetype-simple", "title": "maven-archetype-simple"}, - {"value": "maven-archetype-j2ee-simple", "title": "maven-archetype-j2ee-simple"}, - {"value": "maven-archetype-plugin", "title": "maven-archetype-plugin"}, - {"value": "maven-archetype-archetype", "title": "maven-archetype-archetype"}, - {"value": "maven-archetype-site-simple", "title": "maven-archetype-site-simple"}, - {"value": "custom", "title": "Custom archetype…"} - ] - }, - { - "id": "archetypeGroupId", - "type": "text", - "title": "Archetype GroupId", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_-]*)*", - "maxLength": 200, - "placeholder": "org.example.archetypes", - "visibleWhen": {"field": "archetype", "equals": "custom"} - }, - { - "id": "archetypeArtifactId", - "type": "text", - "title": "Archetype ArtifactId", - "pattern": "[A-Za-z0-9_][A-Za-z0-9_.-]*", - "maxLength": 200, - "placeholder": "my-archetype", - "visibleWhen": {"field": "archetype", "equals": "custom"} - }, - { - "id": "archetypeVersion", - "type": "text", - "title": "Archetype version", - "description": "Leave empty to use the latest version Maven finds in its catalog.", - "optional": true, - "pattern": "[A-Za-z0-9_.-]+", - "maxLength": 64, - "placeholder": "Latest" - }, - { - "id": "groupId", - "type": "text", - "title": "GroupId", - "advanced": true, - "default": "org.example", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*", - "maxLength": 200 - }, - { - "id": "artifactId", - "type": "text", - "title": "ArtifactId", - "advanced": true, - "default": "${project.name}", - "pattern": "[A-Za-z0-9_][A-Za-z0-9_.-]*", - "maxLength": 200 - }, - { - "id": "version", - "type": "text", - "title": "Version", - "advanced": true, - "default": "1.0-SNAPSHOT", - "pattern": "[A-Za-z0-9_.-]+", - "maxLength": 64 - }, - { - "id": "packageName", - "type": "text", - "title": "Package", - "advanced": true, - "default": "${field.groupId}.${field.artifactId|package}", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*", - "maxLength": 200 - } - ], - "requirements": [ - {"languageID": "java"}, - {"buildSystemID": "maven"} - ], - "steps": [ - { - "kind": "command", - "command": "mvn", - "arguments": [ - "-B", - "org.apache.maven.plugins:maven-archetype-plugin:3.3.1:generate", - "-DinteractiveMode=false", - {"value": "-DarchetypeGroupId=org.apache.maven.archetypes", "when": {"field": "archetype", "notEquals": "custom"}}, - {"value": "-DarchetypeArtifactId=${field.archetype}", "when": {"field": "archetype", "notEquals": "custom"}}, - {"value": "-DarchetypeGroupId=${field.archetypeGroupId}", "when": {"field": "archetype", "equals": "custom"}}, - {"value": "-DarchetypeArtifactId=${field.archetypeArtifactId}", "when": {"field": "archetype", "equals": "custom"}}, - {"value": "-DarchetypeVersion=${field.archetypeVersion}", "when": {"field": "archetypeVersion", "notEquals": ""}}, - "-DgroupId=${field.groupId}", - "-DartifactId=${field.artifactId}", - "-Dversion=${field.version}", - "-Dpackage=${field.packageName}" - ], - "environment": {"JAVA_HOME": "${field.jdk}"}, - "collect": "${field.artifactId}", - "mayUseNetwork": true, - "timeoutSeconds": 900 - } - ], - "openFiles": ["pom.xml"] - }, - { - "id": "spring-boot", - "displayName": "Spring Boot", - "description": "A Spring Boot project from Spring Initializr.", - "section": "generator", - "order": 20, - "icon": {"path": "icons/spring-boot.svg", "darkPath": "icons/spring-boot_dark.svg", "mode": "original"}, - "fields": [ - { - "id": "serverUrl", - "type": "text", - "title": "Server URL", - "description": "The Spring Initializr server that generates the project. Change it to use a mirror or your company's own server.", - "default": "https://start.spring.io", - "pattern": "(https://[A-Za-z0-9.-]+|http://(localhost|127\\.0\\.0\\.1))(:[0-9]+)?(/[A-Za-z0-9._~-]+)*", - "maxLength": 256 - }, - { - "id": "language", - "type": "enum", - "title": "Language", - "presentation": "segmented", - "options": [ - {"value": "java", "title": "Java"}, - {"value": "kotlin", "title": "Kotlin"}, - {"value": "groovy", "title": "Groovy"} - ] - }, - { - "id": "type", - "type": "enum", - "title": "Type", - "presentation": "segmented", - "default": "maven-project", - "options": [ - {"value": "gradle-project", "title": "Gradle - Groovy"}, - {"value": "gradle-project-kotlin", "title": "Gradle - Kotlin"}, - {"value": "maven-project", "title": "Maven"} - ] - }, - { - "id": "groupId", - "type": "text", - "title": "Group", - "description": "Usually the reversed domain name of your organization, such as com.example.", - "default": "com.example", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*", - "maxLength": 200 - }, - { - "id": "artifactId", - "type": "text", - "title": "Artifact", - "description": "The name of the artifact the build produces.", - "default": "${project.name}", - "pattern": "[A-Za-z0-9_][A-Za-z0-9_.-]*", - "maxLength": 200 - }, - { - "id": "packageName", - "type": "text", - "title": "Package name", - "default": "${field.groupId}.${field.artifactId|package}", - "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*", - "maxLength": 200 - }, - { - "id": "jdk", - "type": "runtime", - "title": "JDK", - "description": "The JDK the new project uses. It must be at least the Java version below.", - "runtime": "java", - "minimumVersion": "17" - }, - { - "id": "javaVersion", - "type": "enum", - "title": "Java", - "maximumVersion": "${field.jdk.major}", - "presentation": "menu", - "default": "17", - "options": [ - {"value": "17", "title": "17"}, - {"value": "21", "title": "21"}, - {"value": "25", "title": "25"} - ] - }, - { - "id": "packaging", - "type": "enum", - "title": "Packaging", - "presentation": "segmented", - "options": [ - {"value": "jar", "title": "Jar"}, - {"value": "war", "title": "War"} - ] - }, - { - "id": "configurationFileFormat", - "type": "enum", - "title": "Configuration", - "presentation": "segmented", - "options": [ - {"value": "properties", "title": "Properties"}, - {"value": "yaml", "title": "YAML"} - ] - }, - { - "id": "bootVersion", - "type": "text", - "title": "Spring Boot", - "description": "Leave empty to use the version the server recommends.", - "optional": true, - "pattern": "[0-9]+\\.[0-9]+\\.[0-9]+(-[A-Za-z0-9.]+)?", - "maxLength": 64, - "placeholder": "Server default" - }, - { - "id": "dependencies", - "type": "multiSelect", - "title": "Dependencies", - "options": [ - {"value": "devtools", "title": "Spring Boot DevTools", "group": "Developer Tools"}, - {"value": "lombok", "title": "Lombok", "group": "Developer Tools"}, - {"value": "configuration-processor", "title": "Configuration Processor", "group": "Developer Tools"}, - {"value": "web", "title": "Spring Web", "group": "Web"}, - {"value": "webflux", "title": "Spring Reactive Web", "group": "Web"}, - {"value": "thymeleaf", "title": "Thymeleaf", "group": "Template Engines"}, - {"value": "security", "title": "Spring Security", "group": "Security"}, - {"value": "oauth2-client", "title": "OAuth2 Client", "group": "Security"}, - {"value": "oauth2-resource-server", "title": "OAuth2 Resource Server", "group": "Security"}, - {"value": "data-jpa", "title": "Spring Data JPA", "group": "SQL"}, - {"value": "jdbc", "title": "JDBC API", "group": "SQL"}, - {"value": "mybatis", "title": "MyBatis Framework", "group": "SQL"}, - {"value": "flyway", "title": "Flyway Migration", "group": "SQL"}, - {"value": "liquibase", "title": "Liquibase Migration", "group": "SQL"}, - {"value": "mysql", "title": "MySQL Driver", "group": "SQL"}, - {"value": "postgresql", "title": "PostgreSQL Driver", "group": "SQL"}, - {"value": "h2", "title": "H2 Database", "group": "SQL"}, - {"value": "data-redis", "title": "Spring Data Redis", "group": "NoSQL"}, - {"value": "data-mongodb", "title": "Spring Data MongoDB", "group": "NoSQL"}, - {"value": "data-elasticsearch", "title": "Spring Data Elasticsearch", "group": "NoSQL"}, - {"value": "amqp", "title": "Spring for RabbitMQ", "group": "Messaging"}, - {"value": "kafka", "title": "Spring for Apache Kafka", "group": "Messaging"}, - {"value": "validation", "title": "Validation", "group": "I/O"}, - {"value": "mail", "title": "Java Mail Sender", "group": "I/O"}, - {"value": "cache", "title": "Spring Cache Abstraction", "group": "I/O"}, - {"value": "quartz", "title": "Quartz Scheduler", "group": "I/O"}, - {"value": "actuator", "title": "Spring Boot Actuator", "group": "Ops"}, - {"value": "testcontainers", "title": "Testcontainers", "group": "Testing"} - ] - } - ], - "requirements": [ - {"languageID": "java", "when": {"field": "language", "equals": "java"}}, - {"languageID": "kotlin", "when": {"field": "language", "equals": "kotlin"}}, - {"languageID": "groovy", "when": {"field": "language", "equals": "groovy"}}, - {"buildSystemID": "maven", "when": {"field": "type", "equals": "maven-project"}}, - {"buildSystemID": "gradle", "when": {"field": "type", "oneOf": ["gradle-project", "gradle-project-kotlin"]}} - ], - "steps": [ - { - "kind": "archive", - "url": "${field.serverUrl}/starter.zip", - "query": [ - {"name": "type", "value": "${field.type}"}, - {"name": "language", "value": "${field.language}"}, - {"name": "bootVersion", "value": "${field.bootVersion}", "omitEmpty": true}, - {"name": "groupId", "value": "${field.groupId}"}, - {"name": "artifactId", "value": "${field.artifactId}"}, - {"name": "name", "value": "${project.name}"}, - {"name": "packageName", "value": "${field.packageName}"}, - {"name": "packaging", "value": "${field.packaging}"}, - {"name": "javaVersion", "value": "${field.javaVersion}"}, - {"name": "configurationFileFormat", "value": "${field.configurationFileFormat}"}, - {"name": "dependencies", "value": "${field.dependencies}", "omitEmpty": true} - ] - } - ], - "openFiles": [ - {"path": "pom.xml", "when": {"field": "type", "equals": "maven-project"}}, - {"path": "build.gradle", "when": {"field": "type", "equals": "gradle-project"}}, - {"path": "build.gradle.kts", "when": {"field": "type", "equals": "gradle-project-kotlin"}} - ] - } - ] -} diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/build.gradle b/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/build.gradle deleted file mode 100644 index 8c4bd098a1..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/build.gradle +++ /dev/null @@ -1,26 +0,0 @@ -plugins { - id 'java' -} - -group = '{{ field.groupId }}' -version = '1.0-SNAPSHOT' - -java { - toolchain { - languageVersion = JavaLanguageVersion.of({{ field.jdk.major }}) - } -} - -repositories { - mavenCentral() -} - -dependencies { - testImplementation platform('org.junit:junit-bom:5.13.4') - testImplementation 'org.junit.jupiter:junit-jupiter' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher' -} - -test { - useJUnitPlatform() -} diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/dot-gitignore b/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/dot-gitignore deleted file mode 100644 index 2246277a04..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/dot-gitignore +++ /dev/null @@ -1,23 +0,0 @@ -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### Lithe ### -.lithe/workspace/ - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### macOS ### -.DS_Store diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/settings.gradle b/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/settings.gradle deleted file mode 100644 index 19318abf56..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-groovy/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = '{{ field.artifactId }}' diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/build.gradle.kts b/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/build.gradle.kts deleted file mode 100644 index 578317c2d1..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/build.gradle.kts +++ /dev/null @@ -1,26 +0,0 @@ -plugins { - java -} - -group = "{{ field.groupId }}" -version = "1.0-SNAPSHOT" - -java { - toolchain { - languageVersion = JavaLanguageVersion.of({{ field.jdk.major }}) - } -} - -repositories { - mavenCentral() -} - -dependencies { - testImplementation(platform("org.junit:junit-bom:5.13.4")) - testImplementation("org.junit.jupiter:junit-jupiter") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") -} - -tasks.test { - useJUnitPlatform() -} diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/dot-gitignore b/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/dot-gitignore deleted file mode 100644 index 2246277a04..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/dot-gitignore +++ /dev/null @@ -1,23 +0,0 @@ -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### Lithe ### -.lithe/workspace/ - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### macOS ### -.DS_Store diff --git a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/settings.gradle.kts b/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/settings.gradle.kts deleted file mode 100644 index e95732bbaf..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/gradle-kotlin/settings.gradle.kts +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "{{ field.artifactId }}" diff --git a/Plugins/mac/Official/JavaSupport/templates/java/maven/dot-gitignore b/Plugins/mac/Official/JavaSupport/templates/java/maven/dot-gitignore deleted file mode 100644 index f5ed2ce8eb..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/maven/dot-gitignore +++ /dev/null @@ -1,19 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### Lithe ### -.lithe/workspace/ - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### macOS ### -.DS_Store diff --git a/Plugins/mac/Official/JavaSupport/templates/java/maven/pom.xml b/Plugins/mac/Official/JavaSupport/templates/java/maven/pom.xml deleted file mode 100644 index 3fa0e0eb16..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/maven/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - {{ field.groupId }} - {{ field.artifactId }} - 1.0-SNAPSHOT - - - {{ field.jdk.major }} - UTF-8 - - - - - org.junit.jupiter - junit-jupiter - 5.13.4 - test - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.4 - - - - - diff --git a/Plugins/mac/Official/JavaSupport/templates/java/plain-empty/src/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/plain-empty/src/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/Official/JavaSupport/templates/java/plain-sample/src/Main.java b/Plugins/mac/Official/JavaSupport/templates/java/plain-sample/src/Main.java deleted file mode 100644 index 5a5f303d1c..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/plain-sample/src/Main.java +++ /dev/null @@ -1,5 +0,0 @@ -public class Main { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} diff --git a/Plugins/mac/Official/JavaSupport/templates/java/plain/dot-gitignore b/Plugins/mac/Official/JavaSupport/templates/java/plain/dot-gitignore deleted file mode 100644 index 813b13986a..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/plain/dot-gitignore +++ /dev/null @@ -1,16 +0,0 @@ -### Lithe ### -.lithe/workspace/ -out/ - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ - -### macOS ### -.DS_Store diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/main/java/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/main/java/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/main/resources/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/main/resources/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/test/java/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/standard-empty/src/test/java/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-sample-main/Main.java b/Plugins/mac/Official/JavaSupport/templates/java/standard-sample-main/Main.java deleted file mode 100644 index 0550c627f4..0000000000 --- a/Plugins/mac/Official/JavaSupport/templates/java/standard-sample-main/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package {{ field.groupId | package }}; - -public class Main { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-sample/src/main/resources/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/standard-sample/src/main/resources/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/Official/JavaSupport/templates/java/standard-sample/src/test/java/dot-gitkeep b/Plugins/mac/Official/JavaSupport/templates/java/standard-sample/src/test/java/dot-gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Plugins/mac/README.md b/Plugins/mac/README.md index 2fdff761c0..ad1a0e17dc 100644 --- a/Plugins/mac/README.md +++ b/Plugins/mac/README.md @@ -1,23 +1,35 @@ # macOS plugins -`Official/` contains the official plugin packages for the macOS product. They -are declarative packages following -[plugin contract v1](../../shared/contracts/plugins/v1/README.md): each package -is a `plugin.json` plus the resources it declares. Lithe reads the declaration, -verifies the package, and launches the declared language server and run/test -processes itself. No plugin code is loaded into the Lithe process, so a package -does not need to be rebuilt for each Lithe release; compatibility is decided by -`pluginAPIVersion`. - -| Package | Distribution | Language server | -| --- | --- | --- | -| `JavaSupport` | Publisher-signed download; sealed transition copy until both architectures are listed | JDT LS packaged with Lithe; New Project entries for Java, Maven Archetype, and Spring Boot ([project generators](../../shared/contracts/plugins/v1/README.md#project-generators)) | +The macOS product no longer bundles or builds any official plugin. Every +language, build-tool and VCS plugin is a community plugin maintained and +released in its own repository and listed in +[Lithe Store](https://github.com/Lithe-IDEA/Lithe-store). Plugins are +declarative packages following +[plugin contract v1](../../shared/contracts/plugins/v1/README.md); plugin +authors follow [lithe-plugin-docs](https://github.com/Lithe-IDEA/lithe-plugin-docs). + +`Plugins/marketplace/index.json` stays as the empty official index that app +packaging embeds; it lists no official plugin. + +## Java, Maven and Gradle moved to Lithe Store + +Java Support is no longer an official plugin and the app no longer bundles a +JDK or JDT LS. The community plugins bring their own language server and +runtime resources: + +| Plugin ID | Repository | +| --- | --- | +| `io.github.lithe-idea.java-support` | [lithe-plugin-java](https://github.com/Lithe-IDEA/lithe-plugin-java) | +| `io.github.lithe-idea.maven-support` | [lithe-plugin-maven](https://github.com/Lithe-IDEA/lithe-plugin-maven) | +| `io.github.lithe-idea.gradle-support` | [lithe-plugin-gradle](https://github.com/Lithe-IDEA/lithe-plugin-gradle) | + +The retired official ID `dev.lithe.plugin.java-support` stays in +`OfficialPluginCatalog` as moved to the community, like Go and PHP below. ## Go and PHP moved to Lithe Store Go Support and PHP Support are no longer official plugins. They are community -plugins in their own repositories and are listed in -[Lithe Store](https://github.com/Lithe-IDEA/Lithe-store): +plugins in their own repositories: | Plugin ID | Repository | Language server | | --- | --- | --- | @@ -27,13 +39,13 @@ plugins in their own repositories and are listed in The PHP plugin does not bundle Intelephense because the Intelephense licence does not allow redistribution. -The retired official IDs `dev.lithe.plugin.go-support` and -`dev.lithe.plugin.php-support` stay in `OfficialPluginCatalog` so an installed -copy is still verified against its publisher signature. Plugin Management shows -those copies as moved to the community, offers no official update, and asks the -user to uninstall them before installing the community version. Their last -manifests live in `macos/Tests/LitheTests/Fixtures/RetiredOfficialPlugins/` for -tests only. +The retired official IDs `dev.lithe.plugin.go-support`, +`dev.lithe.plugin.php-support` and `dev.lithe.plugin.java-support` stay in +`OfficialPluginCatalog` so an installed copy is still verified against its +publisher signature. Plugin Management shows those copies as moved to the +community, offers no official update, and asks the user to uninstall them +before installing the community version. The last Go and PHP manifests live in +`macos/Tests/LitheTests/Fixtures/RetiredOfficialPlugins/` for tests only. ## Cargo community plugin @@ -59,59 +71,4 @@ its manifest fixture, and the Core tests; the SDK's sample provider (`sample-vcs`) lives with the SDK in [lithe-plugin-docs](https://github.com/Lithe-IDEA/lithe-plugin-docs). -## Downloadable official plugins - -Java Support now has a two-architecture release configuration, with automatic -publication disabled (`releaseEnabled: false`) until the host trust capability -and migration are released. No downloadable official plugin is listed yet: -`Plugins/marketplace/index.json` is empty. The release flow (`scripts/plugins/build-official-plugins.sh`, -`scripts/plugins/official-plugin-releases.mjs`, and -`.github/workflows/release-official-plugins.yml`) is kept for future official -plugins. A new one gets its own directory under `Official/`, its own tag series -(`plugin--v`), and an entry in `official-plugins.json`. - -A publisher-signed package requires `LITHE_PLUGIN_PACKAGE_PRIVATE_KEY`, a -base64-encoded 32-byte Ed25519 private key whose public key matches the embedded -publisher key; debug builds skip these packages when the key is absent, and a -direct package build fails instead of producing an unsigned package. Keep the -key in a protected file or environment variable and never commit it. - -## Local development packages - -This section is for official plugins built in this repository. Community plugin -authors follow [lithe-plugin-docs](https://github.com/Lithe-IDEA/lithe-plugin-docs) -instead. - -Plugin authors can test without the publisher key. Build an unsigned -development package with `--development-unsigned`, then install it from disk in -a debug build of Lithe: - -```sh -scripts/plugins/build-official-plugins.sh --configuration debug \ - --triple arm64-apple-macosx --plugin-id \ - --development-unsigned --output /tmp/lithe-dev-plugins -``` - -The package has no `lithe-plugin-signature.json`. Plugin Management records it -as an unsigned development package and replaces it when the same version is -installed again. Release builds of Lithe refuse to load it, and the flag is -rejected for release plugin builds. A package that does contain a signature -document is always verified, whichever way it was installed. - Plugins never delete user tools or project files. - -Java Support's manifest now requires `packageTrust: 1`: user-installed copies -require a publisher signature, while the explicitly pinned bundled copy can -rely on the host application's seal. `--bundled-only` selects that application -build; an ordinary standalone release build must carry the publisher signature. -Existing hosts without this capability refuse the new version before download. - -Java publication remains paused (`releaseEnabled: false`). App assembly retains -the transition copy until the checked-in official index lists a compatible -release at or above `bundledUntilPublishedVersion` with both architecture -archives. Then `--bundled-only` omits Java and app packaging skips its downloads. -The same index is embedded in the app. `LITHE_OFFICIAL_PLUGIN_INDEX` (app build) -and `--marketplace-index` (plugin build) select an explicit read-only build input; -test fixture indexes must never be published. Installation preserves saved -choices and settings; missing Java support has Marketplace and offline disk -installation entry points. diff --git a/Plugins/marketplace/official-plugins.json b/Plugins/marketplace/official-plugins.json deleted file mode 100644 index 241f08f8ab..0000000000 --- a/Plugins/marketplace/official-plugins.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "schemaVersion": 1, - "description": "Official plugins released through their own tag series and listed in index.json. A plugin is released when its packageDirectory changes and its plugin.json version has no tag yet; changing the directory without a new version fails CI.", - "plugins": [ - { - "id": "dev.lithe.plugin.java-support", - "releaseEnabled": false, - "bundledUntilPublishedVersion": "1.1.0", - "tagPrefix": "plugin-java-support-v", - "packageDirectory": "Plugins/mac/Official/JavaSupport", - "inputPaths": ["third_party/jdtls/manifest.json", "third_party/jdk/manifest.json", "scripts/macos/prepare/prepare-jdtls.sh", "scripts/macos/prepare/prepare-jdk.sh", "scripts/plugins/build-official-plugins.sh"], - "assets": [ - {"assetName": "Lithe-Java-Support-{version}-darwin-arm64.zip", "platforms": ["darwin-arm64"], "arch": "arm64"}, - {"assetName": "Lithe-Java-Support-{version}-darwin-x64.zip", "platforms": ["darwin-x64"], "arch": "x86_64"} - ], - "index": { - "name": "Java Support", - "author": "Lithe", - "repository": "https://github.com/1lck/Lithe-IDEA", - "description": "Java language support with JDT LS, Lombok, debug and test extensions, a language-server JDK, and project generators.", - "tags": ["java", "language"], - "license": "Multiple; see bundled third-party licenses" - } - } - ] -} diff --git a/docs/assets/java-installation-guidance/README.md b/docs/assets/java-installation-guidance/README.md deleted file mode 100644 index 4e1a18ffa3..0000000000 --- a/docs/assets/java-installation-guidance/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Java Support 安装引导的界面验证 - -这些截图对应 #1483 的 review 补验,由真实 SwiftUI/AppKit 视图生成。 -通知使用现有通知模型和展开操作;新建项目页使用真实 Core 生成器目录、空插件 -清单和隔离偏好。市场动作由测试记录,不会联网、安装插件、创建项目或执行工具。 - -| 场景 | 浅色 | 深色 | -| --- | --- | --- | -| Java 缺包通知,展开全文 | [截图](java-missing-notification-light.png) | [截图](java-missing-notification-dark.png) | -| 新建项目页的 Java/Maven/Spring 模板安装入口 | [截图](java-new-project-light.png) | [截图](java-new-project-dark.png) | - -本轮修复改变缺包判断,没有调整布局。卸载后的 `.removed` 快照在重启后允许 -显示通知;仍有待重启变更的副本、已安装但禁用的副本继续使用原管理流程。 -回归另外通过真实包存储执行安装、卸载、启动准备和重新扫描,核对移除快照下的 -Java 文件与 Maven 项目提示,不把单独渲染通知当作完整卸载流程的证明。 - -复验入口: - -```bash -LITHE_JAVA_GUIDANCE_CAPTURE_DIR="$PWD/.artifacts/test-stability/java-installation-guidance" \ - ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh \ - -- --filter 'PluginBundledPublisherTrustTests|PluginInstallationGuidancePresentationTests' -``` - -测试使用默认桌面隔离模式,仍创建并关闭真实窗口。截图证明原生视图的绘制和 -按钮动作,不证明桌面合成、真实市场下载、正式双架构发行或 Windows 独立分发。 - -本轮计时报告 `pr1483-review-macos` 共 75 项测试、5 组套件通过;完整冷编译与测试 -分别执行,最终测试仍使用原有计时上限和默认桌面隔离。 diff --git a/docs/assets/java-installation-guidance/java-missing-notification-dark.png b/docs/assets/java-installation-guidance/java-missing-notification-dark.png deleted file mode 100644 index c4502a1709..0000000000 Binary files a/docs/assets/java-installation-guidance/java-missing-notification-dark.png and /dev/null differ diff --git a/docs/assets/java-installation-guidance/java-missing-notification-light.png b/docs/assets/java-installation-guidance/java-missing-notification-light.png deleted file mode 100644 index 7a5a967e0e..0000000000 Binary files a/docs/assets/java-installation-guidance/java-missing-notification-light.png and /dev/null differ diff --git a/docs/assets/java-installation-guidance/java-new-project-dark.png b/docs/assets/java-installation-guidance/java-new-project-dark.png deleted file mode 100644 index 63a57188a9..0000000000 Binary files a/docs/assets/java-installation-guidance/java-new-project-dark.png and /dev/null differ diff --git a/docs/assets/java-installation-guidance/java-new-project-light.png b/docs/assets/java-installation-guidance/java-new-project-light.png deleted file mode 100644 index 2142af9c31..0000000000 Binary files a/docs/assets/java-installation-guidance/java-new-project-light.png and /dev/null differ diff --git a/macos/Resources/en.lproj/Localizable.strings b/macos/Resources/en.lproj/Localizable.strings index 0fb33b7698..3a441969ff 100644 --- a/macos/Resources/en.lproj/Localizable.strings +++ b/macos/Resources/en.lproj/Localizable.strings @@ -27,6 +27,8 @@ "%@ disabled" = "%@ disabled"; "%@ does not include %@; Lithe renders those characters with %@ and the system font." = "%@ does not include %@; Lithe renders those characters with %@ and the system font."; "%@ does not provide archived conversations." = "%@ does not provide archived conversations."; +"%@ does not provide debugging" = "%@ does not provide debugging"; +"%@ does not provide project execution" = "%@ does not provide project execution"; "%@ does not support Debug yet" = "%@ does not support Debug yet"; "%@ does not support running the current file directly. Use a project run configuration." = "%@ does not support running the current file directly. Use a project run configuration."; "%@ enabled" = "%@ enabled"; @@ -57,6 +59,7 @@ "%@ 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 execution provider" = "%@ returned an invalid execution provider"; "%@ returned an invalid language-server provider." = "%@ returned an invalid language-server provider."; "%@ returned an unexpected response." = "%@ returned an unexpected response."; "%@ sent messages too quickly, so some were not shown." = "%@ sent messages too quickly, so some were not shown."; @@ -196,7 +199,7 @@ "A skill with this directory name already exists. Existing skills are never overwritten." = "A skill with this directory name already exists. Existing skills are never overwritten."; "A stable release installation is already in progress." = "A stable release installation is already in progress."; "A task %@ started before Lithe last closed unexpectedly is still running" = "A task %@ started before Lithe last closed unexpectedly is still running"; -"A terminal is busy when a program other than the shell still runs in it, such as a Spring Boot app, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." = "A terminal is busy when a program other than the shell still runs in it, such as a Spring Boot app, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it."; +"A terminal is busy when a program other than the shell still runs in it, such as a dev server, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." = "A terminal is busy when a program other than the shell still runs in it, such as a dev server, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it."; "A terminal session is still running." = "A terminal session is still running."; "A test path must stay inside the current workspace." = "A test path must stay inside the current workspace."; "A unique filename could not be created for the image" = "A unique filename could not be created for the image"; @@ -290,7 +293,6 @@ "Address or expression" = "Address or expression"; "Addresses that bypass the proxy, separated by commas. Entries support wildcard domains such as *.internal.example." = "Addresses that bypass the proxy, separated by commas. Entries support wildcard domains such as *.internal.example."; "Adds Go language-server integration, formatting, running, and test support." = "Adds Go language-server integration, formatting, running, and test support."; -"Adds Java language intelligence through the Eclipse JDT language server, with Lombok, debugging, and test support. Ships its own Java runtime." = "Adds Java language intelligence through the Eclipse JDT language server, with Lombok, debugging, and test support. Ships its own Java runtime."; "Adds language-server integration and formatting support." = "Adds language-server integration and formatting support."; "Adds language-server integration, formatting, running, and test support." = "Adds language-server integration, formatting, running, and test support."; "Adds to the pull request conversation without an approval decision." = "Adds to the pull request conversation without an approval decision."; @@ -348,7 +350,7 @@ "Allow Recreating File" = "Allow Recreating File"; "Allow fast-forward" = "Allow fast-forward"; "Allow insecure HTTP" = "Allow insecure HTTP"; -"Allow project environment and Maven configuration changes" = "Allow project environment and Maven configuration changes"; +"Allow project environment and build configuration changes" = "Allow project environment and build configuration changes"; "Allow run, build, reload and stop (executes project code)" = "Allow run, build, reload and stop (executes project code)"; "Allow the Agent to continue?" = "Allow the Agent to continue?"; "Allow “%@” to open a terminal?" = "Allow “%@” to open a terminal?"; @@ -451,9 +453,7 @@ "Authentication must be a JSON object containing an OPENAI_API_KEY string." = "Authentication must be a JSON object containing an OPENAI_API_KEY string."; "Author" = "Author"; "Authorize in your browser" = "Authorize in your browser"; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant." = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant."; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes." = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes."; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes. Enabled plugins can also use this project grant." = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes. Enabled plugins can also use this project grant."; +"Authorize this project to expose its environment, build tools, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant." = "Authorize this project to expose its environment, build tools, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant."; "Auto" = "Auto"; "Auto-compact at" = "Auto-compact at"; "Auto-compact must not be larger than the context length." = "Auto-compact must not be larger than the context length."; @@ -945,7 +945,7 @@ "Configure dependency search paths" = "Configure dependency search paths"; "Configure editor and project behavior" = "Configure editor and project behavior"; "Configure in Settings" = "Configure in Settings"; -"Configure project JDK and Maven…" = "Configure project JDK and Maven…"; +"Configure runtime environment…" = "Configure runtime environment…"; "Configured" = "Configured"; "Configured remote name" = "Configured remote name"; "Configure…" = "Configure…"; @@ -961,12 +961,12 @@ "Connect to Debug Adapter…" = "Connect to Debug Adapter…"; "Connect to Running JVM" = "Connect to Running JVM"; "Connect to Running JVM…" = "Connect to Running JVM…"; -"Connect to an already running DAP server using the active file's installed debugger. This is not a JVM JDWP or gdbserver port. No proxy or tunnel is created." = "Connect to an already running DAP server using the active file's installed debugger. This is not a JVM JDWP or gdbserver port. No proxy or tunnel is created."; +"Connect to an already running DAP server using the active file's installed debugger. This is not a gdbserver port. No proxy or tunnel is created." = "Connect to an already running DAP server using the active file's installed debugger. This is not a gdbserver port. No proxy or tunnel is created."; "Connect to an external debug adapter?" = "Connect to an external debug adapter?"; "Connect to databases, browse schemas, edit data, run SQL, and manage backups from the Database workspace." = "Connect to databases, browse schemas, edit data, run SQL, and manage backups from the Database workspace."; "Connect to running JVM" = "Connect to running JVM"; "Connected" = "Connected"; -"Connected agents can change the project JDK, Maven and run configuration settings." = "Connected agents can change the project JDK, Maven and run configuration settings."; +"Connected agents can change the project toolchain, build and run configuration settings." = "Connected agents can change the project toolchain, build and run configuration settings."; "Connected agents can run, build, reload and stop the project. Commands execute project code, so enable this only for projects you trust." = "Connected agents can run, build, reload and stop the project. Commands execute project code, so enable this only for projects you trust."; "Connected agents can use the configuration below while this project is open." = "Connected agents can use the configuration below while this project is open."; "Connected as @%@" = "Connected as @%@"; @@ -1003,6 +1003,7 @@ "Controls how Lithe's ordinary Fetch updates submodules." = "Controls how Lithe's ordinary Fetch updates submodules."; "Controls how Lithe's ordinary Fetch updates submodules. Inherit follows Git's fetch.recurseSubmodules setting." = "Controls how Lithe's ordinary Fetch updates submodules. Inherit follows Git's fetch.recurseSubmodules setting."; "Controls where Step Into stops. Changes apply to the next Java debug session." = "Controls where Step Into stops. Changes apply to the next Java debug session."; +"Controls where Step Into stops. Changes apply to the next debug session of this debugger." = "Controls where Step Into stops. Changes apply to the next debug session of this debugger."; "Controls whether Lithe's ordinary Fetch removes stale remote branches." = "Controls whether Lithe's ordinary Fetch removes stale remote branches."; "Conventional Commits" = "Conventional Commits"; "Conversation" = "Conversation"; @@ -1114,11 +1115,13 @@ "Could not restore local history" = "Could not restore local history"; "Could not restore project history" = "Could not restore project history"; "Could not restore this project history entry" = "Could not restore this project history entry"; +"Could not save %@" = "Could not save %@"; "Could not save %@: permission denied. Check the file and parent folder permissions. Your edits are still unsaved." = "Could not save %@: permission denied. Check the file and parent folder permissions. Your edits are still unsaved."; "Could not save access to the selected background image." = "Could not save access to the selected background image."; "Could not save project indexing settings. Your previous settings remain unchanged." = "Could not save project indexing settings. Your previous settings remain unchanged."; "Could not save service selection" = "Could not save service selection"; "Could not save the connections: %@" = "Could not save the connections: %@"; +"Could not start debugging" = "Could not start debugging"; "Could not start the Java test result listener: %@" = "Could not start the Java test result listener: %@"; "Could not start the MCP command. Check its executable and runtime." = "Could not start the MCP command. Check its executable and runtime."; "Could not verify the commit outcome. Review before retrying." = "Could not verify the commit outcome. Review before retrying."; @@ -1667,7 +1670,7 @@ "Filter problems by severity" = "Filter problems by severity"; "Filter results" = "Filter results"; "Filter route, controller, or method" = "Filter route, controller, or method"; -"Filter: server:jdtls level>=warn -event:lsp.trace.received /regex/ op:c0ffee" = "Filter: server:jdtls level>=warn -event:lsp.trace.received /regex/ op:c0ffee"; +"Filter: server:gopls level>=warn -event:lsp.trace.received /regex/ op:c0ffee" = "Filter: server:gopls level>=warn -event:lsp.trace.received /regex/ op:c0ffee"; "Find" = "Find"; "Find Action" = "Find Action"; "Find Action…" = "Find Action…"; @@ -1987,7 +1990,6 @@ "Install ACP adapters, check the runtime, and manage local or custom providers." = "Install ACP adapters, check the runtime, and manage local or custom providers."; "Install AutoBuild" = "Install AutoBuild"; "Install Codex CLI to discover its skills." = "Install Codex CLI to discover its skills."; -"Install Java Support for Java, Maven and Spring templates…" = "Install Java Support for Java, Maven and Spring templates…"; "Install Node.js and npm before installing the adapter." = "Install Node.js and npm before installing the adapter."; "Install PHP Support Plugin" = "Install PHP Support Plugin"; "Install PHP Support from a signed plugin package." = "Install PHP Support from a signed plugin package."; @@ -2067,9 +2069,6 @@ "Java Application" = "Java Application"; "Java Run marker request failed" = "Java Run marker request failed"; "Java SDK" = "Java SDK"; -"Java Stepping Filters" = "Java Stepping Filters"; -"Java Stepping Filters…" = "Java Stepping Filters…"; -"Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept." = "Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept."; "Java entries appear after the Java language service lists runnable classes." = "Java entries appear after the Java language service lists runnable classes."; "Java entries could not be refreshed" = "Java entries could not be refreshed"; "Java entry-point freshness check failed" = "Java entry-point freshness check failed"; @@ -2322,7 +2321,6 @@ "Look Up Location" = "Look Up Location"; "Looked in: %@" = "Looked in: %@"; "Looking for Git…" = "Looking for Git…"; -"Looking for installed JDKs…" = "Looking for installed JDKs…"; "Looking for installed tools…" = "Looking for installed tools…"; "Looking up the location sends this address to ipinfo.io. Lithe does this only when you click Look Up." = "Looking up the location sends this address to ipinfo.io. Lithe does this only when you click Look Up."; "Low" = "Low"; @@ -2577,7 +2575,6 @@ "No Hooks yet." = "No Hooks yet."; "No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory." = "No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory."; "No JDK is configured for this project." = "No JDK is configured for this project."; -"No JDK was found. Install a JDK, then reopen this window." = "No JDK was found. Install a JDK, then reopen this window."; "No JVM performance samples received for 10 seconds." = "No JVM performance samples received for 10 seconds."; "No Java navigation results" = "No Java navigation results"; "No Java problems" = "No Java problems"; @@ -2800,6 +2797,7 @@ "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/` or `/*` to hide a folder and everything in it; start with `**/` to match at any depth. Other patterns hide matching files.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/*` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe built-in patterns below always apply." = "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/` or `/*` to hide a folder and everything in it; start with `**/` to match at any depth. Other patterns hide matching files.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/*` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe built-in patterns below always apply."; "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/`, `/*` or `/**` to hide a folder and everything in it; start with `**/` to match at any depth. A pattern without a trailing slash only hides files: `.lithe` hides a file named .lithe, not the folder.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/**` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe list starts with the built-in patterns. Delete one to show those files again; type it back to hide them." = "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/`, `/*` or `/**` to hide a folder and everything in it; start with `**/` to match at any depth. A pattern without a trailing slash only hides files: `.lithe` hides a file named .lithe, not the folder.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/**` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe list starts with the built-in patterns. Delete one to show those files again; type it back to hide them."; "One pattern per line, for example org.mockito.* or com.example.generated.*" = "One pattern per line, for example org.mockito.* or com.example.generated.*"; +"One pattern per line. The debugger defines the pattern syntax." = "One pattern per line. The debugger defines the pattern syntax."; "One pattern per line: `*.log`, `**/.*/`, `.*`, `cache/`. Only affects this Search Everywhere window." = "One pattern per line: `*.log`, `**/.*/`, `.*`, `cache/`. Only affects this Search Everywhere window."; "One sentence focused on the main change" = "One sentence focused on the main change"; "One test: %@" = "One test: %@"; @@ -3554,7 +3552,7 @@ "Run configuration" = "Run configuration"; "Run configuration changed while saving. Reload and try again." = "Run configuration changed while saving. Reload and try again."; "Run configurations" = "Run configurations"; -"Run configurations and Maven goals started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." = "Run configurations and Maven goals started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first."; +"Run configurations and build tasks started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." = "Run configurations and build tasks started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first."; "Run configurations are unavailable. Enable the execution module and try again." = "Run configurations are unavailable. Enable the execution module and try again."; "Run configurations inherit the project JDK and Maven unless overridden below." = "Run configurations inherit the project JDK and Maven unless overridden below."; "Run configurations may be out of date" = "Run configurations may be out of date"; @@ -3663,7 +3661,6 @@ "Search Everywhere (Double Shift)" = "Search Everywhere (Double Shift)"; "Search Everywhere…" = "Search Everywhere…"; "Search Hooks" = "Search Hooks"; -"Search JDKs" = "Search JDKs"; "Search MCP servers" = "Search MCP servers"; "Search MCP servers — GitHub, browsers, documentation…" = "Search MCP servers — GitHub, browsers, documentation…"; "Search Paths: %@" = "Search Paths: %@"; @@ -3961,7 +3958,7 @@ "Source Repository" = "Source Repository"; "Source Roots" = "Source Roots"; "Sources Root" = "Sources Root"; -"Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:jdtls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results." = "Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:jdtls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results."; +"Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:gopls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results." = "Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:gopls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results."; "Speed" = "Speed"; "Spring Boot" = "Spring Boot"; "Spring Endpoints" = "Spring Endpoints"; @@ -4043,6 +4040,8 @@ "Step into" = "Step into"; "Step out" = "Step out"; "Step over" = "Step over"; +"Stepping Filters" = "Stepping Filters"; +"Stepping Filters…" = "Stepping Filters…"; "Stepping by instruction" = "Stepping by instruction"; "Sticky scroll" = "Sticky scroll"; "Stop" = "Stop"; @@ -4326,6 +4325,7 @@ "The featured MCP catalog could not be loaded." = "The featured MCP catalog could not be loaded."; "The field value does not match its declaration or exceeds its size limit." = "The field value does not match its declaration or exceeds its size limit."; "The field value is invalid or exceeds 1024 UTF-8 bytes." = "The field value is invalid or exceeds 1024 UTF-8 bytes."; +"The file changed while preparing to start. Try again." = "The file changed while preparing to start. Try again."; "The file could not be decoded with the selected or detected encoding. Check its encoding or open it in an external editor." = "The file could not be decoded with the selected or detected encoding. Check its encoding or open it in an external editor."; "The file could not be opened as a text document." = "The file could not be opened as a text document."; "The file could not be read. Check its availability and try again." = "The file could not be read. Check its availability and try again."; @@ -4337,7 +4337,6 @@ "The file or its hard links changed while saving. Your edits are still unsaved. Check the file and save again." = "The file or its hard links changed while saving. Your edits are still unsaved. Check the file and save again."; "The file system that holds the home directory." = "The file system that holds the home directory."; "The file will be created when you save." = "The file will be created when you save."; -"The framework did not open its JVM debug port before the deadline. Check the Run output." = "The framework did not open its JVM debug port before the deadline. Check the Run output."; "The function call was cancelled." = "The function call was cancelled."; "The generated message will replace the text currently in the editor." = "The generated message will replace the text currently in the editor."; "The generated title or description would replace text you already entered." = "The generated title or description would replace text you already entered."; @@ -4565,7 +4564,7 @@ "These overrides affect only this run configuration. Clear a path to inherit the project environment." = "These overrides affect only this run configuration. Clear a path to inherit the project environment."; "These processes left their terminal or tool to keep running in the background, like daemons and dev servers. Checked items end when Lithe quits; unchecked items keep running." = "These processes left their terminal or tool to keep running in the background, like daemons and dev servers. Checked items end when Lithe quits; unchecked items keep running."; "These programs were started in Lithe before it closed unexpectedly. Checked items are ended now; unchecked items keep running and are not tracked anymore." = "These programs were started in Lithe before it closed unexpectedly. Checked items are ended now; unchecked items keep running and are not tracked anymore."; -"These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, JVM dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests." = "These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, JVM dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests."; +"These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, build tool dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests." = "These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, build tool dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests."; "Thinking" = "Thinking"; "Thinking level" = "Thinking level"; "Thinking process" = "Thinking process"; @@ -5147,7 +5146,7 @@ "debug.tcp.confirmBody" = "The debug adapter at %1$@ can access your debugging data. Plain TCP is not encrypted or authenticated. Connect only over a trusted network or a tunnel you configured."; "debug.tcp.confirmTitle" = "Connect to an external debug adapter?"; "debug.tcp.declined" = "The debug adapter connection was not approved."; -"debug.tcp.help" = "Connect to an already running DAP server using the active file's installed debugger. This is not a JVM JDWP or gdbserver port. No proxy or tunnel is created."; +"debug.tcp.help" = "Connect to an already running DAP server using the active file's installed debugger. This is not a gdbserver port. No proxy or tunnel is created."; "debug.tcp.invalidArguments" = "Enter a JSON object of adapter arguments no larger than 256 KiB."; "debug.tcp.invalidEndpoint" = "Enter a valid debug adapter host and a port between 1 and 65535."; "debug.tcp.launchRequest" = "Launch Request"; @@ -5404,8 +5403,8 @@ "logs.window.fields" = "Fields"; "logs.window.filterChannel" = "filter channel"; "logs.window.filterErrorAtLldLld" = "Filter error at %1$lld–%2$lld: %3$@"; -"logs.window.filterHelp" = "Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:jdtls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results."; -"logs.window.filterServerJdtlsLevelWarnEventLspTraceReceivedRegexOpC0ffee" = "Filter: server:jdtls level>=warn -event:lsp.trace.received /regex/ op:c0ffee"; +"logs.window.filterHelp" = "Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:gopls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results."; +"logs.window.filterServerJdtlsLevelWarnEventLspTraceReceivedRegexOpC0ffee" = "Filter: server:gopls level>=warn -event:lsp.trace.received /regex/ op:c0ffee"; "logs.window.followHelp" = "Live follow appends logs in their recorded order and scrolls to the latest record. The writer delivers short batches; bursts reflect real activity. Scrolling up pauses automatic scrolling while collection continues. Resume to return to the latest logs."; "logs.window.following" = "Following"; "logs.window.hideThisEvent" = "Hide this event"; @@ -5469,8 +5468,7 @@ "mac.workbench.unhide" = "Unhide"; "macOS could not prepare the update disk image. Download the release manually and try again." = "macOS could not prepare the update disk image. Download the release manually and try again."; "macOS could not prepare the update disk image. Open the Release page and install it manually." = "macOS could not prepare the update disk image. Open the Release page and install it manually."; -"macos.buildProvider.jvmDebugPortTimeout" = "The framework did not open its JVM debug port before the deadline. Check the Run output."; -"macos.buildProvider.jvmDebugRemoteUnavailable" = "Framework service debugging is not available in remote workspaces yet."; +"macos.buildProvider.serviceDebugRemoteUnavailable" = "Framework service debugging is not available in remote workspaces yet."; "macos.native.savedRunMigrationNeedsUpdate" = "Some saved run configurations cannot be migrated yet. Keep the existing files and retry after updating Lithe and its build plugin."; "main Java" = "main Java"; "main resources" = "main resources"; @@ -5507,7 +5505,6 @@ "native.aSpringBootProjectFromSpringInitializr" = "A Spring Boot project from Spring Initializr."; "native.aStableReleaseInstallationIsAlreadyInProgress" = "A stable release installation is already in progress."; "native.aTaskStartedBeforeLitheLastClosedUnexpectedlyIsStillRunning" = "A task %1$@ started before Lithe last closed unexpectedly is still running"; -"native.aTerminalIsBusyWhenAProgramOtherThanTheShellStillRunsInItSuchAsASpringBootAppNa88ac3e46a" = "A terminal is busy when a program other than the shell still runs in it, such as a Spring Boot app, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it."; "native.aTerminalSessionIsStillRunning" = "A terminal session is still running."; "native.aTestPathMustStayInsideTheCurrent" = "A test path must stay inside the current workspace."; "native.aUniqueFilenameCouldNotBeCreatedFor" = "A unique filename could not be created for the image"; @@ -5569,7 +5566,6 @@ "native.additions" = "Additions"; "native.address" = "Address"; "native.addsGoLanguageServerIntegrationFormattingRunningAndTestSupport" = "Adds Go language-server integration, formatting, running, and test support."; -"native.addsJavaLanguageIntelligenceThroughTheEclipseJDTLanguageServerWithLombokDebuggb2eae07f8b" = "Adds Java language intelligence through the Eclipse JDT language server, with Lombok, debugging, and test support. Ships its own Java runtime."; "native.addsLanguageServerIntegrationAndFormattingSupport" = "Adds language-server integration and formatting support."; "native.addsLanguageServerIntegrationFormattingRunningAndTestSupport" = "Adds language-server integration, formatting, running, and test support."; "native.addsToThePullRequestConversationWithoutAnApprovalDecision" = "Adds to the pull request conversation without an approval decision."; @@ -5649,7 +5645,6 @@ "native.allow" = "Allow"; "native.allowFastForward" = "Allow fast-forward"; "native.allowInsecureHTTP" = "Allow insecure HTTP"; -"native.allowProjectEnvironmentAndMavenConfigurationChanges" = "Allow project environment and Maven configuration changes"; "native.allowRecreatingFile" = "Allow Recreating File"; "native.allowRunBuildReloadAndStopExecutesProjectCode" = "Allow run, build, reload and stop (executes project code)"; "native.allowTheAgentToContinue" = "Allow the Agent to continue?"; @@ -5759,9 +5754,6 @@ "native.authenticationMustBeAJSONObjectContainingAnOPENAIAPIKEYString" = "Authentication must be a JSON object containing an OPENAI_API_KEY string."; "native.author" = "Author"; "native.authorizeInYourBrowser" = "Authorize in your browser"; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnec6e24e4763f" = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes."; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnecb6f617e865" = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes. Enabled plugins can also use this project grant."; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnece4d5e32bce" = "Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant."; "native.auto" = "Auto"; "native.autoCompactAboveContext" = "Auto-compact must not be larger than the context length."; "native.autoCompactAt" = "Auto-compact at"; @@ -6216,7 +6208,7 @@ "native.configureDependencySearchPaths" = "Configure dependency search paths"; "native.configureEditorAndProjectBehavior" = "Configure editor and project behavior"; "native.configureInSettings" = "Configure in Settings"; -"native.configureProjectJDKAndMaven" = "Configure project JDK and Maven…"; +"native.configureRuntimeEnvironment" = "Configure runtime environment…"; "native.configured" = "Configured"; "native.configuredRemoteName" = "Configured remote name"; "native.confirmDeletion" = "Confirm deletion"; @@ -6232,7 +6224,6 @@ "native.connectToRunningJVM2" = "Connect to Running JVM…"; "native.connectToRunningJvm" = "Connect to Running JVM"; "native.connected" = "Connected"; -"native.connectedAgentsCanChangeTheProjectJDKMavenAndRunConfigurationSettings" = "Connected agents can change the project JDK, Maven and run configuration settings."; "native.connectedAgentsCanRunBuildReloadAndStopTheProjectCommandsExecuteProjectCodeSoE6d273dab37" = "Connected agents can run, build, reload and stop the project. Commands execute project code, so enable this only for projects you trust."; "native.connectedAgentsCanUseTheConfigurationBelowWhileThisProjectIsOpen" = "Connected agents can use the configuration below while this project is open."; "native.connectedAs" = "Connected as @%1$@"; @@ -6269,6 +6260,7 @@ "native.controlsHowLitheSOrdinaryFetchUpdatesSubmodules" = "Controls how Lithe's ordinary Fetch updates submodules."; "native.controlsHowLitheSOrdinaryFetchUpdatesSubmodulesInheritFollowsGitSFetchRecurseSubmodulesSetting" = "Controls how Lithe's ordinary Fetch updates submodules. Inherit follows Git's fetch.recurseSubmodules setting."; "native.controlsWhereStepIntoStopsChangesApplyTo" = "Controls where Step Into stops. Changes apply to the next Java debug session."; +"native.controlsWhereStepIntoStopsNextSession" = "Controls where Step Into stops. Changes apply to the next debug session of this debugger."; "native.controlsWhetherLitheSOrdinaryFetchRemovesStaleRemoteBranches" = "Controls whether Lithe's ordinary Fetch removes stale remote branches."; "native.conventionalCommits" = "Conventional Commits"; "native.conversation" = "Conversation"; @@ -6352,9 +6344,11 @@ "native.couldNotRestoreLocalHistory" = "Could not restore local history"; "native.couldNotRestoreProjectHistory" = "Could not restore project history"; "native.couldNotRestoreThisProjectHistoryEntry" = "Could not restore this project history entry"; +"native.couldNotSave" = "Could not save %1$@"; "native.couldNotSaveAccessToTheSelectedBackgroundImage" = "Could not save access to the selected background image."; "native.couldNotSaveServiceSelection" = "Could not save service selection"; "native.couldNotSaveTheConnections" = "Could not save the connections: %1$@"; +"native.couldNotStartDebugging" = "Could not start debugging"; "native.couldNotStartTheJavaTestResultListener" = "Could not start the Java test result listener: %1$@"; "native.couldNotStartTheMcpCommandCheckItsExecutableAndRuntime" = "Could not start the MCP command. Check its executable and runtime."; "native.couldNotVerifySavedProjectEnvironment" = "Could not verify the saved project environment settings. The previous preferences have been kept when possible."; @@ -6593,6 +6587,8 @@ "native.documentation" = "Documentation"; "native.doesNotIncludeLitheRendersThoseCharactersWithAndTheSystemFont" = "%1$@ does not include %2$@; Lithe renders those characters with %3$@ and the system font."; "native.doesNotProvideArchivedConversations" = "%1$@ does not provide archived conversations."; +"native.doesNotProvideDebugging" = "%1$@ does not provide debugging"; +"native.doesNotProvideProjectExecution" = "%1$@ does not provide project execution"; "native.doesNotSupportDebugYet" = "%1$@ does not support Debug yet"; "native.doesNotSupportRunningTheCurrentFileDirectly" = "%1$@ does not support running the current file directly. Use a project run configuration."; "native.donTAllow" = "Don’t Allow"; @@ -7342,8 +7338,6 @@ "native.javaServiceIsPreparing" = "Java service is preparing"; "native.javaServiceIsReady" = "Java service is ready"; "native.javaServicePreparationTimedOut" = "Java service preparation timed out"; -"native.javaSteppingFilters" = "Java Stepping Filters"; -"native.javaSteppingFilters2" = "Java Stepping Filters…"; "native.javaTestDiscoveryIsNotSupportedByThis" = "Java test discovery is not supported by this language server."; "native.javaWorkspacePreparationCancelled" = "Java workspace preparation cancelled"; "native.jdkHome" = "JDK Home"; @@ -7624,7 +7618,6 @@ "native.lookUpLocation" = "Look Up Location"; "native.lookedIn" = "Looked in: %1$@"; "native.lookingForGit" = "Looking for Git…"; -"native.lookingForInstalledJDKs" = "Looking for installed JDKs…"; "native.lookingForInstalledTools" = "Looking for installed tools…"; "native.lookingUpTheLocationSendsThisAddressToIpinfoIoLitheDoesThisOnlyWhenYouClickLookUp" = "Looking up the location sends this address to ipinfo.io. Lithe does this only when you click Look Up."; "native.low" = "Low"; @@ -7929,7 +7922,6 @@ "native.noItems" = "No items"; "native.noJDKFoundSetJAVAHOMEInstallAJDKOrChooseAJDKDirectory" = "No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory."; "native.noJDKIsConfiguredForThisProject" = "No JDK is configured for this project."; -"native.noJDKWasFoundInstallAJDKThenReopenThisWindow" = "No JDK was found. Install a JDK, then reopen this window."; "native.noJVMPerformanceSamplesReceivedFor10Seconds" = "No JVM performance samples received for 10 seconds."; "native.noJavaNavigationResults" = "No Java navigation results"; "native.noJavaProblems" = "No Java problems"; @@ -8086,6 +8078,7 @@ "native.onePathPerLineRelativePathsAreResolvedFromTheWorkspace" = "One path per line. Relative paths are resolved from the workspace."; "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx35941b6a99" = "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/`, `/*` or `/**` to hide a folder and everything in it; start with `**/` to match at any depth. A pattern without a trailing slash only hides files: `.lithe` hides a file named .lithe, not the folder.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/**` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe list starts with the built-in patterns. Delete one to show those files again; type it back to hide them."; "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx4f7ef7b38a" = "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/` or `/*` to hide a folder and everything in it; start with `**/` to match at any depth. Other patterns hide matching files.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/*` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe built-in patterns below always apply."; +"native.onePatternPerLineDebuggerDefinesSyntax" = "One pattern per line. The debugger defines the pattern syntax."; "native.onePatternPerLineForExampleOrgMockito" = "One pattern per line, for example org.mockito.* or com.example.generated.*"; "native.onePatternPerLineLogCacheOnlyAffectsThisSearchEverywhereWindow" = "One pattern per line: `*.log`, `**/.*/`, `.*`, `cache/`. Only affects this Search Everywhere window."; "native.oneSentenceFocusedOnTheMainChange" = "One sentence focused on the main change"; @@ -8719,6 +8712,7 @@ "native.returnToStable" = "Return to Stable"; "native.returnToStable.variant2" = "Return to Stable?"; "native.returnToTheWelcomeScreen" = "Return to the Welcome screen"; +"native.returnedAnInvalidExecutionProvider" = "%1$@ returned an invalid execution provider"; "native.returnedAnInvalidLanguageServerProvider" = "%1$@ returned an invalid language-server provider."; "native.returnedAnUnexpectedResponse" = "%1$@ returned an unexpected response."; "native.returnedHTTP" = "%1$@ returned HTTP %2$@."; @@ -8773,7 +8767,6 @@ "native.runConfiguration.variant2" = "Run configuration"; "native.runConfiguration.variant3" = "run configuration"; "native.runConfigurations" = "Run configurations"; -"native.runConfigurationsAndMavenGoalsStartedInLitheTheyAlwaysStopWhenTheirProjectOrWi2085dbd360" = "Run configurations and Maven goals started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first."; "native.runConfigurationsAreUnavailableEnableTheExecutionModuleAndTryAgain" = "Run configurations are unavailable. Enable the execution module and try again."; "native.runConfigurationsInheritTheProjectJDKAndMavenUnlessOverriddenBelow" = "Run configurations inherit the project JDK and Maven unless overridden below."; "native.runConfigurationsMayBeOutOfDate" = "Run configurations may be out of date"; @@ -8879,7 +8872,6 @@ "native.searchHooks" = "Search Hooks"; "native.searchImplementations" = "Search implementations"; "native.searchInProject" = "Search in Project"; -"native.searchJDKs" = "Search JDKs"; "native.searchMcpServers" = "Search MCP servers"; "native.searchMcpServersGithubBrowsersDocumentation" = "Search MCP servers — GitHub, browsers, documentation…"; "native.searchOfficialMicrosoftAndAzureDocumentationAndCodeSamples" = "Search official Microsoft and Azure documentation and code samples."; @@ -9206,6 +9198,8 @@ "native.stepLldOfLld" = "Step %1$lld of %2$lld"; "native.stepOut" = "Step out"; "native.stepOver" = "Step over"; +"native.steppingFilters" = "Stepping Filters"; +"native.steppingFilters2" = "Stepping Filters…"; "native.stopActiveExecution" = "Stop active execution"; "native.stopAllServers" = "Stop All Servers"; "native.stopAllServices" = "Stop all services"; @@ -9410,6 +9404,7 @@ "native.theFeaturedMcpCatalogCouldNotBeLoaded" = "The featured MCP catalog could not be loaded."; "native.theFieldValueDoesNotMatchItsDeclarationOrExceedsItsSizeLimit" = "The field value does not match its declaration or exceeds its size limit."; "native.theFieldValueIsInvalidOrExceeds1024UTF8Bytes" = "The field value is invalid or exceeds 1024 UTF-8 bytes."; +"native.theFileChangedWhilePreparingToStartTryAgain" = "The file changed while preparing to start. Try again."; "native.theFileCouldNotBeOpenedAsATextDocument" = "The file could not be opened as a text document."; "native.theFileHasChangedSinceTheAgentEditOpenTheDiffAndReviewItManually" = "The file has changed since the Agent edit. Open the diff and review it manually."; "native.theFileHasUnsavedChangesSaveItFirstBecauseTheBrowserShowsTheSavedFile" = "The file has unsaved changes. Save it first, because the browser shows the saved file."; @@ -10239,8 +10234,6 @@ "plugin.terminal.permission" = "Open and manage its own native terminals, retaining bounded display history for reopening"; "plugin.terminal.running" = "The plugin terminal is still running."; "plugin.terminal.unavailable" = "The terminal is unavailable."; -"plugins.java.installNotice" = "Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept."; -"plugins.java.installTemplates" = "Install Java Support for Java, Maven and Spring templates…"; "plugins.title" = "Plugins"; "ports %@" = "ports %@"; "project Maven Wrapper" = "project Maven Wrapper"; @@ -10334,6 +10327,9 @@ "settings.mac.projects" = "Projects"; "settings.mac.restoreDefaults" = "Restore Defaults"; "settings.mac.shortcuts" = "Keyboard shortcuts"; +"settings.mcp.allowConfigure.info" = "Connected agents can change the project toolchain, build and run configuration settings."; +"settings.mcp.allowConfigure.title" = "Allow project environment and build configuration changes"; +"settings.mcp.info.projectAccess" = "Authorize this project to expose its environment, build tools, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant."; "settings.network.checkFailed" = "The connection check failed."; "settings.network.connectionSucceeded" = "Connection succeeded in %1$@ ms."; "settings.network.credentialsUnavailable" = "Proxy credentials cannot be saved in this build."; @@ -10348,7 +10344,7 @@ "settings.network.info.password" = "Leave empty when the proxy does not require authentication. The password is stored in the Keychain, never in settings files."; "settings.network.info.passwordSaved" = "A password is saved for its original proxy. An empty field reuses it only when the proxy type, address, port and username match."; "settings.network.info.port" = "The proxy server's port, for example 7890."; -"settings.network.info.scope" = "These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, JVM dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests."; +"settings.network.info.scope" = "These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, build tool dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests."; "settings.network.info.type" = "HTTP proxies carry HTTPS requests through CONNECT. SOCKS5 tunnels every protocol and port."; "settings.network.info.username" = "Leave empty when the proxy does not require authentication."; "settings.network.mode.custom" = "Custom proxy server"; @@ -10367,6 +10363,8 @@ "settings.network.type.socks5" = "SOCKS5"; "settings.network.username" = "Username"; "settings.noResults" = "No settings found"; +"settings.processTermination.info.runConfigurations" = "Run configurations and build tasks started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first."; +"settings.processTermination.info.terminals" = "A terminal is busy when a program other than the shell still runs in it, such as a dev server, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it."; "settings.search" = "Search settings"; "stash restore" = "stash restore"; "svg.preview" = "Preview"; diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 23283ecedd..cd90a27632 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -27,6 +27,8 @@ "%@ disabled" = "%@ 已停用"; "%@ does not include %@; Lithe renders those characters with %@ and the system font." = "%@ 不包含%@;Lithe 会用 %@ 和系统字体显示这些字符。"; "%@ does not provide archived conversations." = "%@ 不支持归档会话。"; +"%@ does not provide debugging" = "%@ 没有提供调试功能"; +"%@ does not provide project execution" = "%@ 没有提供项目运行功能"; "%@ does not support Debug yet" = "%@ 暂不支持调试"; "%@ does not support running the current file directly. Use a project run configuration." = "%@ 不支持直接运行当前文件。请使用项目运行配置。"; "%@ enabled" = "%@ 已启用"; @@ -57,6 +59,7 @@ "%@ 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 execution provider" = "%@ 返回了无效的运行提供者"; "%@ returned an invalid language-server provider." = "%@ 返回了无效的语言服务器 Provider。"; "%@ returned an unexpected response." = "%@ 返回了无法识别的响应。"; "%@ sent messages too quickly, so some were not shown." = "%@ 发送消息过快,部分消息未显示。"; @@ -196,7 +199,7 @@ "A skill with this directory name already exists. Existing skills are never overwritten." = "同名技能目录已存在,不会覆盖已有技能。"; "A stable release installation is already in progress." = "正在进行正式版安装,请等待完成。"; "A task %@ started before Lithe last closed unexpectedly is still running" = "Lithe 上次意外关闭前,%@ 启动的一个任务仍在运行"; -"A terminal is busy when a program other than the shell still runs in it, such as a Spring Boot app, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." = "终端里除了 Shell 本身还有程序在运行时(例如 Spring Boot 应用、npm run dev 或放到后台的任务),这个终端就是“运行中”。空闲终端总是直接关闭,不会询问。结束一个终端会结束其中启动的所有程序。"; +"A terminal is busy when a program other than the shell still runs in it, such as a dev server, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." = "终端里除了 Shell 本身还有程序在运行时(例如开发服务器、npm run dev 或放到后台的任务),这个终端就是“运行中”。空闲终端总是直接关闭,不会询问。结束一个终端会结束其中启动的所有程序。"; "A terminal session is still running." = "终端会话仍在运行。"; "A test path must stay inside the current workspace." = "测试路径必须保持在当前工作区内。"; "A unique filename could not be created for the image" = "无法为图片创建唯一的文件名"; @@ -290,7 +293,6 @@ "Address or expression" = "地址或表达式"; "Addresses that bypass the proxy, separated by commas. Entries support wildcard domains such as *.internal.example." = "不经过代理的地址,用逗号分隔。支持通配符域名,例如 *.internal.example。"; "Adds Go language-server integration, formatting, running, and test support." = "提供 Go 语言服务器、格式化、运行和测试支持。"; -"Adds Java language intelligence through the Eclipse JDT language server, with Lombok, debugging, and test support. Ships its own Java runtime." = "通过 Eclipse JDT 语言服务器提供 Java 代码智能,并支持 Lombok、调试和测试。自带 Java 运行时。"; "Adds language-server integration and formatting support." = "提供语言服务器和格式化支持。"; "Adds language-server integration, formatting, running, and test support." = "提供语言服务器、格式化、运行和测试支持。"; "Adds to the pull request conversation without an approval decision." = "在拉取请求中发表评论,不作出批准决定。"; @@ -348,7 +350,7 @@ "Allow Recreating File" = "允许重新创建文件"; "Allow fast-forward" = "允许快进"; "Allow insecure HTTP" = "允许不安全的 HTTP"; -"Allow project environment and Maven configuration changes" = "允许修改项目环境和 Maven 配置"; +"Allow project environment and build configuration changes" = "允许修改项目环境和构建配置"; "Allow run, build, reload and stop (executes project code)" = "允许运行、构建、重载和停止(会执行项目代码)"; "Allow the Agent to continue?" = "允许 Agent 继续吗?"; "Allow “%@” to open a terminal?" = "允许“%@”打开终端?"; @@ -451,9 +453,7 @@ "Authentication must be a JSON object containing an OPENAI_API_KEY string." = "认证配置必须是包含 OPENAI_API_KEY 字符串的 JSON 对象。"; "Author" = "作者"; "Authorize in your browser" = "在浏览器中授权"; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant." = "授权当前项目后,已连接的 Agent 可以访问环境、Maven、运行配置与输出。输出可能包含敏感项目数据。关闭项目或退出 Lithe 时访问结束,并移除项目级服务器注册。已启用的插件也可以使用该授权。"; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes." = "仅授权此项目,连接的 Agent 可以读取环境、Maven、运行配置和输出。输出可能包含项目敏感信息。关闭项目或退出 Lithe 后连接失效。"; -"Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes. Enabled plugins can also use this project grant." = "仅授权此项目,连接的 Agent 可以读取环境、Maven、运行配置和输出。输出可能包含项目敏感信息。关闭项目或退出 Lithe 后连接失效。已启用的插件也可使用此项目授权。"; +"Authorize this project to expose its environment, build tools, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant." = "授权当前项目后,已连接的 Agent 可以访问项目环境、构建工具、运行配置与输出。输出可能包含敏感项目数据。关闭项目或退出 Lithe 时访问结束,并移除项目级服务器注册。已启用的插件也可以使用该授权。"; "Auto" = "自动"; "Auto-compact at" = "自动压缩阈值"; "Auto-compact must not be larger than the context length." = "自动压缩阈值不能大于上下文长度。"; @@ -945,7 +945,7 @@ "Configure dependency search paths" = "配置依赖搜索路径"; "Configure editor and project behavior" = "配置编辑器和项目行为"; "Configure in Settings" = "在设置中配置"; -"Configure project JDK and Maven…" = "配置项目 JDK 和 Maven…"; +"Configure runtime environment…" = "配置运行环境…"; "Configured" = "已配置"; "Configured remote name" = "已配置的远程仓库名称"; "Configure…" = "配置…"; @@ -961,12 +961,12 @@ "Connect to Debug Adapter…" = "连接调试适配器…"; "Connect to Running JVM" = "连接到运行中的 JVM"; "Connect to Running JVM…" = "连接到运行中的 JVM…"; -"Connect to an already running DAP server using the active file's installed debugger. This is not a JVM JDWP or gdbserver port. No proxy or tunnel is created." = "使用当前文件已安装的调试器连接已运行的 DAP 服务。这不是 JVM JDWP 或 gdbserver 端口。不会创建代理或隧道。"; +"Connect to an already running DAP server using the active file's installed debugger. This is not a gdbserver port. No proxy or tunnel is created." = "使用当前文件已安装的调试器连接已运行的 DAP 服务。这不是 gdbserver 端口。不会创建代理或隧道。"; "Connect to an external debug adapter?" = "连接到外部调试适配器?"; "Connect to databases, browse schemas, edit data, run SQL, and manage backups from the Database workspace." = "连接数据库、浏览结构、编辑数据、运行 SQL,并在数据库工作区中管理备份。"; "Connect to running JVM" = "连接到正在运行的 JVM"; "Connected" = "已连接"; -"Connected agents can change the project JDK, Maven and run configuration settings." = "连接的 Agent 可以修改项目 JDK、Maven 和运行配置。"; +"Connected agents can change the project toolchain, build and run configuration settings." = "连接的 Agent 可以修改项目工具链、构建和运行配置。"; "Connected agents can run, build, reload and stop the project. Commands execute project code, so enable this only for projects you trust." = "连接的 Agent 可以运行、构建、重载和停止项目。命令会执行项目代码,请仅对信任的项目开启。"; "Connected agents can use the configuration below while this project is open." = "项目打开期间,连接的 Agent 可以使用下方配置。"; "Connected as @%@" = "已连接为 @%@"; @@ -1003,6 +1003,7 @@ "Controls how Lithe's ordinary Fetch updates submodules." = "控制 Lithe 普通 Fetch 如何更新子模块。"; "Controls how Lithe's ordinary Fetch updates submodules. Inherit follows Git's fetch.recurseSubmodules setting." = "控制 Lithe 普通 Fetch 如何更新子模块。“继承”表示遵循 Git 的 fetch.recurseSubmodules 设置。"; "Controls where Step Into stops. Changes apply to the next Java debug session." = "控制“步入”的停止位置。更改将在下一次 Java 调试会话中生效。"; +"Controls where Step Into stops. Changes apply to the next debug session of this debugger." = "控制“步入”的停止位置。更改将在此调试器的下一次调试会话中生效。"; "Controls whether Lithe's ordinary Fetch removes stale remote branches." = "控制 Lithe 普通 Fetch 是否清理失效的远程分支。"; "Conventional Commits" = "Conventional Commits 规范"; "Conversation" = "讨论"; @@ -1114,11 +1115,13 @@ "Could not restore local history" = "无法恢复本地历史"; "Could not restore project history" = "无法恢复项目历史"; "Could not restore this project history entry" = "无法恢复此项目历史记录"; +"Could not save %@" = "无法保存 %@"; "Could not save %@: permission denied. Check the file and parent folder permissions. Your edits are still unsaved." = "无法保存 %@:权限不足。请检查文件及其父文件夹的权限,编辑内容尚未保存。"; "Could not save access to the selected background image." = "无法保存所选背景图片的访问权限。"; "Could not save project indexing settings. Your previous settings remain unchanged." = "无法保存项目索引设置,原有设置未改变。"; "Could not save service selection" = "无法保存服务勾选状态"; "Could not save the connections: %@" = "无法保存连接:%@"; +"Could not start debugging" = "无法开始调试"; "Could not start the Java test result listener: %@" = "无法启动 Java 测试结果监听器:%@"; "Could not start the MCP command. Check its executable and runtime." = "无法启动 MCP 命令,请检查程序及所需运行时。"; "Could not verify the commit outcome. Review before retrying." = "无法确认提交结果,请检查后再重试。"; @@ -1667,7 +1670,7 @@ "Filter problems by severity" = "按严重级别筛选问题"; "Filter results" = "筛选结果"; "Filter route, controller, or method" = "筛选路由、控制器或方法"; -"Filter: server:jdtls level>=warn -event:lsp.trace.received /regex/ op:c0ffee" = "过滤:server:jdtls level>=warn -event:lsp.trace.received /正则/ op:c0ffee"; +"Filter: server:gopls level>=warn -event:lsp.trace.received /regex/ op:c0ffee" = "过滤:server:gopls level>=warn -event:lsp.trace.received /正则/ op:c0ffee"; "Find" = "查找"; "Find Action" = "查找操作"; "Find Action…" = "查找操作…"; @@ -1987,7 +1990,6 @@ "Install ACP adapters, check the runtime, and manage local or custom providers." = "安装 ACP 适配器、检查运行环境,管理本机配置或自定义供应商。"; "Install AutoBuild" = "安装 AutoBuild"; "Install Codex CLI to discover its skills." = "请先安装 Codex CLI,再查看它发现的技能。"; -"Install Java Support for Java, Maven and Spring templates…" = "安装 Java Support,获取 Java、Maven 和 Spring 项目模板…"; "Install Node.js and npm before installing the adapter." = "请先安装 Node.js 和 npm,再安装适配器。"; "Install PHP Support Plugin" = "安装 PHP Support 插件"; "Install PHP Support from a signed plugin package." = "请从已签名的插件包安装 PHP Support。"; @@ -2067,9 +2069,6 @@ "Java Application" = "Java 应用"; "Java Run marker request failed" = "Java 运行标记请求失败"; "Java SDK" = "Java SDK"; -"Java Stepping Filters" = "Java 步进过滤器"; -"Java Stepping Filters…" = "Java 步进过滤器…"; -"Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept." = "Java Support 现已独立安装。请从插件市场安装,或使用“从磁盘安装”导入离线包。原有 Java 设置会保留。"; "Java entries appear after the Java language service lists runnable classes." = "Java 语言服务列出可运行的类之后,Java 入口才会出现。"; "Java entries could not be refreshed" = "无法刷新 Java 入口"; "Java entry-point freshness check failed" = "Java 入口点时效性检查失败"; @@ -2322,7 +2321,6 @@ "Look Up Location" = "查询地区"; "Looked in: %@" = "已查找:%@"; "Looking for Git…" = "正在查找 Git…"; -"Looking for installed JDKs…" = "正在查找已安装的 JDK…"; "Looking for installed tools…" = "正在查找已安装的工具…"; "Looking up the location sends this address to ipinfo.io. Lithe does this only when you click Look Up." = "查询地区会把这个地址发送给 ipinfo.io。只有你点击“查询地区”时 Lithe 才会这样做。"; "Low" = "低"; @@ -2577,7 +2575,6 @@ "No Hooks yet." = "还没有 Hook。"; "No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory." = "未找到 JDK。请设置 JAVA_HOME、安装 JDK,或选择 JDK 目录。"; "No JDK is configured for this project." = "此项目没有配置 JDK。"; -"No JDK was found. Install a JDK, then reopen this window." = "未找到 JDK。请安装 JDK 后重新打开此窗口。"; "No JVM performance samples received for 10 seconds." = "10 秒内未收到 JVM 性能采样。"; "No Java navigation results" = "没有 Java 导航结果"; "No Java problems" = "没有 Java 问题"; @@ -2800,6 +2797,7 @@ "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/` or `/*` to hide a folder and everything in it; start with `**/` to match at any depth. Other patterns hide matching files.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/*` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe built-in patterns below always apply." = "每行一条规则,不区分大小写。规则使用通配符,是正则表达式的简化写法:`*` 匹配任意字符,`?` 匹配单个字符。\n以 `/` 或 `/*` 结尾表示隐藏整个文件夹及其内容,以 `**/` 开头表示匹配任意层级;其他写法隐藏匹配的文件。\n示例:\n`**/dist/` — 任意层级的 dist 文件夹\n`.lithe/*` — 项目根目录下的 .lithe 文件夹\n`*.log` — 所有 .log 文件\n`docs/*.md` — docs 下的 Markdown 文件\n下方的内置规则始终生效。"; "One pattern per line, case-insensitive. Patterns use wildcards, a simplified form of regular expressions: `*` matches any characters and `?` matches one.\nEnd a pattern with `/`, `/*` or `/**` to hide a folder and everything in it; start with `**/` to match at any depth. A pattern without a trailing slash only hides files: `.lithe` hides a file named .lithe, not the folder.\nExamples:\n`**/dist/` — every dist folder\n`.lithe/**` — the .lithe folder in the project root\n`*.log` — all log files\n`docs/*.md` — Markdown files in docs\nThe list starts with the built-in patterns. Delete one to show those files again; type it back to hide them." = "每行一条规则,不区分大小写。规则使用通配符,是正则表达式的简化写法:`*` 匹配任意字符,`?` 匹配单个字符。\n以 `/`、`/*` 或 `/**` 结尾表示隐藏整个文件夹及其内容,以 `**/` 开头表示匹配任意层级。不带结尾斜杠的规则只隐藏文件:`.lithe` 隐藏名为 .lithe 的文件,而不是文件夹。\n示例:\n`**/dist/` — 任意层级的 dist 文件夹\n`.lithe/**` — 项目根目录下的 .lithe 文件夹\n`*.log` — 所有 .log 文件\n`docs/*.md` — docs 下的 Markdown 文件\n列表开头是内置规则。删掉一行即可重新显示这些文件,再输入回来就会重新隐藏。"; "One pattern per line, for example org.mockito.* or com.example.generated.*" = "每行一个模式,例如 org.mockito.* 或 com.example.generated.*"; +"One pattern per line. The debugger defines the pattern syntax." = "每行一个模式,模式语法由调试器定义。"; "One pattern per line: `*.log`, `**/.*/`, `.*`, `cache/`. Only affects this Search Everywhere window." = "每行一个表达式:`*.log`、`**/.*/`、`.*`、`cache/`。仅影响当前双 Shift 搜索窗口。"; "One sentence focused on the main change" = "聚焦主要更改的一句话"; "One test: %@" = "单个测试:%@"; @@ -3554,7 +3552,7 @@ "Run configuration" = "运行配置"; "Run configuration changed while saving. Reload and try again." = "保存期间运行配置已更改。请重新加载后再试。"; "Run configurations" = "运行配置"; -"Run configurations and Maven goals started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." = "在 Lithe 中启动的运行配置和 Maven 目标。项目或窗口关闭、或退出 Lithe 时,它们总会连同自己启动的进程一起停止;这里只决定 Lithe 是否先列出并询问。"; +"Run configurations and build tasks started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." = "在 Lithe 中启动的运行配置和构建任务。项目或窗口关闭、或退出 Lithe 时,它们总会连同自己启动的进程一起停止;这里只决定 Lithe 是否先列出并询问。"; "Run configurations are unavailable. Enable the execution module and try again." = "运行配置暂不可用,请启用执行模块后重试。"; "Run configurations inherit the project JDK and Maven unless overridden below." = "运行配置默认继承项目 JDK 和 Maven,可在下方为当前配置单独覆盖。"; "Run configurations may be out of date" = "运行配置可能已过期"; @@ -3663,7 +3661,6 @@ "Search Everywhere (Double Shift)" = "全局搜索(双击 Shift)"; "Search Everywhere…" = "全局搜索…"; "Search Hooks" = "搜索 Hook"; -"Search JDKs" = "搜索 JDK"; "Search MCP servers" = "搜索 MCP 服务器"; "Search MCP servers — GitHub, browsers, documentation…" = "搜索 MCP 服务器 — GitHub、浏览器、文档…"; "Search Paths: %@" = "搜索路径:%@"; @@ -3961,7 +3958,7 @@ "Source Repository" = "源码仓库"; "Source Roots" = "源码目录"; "Sources Root" = "源代码根目录"; -"Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:jdtls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results." = "空格分隔的条件同时满足(AND)。level>=warn 包含 WARN 和 ERROR;level:info 精确匹配级别。event:、channel: 和 op: 按前缀匹配;server:jdtls 和 key:value 匹配字段中的文本。/正则/ 搜索消息,忽略大小写;前置 - 排除该条件。含空格的值用双引号包住。左侧通道、级别按钮和时间范围与表达式取交集;语法错误时保留上一次有效结果。"; +"Spaces combine conditions with AND. level>=warn includes WARN and ERROR; level:info is exact. event:, channel: and op: match prefixes. server:gopls and key:value match field substrings. /regex/ searches messages, ignoring case; - excludes a condition. Use double quotes around values containing spaces. Channel, level and time controls also intersect with the expression. Invalid expressions keep the last valid results." = "空格分隔的条件同时满足(AND)。level>=warn 包含 WARN 和 ERROR;level:info 精确匹配级别。event:、channel: 和 op: 按前缀匹配;server:gopls 和 key:value 匹配字段中的文本。/正则/ 搜索消息,忽略大小写;前置 - 排除该条件。含空格的值用双引号包住。左侧通道、级别按钮和时间范围与表达式取交集;语法错误时保留上一次有效结果。"; "Speed" = "速度"; "Spring Boot" = "Spring Boot"; "Spring Endpoints" = "Spring 接口"; @@ -4043,6 +4040,8 @@ "Step into" = "单步进入"; "Step out" = "单步跳出"; "Step over" = "单步跳过"; +"Stepping Filters" = "步进过滤器"; +"Stepping Filters…" = "步进过滤器…"; "Stepping by instruction" = "按指令单步"; "Sticky scroll" = "固定显示作用域标题"; "Stop" = "停止"; @@ -4326,6 +4325,7 @@ "The featured MCP catalog could not be loaded." = "无法加载内置 MCP 精选目录。"; "The field value does not match its declaration or exceeds its size limit." = "字段值不符合声明或超过大小限制。"; "The field value is invalid or exceeds 1024 UTF-8 bytes." = "字段值无效或超过 1024 个 UTF-8 字节。"; +"The file changed while preparing to start. Try again." = "准备启动时文件已改变,请重试。"; "The file could not be decoded with the selected or detected encoding. Check its encoding or open it in an external editor." = "无法按所选或自动识别的编码解码文件。请检查文件编码,或使用外部编辑器打开。"; "The file could not be opened as a text document." = "无法将该文件作为文本文档打开。"; "The file could not be read. Check its availability and try again." = "无法读取文件。请检查文件是否可访问后重试。"; @@ -4337,7 +4337,6 @@ "The file or its hard links changed while saving. Your edits are still unsaved. Check the file and save again." = "保存期间文件或硬链接发生了变化。编辑内容尚未保存,请检查文件后重新保存。"; "The file system that holds the home directory." = "主目录所在的文件系统。"; "The file will be created when you save." = "保存时将创建此文件。"; -"The framework did not open its JVM debug port before the deadline. Check the Run output." = "框架未在期限内开放 JVM 调试端口,请查看运行输出。"; "The function call was cancelled." = "函数调用已取消。"; "The generated message will replace the text currently in the editor." = "生成的提交信息将替换编辑器中的当前文本。"; "The generated title or description would replace text you already entered." = "生成的标题或描述可能会替换你已经输入的内容。"; @@ -4565,7 +4564,7 @@ "These overrides affect only this run configuration. Clear a path to inherit the project environment." = "以下覆盖值仅影响当前运行配置。清空路径可恢复继承项目环境。"; "These processes left their terminal or tool to keep running in the background, like daemons and dev servers. Checked items end when Lithe quits; unchecked items keep running." = "这些进程已脱离所在的终端或工具,在后台独立运行,例如守护进程和开发服务器。勾选的项目会在 Lithe 退出时结束;未勾选的项目继续运行。"; "These programs were started in Lithe before it closed unexpectedly. Checked items are ended now; unchecked items keep running and are not tracked anymore." = "这些程序是 Lithe 意外关闭前在 Lithe 中启动的。勾选的项目会立即结束;未勾选的项目继续运行,Lithe 之后不再管理它们。"; -"These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, JVM dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests." = "这些设置作用于 Lithe 自身的请求:插件市场、GitHub 和 AI 提供方。终端命令、Git、JVM 依赖下载和内置更新器使用各自的网络设置;更新器始终跟随系统代理。更改对新请求生效。"; +"These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, build tool dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests." = "这些设置作用于 Lithe 自身的请求:插件市场、GitHub 和 AI 提供方。终端命令、Git、构建工具的依赖下载和内置更新器使用各自的网络设置;更新器始终跟随系统代理。更改对新请求生效。"; "Thinking" = "思考"; "Thinking level" = "思考强度"; "Thinking process" = "思考过程"; @@ -5147,7 +5146,7 @@ "debug.tcp.confirmBody" = "位于 %1$@ 的调试适配器可以访问你的调试数据。普通 TCP 不提供加密或身份认证。请仅通过可信网络或你自行配置的隧道连接。"; "debug.tcp.confirmTitle" = "连接到外部调试适配器?"; "debug.tcp.declined" = "未批准连接调试适配器。"; -"debug.tcp.help" = "使用当前文件已安装的调试器连接已运行的 DAP 服务。这不是 JVM JDWP 或 gdbserver 端口。不会创建代理或隧道。"; +"debug.tcp.help" = "使用当前文件已安装的调试器连接已运行的 DAP 服务。这不是 gdbserver 端口。不会创建代理或隧道。"; "debug.tcp.invalidArguments" = "请输入不超过 256 KiB 的适配器参数 JSON 对象。"; "debug.tcp.invalidEndpoint" = "请输入有效的调试适配器主机和 1 到 65535 之间的端口。"; "debug.tcp.launchRequest" = "启动请求"; @@ -5404,8 +5403,8 @@ "logs.window.fields" = "字段"; "logs.window.filterChannel" = "只看此通道"; "logs.window.filterErrorAtLldLld" = "过滤错误,位置 %1$lld–%2$lld:%3$@"; -"logs.window.filterHelp" = "空格分隔的条件同时满足(AND)。level>=warn 包含 WARN 和 ERROR;level:info 精确匹配级别。event:、channel: 和 op: 按前缀匹配;server:jdtls 和 key:value 匹配字段中的文本。/正则/ 搜索消息,忽略大小写;前置 - 排除该条件。含空格的值用双引号包住。左侧通道、级别按钮和时间范围与表达式取交集;语法错误时保留上一次有效结果。"; -"logs.window.filterServerJdtlsLevelWarnEventLspTraceReceivedRegexOpC0ffee" = "过滤:server:jdtls level>=warn -event:lsp.trace.received /正则/ op:c0ffee"; +"logs.window.filterHelp" = "空格分隔的条件同时满足(AND)。level>=warn 包含 WARN 和 ERROR;level:info 精确匹配级别。event:、channel: 和 op: 按前缀匹配;server:gopls 和 key:value 匹配字段中的文本。/正则/ 搜索消息,忽略大小写;前置 - 排除该条件。含空格的值用双引号包住。左侧通道、级别按钮和时间范围与表达式取交集;语法错误时保留上一次有效结果。"; +"logs.window.filterServerJdtlsLevelWarnEventLspTraceReceivedRegexOpC0ffee" = "过滤:server:gopls level>=warn -event:lsp.trace.received /正则/ op:c0ffee"; "logs.window.followHelp" = "实时跟随按记录顺序追加日志并滚动到最新记录。写入器按短批次交付,突发日志反映实际活动。向上滚动会暂停自动跟随,日志收集继续;恢复跟随可回到最新记录。"; "logs.window.following" = "跟随中"; "logs.window.hideThisEvent" = "隐藏这个事件"; @@ -5469,8 +5468,7 @@ "mac.workbench.unhide" = "取消隐藏"; "macOS could not prepare the update disk image. Download the release manually and try again." = "macOS 无法准备更新磁盘映像,请手动下载版本后重试。"; "macOS could not prepare the update disk image. Open the Release page and install it manually." = "macOS 无法准备更新磁盘映像。请打开 Release 页面手动安装。"; -"macos.buildProvider.jvmDebugPortTimeout" = "框架未在期限内开放 JVM 调试端口,请查看运行输出。"; -"macos.buildProvider.jvmDebugRemoteUnavailable" = "远程工作区暂不支持框架服务调试。"; +"macos.buildProvider.serviceDebugRemoteUnavailable" = "远程工作区暂不支持框架服务调试。"; "macos.native.savedRunMigrationNeedsUpdate" = "部分已保存的运行配置暂时无法迁移。请保留现有文件,在更新 Lithe 及其构建插件后重试。"; "main Java" = "主代码"; "main resources" = "主资源"; @@ -5507,7 +5505,6 @@ "native.aSpringBootProjectFromSpringInitializr" = "由 Spring Initializr 生成的 Spring Boot 项目。"; "native.aStableReleaseInstallationIsAlreadyInProgress" = "正在进行正式版安装,请等待完成。"; "native.aTaskStartedBeforeLitheLastClosedUnexpectedlyIsStillRunning" = "Lithe 上次意外关闭前,%1$@ 启动的一个任务仍在运行"; -"native.aTerminalIsBusyWhenAProgramOtherThanTheShellStillRunsInItSuchAsASpringBootAppNa88ac3e46a" = "终端里除了 Shell 本身还有程序在运行时(例如 Spring Boot 应用、npm run dev 或放到后台的任务),这个终端就是“运行中”。空闲终端总是直接关闭,不会询问。结束一个终端会结束其中启动的所有程序。"; "native.aTerminalSessionIsStillRunning" = "终端会话仍在运行。"; "native.aTestPathMustStayInsideTheCurrent" = "测试路径必须保持在当前工作区内。"; "native.aUniqueFilenameCouldNotBeCreatedFor" = "无法为图片创建唯一的文件名"; @@ -5569,7 +5566,6 @@ "native.additions" = "新增"; "native.address" = "地址"; "native.addsGoLanguageServerIntegrationFormattingRunningAndTestSupport" = "提供 Go 语言服务器、格式化、运行和测试支持。"; -"native.addsJavaLanguageIntelligenceThroughTheEclipseJDTLanguageServerWithLombokDebuggb2eae07f8b" = "通过 Eclipse JDT 语言服务器提供 Java 代码智能,并支持 Lombok、调试和测试。自带 Java 运行时。"; "native.addsLanguageServerIntegrationAndFormattingSupport" = "提供语言服务器和格式化支持。"; "native.addsLanguageServerIntegrationFormattingRunningAndTestSupport" = "提供语言服务器、格式化、运行和测试支持。"; "native.addsToThePullRequestConversationWithoutAnApprovalDecision" = "在拉取请求中发表评论,不作出批准决定。"; @@ -5649,7 +5645,6 @@ "native.allow" = "允许"; "native.allowFastForward" = "允许快进"; "native.allowInsecureHTTP" = "允许不安全的 HTTP"; -"native.allowProjectEnvironmentAndMavenConfigurationChanges" = "允许修改项目环境和 Maven 配置"; "native.allowRecreatingFile" = "允许重新创建文件"; "native.allowRunBuildReloadAndStopExecutesProjectCode" = "允许运行、构建、重载和停止(会执行项目代码)"; "native.allowTheAgentToContinue" = "允许 Agent 继续吗?"; @@ -5759,9 +5754,6 @@ "native.authenticationMustBeAJSONObjectContainingAnOPENAIAPIKEYString" = "认证配置必须是包含 OPENAI_API_KEY 字符串的 JSON 对象。"; "native.author" = "作者"; "native.authorizeInYourBrowser" = "在浏览器中授权"; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnec6e24e4763f" = "仅授权此项目,连接的 Agent 可以读取环境、Maven、运行配置和输出。输出可能包含项目敏感信息。关闭项目或退出 Lithe 后连接失效。"; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnecb6f617e865" = "仅授权此项目,连接的 Agent 可以读取环境、Maven、运行配置和输出。输出可能包含项目敏感信息。关闭项目或退出 Lithe 后连接失效。已启用的插件也可使用此项目授权。"; -"native.authorizeThisProjectToExposeEnvironmentMavenRunConfigurationsAndOutputToConnece4d5e32bce" = "授权当前项目后,已连接的 Agent 可以访问环境、Maven、运行配置与输出。输出可能包含敏感项目数据。关闭项目或退出 Lithe 时访问结束,并移除项目级服务器注册。已启用的插件也可以使用该授权。"; "native.auto" = "自动"; "native.autoCompactAboveContext" = "自动压缩阈值不能大于上下文长度。"; "native.autoCompactAt" = "自动压缩阈值"; @@ -6216,7 +6208,7 @@ "native.configureDependencySearchPaths" = "配置依赖搜索路径"; "native.configureEditorAndProjectBehavior" = "配置编辑器和项目行为"; "native.configureInSettings" = "在设置中配置"; -"native.configureProjectJDKAndMaven" = "配置项目 JDK 和 Maven…"; +"native.configureRuntimeEnvironment" = "配置运行环境…"; "native.configured" = "已配置"; "native.configuredRemoteName" = "已配置的远程仓库名称"; "native.confirmDeletion" = "确认删除"; @@ -6232,7 +6224,6 @@ "native.connectToRunningJVM2" = "连接到运行中的 JVM…"; "native.connectToRunningJvm" = "连接到运行中的 JVM"; "native.connected" = "已连接"; -"native.connectedAgentsCanChangeTheProjectJDKMavenAndRunConfigurationSettings" = "连接的 Agent 可以修改项目 JDK、Maven 和运行配置。"; "native.connectedAgentsCanRunBuildReloadAndStopTheProjectCommandsExecuteProjectCodeSoE6d273dab37" = "连接的 Agent 可以运行、构建、重载和停止项目。命令会执行项目代码,请仅对信任的项目开启。"; "native.connectedAgentsCanUseTheConfigurationBelowWhileThisProjectIsOpen" = "项目打开期间,连接的 Agent 可以使用下方配置。"; "native.connectedAs" = "已连接为 @%1$@"; @@ -6269,6 +6260,7 @@ "native.controlsHowLitheSOrdinaryFetchUpdatesSubmodules" = "控制 Lithe 普通 Fetch 如何更新子模块。"; "native.controlsHowLitheSOrdinaryFetchUpdatesSubmodulesInheritFollowsGitSFetchRecurseSubmodulesSetting" = "控制 Lithe 普通 Fetch 如何更新子模块。“继承”表示遵循 Git 的 fetch.recurseSubmodules 设置。"; "native.controlsWhereStepIntoStopsChangesApplyTo" = "控制“步入”的停止位置。更改将在下一次 Java 调试会话中生效。"; +"native.controlsWhereStepIntoStopsNextSession" = "控制“步入”的停止位置。更改将在此调试器的下一次调试会话中生效。"; "native.controlsWhetherLitheSOrdinaryFetchRemovesStaleRemoteBranches" = "控制 Lithe 普通 Fetch 是否清理失效的远程分支。"; "native.conventionalCommits" = "Conventional Commits 规范"; "native.conversation" = "讨论"; @@ -6352,9 +6344,11 @@ "native.couldNotRestoreLocalHistory" = "无法恢复本地历史"; "native.couldNotRestoreProjectHistory" = "无法恢复项目历史"; "native.couldNotRestoreThisProjectHistoryEntry" = "无法恢复此项目历史记录"; +"native.couldNotSave" = "无法保存 %1$@"; "native.couldNotSaveAccessToTheSelectedBackgroundImage" = "无法保存所选背景图片的访问权限。"; "native.couldNotSaveServiceSelection" = "无法保存服务勾选状态"; "native.couldNotSaveTheConnections" = "无法保存连接:%1$@"; +"native.couldNotStartDebugging" = "无法开始调试"; "native.couldNotStartTheJavaTestResultListener" = "无法启动 Java 测试结果监听器:%1$@"; "native.couldNotStartTheMcpCommandCheckItsExecutableAndRuntime" = "无法启动 MCP 命令,请检查程序及所需运行时。"; "native.couldNotVerifySavedProjectEnvironment" = "无法核对已保存的项目环境设置。已尽可能保留原偏好。"; @@ -6593,6 +6587,8 @@ "native.documentation" = "文档"; "native.doesNotIncludeLitheRendersThoseCharactersWithAndTheSystemFont" = "%1$@ 不包含%2$@;Lithe 会用 %3$@ 和系统字体显示这些字符。"; "native.doesNotProvideArchivedConversations" = "%1$@ 不支持归档会话。"; +"native.doesNotProvideDebugging" = "%1$@ 没有提供调试功能"; +"native.doesNotProvideProjectExecution" = "%1$@ 没有提供项目运行功能"; "native.doesNotSupportDebugYet" = "%1$@ 暂不支持调试"; "native.doesNotSupportRunningTheCurrentFileDirectly" = "%1$@ 不支持直接运行当前文件。请使用项目运行配置。"; "native.donTAllow" = "不允许"; @@ -7342,8 +7338,6 @@ "native.javaServiceIsPreparing" = "Java 服务正在准备"; "native.javaServiceIsReady" = "Java 服务已就绪"; "native.javaServicePreparationTimedOut" = "Java 服务准备超时"; -"native.javaSteppingFilters" = "Java 步进过滤器"; -"native.javaSteppingFilters2" = "Java 步进过滤器…"; "native.javaTestDiscoveryIsNotSupportedByThis" = "此语言服务器不支持 Java 测试发现。"; "native.javaWorkspacePreparationCancelled" = "Java 工作区准备已取消"; "native.jdkHome" = "JDK 主目录"; @@ -7624,7 +7618,6 @@ "native.lookUpLocation" = "查询地区"; "native.lookedIn" = "已查找:%1$@"; "native.lookingForGit" = "正在查找 Git…"; -"native.lookingForInstalledJDKs" = "正在查找已安装的 JDK…"; "native.lookingForInstalledTools" = "正在查找已安装的工具…"; "native.lookingUpTheLocationSendsThisAddressToIpinfoIoLitheDoesThisOnlyWhenYouClickLookUp" = "查询地区会把这个地址发送给 ipinfo.io。只有你点击“查询地区”时 Lithe 才会这样做。"; "native.low" = "低"; @@ -7929,7 +7922,6 @@ "native.noItems" = "暂无项目"; "native.noJDKFoundSetJAVAHOMEInstallAJDKOrChooseAJDKDirectory" = "未找到 JDK。请设置 JAVA_HOME、安装 JDK,或选择 JDK 目录。"; "native.noJDKIsConfiguredForThisProject" = "此项目没有配置 JDK。"; -"native.noJDKWasFoundInstallAJDKThenReopenThisWindow" = "未找到 JDK。请安装 JDK 后重新打开此窗口。"; "native.noJVMPerformanceSamplesReceivedFor10Seconds" = "10 秒内未收到 JVM 性能采样。"; "native.noJavaNavigationResults" = "没有 Java 导航结果"; "native.noJavaProblems" = "没有 Java 问题"; @@ -8086,6 +8078,7 @@ "native.onePathPerLineRelativePathsAreResolvedFromTheWorkspace" = "每行一个路径;相对路径以当前工作区为基准。"; "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx35941b6a99" = "每行一条规则,不区分大小写。规则使用通配符,是正则表达式的简化写法:`*` 匹配任意字符,`?` 匹配单个字符。\n以 `/`、`/*` 或 `/**` 结尾表示隐藏整个文件夹及其内容,以 `**/` 开头表示匹配任意层级。不带结尾斜杠的规则只隐藏文件:`.lithe` 隐藏名为 .lithe 的文件,而不是文件夹。\n示例:\n`**/dist/` — 任意层级的 dist 文件夹\n`.lithe/**` — 项目根目录下的 .lithe 文件夹\n`*.log` — 所有 .log 文件\n`docs/*.md` — docs 下的 Markdown 文件\n列表开头是内置规则。删掉一行即可重新显示这些文件,再输入回来就会重新隐藏。"; "native.onePatternPerLineCaseInsensitivePatternsUseWildcardsASimplifiedFormOfRegularEx4f7ef7b38a" = "每行一条规则,不区分大小写。规则使用通配符,是正则表达式的简化写法:`*` 匹配任意字符,`?` 匹配单个字符。\n以 `/` 或 `/*` 结尾表示隐藏整个文件夹及其内容,以 `**/` 开头表示匹配任意层级;其他写法隐藏匹配的文件。\n示例:\n`**/dist/` — 任意层级的 dist 文件夹\n`.lithe/*` — 项目根目录下的 .lithe 文件夹\n`*.log` — 所有 .log 文件\n`docs/*.md` — docs 下的 Markdown 文件\n下方的内置规则始终生效。"; +"native.onePatternPerLineDebuggerDefinesSyntax" = "每行一个模式,模式语法由调试器定义。"; "native.onePatternPerLineForExampleOrgMockito" = "每行一个模式,例如 org.mockito.* 或 com.example.generated.*"; "native.onePatternPerLineLogCacheOnlyAffectsThisSearchEverywhereWindow" = "每行一个表达式:`*.log`、`**/.*/`、`.*`、`cache/`。仅影响当前双 Shift 搜索窗口。"; "native.oneSentenceFocusedOnTheMainChange" = "聚焦主要更改的一句话"; @@ -8719,6 +8712,7 @@ "native.returnToStable" = "回到正式版"; "native.returnToStable.variant2" = "回到正式版?"; "native.returnToTheWelcomeScreen" = "返回 Welcome 页面"; +"native.returnedAnInvalidExecutionProvider" = "%1$@ 返回了无效的运行提供者"; "native.returnedAnInvalidLanguageServerProvider" = "%1$@ 返回了无效的语言服务器 Provider。"; "native.returnedAnUnexpectedResponse" = "%1$@ 返回了无法识别的响应。"; "native.returnedHTTP" = "%1$@ 返回了 HTTP %2$@。"; @@ -8773,7 +8767,6 @@ "native.runConfiguration.variant2" = "运行配置"; "native.runConfiguration.variant3" = "运行配置"; "native.runConfigurations" = "运行配置"; -"native.runConfigurationsAndMavenGoalsStartedInLitheTheyAlwaysStopWhenTheirProjectOrWi2085dbd360" = "在 Lithe 中启动的运行配置和 Maven 目标。项目或窗口关闭、或退出 Lithe 时,它们总会连同自己启动的进程一起停止;这里只决定 Lithe 是否先列出并询问。"; "native.runConfigurationsAreUnavailableEnableTheExecutionModuleAndTryAgain" = "运行配置暂不可用,请启用执行模块后重试。"; "native.runConfigurationsInheritTheProjectJDKAndMavenUnlessOverriddenBelow" = "运行配置默认继承项目 JDK 和 Maven,可在下方为当前配置单独覆盖。"; "native.runConfigurationsMayBeOutOfDate" = "运行配置可能已过期"; @@ -8879,7 +8872,6 @@ "native.searchHooks" = "搜索 Hook"; "native.searchImplementations" = "搜索实现"; "native.searchInProject" = "在项目中搜索"; -"native.searchJDKs" = "搜索 JDK"; "native.searchMcpServers" = "搜索 MCP 服务器"; "native.searchMcpServersGithubBrowsersDocumentation" = "搜索 MCP 服务器 — GitHub、浏览器、文档…"; "native.searchOfficialMicrosoftAndAzureDocumentationAndCodeSamples" = "搜索微软与 Azure 的官方文档和代码示例。"; @@ -9206,6 +9198,8 @@ "native.stepLldOfLld" = "第 %1$lld 步,共 %2$lld 步"; "native.stepOut" = "单步跳出"; "native.stepOver" = "单步跳过"; +"native.steppingFilters" = "步进过滤器"; +"native.steppingFilters2" = "步进过滤器…"; "native.stopActiveExecution" = "停止当前执行"; "native.stopAllServers" = "停止所有服务器"; "native.stopAllServices" = "停止所有服务"; @@ -9410,6 +9404,7 @@ "native.theFeaturedMcpCatalogCouldNotBeLoaded" = "无法加载内置 MCP 精选目录。"; "native.theFieldValueDoesNotMatchItsDeclarationOrExceedsItsSizeLimit" = "字段值不符合声明或超过大小限制。"; "native.theFieldValueIsInvalidOrExceeds1024UTF8Bytes" = "字段值无效或超过 1024 个 UTF-8 字节。"; +"native.theFileChangedWhilePreparingToStartTryAgain" = "准备启动时文件已改变,请重试。"; "native.theFileCouldNotBeOpenedAsATextDocument" = "无法将该文件作为文本文档打开。"; "native.theFileHasChangedSinceTheAgentEditOpenTheDiffAndReviewItManually" = "文件内容与 Agent 修改存在冲突,请打开差异手动确认。"; "native.theFileHasUnsavedChangesSaveItFirstBecauseTheBrowserShowsTheSavedFile" = "文件有未保存的更改。请先保存,因为浏览器显示的是已保存的文件。"; @@ -10239,8 +10234,6 @@ "plugin.terminal.permission" = "打开并管理自己的原生终端,保留有限的显示历史用于重新打开"; "plugin.terminal.running" = "插件终端仍在运行。"; "plugin.terminal.unavailable" = "终端不可用。"; -"plugins.java.installNotice" = "Java Support 现已独立安装。请从插件市场安装,或使用“从磁盘安装”导入离线包。原有 Java 设置会保留。"; -"plugins.java.installTemplates" = "安装 Java Support,获取 Java、Maven 和 Spring 项目模板…"; "plugins.title" = "插件"; "ports %@" = "端口 %@"; "project Maven Wrapper" = "项目 Maven Wrapper"; @@ -10334,6 +10327,9 @@ "settings.mac.projects" = "项目"; "settings.mac.restoreDefaults" = "恢复默认设置"; "settings.mac.shortcuts" = "键盘快捷键"; +"settings.mcp.allowConfigure.info" = "连接的 Agent 可以修改项目工具链、构建和运行配置。"; +"settings.mcp.allowConfigure.title" = "允许修改项目环境和构建配置"; +"settings.mcp.info.projectAccess" = "授权当前项目后,已连接的 Agent 可以访问项目环境、构建工具、运行配置与输出。输出可能包含敏感项目数据。关闭项目或退出 Lithe 时访问结束,并移除项目级服务器注册。已启用的插件也可以使用该授权。"; "settings.network.checkFailed" = "连接检查失败。"; "settings.network.connectionSucceeded" = "连接成功,耗时 %1$@ 毫秒。"; "settings.network.credentialsUnavailable" = "此构建无法保存代理凭据。"; @@ -10348,7 +10344,7 @@ "settings.network.info.password" = "代理无需认证时留空。密码保存在钥匙串中,不会写入设置文件。"; "settings.network.info.passwordSaved" = "密码已绑定到原代理。仅当代理类型、地址、端口和用户名一致时,空密码框才会复用已存密码。"; "settings.network.info.port" = "代理服务器的端口,例如 7890。"; -"settings.network.info.scope" = "这些设置作用于 Lithe 自身的请求:插件市场、GitHub 和 AI 提供方。终端命令、Git、JVM 依赖下载和内置更新器使用各自的网络设置;更新器始终跟随系统代理。更改对新请求生效。"; +"settings.network.info.scope" = "这些设置作用于 Lithe 自身的请求:插件市场、GitHub 和 AI 提供方。终端命令、Git、构建工具的依赖下载和内置更新器使用各自的网络设置;更新器始终跟随系统代理。更改对新请求生效。"; "settings.network.info.type" = "HTTP 代理通过 CONNECT 承载 HTTPS 请求;SOCKS5 隧道承载任意协议与端口。"; "settings.network.info.username" = "代理无需认证时留空。"; "settings.network.mode.custom" = "自定义代理服务器"; @@ -10367,6 +10363,8 @@ "settings.network.type.socks5" = "SOCKS5"; "settings.network.username" = "用户名"; "settings.noResults" = "未找到设置"; +"settings.processTermination.info.runConfigurations" = "在 Lithe 中启动的运行配置和构建任务。项目或窗口关闭、或退出 Lithe 时,它们总会连同自己启动的进程一起停止;这里只决定 Lithe 是否先列出并询问。"; +"settings.processTermination.info.terminals" = "终端里除了 Shell 本身还有程序在运行时(例如开发服务器、npm run dev 或放到后台的任务),这个终端就是“运行中”。空闲终端总是直接关闭,不会询问。结束一个终端会结束其中启动的所有程序。"; "settings.search" = "搜索设置"; "stash restore" = "恢复暂存更改"; "svg.preview" = "预览"; diff --git a/macos/Sources/Lithe/Application/Composition/AppModelFeatureGraph.swift b/macos/Sources/Lithe/Application/Composition/AppModelFeatureGraph.swift index a7093f5c67..bf7357e43b 100644 --- a/macos/Sources/Lithe/Application/Composition/AppModelFeatureGraph.swift +++ b/macos/Sources/Lithe/Application/Composition/AppModelFeatureGraph.swift @@ -28,17 +28,13 @@ final class AppModelFeatureGraph { let terminalPlacement: TerminalPlacementFeatureModel let document: DocumentFeatureModel let navigationHistory: NavigationHistoryFeatureModel - let java: JavaFeatureModel - let spring: SpringFeatureModel - let mybatis: MybatisFeatureModel let editorSession: EditorSessionCoordinator - let javaTestWorkflow: JavaTestWorkflowState let languageNavigation: LanguageNavigationCoordinator let languageEditing: LanguageEditingCoordinator let languageCapabilityPolicy: LanguageCapabilityPolicy let debugLaunchPreparation: DebugLaunchPreparationCoordinator let debugSessionCleanup: DebugSessionCleanupCoordinator - let javaTestDebugWorkflow: JavaTestDebugWorkflowCoordinator + let languageTestWorkflow: LanguageTestWorkflowState /// Nil only when the application has no log store (some tests). let languageServerLogs: LanguageServerLogsModel? @@ -48,13 +44,14 @@ final class AppModelFeatureGraph { self.notification = notification // Coordinators report user-facing failures through the notification // feature directly; the application shell forwards the same call. - let notify: @MainActor (String) -> Void = { message in + let notifyFormatted: @MainActor (String, [String]) -> Void = { message, arguments in var reference: LogRecordReference? if let sink = services.logSink { reference = LogScope(sink: sink).emitReferenced(AppNotificationOperationRejected(operation: "language_debug_workflow", reason: "request_failed")) } - notification.show(message, logReference: reference) + notification.show(message, arguments: arguments, logReference: reference) } + let notify: @MainActor (String) -> Void = { notifyFormatted($0, []) } workbench = WorkbenchFeatureModel(layoutStore: services.workbenchLayoutStore) commitDraft = CommitDraftFeatureModel() searchSession = SearchSessionFeatureModel() @@ -118,16 +115,12 @@ final class AppModelFeatureGraph { confirmHardLinkSave: { services.platformUI.confirmHardLinkSave(at: $0) } ) navigationHistory = NavigationHistoryFeatureModel(logSink: services.logSink) - java = JavaFeatureModel(operations: services.javaMavenOperations) - spring = SpringFeatureModel(operations: services.javaMavenOperations) - mybatis = MybatisFeatureModel(operations: services.javaMavenOperations) - javaTestWorkflow = JavaTestWorkflowState(notify: notify) languageNavigation = LanguageNavigationCoordinator(notify: notify) languageEditing = LanguageEditingCoordinator(notify: notify) languageCapabilityPolicy = LanguageCapabilityPolicy() - debugLaunchPreparation = DebugLaunchPreparationCoordinator(notify: notify) + debugLaunchPreparation = DebugLaunchPreparationCoordinator(notify: notifyFormatted) debugSessionCleanup = DebugSessionCleanupCoordinator() - javaTestDebugWorkflow = JavaTestDebugWorkflowCoordinator(notify: notify) + languageTestWorkflow = LanguageTestWorkflowState() let languageServerLogs = services.logWindowLogging.map { LanguageServerLogsModel(logging: $0, sink: services.logSink) } diff --git a/macos/Sources/Lithe/Application/Composition/AppModelObservationBinder.swift b/macos/Sources/Lithe/Application/Composition/AppModelObservationBinder.swift index 9708b5909a..14788d9738 100644 --- a/macos/Sources/Lithe/Application/Composition/AppModelObservationBinder.swift +++ b/macos/Sources/Lithe/Application/Composition/AppModelObservationBinder.swift @@ -18,7 +18,6 @@ final class AppModelObservationBinder { graph.terminalPlacement.objectWillChange, graph.document.objectWillChange, graph.media.objectWillChange, - graph.java.objectWillChange, graph.notification.objectWillChange, graph.workbench.objectWillChange, graph.searchSession.objectWillChange, diff --git a/macos/Sources/Lithe/Application/Composition/AppServices.swift b/macos/Sources/Lithe/Application/Composition/AppServices.swift index ed2ea2eb73..d11f54e72d 100644 --- a/macos/Sources/Lithe/Application/Composition/AppServices.swift +++ b/macos/Sources/Lithe/Application/Composition/AppServices.swift @@ -102,16 +102,13 @@ final class AppServices { let workspaceLanguageServerPreferences: any WorkspaceLanguageServerPreferencesStoring let debugLaunchConfigurationResolver: DebugLaunchConfigurationResolver let debugPortAvailabilityChecker: any DebugPortAvailabilityChecking - let javaTestDebugLaunchService: JavaTestDebugLaunchService let debugPerformanceSampler: (any DebugPerformanceSampling)? - let testJVMPerformance: (any TestJVMPerformanceProviding)? let debugBreakpointPersistence: (any DebugBreakpointPersisting)? let workspaceOperations: any WorkspaceOperations let documentLifecycleDecider: any DocumentLifecycleDeciding /// Deterministic line-level editing transforms shared with Windows; the /// editor view applies the results through its native text engine. let lineEditing: any EditorLineEditing - let javaMavenOperations: any JavaMavenOperations let markdownRenderer: any MarkdownRendering let markdownImageImporter: any MarkdownImageImporting let store: any KeyValueStore @@ -163,12 +160,10 @@ final class AppServices { languageProviderCatalogSnapshot: LanguageProviderCatalogSnapshot? = nil, debugLaunchConfigurationResolver: DebugLaunchConfigurationResolver? = nil, debugPortAvailabilityChecker: (any DebugPortAvailabilityChecking)? = nil, - javaTestResultServerFactory: @escaping @MainActor () -> any JavaTestResultServing, debugBreakpointPersistence: (any DebugBreakpointPersisting)? = nil, workspaceOperations: any WorkspaceOperations, documentLifecycleDecider: any DocumentLifecycleDeciding, lineEditing: any EditorLineEditing, - javaMavenOperations: any JavaMavenOperations, markdownRenderer: any MarkdownRendering, markdownImageImporter: any MarkdownImageImporting, store: any KeyValueStore, @@ -197,11 +192,9 @@ final class AppServices { directoryWatcherFactory: any DirectoryWatcherFactory, platformUI: any PlatformUI, shortcutDetectorFactory: any ShortcutDetectorFactory, - debugPerformanceSampler: (any DebugPerformanceSampling)? = nil, - testJVMPerformance: (any TestJVMPerformanceProviding)? = nil + debugPerformanceSampler: (any DebugPerformanceSampling)? = nil ) { self.debugPerformanceSampler = debugPerformanceSampler - self.testJVMPerformance = testJVMPerformance self.moduleRuntime = moduleRuntime self.pluginManager = pluginManager self.pluginMarketplace = pluginMarketplace @@ -220,15 +213,10 @@ final class AppServices { ?? DebugLaunchConfigurationResolver() self.debugPortAvailabilityChecker = debugPortAvailabilityChecker ?? AlwaysAvailableDebugPortChecker() - self.javaTestDebugLaunchService = JavaTestDebugLaunchService( - configurationResolver: self.debugLaunchConfigurationResolver, - resultServerFactory: javaTestResultServerFactory - ) self.debugBreakpointPersistence = debugBreakpointPersistence self.workspaceOperations = workspaceOperations self.documentLifecycleDecider = documentLifecycleDecider self.lineEditing = lineEditing - self.javaMavenOperations = javaMavenOperations self.markdownRenderer = markdownRenderer self.markdownImageImporter = markdownImageImporter self.store = store diff --git a/macos/Sources/Lithe/Application/Composition/DocumentFeatureComposition.swift b/macos/Sources/Lithe/Application/Composition/DocumentFeatureComposition.swift index be104ab7d7..51e0147141 100644 --- a/macos/Sources/Lithe/Application/Composition/DocumentFeatureComposition.swift +++ b/macos/Sources/Lithe/Application/Composition/DocumentFeatureComposition.swift @@ -9,34 +9,20 @@ enum DocumentFeatureComposition { let document = graph.document let workspace = graph.workspace let session = graph.workspaceSession - let java = graph.java - let spring = graph.spring - let mybatis = graph.mybatis let notification = graph.notification let settings = model.settings let coordinator = DocumentLanguageCoordinator( activate: { [weak model] document in _ = model?.activateLanguageServerIfAvailable(for: document) }, - reloadProject: { [weak spring, weak mybatis, weak session, weak workspace, weak document] changed in - guard let root = session?.workspaceURL else { return } - let files = workspace?.projectFiles ?? [] - let openDocuments = document?.openDocuments ?? [] - spring?.scheduleReload( - changedDocument: changed, workspaceURL: root, - files: files, openDocuments: openDocuments - ) - mybatis?.scheduleReload( - changedDocument: changed, workspaceURL: root, - files: files, openDocuments: openDocuments - ) - }, - close: { [weak model, weak java] document in + // Project indexes and inline hints come from language plugins + // through their language servers; the host keeps no per-language index. + reloadProject: { _ in }, + close: { [weak model] document in model?.languageToolingSessionsIfActive?.closeDocument(document.url) - if java?.handles(fileURL: document.url) == true { java?.close(document) } }, - supportsHints: { [weak java] in java?.handles(fileURL: $0.url) == true }, - refreshHints: { [weak model] in await model?.refreshCodeVision(for: $0) } + supportsHints: { _ in false }, + refreshHints: { _ in } ) graph.languageTooling.logSink = model.services.logSink graph.languageTooling.notifyLog = { [weak notification] in notification?.show($0, logReference: $1) } @@ -75,13 +61,6 @@ enum DocumentFeatureComposition { onProjectCloseReady: { [weak session] in session?.projectCloseReady() }, onCloseFailed: { [weak session] in session?.cancelPendingClose() } ) - java.configure( - documentProvider: { [weak document] in document?.activeDocument }, - loadBlame: { [weak model] fileURL in - guard let feature = await model?.activateGitModule() else { return [] } - return await feature.loadBlame(for: fileURL) - } - ) return coordinator } } diff --git a/macos/Sources/Lithe/Application/Composition/JavaLanguageServerPreparationCoordinator.swift b/macos/Sources/Lithe/Application/Composition/JavaLanguageServerPreparationCoordinator.swift deleted file mode 100644 index 521a25a280..0000000000 --- a/macos/Sources/Lithe/Application/Composition/JavaLanguageServerPreparationCoordinator.swift +++ /dev/null @@ -1,230 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheLanguageIntelligenceModule - -/// Owns the asynchronous task associated with Java language-server preparation. -@MainActor -final class JavaLanguageServerPreparationCoordinator { - typealias SessionsProvider = @MainActor () async throws -> LanguageToolingSessionManager - typealias OwnershipCheck = @MainActor () -> Bool - typealias FailureHandler = @MainActor (JavaLanguageServerPreparationFailure) -> Void - typealias StartedHandler = @MainActor (UUID) -> Void - - private var mavenConfigurationTask: Task? - private var mavenConfigurationID: UUID? - private var mavenRecoveryRoot: URL? - - deinit { - mavenConfigurationTask?.cancel() - } - - func schedule( - for owner: JavaLanguageServerPreparationOwner, - operation: @escaping @MainActor () async -> Void - ) { - owner.task?.cancel() - let task = Task { @MainActor [weak owner] in - guard owner != nil else { return } - await operation() - } - owner.task = task - } - - func cancel(_ owner: JavaLanguageServerPreparationOwner?) { - owner?.cancel() - } - - func prepareAndStart( - owner: JavaLanguageServerPreparationOwner, - workspaceURL: URL, - runtimePreparation: @escaping @MainActor () async - -> ProjectRuntimeService.JavaLanguageServerRuntimePreparation, - sessionsProvider: @escaping SessionsProvider, - languageImportPreparation: @escaping @MainActor () async throws -> Void, - ownsPreparation: @escaping OwnershipCheck, - onStarted: @escaping StartedHandler, - onFailure: @escaping FailureHandler - ) { - schedule(for: owner) { @MainActor [weak owner] in - guard let owner else { return } - do { - let sessions = try await sessionsProvider() - guard !Task.isCancelled, ownsPreparation() else { return } - let preparation = await runtimePreparation() - guard !Task.isCancelled, ownsPreparation() else { return } - switch preparation { - case .unprepared: - return - case .failed(let message): - onFailure(.failed(message: message)) - return - case .ready: - break - } - // Runtime and plugin preparation can suspend after the first - // import wait. Rejoin the current detection immediately before - // the synchronous provider reads its configuration. - try await languageImportPreparation() - guard !Task.isCancelled, ownsPreparation() else { return } - let startedOperationID = try sessions.startLanguageServer( - providerID: "java", - rootURL: workspaceURL, - operationID: owner.operationID - ) - guard ownsPreparation() else { return } - onStarted(startedOperationID) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard !Task.isCancelled, ownsPreparation() else { return } - let sessionFailure = (error as? LanguageServerSessionStartError)?.failure - onFailure( - sessionFailure?.isTimedOut == true - ? .timedOut(message: error.localizedDescription) - : .failed(message: error.localizedDescription) - ) - } - } - } - - /// Serializes plugin Maven updates with restart recovery. A successor must - /// join cancelled recovery before touching its session: cancellation may - /// still be stopping the session that the previous reload created. - @discardableResult - func synchronizeMavenConfiguration( - sessions: LanguageToolingSessionManager, - workspaceURL: URL, - languageImportPreparation: @escaping @MainActor () async throws -> Void, - ownsWorkspace: @escaping OwnershipCheck - ) -> Task { - let replacesRecovery = mavenRecoveryRoot == workspaceURL - let previous = mavenConfigurationTask - previous?.cancel() - let id = UUID() - mavenConfigurationID = id - let task = Task { @MainActor [weak self, weak sessions] in - defer { self?.finishMavenConfiguration(id: id) } - await previous?.value - guard let sessions, !Task.isCancelled, - self?.mavenConfigurationID == id, ownsWorkspace() else { return } - do { - try await languageImportPreparation() - guard !Task.isCancelled, self?.mavenConfigurationID == id, ownsWorkspace() else { return } - switch sessions.updateJavaMavenConfiguration(rootURL: workspaceURL, reloadProjects: false) { - case .updated: - return - case .noSession: - // Cancelling the previous reload stops only its replacement - // session. Its successor still owes this root a restart. - guard replacesRecovery else { return } - case .failed: - self?.mavenRecoveryRoot = workspaceURL - } - try await sessions.reloadJavaWorkspace(rootURL: workspaceURL) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard !Task.isCancelled, self?.mavenConfigurationID == id, ownsWorkspace() else { return } - sessions.recordHostFailure(providerID: "java", stage: "mavenConfiguration", error: error) - } - } - mavenConfigurationTask = task - return task - } - - func cancelMavenConfigurationSynchronization() { - mavenConfigurationID = nil - mavenRecoveryRoot = nil - // Retain the handle until it finishes so a new workspace or selection - // can join cleanup before starting another recovery. - mavenConfigurationTask?.cancel() - } - - private func finishMavenConfiguration(id: UUID) { - guard mavenConfigurationID == id else { return } - mavenConfigurationID = nil - mavenConfigurationTask = nil - mavenRecoveryRoot = nil - } - - func notifyWorkspaceFileChanges( - _ changes: [WorkspaceFileChange], - workspaceURL: URL, - projectFiles: [URL], - openDocuments: [EditorDocument], - policy: @escaping (URL, [URL], [URL]) -> JavaWorkspacePolicyResult?, - sessions: LanguageToolingSessionManager? - ) { - guard let workspacePolicy = policy( - workspaceURL, - projectFiles, - changes.map(\.fileURL) - ) else { return } - let changeKinds = Dictionary( - uniqueKeysWithValues: changes.map { ($0.fileURL.standardizedFileURL, $0.kind) } - ) - let openJavaURLs = Set(openDocuments.compactMap { document in - document.url.pathExtension.lowercased() == "java" - ? document.url.standardizedFileURL - : nil - }) - let languageServerChanges = workspacePolicy.changes.compactMap { - change -> LanguageServerWorkspaceFileChange? in - guard change.kind == .source || change.kind == .buildConfiguration else { - return nil - } - let url = change.url.standardizedFileURL - guard !openJavaURLs.contains(url), let kind = changeKinds[url] else { - return nil - } - let languageServerKind: LanguageServerWorkspaceFileChangeKind = switch kind { - case .created: .created - case .changed: .changed - case .deleted: .deleted - } - return LanguageServerWorkspaceFileChange(fileURL: url, kind: languageServerKind) - } - guard !languageServerChanges.isEmpty else { return } - do { - try sessions?.notifyWorkspaceFilesChanged( - providerID: "java", - changes: languageServerChanges - ) - } catch { - sessions?.recordHostFailure(providerID: "java", stage: "workspaceFilesChanged", error: error) - } - } - - func handleSessionState( - _ state: LanguageServerSessionState, - operationID: UUID?, - javaFeature: JavaFeatureModel, - workspaceURL: URL?, - onReady: @MainActor () -> Void, - onFailure: @MainActor (JavaLanguageServerPreparationFailure) -> Void - ) { - guard let operationID, - javaFeature.languageServerOperationID == operationID, - let workspaceURL else { return } - switch state { - case .ready: - javaFeature.markLanguageServerReady( - workspaceURL: workspaceURL.standardizedFileURL, - operationID: operationID - ) - onReady() - case .failed(let failure): - onFailure( - failure.isTimedOut - ? .timedOut(message: failure.message ?? "JDTLS failed to start.") - : .failed(message: failure.message ?? "JDTLS failed to start.") - ) - case .stopped: - javaFeature.cancelLanguageServerPreparation() - case .startingProcess, .initializing, .stopping: - break - } - } -} diff --git a/macos/Sources/Lithe/Application/Composition/WorkspaceProjectionComposition.swift b/macos/Sources/Lithe/Application/Composition/WorkspaceProjectionComposition.swift index a0f1857093..3ba0da0f7f 100644 --- a/macos/Sources/Lithe/Application/Composition/WorkspaceProjectionComposition.swift +++ b/macos/Sources/Lithe/Application/Composition/WorkspaceProjectionComposition.swift @@ -88,7 +88,6 @@ enum WorkspaceProjectionComposition { }, onSnapshotLoaded: { [weak model] snapshot, isInitialLoad in guard let model else { return } - model.suggestJavaPluginIfNeeded(files: snapshot.files) if !isInitialLoad { // Core may have withdrawn working copies after an exclusion change. // Reconcile open buffers so cancelling exclusion restores language features. diff --git a/macos/Sources/Lithe/Application/Features/DebugAutomaticExpressionProjection.swift b/macos/Sources/Lithe/Application/Features/DebugAutomaticExpressionProjection.swift deleted file mode 100644 index fcdcb4c09e..0000000000 --- a/macos/Sources/Lithe/Application/Features/DebugAutomaticExpressionProjection.swift +++ /dev/null @@ -1,104 +0,0 @@ -import Foundation - -/// Extracts source-referenced Java expressions for automatic debugger -/// inspection. The projection is intentionally deterministic and bounded so -/// selecting a stack frame cannot trigger an unbounded batch of evaluations. -enum DebugAutomaticExpressionProjection { - static let maximumExpressions = 8 - - private static let javaKeywords: Set = [ - "abstract", "assert", "boolean", "break", "byte", "case", "catch", - "char", "class", "const", "continue", "default", "do", "double", - "else", "enum", "extends", "false", "final", "finally", "float", - "for", "goto", "if", "implements", "import", "instanceof", "int", - "interface", "long", "native", "new", "null", "package", "private", - "protected", "public", "record", "return", "short", "static", "strictfp", - "super", "switch", "synchronized", "this", "throw", "throws", "transient", - "true", "try", "var", "void", "volatile", "while", "yield" - ] - - static func javaExpressions(forLine line: Int, in source: NSString) -> [String] { - guard let lineRange = lineRange(for: line, in: source) else { return [] } - let lineSource = source.substring(with: lineRange) as NSString - var values: [String] = [] - var known = Set() - var location = 0 - while location < lineSource.length, values.count < maximumExpressions { - guard isIdentifierStart(at: location, in: lineSource) else { - location += 1 - continue - } - let start = location - location += 1 - while location < lineSource.length, - isIdentifierCharacter(at: location, in: lineSource) { - location += 1 - } - let range = NSRange(location: start, length: location - start) - let token = lineSource.substring(with: range) - let previous = previousNonWhitespaceCharacter(before: start, in: lineSource) - let next = nextNonWhitespaceCharacter(after: location, in: lineSource) - guard !javaKeywords.contains(token), previous != ".", next != "(" else { continue } - if known.insert(token).inserted { values.append(token) } - } - return values - } - - private static func isIdentifierStart(at location: Int, in source: NSString) -> Bool { - guard let scalar = scalar(at: location, in: source) else { return false } - return CharacterSet.letters.union(CharacterSet(charactersIn: "_$")) - .contains(scalar) - } - - private static func isIdentifierCharacter(at location: Int, in source: NSString) -> Bool { - guard let scalar = scalar(at: location, in: source) else { return false } - return CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_$")) - .contains(scalar) - } - - private static func scalar(at location: Int, in source: NSString) -> UnicodeScalar? { - guard location >= 0, location < source.length else { return nil } - return UnicodeScalar(source.character(at: location)) - } - - private static func previousNonWhitespaceCharacter( - before location: Int, - in source: NSString - ) -> Character? { - var cursor = location - 1 - while cursor >= 0 { - guard let scalar = scalar(at: cursor, in: source) else { return nil } - if !CharacterSet.whitespacesAndNewlines.contains(scalar) { return Character(scalar) } - cursor -= 1 - } - return nil - } - - private static func nextNonWhitespaceCharacter( - after location: Int, - in source: NSString - ) -> Character? { - var cursor = location - while cursor < source.length { - guard let scalar = scalar(at: cursor, in: source) else { return nil } - if !CharacterSet.whitespacesAndNewlines.contains(scalar) { return Character(scalar) } - cursor += 1 - } - return nil - } - - private static func lineRange(for line: Int, in source: NSString) -> NSRange? { - guard line >= 0, source.length > 0 else { return nil } - var location = 0 - var currentLine = 0 - while currentLine < line, location < source.length { - let range = source.lineRange(for: NSRange(location: location, length: 0)) - let next = NSMaxRange(range) - guard next > location else { return nil } - location = next - currentLine += 1 - } - guard currentLine == line, location < source.length else { return nil } - return source.lineRange(for: NSRange(location: location, length: 0)) - } -} diff --git a/macos/Sources/Lithe/Application/Features/DebugLaunchPreparationCoordinator.swift b/macos/Sources/Lithe/Application/Features/DebugLaunchPreparationCoordinator.swift index b76121099b..e8b641f2d8 100644 --- a/macos/Sources/Lithe/Application/Features/DebugLaunchPreparationCoordinator.swift +++ b/macos/Sources/Lithe/Application/Features/DebugLaunchPreparationCoordinator.swift @@ -9,21 +9,10 @@ import LitheCoreContracts /// per-call closures. @MainActor final class DebugLaunchPreparationCoordinator { - enum PreparationError: LocalizedError { - case portUnavailable(Int) - - var errorDescription: String? { - switch self { - case .portUnavailable(let port): - return L10n.string("Port \(String(port)) is already in use. Stop the process using it or change server.port in the Run configuration.") - } - } - } - - private let notify: @MainActor (String) -> Void + private let notify: @MainActor (String, [String]) -> Void private weak var actions: (any DebugWorkflowActions)? - init(notify: @escaping @MainActor (String) -> Void) { + init(notify: @escaping @MainActor (String, [String]) -> Void) { self.notify = notify } @@ -41,7 +30,7 @@ final class DebugLaunchPreparationCoordinator { actions.recordSave(document, previousText: previousText) return true } catch { - notify("Could not save \(document.url.lastPathComponent)") + notify("Could not save %@", [document.url.lastPathComponent]) return false } } @@ -52,44 +41,26 @@ final class DebugLaunchPreparationCoordinator { errorMessage: String? ) -> Bool { guard launch() else { - notify(errorMessage ?? "Could not start debugging") + notify(errorMessage ?? "Could not start debugging", []) actions?.showDebugToolWindow() return false } return true } + /// Resolves the launch configuration of the plugin whose debug adapter + /// serves the provider's language. func prepare( provider: LanguageProviderDescriptor, fileURL: URL, workspaceURL: URL, - runFeature: RunFeatureModel, - resolver: DebugLaunchConfigurationResolver, - portChecker: any DebugPortAvailabilityChecking, - resolveJavaTarget: @escaping () async throws -> JavaDebugLaunchTarget? - ) async throws -> DebugLaunchConfiguration { - if provider.id == "java", - let selected = runFeature.selectedConfiguration, - let port = runFeature.configuredServerPort(for: selected), - !portChecker.isPortAvailable(port) { - throw PreparationError.portUnavailable(port) - } - - let selected = runFeature.selectedConfiguration - let configurations = runFeature.configurations - let selectedOptions = selected.map { runFeature.options(for: $0) } - let javaTarget = provider.id == "java" ? try await resolveJavaTarget() : nil + resolver: DebugLaunchConfigurationResolver + ) throws -> DebugLaunchConfiguration { try Task.checkCancellation() return try resolver.resolve( provider: provider, documentURL: fileURL, - workspaceURL: workspaceURL, - configurations: configurations, - selectedConfiguration: selected, - javaTarget: javaTarget, - options: { [runFeature] in - $0 == selected ? (selectedOptions ?? RunOptions()) : runFeature.options(for: $0) - } + workspaceURL: workspaceURL ) } } diff --git a/macos/Sources/Lithe/Application/Features/DebugPerformanceFeatureModel.swift b/macos/Sources/Lithe/Application/Features/DebugPerformanceFeatureModel.swift index ea0e9cc2a8..840e884a9c 100644 --- a/macos/Sources/Lithe/Application/Features/DebugPerformanceFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/DebugPerformanceFeatureModel.swift @@ -20,9 +20,9 @@ final class DebugPerformanceFeatureModel: ObservableObject { init(sampler: (any DebugPerformanceSampling)?) { self.sampler = sampler } func register(_ target: DebugPerformanceTarget, sessionID: UUID) { - guard target.processID > 0, (target.javaExecutable == nil || target.javaExecutable?.lastPathComponent == "java") else { return } + guard target.processID > 0 else { return } guard targets[sessionID] != target else { return } - // DAP restart can retain the session ID while launching a different JVM. + // DAP restart can retain the session ID while launching a different process. if targets[sessionID] != nil { histories.removeValue(forKey: sessionID) if activeSessionID == sessionID { samples = [] } @@ -59,10 +59,7 @@ final class DebugPerformanceFeatureModel: ObservableObject { isSampling = false errorMessage = nil guard isVisible, isActive else { return } - guard let id = activeSessionID, let target = targets[id], let sampler else { - errorMessage = "Performance is available for local Java processes launched by Lithe." - return - } + guard let id = activeSessionID, let target = targets[id], let sampler else { return } let current = generation isSampling = true task = Task { [weak self] in diff --git a/macos/Sources/Lithe/Application/Features/DebugSessionCleanupCoordinator.swift b/macos/Sources/Lithe/Application/Features/DebugSessionCleanupCoordinator.swift index f016a9d17c..6426e2652d 100644 --- a/macos/Sources/Lithe/Application/Features/DebugSessionCleanupCoordinator.swift +++ b/macos/Sources/Lithe/Application/Features/DebugSessionCleanupCoordinator.swift @@ -5,7 +5,7 @@ import LitheDebugModule /// Coordinates presentation and resource cleanup as a debug adapter session /// changes state. /// -/// A Java launch may request an integrated terminal before the adapter reaches +/// A launch may request an integrated terminal before the adapter reaches /// `running`, so terminal teardown is keyed on the session that owned it rather /// than stopping every debug terminal. @MainActor @@ -29,7 +29,6 @@ final class DebugSessionCleanupCoordinator { actions.showDebugToolWindow() actions.activateApplication() case .terminated, .failed: - actions.stopJavaTestResultServer() actions.stopDebugTerminalProcesses(for: activeSessionID) default: break diff --git a/macos/Sources/Lithe/Application/Features/DocumentFeatureModel.swift b/macos/Sources/Lithe/Application/Features/DocumentFeatureModel.swift index 3aff08de56..c952b70987 100644 --- a/macos/Sources/Lithe/Application/Features/DocumentFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/DocumentFeatureModel.swift @@ -83,7 +83,7 @@ enum StandaloneFileLoadState: Equatable { case failed(StandaloneFileOpenFailure) } -/// Owns editor document lifecycle and persistence-facing state. Java services, +/// Owns editor document lifecycle and persistence-facing state. Language services, /// local history, and UI notifications are supplied by application composition. @MainActor final class DocumentFeatureModel: ObservableObject { diff --git a/macos/Sources/Lithe/Application/Features/ExecutionFeatureAliases.swift b/macos/Sources/Lithe/Application/Features/ExecutionFeatureAliases.swift index 6b3ba5cc37..cb91084a72 100644 --- a/macos/Sources/Lithe/Application/Features/ExecutionFeatureAliases.swift +++ b/macos/Sources/Lithe/Application/Features/ExecutionFeatureAliases.swift @@ -3,5 +3,4 @@ import LitheExecutionModule typealias RunFeatureModel = LitheExecutionModule.RunFeatureModel typealias ProjectDevelopmentFeatureModel = LitheExecutionModule.ProjectDevelopmentFeatureModel typealias RunConfigurationGenerationIntent = LitheExecutionModule.RunConfigurationGenerationIntent -typealias JavaRunFeatureModel = LitheExecutionModule.RunFeatureModel typealias BuildSystemsFeatureModel = LitheExecutionModule.BuildSystemsFeatureModel diff --git a/macos/Sources/Lithe/Application/Features/IdeCapabilitiesFeatureModel.swift b/macos/Sources/Lithe/Application/Features/IdeCapabilitiesFeatureModel.swift index 3c1d29c81d..040ed12b4e 100644 --- a/macos/Sources/Lithe/Application/Features/IdeCapabilitiesFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/IdeCapabilitiesFeatureModel.swift @@ -11,15 +11,11 @@ final class IdeCapabilitiesFeatureModel: ObservableObject { /// Only workflows implemented by this product are advertised. Schema types /// and permissions remain in the shared catalog; this list can only narrow it. static let toolExposure: [[String: Any]] = [ - "lithe_project_inspect", "lithe_environment_inspect", "lithe_environment_configure", + "lithe_project_inspect", "lithe_run_list", "lithe_run_start", "lithe_run_restart", "lithe_operations_list", "lithe_operation_output", "lithe_operation_stop", "lithe_build_inspect", "lithe_build_reload", "lithe_build_configure", "lithe_build_execute" - ].map { name in - name == "lithe_environment_configure" - ? ["name": name, "arguments": ["javaHomePath", "mavenExecutablePath", "mavenJavaHomePath"]] - : ["name": name] - } + ].map { ["name": $0] } private let logSink: (any LogSink)? private weak var model: (any IdeCapabilityActions)? @Published private(set) var isEnabled = false @@ -157,32 +153,6 @@ final class IdeCapabilitiesFeatureModel: ObservableObject { private func execute(_ name: String, _ args: [String: Any], model: any IdeCapabilityActions, identity: WorkspaceIdentity, grant: String) async throws -> [String: Any] { if name == "lithe_project_inspect" { return ["workspaceID": model.id.uuidString, "name": model.projectName, "permissions": permissions] } - if name == "lithe_environment_inspect" || name == "lithe_environment_configure" { - await model.runtimeFeature.ensureRuntimesDiscovered() - try check(model, identity, grant: grant) - guard !model.runtimeFeature.hasChanges, !model.runtimeFeature.isSaving else { - return failed("BUSY", "Save or cancel the open environment settings draft before using this capability") - } - guard model.runtimeFeature.reloadToolchainSettings() else { - throw failure(model.runtimeFeature.settingsError ?? L10n.string("Could not verify the saved project environment settings. The previous preferences have been kept when possible.")) - } - if name == "lithe_environment_configure" { - model.runtimeFeature.updateSettings { settings in - if let value = args["javaHomePath"] as? String { settings.javaHomePath = value } - if let value = args["mavenJavaHomePath"] as? String { settings.mavenJavaHomePath = value } - if let value = args["mavenExecutablePath"] as? String { - settings.mavenHomeSelection = value.isEmpty ? .automatic : value == "mvnw" ? .wrapper : .custom - settings.mavenHomePath = value - } - } - guard model.runtimeFeature.saveSettings() else { - throw failure(model.runtimeFeature.settingsError ?? L10n.string("Could not verify the saved project environment settings. The previous preferences have been kept when possible.")) - } - model.runtimeFeature.finishSaving() - try check(model, identity, grant: grant) - } - return environment(model, root: identity.url) - } guard let execution = await model.activateExecutionModule() else { return failed("NOT_AVAILABLE", "The execution module is disabled") } try check(model, identity, grant: grant) let run = execution.runFeature @@ -361,33 +331,4 @@ final class IdeCapabilitiesFeatureModel: ObservableObject { private func runStatus(_ status: ProjectRunConfigurationStatus) -> String { switch status { case .missing: "missing"; case .ready: "ready"; case .invalid: "invalid" } } - - private func environment(_ model: any IdeCapabilityActions, root: URL) -> [String: Any] { - let feature = model.runtimeFeature - let settings = feature.settings - return ["scope": "project-local", "settings": ["javaHomePath": settings.javaHomePath, "mavenExecutablePath": settings.mavenExecutableOverride, "mavenJavaHomePath": settings.mavenJavaHomePath], "discovered": ["java": feature.javaRuntimes.map { ["homePath": $0.homePath, "version": $0.version, "vendor": $0.vendor] }, "maven": feature.mavenRuntimes.map { ["executablePath": $0.executablePath, "version": $0.version] }], "effective": ["java": choice(feature.javaChoice(overridePath: nil)), "mavenJava": choice(feature.mavenJavaChoice(overridePath: nil)), "maven": choice(feature.mavenChoice(at: root, overridePath: nil))]] - } - private func choiceSource(_ source: RuntimeChoiceSource) -> String { - switch source { - case .configured: "configured" - case .projectSetting: "project" - case .javaHomeEnvironment: "javaHome" - case .detected: "detected" - case .projectJDK: "projectJdk" - case .mavenWrapper: "mavenWrapper" - case .systemMaven: "path" - } - } - private func choice(_ value: RuntimeChoice?) -> [String: Any] { - switch value { - case .found(let url, let source): return ["status": "resolved", "path": url.path, "source": choiceSource(source)] - case .invalid(let path): return ["status": "invalid", "message": "Invalid toolchain: " + path] - case .fallback(let path, let next): var result = choice(next); result["invalidOverride"] = path; return result - case .warning(let url, let source, let message): - return ["status": "resolved", "path": url.path, "source": choiceSource(source), "warning": message] - case .unavailable(let message): return ["status": "invalid", "message": message] - case .notFound: return ["status": "notFound"] - case nil: return ["status": "loading"] - } - } } diff --git a/macos/Sources/Lithe/Application/Features/JavaFeatureModel.swift b/macos/Sources/Lithe/Application/Features/JavaFeatureModel.swift deleted file mode 100644 index 8f06a74850..0000000000 --- a/macos/Sources/Lithe/Application/Features/JavaFeatureModel.swift +++ /dev/null @@ -1,223 +0,0 @@ -import Combine -import Foundation -import LitheGitModule - -@MainActor -final class JavaLanguageServerPreparationOwner { - let workspaceURL: URL - var operationID: UUID - var task: Task? - - init(workspaceURL: URL, operationID: UUID) { - self.workspaceURL = workspaceURL.standardizedFileURL - self.operationID = operationID - } - - func cancel() { - task?.cancel() - task = nil - } -} - -enum JavaLanguageServerActivationReadiness { - case ready - case preparing -} - -enum JavaLanguageServerPreparationFailure { - case failed(message: String?) - case timedOut(message: String?) - - var message: String? { - switch self { - case .failed(let message), .timedOut(let message): message - } - } -} - -@MainActor -enum JavaLanguageServerWorkspaceState { - case idle - case preparing(owner: JavaLanguageServerPreparationOwner) - case ready(workspaceURL: URL, operationID: UUID) - case failed( - workspaceURL: URL, - operationID: UUID, - failure: JavaLanguageServerPreparationFailure - ) - - var operationID: UUID? { - switch self { - case .idle: nil - case .preparing(let owner): owner.operationID - case .ready(_, let operationID), - .failed(_, let operationID, _): operationID - } - } - - func belongs(to workspaceURL: URL) -> Bool { - switch self { - case .idle: false - case .preparing(let owner): owner.workspaceURL == workspaceURL.standardizedFileURL - case .ready(let ownedURL, _), - .failed(let ownedURL, _, _): - ownedURL == workspaceURL.standardizedFileURL - } - } -} - -/// Owns Java-only code vision and source structure behavior. -/// Java LSP navigation and editing are delegated to the Rust host. -@MainActor -final class JavaFeatureModel: ObservableObject { - @Published private(set) var javaCodeVisionHints: [URL: [JavaCodeVisionHint]] = [:] - private(set) var languageServerWorkspaceState: JavaLanguageServerWorkspaceState = .idle - - private let operations: any JavaMavenOperations - private var documentProvider: (@MainActor () -> EditorDocument?)? - private var loadBlame: (@MainActor (URL) async -> [GitBlameLine])? - - init(operations: any JavaMavenOperations) { - self.operations = operations - } - - func configure( - documentProvider: @escaping @MainActor () -> EditorDocument?, - loadBlame: @escaping @MainActor (URL) async -> [GitBlameLine] - ) { - self.documentProvider = documentProvider - self.loadBlame = loadBlame - } - - /// Explicit boundary for Java-only editor adornments and legacy services. - /// Callers can avoid scheduling Java work for every supported language. - func handles(fileURL: URL) -> Bool { - fileURL.pathExtension.lowercased() == "java" - } - - func stop() { - cancelLanguageServerPreparation() - javaCodeVisionHints = [:] - } - - func beginLanguageServerPreparation( - workspaceURL: URL, - operationID: UUID - ) -> JavaLanguageServerPreparationOwner { - let owner = JavaLanguageServerPreparationOwner( - workspaceURL: workspaceURL, - operationID: operationID - ) - languageServerWorkspaceState = .preparing(owner: owner) - return owner - } - - @discardableResult - func cancelLanguageServerPreparation() -> JavaLanguageServerPreparationOwner? { - let owner: JavaLanguageServerPreparationOwner? - if case .preparing(let currentOwner) = languageServerWorkspaceState { - owner = currentOwner - } else { - owner = nil - } - languageServerWorkspaceState = .idle - owner?.cancel() - return owner - } - - func ownsLanguageServerPreparation( - workspaceURL: URL, - operationID: UUID, - activeWorkspaceURL: URL? - ) -> Bool { - guard case .preparing(let owner) = languageServerWorkspaceState else { return false } - let normalizedURL = workspaceURL.standardizedFileURL - return owner.operationID == operationID - && owner.workspaceURL == normalizedURL - && activeWorkspaceURL?.standardizedFileURL == normalizedURL - } - - func markLanguageServerReady(workspaceURL: URL, operationID: UUID) { - languageServerWorkspaceState = .ready( - workspaceURL: workspaceURL.standardizedFileURL, - operationID: operationID - ) - } - - func markLanguageServerFailed( - workspaceURL: URL, - operationID: UUID, - failure: JavaLanguageServerPreparationFailure - ) { - languageServerWorkspaceState = .failed( - workspaceURL: workspaceURL.standardizedFileURL, - operationID: operationID, - failure: failure - ) - } - - var languageServerOperationID: UUID? { languageServerWorkspaceState.operationID } - - func languageServerStateBelongs(to workspaceURL: URL) -> Bool { - languageServerWorkspaceState.belongs(to: workspaceURL) - } - - var isLanguageServerPreparing: Bool { - if case .preparing = languageServerWorkspaceState { return true } - return false - } - - func close(_ document: EditorDocument) { - javaCodeVisionHints[document.url.standardizedFileURL] = nil - } - - func refreshCodeVision( - for document: EditorDocument, - projectFiles: [URL], - workspaceRoot: URL - ) async { - let normalizedURL = document.url.standardizedFileURL - guard normalizedURL.pathExtension.lowercased() == "java", !document.isReadOnly else { return } - let blame = await loadBlame?(normalizedURL) ?? [] - let baseHints = await codeVision( - for: normalizedURL, - projectFiles: projectFiles, - workspaceRoot: workspaceRoot, - blameLines: blame - ) - guard documentProvider?()?.id == document.id else { return } - javaCodeVisionHints[normalizedURL] = baseHints.map { hint in - JavaCodeVisionHint( - line: hint.line, - utf16Column: hint.utf16Column, - symbol: hint.symbol, - usageCount: hint.usageCount, - implementationCount: 0, - authorName: hint.authorName - ) - } - } - - func structure(source: String, declarationSources: [String] = []) async -> JavaStructureResult? { - let operations = self.operations - return await Task.detached(priority: .utility) { - operations.structure(source: source, declarationSources: declarationSources) - }.value - } - - func codeVision( - for fileURL: URL, - projectFiles: [URL], - workspaceRoot: URL, - blameLines: [GitBlameLine] - ) async -> [JavaCodeVisionHint] { - await JavaCodeVisionService.hints( - for: fileURL, - projectFiles: projectFiles, - workspaceRoot: workspaceRoot, - blameLines: blameLines, - operations: operations - ) - } - -} diff --git a/macos/Sources/Lithe/Application/Features/JavaPluginTransition.swift b/macos/Sources/Lithe/Application/Features/JavaPluginTransition.swift deleted file mode 100644 index 5da934c288..0000000000 --- a/macos/Sources/Lithe/Application/Features/JavaPluginTransition.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation -import LitheModuleAPI - -// Note: Java 独立分发与迁移见 .agents/notes/implemented/architecture/2026-10-25-java-plugin-distribution-foundation.md - -/// Suggests installation only when Java is needed and the package is absent. -/// Disabled, staged and pending-uninstall packages keep their management flow. -/// Removed packages can be restored explicitly; a suggestion never installs one. -enum JavaPluginTransition { - static func shouldSuggest(files: [URL], plugins: [PluginManagementSnapshot]) -> Bool { - guard !plugins.contains(where: { - $0.id == OfficialPluginCatalog.javaPluginID - && ($0.installationStatus != .removed || $0.hasChangesPendingRestart) - }), - let java = OfficialPluginCatalog.entry(for: OfficialPluginCatalog.javaPluginID) else { return false } - return files.contains { - java.fileExtensions.contains($0.pathExtension.lowercased()) - || java.projectFileNames.contains($0.lastPathComponent.lowercased()) - } - } -} diff --git a/macos/Sources/Lithe/Application/Features/JavaTestDebugWorkflowCoordinator.swift b/macos/Sources/Lithe/Application/Features/JavaTestDebugWorkflowCoordinator.swift deleted file mode 100644 index ed855cf06e..0000000000 --- a/macos/Sources/Lithe/Application/Features/JavaTestDebugWorkflowCoordinator.swift +++ /dev/null @@ -1,61 +0,0 @@ -import Foundation - -/// Coordinates the asynchronous Java test debug launch without owning the -/// generic debugger session itself. -/// -/// The launch is identified by an operation ID so a second Debug Test — or a -/// cancellation — cannot let an earlier launch adopt the result server or start -/// a session that is no longer wanted. -@MainActor -final class JavaTestDebugWorkflowCoordinator { - private let notify: @MainActor (String) -> Void - private weak var actions: (any DebugWorkflowActions)? - - init(notify: @escaping @MainActor (String) -> Void) { - self.notify = notify - } - - /// Held weakly: the application aggregate owns this coordinator. - func connect(actions: any DebugWorkflowActions) { - self.actions = actions - } - - func start( - request: JavaTestDebugRequest, - state: JavaTestWorkflowState, - prepareDirtyDocument: @escaping () async -> Bool, - prepareLaunch: @escaping () async throws -> PreparedJavaTestDebugLaunch, - startDebug: @escaping (PreparedJavaTestDebugLaunch) -> Bool, - errorMessage: @escaping () -> String? - ) { - let operationID = state.beginDebugLaunch() - state.debugLaunchTask = Task { @MainActor [weak self, weak state] in - guard let self, let state else { return } - defer { state.finishDebugLaunch(operationID, stopResultServer: false) } - guard state.isCurrentDebugLaunch(operationID) else { return } - guard await prepareDirtyDocument(), state.isCurrentDebugLaunch(operationID) else { return } - - do { - let prepared = try await prepareLaunch() - guard state.isCurrentDebugLaunch(operationID) else { - prepared.stop() - return - } - state.stopResultServer() - state.resultServer = prepared.resultServer - guard startDebug(prepared) else { - state.stopResultServer() - self.notify(errorMessage() ?? "Could not debug the Java test") - return - } - self.actions?.showDebugToolWindow() - } catch is CancellationError { - state.finishDebugLaunch(operationID, stopResultServer: true) - } catch { - guard state.isCurrentDebugLaunch(operationID) else { return } - state.finishDebugLaunch(operationID, stopResultServer: true) - self.notify(error.localizedDescription) - } - } - } -} diff --git a/macos/Sources/Lithe/Application/Features/JavaTestWorkflowState.swift b/macos/Sources/Lithe/Application/Features/JavaTestWorkflowState.swift deleted file mode 100644 index d55430b80a..0000000000 --- a/macos/Sources/Lithe/Application/Features/JavaTestWorkflowState.swift +++ /dev/null @@ -1,202 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheExecutionModule -import LitheLanguageIntelligenceModule - -/// Resolved Java test target passed into the asynchronous debug preparation. -struct JavaTestDebugRequest { - /// Source file containing the selected test. - let fileURL: URL - /// Optional semantic test identifier; `nil` means debug the whole file. - let testIdentifier: String? -} - -/// Owns cancellable state shared by Java test discovery and debug workflows. -@MainActor -final class JavaTestWorkflowState { - private let notify: @MainActor (String) -> Void - - init(notify: @escaping @MainActor (String) -> Void) { - self.notify = notify - } - - enum DebugRequestResolution { - case resolved(JavaTestDebugRequest) - case rejected(String) - } - - func resolveDebugRequest( - providerID: String, - scope: LanguageTestScope - ) -> DebugRequestResolution { - guard providerID == "java" else { - return .rejected("Java test debugging is currently available for Java projects only") - } - switch scope { - case .workspace: - return .rejected("Select a Java test file or test case to debug") - case .file(let url): - return .resolved( - JavaTestDebugRequest( - fileURL: url.standardizedFileURL, - testIdentifier: nil - ) - ) - case .testCase(let identifier, let url, _): - guard let url else { - return .rejected("The selected Java test has no source file") - } - return .resolved( - JavaTestDebugRequest( - fileURL: url.standardizedFileURL, - testIdentifier: identifier - ) - ) - } - } - - func projectDiscoveredItems( - _ baseItems: [LanguageTestItem], - workspaceURL: URL, - sessions: LanguageToolingSessionManager, - isCurrent: @MainActor (UUID) -> Bool, - operationID: UUID - ) async throws -> [LanguageTestItem] { - let javaFiles = baseItems.filter { $0.kind == .file && $0.fileURL != nil } - guard !javaFiles.isEmpty else { return baseItems } - var projected = baseItems.filter { $0.kind == .workspace } - var completedFileCount = 0 - for fileItem in javaFiles { - try Task.checkCancellation() - guard isCurrent(operationID), let fileURL = fileItem.fileURL else { - throw CancellationError() - } - do { - let details = try await sessions.discoverJavaTestItems( - fileURL: fileURL, - rootURL: workspaceURL - ) - completedFileCount += 1 - if !details.isEmpty { - projected.append(fileItem) - projected.append(contentsOf: details) - } - } catch is CancellationError { - throw CancellationError() - } catch { - projected.append(fileItem) - } - } - guard isCurrent(operationID) else { throw CancellationError() } - if projected.allSatisfy({ $0.kind == .workspace }), completedFileCount > 0 { - return [] - } - return projected - } - - /// Saves the test's source file when the editor holds unsaved changes, so - /// the debug launch compiles what the user sees. Returns `false` only when - /// the save failed, which must abort the launch. - func prepareDirtyDocument( - fileURL: URL, - documents: [EditorDocument], - saving: any EditorDocumentSaving - ) async -> Bool { - guard let document = documents.first(where: { - $0.url.standardizedFileURL == fileURL.standardizedFileURL - }), document.isDirty else { - return true - } - do { - let previousText = document.savedText - try await saving.save(document) - saving.recordSave(document, previousText: previousText) - return true - } catch { - notify("Could not save \(document.url.lastPathComponent)") - return false - } - } - - var runPreparationTask: Task? - private var runPreparationID: UUID? - - func beginRunPreparation() -> UUID { - cancelRunPreparation() - let id = UUID() - runPreparationID = id - return id - } - func isCurrentRunPreparation(_ id: UUID) -> Bool { runPreparationID == id && !Task.isCancelled } - func finishRunPreparation(_ id: UUID) { - guard runPreparationID == id else { return } - runPreparationID = nil - runPreparationTask = nil - } - func cancelRunPreparation() { - runPreparationID = nil - runPreparationTask?.cancel() - runPreparationTask = nil - } - - var resultServer: (any JavaTestResultServing)? - var debugLaunchTask: Task? - var debugLaunchOperationID: UUID? - var discoveryTask: Task? - var discoveryOperationID: UUID? - - func beginDiscovery() -> UUID { - cancelDiscovery() - let operationID = UUID() - discoveryOperationID = operationID - return operationID - } - - func beginDebugLaunch() -> UUID { - cancelDebugLaunch() - let operationID = UUID() - debugLaunchOperationID = operationID - return operationID - } - - func stopResultServer() { - resultServer?.stop() - resultServer = nil - } - - func cancelDebugLaunch() { - debugLaunchOperationID = nil - debugLaunchTask?.cancel() - debugLaunchTask = nil - stopResultServer() - } - - func finishDebugLaunch(_ operationID: UUID, stopResultServer: Bool) { - guard debugLaunchOperationID == operationID else { return } - debugLaunchOperationID = nil - debugLaunchTask = nil - if stopResultServer { - self.stopResultServer() - } - } - - func isCurrentDebugLaunch(_ operationID: UUID) -> Bool { - debugLaunchOperationID == operationID && !Task.isCancelled - } - - func cancelDiscovery() { - discoveryOperationID = nil - discoveryTask?.cancel() - discoveryTask = nil - } - - func isCurrentDiscovery(_ operationID: UUID) -> Bool { - discoveryOperationID == operationID && !Task.isCancelled - } - - func finishDiscovery(_ operationID: UUID) { - guard discoveryOperationID == operationID else { return } - discoveryOperationID = nil - discoveryTask = nil - } -} diff --git a/macos/Sources/Lithe/Application/Features/LSPControlCenterPresentation.swift b/macos/Sources/Lithe/Application/Features/LSPControlCenterPresentation.swift index 80d84f91e1..62b4d49f1e 100644 --- a/macos/Sources/Lithe/Application/Features/LSPControlCenterPresentation.swift +++ b/macos/Sources/Lithe/Application/Features/LSPControlCenterPresentation.swift @@ -46,13 +46,6 @@ enum LSPCapabilityPresentationState: Equatable, Sendable { case active } -enum MavenProfilePresentationState: Equatable, Sendable { - case idle - case applying - case partiallyFailed(failed: Int, total: Int) - case complete -} - enum LSPControlCenterPresenter { static func serverStatus( isDisabled: Bool, @@ -138,15 +131,4 @@ enum LSPControlCenterPresenter { } return isActive ? .active : .available } - - static func mavenProfileState( - _ results: [MavenProfileProjectResult] - ) -> MavenProfilePresentationState { - guard !results.isEmpty else { return .idle } - let failed = results.filter { $0.status == "failed" || $0.status == "timedOut" }.count - let running = results.contains { $0.status == "running" } - if running { return .applying } - if failed > 0 { return .partiallyFailed(failed: failed, total: results.count) } - return .complete - } } diff --git a/macos/Sources/Lithe/Application/Features/LanguageTestWorkflowState.swift b/macos/Sources/Lithe/Application/Features/LanguageTestWorkflowState.swift new file mode 100644 index 0000000000..b62d729393 --- /dev/null +++ b/macos/Sources/Lithe/Application/Features/LanguageTestWorkflowState.swift @@ -0,0 +1,55 @@ +import Foundation + +/// Owns the cancellable tasks behind test discovery and test run preparation. +/// +/// Each operation gets an identity so a replaced or cancelled task cannot clear +/// or publish over the state of the task that superseded it. +@MainActor +final class LanguageTestWorkflowState { + var runPreparationTask: Task? + private var runPreparationID: UUID? + + func beginRunPreparation() -> UUID { + cancelRunPreparation() + let id = UUID() + runPreparationID = id + return id + } + func isCurrentRunPreparation(_ id: UUID) -> Bool { runPreparationID == id && !Task.isCancelled } + func finishRunPreparation(_ id: UUID) { + guard runPreparationID == id else { return } + runPreparationID = nil + runPreparationTask = nil + } + func cancelRunPreparation() { + runPreparationID = nil + runPreparationTask?.cancel() + runPreparationTask = nil + } + + var discoveryTask: Task? + var discoveryOperationID: UUID? + + func beginDiscovery() -> UUID { + cancelDiscovery() + let operationID = UUID() + discoveryOperationID = operationID + return operationID + } + + func cancelDiscovery() { + discoveryOperationID = nil + discoveryTask?.cancel() + discoveryTask = nil + } + + func isCurrentDiscovery(_ operationID: UUID) -> Bool { + discoveryOperationID == operationID && !Task.isCancelled + } + + func finishDiscovery(_ operationID: UUID) { + guard discoveryOperationID == operationID else { return } + discoveryOperationID = nil + discoveryTask = nil + } +} diff --git a/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift b/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift index 5fa32b2321..cbce00c438 100644 --- a/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/LanguageToolingFeatureModel.swift @@ -12,12 +12,10 @@ final class LanguageToolingFeatureModel: ObservableObject { @Published private(set) var catalog: LanguageProviderCatalog @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] = [:] @@ -31,7 +29,6 @@ final class LanguageToolingFeatureModel: ObservableObject { private var notify: (@MainActor (String) -> Void)? var notifyLog: ((String, LogRecordReference?) -> Void)? var logSink: (any LogSink)? - private var preparationCancellations: [String: @MainActor () -> Void] = [:] private var activationEpoch = UUID() private var activationGenerations: [String: UUID] = [:] private var restartTasks: [String: Task] = [:] @@ -47,14 +44,9 @@ final class LanguageToolingFeatureModel: ObservableObject { ActivationToken(epoch: activationEpoch, generation: activationGenerations[providerID]) } - func registerPreparationCancellation(providerID: String, cancel: @escaping @MainActor () -> Void) { - preparationCancellations[providerID] = cancel - } - private func prepareToStop(providerID: String) { restartTasks.removeValue(forKey: providerID)?.cancel() activationGenerations[providerID] = UUID() - preparationCancellations[providerID]?() } init( @@ -86,13 +78,10 @@ final class LanguageToolingFeatureModel: ObservableObject { sessionsProvider = provider } - func bindProjectPreparation(_ sessions: LanguageToolingSessionManager) { + func bindSessions(_ sessions: LanguageToolingSessionManager) { statusObservation = Publishers.CombineLatest(sessions.$languageServerStates, sessions.$languageServerInfos) .map { LanguageServerRuntimeSnapshot(states: $0, infos: $1) } .removeDuplicates().sink { [weak self] in self?.serverRuntimeSnapshot = $0 } - preparationObservation = sessions.$projectPreparation.removeDuplicates().sink { [weak self] snapshot in - self?.projectPreparation = snapshot - } pluginStatusObservation = sessions.$pluginServerStatuses.removeDuplicates().sink { [weak self] statuses in self?.pluginServerStatuses = statuses } @@ -104,7 +93,6 @@ final class LanguageToolingFeatureModel: ObservableObject { activationEpoch = UUID() activationGenerations.removeAll() serverRuntimeSnapshot = LanguageServerRuntimeSnapshot() - projectPreparation = nil startupFailures.removeAll() } @@ -143,7 +131,7 @@ final class LanguageToolingFeatureModel: ObservableObject { projectUsage.reset() self.workspaceURL = workspaceURL?.standardizedFileURL // Restore preferences before workspace restoration can activate documents - // or prewarm Java. Runtime resets must not erase explicit user choices. + // or prewarm servers. Runtime resets must not erase explicit user choices. disabledProviderIDs = self.workspaceURL.map { preferences.disabledProviderIDs(for: $0) } ?? [] resetWorkspaceState() let snapshot = catalogSource.load(workspaceURL: workspaceURL) diff --git a/macos/Sources/Lithe/Application/Features/MybatisFeatureModel.swift b/macos/Sources/Lithe/Application/Features/MybatisFeatureModel.swift deleted file mode 100644 index d62c137722..0000000000 --- a/macos/Sources/Lithe/Application/Features/MybatisFeatureModel.swift +++ /dev/null @@ -1,139 +0,0 @@ -import Combine -import Foundation -import LitheCoreContracts - -/// Owns the workspace-level MyBatis mapper/XML projection produced by Rust Core. -@MainActor -final class MybatisFeatureModel: ObservableObject { - @Published private(set) var statements: [MybatisStatement] = [] - @Published private(set) var isIndexing = false - - private let operations: any JavaMavenOperations - private var generation = UUID() - private var reloadTask: Task? - - init(operations: any JavaMavenOperations) { - self.operations = operations - } - - func load( - workspaceURL: URL, - files: [URL], - textOverrides: [URL: String] = [:] - ) async { - generation = UUID() - let currentGeneration = generation - isIndexing = true - let operations = self.operations - let indexedFiles = files.filter(MybatisIndexPaths.matches) - let result = await Task.detached(priority: .utility) { - operations.mybatisIndex( - at: workspaceURL, - files: indexedFiles, - textOverrides: textOverrides - ) - }.value ?? .empty - guard generation == currentGeneration else { return } - statements = result.statements - isIndexing = false - } - - /// Starts a workspace index without making the caller wait for it. Opening a - /// project must not block run state behind mapper indexing. - func scheduleLoad( - workspaceURL: URL, - files: [URL], - textOverrides: [URL: String] = [:] - ) { - reloadTask?.cancel() - reloadTask = Task { @MainActor [weak self] in - guard !Task.isCancelled, let self else { return } - await self.load( - workspaceURL: workspaceURL, - files: files, - textOverrides: textOverrides - ) - } - } - - func reset() { - reloadTask?.cancel() - reloadTask = nil - generation = UUID() - statements = [] - isIndexing = false - } - - func scheduleReload( - changedDocument: EditorDocument, - workspaceURL: URL, - files: [URL], - openDocuments: [EditorDocument] - ) { - guard editChangesIndex(changedDocument.url) else { return } - reloadTask?.cancel() - reloadTask = Task { @MainActor [weak self] in - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - try? await Task.sleep(for: .milliseconds(300)) - guard !Task.isCancelled, let self else { return } - let overrides = Dictionary(uniqueKeysWithValues: openDocuments.map { - ($0.url.standardizedFileURL, $0.text) - }) - await self.load( - workspaceURL: workspaceURL, - files: files, - textOverrides: overrides - ) - } - } - - /// A temporarily unpaired Java buffer can add or restore its first mapper - /// method. Core prunes unrelated reads using XML namespaces; successful - /// statement pairs are not a complete set of invalidation candidates. - func editChangesIndex(_ url: URL) -> Bool { - let ext = url.pathExtension.lowercased() - return ext == "java" || ext == "xml" - } - - func handles(_ url: URL) -> Bool { - let normalized = url.standardizedFileURL - return statements.contains { - $0.javaURL.standardizedFileURL == normalized - || $0.xmlURL.standardizedFileURL == normalized - } - } - - func navigationLocations(for url: URL, line: Int, utf16Column: Int) -> [LanguageServerLocation] { - let normalized = url.standardizedFileURL - let fromJava = statements.compactMap { statement -> LanguageServerLocation? in - guard statement.javaURL.standardizedFileURL == normalized, - statement.matchesJavaName(line: line, utf16Column: utf16Column) else { return nil } - return location(statement.xmlURL, line: statement.xmlLine, column: statement.xmlColumn) - } - if !fromJava.isEmpty { return unique(fromJava) } - return unique(statements.compactMap { statement in - guard statement.xmlURL.standardizedFileURL == normalized, - statement.matchesXmlId(line: line, utf16Column: utf16Column) else { return nil } - return location(statement.javaURL, line: statement.javaLine, column: statement.javaColumn) - }) - } - - private func location(_ url: URL, line: Int, column: Int) -> LanguageServerLocation { - let position = LanguageServerPosition( - line: max(0, line - 1), - utf16Column: max(0, column - 1) - ) - return LanguageServerLocation( - url: url, - range: LanguageServerRange(start: position, end: position) - ) - } - - private func unique(_ locations: [LanguageServerLocation]) -> [LanguageServerLocation] { - var seen = Set() - return locations.filter { location in - let key = "\(location.url.standardizedFileURL.path):\(location.range.start.line):\(location.range.start.utf16Column)" - return seen.insert(key).inserted - } - } -} diff --git a/macos/Sources/Lithe/Application/Features/NewProjectFeatureModel.swift b/macos/Sources/Lithe/Application/Features/NewProjectFeatureModel.swift index ece5d7ddba..d0928a9e0f 100644 --- a/macos/Sources/Lithe/Application/Features/NewProjectFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/NewProjectFeatureModel.swift @@ -11,16 +11,14 @@ struct NewProjectEnvironment { /// a plugin enabled from the window takes effect at once. let sources: @MainActor () -> [ProjectGeneratorPluginSource] let iconResources: [String: PluginUIIconResources] - /// Discovered JDKs, best first; the window may run without a project. - let javaRuntimes: @MainActor () async -> [JavaRuntimeCandidate] let service: ProjectGenerationService let setPluginEnabled: @MainActor (PluginID) async throws -> Void /// Opens plugin management on the marketplace with a search. let openMarketplace: @MainActor (String) -> Void let openProject: @MainActor (CreatedProject) -> Void let store: any KeyValueStore - /// Installations of the tools `tool` fields pick, by tool definition ID and - /// best first. A new project has no workspace yet, so this is the + /// Installations of the tools `tool` and `runtime` fields pick, by tool + /// definition ID and best first. A new project has no workspace yet, so this is the /// machine-wide discovery; a tool nothing defines is simply absent. Throws /// when discovery could not run, which is not the same as nothing found. var toolInstallations: @MainActor ([String]) async throws -> [String: [ProjectToolInstallation]] = { _ in [:] } @@ -65,9 +63,6 @@ final class NewProjectFeatureModel: ObservableObject { static let defaultLocation = "~/LitheProjects" @Published private(set) var entries: [ProjectGeneratorEntry] = [] - var isJavaSupportMissing: Bool { - !sources.contains { $0.pluginID == OfficialPluginCatalog.javaPluginID } - } @Published private(set) var catalogError: String? @Published var selection: Selection = .empty { didSet { if oldValue != selection { selectionChanged() } } @@ -86,10 +81,6 @@ final class NewProjectFeatureModel: ObservableObject { @Published private(set) var formState: ProjectGeneratorFormState? @Published private(set) var nameProblem: ProjectFieldProblem? @Published private(set) var formError: String? - @Published private(set) var javaRuntimes: [JavaRuntimeCandidate] = [] - /// Set once JDK discovery finished, so an empty list reads as "none - /// installed" rather than "still looking". - @Published private(set) var hasLoadedJavaRuntimes = false @Published private(set) var isCreating = false @Published private(set) var progressOutput = "" @Published private(set) var errorMessage: String? @@ -129,14 +120,16 @@ final class NewProjectFeatureModel: ObservableObject { // MARK: Catalog - /// Loads the entries and JDKs; called when the window appears. + /// Loads the entries and the installations the first selected entry's + /// fields pick; called when the window appears. func load() async { reloadCatalog() if selection == .empty, let first = entries.first(where: { $0.generator.section == .project }) { selection = .generator(first.id) } - javaRuntimes = await environment.javaRuntimes() - hasLoadedJavaRuntimes = true + // Selecting the entry started the lookup; waiting for it lets the + // window open on runtime fields that already hold an installation. + await toolListing?.value evaluate() } @@ -215,7 +208,13 @@ final class NewProjectFeatureModel: ObservableObject { evaluate() } - /// The JDK chosen for a runtime field, by home path. + /// The installations a runtime field offers, best first: those found for + /// the tool definition its `runtime` names, like a `tool` field's. + func runtimeInstallations(for field: ProjectGeneratorField) -> [ProjectToolInstallation] { + field.runtime.flatMap { listedTools[$0] } ?? [] + } + + /// The installation chosen for a runtime field, by home path. func selectedRuntimeHome(for field: ProjectGeneratorField) -> String { guard let entry = selectedEntry else { return "" } return input(for: entry).runtimes[field.id]?.home ?? "" @@ -223,9 +222,9 @@ final class NewProjectFeatureModel: ObservableObject { func selectRuntime(home: String, for field: ProjectGeneratorField) { guard let entry = selectedEntry, - let runtime = javaRuntimes.first(where: { $0.homePath == home }) else { return } + let runtime = runtimeInstallations(for: field).first(where: { $0.home == home }) else { return } var input = input(for: entry) - input.runtimes[field.id] = ProjectRuntimeSelection(home: runtime.homePath, version: runtime.version) + input.runtimes[field.id] = ProjectRuntimeSelection(home: runtime.home, version: runtime.version) inputs[entry.id] = input evaluate() } @@ -277,21 +276,33 @@ final class NewProjectFeatureModel: ObservableObject { for field in entry.generator.fields where field.kind == .tool { input.tools[field.id] = field.tool.flatMap { listedTools[$0] } ?? [] } - // Every runtime field starts on the best JDK the generator accepts. - for field in entry.generator.fields where field.kind == .runtime && input.runtimes[field.id] == nil { - if let runtime = Self.preferredRuntime(javaRuntimes, minimum: field.minimumVersion) { - input.runtimes[field.id] = ProjectRuntimeSelection(home: runtime.homePath, version: runtime.version) - } + // Every runtime field starts on the best installation the generator + // accepts, and moves to it again when the chosen one is no longer + // listed. Until its tool is listed the field keeps what it holds. + for field in entry.generator.fields where field.kind == .runtime { + guard let found = field.runtime.flatMap({ listedTools[$0] }) else { continue } + if let chosen = input.runtimes[field.id], found.contains(where: { $0.home == chosen.home }) { continue } + input.runtimes[field.id] = Self.preferredRuntime(found, minimum: field.minimumVersion) + .map { ProjectRuntimeSelection(home: $0.home, version: $0.version) } } return input } - static func preferredRuntime(_ runtimes: [JavaRuntimeCandidate], minimum: String?) -> JavaRuntimeCandidate? { - let minimumMajor = minimum.flatMap { Int($0.split(separator: ".").first ?? "") } ?? 0 - return runtimes - .filter { ($0.majorVersion ?? 0) >= minimumMajor } - .max { ($0.majorVersion ?? 0) < ($1.majorVersion ?? 0) } - ?? runtimes.first + /// The first installation, in the host's best-first order, whose version is + /// at least `minimum`, or else the first one. Versions compare by their + /// numeric dot-separated parts with trailing zeros ignored, as Rust Core + /// compares them, so the pick is one Core does not report as too old. + static func preferredRuntime(_ installations: [ProjectToolInstallation], minimum: String?) -> ProjectToolInstallation? { + guard let minimum else { return installations.first } + let floor = releaseComponents(minimum) + return installations.first { !releaseComponents($0.version).lexicographicallyPrecedes(floor) } + ?? installations.first + } + + private static func releaseComponents(_ version: String) -> [Int] { + var numbers = version.split(separator: ".").compactMap { Int($0) } + while numbers.last == 0 { numbers.removeLast() } + return numbers } private func selectionChanged() { @@ -390,20 +401,30 @@ final class NewProjectFeatureModel: ObservableObject { return .findInMarketplace(query) } - /// The distinct tools the entry's tool fields pick, in declaration order. + /// The distinct tools the entry's tool and runtime fields pick, in + /// declaration order. private func toolIDs(of entry: ProjectGeneratorEntry?) -> [String] { var seen = Set() return (entry?.generator.fields ?? []) - .filter { $0.kind == .tool } - .compactMap(\.tool) + .compactMap(Self.listedToolID(of:)) .filter { seen.insert($0).inserted } } + /// The tool definition whose installations a field picks from: a `tool` + /// field's `tool`, or a `runtime` field's `runtime`; nil for other fields. + private static func listedToolID(of field: ProjectGeneratorField) -> String? { + switch field.kind { + case .tool: field.tool + case .runtime: field.runtime + case .text, .enum, .boolean, .multiSelect: nil + } + } + /// Why the installations of the field's tool could not be looked up, or /// nil when they were (or are still being) looked up. func toolListingError(for field: ProjectGeneratorField) -> String? { guard !isListingTools else { return nil } - return field.tool.flatMap { toolListingFailures[$0] } + return Self.listedToolID(of: field).flatMap { toolListingFailures[$0] } } /// Looks the selected generator's tools up again after a failure. diff --git a/macos/Sources/Lithe/Application/Features/PluginEditorActionLaunch.swift b/macos/Sources/Lithe/Application/Features/PluginEditorActionLaunch.swift new file mode 100644 index 0000000000..ee955de5d5 --- /dev/null +++ b/macos/Sources/Lithe/Application/Features/PluginEditorActionLaunch.swift @@ -0,0 +1,155 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +// Note: 独立扩展点与领域契约的边界见 .agents/notes/implemented/architecture/2026-10-31-plugin-capability-and-domain-boundaries.md + +/// One action a plugin answered for a document, kept with the binding it came +/// from so a later click can be validated against that same binding. +struct PluginEditorActionItem: Equatable { + let registration: PluginEditorActionRegistration + let action: PluginEditorAction +} + +/// The toolbar button a plugin-owned language maps onto its editor actions. +enum PluginEditorActionIntent: Equatable { + case run + case debug +} + +/// The function one toolbar click calls among a document's plugin actions. +struct PluginEditorActionChoice: Equatable { + let item: PluginEditorActionItem + let invocation: PluginEditorAction.Invocation + let alternativeID: String? +} + +/// Maps the host's Run and Debug buttons onto a plugin's own editor actions. +/// +/// The host does not know what an action does; it only picks by the plugin's +/// declared presentation token. Run takes the first `run`/`run-all` action in +/// document order and Debug takes that action's `debug` alternative (or an +/// action drawn with `debug` itself), so the toolbar reaches the same plugin +/// function a gutter click would. No match leaves the decision to the caller. +enum PluginEditorActionLaunchSelection { + static let runIcons: Set = ["run", "run-all"] + static let debugIcon = "debug" + + static func choose(_ items: [PluginEditorActionItem], intent: PluginEditorActionIntent) -> PluginEditorActionChoice? { + let ordered = items.enumerated().sorted { lhs, rhs in + let left = lhs.element.action.range.start, right = rhs.element.action.range.start + if left.line != right.line { return left.line < right.line } + if left.column != right.column { return left.column < right.column } + return lhs.offset < rhs.offset + }.map(\.element) + switch intent { + case .run: + guard let item = ordered.first(where: { runIcons.contains($0.action.icon) }) else { return nil } + return PluginEditorActionChoice(item: item, invocation: item.action.invoke, alternativeID: nil) + case .debug: + for item in ordered where runIcons.contains(item.action.icon) { + if let alternative = item.action.alternatives.first(where: { $0.icon == debugIcon }) { + return PluginEditorActionChoice(item: item, invocation: alternative.invoke, alternativeID: alternative.id) + } + } + guard let item = ordered.first(where: { $0.action.icon == debugIcon }) else { return nil } + return PluginEditorActionChoice(item: item, invocation: item.action.invoke, alternativeID: nil) + } + } +} + +/// Collects a document's plugin editor actions and invokes a chosen one, the +/// same way for the gutter and the toolbar: one collection budget across all +/// bindings, per-binding failures logged and skipped, every function checked +/// against the live registration before and after the backend answers. +@MainActor +struct PluginEditorActionCollector { + let service: PluginEditorActionHostService + let backends: any PluginBackendRequesting + let workspace: PluginWorkspaceContextReference + let logSink: (any LogSink)? + + /// At most this many actions are kept for one document; more empties the answer. + static let maximumActions = 1000 + + /// `path` is the document's workspace-relative path, nil outside the workspace. + static func input(documentID: String, version: UInt64, path: String?, text: String) -> ToolingJSONValue { + .object([ + "document": .object([ + "documentID": .string(documentID), + "version": .integer(Int(clamping: version)), + "path": path.map(ToolingJSONValue.string) ?? .null, + ]), + "text": .string(text), + ]) + } + + static func workspaceRelativePath(of url: URL, root: URL?) -> String? { + guard let root else { return nil } + let prefix = root.standardizedFileURL.path + "/", path = url.standardizedFileURL.path + return path.hasPrefix(prefix) ? String(path.dropFirst(prefix.count)) : nil + } + + /// Whether `document` can be collected on this host at all. + static func admits(_ document: EditorDocument, service: PluginEditorActionHostService) -> Bool { + document.text.utf8.count <= service.host.actionSourceBytes + } + + func registrations(for document: EditorDocument) -> [PluginEditorActionRegistration] { + service.registrations(context: workspace, filename: document.url.lastPathComponent) + } + + /// Asks every binding in turn. Throws only `CancellationError`. + func collect( + documentID: String, version: UInt64, path: String?, text: String, + registrations: [PluginEditorActionRegistration] + ) async throws -> [PluginEditorActionItem] { + let input = Self.input(documentID: documentID, version: version, path: path, text: text) + var items: [PluginEditorActionItem] = [] + let clock = ContinuousClock(), started = clock.now + for registration in registrations { + do { + try Task.checkCancellation() + guard let remaining = PluginEditorActionCollectionBudget.remaining(after: started.duration(to: clock.now)) else { break } + guard service.contains(registration) else { continue } + let result = try await backends.invokePluginFunction(registration.functionID, params: input, + ofPlugin: registration.pluginID, context: workspace, timeout: remaining, progress: { _ in }) + try Task.checkCancellation() + let actions = try service.decode(result, text: text) + guard service.contains(registration), + actions.allSatisfy({ action in action.functionIDs.allSatisfy { service.contains(registration, functionID: $0) } }) + else { continue } + items.append(contentsOf: actions.map { PluginEditorActionItem(registration: registration, action: $0) }) + guard items.count <= Self.maximumActions else { return [] } + } catch is CancellationError { + throw CancellationError() + } catch { + if Task.isCancelled { throw CancellationError() } + if let plugin = LogSegment(registration.pluginID) { logSink?.emit(PluginsEditorActionsFailed(error: error, plugin: plugin)) } + } + } + return items + } + + /// Whether every function `items` would call is still registered. + func stillRegistered(_ items: [PluginEditorActionItem]) -> Bool { + items.allSatisfy { item in item.action.functionIDs.allSatisfy { service.contains(item.registration, functionID: $0) } } + } + + /// Calls the chosen function through the ordinary invocation lifecycle and + /// returns the locations the plugin asks the host to reveal, if any. + func invoke( + _ choice: PluginEditorActionChoice, documentID: String, expectedVersion: UInt64 + ) async throws -> PluginEditorReveal? { + var members: [String: ToolingJSONValue] = [ + "documentID": .string(documentID), "expectedVersion": .integer(Int(clamping: expectedVersion)), + "actionID": .string(choice.item.action.id), "data": choice.invocation.params, + ] + if let alternativeID = choice.alternativeID { members["alternativeID"] = .string(alternativeID) } + let result = try await backends.invokePluginFunction(choice.invocation.functionID, params: .object(members), + ofPlugin: choice.item.registration.pluginID, context: choice.item.registration.context, + timeout: .seconds(60), progress: { _ in }) + try Task.checkCancellation() + return try service.decodeReveal(result) + } +} diff --git a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift index 87d8da06a8..b78091f609 100644 --- a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift +++ b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift @@ -80,7 +80,7 @@ enum PluginHostErrorCode: String, Sendable, CaseIterable { /// A failed host service request. The message reaches the backend, so it /// never carries a secret or a path the plugin may not see. -struct PluginHostServiceError: Error, Equatable, Sendable { +struct PluginHostServiceError: LocalizedError, Equatable, Sendable { let code: PluginHostErrorCode let message: String /// Facts the backend may act on, such as `{ currentVersion }` of a @@ -98,6 +98,10 @@ struct PluginHostServiceError: Error, Equatable, Sendable { lhs.code == rhs.code && lhs.message == rhs.message && lhs.details == rhs.details } + /// The host's own wording of the refusal, so a log line names which + /// check failed instead of the bridged NSError's generic text. + var errorDescription: String? { message } + var failure: PluginHostRequestFailure { PluginHostRequestFailure(message: message, code: code.rawValue, details: details.map { .object($0) }) } @@ -415,8 +419,10 @@ final class PluginHostServiceDispatcher { case .success(let value): decision = value case .failure(let error): if let plugin = LogSegment(pluginID) { - logSink?.emit(PluginsHostRequestFailed(error: LogFailure(domain: "RustCore", code: error.code), - plugin: plugin, operationID: request.id)) + logSink?.emit(PluginsHostRequestFailed( + code: PluginHostErrorCode.unavailable.rawValue, error: LogFailure(domain: "RustCore", code: error.code), + method: request.method, plugin: plugin, operationID: request.id + )) } return .failure(PluginHostServiceError(.unavailable, L10n.string("The plugin is not allowed to use the host service \(request.service).") @@ -468,7 +474,10 @@ final class PluginHostServiceDispatcher { ) let result = await handler.answer(call) if case .failure(let failure) = result, failure.code != .cancelled, let plugin = LogSegment(pluginID) { - logSink?.emit(PluginsHostRequestFailed(error: failure.logError ?? LogFailure(domain: "PluginHost", code: failure.code.rawValue), plugin: plugin, operationID: request.id)) + logSink?.emit(PluginsHostRequestFailed( + code: failure.code.rawValue, error: failure.logError ?? LogFailure(domain: "PluginHost", code: failure.code.rawValue), + method: request.method, plugin: plugin, operationID: request.id + )) } return result.mapError(\.failure) } diff --git a/macos/Sources/Lithe/Application/Features/PluginRunHostService.swift b/macos/Sources/Lithe/Application/Features/PluginRunHostService.swift index 64b849d9b9..3ccc0a25d2 100644 --- a/macos/Sources/Lithe/Application/Features/PluginRunHostService.swift +++ b/macos/Sources/Lithe/Application/Features/PluginRunHostService.swift @@ -154,11 +154,16 @@ final class PluginRunHostService: PluginHostServiceHandling { } /// The installation the user's layers choose for `tool`. Project code is allowed, as for any Run. + /// + /// Core expands the definition's `launch` template afterwards (`expand`), so the tool is + /// resolved as an installation: a template with `${runtimeArguments}` or wrapper flags is + /// as valid here as the bare `["${executable}", "${arguments}"]` a direct launch needs. private func select(_ tool: String, start: PluginRunStart, workspace: URL, environment: [String: String]) async throws -> ResolvedDefinedToolchain { do { if let selected = try await tools.resolve(tool: tool, directory: start.workingDirectory, workspace: workspace, - environment: environment, minimumVersion: nil, projectCodeAllowed: true) { + environment: environment, minimumVersion: nil, projectCodeAllowed: true, + fixed: nil, use: .installation, consumerID: nil) { return selected } } catch is BuildToolResolutionError { diff --git a/macos/Sources/Lithe/Application/Features/ProcessExitCoordinator.swift b/macos/Sources/Lithe/Application/Features/ProcessExitCoordinator.swift index 3d4f49d11b..11ce559505 100644 --- a/macos/Sources/Lithe/Application/Features/ProcessExitCoordinator.swift +++ b/macos/Sources/Lithe/Application/Features/ProcessExitCoordinator.swift @@ -17,7 +17,7 @@ struct TerminalExitCandidate: Equatable, Sendable { var recordID: String { "terminal:\(sessionID.uuidString)" } } -/// A Run configuration or Maven goal that is still running in a project. +/// A Run configuration or build task that is still running in a project. struct RunServiceExitCandidate: Equatable, Sendable { /// Lifecycle record ID; unique across the projects being closed. let id: String diff --git a/macos/Sources/Lithe/Application/Features/RunBrowserState.swift b/macos/Sources/Lithe/Application/Features/RunBrowserState.swift index 98930455c7..fcc955e059 100644 --- a/macos/Sources/Lithe/Application/Features/RunBrowserState.swift +++ b/macos/Sources/Lithe/Application/Features/RunBrowserState.swift @@ -70,11 +70,11 @@ struct RunBrowserState { checkedIDs.formIntersection(configurations.filter { !$0.usesCurrentEditorFile }.map(\.id)) } - /// Group by the provider's presentation family; all JVM entry points share - /// Java while unfamiliar providers keep their own visible group. + /// Group by provider; the host knows no language families, so a plugin + /// that wants several providers shown together gives them one provider ID. static func groups(for configurations: [RunConfiguration]) -> [ApplicationGroup] { let grouped = Dictionary(grouping: configurations.filter { !$0.usesCurrentEditorFile }) { - $0.kind.capabilities.contains(.javaRuntime) ? "java" : $0.kind.providerID + $0.kind.providerID } return grouped.map { id, configurations in let sorted = configurations.sorted { @@ -84,8 +84,8 @@ struct RunBrowserState { let kind = sorted[0].kind return ApplicationGroup( id: id, - title: id == "java" ? "Java" : kind.title, - iconKind: id == "java" ? .javaMain : kind, + title: kind.title, + iconKind: kind, configurations: sorted ) }.sorted { diff --git a/macos/Sources/Lithe/Application/Features/RunWorkflowCoordinator.swift b/macos/Sources/Lithe/Application/Features/RunWorkflowCoordinator.swift index f6a924afdb..ed45730a6c 100644 --- a/macos/Sources/Lithe/Application/Features/RunWorkflowCoordinator.swift +++ b/macos/Sources/Lithe/Application/Features/RunWorkflowCoordinator.swift @@ -41,7 +41,6 @@ enum RunConfigurationReadiness { enum DebugSourceResolution { case resolved(URL) case currentFileUnavailable - case javaSourceUnavailable(String) case unsupported(String) } @@ -105,14 +104,15 @@ final class RunWorkflowCoordinator { private let pluginCatalog: ValidatedPluginCatalog private let moduleRuntime: ModuleRuntime - private let notify: @MainActor (String) -> Void + /// A localization key and its `%@` arguments, resolved when shown. + private let notify: @MainActor (String, [String]) -> Void private let onPendingActionChange: @MainActor () -> Void private weak var actions: (any RunWorkflowActions)? init( pluginCatalog: ValidatedPluginCatalog, moduleRuntime: ModuleRuntime, - notify: @escaping @MainActor (String) -> Void, + notify: @escaping @MainActor (String, [String]) -> Void, onPendingActionChange: @escaping @MainActor () -> Void = {} ) { self.pluginCatalog = pluginCatalog @@ -143,30 +143,12 @@ final class RunWorkflowCoordinator { runFeature.select(selected) } - func debugConfiguration( - selected: RunConfiguration, - activeDocumentIsLaunchable: Bool, - configurations: [RunConfiguration] - ) -> RunConfiguration { - DebugLaunchSourceResolver().configurationForDebug( - selected: selected, - activeDocumentIsLaunchable: activeDocumentIsLaunchable, - configurations: configurations - ) - } - func sourceURLForDebug( configuration: RunConfiguration, activeDocument: EditorDocument?, projectFiles: [URL], workspaceURL: URL ) -> URL? { - if configuration.usesCurrentEditorFile { - return activeDocument?.url - } - guard configuration.kind.capabilities.contains(.jdwpDebug) else { - return nil - } return DebugLaunchSourceResolver().resolve( configuration: configuration, activeDocumentURL: activeDocument?.url, @@ -190,9 +172,6 @@ final class RunWorkflowCoordinator { if configuration.usesCurrentEditorFile { return .currentFileUnavailable } - if configuration.kind.capabilities.contains(.jdwpDebug) { - return .javaSourceUnavailable(configuration.name) - } return .unsupported(configuration.name) } return .resolved(sourceURL) @@ -213,7 +192,7 @@ final class RunWorkflowCoordinator { runFeature: RunFeatureModel ) async -> Bool { guard support.executionModuleID != nil else { - notify("\(support.displayName) does not provide project execution") + notify("%@ does not provide project execution", [support.displayName]) return false } do { @@ -222,12 +201,12 @@ final class RunWorkflowCoordinator { ) guard let provider = value as? any LanguageRunExtensionProviding, runFeature.registerLanguageRunExtension(provider, support: support) else { - notify("\(support.displayName) returned an invalid execution provider") + notify("%@ returned an invalid execution provider", [support.displayName]) return false } return true } catch { - if !error.isCancellation { notify(error.localizedDescription) } + if !error.isCancellation { notify(error.localizedDescription, []) } return false } } @@ -271,6 +250,48 @@ final class RunWorkflowCoordinator { return support } + /// The package whose own editor actions the toolbar button for + /// `capability` must call. That is the package owning the current file's + /// language when it declares neither a module nor a host capability for + /// `capability`: the host has nothing of its own to start, and the package + /// exposes running or debugging only as editor actions. For Debug, a + /// package whose adapter never launches a file (it only attaches, or debugs + /// executables) counts the same: its debug module serves the sessions its + /// run action opens, and the host could only answer the button with an + /// error. `nil` for host-run languages, for project configurations, and for + /// packages that only add a debugger or editor resources to a language + /// another owner serves. + func languageSupportRoutingToEditorActions( + _ capability: LanguageHostCapability, + for configuration: RunConfiguration, + currentFileURL: URL?, + languageSupportForFile: (URL) -> LanguageSupportDeclaration?, + hostLaunchesFiles: (_ languageID: String) -> Bool + ) -> LanguageSupportDeclaration? { + guard configuration.usesCurrentEditorFile, let currentFileURL, + let support = languageSupportForFile(currentFileURL), + !support.isDebugOnly, !support.isEditorOnly, + !support.hostCapabilities.contains(capability) else { return nil } + switch capability { + case .run: return support.executionModuleID == nil ? support : nil + case .debug: return support.debugModuleID == nil || !hostLaunchesFiles(support.id) ? support : nil + case .testing: return support.testingModuleID == nil ? support : nil + } + } + + func languageSupportRoutingToEditorActions( + _ capability: LanguageHostCapability, + for configuration: RunConfiguration, + currentFileURL: URL?, + hostLaunchesFiles: (_ languageID: String) -> Bool + ) -> LanguageSupportDeclaration? { + languageSupportRoutingToEditorActions( + capability, for: configuration, currentFileURL: currentFileURL, + languageSupportForFile: { [pluginCatalog] fileURL in pluginCatalog.languageSupport(for: fileURL)?.declaration }, + hostLaunchesFiles: hostLaunchesFiles + ) + } + func languageSupport( for configuration: RunConfiguration, currentFileURL: URL?, @@ -300,7 +321,7 @@ final class RunWorkflowCoordinator { saving.recordSave(document, previousText: previousText) return true } catch { - notify("Could not save \(document.url.lastPathComponent)") + notify("Could not save %@", [document.url.lastPathComponent]) return false } } diff --git a/macos/Sources/Lithe/Application/Features/RuntimeSettingsFeatureModel.swift b/macos/Sources/Lithe/Application/Features/RuntimeSettingsFeatureModel.swift index c4720147f2..c6e0920809 100644 --- a/macos/Sources/Lithe/Application/Features/RuntimeSettingsFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/RuntimeSettingsFeatureModel.swift @@ -1,212 +1,18 @@ -import Combine import Foundation -import LitheCoreContracts -import LitheModuleAPI -/// UI-facing projection for project runtime settings and discovery. +/// UI-facing entry to the project's tool and environment lookup. It carries no +/// tool-specific state: which tools exist and how each is chosen comes from the +/// plugin-defined tool definitions on the generic Environment page. @MainActor final class RuntimeSettingsFeatureModel: ObservableObject { private let service: ProjectRuntimeService - private var observation: AnyCancellable? - private var baseline = ProjectRuntimeSettings() - private var draftSnapshot: ProjectRuntimeSettingsSnapshot? - @Published private(set) var settingsError: String? - @Published private(set) var isSaving = false - var hasChanges: Bool { settings != baseline } - - @Published private(set) var javaRuntimes: [JavaRuntimeCandidate] - @Published private(set) var mavenRuntimes: [MavenRuntimeCandidate] - @Published private(set) var javaEnvironmentReport: JavaEnvironmentReport? - @Published private(set) var isDiscovering: Bool - @Published private(set) var settings: ProjectRuntimeSettings - @Published private(set) var subprojects: [ProjectRuntimeSubproject] = [] init(service: ProjectRuntimeService) { self.service = service - _javaRuntimes = Published(initialValue: service.javaRuntimes) - _mavenRuntimes = Published(initialValue: service.mavenRuntimes) - _javaEnvironmentReport = Published(initialValue: service.javaEnvironmentReport) - _isDiscovering = Published(initialValue: service.isDiscovering) - _settings = Published(initialValue: service.settings) - observation = service.objectWillChange.sink { [weak self] _ in - guard let self else { return } - self.javaRuntimes = self.service.javaRuntimes - self.mavenRuntimes = self.service.mavenRuntimes - self.javaEnvironmentReport = self.service.javaEnvironmentReport - self.isDiscovering = self.service.isDiscovering - self.settingsError = self.service.settingsError - } } - func openProject(at url: URL) { - service.openProject(at: url) - settings = service.settings - baseline = settings - draftSnapshot = nil - isSaving = false - settingsError = service.settingsError - } - func closeProject() { - service.closeProject() - subprojects = [] - settings = ProjectRuntimeSettings() - baseline = settings - draftSnapshot = nil - isSaving = false - settingsError = nil - } + func openProject(at url: URL) { service.openProject(at: url) } + func closeProject() { service.closeProject() } func refreshAvailableRuntimes() async { await service.refreshAvailableRuntimes() } func ensureRuntimesDiscovered() async { await service.ensureRuntimesDiscovered() } - func activeJavaRuntime() -> JavaRuntimeCandidate? { service.activeJavaRuntime() } - func executableCandidates(_ command: String) -> [RuntimeToolCandidate] { - service.executableCandidates(command) - } - func toolGuidance(_ command: String) -> RuntimeToolGuidance { - service.toolGuidance(command) - } - - // Settings shows what a launch would use through the launch's own selection - // chains. Detection uses the runtimes already discovered in the background; - // `nil` means that discovery has not finished yet. - - func javaChoice(overridePath: String?) -> RuntimeChoice? { - service.chooseJavaHome(overridePath: overridePath, detected: detectedJavaRuntimes) - } - - func mavenJavaChoice(overridePath: String?) -> RuntimeChoice? { - service.chooseMavenJavaHome(overridePath: overridePath, detected: detectedJavaRuntimes) - } - - func mavenChoice(at rootURL: URL, overridePath: String?) -> RuntimeChoice { - service.chooseMavenExecutable(at: rootURL, overridePath: overridePath) - } - - func javaRuntimeName(at url: URL) -> String? { - javaRuntimes.first { $0.homePath == url.path }?.displayName - } - - func mavenRuntimeName(at url: URL) -> String? { - mavenRuntimes.first { $0.executablePath == url.path }?.displayName - } - - private func detectedJavaRuntimes() -> [JavaRuntimeCandidate]? { - service.hasDiscoveredRuntimes ? service.javaRuntimes : nil - } - - func prepare( - workspaceName: String, - workspaceURL: URL?, - files: [URL], - buildSources: [ProjectRuntimeInventory.BuildSource] = [], - languageSupports: [LanguageSupportDeclaration] = [] - ) { - guard !isSaving else { return } - guard let workspaceURL else { - subprojects = [] - return - } - service.reloadSettings() - subprojects = ProjectRuntimeInventory.subprojects( - workspaceName: workspaceName, - workspaceURL: workspaceURL, - files: files, - buildSources: buildSources, - languageSupports: languageSupports - ) - settings = service.settings - baseline = settings - draftSnapshot = service.settingsSnapshot - settingsError = service.settingsError - } - - /// Refreshes canonical tool selections without loading a build model or - /// replacing an open settings draft. Provider-owned configuration has a separate editor. - func reloadToolchainSettings() -> Bool { - guard !isSaving, !hasChanges else { return false } - guard service.reloadSettings() else { - settingsError = service.settingsError - return false - } - let current = service.settings - settings = current - baseline = current - draftSnapshot = service.settingsSnapshot - settingsError = service.settingsError - return draftSnapshot != nil - } - - @discardableResult - func saveSettings() -> Bool { - guard !isSaving else { - settingsError = L10n.string("Project environment settings are being saved. Wait before saving again.") - return false - } - isSaving = true - guard let draftSnapshot, service.updateSettings(settings, expecting: draftSnapshot) else { - settingsError = service.settingsError - isSaving = false - return false - } - let saved = service.settings - settings = saved - self.draftSnapshot = service.settingsSnapshot - return true - } - - func finishSaving(error: String? = nil) { - isSaving = false - settingsError = error - if error == nil { baseline = settings } - } - - func cancelChanges() { - guard !isSaving else { return } - guard service.reloadSettings() else { - settingsError = service.settingsError - return - } - let current = service.settings - settings = current - baseline = current - draftSnapshot = service.settingsSnapshot - settingsError = nil - } - - func updateSettings(_ mutate: (inout ProjectRuntimeSettings) -> Void) { - guard !isSaving else { return } - var next = settings - mutate(&next) - settings = next - } - - func javaRuntimeTitle(for path: String, automaticTitle: String) -> String { - let normalized = path.trimmingCharacters(in: .whitespacesAndNewlines) - if normalized.isEmpty { return automaticTitle } - if let match = javaRuntimes.first(where: { $0.homePath == normalized }) { - return "\(match.displayName) — \(match.homePath)" - } - return normalized - } - - func mavenRuntimeTitle(for path: String, automaticTitle: String) -> String { - let normalized = path.trimmingCharacters(in: .whitespacesAndNewlines) - if normalized.isEmpty { return automaticTitle } - if let match = mavenRuntimes.first(where: { - $0.executablePath == normalized || $0.homePath == normalized - }) { - return "\(match.displayName) — \(match.homePath)" - } - return normalized - } - - func effectiveJavaHome(for subproject: ProjectRuntimeSubproject) -> String { - if !subproject.usesJava { return "" } - if subproject.kind == .projectDefaults { - return settings.javaHomePath - } - return settings.overlay( - onto: RunOptions(), - workspaceRelativePath: subproject.relativePath - ).javaHomePath - } } diff --git a/macos/Sources/Lithe/Application/Features/SpringFeatureModel.swift b/macos/Sources/Lithe/Application/Features/SpringFeatureModel.swift deleted file mode 100644 index d446486c30..0000000000 --- a/macos/Sources/Lithe/Application/Features/SpringFeatureModel.swift +++ /dev/null @@ -1,292 +0,0 @@ -import Combine -import Foundation -import LitheCoreContracts - -/// Owns the workspace-level Spring semantic projection produced by Rust Core. -@MainActor -final class SpringFeatureModel: ObservableObject { - @Published private(set) var properties: [SpringProperty] = [] - @Published private(set) var values: [SpringConfigurationValue] = [] - @Published private(set) var propertyReferences: [SpringPropertyReference] = [] - @Published private(set) var diagnostics: [SpringDiagnostic] = [] - @Published private(set) var beans: [SpringBean] = [] - @Published private(set) var injections: [SpringInjection] = [] - @Published private(set) var endpoints: [SpringEndpoint] = [] - @Published private(set) var isIndexing = false - - private let operations: any JavaMavenOperations - private var generation = UUID() - private var reloadTask: Task? - - init(operations: any JavaMavenOperations) { - self.operations = operations - } - - func load( - workspaceURL: URL, - files: [URL], - textOverrides: [URL: String] = [:], - refreshDependencyMetadata: Bool = true - ) async { - generation = UUID() - let currentGeneration = generation - isIndexing = true - let operations = self.operations - let result = await Task.detached(priority: .utility) { - operations.springIndex( - at: workspaceURL, - files: files, - textOverrides: textOverrides, - refreshDependencyMetadata: refreshDependencyMetadata - ) - }.value ?? .empty - guard generation == currentGeneration else { return } - properties = result.properties - values = result.values - propertyReferences = result.propertyReferences - diagnostics = result.diagnostics - beans = result.beans - injections = result.injections - endpoints = result.endpoints - isIndexing = false - } - - /// Starts a workspace index without making the caller wait for it. Opening a - /// project must not block build-system and run state behind Spring indexing, - /// which scales with the number of Java sources in the workspace. - func scheduleLoad( - workspaceURL: URL, - files: [URL], - textOverrides: [URL: String] = [:], - refreshDependencyMetadata: Bool = true - ) { - reloadTask?.cancel() - reloadTask = Task { @MainActor [weak self] in - // Cancellation is cooperative, so a schedule that was superseded - // before it started must return here instead of running a second - // full workspace index whose result the generation token discards. - guard !Task.isCancelled, let self else { return } - await self.load( - workspaceURL: workspaceURL, - files: files, - textOverrides: textOverrides, - refreshDependencyMetadata: refreshDependencyMetadata - ) - } - } - - func reset() { - reloadTask?.cancel() - reloadTask = nil - generation = UUID() - properties = [] - values = [] - propertyReferences = [] - diagnostics = [] - beans = [] - injections = [] - endpoints = [] - isIndexing = false - } - - func scheduleReload( - changedDocument: EditorDocument, - workspaceURL: URL, - files: [URL], - openDocuments: [EditorDocument] - ) { - let name = changedDocument.url.lastPathComponent - guard handles(changedDocument.url) - || changedDocument.url.pathExtension.lowercased() == "java" - || name == "spring-configuration-metadata.json" - || name == "additional-spring-configuration-metadata.json" else { return } - reloadTask?.cancel() - reloadTask = Task { @MainActor [weak self] in - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - try? await Task.sleep(for: .milliseconds(300)) - guard !Task.isCancelled, let self else { return } - let overrides = Dictionary(uniqueKeysWithValues: openDocuments.map { - ($0.url.standardizedFileURL, $0.text) - }) - await self.load( - workspaceURL: workspaceURL, - files: files, - textOverrides: overrides, - refreshDependencyMetadata: false - ) - } - } - - func handles(_ url: URL) -> Bool { - let name = url.lastPathComponent.lowercased() - return name == "application.properties" - || (name.hasPrefix("application-") && name.hasSuffix(".properties")) - || ((name == "application.yml" || name == "application.yaml") - || (name.hasPrefix("application-") && ["yml", "yaml"].contains(url.pathExtension.lowercased()))) - } - - func completions( - document: EditorDocument, - line: Int, - utf16Column: Int - ) -> [LanguageServerCompletionItem] { - guard handles(document.url), - let context = completionContext( - text: document.text, - extensionName: document.url.pathExtension.lowercased(), - line: line, - utf16Column: utf16Column - ) else { return [] } - return properties.compactMap { property in - guard property.name.hasPrefix(context.parentPrefix) else { return nil } - let insertText = String(property.name.dropFirst(context.parentPrefix.count)) - guard insertText.localizedCaseInsensitiveContains(context.typedPrefix) else { return nil } - let detail = [property.typeName, property.defaultValue.map { "default: \($0)" }] - .compactMap { $0 }.joined(separator: " · ") - return LanguageServerCompletionItem( - label: property.name, - detail: detail.isEmpty ? "Spring Boot property" : detail, - documentation: property.documentation, - insertText: insertText, - sortText: property.name, - filterText: property.name, - kind: 10, - textEdit: LanguageServerTextEdit( - range: LanguageServerRange( - start: LanguageServerPosition(line: line, utf16Column: context.replacementStart), - end: LanguageServerPosition(line: line, utf16Column: utf16Column) - ), - newText: insertText - ), - additionalTextEdits: [], - data: nil - ) - } - } - - func hover(for url: URL, line: Int) -> LanguageServerHover? { - guard let value = values.first(where: { - $0.url.standardizedFileURL == url.standardizedFileURL && $0.line == line + 1 - }), let property = properties.first(where: { $0.name == value.key }) else { return nil } - var parts = ["`\(property.name)`"] - if let typeName = property.typeName { parts.append("Type: `\(typeName)`") } - if let defaultValue = property.defaultValue { parts.append("Default: `\(defaultValue)`") } - if let documentation = property.documentation { parts.append(documentation) } - if let profile = value.profile { parts.append("Profile: `\(profile)`") } - if value.overridesBaseValue { parts.append("Overrides the base application value.") } - return LanguageServerHover(contents: parts.joined(separator: "\n\n"), isMarkdown: true, range: nil) - } - - func navigationLocations(for url: URL, line: Int) -> [LanguageServerLocation] { - if let value = values.first(where: { - $0.url.standardizedFileURL == url.standardizedFileURL && $0.line == line + 1 - }) { - var locations: [LanguageServerLocation] = [] - if let targetURL = value.targetURL { - locations.append(location( - targetURL, - line: value.targetLine, - column: value.targetColumn - )) - } - locations.append(contentsOf: propertyReferences.filter { $0.key == value.key }.map { - location($0.url, line: $0.line, column: $0.column) - }) - if !locations.isEmpty { return unique(locations) } - } - if let reference = propertyReferences.first(where: { - $0.url.standardizedFileURL == url.standardizedFileURL && $0.line == line + 1 - }) { - return unique(values.filter { $0.key == reference.key }.map { - location($0.url, line: $0.line, column: $0.column) - }) - } - if let injection = injections.first(where: { - $0.url.standardizedFileURL == url.standardizedFileURL && abs($0.line - (line + 1)) <= 1 - }) { - return injection.beanIDs.compactMap { id in - beans.first(where: { $0.id == id }).map { - location($0.url, line: $0.line, column: $0.column) - } - } - } - let matchingProperties = properties.filter { - $0.sourceURL?.standardizedFileURL == url.standardizedFileURL - && $0.sourceLine.map { abs($0 - (line + 1)) <= 1 } == true - } - return matchingProperties.flatMap { property in - values.filter { $0.key == property.name }.map { - location($0.url, line: $0.line, column: $0.column) - } - } - } - - var languageDiagnostics: [URL: [LanguageServerDiagnostic]] { - Dictionary(grouping: diagnostics, by: { $0.url.standardizedFileURL }).mapValues { values in - values.map { value in - LanguageServerDiagnostic( - range: LanguageServerRange( - start: LanguageServerPosition(line: max(0, value.line - 1), utf16Column: max(0, value.column - 1)), - end: LanguageServerPosition(line: max(0, value.line - 1), utf16Column: max(0, value.column)) - ), - severity: value.severity == "error" ? 1 : 2, - message: value.message, - source: "Spring", - code: "spring.configuration" - ) - } - } - } - - private func location(_ url: URL, line: Int?, column: Int?) -> LanguageServerLocation { - let position = LanguageServerPosition( - line: max(0, (line ?? 1) - 1), - utf16Column: max(0, (column ?? 1) - 1) - ) - return LanguageServerLocation( - url: url, - range: LanguageServerRange(start: position, end: position) - ) - } - - private func unique(_ locations: [LanguageServerLocation]) -> [LanguageServerLocation] { - var seen = Set() - return locations.filter { location in - let key = "\(location.url.standardizedFileURL.path):\(location.range.start.line):\(location.range.start.utf16Column)" - return seen.insert(key).inserted - } - } - - private func completionContext( - text: String, - extensionName: String, - line: Int, - utf16Column: Int - ) -> (parentPrefix: String, typedPrefix: String, replacementStart: Int)? { - let lines = text.components(separatedBy: .newlines) - guard lines.indices.contains(line) else { return nil } - let current = lines[line] as NSString - let column = min(max(0, utf16Column), current.length) - var start = column - let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-_")) - while start > 0, - let scalar = UnicodeScalar(current.character(at: start - 1)), - allowed.contains(scalar) { - start -= 1 - } - let typed = current.substring(with: NSRange(location: start, length: column - start)) - guard extensionName != "properties" else { return ("", typed, start) } - let indent = lines[line].prefix { $0 == " " || $0 == "\t" }.count - var stack: [(indent: Int, key: String)] = [] - for previous in lines.prefix(line) { - let trimmed = previous.trimmingCharacters(in: .whitespaces) - guard !trimmed.isEmpty, !trimmed.hasPrefix("#"), trimmed.hasSuffix(":") else { continue } - let previousIndent = previous.prefix { $0 == " " || $0 == "\t" }.count - while stack.last.map({ $0.indent >= previousIndent }) == true { stack.removeLast() } - stack.append((previousIndent, String(trimmed.dropLast()).trimmingCharacters(in: CharacterSet(charactersIn: "\"'")))) - } - while stack.last.map({ $0.indent >= indent }) == true { stack.removeLast() } - let parent = stack.map(\.key).joined(separator: ".") - return (parent.isEmpty ? "" : parent + ".", typed, start) - } -} diff --git a/macos/Sources/Lithe/Application/Features/TestJVMPerformanceFeatureModel.swift b/macos/Sources/Lithe/Application/Features/TestJVMPerformanceFeatureModel.swift deleted file mode 100644 index 8617554fa1..0000000000 --- a/macos/Sources/Lithe/Application/Features/TestJVMPerformanceFeatureModel.swift +++ /dev/null @@ -1,201 +0,0 @@ -import Combine -import Foundation -import LitheExecutionModule - -/// Owns the selected test worker, its live charts and one explicit JFR recording. -/// Collapsing stops live sampling; an explicitly started recording continues until -/// stopped or the worker exits. Replacing/closing the run disposes its recording. -@MainActor -final class TestJVMPerformanceFeatureModel: ObservableObject { - let metrics: DebugPerformanceFeatureModel - @Published private(set) var processes: [TestJVMProcess] = [] - @Published private(set) var selectedProcess: TestJVMProcess? - @Published private(set) var recording: TestJVMRecording? - @Published private(set) var isRecording = false - @Published private(set) var recordingDuration: TimeInterval = 0 - @Published private(set) var isBusy = false - @Published private(set) var errorMessage: String? - @Published var report: String? - @Published private(set) var usesJVM = true - private let provider: (any TestJVMPerformanceProviding)? - private var runID: UUID? - private var rootPID: Int32? - private var active = false - private var visible = false - private var discovery: Task? - private var operation: Task? - private var workerIDs: [String: UUID] = [:] - private var generation = UUID() - private weak var boundService: LanguageTestService? - private var observation: AnyCancellable? - private var discardRecording: (@Sendable () -> Void)? - - init(sampler: (any DebugPerformanceSampling)?, provider: (any TestJVMPerformanceProviding)?) { - metrics = DebugPerformanceFeatureModel(sampler: sampler) - self.provider = provider - } - - func bind(to service: LanguageTestService) { - guard boundService !== service else { return } - boundService = service - observation = Publishers.CombineLatest4(service.$runID, service.$processID, service.$state, service.$activePlan) - .sink { [weak self] id, pid, state, plan in - self?.update(runID: id, processID: pid, isRunning: state == .running, - isJava: (plan?.providerID ?? "java") == "java") - } - } - - var isProcessRunning: Bool { active && selectedProcess.map(processes.contains) == true } - var canStartRecording: Bool { active && selectedProcess.map(processes.contains) == true && !isRecording && !isBusy } - - func update(runID: UUID?, processID: Int32?, isRunning: Bool, isJava: Bool) { - if self.runID != runID { - generation = UUID() - discovery?.cancel(); discovery = nil - operation?.cancel(); operation = nil - discardRecording?(); discardRecording = nil - self.recording = nil; recordingDuration = 0; isRecording = false; isBusy = false; report = nil - processes = []; selectedProcess = nil; workerIDs = [:]; errorMessage = nil - self.runID = runID - } - let changed = rootPID != processID || active != isRunning || usesJVM != isJava - rootPID = processID; active = isRunning; usesJVM = isJava - if !isJava { - discovery?.cancel(); discovery = nil - if let runID, let processID { metrics.register(DebugPerformanceTarget(processID: processID), sessionID: runID) } - metrics.select(sessionID: runID, isActive: isRunning && processID != nil) - } else if !isRunning || processID == nil { - discovery?.cancel(); discovery = nil - selectMetrics(active: false) - if isRecording { stopRecording() } - } else if changed { discover() } - } - - func setVisible(_ value: Bool) { - visible = value - metrics.setVisible(value) - reconcileDiscovery() - } - - private func reconcileDiscovery() { - if !visible && !isRecording && !isBusy { - discovery?.cancel(); discovery = nil - } else { discover() } - } - - func select(_ process: TestJVMProcess) { - guard !isRecording, !isBusy, processes.contains(process) else { return } - selectedProcess = process - selectMetrics(active: active) - } - - private func selectMetrics(active: Bool) { - guard let process = selectedProcess else { metrics.select(sessionID: nil, isActive: false); return } - let id = workerIDs[process.id] ?? UUID() - workerIDs[process.id] = id - // ponytail: Match the shared chart owner's 16-worker history ceiling. - for key in workerIDs.keys.sorted() where workerIDs.count > 16 && key != process.id { - workerIDs.removeValue(forKey: key) - } - metrics.register(process.target, sessionID: id) - metrics.select(sessionID: id, isActive: active && processes.contains(process)) - } - - private func discover() { - guard usesJVM, active, let rootPID, let provider, discovery == nil, visible || isRecording || isBusy else { return } - let current = generation - discovery = Task { [weak self] in - do { - for try await workers in provider.processes(rootProcessID: rootPID) { - guard let self, !Task.isCancelled, generation == current else { return } - if processes != workers { processes = workers } - if let recording, isRecording, Date().timeIntervalSince(recording.startedAt) >= 120 { stopRecording() } - if let selectedProcess, !workers.contains(selectedProcess), isRecording { stopRecording() } - if !isRecording && !isBusy, let first = workers.first, - selectedProcess.map({ !workers.contains($0) }) ?? true { - selectedProcess = first - } - selectMetrics(active: active) - } - guard let self, !Task.isCancelled, generation == current else { return } - discovery = nil - active = false; processes = [] - selectMetrics(active: false) - if isRecording { stopRecording() } - } catch { - guard let self, !Task.isCancelled, generation == current else { return } - discovery = nil; errorMessage = error.localizedDescription - } - } - } - - func startRecording() { - guard let selectedProcess, let provider, active, !isBusy, !isRecording else { return } - let current = generation - isBusy = true; errorMessage = nil; report = nil - let previous = recording - discardRecording = nil - recording = nil - operation = Task { [weak self] in - if let previous { await provider.discard(previous) } - do { - let value = try await provider.startRecording(selectedProcess) - guard let self, !Task.isCancelled, generation == current else { await provider.discard(value); return } - recording = value - discardRecording = { Task { await provider.discard(value) } } - recordingDuration = 0; isRecording = true; isBusy = false - if !active || !processes.contains(selectedProcess) { stopRecording() } - else { discover() } - } catch { - guard let self, generation == current else { return } - isBusy = false; errorMessage = error.localizedDescription - reconcileDiscovery() - } - } - } - - func stopRecording() { - guard let recording, let provider, isRecording, !isBusy else { return } - let current = generation - isBusy = true; errorMessage = nil - operation = Task { [weak self] in - do { try await provider.stopRecording(recording) } - catch { - guard let self, generation == current else { return } - errorMessage = error.localizedDescription - isBusy = false - reconcileDiscovery() - return - } - guard let self, generation == current else { return } - recordingDuration = min(120, max(0, Date().timeIntervalSince(recording.startedAt))) - isRecording = false; isBusy = false - if let first = processes.first, selectedProcess.map({ !self.processes.contains($0) }) ?? true { selectedProcess = first } - selectMetrics(active: active) - reconcileDiscovery() - } - } - - func showResults() { - guard let recording, let provider, !isRecording, !isBusy else { return } - let current = generation - isBusy = true; errorMessage = nil - operation = Task { [weak self] in - do { - let result = try await provider.report(recording) - guard let self, !Task.isCancelled, generation == current else { return } - report = result; isBusy = false - reconcileDiscovery() - } catch { - guard let self, generation == current else { return } - errorMessage = error.localizedDescription; isBusy = false - reconcileDiscovery() - } - } - } - - deinit { - discovery?.cancel(); operation?.cancel() - discardRecording?() - } -} diff --git a/macos/Sources/Lithe/Application/Features/WorkbenchFeatureModel.swift b/macos/Sources/Lithe/Application/Features/WorkbenchFeatureModel.swift index dfdd8021c3..601773b4f2 100644 --- a/macos/Sources/Lithe/Application/Features/WorkbenchFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/WorkbenchFeatureModel.swift @@ -36,13 +36,12 @@ final class WorkbenchFeatureModel: ObservableObject { static let agent = Self(rawValue: "agent.conversation") static let references = Self(rawValue: "language.references") static let problems = Self(rawValue: "language.problems") - static let spring = Self(rawValue: "language.spring") static let run = Self(rawValue: "execution.run") static let tests = Self(rawValue: "execution.tests") static let debug = Self(rawValue: "debug.session") static let buildOutput = Self(rawValue: "execution.build.output") static let allCases: [Self] = [.project, .changes, .pullRequests, .search, - .gitLog, .terminal, .agent, .references, .problems, .spring, .run, .tests, .debug, + .gitLog, .terminal, .agent, .references, .problems, .run, .tests, .debug, .buildOutput] // Docking layouts written before contribution registration used enum case names. // Their windows may since have been removed, so the mapping names the @@ -53,8 +52,7 @@ final class WorkbenchFeatureModel: ObservableObject { "project": "workspace.project", "changes": "git.changes", "pullRequests": "github.pull-requests", "search": "search.workspace", "database": "database.workspace", "gitLog": "git.log", "terminal": "terminal.sessions", "agent": "agent.conversation", "databaseServices": "database.services", - "references": "language.references", "problems": "language.problems", "maven": "execution.maven", - "mavenOutput": "execution.maven.output", "spring": "language.spring", "run": "execution.run", + "references": "language.references", "problems": "language.problems", "run": "execution.run", "tests": "execution.tests", "debug": "debug.session" ] return legacy[id] ?? id diff --git a/macos/Sources/Lithe/Application/Features/WorkflowActionPorts.swift b/macos/Sources/Lithe/Application/Features/WorkflowActionPorts.swift index 1b439574d5..1737cdf66d 100644 --- a/macos/Sources/Lithe/Application/Features/WorkflowActionPorts.swift +++ b/macos/Sources/Lithe/Application/Features/WorkflowActionPorts.swift @@ -13,7 +13,7 @@ import LitheExecutionModule /// Saving and local-history recording for an open editor document. /// -/// Run, Debug, and Java test launches all persist a dirty document before +/// Run, Debug, and language test launches all persist a dirty document before /// starting, and each records the previous text so the save is undoable from /// Local History. @MainActor @@ -40,7 +40,7 @@ protocol RunWorkflowActions: EditorDocumentSaving { func restartSelectedRun() } -/// Application operations the debug and Java test launch workflows call back +/// Application operations the debug and language test launch workflows call back /// into. /// /// A failed launch reopens the Debug tool window so the adapter's own output @@ -59,6 +59,5 @@ protocol DebugWorkflowActions: EditorDocumentSaving { @MainActor protocol DebugSessionCleanupActions: DebugWorkflowActions { func activateApplication() - func stopJavaTestResultServer() func stopDebugTerminalProcesses(for debugSessionID: DebugSessionID?) } diff --git a/macos/Sources/Lithe/Core/Debug/JavaTestResultServer.swift b/macos/Sources/Lithe/Core/Debug/JavaTestResultServer.swift deleted file mode 100644 index 1ffd45ccb1..0000000000 --- a/macos/Sources/Lithe/Core/Debug/JavaTestResultServer.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -/// Platform port for the short-lived loopback server required by Java test runners. -@MainActor -protocol JavaTestResultServing: AnyObject { - func start() async throws -> UInt16 - func stop() -} diff --git a/macos/Sources/Lithe/Core/Ports/DebugPerformanceSampling.swift b/macos/Sources/Lithe/Core/Ports/DebugPerformanceSampling.swift index d20722dced..5efbf4bd9a 100644 --- a/macos/Sources/Lithe/Core/Ports/DebugPerformanceSampling.swift +++ b/macos/Sources/Lithe/Core/Ports/DebugPerformanceSampling.swift @@ -1,9 +1,8 @@ import Foundation +/// The process whose tree is monitored with native CPU/RSS counters. struct DebugPerformanceTarget: Equatable, Sendable { let processID: Int32 - /// nil monitors the owned process tree using native CPU/RSS counters. - var javaExecutable: URL? = nil } struct DebugPerformanceSample: Equatable, Sendable, Identifiable { diff --git a/macos/Sources/Lithe/Core/Ports/ProjectRuntimeSettingsStoring.swift b/macos/Sources/Lithe/Core/Ports/ProjectRuntimeSettingsStoring.swift deleted file mode 100644 index ea4a6570e8..0000000000 --- a/macos/Sources/Lithe/Core/Ports/ProjectRuntimeSettingsStoring.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - -/// A settings draft is tied to both the local run document and the remaining -/// Lithe preferences. The revision is opaque and must not contain file contents. -struct ProjectRuntimeSettingsSnapshot: Equatable { - let workspaceURL: URL - let settings: ProjectRuntimeSettings - let revision: String - var hasSavedToolchain = false -} - -@MainActor -protocol ProjectRuntimeSettingsStoring { - /// Migration is allowed only during workspace activation, never page display. - func load(at workspace: URL, migrateLegacy: Bool) throws -> ProjectRuntimeSettingsSnapshot - func save(_ settings: ProjectRuntimeSettings, at workspace: URL, - expecting snapshot: ProjectRuntimeSettingsSnapshot) throws -> ProjectRuntimeSettingsSnapshot -} diff --git a/macos/Sources/Lithe/Core/Ports/RunConfigurationOperations.swift b/macos/Sources/Lithe/Core/Ports/RunConfigurationOperations.swift index 92067ef5a5..4228d7c940 100644 --- a/macos/Sources/Lithe/Core/Ports/RunConfigurationOperations.swift +++ b/macos/Sources/Lithe/Core/Ports/RunConfigurationOperations.swift @@ -12,11 +12,7 @@ typealias RunConfigurationResolution = LitheCoreContracts.RunConfigurationResolu typealias RunConfigurationOperationFailure = LitheCoreContracts.RunConfigurationOperationFailure typealias SharedLaunchPlan = LitheCoreContracts.SharedLaunchPlan typealias RunConfigurationGenerationResult = LitheCoreContracts.RunConfigurationGenerationResult -typealias RunConfigurationDraft = LitheCoreContracts.RunConfigurationDraft typealias RunConfigurationDocumentMutation = LitheCoreContracts.RunConfigurationDocumentMutation typealias RunConfigurationDocumentMutating = LitheCoreContracts.RunConfigurationDocumentMutating -typealias ProjectToolchainSelection = LitheCoreContracts.ProjectToolchainSelection typealias ProjectToolchainCandidate = LitheCoreContracts.ProjectToolchainCandidate typealias RunConfigurationOperations = LitheCoreContracts.RunConfigurationOperations - -typealias RunProjectOwnership = LitheCoreContracts.RunProjectOwnership diff --git a/macos/Sources/Lithe/Core/Ports/RunExecutableResolving.swift b/macos/Sources/Lithe/Core/Ports/RunExecutableResolving.swift index 1451d73bbf..d159cf41d8 100644 --- a/macos/Sources/Lithe/Core/Ports/RunExecutableResolving.swift +++ b/macos/Sources/Lithe/Core/Ports/RunExecutableResolving.swift @@ -20,5 +20,5 @@ protocol RunToolchainMetadataResolving: Sendable { /// Application boundary for resolving a launch plan. Toolchain ids are an /// open registry, but every id must have an explicit resolver; an unknown id -/// must never silently acquire Maven semantics. +/// must never silently acquire another toolchain's semantics. typealias RunExecutableResolving = LitheCoreContracts.RunExecutableResolving diff --git a/macos/Sources/Lithe/Core/Ports/RunLaunchEnvironmentResolving.swift b/macos/Sources/Lithe/Core/Ports/RunLaunchEnvironmentResolving.swift index 8d3268eedc..9434fe75ca 100644 --- a/macos/Sources/Lithe/Core/Ports/RunLaunchEnvironmentResolving.swift +++ b/macos/Sources/Lithe/Core/Ports/RunLaunchEnvironmentResolving.swift @@ -13,7 +13,6 @@ protocol RunLaunchEnvironmentResolving { func resolveLaunchEnvironment( toolchain: String?, - selectedHome: String?, inherited: [String: String], overrides: [String: String] ) throws -> [String: String] diff --git a/macos/Sources/Lithe/Core/Ports/RunToolchainProviders.swift b/macos/Sources/Lithe/Core/Ports/RunToolchainProviders.swift index f31c184d4c..bf535d13f6 100644 --- a/macos/Sources/Lithe/Core/Ports/RunToolchainProviders.swift +++ b/macos/Sources/Lithe/Core/Ports/RunToolchainProviders.swift @@ -16,7 +16,7 @@ protocol RunToolchainProvider: AnyObject { var identifiers: Set { get } var toolchainType: String { get } /// Owning language pack, when this provider is language-specific. A nil - /// value is reserved for shared build tools such as Maven or Gradle. + /// value is reserved for shared build tools. var languageProviderID: String? { get } var discoverable: Bool { get } func resolve( @@ -147,9 +147,6 @@ final class RunToolchainRegistry { static func standardProviders() -> [any RunToolchainProvider] { [ - JavaRunToolchainProvider(), - MavenRunToolchainProvider(), - GradleRunToolchainProvider(), PathRunToolchainProvider( identifiers: ["go", "project-go"], command: "go", languageProviderID: "go"), @@ -177,93 +174,6 @@ final class RunToolchainRegistry { } } -@MainActor -private final class GradleRunToolchainProvider: RunToolchainProvider { - let identifiers: Set = ["gradle", "project-gradle"] - let toolchainType = "gradle" - let languageProviderID: String? = "java" - - func resolve( - projectURL: URL, - options: RunOptions, - runtimeService: ProjectRuntimeService - ) throws -> ResolvedRunToolchain { - guard let executable = runtimeService.gradleExecutable(at: projectURL) else { - throw RunExecutableResolutionError( - message: L10n.string("No Gradle wrapper or Gradle executable was found.") - ) - } - return ResolvedRunToolchain( - executableURL: executable, - environment: runtimeService.processEnvironment() - ) - } -} - -@MainActor -private final class JavaRunToolchainProvider: RunToolchainProvider { - let identifiers: Set = ["project-jdk"] - let toolchainType = "java" - let languageProviderID: String? = "java" - - func resolve( - projectURL: URL, - options: RunOptions, - runtimeService: ProjectRuntimeService - ) throws -> ResolvedRunToolchain { - guard let executable = runtimeService.javaExecutableURL(overridePath: options.javaHomePath) else { - throw RunExecutableResolutionError( - message: L10n.string("No Java runtime was found. Set JAVA_HOME or install a JDK.") - ) - } - return ResolvedRunToolchain( - executableURL: executable, - environment: runtimeService.environment( - for: .java, - javaHomeOverride: options.javaHomePath - ) - ) - } -} - -@MainActor -private final class MavenRunToolchainProvider: RunToolchainProvider { - let identifiers: Set = ["project-maven"] - let toolchainType = "maven" - let languageProviderID: String? = "java" - - func resolvePassive(projectURL: URL, options: RunOptions, runtimeService: ProjectRuntimeService) throws -> ResolvedRunToolchain? { - guard let executable = runtimeService.mavenExecutable(at: projectURL, overridePath: options.mavenExecutablePath) else { - throw RunExecutableResolutionError(message: L10n.string("No Maven executable was found. Edit this service configuration.")) - } - return ResolvedRunToolchain(executableURL: executable, environment: [:]) - } - - func resolve( - projectURL: URL, - options: RunOptions, - runtimeService: ProjectRuntimeService - ) throws -> ResolvedRunToolchain { - guard let executable = runtimeService.mavenExecutable( - at: projectURL, - overridePath: options.mavenExecutablePath - ) else { - throw RunExecutableResolutionError( - message: L10n.string("No Maven executable was found. Edit this service configuration.") - ) - } - return ResolvedRunToolchain( - executableURL: executable, - environment: runtimeService.environment( - for: .maven, - javaHomeOverride: options.mavenJavaHomePath.isEmpty - ? options.javaHomePath - : options.mavenJavaHomePath - ) - ) - } -} - @MainActor private final class PathRunToolchainProvider: RunToolchainProvider { let identifiers: Set diff --git a/macos/Sources/Lithe/Core/Ports/RuntimeLocator.swift b/macos/Sources/Lithe/Core/Ports/RuntimeLocator.swift index d3155c89a7..cd45268b30 100644 --- a/macos/Sources/Lithe/Core/Ports/RuntimeLocator.swift +++ b/macos/Sources/Lithe/Core/Ports/RuntimeLocator.swift @@ -69,73 +69,33 @@ protocol RuntimeLocator: Sendable { /// A failed host probe must not be presented as an empty local toolchain. var discoveryFailure: String? { get } func normalizedPath(_ path: String, relativeTo root: URL?) -> String - func configureProbePaths(_ paths: [String]) - /// Remote adapters select from a host-read snapshot without UI-thread I/O. - func selectJavaRuntime(candidates: [AutomaticJavaCandidate], fallbackID: String?) -> Result? func environment() -> [String: String] /// Platform search path used only when a launch environment omits PATH. func defaultExecutableSearchPath() -> String? - func discover() -> RuntimeDiscoveryResult - func discover(isCancelled: @Sendable () -> Bool) -> RuntimeDiscoveryResult - /// Java-only probing for launch paths; never runs Maven or other tools. - func discoverJavaRuntimes() -> [JavaRuntimeCandidate] - func discoverJavaRuntimes(isCancelled: @Sendable () -> Bool) -> [JavaRuntimeCandidate] - /// Explicit refresh invalidates the platform's in-memory version probes. + /// Reads the host's login environment and the executables on its PATH. + /// Only adapters that cannot answer synchronously (a remote host) do work + /// here; the call runs on a worker queue, never on the UI executor. + func probeHost(isCancelled: @Sendable () -> Bool) + /// Explicit refresh invalidates the platform's in-memory probes. func invalidateProbeCache() - func validJavaHome(path: String) -> URL? - /// Returns the candidate reached by PATH, resolving platform symlinks. - func javaHomeOnPath(in candidates: [JavaRuntimeCandidate]) -> URL? - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? func isExecutable(at url: URL) -> Bool - func systemMavenExecutable() -> URL? - func mavenExecutable(forHomePath path: String) -> URL? - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? } extension RuntimeLocator { var discoveryFailure: String? { nil } - func configureProbePaths(_ paths: [String]) {} - func selectJavaRuntime(candidates: [AutomaticJavaCandidate], fallbackID: String?) -> Result? { nil } func normalizedPath(_ path: String, relativeTo root: URL?) -> String { let normalized = ((path as NSString).expandingTildeInPath as NSString).standardizingPath guard !(normalized as NSString).isAbsolutePath, let root else { return normalized } return root.appendingPathComponent(normalized).standardizedFileURL.path } - func discover(isCancelled: @Sendable () -> Bool) -> RuntimeDiscoveryResult { - isCancelled() ? RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) : discover() - } func defaultExecutableSearchPath() -> String? { nil } + func probeHost(isCancelled: @Sendable () -> Bool) {} func invalidateProbeCache() {} - func discoverJavaRuntimes(isCancelled: @Sendable () -> Bool) -> [JavaRuntimeCandidate] { - isCancelled() ? [] : discoverJavaRuntimes() - } - func discoverJavaRuntimes() -> [JavaRuntimeCandidate] { discover().javaRuntimes } - func javaHomeOnPath(in candidates: [JavaRuntimeCandidate]) -> URL? { nil } } /// Synchronous host I/O used exclusively by runtime discovery's owned worker. protocol RemoteRuntimeProbing: Sendable { func runtimeEnvironment(session: String) throws -> [String: String] func runtimeDirectory(_ path: String, session: String) throws -> [RemoteDirectoryEntry] - func runtimeRealPath(_ path: String, session: String) throws -> String func runtimeExecutable(_ path: String, session: String) throws -> Bool - func runtimeVersion(_ executable: String, session: String) throws -> String - func runtimeRequirements(_ root: String, session: String) throws -> ToolingJSONValue -} - -/// Shared selection policy; platform locators still own executable validation -/// and version probing. Requirements are read through Core's existing document. -protocol JavaRuntimeSelecting: Sendable { - func selectJavaRuntime(at root: URL?, candidates: [AutomaticJavaCandidate], fallbackID: String?) -> Result -} - -struct AutomaticJavaCandidate: Codable, Sendable { - let id: String - let version: String - let priority: UInt32 -} - -struct AutomaticJavaSelection: Decodable, Sendable { - let id: String? - let warning: String? } diff --git a/macos/Sources/Lithe/Core/Ports/TestJVMPerformance.swift b/macos/Sources/Lithe/Core/Ports/TestJVMPerformance.swift deleted file mode 100644 index 0118f7bfd5..0000000000 --- a/macos/Sources/Lithe/Core/Ports/TestJVMPerformance.swift +++ /dev/null @@ -1,28 +0,0 @@ -import Foundation - -struct TestJVMProcess: Equatable, Hashable, Sendable, Identifiable { - let processID: Int32 - let javaExecutable: URL - let startedSeconds: UInt64 - let startedMicroseconds: UInt64 - var id: String { "\(processID):\(startedSeconds):\(startedMicroseconds)" } - var target: DebugPerformanceTarget { DebugPerformanceTarget(processID: processID, javaExecutable: javaExecutable) } -} - -struct TestJVMRecording: Equatable, Sendable { - let id: UUID - let process: TestJVMProcess - let fileURL: URL - let startedAt: Date - var name: String { "lithe-\(id.uuidString)" } -} - -/// JDK tools own recording and report semantics; the native host owns processes -/// and temporary files. No JFR binary parser or JVM agent lives in the UI. -protocol TestJVMPerformanceProviding: Sendable { - func processes(rootProcessID: Int32) -> AsyncThrowingStream<[TestJVMProcess], Error> - func startRecording(_ process: TestJVMProcess) async throws -> TestJVMRecording - func stopRecording(_ recording: TestJVMRecording) async throws - func report(_ recording: TestJVMRecording) async throws -> String - func discard(_ recording: TestJVMRecording) async -} diff --git a/macos/Sources/Lithe/Core/Ports/ToolchainSettings.swift b/macos/Sources/Lithe/Core/Ports/ToolchainSettings.swift index 3a18b16743..d46fbf659e 100644 --- a/macos/Sources/Lithe/Core/Ports/ToolchainSettings.swift +++ b/macos/Sources/Lithe/Core/Ports/ToolchainSettings.swift @@ -99,7 +99,7 @@ struct ToolchainSettingsSnapshot: Equatable, Sendable { /// `host:system` for a definition scan, otherwise the qualified provider. let provider: String /// The scanned entry the home was found under, when the definition's home layout - /// adds a suffix (`jdk-21.jdk` for `jdk-21.jdk/Contents/Home`); it names the installation. + /// adds a suffix (`tool-21.kit` for `tool-21.kit/Contents/Home`); it names the installation. var location: String? = nil } diff --git a/macos/Sources/Lithe/Core/Rust/RustBuildSystemOperations.swift b/macos/Sources/Lithe/Core/Rust/RustBuildSystemOperations.swift index e22d791146..3c70baef74 100644 --- a/macos/Sources/Lithe/Core/Rust/RustBuildSystemOperations.swift +++ b/macos/Sources/Lithe/Core/Rust/RustBuildSystemOperations.swift @@ -28,24 +28,6 @@ struct RustBuildSystemOperations: BuildSystemPlanning { return outcome.value.detection } - func languageImport( - _ target: BuildSystemTarget, - workspaceURL: URL, - root: String, - options: [String: ToolingJSONValue], - executableURL: URL? - ) throws -> BuildLanguageImport? { - let outcome: Outcome = try execute( - "build.languageImport", - target: target, - request: LanguageImportRequest( - workspaceRoot: workspaceURL.path, root: root, options: options, - executablePath: executableURL?.path - ) - ) - return outcome.value.languageImport - } - func invocationPlan( _ target: BuildSystemTarget, root: String, settings: [String: ToolingJSONValue] = [:] ) throws -> BuildInvocation { @@ -432,17 +414,6 @@ struct RustBuildSystemOperations: BuildSystemPlanning { let request: Request } - private struct LanguageImportRequest: Encodable { - let workspaceRoot: String - let root: String - let options: [String: ToolingJSONValue] - let executablePath: String? - } - - private struct LanguageImportResult: Decodable { - let languageImport: BuildLanguageImport? - } - private struct InvocationRequest: Encodable { let root: String let platform: String diff --git a/macos/Sources/Lithe/Core/Rust/RustCoreBridge+RemoteWorkspace.swift b/macos/Sources/Lithe/Core/Rust/RustCoreBridge+RemoteWorkspace.swift index 0599c1b173..ca5a444cc2 100644 --- a/macos/Sources/Lithe/Core/Rust/RustCoreBridge+RemoteWorkspace.swift +++ b/macos/Sources/Lithe/Core/Rust/RustCoreBridge+RemoteWorkspace.swift @@ -12,7 +12,7 @@ extension RustCoreBridge { "workspace.repositories", "workspace.snapshot", "workspace.listDirectories", "workspace.search", "workspace.searchEverywhere", "file.read", "file.write", "workspace.searchIndex.warm", "workspace.searchIndex.update", "workspace.searchIndex.invalidate", - "workspace.replacePreview", "runConfig.selectJava", "lsp.startServer" + "workspace.replacePreview", "lsp.startServer" ].contains(command) else { return nil } let encoded = try JSONEncoder().encode(payload) guard let object = try JSONSerialization.jsonObject(with: encoded) as? [String: Any] else { return nil } diff --git a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift index 1cadb1c7bd..d745572541 100644 --- a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift +++ b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift @@ -419,113 +419,12 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let description: String } - struct JavaRunMarkersPayload: Decodable, Sendable { - let markers: [JavaRunMarker] - } - - struct SpringIndexPayload: Decodable, Sendable { - struct Property: Decodable, Sendable { - let name: String - let typeName: String? - let description: String? - let defaultValue: String? - let sourcePath: String? - let sourceLine: Int? - let sourceColumn: Int? - } - struct ConfigurationValue: Decodable, Sendable { - let key: String - let value: String - let path: String - let line: Int - let column: Int - let profile: String? - let overridesBaseValue: Bool - let targetPath: String? - let targetLine: Int? - let targetColumn: Int? - } - struct PropertyReference: Decodable, Sendable { - let key: String - let path: String - let line: Int - let column: Int - } - struct Diagnostic: Decodable, Sendable { - let path: String - let line: Int - let column: Int - let severity: String - let message: String - } - struct Bean: Decodable, Sendable { - let id: String - let name: String - let typeName: String - let path: String - let line: Int - let column: Int - let kind: String - } - struct Injection: Decodable, Sendable { - let path: String - let line: Int - let column: Int - let typeName: String - let qualifier: String? - let beanIds: [String] - } - struct Endpoint: Decodable, Sendable { - let id: String - let httpMethods: [String] - let route: String - let controller: String - let method: String - let path: String - let line: Int - let column: Int - } - - let properties: [Property] - let values: [ConfigurationValue] - let propertyReferences: [PropertyReference] - let diagnostics: [Diagnostic] - let beans: [Bean] - let injections: [Injection] - let endpoints: [Endpoint] - } - - struct MybatisIndexPayload: Decodable, Sendable { - struct Statement: Decodable, Sendable { - let id: String - let namespace: String - let statementId: String - let kind: String - let javaPath: String - let javaLine: Int - let javaColumn: Int - let javaEndLine: Int - let javaEndColumn: Int - let xmlPath: String - let xmlLine: Int - let xmlColumn: Int - let xmlEndColumn: Int - } - - let statements: [Statement] - } - struct RunConfigurationPayload: Codable, Sendable { + /// Document-level machine toolchain of the local layer: explicit + /// executables per generic toolchain ID and inert generic preferences. struct Toolchain: Codable, Sendable { - struct Java: Codable, Sendable { let homePath: String? } - struct Maven: Codable, Sendable { - let executablePath: String? - let javaHomePath: String? - } - - let java: Java? - let maven: Maven? - var pathOverrides: [String: ProjectToolchainSelection.PathOverride]? = nil + var runtimeExecutablePaths: [String: String]? = nil + var preferences: ToolingJSONValue? = nil } struct Generator: Codable, Sendable { let fingerprint: String @@ -535,35 +434,14 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let inputs: [String: String]? } struct Configuration: Codable, Sendable { - struct Maven: Codable, Sendable { - var reactorPath: String? = nil - let module: String? - let mainClass: String? - let jvmArguments: [String]? - let programArguments: [String]? - let profiles: [String]? - let skipTests: Bool? - } - struct Java: Codable, Sendable { - let homePath: String? - let mavenExecutablePath: String? - let mavenJavaHomePath: String? - let source: String? - let sourceSet: String? - var module: String? = nil - var mainClass: String? = nil - var build: RunBuildProjectReference? = nil - } struct Debug: Codable, Sendable { let adapter: String } struct Extensions: Codable, Sendable { - let maven: Maven? - let java: Java? var build: BuildProviderRunReference? = nil var buildRun: BuildProviderRunOptions? = nil private enum CodingKeys: String, CodingKey { - case maven, java, build + case build case buildRun = "build-run" } } @@ -582,8 +460,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let extensions: Extensions? let disabled: Bool let source: String? - - var maven: Maven? { extensions?.maven } } let version: Int @@ -607,7 +483,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let preferredVendor: String? let wrapper: String? let version: String? - let java: String? } let version: Int let toolchains: [String: Requirement] @@ -629,20 +504,11 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let command: String? let tool: String? } - struct PreLaunchStep: Codable, Sendable { - let executable: Executable - let arguments: [String] - let classpath: [String]? - let workingDirectory: String? - } let executable: Executable let arguments: [String] let workingDirectory: String let environment: [String: [String: String]] let env: [String: String]? - let preLaunchSteps: [PreLaunchStep]? - let classpath: [String]? - let modulepath: [String]? } struct RunConfigurationMutationPayload: Codable, Sendable { @@ -655,30 +521,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let projectDocument: String? } - struct JavaCodeVisionPayload: Decodable, Sendable { - struct Hint: Decodable, Sendable { - let line: Int - let utf16Column: Int - let symbol: String - let usageCount: Int - } - - let hints: [Hint] - } - - struct JavaClassNamePayload: Decodable, Sendable { - let className: String - } - - struct JavaSourceDefinitionPayload: Decodable, Sendable { - let line: Int - let utf16Column: Int - } - - struct JavaServerPortPayload: Decodable, Sendable { - let port: Int? - } - struct TextPayload: Decodable, Sendable { let text: String } @@ -886,48 +728,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { } } - struct JavaStructurePayload: Decodable, Sendable { - struct FoldRegion: Decodable, Sendable { - let kind: String - let startLine: Int - let endLine: Int - let hiddenStart: Int - let hiddenLength: Int - - func makeModel() -> JavaFoldRegion? { - guard let kind = JavaFoldKind(rawValue: kind) else { return nil } - return JavaFoldRegion( - kind: kind, - startLine: startLine, - endLine: endLine, - hiddenRange: NSRange(location: hiddenStart, length: hiddenLength) - ) - } - } - - struct SyntaxHighlight: Decodable, Sendable { - let utf16Start: Int - let utf16Length: Int - let role: String - - func makeModel() -> JavaSyntaxHighlight? { - guard utf16Start >= 0, utf16Length > 0 else { return nil } - return JavaSyntaxHighlight( - range: NSRange(location: utf16Start, length: utf16Length), - role: role - ) - } - } - - let foldRegions: [FoldRegion] - let syntaxHighlights: [SyntaxHighlight] - - func makeFoldRegions() -> [JavaFoldRegion] { foldRegions.compactMap { $0.makeModel() } } - func makeSyntaxHighlights() -> [JavaSyntaxHighlight] { - syntaxHighlights.compactMap { $0.makeModel() } - } - } - struct GitCommandPayload: Decodable, Sendable { struct Invocation: Decodable, Sendable { let arguments: [String] @@ -1783,61 +1583,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let processId: Int32? } - private struct JdtWorkspaceKeyRequest: Encodable { - let workspaceRoot: String - let workspaceFingerprint: String? - } - - private struct JdtWorkspaceKeyPayload: Decodable { - let workspaceKey: String - } - - struct JdtBuildFileObservation: Encodable, Equatable, Sendable { - let path: String - } - - private struct JdtWorkspaceFingerprintRequest: Encodable { - let buildFiles: [JdtBuildFileObservation] - let directMavenModules: [String] - let jdtlsVersion: String - } - - private struct JdtWorkspaceFingerprintPayload: Decodable { - let workspaceFingerprint: String - } - - struct JdtCacheEntry: Encodable, Sendable { - let workspaceKey: String - let lastModifiedUnixSeconds: UInt64 - } - - private struct JdtCacheRetentionRequest: Encodable { - let nowUnixSeconds: UInt64 - let activeWorkspaceKey: String? - let entries: [JdtCacheEntry] - } - - struct JdtCacheRetentionPayload: Decodable, Sendable { - let retentionDays: UInt64 - let expiredWorkspaceKeys: [String] - } - - private struct JavaWorkspacePolicyRequest: Encodable { - let workspacePaths: [String] - let changedPaths: [String] - } - - struct JavaWorkspacePolicyPayload: Decodable, Sendable { - struct Change: Decodable, Sendable { - let path: String - let kind: String - } - - let shouldStart: Bool - let representativeJavaPath: String? - let changes: [Change] - } - /// File paths are converted by Core inside the existing LSP request. An /// upstream virtual URI keeps its original identity and is never rewritten. private enum LspDocumentURI: Encodable { @@ -1893,13 +1638,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { /// (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? - let workspaceFingerprint: String? - let mavenContext: MavenLaunchContext? - let javaGradle: JavaGradleImportConfiguration? - let javaRuntimes: [LspJavaRuntimeRequest] let initializeTimeoutMilliseconds: Int let requestTimeoutMilliseconds: Int let shutdownTimeoutMilliseconds: Int @@ -1911,30 +1649,10 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let editor: PluginEditorHostOptions } - private struct LspJavaRuntimeRequest: Encodable { - let isDefault: Bool - let homePath: String - let version: String - } - - private struct LspJdtlsLaunchResourcesRequest: Encodable { - let launcherJarPath: String - let configurationDirectory: String - let lombokAgentPath: String - let javaDebugBundlePath: String? - let javaExtensionBundlePaths: [String] - } - private struct LspSessionIdentifierRequest: Encodable { let sessionId: String } - private struct LspUpdateMavenConfigurationRequest: Encodable { - let sessionId: String - let mavenContext: MavenLaunchContext - let reloadProjects: Bool - } - private struct LspSyncDocumentRequest: Encodable { struct Change: Encodable { let range: Range @@ -1970,22 +1688,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let changed: Bool } - private struct JavaNavigationMarkersRequest: Encodable { - let sessionId: String - let uri: LspDocumentURI - let documentVersion: Int - } - - private struct JavaResolveNavigationRequest: Encodable { - let sessionId: String - let uri: LspDocumentURI - let line: Int - let utf16Column: Int - let direction: String - let relation: String - let documentVersion: Int - } - private struct LspCloseDocumentRequest: Encodable { let sessionId: String let uri: LspDocumentURI @@ -2159,14 +1861,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let level: String? let message: String? let detail: String? - let mavenProfileTask: String? - let mavenProfileProject: MavenProfileProjectPayload? - } - - struct MavenProfileProjectPayload: Decodable, Sendable { - let projectUri: URL - let status: String - let errorDetails: String? } struct LspRuntimeErrorPayload: Decodable, Sendable { @@ -2179,7 +1873,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let message: String let underlyingMessage: String? 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. @@ -2191,34 +1884,18 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let version: String? } - private struct JavaRunMarkersRequest: Encodable { - let mainMethods: [JavaMainMethod] - let testItems: [JavaTestItem] - let testCases: [BuildTestResults.TestCase] - } - private struct RunConfigurationInspectRequest: Encodable { let root: String /// Omitted means full inspection, including the input fingerprint. let checkFingerprint: Bool? - /// JDT's current answer; omitted while the Java service is not ready. - let javaEntrypoints: JavaEntrypoints? - let projectOwnership: [RunProjectOwnership]? let providerRuns: [RunProviderConfiguration]? } private struct RunConfigurationGenerateRequest: Encodable { let root: String - let paths: [String] - let modulePaths: [String] - /// Omitted while JDT has not answered; Core then keeps the previous - /// generation's Java entries. - let javaEntrypoints: JavaEntrypoints? - let projectOwnership: [RunProjectOwnership]? let providerRuns: [RunProviderConfiguration]? /// Application cache root where Core keeps the last detection for the /// next session; the workspace is never written. let cacheDirectory: String? - } private struct RunConfigurationResolveRequest: Encodable { let root: String @@ -2226,20 +1903,21 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let teamDocument: ToolingJSONValue? let localDocument: ToolingJSONValue? } + /// Document-level machine toolchain written by `runConfig.updateOptions` + /// and `runConfig.saveEditorChanges`; both maps are generic and empty + /// values leave the saved document untouched. + struct RunConfigurationToolchainRequest: Encodable { + var runtimeExecutablePaths: [String: String] = [:] + var preferences: ToolingJSONValue? = nil + } private struct RunConfigurationUpdateOptionsRequest: Encodable { let root: String let scope: String let configurationId: String let workingDirectory: String - let jvmArguments: String let arguments: String let environment: [String: String] - let mavenProfiles: [String] - let mavenSkipTests: Bool? - let javaHomePath: String - let mavenExecutablePath: String - let mavenJavaHomePath: String - let toolchain: ProjectToolchainSelection? + let toolchain: RunConfigurationToolchainRequest? let providerRunOptions: BuildProviderRunOptions? } private struct RunConfigurationCreateUserRequest: Encodable { @@ -2247,65 +1925,11 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let scope: String let name: String let type: String - let module: String - let mainClass: String var build: BuildProviderRunReference? = nil } private struct LaunchPlanRequest: Encodable { - struct JavaLaunch: Encodable { - let mainClass: String - let classPaths: [String] - let modulePaths: [String] - let buildPrepared: Bool - } let root: String let configurationId: String - let currentFile: String? - let classPath: String? - let javaLaunch: JavaLaunch? - let debugPort: Int? - let mavenContext: MavenLaunchContext? - } - - private struct JavaStructureRequest: Encodable { - let source: String - let declarationSources: [String] - } - - private struct SpringIndexRequest: Encodable { - let root: String - let paths: [String] - let metadataRepositories: [String] - let refreshDependencyMetadata: Bool - let textOverrides: [String: String] - } - - private struct MybatisIndexRequest: Encodable { - let root: String - let paths: [String] - let textOverrides: [String: String] - } - - private struct JavaCodeVisionRequest: Encodable { - let root: String - let targetPath: String - let paths: [String] - } - - private struct JavaClassNameRequest: Encodable { - let source: String - let simpleName: String - } - - private struct JavaSourceDefinitionRequest: Encodable { - let source: String - let declarationName: String - let memberName: String? - } - - private struct JavaServerPortRequest: Encodable { - let content: String - let fileExtension: String } private struct GitStatusRequest: Encodable { @@ -2863,54 +2487,9 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { return response?.relocated == true } - /// Combines JDT main/test discovery and recorded outcomes into gutter markers. - func javaRunMarkers( - mainMethods: [JavaMainMethod], - testItems: [JavaTestItem], - testCases: [BuildTestResults.TestCase] - ) -> Result { - executeResult( - command: "java.runMarkers", - payload: JavaRunMarkersRequest( - mainMethods: mainMethods, - testItems: testItems, - testCases: testCases - ) - ) - } - - func selectJavaRuntime( - at root: URL?, candidates: [AutomaticJavaCandidate], fallbackID: String? - ) -> Result { - struct Payload: Encodable { - let root: String? - let candidates: [AutomaticJavaCandidate] - let fallbackId: String? - } - return executeResult(command: "runConfig.selectJava", payload: Payload( - root: root?.standardizedFileURL.path, candidates: candidates, fallbackId: fallbackID - )) - } - - /// Snapshot selection performs no filesystem access, including for a remote project. - func selectJavaRuntime( - requirements: ToolingJSONValue, candidates: [AutomaticJavaCandidate], fallbackID: String? - ) -> Result { - struct Payload: Encodable { - let requirements: ToolingJSONValue - let candidates: [AutomaticJavaCandidate] - let fallbackId: String? - } - return executeResult(command: "runConfig.selectJava", payload: Payload( - requirements: requirements, candidates: candidates, fallbackId: fallbackID - )) - } - func inspectRunConfiguration( at rootURL: URL, checkFingerprint: Bool? = nil, - javaEntrypoints: JavaEntrypoints? = nil, - projectOwnership: [RunProjectOwnership]? = nil, providerRuns: [RunProviderConfiguration]? = nil ) -> Result { executeResult( @@ -2918,32 +2497,22 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { payload: RunConfigurationInspectRequest( root: rootURL.standardizedFileURL.path, checkFingerprint: checkFingerprint, - javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns + providerRuns: providerRuns ) ) } func generateRunConfiguration( at rootURL: URL, - paths: [String], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints? = nil, - projectOwnership: [RunProjectOwnership]? = nil, providerRuns: [RunProviderConfiguration]? = nil, cacheDirectoryURL: URL? = nil - ) -> Result { executeResult( command: "runConfig.generate", payload: RunConfigurationGenerateRequest( root: rootURL.standardizedFileURL.path, - paths: paths, - modulePaths: modulePaths, - javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns, + providerRuns: providerRuns, cacheDirectory: cacheDirectoryURL?.path - ) ) } @@ -2972,30 +2541,13 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { func createLaunchPlan( at rootURL: URL, - configurationID: String, - currentFile: String? = nil, - classPath: String? = nil, - javaLaunch: JavaDebugLaunchTarget? = nil, - debugPort: Int? = nil, - mavenContext: MavenLaunchContext? = nil + configurationID: String ) -> Result { executeResult( command: "runConfig.createLaunchPlan", payload: LaunchPlanRequest( root: rootURL.standardizedFileURL.path, - configurationId: configurationID, - currentFile: currentFile, - classPath: classPath, - javaLaunch: javaLaunch.map { - LaunchPlanRequest.JavaLaunch( - mainClass: $0.mainClass, - classPaths: $0.classPaths, - modulePaths: $0.modulePaths, - buildPrepared: $0.buildPrepared - ) - }, - debugPort: debugPort, - mavenContext: mavenContext + configurationId: configurationID ) ) } @@ -3005,7 +2557,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { configurationID: String, scope: RunConfigurationSaveScope, options: RunOptions, - toolchain: ProjectToolchainSelection? = nil + toolchain: RunConfigurationToolchainRequest? = nil ) -> Result { executeResult( command: "runConfig.updateOptions", @@ -3014,14 +2566,8 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { scope: scope.rawValue, configurationId: configurationID, workingDirectory: options.workingDirectoryPath, - jvmArguments: options.vmArguments, arguments: options.arguments, environment: options.environment, - mavenProfiles: options.activeProfiles.sorted(), - mavenSkipTests: options.mavenSkipTests, - javaHomePath: options.javaHomePath, - mavenExecutablePath: options.mavenExecutablePath, - mavenJavaHomePath: options.mavenJavaHomePath, toolchain: toolchain, providerRunOptions: options.providerRunOptions ) @@ -3033,7 +2579,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { configurationID: String, scope: RunConfigurationSaveScope, options: RunOptions, - toolchain: ProjectToolchainSelection + toolchain: RunConfigurationToolchainRequest = .init() ) -> Result { executeResult( command: "runConfig.saveEditorChanges", @@ -3042,14 +2588,8 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { scope: scope.rawValue, configurationId: configurationID, workingDirectory: options.workingDirectoryPath, - jvmArguments: options.vmArguments, arguments: options.arguments, environment: options.environment, - mavenProfiles: options.activeProfiles.sorted(), - mavenSkipTests: options.mavenSkipTests, - javaHomePath: options.javaHomePath, - mavenExecutablePath: options.mavenExecutablePath, - mavenJavaHomePath: options.mavenJavaHomePath, toolchain: toolchain, providerRunOptions: options.providerRunOptions ) @@ -3060,111 +2600,7 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { name: String) -> Result { executeResult(command: "runConfig.createUserConfiguration", payload: RunConfigurationCreateUserRequest( root: rootURL.standardizedFileURL.path, scope: "local", name: name, type: "buildProvider", - module: "", mainClass: "", build: reference)) - } - - func createUserRunConfiguration( - at rootURL: URL, - draft: RunConfigurationDraft - ) -> Result { - executeResult( - command: "runConfig.createUserConfiguration", - payload: RunConfigurationCreateUserRequest( - root: rootURL.standardizedFileURL.path, - scope: draft.scope.rawValue, - name: draft.name, - type: draft.kind.id, - module: draft.modulePath, - mainClass: draft.mainClass - ) - ) - } - - func javaCodeVision( - at rootURL: URL, - targetPath: String, - paths: [String] - ) -> JavaCodeVisionPayload? { - execute( - command: "java.codeVision", - payload: JavaCodeVisionRequest( - root: rootURL.standardizedFileURL.path, - targetPath: targetPath, - paths: paths - ) - ) - } - - func javaClassName(source: String, simpleName: String) -> JavaClassNamePayload? { - execute( - command: "java.className", - payload: JavaClassNameRequest(source: source, simpleName: simpleName) - ) - } - - func javaSourceDefinition( - source: String, - declarationName: String, - memberName: String? - ) -> JavaSourceDefinitionPayload? { - execute( - command: "java.sourceDefinition", - payload: JavaSourceDefinitionRequest( - source: source, - declarationName: declarationName, - memberName: memberName - ) - ) - } - - func javaServerPort(content: String, fileExtension: String) -> JavaServerPortPayload? { - execute( - command: "java.serverPort", - payload: JavaServerPortRequest(content: content, fileExtension: fileExtension) - ) - } - - func javaStructure(source: String, declarationSources: [String] = []) -> JavaStructurePayload? { - execute( - command: "java.structure", - payload: JavaStructureRequest(source: source, declarationSources: declarationSources) - ) - } - - func springIndex( - at rootURL: URL, - paths: [String], - metadataRepositoryURLs: [URL] = [], - refreshDependencyMetadata: Bool = false, - textOverrides: [String: String] = [:] - ) -> SpringIndexPayload? { - execute( - command: "spring.index", - payload: SpringIndexRequest( - root: rootURL.standardizedFileURL.path, - paths: paths, - metadataRepositories: metadataRepositoryURLs.map { - $0.standardizedFileURL.path - }, - refreshDependencyMetadata: refreshDependencyMetadata, - textOverrides: textOverrides - ) - ) - } - - func mybatisIndex( - at rootURL: URL, - paths: [String], - textOverrides: [String: String] = [:] - ) -> MybatisIndexPayload? { - execute( - command: "mybatis.index", - payload: MybatisIndexRequest( - root: rootURL.standardizedFileURL.path, - paths: paths, - textOverrides: textOverrides - ) - ) + build: reference)) } func gitStatus( @@ -3807,69 +3243,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { // MARK: - Language-server runtime - /// Resolves the exact JDT LS directory key used by the Rust runtime. - func jdtWorkspaceKey( - workspaceRootURL: URL, - workspaceFingerprint: String? - ) -> Result { - let result: Result = executeResult( - command: "lsp.jdtWorkspaceKey", - payload: JdtWorkspaceKeyRequest( - workspaceRoot: workspaceRootURL.standardizedFileURL.path, - workspaceFingerprint: workspaceFingerprint - ) - ) - return result.map(\.workspaceKey) - } - - /// Reduces platform filesystem observations to the shared JDT LS - /// workspace-fingerprint representation owned by Rust Core. - func jdtWorkspaceFingerprint( - buildFiles: [JdtBuildFileObservation], - directMavenModules: [String], - jdtlsVersion: String - ) -> Result { - let result: Result = executeResult( - command: "java.jdtWorkspaceFingerprint", - payload: JdtWorkspaceFingerprintRequest( - buildFiles: buildFiles, - directMavenModules: directMavenModules, - jdtlsVersion: jdtlsVersion - ) - ) - return result.map(\.workspaceFingerprint) - } - - /// Applies the shared retention policy to filesystem metadata collected by - /// a platform adapter. Rust Core selects keys but never deletes directories. - func jdtCacheRetention( - nowUnixSeconds: UInt64, - activeWorkspaceKey: String?, - entries: [JdtCacheEntry] - ) -> Result { - executeResult( - command: "java.jdtCacheRetention", - payload: JdtCacheRetentionRequest( - nowUnixSeconds: nowUnixSeconds, - activeWorkspaceKey: activeWorkspaceKey, - entries: entries - ) - ) - } - - func javaWorkspacePolicy( - workspacePaths: [String], - changedPaths: [String] - ) -> JavaWorkspacePolicyPayload? { - execute( - command: "java.workspacePolicy", - payload: JavaWorkspacePolicyRequest( - workspacePaths: workspacePaths, - changedPaths: changedPaths - ) - ) - } - /// Starts a language server and returns its opaque session ID. Rust spawns /// and owns the process; nothing about it crosses back except this ID. func lspStartServer( @@ -3887,12 +3260,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { toolchainProviders: [String] = [], keymapImportProviders: [String] = [], sessionPolicy: ToolingJSONValue? = nil, - runtimeExecutableURL: URL? = nil, - jdtlsLaunchResources: JDTLSLaunchResources? = nil, - cacheDirectoryURL: URL? = nil, - workspaceFingerprint: String? = nil, - mavenContext: MavenLaunchContext? = nil, - javaGradle: JavaGradleImportConfiguration? = nil, initializeTimeout: TimeInterval = 30, requestTimeout: TimeInterval = 30, shutdownTimeout: TimeInterval = 2 @@ -3916,23 +3283,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { toolchainProviders: toolchainProviders.isEmpty ? nil : toolchainProviders, keymapImportProviders: keymapImportProviders.isEmpty ? nil : keymapImportProviders, sessionPolicy: sessionPolicy, - runtimeExecutablePath: runtimeExecutableURL?.standardizedFileURL.path, - jdtlsLaunchResources: jdtlsLaunchResources.map { - LspJdtlsLaunchResourcesRequest( - launcherJarPath: $0.launcherJarURL.path, - configurationDirectory: $0.configurationDirectoryURL.path, - lombokAgentPath: $0.lombokAgentURL.path, - javaDebugBundlePath: $0.javaDebugBundleURL?.path, - javaExtensionBundlePaths: $0.javaExtensionBundleURLs.map(\.path) - ) - }, - cacheDirectory: cacheDirectoryURL?.standardizedFileURL.path, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, - javaGradle: javaGradle, - javaRuntimes: (jdtlsLaunchResources?.javaRuntimes ?? []).map { - LspJavaRuntimeRequest(isDefault: $0.isDefault, homePath: $0.homePath, version: $0.version) - }, initializeTimeoutMilliseconds: Self.milliseconds(initializeTimeout), requestTimeoutMilliseconds: Self.milliseconds(requestTimeout), shutdownTimeoutMilliseconds: Self.milliseconds(shutdownTimeout) @@ -3969,31 +3319,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { let configuration: ToolingJSONValue } - /// Retries Maven Profile application while retaining the running JDTLS process. - func lspRetryMavenProfiles(sessionID: String) -> Result { - executeVoid( - command: "lsp.retryMavenProfiles", - payload: LspSessionIdentifierRequest(sessionId: sessionID) - ) - } - - /// Sends a changed Maven context to a running JDTLS session. JDT LS - /// re-resolves in place instead of restarting on its unchanged workspace state. - func lspUpdateMavenConfiguration( - sessionID: String, - context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result { - executeResult( - command: "lsp.updateMavenConfiguration", - payload: LspUpdateMavenConfigurationRequest( - sessionId: sessionID, - mavenContext: context, - reloadProjects: reloadProjects - ) - ) - } - func lspSaveDocument(sessionID: String, fileURL: URL, text: String) -> Result { struct Request: Encodable { let sessionId: String; let uri: LspDocumentURI; let text: String } struct Response: Decodable { let sent: Bool } @@ -4133,57 +3458,6 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { ) } - func lspPrepareJavaLaunch( - sessionID: String, - fileURL: URL, - mainClass: String? - ) -> Result { - struct Request: Encodable { - let sessionId: String - let sourcePath: String - let mainClass: String? - } - return executeResult(command: "java.prepareLaunch", payload: Request( - sessionId: sessionID, sourcePath: fileURL.standardizedFileURL.resolvingSymlinksInPath().path, - mainClass: mainClass - )) - } - - func lspJavaNavigationMarkers( - sessionID: String, - fileURL: URL, - documentVersion: Int - ) -> Result { - executeResult( - command: "java.navigationMarkers", - payload: JavaNavigationMarkersRequest( - sessionId: sessionID, - uri: LspDocumentURI(fileURL), - documentVersion: documentVersion - ) - ) - } - - func lspResolveJavaNavigation( - sessionID: String, - fileURL: URL, - marker: JavaNavigationMarker, - documentVersion: Int - ) -> Result { - executeResult( - command: "java.resolveNavigation", - payload: JavaResolveNavigationRequest( - sessionId: sessionID, - uri: LspDocumentURI(fileURL), - line: marker.line, - utf16Column: marker.utf16Column, - direction: marker.direction.rawValue, - relation: marker.relation.rawValue, - documentVersion: documentVersion - ) - ) - } - /// Sends a `lithe/build/*` request Core planned. Core refuses it unless /// the session negotiated the build-provider protocol in `initialize`. func lspBuildRequest( @@ -4800,8 +4074,9 @@ private extension RustCoreBridge.WorkspaceNodePayload { /// 把只含单个子目录的中间包压缩成一行(IDEA 的 Compact Middle Packages)。 /// 规则对齐 TreeViewUtil.isEmptyMiddlePackage:唯一的子节点是目录、且当前 - /// 目录下没有文件时才压缩。只在源码根之下压缩,src/main/java 之外的目录树 - /// 保持原样,否则普通项目里任意的单层目录也会被合并,反而更难看懂。 + /// 目录下没有文件时才压缩。只在源码根之下压缩,源码根之外的目录树保持 + /// 原样,否则普通项目里任意的单层目录也会被合并,反而更难看懂。源码根 + /// 由调用方(用户标记或插件导入的构建模型)给出,这里不按目录名猜测。 private func makeFileNode(at rootURL: URL, insideSourceRoot: Bool, fileURLs: inout [String: URL]) -> FileNode { let url = path.isEmpty ? rootURL : rootURL.appendingPathComponent(path) @@ -4810,8 +4085,7 @@ private extension RustCoreBridge.WorkspaceNodePayload { return FileNode(url: url, isDirectory: false, children: nil) } - let selfIsSourceRoot = LitheIcons.isSourceRootDirectory(url) - let childrenInsideSourceRoot = insideSourceRoot || selfIsSourceRoot + let childrenInsideSourceRoot = insideSourceRoot // 源码根本身不参与压缩,从它的子目录开始。 var collapsed: [String] = [] @@ -4822,7 +4096,7 @@ private extension RustCoreBridge.WorkspaceNodePayload { kids.count == 1, let only = kids.first, only.isDirectory, - LitheIcons.isValidPackageName(only.name) { + LitheIcons.isPackageSegmentName(only.name) { collapsed.append(nodeURL.path) node = only nodeURL = rootURL.appendingPathComponent(only.path) @@ -4840,5 +4114,3 @@ private extension RustCoreBridge.WorkspaceNodePayload { ) } } - -extension RustCoreBridge: JavaRuntimeSelecting {} diff --git a/macos/Sources/Lithe/Core/Rust/RustDebugProtocolCore.swift b/macos/Sources/Lithe/Core/Rust/RustDebugProtocolCore.swift index 55674b2bec..3d7db63793 100644 --- a/macos/Sources/Lithe/Core/Rust/RustDebugProtocolCore.swift +++ b/macos/Sources/Lithe/Core/Rust/RustDebugProtocolCore.swift @@ -1,18 +1,6 @@ import Foundation import LitheCoreContracts -extension RustCoreBridge: JavaTestDebugLaunchResolving { - func resolveJavaTestDebugLaunch( - target: JavaTestDebugLaunchTarget, - resultPort: UInt16 - ) throws -> DebugLaunchConfiguration { - try executeResult( - command: "debug.javaTestLaunch", - payload: JavaTestDebugLaunchPayload(target: target, resultPort: resultPort) - ).get() - } -} - extension RustCoreBridge: DebugBreakpointRelocating { func relocateDebugBreakpoints( source: String, @@ -351,43 +339,6 @@ extension RustCoreBridge: DebugProtocolCore { } } -private struct JavaTestDebugLaunchPayload: Encodable { - let name: String - let framework: JavaTestDebugFramework - let workingDirectory: String - let mainClass: String - let projectName: String? - let classPaths: [String] - let modulePaths: [String] - let vmArguments: [String] - let programArguments: [String] - let resultPort: UInt16 - let testNGRunnerPath: String? - let testNGTestNames: [String] - - init(target: JavaTestDebugLaunchTarget, resultPort: UInt16) { - name = target.name - framework = target.framework - workingDirectory = target.workingDirectory - mainClass = target.mainClass - projectName = target.projectName - classPaths = target.classPaths - modulePaths = target.modulePaths - vmArguments = target.vmArguments - programArguments = target.programArguments - self.resultPort = resultPort - testNGRunnerPath = target.testNGRunnerPath - testNGTestNames = target.testNGTestNames - } - - private enum CodingKeys: String, CodingKey { - case name, framework, workingDirectory, mainClass, projectName - case classPaths, modulePaths, vmArguments, programArguments, resultPort - case testNGRunnerPath = "testngRunnerPath" - case testNGTestNames = "testngTestNames" - } -} - private struct DebugBreakpointRelocationPayload: Encodable { let source: String let edit: DebugSourceEdit diff --git a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift index ff6e2a731b..cd07e90dcf 100644 --- a/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift +++ b/macos/Sources/Lithe/Core/Rust/RustDeclarativePluginOperations.swift @@ -293,14 +293,15 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec arguments: plan.arguments, validationArguments: plan.validationArguments, initializationOptions: plan.initializationOptions, - entryPath: plan.launch.entry, + // A tool launch carries an absolute entry, which `toolLaunch` holds. + entryPath: plan.launch.kind == "tool" ? nil : plan.launch.entry, hostIntegration: plan.hostIntegration.map { .init(id: $0.id, resources: $0.resources.mapValues(\.paths)) }, packagedRuntimePath: plan.launch.packagedRuntime, executableVersionRequirement: plan.launch.versionRequirement, runtimeRequirements: plan.runtimeRequirements.map { - .init(tool: $0.tool, minimumVersion: $0.minimumVersion) + .init(tool: $0.tool, minimumVersion: $0.minimumVersion, resolvesThroughDefinition: $0.kind == "tool") }, requiredDirectories: try plan.requiredDirectories.map { name in guard let directory = DeclarativeLanguageServerLaunchPlan.RequiredDirectory(rawValue: name) else { @@ -323,6 +324,9 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec } ) result.workspaceConfiguration = plan.workspaceConfiguration + // The second step of a backend launch also says `tool`, but it names a + // resolved program, which `resolvedLaunch` carries instead. + result.toolLaunch = plan.writablePaths == nil ? plan.launch.toolLaunch : nil result.backendResolution = plan.backendResolution result.resolvedLaunch = plan.resolvedLaunch result.sessionPolicy = plan.sessionPolicy @@ -596,6 +600,8 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec struct RuntimeRequirement: Decodable { let tool: String let minimumVersion: String? + /// `tool` when the host resolves it through a tool definition. + let kind: String? } struct Launch: Decodable { @@ -607,6 +613,8 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec let packagedRuntime: String? let minimumVersion: String? let versionArguments: [String]? + /// `tool` launches: values for `${runtimeArguments}`. + let runtimeArguments: [String]? /// `backend` launches: the function to call and its timeout. let function: String? let timeoutMilliseconds: Int? @@ -620,6 +628,18 @@ struct RustDeclarativePluginOperations: DeclarativePluginManifestValidating, Dec } } + /// A launch that names a tool definition, which `executable` leaves out. + var toolLaunch: DeclarativeLanguageServerLaunchPlan.ToolLaunch? { + guard kind == "tool", let tool, let entry else { return nil } + return .init( + tool: tool, + entry: entry, + runtimeArguments: runtimeArguments ?? [], + minimumVersion: minimumVersion, + packagedRuntime: packagedRuntime + ) + } + var versionRequirement: LanguageServerExecutableVersionRequirement? { guard let tool, let minimumVersion, let versionArguments else { return nil } return LanguageServerExecutableVersionRequirement( diff --git a/macos/Sources/Lithe/Core/Rust/RustJavaMavenOperations.swift b/macos/Sources/Lithe/Core/Rust/RustJavaMavenOperations.swift deleted file mode 100644 index 691d4d7991..0000000000 --- a/macos/Sources/Lithe/Core/Rust/RustJavaMavenOperations.swift +++ /dev/null @@ -1,379 +0,0 @@ -import Foundation - -protocol JavaMavenOperations: RunServerPortParsing, Sendable { - /// Selects an existing configuration for a provider-supplied entry identity. - func selectContextConfiguration(_ request: RunContextSelectionRequest) -> String? - /// Core's shared projection of JDT answers and test outcomes into editor - /// Run markers; `nil` when Core rejected the input. - func javaRunMarkers( - mainMethods: [JavaMainMethod], - testItems: [JavaTestItem], - testCases: [BuildTestResults.TestCase] - ) -> [JavaRunMarker]? - func javaWorkspacePolicy( - at rootURL: URL, - files: [URL], - changedFiles: [URL] - ) -> JavaWorkspacePolicyResult? - func codeVision( - at rootURL: URL, - targetPath: String, - paths: [String] - ) -> [JavaCodeVisionValue] - func className(source: String, simpleName: String) -> String? - func sourceDefinition( - source: String, - declarationName: String, - memberName: String? - ) -> (line: Int, utf16Column: Int)? - func serverPort(content: String, fileExtension: String) -> Int? - func structure( - source: String, - declarationSources: [String] - ) -> JavaStructureResult? - func springIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String], - refreshDependencyMetadata: Bool - ) -> SpringIndexResult? - func mybatisIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] - ) -> MybatisIndexResult? -} - -extension JavaMavenOperations { - func selectContextConfiguration(_: RunContextSelectionRequest) -> String? { nil } - - func javaRunMarkers( - mainMethods _: [JavaMainMethod], - testItems _: [JavaTestItem], - testCases _: [BuildTestResults.TestCase] - ) -> [JavaRunMarker]? { nil } - - func javaWorkspacePolicy( - at _: URL, - files _: [URL], - changedFiles _: [URL] = [] - ) -> JavaWorkspacePolicyResult? { nil } - - func springIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] = [:], - refreshDependencyMetadata: Bool = false - ) -> SpringIndexResult? { nil } - - func mybatisIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] = [:] - ) -> MybatisIndexResult? { nil } -} - -struct RunContextSelectionRequest: Encodable, Sendable { - struct Candidate: Encodable, Sendable { - let id: String - let sourcePath: String? - let symbol: String? - let generated: Bool - let disabled: Bool - } - - let sourcePath: String - let symbol: String - let preferredId: String? - let caseInsensitivePaths: Bool - let candidates: [Candidate] -} - -enum JavaWorkspaceChangeKind: String, Sendable { - case ignored - case source - case buildConfiguration - case other -} - -struct JavaWorkspacePolicyResult: Sendable { - struct Change: Sendable { - let url: URL - let kind: JavaWorkspaceChangeKind - } - - let shouldStart: Bool - let representativeJavaURL: URL? - let changes: [Change] -} - -struct JavaStructureResult: Sendable { - let foldRegions: [JavaFoldRegion] - let syntaxHighlights: [JavaSyntaxHighlight] -} - -struct JavaSyntaxHighlight: Sendable, Equatable { - let range: NSRange - let role: String -} - -struct JavaCodeVisionValue: Sendable { - let line: Int - let utf16Column: Int - let symbol: String - let usageCount: Int -} - -struct RustJavaMavenOperations: JavaMavenOperations, Sendable { - let core: RustCoreBridge - let metadataRepositoryURLs: [URL] - - init( - core: RustCoreBridge, - metadataRepositoryURL: URL? = nil, - metadataRepositoryURLs: [URL] = [] - ) { - self.core = core - self.metadataRepositoryURLs = ([metadataRepositoryURL].compactMap { $0 } - + metadataRepositoryURLs) - .reduce(into: [URL]()) { values, url in - let standardized = url.standardizedFileURL - if !values.contains(standardized) { values.append(standardized) } - } - } - - func selectContextConfiguration(_ request: RunContextSelectionRequest) -> String? { - struct Response: Decodable { let configurationId: String? } - let response: Response? = try? core.executeResult( - command: "runConfig.selectContextConfiguration", payload: request - ).get() - return response?.configurationId - } - - func javaWorkspacePolicy( - at rootURL: URL, - files: [URL], - changedFiles: [URL] = [] - ) -> JavaWorkspacePolicyResult? { - let root = rootURL.standardizedFileURL - let workspacePaths = files.compactMap { workspaceRelativePath(for: $0, root: root) } - let changedPaths = changedFiles.compactMap { workspaceRelativePath(for: $0, root: root) } - guard let payload = core.javaWorkspacePolicy( - workspacePaths: workspacePaths, - changedPaths: changedPaths - ) else { return nil } - return JavaWorkspacePolicyResult( - shouldStart: payload.shouldStart, - representativeJavaURL: payload.representativeJavaPath.map { - root.appendingPathComponent($0).standardizedFileURL - }, - changes: payload.changes.compactMap { change in - guard let kind = JavaWorkspaceChangeKind(rawValue: change.kind) else { return nil } - return JavaWorkspacePolicyResult.Change( - url: root.appendingPathComponent(change.path).standardizedFileURL, - kind: kind - ) - } - ) - } - - func javaRunMarkers( - mainMethods: [JavaMainMethod], - testItems: [JavaTestItem], - testCases: [BuildTestResults.TestCase] - ) -> [JavaRunMarker]? { - if mainMethods.isEmpty && testItems.isEmpty { return [] } - return try? core.javaRunMarkers( - mainMethods: mainMethods, - testItems: testItems, - testCases: testCases - ).get().markers - } - - func codeVision( - at rootURL: URL, - targetPath: String, - paths: [String] - ) -> [JavaCodeVisionValue] { - core.javaCodeVision(at: rootURL, targetPath: targetPath, paths: paths)?.hints.map { - JavaCodeVisionValue( - line: $0.line, - utf16Column: $0.utf16Column, - symbol: $0.symbol, - usageCount: $0.usageCount - ) - } ?? [] - } - - func className(source: String, simpleName: String) -> String? { - core.javaClassName(source: source, simpleName: simpleName)?.className - } - - func sourceDefinition( - source: String, - declarationName: String, - memberName: String? - ) -> (line: Int, utf16Column: Int)? { - guard let value = core.javaSourceDefinition( - source: source, - declarationName: declarationName, - memberName: memberName - ) else { return nil } - return (value.line, value.utf16Column) - } - - func serverPort(content: String, fileExtension: String) -> Int? { - core.javaServerPort(content: content, fileExtension: fileExtension)?.port - } - - private func workspaceRelativePath(for url: URL, root: URL) -> String? { - let path = url.standardizedFileURL.path - let rootPath = root.standardizedFileURL.path - let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/" - guard path.hasPrefix(prefix) else { return nil } - return String(path.dropFirst(prefix.count)) - } - - func structure( - source: String, - declarationSources: [String] - ) -> JavaStructureResult? { - guard let payload = core.javaStructure( - source: source, - declarationSources: declarationSources - ) else { return nil } - return JavaStructureResult( - foldRegions: payload.makeFoldRegions(), - syntaxHighlights: payload.makeSyntaxHighlights() - ) - } - - func springIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] = [:], - refreshDependencyMetadata: Bool = false - ) -> SpringIndexResult? { - let root = rootURL.standardizedFileURL - let paths = files.compactMap { workspaceRelativePath(for: $0, root: root) } - guard let payload = core.springIndex( - at: root, - paths: paths, - metadataRepositoryURLs: metadataRepositoryURLs, - refreshDependencyMetadata: refreshDependencyMetadata, - textOverrides: Dictionary(uniqueKeysWithValues: textOverrides.compactMap { url, text in - workspaceRelativePath(for: url, root: root).map { ($0, text) } - }) - ) else { return nil } - func url(_ path: String?) -> URL? { - path.map { root.appendingPathComponent($0).standardizedFileURL } - } - return SpringIndexResult( - properties: payload.properties.map { value in - SpringProperty( - name: value.name, - typeName: value.typeName, - documentation: value.description, - defaultValue: value.defaultValue, - sourceURL: url(value.sourcePath), - sourceLine: value.sourceLine, - sourceColumn: value.sourceColumn - ) - }, - values: payload.values.map { value in - SpringConfigurationValue( - key: value.key, - value: value.value, - url: url(value.path)!, - line: value.line, - column: value.column, - profile: value.profile, - overridesBaseValue: value.overridesBaseValue, - targetURL: url(value.targetPath), - targetLine: value.targetLine, - targetColumn: value.targetColumn - ) - }, - propertyReferences: payload.propertyReferences.map { value in - SpringPropertyReference( - key: value.key, - url: url(value.path)!, - line: value.line, - column: value.column - ) - }, - diagnostics: payload.diagnostics.map { value in - SpringDiagnostic( - url: url(value.path)!, line: value.line, column: value.column, - severity: value.severity, message: value.message - ) - }, - beans: payload.beans.map { value in - SpringBean( - id: value.id, name: value.name, typeName: value.typeName, - url: url(value.path)!, line: value.line, column: value.column, kind: value.kind - ) - }, - injections: payload.injections.map { value in - SpringInjection( - url: url(value.path)!, line: value.line, column: value.column, - typeName: value.typeName, qualifier: value.qualifier, beanIDs: value.beanIds - ) - }, - endpoints: payload.endpoints.map { value in - SpringEndpoint( - id: value.id, httpMethods: value.httpMethods, route: value.route, - controller: value.controller, method: value.method, - url: url(value.path)!, line: value.line, column: value.column - ) - } - ) - } - - func mybatisIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] = [:] - ) -> MybatisIndexResult? { - let root = rootURL.standardizedFileURL - let paths = files.compactMap { url -> String? in - guard MybatisIndexPaths.matches(url) else { return nil } - return workspaceRelativePath(for: url, root: root) - } - guard let payload = core.mybatisIndex( - at: root, - paths: paths, - textOverrides: Dictionary(uniqueKeysWithValues: textOverrides.compactMap { url, text in - workspaceRelativePath(for: url, root: root).map { ($0, text) } - }) - ) else { return nil } - func url(_ path: String) -> URL { - root.appendingPathComponent(path).standardizedFileURL - } - return MybatisIndexResult( - statements: payload.statements.map { value in - MybatisStatement( - id: value.id, - namespace: value.namespace, - statementID: value.statementId, - kind: value.kind, - javaURL: url(value.javaPath), - javaLine: value.javaLine, - javaColumn: value.javaColumn, - javaEndLine: value.javaEndLine, - javaEndColumn: value.javaEndColumn, - xmlURL: url(value.xmlPath), - xmlLine: value.xmlLine, - xmlColumn: value.xmlColumn, - xmlEndColumn: value.xmlEndColumn - ) - } - ) - } -} - -private extension MavenOperationError { - init(_ error: RustCoreBridge.CoreCallError) { - self.init(code: error.code, message: error.message, details: error.details) - } -} diff --git a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift index 8103c163ce..37c658725d 100644 --- a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift +++ b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift @@ -25,64 +25,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result { - startLanguageServer( - providerID: providerID, - executableURL: executableURL, - arguments: arguments, - environment: environment, - rootURL: rootURL, - workingDirectoryURL: workingDirectoryURL, - initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: nil, - initializeTimeout: initializeTimeout, - requestTimeout: requestTimeout, - shutdownTimeout: shutdownTimeout - ) - } - - func startLanguageServer( - providerID: String, executableURL: URL, arguments: [String], environment: [String: String], - rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, jdtlsLaunchResources: JDTLSLaunchResources?, cacheDirectoryURL: URL?, - workspaceFingerprint: String?, mavenContext: MavenLaunchContext?, - initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval - ) -> Result { - startLanguageServer( - providerID: providerID, executableURL: executableURL, arguments: arguments, environment: environment, - rootURL: rootURL, workingDirectoryURL: workingDirectoryURL, initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, javaGradle: nil, initializeTimeout: initializeTimeout, - requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout - ) - } - - func startLanguageServer( - providerID: String, - executableURL: URL, - arguments: [String], - environment: [String: String], - rootURL: URL, - workingDirectoryURL: URL, - initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -95,12 +37,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { rootURL: rootURL, workingDirectoryURL: workingDirectoryURL, initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, - javaGradle: javaGradle, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -117,22 +53,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { lspStopServer(sessionID: sessionID) } - func retryMavenProfiles(sessionID: String) -> Result { - lspRetryMavenProfiles(sessionID: sessionID).map { _ in () }.mapError(Self.runtimeFailure) - } - - func updateMavenConfiguration( - sessionID: String, - context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result { - lspUpdateMavenConfiguration( - sessionID: sessionID, - context: context, - reloadProjects: reloadProjects - ).mapError(Self.runtimeFailure) - } - func syncLanguageServerDocument( sessionID: String, fileURL: URL, @@ -199,44 +119,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { .mapError(Self.runtimeFailure) } - func prepareJavaLaunch( - sessionID: String, - fileURL: URL, - mainClass: String? - ) -> Result { - lspPrepareJavaLaunch(sessionID: sessionID, fileURL: fileURL, mainClass: mainClass) - .map { LanguageServerRuntimeOperation(operationID: $0.operationId) } - .mapError(Self.runtimeFailure) - } - - func requestJavaNavigationMarkers( - sessionID: String, - fileURL: URL, - documentVersion: Int - ) -> Result { - lspJavaNavigationMarkers( - sessionID: sessionID, - fileURL: fileURL, - documentVersion: documentVersion - ).map { LanguageServerRuntimeOperation(operationID: $0.operationId) } - .mapError(Self.runtimeFailure) - } - - func resolveJavaNavigation( - sessionID: String, - fileURL: URL, - marker: JavaNavigationMarker, - documentVersion: Int - ) -> Result { - lspResolveJavaNavigation( - sessionID: sessionID, - fileURL: fileURL, - marker: marker, - documentVersion: documentVersion - ).map { LanguageServerRuntimeOperation(operationID: $0.operationId) } - .mapError(Self.runtimeFailure) - } - func requestBuildProvider( sessionID: String, method: String, @@ -280,8 +162,7 @@ extension RustCoreBridge: LanguageServerRuntimeCore { startPluginLanguageServer( pluginID: pluginID, providerID: providerID, executableURL: executableURL, arguments: arguments, environment: environment, rootURL: rootURL, initializationOptions: initializationOptions, - workspaceConfiguration: nil, hostServices: [], hostIntegrationLaunch: nil, - cacheDirectoryURL: nil, workspaceFingerprint: nil, mavenContext: nil, javaGradle: nil, + workspaceConfiguration: nil, hostServices: [], initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout ) @@ -297,11 +178,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { initializationOptions: ToolingJSONValue?, workspaceConfiguration: ToolingJSONValue?, hostServices: [String], - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -318,12 +194,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { workspaceConfiguration: workspaceConfiguration, hostServices: hostServices, editorOptions: .macOS, - runtimeExecutableURL: hostIntegrationLaunch?.runtimeExecutableURL, - jdtlsLaunchResources: hostIntegrationLaunch?.coreLaunch?.jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, - javaGradle: javaGradle, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -343,8 +213,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { workspaceConfiguration: ToolingJSONValue?, sessionPolicy: ToolingJSONValue, hostServices: [String], - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -361,8 +229,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { workspaceConfiguration: workspaceConfiguration, hostServices: hostServices, sessionPolicy: sessionPolicy, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -587,7 +453,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { message: $0.message, underlyingMessage: $0.underlyingMessage, processExitCode: $0.processExitCode, - javaBuildReport: $0.javaBuildReport, pluginErrorCode: $0.pluginErrorCode, details: $0.details ) @@ -599,10 +464,6 @@ extension RustCoreBridge: LanguageServerRuntimeCore { level: event.level, message: event.message, detail: event.detail, - mavenProfileTask: event.mavenProfileTask, - mavenProfileProject: event.mavenProfileProject.map { - MavenProfileProjectResult(projectURI: $0.projectUri, status: $0.status, errorDetails: $0.errorDetails) - }, method: event.method, coreLog: event.event.flatMap { id in guard let level = event.catalogLevel, let channel = event.channel, let fields = event.fields else { return nil } diff --git a/macos/Sources/Lithe/Core/Rust/RustWorkspaceOperations.swift b/macos/Sources/Lithe/Core/Rust/RustWorkspaceOperations.swift index eac534a642..0a19f5ee69 100644 --- a/macos/Sources/Lithe/Core/Rust/RustWorkspaceOperations.swift +++ b/macos/Sources/Lithe/Core/Rust/RustWorkspaceOperations.swift @@ -90,11 +90,9 @@ struct RustWorkspaceOperations: WorkspaceOperations, Sendable { guard let entries = listDirectories([rootURL], at: rootURL, visibilityRules: visibilityRules)?[rootURL.standardizedFileURL.path] else { return nil } - let insideSourceRoot = LitheIcons.isSourceRootDirectory(rootURL) return entries.map { entry in FileNode(url: entry.url, isDirectory: entry.isDirectory, - children: entry.isEmptyDirectory ? [] : nil, - isInsideSourceRoot: entry.isDirectory && insideSourceRoot) + children: entry.isEmptyDirectory ? [] : nil) } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+BuildProviderDebugging.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+BuildProviderDebugging.swift index 3c47e9a368..7bfada27b0 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+BuildProviderDebugging.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+BuildProviderDebugging.swift @@ -24,21 +24,17 @@ extension AppModel { let debug = genericDebugFeatureIfActive else { throw CancellationError() } runWorkflowCoordinator.reapplySelectedConfiguration(run) if configuration.buildProvider != nil { - try await prepareBuildLanguageImport() + try await awaitBuildSystemDetection() guard let builds = buildSystemsFeatureIfActive else { throw CancellationError() } try await builds.prepareRunGenerationModels(workspace: identity.url) guard isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - } else { - try await prepareCurrentProviderGeneration(configuration: configuration, identity: identity) } - var languageImportIsCurrent: @MainActor @Sendable () -> Bool = { true } var connection: PreparedProviderConnectionDebug? let revision = buildSystemsFeatureIfActive?.inputRevision let current: @MainActor @Sendable () -> Bool = { [weak self, weak run] in guard let self, let run else { return false } return self.isCurrentWorkspace(identity) && !Task.isCancelled && run.selectedConfiguration == configuration && self.buildSystemsFeatureIfActive?.inputRevision == revision - && languageImportIsCurrent() && (connection?.isCurrent() ?? true) } guard current() else { throw CancellationError() } @@ -48,15 +44,6 @@ extension AppModel { configurationType: configurationType, adapterID: configuration.debugAdapter, port: port) connection = prepared return prepared.options - }, languageImport: { [weak self] imported in - guard let self, current(), case .maven(let context) = imported else { throw CancellationError() } - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - guard current() else { throw CancellationError() } - let defaults = try self.javaLanguageImportConfiguration(rootURL: identity.url) - try await sessions.applyJavaRunImport(rootURL: identity.url, - languageImport: .init(mavenContext: context, javaGradle: defaults.javaGradle)) - let revision = sessions.javaImportRevision - languageImportIsCurrent = { sessions.javaImportRevision == revision } }, isCurrent: current) operation = launched showToolWindow(.run) diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+BuildSystems.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+BuildSystems.swift index f7fb69f272..14b5c8a290 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+BuildSystems.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+BuildSystems.swift @@ -14,17 +14,12 @@ extension AppModel { func loadBuildSystems(_ access: ExecutionFeatureAccess) { guard let feature = access.buildSystems, let identity = currentWorkspaceIdentity else { return } - feature.onLanguageImportChanged = { [weak self, weak feature] root in - guard let self, let feature, self.isCurrentWorkspace(identity), - root == identity.url, self.buildSystemsFeatureIfActive === feature else { return } - self.synchronizeBuildLanguageImport(at: root) - } if feature.workspaceURL != identity.url { feature.reset(workspaceURL: identity.url) } } - /// Every Java workflow waits here before it can reach the synchronous - /// language-session API. Workspace identity includes reopen generations. - func prepareBuildLanguageImport() async throws { + /// Run, test and debug workflows wait here so they never start with + /// option values from before a save. Workspace identity includes reopen generations. + func awaitBuildSystemDetection() async throws { guard let identity = currentWorkspaceIdentity else { throw CancellationError() } guard hasAvailableBuildSystemPlugins else { return } guard let access = await activateExecutionModule(), isCurrentWorkspace(identity) else { @@ -32,7 +27,7 @@ extension AppModel { } loadBuildSystems(access) if let feature = access.buildSystems { - _ = try await feature.prepareLanguageImport(workspaceURL: identity.url) + try await feature.awaitDetection(workspaceURL: identity.url) } try Task.checkCancellation() guard isCurrentWorkspace(identity) else { throw CancellationError() } @@ -47,49 +42,6 @@ extension AppModel { } } - var isBuildLanguageImportPending: Bool { - hasAvailableBuildSystemPlugins && ( - buildSystemsFeatureIfActive?.workspaceURL != workspaceURL?.standardizedFileURL - || buildSystemsFeatureIfActive?.languageImport == nil - ) - } - - func javaLanguageImportConfiguration(rootURL: URL) throws -> JavaLanguageImportConfiguration { - guard workspaceURL?.standardizedFileURL == rootURL.standardizedFileURL else { throw CancellationError() } - if hasAvailableBuildSystemPlugins { - guard let feature = buildSystemsFeatureIfActive, - feature.workspaceURL == rootURL.standardizedFileURL, - let configuration = feature.languageImport else { - throw RunConfigurationOperationFailure(message: L10n.string("Build-system language import is still preparing. Retry when project loading completes.")) - } - return configuration - } - // No enabled build plugin means no Lithe build override. In particular, - // retiring a plugin must not revive the old Maven service's settings. - return JavaLanguageImportConfiguration() - } - - private func synchronizeBuildLanguageImport(at rootURL: URL) { - guard let identity = currentWorkspaceIdentity, identity.url == rootURL.standardizedFileURL, - !languageToolingFeature.isDisabled("java"), - let sessions = languageToolingSessionsIfActive else { return } - javaLanguageServerPreparationCoordinator.synchronizeMavenConfiguration( - sessions: sessions, - workspaceURL: identity.url, - languageImportPreparation: { [weak self] in - guard let self, self.isCurrentWorkspace(identity) else { throw CancellationError() } - try await self.prepareBuildLanguageImport() - guard self.isCurrentWorkspace(identity) else { throw CancellationError() } - }, - ownsWorkspace: { [weak self, weak sessions] in - guard let self else { return false } - return self.isCurrentWorkspace(identity) - && !self.languageToolingFeature.isDisabled("java") - && self.languageToolingSessionsIfActive === sessions - } - ) - } - func handleBuildSystemFileChanges(_ changes: [WorkspaceFileChange]) { buildSystemsFeatureIfActive?.workspaceFilesChanged(changes.map(\.fileURL)) } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift index 99fcf493e4..08f2cce7ac 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+CodeNavigation.swift @@ -7,29 +7,12 @@ import LitheModuleAPI /// history and the shared editor jump live in `AppModel+NavigationHistory`. /// /// Navigation requests are identified by an operation ID so a superseded -/// request cannot publish its results over a newer one, and the caret-based -/// entry points refuse to run while the Java language server is still -/// preparing rather than reporting a spurious "not found". +/// request cannot publish its results over a newer one. @MainActor extension AppModel { func goToDefinition() { if let document = focusedEditorDocument, let caret = editorCaret, caret.url.standardizedFileURL == document.url.standardizedFileURL { - let productLocations = productNavigationLocations( - for: document.url, - line: caret.line, - utf16Column: caret.utf16Column - ) - if !productLocations.isEmpty { - presentGenericNavigationValues( - productLocations, - kind: .definitions, - navigateToSingleResult: true, - providerID: nil - ) - return - } - if languageServerIsPreparing(for: document.url) { return } // The command asks the same plugin providers a modifier click does. if let pluginDefinitions = pluginDefinitionQuery( for: document, line: caret.line, utf16Column: caret.utf16Column @@ -86,9 +69,6 @@ extension AppModel { guard documentFeature.editorDocuments.contains(where: { $0 === document }) else { completion(.success(false)); return } - if !productNavigationLocations(for: document.url, line: line, utf16Column: utf16Column).isEmpty { - completion(.success(true)); return - } let complete = askPlugins ? pluginSupplementedAvailability( ticket: hover, for: document, line: line, utf16Column: utf16Column, completion: completion) @@ -114,20 +94,6 @@ extension AppModel { line: max(0, line), utf16Column: max(0, utf16Column) ) - let productLocations = productNavigationLocations( - for: normalizedURL, - line: line, - utf16Column: utf16Column - ) - if !productLocations.isEmpty { - presentGenericNavigationValues( - productLocations, - kind: .definitions, - navigateToSingleResult: true, - providerID: nil - ) - return - } let document = openDocuments.first { $0.url.standardizedFileURL == normalizedURL } // Plugin providers add to the language server's answer, so both run together. let pluginDefinitions = askPlugins ? document.flatMap { @@ -166,68 +132,6 @@ extension AppModel { ) } - func findJavaImplementations(line: Int, utf16Column: Int, in fileURL: URL) { - editorCaret = EditorCaret( - url: fileURL.standardizedFileURL, - line: line, - utf16Column: utf16Column - ) - guard languageServerFeatureIsReady( - .implementation, - unsupportedMessage: "Implementation navigation is not supported by this language server" - ) else { return } - performGenericNavigation( - method: "textDocument/implementation", - kind: .implementations, - navigateToSingleResult: false - ) - } - - func resolveJavaNavigation(_ marker: JavaImplementationMarker, in fileURL: URL) { - guard !languageNavigationCoordinator.state.isLoading, - let sessions = languageToolingSessionsIfActive, - let provider = languageProviderCatalog.provider(for: fileURL) else { return } - guard !isJavaLanguageServerPreparing(for: fileURL) else { - showJavaLanguageServerPreparingNotification() - return - } - let kind: LanguageNavigationResultKind = marker.direction == .down - ? .implementations - : .definitions - let operationID = languageNavigationCoordinator.begin( - providerID: provider.id, - kind: kind - ) - do { - try sessions.resolveJavaNavigation( - fileURL: fileURL, - marker: marker.sharedMarker - ) { [weak self] result in - guard let self, - self.languageNavigationCoordinator.owns(operationID) else { return } - switch result { - case .success(let locations): - self.presentGenericNavigationValues( - locations, - kind: kind, - navigateToSingleResult: true, - providerID: provider.id - ) - case .failure(let error): - self.languageNavigationCoordinator.fail( - operationID, - message: error.localizedDescription - ) - } - } - } catch { - languageNavigationCoordinator.fail( - operationID, - message: error.localizedDescription - ) - } - } - func navigate(to location: LanguageNavigationLocation) { isImplementationChooserVisible = false navigate( @@ -262,7 +166,7 @@ extension AppModel { _ feature: LanguageServerFeatureSet, unsupportedMessage: String ) -> Bool { - guard let document = focusedEditorDocument, !languageServerIsPreparing(for: document.url) else { return false } + guard focusedEditorDocument != nil else { return false } guard supportsLanguageServerFeature(feature) else { showNotification(unsupportedMessage, logReference: notificationRejection(operation: "navigation", reason: "unsupported")) return false @@ -270,14 +174,6 @@ extension AppModel { return true } - /// Whether the language server for the file is still preparing. Tells the - /// user so, rather than letting navigation report a spurious "not found". - private func languageServerIsPreparing(for fileURL: URL) -> Bool { - guard isJavaLanguageServerPreparing(for: fileURL) else { return false } - showJavaLanguageServerPreparingNotification() - return true - } - private func performGenericNavigation( method: String, kind: LanguageNavigationResultKind, @@ -430,22 +326,6 @@ extension AppModel { } } - /// Resolves mapper XML and Spring configuration jumps before LSP so a - /// Mapper method does not stop on its own Java declaration. - private func productNavigationLocations( - for url: URL, - line: Int, - utf16Column: Int - ) -> [LanguageServerLocation] { - let mybatisLocations = mybatisFeature.navigationLocations( - for: url, - line: line, - utf16Column: utf16Column - ) - if !mybatisLocations.isEmpty { return mybatisLocations } - return springFeature.navigationLocations(for: url, line: line) - } - func presentGenericNavigationValues( _ values: [LanguageServerLocation], kind: LanguageNavigationResultKind, diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+Debugging.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+Debugging.swift index c86d5cb20a..0ee39d3d09 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+Debugging.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+Debugging.swift @@ -13,22 +13,6 @@ import LitheModuleAPI /// from the run inventory. @MainActor extension AppModel { - func applyDebugServiceUpdate() { - guard let feature = genericDebugFeatureIfActive, let identity = currentWorkspaceIdentity, - let updateSessionID = feature.activeSessionID else { return } - Task { [weak self] in - guard let self else { return } - await feature.applyJavaServiceUpdate { target, source, root in - guard self.isCurrentWorkspace(identity), await self.saveAllDocuments(), - self.isCurrentWorkspace(identity) else { throw CancellationError() } - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - guard self.isCurrentWorkspace(identity), feature.activeSessionID == updateSessionID, - feature.isSessionActive else { throw CancellationError() } - try await sessions.buildJavaServiceUpdate(target: target, fileURL: source, rootURL: root) - } - } - } - /// The plugin of the active session declared how to apply changed code, so the host saves /// the open documents and asks the adapter to apply them. func applyDeclaredDebugCodeChanges() { @@ -42,27 +26,6 @@ extension AppModel { } } - func restartUpdatedDebugService() { - guard let feature = genericDebugFeatureIfActive, let identity = currentWorkspaceIdentity, - let sessionID = feature.activeSessionID else { return } - Task { [weak self] in - guard let self else { return } - await feature.restartJavaService { source, root in - guard self.isCurrentWorkspace(identity), await self.saveAllDocuments(), - self.isCurrentWorkspace(identity), feature.activeSessionID == sessionID else { - throw CancellationError() - } - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - let preparation = try await sessions.prepareJavaRunLaunchTarget(fileURL: source, rootURL: root) - switch preparation { - case .ready(let target): return target - case .buildFailed(_, let failure): - throw RunConfigurationOperationFailure(message: failure.message) - } - } - } - } - func toggleDebug() { guard toggleToolWindow(.debug) else { return } Task { [weak self] in @@ -83,19 +46,10 @@ extension AppModel { } func startDebugging() { - if let target = activeTestTarget { - debugTest(providerID: target.providerID, - scope: target.scope) - return - } runWorkflowCoordinator.startModuleOperation { [weak self] in await self?.startDebuggingAfterActivation() } } func startOrRestartDebugging() { - if let target = activeTestTarget, target.name != genericDebugFeatureIfActive?.targetTitle { - startDebugging() - return - } guard let feature = genericDebugFeatureIfActive, feature.isSessionActive else { startDebugging() @@ -107,12 +61,6 @@ extension AppModel { } } - func attachJavaDebugger(host: String, port: Int) { - Task { [weak self] in - await self?.attachJavaDebuggerAfterActivation(host: host, port: port) - } - } - /// Returns the reason initialization failed, or nil once it has completed /// (or the request was cancelled). The caller keeps its form open on /// a message, so the user's host, port and arguments are not lost. @@ -133,44 +81,6 @@ extension AppModel { ) } - private func attachJavaDebuggerAfterActivation(host: String, port: Int) async { - guard let workspaceURL, - await activateDebugModule() != nil else { return } - let sourceURL = ([activeDocument?.url].compactMap { $0 } + projectFiles) - .map(\.standardizedFileURL) - .first { - languageProviderCatalog.provider(for: $0)?.id == "java" - } - guard let sourceURL else { - showNotification("Open a Java project before connecting the debugger", logReference: notificationRejection(operation: "debugging", reason: "unavailable_0")) - return - } - let configuration: DebugLaunchConfiguration - do { - configuration = try debugLaunchConfigurationResolver.resolveJavaAttach( - host: host, - port: port - ) - } catch { - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "debugging")) - return - } - guard let genericDebugFeature = genericDebugFeatureIfActive, - genericDebugFeature.start( - fileURL: sourceURL, - rootURL: workspaceURL, - configuration: configuration - ) else { - showNotification( - genericDebugFeatureIfActive?.errorMessage ?? "Could not connect to the JVM", - logReference: notificationRejection(operation: "debug_attach", reason: "attach_failed") - ) - showToolWindow(.debug) - return - } - showDebugToolWindow() - } - func startDebuggingAfterActivation(configuration requestedConfiguration: RunConfiguration? = nil) async { guard let identity = currentWorkspaceIdentity else { return } guard let execution = await activateExecutionModule(), @@ -207,6 +117,22 @@ extension AppModel { } return } + // A package that exposes debugging only as editor actions, or whose + // adapter never launches a file, leaves the host nothing to start: the + // toolbar calls its debug action. + if let document = activeDocument, + let support = runWorkflowCoordinator.languageSupportRoutingToEditorActions( + .debug, for: selectedConfiguration, currentFileURL: document.url, + hostLaunchesFiles: { [debugLaunchConfigurationResolver] in + debugLaunchConfigurationResolver.launchesFiles(ofLanguage: $0) + } + ) { + guard await runWorkflowCoordinator.saveDirtyCurrentFileIfNeeded( + configuration: selectedConfiguration, document: document, saving: self + ), isCurrentWorkspace(identity), !Task.isCancelled else { return } + await startPluginEditorAction(.debug, document: document, support: support, identity: identity) + return + } if selectedConfiguration.usesProviderConnectionDebug { await startProviderServiceDebug(selectedConfiguration, identity: identity, run: runFeature) return @@ -223,23 +149,10 @@ extension AppModel { else { showNotification("The build provider's debug program or adapter is unavailable. Build it again and check that the plugin is enabled.", logReference: notificationRejection(operation: "debugging", reason: "unavailable_2")) } return } - let activeDocumentIsLaunchable = selectedConfiguration.usesCurrentEditorFile - ? await isLaunchableJavaEntrypoint(activeDocument, in: workspaceURL) - : false guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - let configuration = runWorkflowCoordinator.debugConfiguration( - selected: selectedConfiguration, - activeDocumentIsLaunchable: activeDocumentIsLaunchable, - configurations: runFeature.configurations - ) - runFeature.select(configuration) - if configuration.usesProviderConnectionDebug { - await startProviderServiceDebug(configuration, identity: identity, run: runFeature) - return - } let sourceResolution = runWorkflowCoordinator.resolveDebugSource( - configuration: configuration, + configuration: selectedConfiguration, activeDocument: activeDocument, projectFiles: projectFiles, workspaceURL: workspaceURL @@ -251,9 +164,6 @@ extension AppModel { case .currentFileUnavailable: showNotification("Open a source file or choose a project Run configuration", logReference: notificationRejection(operation: "debugging", reason: "unavailable_3")) return - case .javaSourceUnavailable(let name): - showNotification("Could not find the Java source for %@", arguments: [name], logReference: notificationRejection(operation: "debugging", reason: "unavailable_4")) - return case .unsupported(let name): showNotification("%@ does not support Debug yet", arguments: [name], logReference: notificationRejection(operation: "debugging", reason: "unavailable_5")) return @@ -283,7 +193,6 @@ extension AppModel { } buildSystemsFeatureIfActive?.cancelDebugPreparation() runWorkflowCoordinator.cancelModuleOperation() - cancelJavaTestDebugLaunch() guard let feature = genericDebugFeatureIfActive else { stopDebugTerminalProcesses() return @@ -494,53 +403,22 @@ extension AppModel { guard isCurrentWorkspace(identity), !Task.isCancelled else { return } let selectedConfiguration = runFeature.selectedConfiguration // Debug is the second execution mode for the Run selection. Re-apply - // the selection here so its project-scoped Java runtime override is - // active even when the Run panel was never opened in this session. + // the selection here so its project-scoped overrides are active even + // when the Run panel was never opened in this session. runWorkflowCoordinator.reapplySelectedConfiguration(runFeature) guard await featureGraph.debugLaunchPreparation.saveDirtyDocumentIfNeeded(document) else { return } - var javaUpdateTarget: JavaDebugLaunchTarget? let configuration: DebugLaunchConfiguration let buildInputs: UInt64? - let javaImport: JavaLanguageImportConfiguration? do { - if let selectedConfiguration { try await prepareCurrentProviderGeneration(configuration: selectedConfiguration, identity: identity) } - if let selectedConfiguration, selectedConfiguration.usesJavaProjectPreparation { - javaImport = try await prepareJavaBuildResources(configuration: selectedConfiguration, fileURL: fileURL, identity: identity) - } else { try await prepareBuildLanguageImport(); javaImport = nil } + try await awaitBuildSystemDetection() buildInputs = buildSystemsFeatureIfActive?.inputRevision - configuration = try await featureGraph.debugLaunchPreparation.prepare( + configuration = try featureGraph.debugLaunchPreparation.prepare( provider: provider, fileURL: fileURL, workspaceURL: workspaceURL, - runFeature: runFeature, - resolver: debugLaunchConfigurationResolver, - portChecker: debugPortAvailabilityChecker, - resolveJavaTarget: { [weak self] in - guard let self else { return nil } - try await self.saveJavaWorkspaceForLaunch(identity: identity) - let operation = self.buildSystemsFeatureIfActive?.operation?.id - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - let preparation: JavaLaunchPreparation - if let javaImport { - preparation = try await sessions.prepareJavaRunLaunchTarget(fileURL: fileURL, rootURL: workspaceURL, languageImport: javaImport, mainClass: selectedConfiguration?.mainClass) - } else { - preparation = try await sessions.prepareJavaRunLaunchTarget(fileURL: fileURL, rootURL: workspaceURL, mainClass: selectedConfiguration?.mainClass) - } - let javaRevision = sessions.javaImportRevision - let target = try await self.resolveJavaLaunchPreparation( - preparation, - identity: identity - ) - guard !Task.isCancelled, self.isCurrentWorkspace(identity), self.buildSystemsFeatureIfActive?.operation?.id == operation, - sessions.javaImportRevision == javaRevision else { throw CancellationError() } - let prepared = JavaDebugLaunchTarget(mainClass: target.mainClass, projectName: target.projectName, - modulePaths: target.modulePaths, classPaths: target.classPaths, - buildPrepared: selectedConfiguration?.usesJavaProjectPreparation == true) - javaUpdateTarget = prepared - return prepared - } + resolver: debugLaunchConfigurationResolver ) // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 } catch is CancellationError { @@ -566,7 +444,6 @@ extension AppModel { ) else { return } - if let javaUpdateTarget { genericDebugFeature.registerJavaUpdateTarget(javaUpdateTarget) } showDebugToolWindow() } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+EditorIntelligence.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+EditorIntelligence.swift index 2542994b81..9dfe6a9c93 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+EditorIntelligence.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+EditorIntelligence.swift @@ -37,45 +37,6 @@ extension AppModel { editorDiagnosticsStore.replace( EditorDiagnostic.fromLanguageServerDiagnostics(languageDiagnostics) ) - announceMavenResolutionProblemsIfChanged() - } - - /// Maven problems JDT LS currently reports for the open workspace. - var mavenResolutionProblems: [EditorDiagnostic] { - MavenResolutionProblems.problems( - workspaceURL: workspaceURL, - diagnosticsByURL: editorDiagnosticsStore.diagnosticsByURL - ) - } - - /// Notifies once per distinct Maven problem set, even when the Maven tool - /// window is closed. A failed import otherwise looks like a successful one. - private func announceMavenResolutionProblemsIfChanged() { - let problems = mavenResolutionProblems - let signature = MavenResolutionProblems.signature(problems) - // An empty set keeps the last signature: the same failure reappearing - // after a rebuild is visible in the Maven tool window already. - guard !signature.isEmpty, signature != announcedMavenResolutionProblems, - let first = problems.first else { return } - announcedMavenResolutionProblems = signature - showNotification(String( - format: L10n.string("Maven could not resolve this project (%lld problems): %@"), - problems.count, - first.message - ), logReference: notificationRejection(operation: "project_import", reason: "resolution_failed")) - } - - func refreshCodeVision(for fileURL: URL) async { - let normalizedURL = fileURL.standardizedFileURL - guard normalizedURL.pathExtension.lowercased() == "java", - let document = openDocuments.first(where: { $0.url.standardizedFileURL == normalizedURL }), - !document.isReadOnly, - let workspaceRoot = workspaceURL else { return } - await javaFeature.refreshCodeVision( - for: document, - projectFiles: projectFiles, - workspaceRoot: workspaceRoot - ) } func canShowBlame(for fileURL: URL) -> Bool { @@ -92,13 +53,4 @@ extension AppModel { func hideBlame() { blameVisibleURL = nil } - - func findUsages(for hint: JavaCodeVisionHint, in fileURL: URL) { - editorCaret = EditorCaret( - url: fileURL.standardizedFileURL, - line: hint.line, - utf16Column: hint.utf16Column - ) - findReferences() - } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+ExecutionModules.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+ExecutionModules.swift index 2be0e23fce..492c6d173a 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+ExecutionModules.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+ExecutionModules.swift @@ -53,19 +53,6 @@ extension AppModel { return access } - func registerJavaDependencySourceIfAvailable() { - guard workspaceURL != nil, - !languageToolingFeature.isDisabled("java"), - languageToolingSessionsIfActive?.activeLanguageServerIDs.contains("java") == true, - let provider = services.moduleRuntime.capability(.languageIntelligence) - as? any LanguageDependencyProviding else { return } - runFeatureIfActive?.registerDependencySource(languageID: "java", displayName: "Java") - provider.setDependencySnapshotChangeHandler { [weak self] in - self?.runFeatureIfActive?.syncLanguageDependencyPaths(languageID: "java") - } - runFeatureIfActive?.syncLanguageDependencyPaths(languageID: "java") - } - func registerLanguageDependencySourceIfAvailable(support: LanguageSupportDeclaration) { guard support.languageServerModuleID != nil, !languageToolingFeature.isDisabled(support.id), @@ -89,45 +76,9 @@ extension AppModel { feature.onStoppedLocation = { [weak self] url, line, column in self?.revealDebugLocation(url: url, line: line, column: column) } - feature.onAutomaticVariableInspectionRequest = { [weak self, weak feature] frame in - guard let self, let feature else { return } - requestAutomaticDebugVariables(for: frame, feature: feature) - } configureDebugRunInTerminalHandler(feature) } - private func requestAutomaticDebugVariables( - for frame: DebugStackFrame, - feature: GenericDebugFeatureModel - ) { - guard feature.providerID == "java", - let sourceURL = frame.sourceURL?.standardizedFileURL, - let source = debugSourceText(at: sourceURL) else { - feature.requestAutomaticVariables([]) - return - } - let expressions = DebugAutomaticExpressionProjection.javaExpressions( - forLine: max(0, frame.line - 1), - in: source as NSString - ) - feature.requestAutomaticVariables(expressions) - } - - private func debugSourceText(at sourceURL: URL) -> String? { - if let document = openDocuments.first(where: { - $0.url.standardizedFileURL == sourceURL - }) { - return document.text - } - guard let metadata = services.fileStorage.metadata(for: sourceURL), - metadata.isRegularFile, - let byteCount = metadata.byteCount, - byteCount <= 2_000_000, - let data = try? services.fileStorage.readData(from: sourceURL, options: []), - let source = String(data: data, encoding: .utf8) else { return nil } - return source - } - private func configureDebugRunInTerminalHandler(_ feature: GenericDebugFeatureModel) { feature.onSessionSelectionChanged = { [weak self] debugSessionID in guard let self else { return } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+FeatureState.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+FeatureState.swift index 19118f1341..e0c57c4833 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+FeatureState.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+FeatureState.swift @@ -7,31 +7,11 @@ import LitheModuleAPI extension AppModel { var workspaceSnapshotID: UUID? { workspaceFeature.appliedSnapshot?.id } - var springEndpoints: [SpringEndpoint] { springFeature.endpoints } - var springBeans: [SpringBean] { springFeature.beans } - var isIndexingSpring: Bool { springFeature.isIndexing } var rootNode: FileNode? { workspaceFeature.rootNode } var projectFiles: [URL] { workspaceFeature.projectFiles } var projectDirectoryMarks: [String: WorkspaceDirectoryMark] { workspaceFeature.indexingStatus.excludedDirectories.keys.reduce(into: workspaceFeature.directoryMarks) { marks, path in marks[path] = .excluded } } - var javaEnvironmentReport: JavaEnvironmentReport? { - runtimeFeature.javaEnvironmentReport - } - - var shouldShowJavaEnvironmentBanner: Bool { - guard javaEnvironmentReport?.status.requiresAttention == true else { return false } - return projectFiles.contains { $0.pathExtension.lowercased() == "java" } - || hasMavenProject - || activeDocument?.url.pathExtension.lowercased() == "java" - } - - /// A Maven project counts as Java for the Java environment banner. Build - /// tool windows come from build-system plugins, not from this check. - var hasMavenProject: Bool { - projectFiles.contains { $0.lastPathComponent.lowercased() == "pom.xml" } - } - var openDocuments: [EditorDocument] { documentFeature.openDocuments } var openMediaDocuments: [MediaDocument] { mediaFeature.openMediaDocuments } var activeMediaDocument: MediaDocument? { mediaFeature.activeMediaDocument } @@ -372,8 +352,7 @@ extension AppModel { case "navigate-forward": canNavigateForward case "go-to-definition": - activeDocument.map { springFeature.handles($0.url) || mybatisFeature.handles($0.url) } == true - || supportsLanguageServerFeature(.definition) + supportsLanguageServerFeature(.definition) case "find-usages": supportsLanguageServerFeature(.references) case "go-to-implementation": @@ -384,36 +363,10 @@ extension AppModel { "replace-in-project", "project-local-history", "run", "debug", "debug-start-or-continue", "stop-run", "stop-debug", "toggle-terminal", "toggle-problems", "toggle-git-log", "toggle-run", "toggle-tests", - "toggle-debug", "view-breakpoints", "spring-endpoints", "rebuild-java-index": + "toggle-debug", "view-breakpoints": workspaceURL != nil default: false } } - - func prepareProjectRuntimeSettings() async { - await runtimeFeature.refreshAvailableRuntimes() - runtimeFeature.prepare( - workspaceName: projectName, - workspaceURL: workspaceURL, - files: projectFiles, - buildSources: buildSystemsFeatureIfActive?.entries.map { entry in - ProjectRuntimeInventory.BuildSource(id: entry.id, root: entry.instance.root, - displayName: entry.instance.displayName, - usesJava: services.pluginCatalog.languageSupports.values.contains { ownership in - let support = ownership.declaration - return support.id == "java" && support.recognizesProject( - fileNames: entry.instance.markers.map { URL(fileURLWithPath: $0).lastPathComponent }) - }, - model: entry.modelState == .loaded && !entry.isReloadRequired ? entry.model : nil) - } ?? [], - languageSupports: services.pluginCatalog.languageSupports.values.map(\.declaration) - .filter { !languageToolingFeature.isDisabled($0.id) } - ) - } - - func persistProjectRuntimeSettings() async { - guard currentWorkspaceIdentity != nil, runtimeFeature.saveSettings() else { return } - runtimeFeature.finishSaving() - } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+GitModule.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+GitModule.swift index aa5580fe6e..fe644f26f0 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+GitModule.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+GitModule.swift @@ -20,7 +20,6 @@ extension AppModel { notify: { [weak self] message in self?.showNotification(message) }, stateRefreshed: { [weak self] in guard let self, let document = self.activeDocument else { return } - await self.refreshCodeVision(for: document.url) await self.loadGitLineChanges(for: document.url) }, saveChangesPolicy: { [weak self] in diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaBuildPreparation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaBuildPreparation.swift deleted file mode 100644 index 0c18eb9ee7..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaBuildPreparation.swift +++ /dev/null @@ -1,82 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheExecutionModule -import LitheModuleAPI - -/// Save/build/JDT ordering for Java Run and Debug; Maven owns resource semantics. -@MainActor -extension AppModel { - func prepareJavaRunLaunch( - for configuration: RunConfiguration, - identity: WorkspaceIdentity - ) async throws -> JavaDebugLaunchTarget? { - guard configuration.usesJavaProjectPreparation else { - try await prepareCurrentProviderGeneration(configuration: configuration, identity: identity) - return nil - } - try await saveJavaWorkspaceForLaunch(identity: identity) - guard let workspaceURL, - let sourceURL = runWorkflowCoordinator.sourceURLForDebug( - configuration: configuration, - activeDocument: activeDocument, - projectFiles: projectFiles, - workspaceURL: workspaceURL - ) else { - throw RunConfigurationOperationFailure( - message: L10n.string("The Java source for \(configuration.name) could not be resolved.") - ) - } - try await prepareCurrentProviderGeneration(configuration: configuration, identity: identity) - let languageImport = try await prepareJavaBuildResources(configuration: configuration, fileURL: sourceURL, identity: identity) - let revision = buildSystemsFeatureIfActive?.inputRevision - let operation = buildSystemsFeatureIfActive?.operation?.id - let sessions = try await languageSessionsForWorkspaceMaintenance(for: identity) - guard isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - let preparation = try await sessions.prepareJavaRunLaunchTarget(fileURL: sourceURL, rootURL: workspaceURL, languageImport: languageImport, mainClass: configuration.mainClass) - let javaRevision = sessions.javaImportRevision - let target = try await resolveJavaLaunchPreparation(preparation, identity: identity) - guard isCurrentWorkspace(identity), !Task.isCancelled, buildSystemsFeatureIfActive?.inputRevision == revision, - buildSystemsFeatureIfActive?.operation?.id == operation, sessions.javaImportRevision == javaRevision else { throw CancellationError() } - return JavaDebugLaunchTarget(mainClass: target.mainClass, projectName: target.projectName, - modulePaths: target.modulePaths, classPaths: target.classPaths, buildPrepared: true) - } - - func prepareCurrentProviderGeneration(configuration: RunConfiguration, identity: WorkspaceIdentity) async throws { - guard configuration.requiresProviderGeneration else { return } - try await prepareBuildLanguageImport() - guard let run = runFeatureIfActive else { throw CancellationError() } - // No enabled build plugin means no Provider model to refresh; validation - // then finds no build-project ownership and lets the launch continue. - if hasAvailableBuildSystemPlugins { - guard let builds = buildSystemsFeatureIfActive else { throw CancellationError() } - try await builds.prepareRunGenerationModels(workspace: identity.url) - guard isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - } - try run.validateProviderGeneration(for: configuration) - } - - /// The provider declares resource preparation; JDT retains launch semantics. - @discardableResult - func prepareJavaBuildResources(configuration: RunConfiguration, fileURL: URL, identity: WorkspaceIdentity) async throws -> JavaLanguageImportConfiguration { - guard configuration.usesJavaProjectPreparation else { return JavaLanguageImportConfiguration() } - guard isCurrentWorkspace(identity), await saveAllDocuments(), isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - try await prepareBuildLanguageImport() - guard let builds = buildSystemsFeatureIfActive, let run = runFeatureIfActive else { throw CancellationError() } - try await prepareCurrentProviderGeneration(configuration: configuration, identity: identity) - let options = run.options(for: configuration) - var overrides: [String: ToolingJSONValue] = [:] - if !options.activeProfiles.isEmpty { overrides["profiles"] = .array(options.activeProfiles.sorted().map(ToolingJSONValue.string)) } - let prepared = try await builds.prepareLanguageRun(fileURL: fileURL, workspace: identity.url, - purpose: "run", optionOverrides: overrides, - isCurrent: { [weak self] in self?.isCurrentWorkspace(identity) == true }) - guard let prepared else { - throw RunConfigurationOperationFailure(message: L10n.string("Load the current build model and enable its provider before running this configuration.")) - } - let current = try javaLanguageImportConfiguration(rootURL: identity.url) - switch prepared { - case .maven(let context): return JavaLanguageImportConfiguration(mavenContext: context, javaGradle: current.javaGradle) - case .gradle(let context): return JavaLanguageImportConfiguration(mavenContext: current.mavenContext, javaGradle: context) - } - } - -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaEntrypoints.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaEntrypoints.swift deleted file mode 100644 index dc6d851246..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaEntrypoints.swift +++ /dev/null @@ -1,195 +0,0 @@ -import Combine -import Foundation -import LitheModuleAPI -import LitheCoreContracts -import LitheExecutionModule -import LitheLanguageIntelligenceModule - -/// Java entry points come from JDT: which classes are launchable is its -/// answer, and the Run list, launch, and Debug all ask it through Core. -/// -/// Note: 入口点归属见 .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md -extension AppModel { - /// Asks JDT which classes can be launched, then regenerates the Run list - /// from its answer. While JDT is still preparing the project the previous - /// entries stay, and the list refreshes once preparation settles. - func generateFromJavaEntrypoints( - _ runFeature: RunFeatureModel, - for identity: WorkspaceIdentity, - automatic: Bool = false - ) async { - do { - try await prepareBuildLanguageImport() - try await buildSystemsFeatureIfActive?.prepareRunGenerationModels(workspace: identity.url) - } catch { - guard isCurrentWorkspace(identity) else { return } - runFeature.reportGenerationProjectNotReady() - return - } - let buildRevision = buildSystemsFeatureIfActive?.inputRevision - let (discovery, sessions) = await discoverJavaEntrypoints(for: identity) - guard isCurrentWorkspace(identity), !Task.isCancelled, - buildSystemsFeatureIfActive?.inputRevision == buildRevision else { return } - await runFeature.generateRunConfigurations(javaDiscovery: discovery, automatic: automatic) - - if discovery == .pending, let sessions { - refreshJavaEntrypointsWhenPrepared(for: identity, sessions: sessions, automatic: automatic) - } - } - - /// Asks JDT which classes can be launched once it has prepared the project. - /// - /// Asking earlier would return a partial list mid-import, so an unprepared - /// workspace reports `.pending` and generation keeps the previous entries. - func discoverJavaEntrypoints( - for identity: WorkspaceIdentity - ) async -> (JavaEntrypointDiscovery, LanguageToolingSessionManager?) { - javaEntrypointRefreshObservation = nil - // A regeneration replaces the entries a pending freshness check compares. - javaEntrypointFreshnessObservation = nil - let hasJavaSources = workspaceFeature.appliedSnapshot?.files - .contains { $0.pathExtension.lowercased() == "java" } ?? false - guard hasJavaSources else { return (.notJava, nil) } - let sessions: LanguageToolingSessionManager - do { - sessions = try await languageSessionsForWorkspaceMaintenance(for: identity) - } catch { - if !(error is CancellationError) { services.logSink?.emit(AppCoreFallbackSelected(error: error, stage: "java-entrypoints")) } - return (.failed(error.localizedDescription), nil) - } - guard isCurrentWorkspace(identity) else { return (.pending, nil) } - guard let preparation = sessions.projectPreparation else { - // Nothing started the Java service for this workspace yet. Asking - // starts it the way a launch does; its outcome reaches the refresh - // through `projectPreparation`, so the result here is not needed. - Task { [weak self, sessions] in - guard self?.isCurrentWorkspace(identity) == true, !Task.isCancelled else { return } - do { _ = try await sessions.javaEntrypoints(rootURL: identity.url) } - catch { sessions.recordHostFailure(providerID: "java", stage: "entrypoint-warmup", error: error) } - } - return (.pending, sessions) - } - if preparation.blocksRun { - return preparation.status == "failed" - ? (.failed(L10n.string("The Java language service failed to prepare the project.")), sessions) - : (.pending, sessions) - } - do { - return (.discovered(try await sessions.javaEntrypoints(rootURL: identity.url)), sessions) - } catch { - if !(error is CancellationError) { services.logSink?.emit(AppCoreFallbackSelected(error: error, stage: "java-entrypoints")) } - return (.failed(error.localizedDescription), sessions) - } - } - - /// Regenerates once JDT has finished (or failed) preparing the project. - func refreshJavaEntrypointsWhenPrepared( - for identity: WorkspaceIdentity, - sessions: LanguageToolingSessionManager, - automatic: Bool = false - ) { - javaEntrypointRefreshObservation = sessions.$projectPreparation - .compactMap { $0 } - .first(where: { !$0.blocksRun || $0.status == "failed" }) - .sink { [weak self] _ in - Task { @MainActor [weak self] in - guard let self else { return } - self.javaEntrypointRefreshObservation = nil - guard self.isCurrentWorkspace(identity) else { return } - await self.generateRunConfigurations(automatic: automatic) - } - } - } - - /// Reports Java entries JDT added or removed since the Run list was generated. - /// - /// The input fingerprint hashes only the Java sources generation reads, so - /// a main method added to an existing class is found here instead. The - /// check never starts the Java service and does not hold the project load - /// open. While a regeneration already waits for JDT, that refresh replaces - /// the entries, so there is nothing to compare. - func checkJavaEntrypointFreshness( - _ runFeature: RunFeatureModel, - for identity: WorkspaceIdentity, - files: [URL] - ) { - javaEntrypointFreshnessObservation = nil - // Without readable generated entries there is nothing to compare, so do - // not ask JDT for an answer the Run service would discard. - guard runFeature.configurationStatus == .ready, - javaEntrypointRefreshObservation == nil, - files.contains(where: { $0.pathExtension.lowercased() == "java" }), - let sessions = languageToolingSessionsIfActive else { return } - if let preparation = sessions.projectPreparation, !preparation.blocksRun { - Task { [weak self] in - await self?.compareJavaEntrypoints(runFeature, for: identity, sessions: sessions) - } - return - } - javaEntrypointFreshnessObservation = sessions.$projectPreparation - .compactMap { $0 } - .first(where: { !$0.blocksRun || $0.status == "failed" }) - .sink { [weak self] preparation in - Task { @MainActor [weak self] in - guard let self else { return } - self.javaEntrypointFreshnessObservation = nil - // A failed import has no answer to compare; generation reports it. - guard !preparation.blocksRun, self.isCurrentWorkspace(identity) else { return } - await self.compareJavaEntrypoints(runFeature, for: identity, sessions: sessions) - } - } - } - - private func compareJavaEntrypoints( - _ runFeature: RunFeatureModel, - for identity: WorkspaceIdentity, - sessions: LanguageToolingSessionManager - ) async { - let entrypoints: JavaEntrypoints - do { - entrypoints = try await sessions.javaEntrypoints(rootURL: identity.url) - } catch { - sessions.recordHostFailure(providerID: "java", stage: "entrypointFreshness", error: error) - return - } - guard isCurrentWorkspace(identity) else { return } - await runFeature.reportJavaEntrypointFreshness(entrypoints) - } - - /// Whether JDT lists `documentURL` as a launchable class in the workspace. - /// - /// When the Java service cannot answer, the file is treated as not - /// launchable and Debug keeps using a project entry, as it did when the - /// editor text was unavailable. - func isLaunchableJavaEntrypoint(_ document: EditorDocument?, in workspaceURL: URL) async -> Bool { - guard let identity = currentWorkspaceIdentity, identity.url == workspaceURL.standardizedFileURL, - let document, document.url.pathExtension.lowercased() == "java" else { - return false - } - guard let sessions = try? await languageSessionsForWorkspaceMaintenance(for: identity) else { - return false - } - do { - // Debug can be clicked before the editor's ordinary synchronization - // task flushes. Make this semantic decision against the exact - // buffer text, including unsaved Java 25 entry points. - try sessions.synchronizeLanguageServer( - for: document.url, - text: document.text, - rootURL: workspaceURL - ) - } catch { - if !(error is CancellationError) { services.logSink?.emit(AppCoreFallbackSelected(error: error, stage: "java-entrypoints")) } - return false - } - guard let entrypoints = try? await sessions.javaEntrypoints(rootURL: workspaceURL) else { - return false - } - let rootPath = workspaceURL.resolvingSymlinksInPath().standardizedFileURL.path - let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/" - let filePath = document.url.resolvingSymlinksInPath().standardizedFileURL.path - guard filePath.hasPrefix(prefix) else { return false } - let relativePath = String(filePath.dropFirst(prefix.count)) - return entrypoints.entries.contains { $0.sourcePath == relativePath } - } -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchDecision.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchDecision.swift deleted file mode 100644 index 3c2806fb49..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchDecision.swift +++ /dev/null @@ -1,101 +0,0 @@ -import Foundation -import LitheCoreContracts - -extension AppModel { - func resolveJavaLaunchPreparation( - _ preparation: JavaLaunchPreparation, - identity: WorkspaceIdentity - ) async throws -> JavaDebugLaunchTarget { - switch preparation { - case .ready(let target): - return target - case .buildFailed(let target, let failure): - guard isCurrentWorkspace(identity), !Task.isCancelled else { - throw CancellationError() - } - if settings.javaBuildFailurePolicy(for: identity.url) == .alwaysContinue { - return target - } - let resolution = await requestJavaLaunchDecision( - failure: failure, - identity: identity - ) - guard isCurrentWorkspace(identity), !Task.isCancelled else { - throw CancellationError() - } - switch resolution { - case .runOnce: - return target - case .alwaysContinue: - settings.setJavaBuildFailurePolicy(.alwaysContinue, for: identity.url) - return target - case .rebuildIndex: - rebuildJavaIndex() - throw CancellationError() - case .cancel: - throw CancellationError() - } - } - } - - func completeJavaLaunchDecision( - _ resolution: JavaLaunchDecisionResolution, - requestID: UUID? = nil - ) { - if let requestID, pendingJavaLaunchDecision?.id != requestID { - return - } - guard let continuation = pendingJavaLaunchDecisionContinuation else { - // Repeated cancellation must not publish a nil-to-nil change. - if pendingJavaLaunchDecision != nil { - pendingJavaLaunchDecision = nil - } - return - } - pendingJavaLaunchDecisionContinuation = nil - pendingJavaLaunchDecision = nil - continuation.resume(returning: resolution) - } - - func cancelPendingJavaLaunchDecision() { - completeJavaLaunchDecision(.cancel) - } - - func askAgainForJavaBuildFailures() { - guard let workspaceURL else { return } - settings.setJavaBuildFailurePolicy(.ask, for: workspaceURL) - objectWillChange.send() - } - - var alwaysContinuesAfterJavaBuildFailures: Bool { - guard let workspaceURL else { return false } - return settings.javaBuildFailurePolicy(for: workspaceURL) == .alwaysContinue - } - - private func requestJavaLaunchDecision( - failure: JavaLaunchBuildFailure, - identity: WorkspaceIdentity - ) async -> JavaLaunchDecisionResolution { - cancelPendingJavaLaunchDecision() - let request = PendingJavaLaunchDecision( - id: UUID(), - workspaceURL: identity.url, - failure: failure - ) - return await withTaskCancellationHandler { - await withCheckedContinuation { continuation in - guard !Task.isCancelled, isCurrentWorkspace(identity) else { - continuation.resume(returning: .cancel) - return - } - pendingJavaLaunchDecisionContinuation = continuation - pendingJavaLaunchDecision = request - } - } onCancel: { [weak self] in - Task { @MainActor in - guard self?.pendingJavaLaunchDecision?.id == request.id else { return } - self?.cancelPendingJavaLaunchDecision() - } - } - } -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchPreparation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchPreparation.swift deleted file mode 100644 index 557f231cbd..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaLaunchPreparation.swift +++ /dev/null @@ -1,26 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheModuleAPI - -/// Saves the Java workspace before requesting the shared launch preparation. -@MainActor -extension AppModel { - func saveJavaWorkspaceForLaunch(identity: WorkspaceIdentity) async throws { - guard isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - let saved = await saveAllDocuments() - guard isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - guard saved else { - throw RunConfigurationOperationFailure( - message: L10n.string("Java launch stopped because modified files could not be saved.") - ) - } - // A prior manual/automatic save may have reached disk while its LSP - // notification failed. Retry clean buffers too and propagate failures - // before asking JDT to build; disk persistence alone is not readiness. - for document in openDocuments where !document.isReadOnly { - try languageToolingSessionsIfActive?.notifyDocumentSaved( - document.url, text: document.savedText, currentText: document.text) - } - } - -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaNavigation.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaNavigation.swift deleted file mode 100644 index f5142bace4..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaNavigation.swift +++ /dev/null @@ -1,36 +0,0 @@ -import LitheModuleAPI -import Foundation - -extension AppModel { - func javaNavigationMarkers(for document: EditorDocument) async -> [JavaImplementationMarker] { - guard !languageToolingFeature.isDisabled("java"), - let sessions = languageToolingSessionsIfActive, - let workspaceURL else { return [] } - do { - try sessions.synchronizeLanguageServer( - for: document.url, - text: document.text, - rootURL: workspaceURL - ) - } catch { - sessions.recordHostFailure(providerID: "java", stage: "navigationSync", error: error) - return [] - } - return await withCheckedContinuation { continuation in - do { - try sessions.javaNavigationMarkers(fileURL: document.url) { result in - switch result { - case .success(let markers): - continuation.resume(returning: markers.map(JavaImplementationMarker.init)) - case .failure(let error): - sessions.recordHostFailure(providerID: "java", stage: "navigation", error: error) - continuation.resume(returning: []) - } - } - } catch { - sessions.recordHostFailure(providerID: "java", stage: "navigation", error: error) - continuation.resume(returning: []) - } - } - } -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaPlugin.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaPlugin.swift deleted file mode 100644 index 7dba811082..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaPlugin.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation -import LitheModuleAPI - -extension AppModel { - /// One notice per window session keeps offline failures retryable on the - /// next launch, without repeating it for each file in a Java project. - func suggestJavaPluginIfNeeded(files: [URL]) { - guard !hasSuggestedJavaPlugin, - JavaPluginTransition.shouldSuggest( - files: files, - plugins: services.pluginManager.snapshots - ) else { return } - hasSuggestedJavaPlugin = true - showNotification( - L10n.string("Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept."), - action: WorkbenchNotification.Action(id: "plugins.marketplace.open", title: L10n.string("Open Marketplace")) { [weak self] in - self?.showPluginMarketplace(searching: "Java Support") - } - ) - } -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaRunMarkers.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+JavaRunMarkers.swift deleted file mode 100644 index 94f0f34d3e..0000000000 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaRunMarkers.swift +++ /dev/null @@ -1,172 +0,0 @@ -import LitheModuleAPI -import Foundation -import LitheCoreContracts -import LitheLanguageIntelligenceModule - -/// IDEA-style Run markers in the Java editor gutter: JDT decides which `main` -/// methods and tests exist, Core projects them with recorded test outcomes, -/// and these entry points launch them through the existing Run, Test, and -/// Debug workflows. -/// -/// Note: 设计见 .agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md -@MainActor -extension AppModel { - enum JavaRunMarkerAction: String { - case run - case debug - case editConfiguration - } - - func javaRunMarkers(for document: EditorDocument) async -> [JavaRunMarker] { - guard document.url.pathExtension.lowercased() == "java", - !languageToolingFeature.isDisabled("java"), - let sessions = languageToolingSessionsIfActive, - let workspaceURL else { return [] } - do { - try sessions.synchronizeLanguageServer( - for: document.url, - text: document.text, - rootURL: workspaceURL - ) - } catch { - recordJavaRunMarkerFailure(error, sessions: sessions) - return [] - } - let fileURL = document.url - let methods = await javaRunMarkerSource(sessions: sessions) { completion in - try sessions.javaMainMethods(fileURL: fileURL) { completion($0.map(\.methods)) } - } ?? [] - let items = await javaRunMarkerSource(sessions: sessions) { completion in - try sessions.javaTestItems(fileURL: fileURL) { completion($0.map(\.items)) } - } ?? [] - let project = buildSystemsFeatureIfActive?.projectPath(containing: document.url) - let outcomes = (languageTestServiceIfActive?.testOutcomes(for: "java") ?? []).filter { - $0.project == nil || $0.project == project - } - return services.javaMavenOperations.javaRunMarkers( - mainMethods: methods, - testItems: items, - testCases: outcomes - ) ?? [] - } - - /// Runs, debugs, or edits what a gutter marker points at. - func performJavaRunMarker(_ marker: JavaRunMarker, action: JavaRunMarkerAction, in fileURL: URL) { - switch marker.kind { - case .main: - guard let mainClass = marker.mainClass else { return } - Task { [weak self] in - await self?.performJavaMain(mainClass, action: action, in: fileURL) - } - case .testClass, .testMethod: - guard action != .editConfiguration, - let identifier = marker.testIdentifier(forDebugging: action == .debug) else { return } - let scope = LanguageTestScope.testCase(identifier: identifier, fileURL: fileURL) - if action == .debug { - debugTest(providerID: "java", scope: scope) - } else { - runTest(providerID: "java", scope: scope) - } - } - } - - private func performJavaMain(_ mainClass: String, action: JavaRunMarkerAction, in fileURL: URL) async { - activeTestTarget = nil - guard let workspaceURL, - let runFeature = await activateExecutionModule()?.runFeature else { return } - let rootPath = workspaceURL.standardizedFileURL.path - let filePath = fileURL.standardizedFileURL.path - guard filePath.hasPrefix(rootPath + "/") else { return } - let sourcePath = String(filePath.dropFirst(rootPath.count + 1)) - var configuration = Self.javaMainConfiguration( - in: runFeature.configurations, - selectedID: runFeature.selectedConfigurationID, - sourcePath: sourcePath, - mainClass: mainClass, - source: runFeature.source(for:), - select: services.javaMavenOperations.selectContextConfiguration - ) - if configuration == nil { - // The marker proves JDT can launch the class; the configuration - // list may predate that answer, so it is regenerated once. - await generateRunConfigurations() - configuration = Self.javaMainConfiguration( - in: runFeature.configurations, - selectedID: runFeature.selectedConfigurationID, - sourcePath: sourcePath, - mainClass: mainClass, - source: runFeature.source(for:), - select: services.javaMavenOperations.selectContextConfiguration - ) - } - guard let configuration else { - showNotification( - "No run configuration exists for \(mainClass) yet. Wait for the Java project to finish importing, then try again.", - logReference: notificationRejection(operation: "run_marker", reason: "configuration_missing") - ) - return - } - runFeature.select(configuration) - switch action { - case .run: - await performStartRunConfiguration(configuration) - case .debug: - await startDebuggingAfterActivation(configuration: configuration) - case .editConfiguration: - runFeature.editingConfigurationID = configuration.id - showSettings(category: .run) - } - } - - /// The configuration that launches `mainClass` from `sourcePath`: a user - /// edited copy wins over the generated entry, and the selection among equals. - static func javaMainConfiguration( - in configurations: [RunConfiguration], - selectedID: String, - sourcePath: String, - mainClass: String, - source: (RunConfiguration) -> RunConfigurationSource, - select: (RunContextSelectionRequest) -> String? - ) -> RunConfiguration? { - let request = RunContextSelectionRequest( - sourcePath: sourcePath, - symbol: mainClass, - preferredId: selectedID, - caseInsensitivePaths: false, - candidates: configurations.map { - RunContextSelectionRequest.Candidate( - id: $0.id, sourcePath: $0.sourcePath, symbol: $0.mainClass, - generated: source($0) == .generated, disabled: $0.disabled - ) - } - ) - guard let id = select(request) else { return nil } - return configurations.first { $0.id == id } - } - - private func javaRunMarkerSource( - sessions: LanguageToolingSessionManager, - _ request: (@escaping (Result) -> Void) throws -> Void - ) async -> Value? { - await withCheckedContinuation { continuation in - do { - try request { result in - switch result { - case .success(let value): - continuation.resume(returning: value) - case .failure(let error): - self.recordJavaRunMarkerFailure(error, sessions: sessions) - continuation.resume(returning: nil) - } - } - } catch { - recordJavaRunMarkerFailure(error, sessions: sessions) - continuation.resume(returning: nil) - } - } - } - - private func recordJavaRunMarkerFailure(_ error: Error, sessions: LanguageToolingSessionManager) { - sessions.recordHostFailure(providerID: "java", stage: "runMarkers", error: error) - } -} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageEditing.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageEditing.swift index 03a09edfc9..47f2170f78 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageEditing.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageEditing.swift @@ -6,9 +6,7 @@ import LitheModuleAPI /// and code actions. /// /// Each request checks the session's advertised capability first so an -/// unsupported server is a no-op rather than a failed round trip, and Spring -/// results are merged as a fallback where the language server has nothing to -/// add. +/// unsupported server is a no-op rather than a failed round trip. @MainActor extension AppModel { var semanticHighlightingSessionState: String { @@ -38,11 +36,6 @@ extension AppModel { utf16Column: Int, completion: @escaping (LanguageServerHover?) -> Void ) { - if let document = requestedDocument ?? focusedEditorDocument, - let hover = springFeature.hover(for: document.url, line: line) { - completion(hover) - return - } guard let document = requestedDocument ?? focusedEditorDocument, featureGraph.languageCapabilityPolicy.supports(.hover, documentURL: document.url, sessions: languageToolingSessionsIfActive), let workspaceURL else { @@ -90,19 +83,10 @@ extension AppModel { context: LanguageServerCompletionContext? = nil, completion: @escaping (LanguageServerCompletionList) -> Void ) { - guard let document = requestedDocument ?? focusedEditorDocument else { - completion(.init()) - return - } - let springCompletions = springFeature.completions( - document: document, - line: line, - utf16Column: utf16Column - ) - guard + guard let document = requestedDocument ?? focusedEditorDocument, featureGraph.languageCapabilityPolicy.supports(.completion, documentURL: document.url, sessions: languageToolingSessionsIfActive), let workspaceURL else { - completion(.init(items: springCompletions)) + completion(.init()) return } do { @@ -116,12 +100,12 @@ extension AppModel { rootURL: workspaceURL, completionContext: context ) { [weak self] result in guard let self else { - completion(.init(items: springCompletions)) + completion(.init()) return } self.featureGraph.languageEditing.handleCompletionResult( result.map(\.items), - fallback: springCompletions, + fallback: [], completion: { items in completion(.init(items: items, isIncomplete: (try? result.get().isIncomplete) ?? false)) } @@ -129,7 +113,7 @@ extension AppModel { } } catch { showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "language_editing")) - completion(.init(items: springCompletions)) + completion(.init()) } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageIntelligence.swift similarity index 67% rename from macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift rename to macos/Sources/Lithe/Models/AppModel/AppModel+LanguageIntelligence.swift index e0c2754c6e..fc63cf2bc6 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+JavaIndex.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageIntelligence.swift @@ -4,33 +4,10 @@ import LitheLanguageIntelligenceModule import LitheModuleAPI extension AppModel { - func rebuildJavaIndex() { - guard let identity = currentWorkspaceIdentity else { - showNotification( - settings.language.localizedString("native.inline.openAProjectBeforeRebuildingTheJavaIndex") - ) - return - } - - Task { @MainActor [weak self] in - guard let self else { return } - do { - let sessions = try await languageSessionsForWorkspaceMaintenance(for: identity) - try sessions.rebuildWorkspaceState(providerID: "java", rootURL: identity.url) - cancelJavaLanguageServerPreparation() - languageToolingFeature.resetProviderState(providerID: "java") - showNotification( - settings.language.localizedString("native.inline.javaIndexClearedReopenAJavaFileToRebuild") - ) - } catch { - let prefix = settings.language.localizedString("native.inline.failedToClearTheJavaIndex") - showNotification("\(prefix): \(error.localizedDescription)", logReference: notificationFailure(error, operation: "java_index")) - } - } - } - func bindLanguageIntelligenceCapability(_ capability: LanguageIntelligenceCapability) { - languageToolingFeature.bindProjectPreparation(capability.sessions) + // The status bar and LSP control center read server states through this + // binding; without it every registered server reports "Not started". + languageToolingFeature.bindSessions(capability.sessions) bindPluginLanguageServers(capability.sessions.pluginServers) cacheModuleCapability( capability, @@ -43,10 +20,6 @@ extension AppModel { self?.handleLanguageSessionChange() } ) - capability.sessions.configureJavaLanguageImportProvider { [weak self] _, rootURL in - guard let self else { throw CancellationError() } - return try self.javaLanguageImportConfiguration(rootURL: rootURL) - } capability.tools.onCandidatesChanged = { [weak self] providerID in guard let self, self.languageToolingFeature.shouldRetryCandidate(providerID: providerID), @@ -56,10 +29,6 @@ extension AppModel { } _ = self.activateLanguageServerIfAvailable(for: document) } - capability.sessions.onLanguageServerStateChange = { [weak self] providerID, state, operationID in - guard providerID == "java" else { return } - self?.handleJavaLanguageServerState(state, operationID: operationID) - } } func languageSessionsForWorkspaceMaintenance(for expectedIdentity: WorkspaceIdentity? = nil) async throws @@ -73,9 +42,6 @@ extension AppModel { await registerPluginLanguageServers(in: sessions) try Task.checkCancellation() guard isCurrentWorkspace(identity) else { throw CancellationError() } - try await prepareBuildLanguageImport() - try Task.checkCancellation() - guard isCurrentWorkspace(identity) else { throw CancellationError() } return sessions } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageServerRuntime.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageServerRuntime.swift index beeff5ecca..c40d74bb45 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageServerRuntime.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageServerRuntime.swift @@ -30,10 +30,6 @@ extension AppModel { } else if let support = services.pluginCatalog.languageSupports[providerID]?.declaration { registerLanguageDependencySourceIfAvailable(support: support) } - if providerID == "java", enabled { registerJavaDependencySourceIfAvailable() } - if providerID == "java", enabled, let workspaceURL { - prepareJavaLanguageServerForWorkspaceIfNeeded(at: workspaceURL, files: projectFiles) - } } func disableLanguageServerForCurrentWorkspace(providerID: String) { @@ -103,12 +99,6 @@ extension AppModel { } return false } - if descriptor.id == "java" { - switch prepareJavaLanguageServerRuntimeIfNeeded(for: document) { - case .ready: break - case .preparing: return false - } - } if let ownership = services.pluginCatalog.languageSupport(for: document.url), let moduleID = ownership.declaration.languageServerModuleID { let support = ownership.declaration @@ -184,9 +174,12 @@ extension AppModel { } registerLanguageDependencySourceIfAvailable(support: support) } - if let snapshot = try? services.moduleRuntime.snapshot(for: .languageIntelligence), - snapshot.state != .active, - snapshot.state != .idle { + // The host works through the bound capability, not the module state: + // a plugin's language server extension activates this module as its + // dependency without binding it here, so an active module can still + // have no sessions. Binding it is what lets a restored document start + // its server without waiting for the user to click the tab. + if languageToolingSessionsIfActive == nil { Task { [weak self] in guard let self else { return } do { @@ -231,224 +224,10 @@ extension AppModel { } } - func prepareJavaLanguageServerRuntimeIfNeeded( - for document: EditorDocument - ) -> JavaLanguageServerActivationReadiness { - if services.projectRuntimeService.isJavaLanguageServerRuntimePrepared(), - !isBuildLanguageImportPending || languageToolingSessionsIfActive?.activeLanguageServerIDs.contains("java") == true { - return .ready - } - guard !javaFeature.isLanguageServerPreparing, let workspaceURL else { return .preparing } - prepareJavaLanguageServerForWorkspaceIfNeeded( - at: workspaceURL, - files: projectFiles, - fallbackDocument: document - ) - return .preparing - } - - func prepareJavaLanguageServerForWorkspaceIfNeeded( - at workspaceURL: URL, - files: [URL], - fallbackDocument: EditorDocument? = nil - ) { - let normalizedRoot = workspaceURL.standardizedFileURL - guard let identity = currentWorkspaceIdentity, identity.url == normalizedRoot, - !languageToolingFeature.isDisabled("java") else { return } - guard services.javaMavenOperations.javaWorkspacePolicy( - at: normalizedRoot, - files: files, - changedFiles: [] - )?.shouldStart == true else { return } - guard !javaFeature.languageServerStateBelongs(to: normalizedRoot) else { return } - - cancelJavaLanguageServerPreparation() - let operationID = UUID() - let owner = javaFeature.beginLanguageServerPreparation( - workspaceURL: normalizedRoot, - operationID: operationID - ) - showJavaLanguageServerPreparingNotification() - javaLanguageServerPreparationCoordinator.prepareAndStart( - owner: owner, - workspaceURL: normalizedRoot, - runtimePreparation: { [weak self] in - guard let self else { return .unprepared } - return await self.services.projectRuntimeService - .prepareJavaLanguageServerRuntime() - }, - sessionsProvider: { [weak self] in - guard let self else { - throw CancellationError() - } - return try await self.languageSessionsForWorkspaceMaintenance(for: identity) - }, - languageImportPreparation: { [weak self] in - guard let self, self.isCurrentWorkspace(identity) else { throw CancellationError() } - try await self.prepareBuildLanguageImport() - guard self.isCurrentWorkspace(identity) else { throw CancellationError() } - }, - ownsPreparation: { [weak self] in - guard let self else { return false } - return self.ownsJavaLanguageServerPreparation( - workspaceURL: normalizedRoot, - operationID: operationID - ) - }, - onStarted: { [weak self, weak fallbackDocument] startedOperationID in - guard let self else { return } - if startedOperationID != operationID { - owner.operationID = startedOperationID - if let currentState = self.languageToolingSessionsIfActive? - .languageServerStates["java"] { - self.handleJavaLanguageServerState( - currentState, - operationID: startedOperationID - ) - } - } - if let fallbackDocument, - fallbackDocument.url.pathExtension.lowercased() == "java" { - _ = self.activateLanguageServerIfAvailable(for: fallbackDocument) - } - }, - onFailure: { [weak self] failure in - self?.failJavaLanguageServerPreparation( - workspaceURL: normalizedRoot, - operationID: operationID, - failure: failure - ) - } - ) - } - - func cancelJavaLanguageServerPreparation() { - cancelPendingJavaLaunchDecision() - if case .preparing(let owner) = javaFeature.languageServerWorkspaceState { - javaFeature.cancelLanguageServerPreparation() - return - } - javaFeature.cancelLanguageServerPreparation() - } - - func handleJavaLanguageServerState( - _ state: LanguageServerSessionState, - operationID: UUID? - ) { - switch state { - case .ready: - registerJavaDependencySourceIfAvailable() - case .stopped, .failed: - runFeatureIfActive?.unregisterDependencySource(languageID: "java") - case .startingProcess, .initializing, .stopping: - break - } - let currentWorkspaceURL = workspaceURL - javaLanguageServerPreparationCoordinator.handleSessionState( - state, - operationID: operationID, - javaFeature: javaFeature, - workspaceURL: workspaceURL, - onReady: { [weak self] in - self?.showNotification("Java service is ready") - }, - onFailure: { [weak self] failure in - guard let self, let operationID, let currentWorkspaceURL else { return } - self.failJavaLanguageServerPreparation( - workspaceURL: currentWorkspaceURL, - operationID: operationID, - failure: failure - ) - } - ) - } - - func isJavaLanguageServerPreparing(for fileURL: URL) -> Bool { - guard fileURL.pathExtension.lowercased() == "java" else { return false } - switch languageToolingSessionsIfActive?.languageServerStates["java"] { - case .startingProcess, .initializing: return true - default: break - } - return javaFeature.isLanguageServerPreparing - } - - func showJavaLanguageServerPreparingNotification() { - showNotification("Java service is preparing") - } - func handleWorkspaceFileChanges(_ changes: [WorkspaceFileChange]) { - guard let workspaceURL else { return } runFeatureIfActive?.markDependencyFilesChanged(changes) handleBuildSystemFileChanges(changes) handleVcsProviderFileChanges(changes) toolchainSettingsFeature.workspaceFilesChanged(changes) - let forwarded = changes.filter { change in - if Self.isWorkspaceDependencyMetadata( - change.fileURL, - workspaceURL: workspaceURL - ) { - return false - } - return true - } - javaLanguageServerPreparationCoordinator.notifyWorkspaceFileChanges( - forwarded, - workspaceURL: workspaceURL, - projectFiles: projectFiles, - openDocuments: openDocuments, - policy: { rootURL, files, changedFiles in - self.services.javaMavenOperations.javaWorkspacePolicy( - at: rootURL, - files: files, - changedFiles: changedFiles - ) - }, - sessions: languageToolingSessionsIfActive - ) - } - - private static func isWorkspaceDependencyMetadata( - _ fileURL: URL, - workspaceURL: URL - ) -> Bool { - let directory = workspaceURL.standardizedFileURL - .appendingPathComponent(".lithe", isDirectory: true) - .appendingPathComponent("dependencies", isDirectory: true) - .standardizedFileURL.path - let path = fileURL.standardizedFileURL.path - return path == directory || path.hasPrefix(directory + "/") - } - - private func ownsJavaLanguageServerPreparation( - workspaceURL: URL, - operationID: UUID - ) -> Bool { - !languageToolingFeature.isDisabled("java") && javaFeature.ownsLanguageServerPreparation( - workspaceURL: workspaceURL, - operationID: operationID, - activeWorkspaceURL: self.workspaceURL - ) - } - - private func failJavaLanguageServerPreparation( - workspaceURL: URL, - operationID: UUID, - failure: JavaLanguageServerPreparationFailure - ) { - javaFeature.markLanguageServerFailed( - workspaceURL: workspaceURL, - operationID: operationID, - failure: failure - ) - switch failure { - case .timedOut: - showNotification("Java service preparation timed out", logReference: notificationRejection(operation: "language_server", reason: "timed_out")) - case .failed(let message): - if let message, !message.isEmpty { - showNotification("Java service failed to start: %@", arguments: [message], logReference: notificationRejection(operation: "language_server", reason: "startup_failed")) - } else { - showNotification("Java service failed to start", logReference: notificationRejection(operation: "language_server", reason: "startup_failed")) - } - } } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageTests.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageTests.swift index 0d2ee79c4e..4f51e97cc2 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageTests.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+LanguageTests.swift @@ -3,12 +3,11 @@ import LitheCoreContracts import LitheExecutionModule import LitheModuleAPI -/// Test tool window entry points: discovery, run, and the Java debug-test -/// workflow. +/// Test tool window entry points: discovery and run. /// /// Discovery is cancellable and identified by an operation ID so a workspace -/// switch or a second refresh cannot let an older projection overwrite the -/// items the current discovery published. +/// switch or a second refresh cannot let an older discovery overwrite the +/// items the current one published. @MainActor extension AppModel { func toggleTests() { @@ -27,8 +26,8 @@ extension AppModel { private func startLanguageTestDiscovery(workspaceURL: URL) { guard let identity = currentWorkspaceIdentity, identity.url == workspaceURL.standardizedFileURL else { return } - let operationID = javaTestWorkflowState.beginDiscovery() - javaTestWorkflowState.discoveryTask = Task { [weak self] in + let operationID = languageTestWorkflowState.beginDiscovery() + languageTestWorkflowState.discoveryTask = Task { [weak self] in guard let self else { return } defer { finishLanguageTestDiscovery(operationID) } guard let execution = await activateExecutionModule(), @@ -38,54 +37,30 @@ extension AppModel { ), isCurrentWorkspace(identity), isCurrentLanguageTestDiscovery(operationID) else { return } execution.tests.discover(workspaceURL: workspaceURL, files: projectFiles) - - let baseItems = execution.tests.itemsByProviderID["java"] ?? [] - let javaFiles = baseItems.filter { $0.kind == .file && $0.fileURL != nil } - guard !javaFiles.isEmpty, !languageToolingFeature.isDisabled("java") else { return } - do { - let sessions = try await languageSessionsForWorkspaceMaintenance(for: identity) - guard !languageToolingFeature.isDisabled("java") else { return } - let projected = try await javaTestWorkflowState.projectDiscoveredItems( - baseItems, - workspaceURL: workspaceURL, - sessions: sessions, - isCurrent: { [weak self] operationID in - self?.isCurrentLanguageTestDiscovery(operationID) ?? false - }, - operationID: operationID - ) - execution.tests.replaceDiscoveredItems(projected, providerID: "java") - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentLanguageTestDiscovery(operationID) else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "language_tests")) - } } } func cancelLanguageTestDiscovery() { - javaTestWorkflowState.cancelDiscovery() + languageTestWorkflowState.cancelDiscovery() } private func isCurrentLanguageTestDiscovery(_ operationID: UUID) -> Bool { - javaTestWorkflowState.isCurrentDiscovery(operationID) + languageTestWorkflowState.isCurrentDiscovery(operationID) } private func finishLanguageTestDiscovery(_ operationID: UUID) { - javaTestWorkflowState.finishDiscovery(operationID) + languageTestWorkflowState.finishDiscovery(operationID) } func runTest(providerID: String, scope: LanguageTestScope) { guard let workspaceURL, let identity = currentWorkspaceIdentity else { return } activeTestTarget = ActiveTestTarget(providerID: providerID, scope: scope) showToolWindow(.tests) - let preparationID = javaTestWorkflowState.beginRunPreparation() - javaTestWorkflowState.runPreparationTask = Task { [weak self] in + let preparationID = languageTestWorkflowState.beginRunPreparation() + languageTestWorkflowState.runPreparationTask = Task { [weak self] in guard let self else { return } - defer { javaTestWorkflowState.finishRunPreparation(preparationID) } - guard let execution = await activateExecutionModule(), javaTestWorkflowState.isCurrentRunPreparation(preparationID) else { return } + defer { languageTestWorkflowState.finishRunPreparation(preparationID) } + guard let execution = await activateExecutionModule(), languageTestWorkflowState.isCurrentRunPreparation(preparationID) else { return } if let ownership = services.pluginCatalog.languageSupports[providerID], !(await languageIntelligenceModuleCoordinator.activateTestExtension( ownership.declaration, @@ -93,49 +68,20 @@ extension AppModel { )) { return } - guard isCurrentWorkspace(identity), javaTestWorkflowState.isCurrentRunPreparation(preparationID) else { return } - if providerID == "java" { - do { try await prepareBuildLanguageImport() } - catch { - if !error.isCancellation { showNotification(error.localizedDescription) } - return - } - guard isCurrentWorkspace(identity), javaTestWorkflowState.isCurrentRunPreparation(preparationID) else { return } - if let builds = execution.buildSystems, - builds.entries.contains(where: { $0.declaration.testSelectorKinds.contains("java.test.fullName") }) { - execution.tests.runUsingBackend(providerID: providerID, scope: scope, workspaceURL: workspaceURL, - label: L10n.string("Tests")) { [weak self, weak builds] output, process in - guard let self, let builds, isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - if let reference = scope.buildReference { - return try await builds.performLanguageTests(reference: reference, workspace: workspaceURL, title: L10n.string("Tests"), - isCurrent: { [weak self] in self?.isCurrentWorkspace(identity) == true }, beforePreparing: { - guard await self.saveAllDocuments(), self.isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - try await self.prepareBuildLanguageImport() - }, output: output, process: process) - } - let fileURL: URL? - let identifier: String? - switch scope { - case .workspace: fileURL = nil; identifier = nil - case .file(let file): fileURL = file; identifier = nil - case .testCase(let value, let file, _): - guard let file else { throw LanguageTestPlanError.unsupportedProvider("Java") } - fileURL = file; identifier = value - } - return try await builds.performLanguageTests(selectorKind: "java.test.fullName", fileURL: fileURL, - workspace: workspaceURL, title: L10n.string("Tests"), isCurrent: { [weak self] in - self?.isCurrentWorkspace(identity) == true - }, beforePreparing: { - guard await self.saveAllDocuments(), self.isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } - try await self.prepareBuildLanguageImport() - }, prepareSelectors: { - guard let fileURL else { return [] } - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - return try await sessions.javaBuildTestSelectors(fileURL: fileURL, identifier: identifier, rootURL: workspaceURL) - }, output: output, process: process) - } - return + guard isCurrentWorkspace(identity), languageTestWorkflowState.isCurrentRunPreparation(preparationID) else { return } + // A test the build provider reported earlier is rerun by the same + // provider, through the reference it published with the result. + if let reference = scope.buildReference, let builds = execution.buildSystems { + execution.tests.runUsingBackend(providerID: providerID, scope: scope, workspaceURL: workspaceURL, + label: L10n.string("Tests")) { [weak self, weak builds] output, process in + guard let self, let builds, isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } + return try await builds.performLanguageTests(reference: reference, workspace: workspaceURL, title: L10n.string("Tests"), + isCurrent: { [weak self] in self?.isCurrentWorkspace(identity) == true }, beforePreparing: { + guard await self.saveAllDocuments(), self.isCurrentWorkspace(identity), !Task.isCancelled else { throw CancellationError() } + try await self.awaitBuildSystemDetection() + }, output: output, process: process) } + return } _ = execution.tests.run( providerID: providerID, @@ -146,79 +92,6 @@ extension AppModel { } } - func debugTest(providerID: String, scope: LanguageTestScope) { - guard let workspaceURL else { return } - activeTestTarget = ActiveTestTarget(providerID: providerID, scope: scope) - switch javaTestWorkflowState.resolveDebugRequest(providerID: providerID, scope: scope) { - case .rejected(let message): - showNotification(message, logReference: notificationRejection(operation: "test_debug", reason: "request_rejected")) - return - case .resolved(let request): - startJavaTestDebug(request: request, workspaceURL: workspaceURL) - } - } - - private func startJavaTestDebug( - request: JavaTestDebugRequest, - workspaceURL: URL - ) { - guard let identity = currentWorkspaceIdentity, identity.url == workspaceURL.standardizedFileURL else { return } - let selectedTarget = activeTestTarget - featureGraph.javaTestDebugWorkflow.start( - request: request, - state: javaTestWorkflowState, - prepareDirtyDocument: { [weak self] in - guard let self else { return false } - return await self.javaTestWorkflowState.prepareDirtyDocument( - fileURL: request.fileURL, - documents: self.openDocuments, - saving: self - ) - }, - prepareLaunch: { [weak self] in - guard let self else { throw CancellationError() } - guard let runFeature = await self.activateExecutionModule()?.runFeature, - await self.activateDebugModule()?.genericFeature != nil else { - throw CancellationError() - } - if let selectedConfiguration = runFeature.selectedConfiguration { - runFeature.select(selectedConfiguration) - } - try await self.prepareBuildLanguageImport() - let revision = self.buildSystemsFeatureIfActive?.inputRevision - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - let prepared = try await self.services.javaTestDebugLaunchService.prepare( - fileURL: request.fileURL, - testIdentifier: request.testIdentifier, - rootURL: workspaceURL, - targetResolver: sessions - ) - guard self.isCurrentWorkspace(identity), !Task.isCancelled, self.buildSystemsFeatureIfActive?.inputRevision == revision else { - prepared.stop() - throw CancellationError() - } - return prepared - }, - startDebug: { [weak self] prepared in - guard let self, self.isCurrentWorkspace(identity), !Task.isCancelled, - let genericDebugFeature = self.genericDebugFeatureIfActive else { - return false - } - if self.activeTestTarget == selectedTarget { - self.activeTestTarget?.resolvedName = prepared.configuration.name - } - return genericDebugFeature.start( - fileURL: prepared.target.fileURL, - rootURL: workspaceURL, - configuration: prepared.configuration - ) - }, - errorMessage: { [weak self] in - self?.genericDebugFeatureIfActive?.errorMessage - } - ) - } - private func activateLanguageTestExtensionsIfNeeded( for files: [URL], testService: LanguageTestService @@ -235,27 +108,12 @@ extension AppModel { } func stopTests() { - javaTestWorkflowState.cancelRunPreparation() + languageTestWorkflowState.cancelRunPreparation() executionModuleCoordinator.stopTests(languageTestServiceIfActive) } - func cancelJavaTestDebugLaunch() { - javaTestWorkflowState.cancelDebugLaunch() - } - - func stopJavaTestResultServer() { - javaTestWorkflowState.stopResultServer() - } - - func cancelJavaTestWorkflows() { - javaTestWorkflowState.cancelRunPreparation() + func cancelLanguageTestWorkflows() { + languageTestWorkflowState.cancelRunPreparation() cancelLanguageTestDiscovery() - cancelJavaTestDebugLaunch() - } - - func cancelJavaWorkspaceWorkflows() { - javaLanguageServerPreparationCoordinator.cancelMavenConfigurationSynchronization() - cancelJavaLanguageServerPreparation() - cancelJavaTestWorkflows() } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+NewProject.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+NewProject.swift index 16be16d282..3176e553c8 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+NewProject.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+NewProject.swift @@ -21,11 +21,9 @@ extension AppModel { /// create projects. func makeNewProjectFeature() -> NewProjectFeatureModel? { guard let service = services.projectGeneration else { return nil } - let runtime = services.projectRuntimeService return NewProjectFeatureModel(environment: NewProjectEnvironment( sources: { [weak self] in self?.services.projectGeneratorSources?() ?? [] }, iconResources: services.pluginUIIconResources, - javaRuntimes: { await runtime.discoverJavaRuntimesForNewProject() }, service: service, setPluginEnabled: { [weak self] pluginID in try await self?.services.pluginManager.setEnabled(true, for: pluginID) diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginEditorActionLaunch.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginEditorActionLaunch.swift new file mode 100644 index 0000000000..1f5c760883 --- /dev/null +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginEditorActionLaunch.swift @@ -0,0 +1,72 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI + +/// Toolbar Run and Debug for a language whose package exposes execution only +/// as editor actions (`RunWorkflowCoordinator.languageSupportRoutingToEditorActions`). +/// +/// The host collects the active document's actions exactly as the gutter does +/// and calls the plugin's own function for the one drawn as `run`/`debug`. +/// Whether anything starts remains the plugin's decision; a run or debug +/// session it opens through the host methods appears in the tool windows the +/// same way a gutter click would. +@MainActor +extension AppModel { + /// The collector for the local workspace this window shows; nil when + /// plugin editor actions are not served here (remote workspace, no service). + var pluginEditorActionCollector: PluginEditorActionCollector? { + guard let workspace = pluginWebWorkspaceContext, + services.pluginWorkspaceContexts?.contexts.contains(where: { $0.reference == workspace && $0.authority == .local }) == true, + let service = services.pluginEditorActions, let backends = pluginWebBackends else { return nil } + return PluginEditorActionCollector(service: service, backends: backends, workspace: workspace, logSink: services.logSink) + } + + /// Starts `intent` for `document` through the owning package's editor + /// action, or tells the user why nothing could start. + func startPluginEditorAction( + _ intent: PluginEditorActionIntent, document: EditorDocument, + support: LanguageSupportDeclaration, identity: WorkspaceIdentity + ) async { + let unavailable: () -> Void = { [weak self] in + guard let self else { return } + let key = intent == .run ? "%@ does not provide project execution" : "%@ does not provide debugging" + let reason = intent == .run ? "run_editor_action_unavailable" : "debug_editor_action_unavailable" + showNotification(key, arguments: [support.displayName], + logReference: notificationRejection(operation: "run_workflow", reason: reason)) + } + guard let collector = pluginEditorActionCollector, + PluginEditorActionCollector.admits(document, service: collector.service) else { return unavailable() } + let registrations = collector.registrations(for: document) + guard !registrations.isEmpty else { return unavailable() } + let documentID = document.id.uuidString, version = document.contentVersion + let path = PluginEditorActionCollector.workspaceRelativePath(of: document.url, root: workspaceURL) + let items: [PluginEditorActionItem] + do { + items = try await collector.collect(documentID: documentID, version: version, path: path, + text: document.text, registrations: registrations) + } catch { return } // log-exempt: collect 只在取消时抛出,其它插件失败已由收集器记录 PluginsEditorActionsFailed + guard isCurrentWorkspace(identity), !Task.isCancelled else { return } + guard document.contentVersion == version, collector.stillRegistered(items) else { + showNotification("The file changed while preparing to start. Try again.", + logReference: notificationRejection(operation: "run_workflow", reason: "editor_action_stale")) + return + } + guard let choice = PluginEditorActionLaunchSelection.choose(items, intent: intent) else { return unavailable() } + let operation = UUID() + do { + if let reveal = try await collector.invoke(choice, documentID: documentID, expectedVersion: version) { + revealPluginLocations(reveal) + } + } catch is CancellationError { // log-exempt: 用户取消或切换工作区不是失败,不需要记录 + return + } catch { + var reference: LogRecordReference? + if let plugin = LogSegment(choice.item.registration.pluginID) { + let event = PluginsEditorActionFailed(error: error, plugin: plugin, operationID: operation.uuidString) + services.logSink?.emit(event) + reference = event.reference + } + showNotification("The plugin host request could not be completed.", logReference: reference) + } + } +} diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift index e4d8b77e3d..6657997944 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginHostWindow.swift @@ -66,7 +66,6 @@ extension AppModel: PluginHostWindowPort { guard MediaDocumentKind.from(url: normalized) == nil else { return nil } if activation == .select { // The same preparation as opening a file from the project tree. - suggestJavaPluginIfNeeded(files: [normalized]) editorTabOrderFeature.repositoryDiffSelected = false editorNavigationTarget = nil } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginOutputLinks.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginOutputLinks.swift index 7e9911a25e..aa62d436e6 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginOutputLinks.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginOutputLinks.swift @@ -29,7 +29,10 @@ extension AppModel { return try await service.location(answering: question, backends: backends, context: pluginWebWorkspaceContext) } catch { if let plugin = LogSegment(question.pluginID) { - services.logSink?.emit(PluginsHostRequestFailed(error: error, plugin: plugin)) + let code = (error as? PluginHostServiceError)?.code ?? .failed + services.logSink?.emit(PluginsHostRequestFailed( + code: code.rawValue, error: error, method: question.function, plugin: plugin + )) } return nil } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginSettings.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginSettings.swift index 72700f90a4..d43c96fe09 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+PluginSettings.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+PluginSettings.swift @@ -97,7 +97,7 @@ extension AppModel { } loadBuildSystems(access) do { - _ = try await feature.prepareLanguageImport(workspaceURL: workspaceURL) + try await feature.awaitDetection(workspaceURL: workspaceURL) // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 } catch is CancellationError { return diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+RunConfiguration.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+RunConfiguration.swift index 3074e12dfc..a4a1890fab 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+RunConfiguration.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+RunConfiguration.swift @@ -17,34 +17,6 @@ extension AppModel { showToolWindow(.buildOutput) } - func updateRunningService(_ session: RunSession) { - guard let feature = runFeatureIfActive, let identity = currentWorkspaceIdentity else { return } - Task { [weak self] in - guard let self else { return } - await feature.updateService(session) { target, source in - guard self.isCurrentWorkspace(identity), await self.saveAllDocuments(), - self.isCurrentWorkspace(identity), - feature.moduleSessions.contains(where: { $0.executionID == session.executionID && $0.isRunning }) - else { throw CancellationError() } - let sessions = try await self.languageSessionsForWorkspaceMaintenance(for: identity) - guard self.isCurrentWorkspace(identity) else { throw CancellationError() } - try await sessions.buildJavaServiceUpdate(target: target, fileURL: source, rootURL: identity.url) - } - } - } - - func toggleSpringEndpoints() { - guard toggleToolWindow(.spring) else { return } - } - - func openSpringEndpoint(_ endpoint: SpringEndpoint) { - navigateToEditorLocation( - url: endpoint.url, - line: max(0, endpoint.line - 1), - utf16Column: max(0, endpoint.column - 1) - ) - } - func toggleRun() { guard toggleToolWindow(.run) else { return } Task { [weak self] in @@ -91,7 +63,7 @@ extension AppModel { guard runFeature.recoveryAction != .upgradeApplication else { return } switch await ensureRunProjectReady(runFeature, for: identity) { case .ready: - await generateFromJavaEntrypoints(runFeature, for: identity, automatic: automatic) + await generateAfterBuildDetection(runFeature, for: identity, automatic: automatic) case .waitingForSnapshot: runFeature.reportGenerationProjectNotReady() case .stale: @@ -99,6 +71,25 @@ extension AppModel { } } + /// Regenerates the Run list once build-system detection has settled, so + /// provider runs reflect the saved build options of this workspace. + func generateAfterBuildDetection( + _ runFeature: RunFeatureModel, + for identity: WorkspaceIdentity, + automatic: Bool = false + ) async { + do { + try await awaitBuildSystemDetection() + try await buildSystemsFeatureIfActive?.prepareRunGenerationModels(workspace: identity.url) + } catch { + guard isCurrentWorkspace(identity) else { return } + runFeature.reportGenerationProjectNotReady() + return + } + guard isCurrentWorkspace(identity), !Task.isCancelled else { return } + await runFeature.generateRunConfigurations(automatic: automatic) + } + func openRunConfiguration(relativePath: String?) { guard let workspaceURL else { return } let url = workspaceURL.appendingPathComponent(relativePath ?? ".lithe/run/configurations.json") @@ -136,24 +127,6 @@ extension AppModel { ) async { let target = workspaceURL.standardizedFileURL guard let identity = currentWorkspaceIdentity, identity.url == target else { return } - prepareJavaLanguageServerForWorkspaceIfNeeded( - at: target, - files: files - ) - springFeature.scheduleLoad( - workspaceURL: target, - files: files, - textOverrides: Dictionary(uniqueKeysWithValues: openDocuments.map { - ($0.url.standardizedFileURL, $0.text) - }) - ) - mybatisFeature.scheduleLoad( - workspaceURL: target, - files: files, - textOverrides: Dictionary(uniqueKeysWithValues: openDocuments.map { - ($0.url.standardizedFileURL, $0.text) - }) - ) loadVcsProviders(at: target) guard let execution = await activateExecutionModule() else { return } guard isCurrentWorkspace(identity), !Task.isCancelled else { return } @@ -169,11 +142,9 @@ extension AppModel { // project this process has not identified yet is identified now. if snapshotID != nil, execution.runFeature.configurationStatus == .missing || execution.runFeature.requiresConfigurationGeneration { - await generateFromJavaEntrypoints(execution.runFeature, for: identity, automatic: true) + await generateAfterBuildDetection(execution.runFeature, for: identity, automatic: true) guard isCurrentWorkspace(identity), !Task.isCancelled else { return } } - - checkJavaEntrypointFreshness(execution.runFeature, for: identity, files: files) guard resumesDeferredRunAction else { return } runWorkflowCoordinator.resumeDeferredAction( runFeature: execution.runFeature, @@ -244,6 +215,18 @@ extension AppModel { break } guard case .ready(let configuration) = configurationReadiness else { return } + // A package that exposes running only as editor actions has no + // execution module to activate: the toolbar calls its run action. + if let document = activeDocument, + let support = runWorkflowCoordinator.languageSupportRoutingToEditorActions( + .run, for: configuration, currentFileURL: document.url, hostLaunchesFiles: { _ in false } + ) { + guard await runWorkflowCoordinator.saveDirtyCurrentFileIfNeeded( + configuration: configuration, document: document, saving: self + ), isCurrentWorkspace(identity), !Task.isCancelled else { return } + await startPluginEditorAction(.run, document: document, support: support, identity: identity) + return + } if !(await activateLanguageRunExtensionIfNeeded( for: configuration, currentFileURL: activeDocument?.url, @@ -260,25 +243,10 @@ extension AppModel { return } guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - let javaLaunch: JavaDebugLaunchTarget? - do { - javaLaunch = try await prepareJavaRunLaunch( - for: configuration, - identity: identity - ) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - return - } - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } if configuration.kind != .currentFile { - runFeature.startConfiguration(configuration, javaLaunch: javaLaunch) + runFeature.startConfiguration(configuration) } else { - runFeature.runSelected(currentFileURL: activeDocument?.url, javaLaunch: javaLaunch) + runFeature.runSelected(currentFileURL: activeDocument?.url) } showToolWindow(.run) } @@ -331,22 +299,7 @@ extension AppModel { saving: self ) else { return } guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - let javaLaunch: JavaDebugLaunchTarget? - do { - javaLaunch = try await prepareJavaRunLaunch( - for: configuration, - identity: identity - ) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - return - } - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - runFeature.restart(javaLaunch: javaLaunch) + runFeature.restart() } } @@ -378,27 +331,9 @@ extension AppModel { ), isCurrentWorkspace(identity) else { return } } - var preparedConfigurations: [(RunConfiguration, JavaDebugLaunchTarget?)] = [] - do { - for configuration in configurations { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - let target = try await prepareJavaRunLaunch( - for: configuration, - identity: identity - ) - preparedConfigurations.append((configuration, target)) - } - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - return - } - for (configuration, javaLaunch) in preparedConfigurations { + for configuration in configurations { guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - runFeature.startConfiguration(configuration, javaLaunch: javaLaunch) + runFeature.startConfiguration(configuration) } showToolWindow(.run) } @@ -427,19 +362,7 @@ extension AppModel { runFeature: runFeature ) else { return } guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - let javaLaunch: JavaDebugLaunchTarget? - do { - javaLaunch = try await prepareJavaRunLaunch(for: configuration, identity: identity) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - return - } - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - runFeature.startConfiguration(configuration, javaLaunch: javaLaunch) + runFeature.startConfiguration(configuration) showToolWindow(.run) } @@ -479,20 +402,7 @@ extension AppModel { let current = runFeature.configurations.first(where: { $0.id == id }), !runFeature.moduleSessions.contains(where: { $0.id == id && $0.isRunning }) else { continue } - do { - let javaLaunch = try await prepareJavaRunLaunch( - for: current, - identity: identity - ) - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - runFeature.startConfiguration(current, javaLaunch: javaLaunch) - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - } + runFeature.startConfiguration(current) } showToolWindow(.run) } @@ -521,26 +431,7 @@ extension AppModel { ) else { return } guard isCurrentWorkspace(identity), !Task.isCancelled else { return } } - var javaLaunches: [String: JavaDebugLaunchTarget] = [:] - do { - for configuration in serviceConfigurations { - if let target = try await prepareJavaRunLaunch( - for: configuration, - identity: identity - ) { - javaLaunches[configuration.id] = target - } - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - } - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - guard isCurrentWorkspace(identity), !Task.isCancelled else { return } - showNotification(error.localizedDescription, logReference: notificationFailure(error, operation: "run_configuration")) - return - } - runFeature.runAllServices(javaLaunches: javaLaunches) + runFeature.runAllServices() } } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+Terminal.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+Terminal.swift index e60a3f28e1..18c70f4501 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+Terminal.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+Terminal.swift @@ -169,11 +169,6 @@ extension AppModel { debugTerminalSessionIDsByDebugSession[debugSessionID, default: []].insert(created.session.id) activeDebugTerminalSessionIDsByDebugSession[debugSessionID] = created.session.id } - if let id = debugSessionID, executablePath.hasSuffix("/java"), - services.remoteConnections?.workspaces.contains(workspaceURL) != true { - debugPerformanceFeature.register(DebugPerformanceTarget(processID: created.processID, - javaExecutable: URL(fileURLWithPath: executablePath)), sessionID: id.rawValue) - } showToolWindow(.terminal) created.session.focus() return DebugRunInTerminalResponse(processID: Int(created.processID)) diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel+WorkbenchState.swift b/macos/Sources/Lithe/Models/AppModel/AppModel+WorkbenchState.swift index e168ef49dc..177fdf6cba 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel+WorkbenchState.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel+WorkbenchState.swift @@ -46,11 +46,6 @@ extension AppModel { set { workbenchFeature.setVisibility(.problems, isVisible: newValue) } } - var isSpringVisible: Bool { - get { workbenchFeature.isVisible(.spring) } - set { workbenchFeature.setVisibility(.spring, isVisible: newValue) } - } - var isDebugVisible: Bool { get { workbenchFeature.isVisible(.debug) } set { workbenchFeature.setVisibility(.debug, isVisible: newValue) } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModel.swift b/macos/Sources/Lithe/Models/AppModel/AppModel.swift index 9ac0edf25e..4820a7da91 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModel.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModel.swift @@ -14,10 +14,7 @@ import LitheCoreContracts final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { let id = UUID() lazy var editorSettingsImport = services.makeEditorSettingsImport(settings: settings) - var hasSuggestedJavaPlugin = false lazy var debugPerformanceFeature = DebugPerformanceFeatureModel(sampler: services.debugPerformanceSampler) - lazy var testPerformanceFeature = TestJVMPerformanceFeatureModel( - sampler: services.debugPerformanceSampler, provider: services.testJVMPerformance) lazy var ideCapabilities = IdeCapabilitiesFeatureModel(model: self, logSink: services.logSink) /// Settings › MCP: servers registered with Codex and Claude Code, created /// when the page is first shown. @@ -134,8 +131,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { var isGeneratingCommitMessage: Bool { commitDraftFeature.isGenerating } var pendingGeneratedCommitMessage: String? { commitDraftFeature.pendingGeneratedMessage } var pendingRunAction: PendingRunAction? { runWorkflowCoordinator.pendingAction } - @Published var pendingJavaLaunchDecision: PendingJavaLaunchDecision? - var pendingJavaLaunchDecisionContinuation: CheckedContinuation? @Published var debugBreakpointPresentation = DebugBreakpointPresentationState() @Published var isImplementationChooserVisible = false var languageProviderCatalog: LanguageProviderCatalog { languageToolingFeature.catalog } @@ -153,9 +148,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { featureGraph.navigationHistory } var virtualDocumentProviderIDs: [URL: String] = [:] - var javaCodeVisionHints: [URL: [JavaCodeVisionHint]] { - javaFeature.javaCodeVisionHints - } @Published var blameVisibleURL: URL? private var shortcutSessionCoordinator: ShortcutSessionCoordinator? private var documentLanguageCoordinator: DocumentLanguageCoordinator? @@ -175,9 +167,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { private var didCloseProject: (() -> Void)? /// Asks whether this project's Run services may stop; set by the session manager. private var confirmRunServicesBeforeClose: (@MainActor ([RunServiceExitCandidate]) async -> Bool)? - var javaTestWorkflowState: JavaTestWorkflowState { - featureGraph.javaTestWorkflow - } var languageNavigationCoordinator: LanguageNavigationCoordinator { featureGraph.languageNavigation } @@ -186,6 +175,7 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { let settings: AppSettings let featureGraph: AppModelFeatureGraph var workbenchFeature: WorkbenchFeatureModel { featureGraph.workbench } + var languageTestWorkflowState: LanguageTestWorkflowState { featureGraph.languageTestWorkflow } var workspaceSessionCoordinator: WorkspaceSessionCoordinator { featureGraph.workspaceSession } @@ -269,7 +259,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { onChange: { [weak self] in self?.scheduleObjectWillChangeRelay(affectsSettings: false) }, onError: { [weak self] in self?.showNotification($0, logReference: self?.notificationRejection(operation: "module_activation", reason: "activation_failed")) } ) - let javaLanguageServerPreparationCoordinator = JavaLanguageServerPreparationCoordinator() lazy var historyModuleCoordinator = HistoryModuleCoordinator( runtime: services.moduleRuntime, store: moduleCapabilityStore, @@ -296,7 +285,10 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { lazy var runWorkflowCoordinator = RunWorkflowCoordinator( pluginCatalog: services.pluginCatalog, moduleRuntime: services.moduleRuntime, - notify: { [weak self] in self?.showNotification($0, logReference: self?.notificationRejection(operation: "run_workflow", reason: "preparation_failed")) }, + notify: { [weak self] message, arguments in + self?.showNotification(message, arguments: arguments, + logReference: self?.notificationRejection(operation: "run_workflow", reason: "preparation_failed")) + }, onPendingActionChange: { [weak self] in self?.scheduleObjectWillChangeRelay(affectsSettings: false) } ) var languageCapability: LitheLanguageIntelligenceModule.LanguageIntelligenceCapability? { @@ -318,9 +310,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { cachedModuleCapability(.gitWorkspace) } var documentFeature: DocumentFeatureModel { featureGraph.document } - var javaFeature: JavaFeatureModel { featureGraph.java } - var springFeature: SpringFeatureModel { featureGraph.spring } - var mybatisFeature: MybatisFeatureModel { featureGraph.mybatis } var moduleSnapshots: [ModuleSnapshot] { services.moduleRuntime.snapshots() } lazy var workbenchUIRegistry: WorkbenchModuleUIRegistry = { do { return try WorkbenchModuleUIComposition.registry(for: services.pluginCatalog, iconResources: services.pluginUIIconResources) } @@ -370,19 +359,12 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { executionCapability?.testService as? LanguageTestService } var languageDiagnostics: [URL: [LanguageServerDiagnostic]] { - var combined = languageToolingSessionsIfActive?.diagnostics ?? [:] - for (url, diagnostics) in springFeature.languageDiagnostics { - combined[url, default: []].append(contentsOf: diagnostics) - } - return combined + languageToolingSessionsIfActive?.diagnostics ?? [:] } var editorDiagnostics: [URL: [EditorDiagnostic]] { editorDiagnosticsStore.diagnosticsByURL } var languageSessionChromeSignature: LanguageSessionChromeSignature? - /// Last Maven problem set announced for the workspace, so one failure is - /// reported once rather than on every diagnostics refresh. - var announcedMavenResolutionProblems = "" var detectedCodexConfiguration: CodexConfigurationSnapshot? { detectedAIConfigurations.first { $0.source == .codex } @@ -403,8 +385,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { showSettings(category: .agents) } - private var springFeatureObservation: AnyCancellable? - private var mybatisFeatureObservation: AnyCancellable? private var isObjectWillChangeRelayScheduled = false /// Whether any change waiting in the scheduled relay can affect a settings page. private var pendingRelayAffectsSettings = false @@ -419,12 +399,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { /// not rebuild while the project is busy. See `SettingsModelContext`. let settingsChanges = ObservableObjectPublisher() private var languageToolingObservation: AnyCancellable? - /// Regenerates the Run list once JDT has prepared the project, after a - /// generation that could only show the previous Java entries. - var javaEntrypointRefreshObservation: AnyCancellable? - /// Compares the generated Java entries with JDT once it has prepared the - /// project, after a load that found it still importing. - var javaEntrypointFreshnessObservation: AnyCancellable? func cachedModuleCapability( _ id: ModuleCapabilityID, @@ -568,10 +542,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { languageToolingFeature.configureSessions { [weak self] in self?.languageToolingSessionsIfActive } - languageToolingFeature.registerPreparationCancellation(providerID: "java") { [weak self] in - self?.javaLanguageServerPreparationCoordinator.cancelMavenConfigurationSynchronization() - self?.cancelJavaLanguageServerPreparation() - } services.connectBuildProviderLanguageSessions? { [weak self] in self?.languageToolingSessionsIfActive } @@ -580,7 +550,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { } runWorkflowCoordinator.connect(actions: self) featureGraph.debugLaunchPreparation.connect(actions: self) - featureGraph.javaTestDebugWorkflow.connect(actions: self) featureGraph.debugSessionCleanup.connect(actions: self) workbenchFeature.reconcileContributions(services.moduleRuntime.availableContributions()) moduleSessionCoordinator = ModuleSessionCoordinator( @@ -602,13 +571,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { } WorkspaceProjectionComposition.configure(model: self) documentLanguageCoordinator = DocumentFeatureComposition.configure(model: self) - springFeatureObservation = springFeature.objectWillChange.sink { [weak self] _ in - self?.refreshEditorDiagnosticsStore() - self?.scheduleObjectWillChangeRelay(affectsSettings: false) - } - mybatisFeatureObservation = mybatisFeature.objectWillChange.sink { [weak self] _ in - self?.scheduleObjectWillChangeRelay(affectsSettings: false) - } fileVisibilityRulesObserverID = settings.addFileVisibilityRulesObserver { [weak self] in guard let self else { return } self.workspaceFeature.updateVisibilityRules(self.settings.fileVisibilityRules) @@ -730,7 +692,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { shortcutSessionCoordinator?.setActive(isActive) if !isActive { dismissSearchEverywhere() - cancelJavaLanguageServerPreparation() } } @@ -750,7 +711,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { await ideCapabilities.shutdown() shortcutSessionCoordinator?.shutdown() documentLanguageCoordinator?.stop() - cancelJavaWorkspaceWorkflows() languageToolingSessionsIfActive?.stopAll() executionModuleCoordinator.stopTests(languageTestServiceIfActive) stopTerminalSessions() @@ -791,28 +751,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { await moduleSessionCoordinator?.awaitShutdown() } - private func reloadJavaRuntimeServices() { - cancelJavaTestWorkflows() - debugModuleCoordinator.stopFeature(genericDebugFeatureIfActive) - executionModuleCoordinator.stopFeatures( - run: runFeatureIfActive - ) - languageToolingSessionsIfActive?.stopLanguageServer(providerID: "java") - javaFeature.stop() - springFeature.reset() - mybatisFeature.reset() - if let workspaceURL { - if let document = activeDocument, - document.url.pathExtension.lowercased() == "java" { - activateLanguageServerIfAvailable(for: document) - } - Task { [weak self] in - guard let self else { return } - await self.loadProjectServicesForAppliedSnapshot(at: workspaceURL) - } - } - } - var projectName: String { workspaceURL?.lastPathComponent ?? "Lithe" } @@ -851,7 +789,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { feature: languageToolingFeature, sessions: languageToolingSessionsIfActive ) - cancelJavaLanguageServerPreparation() let didStart = activateCurrentDocumentLanguageServerIfAvailable() showNotification( didStart @@ -865,10 +802,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { showNotification(settings.language.localizedString("native.inline.languageServerDiagnosticsCleared")) } - func javaStructure(source: String, declarationSources: [String] = []) async -> JavaStructureResult? { - await javaFeature.structure(source: source, declarationSources: declarationSources) - } - var activeDocument: EditorDocument? { documentFeature.activeDocument } @@ -978,7 +911,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { // every provider session before replacing the catalog or clearing the // document projection so no old-root documents, diagnostics, or // responses can survive into the next workspace. - cancelJavaWorkspaceWorkflows() languageToolingSessionsIfActive?.stopAll() reloadLanguageProviderCatalog(for: normalizedURL) stopTerminalSessions() @@ -995,9 +927,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { debugModuleCoordinator.resetFeature(genericDebugFeatureIfActive) debugBreakpointPresentation.reset() clearLanguageNavigationProjection() - javaFeature.stop() - springFeature.reset() - mybatisFeature.reset() workspaceSessionCoordinator.resetWorkspaceFeature() // The popup belongs to the old project; an activation it started may never finish. dismissSearchEverywhere() @@ -1038,7 +967,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { releaseRemoteWorkspace(at: workspaceURL) ideCapabilities.disable() documentLanguageCoordinator?.stop() - cancelJavaLanguageServerPreparation() beginModuleRuntimeShutdown() reloadLanguageProviderCatalog(for: nil) selectedSidebar = .project @@ -1054,7 +982,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { gitModuleCoordinator.resetFeature(gitFeatureIfActive) workbenchFeature.hideAllToolWindows() stopTerminalSessions() - cancelJavaWorkspaceWorkflows() languageToolingSessionsIfActive?.stopAll() executionModuleCoordinator.resetTests(languageTestServiceIfActive) runtimeFeature.closeProject() @@ -1068,9 +995,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { runWorkflowCoordinator.resetPendingAction() debugModuleCoordinator.resetFeature(genericDebugFeatureIfActive) debugBreakpointPresentation.reset() - javaFeature.stop() - springFeature.reset() - mybatisFeature.reset() editorChrome.reset() editorNavigationTarget = nil navigationHistoryFeature.reset() @@ -1129,7 +1053,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { displayPath: String? = nil, allowsOutsideWorkspace: Bool = false ) { - suggestJavaPluginIfNeeded(files: [url]) editorTabOrderFeature.repositoryDiffSelected = false editorNavigationTarget = nil // SVG remains a text document so edits, saves, and previews share one buffer. @@ -1145,7 +1068,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { } func openStandaloneFile(_ url: URL) { - suggestJavaPluginIfNeeded(files: [url]) workspaceSessionCoordinator.openStandaloneFile(at: url) } @@ -1156,10 +1078,6 @@ final class AppModel: ObservableObject, Identifiable, UnsavedDocumentHandling { platformUI.open(url) } - func javaIconKind(for url: URL) async -> LitheIconKind? { - await JavaFileIconResolver.resolve(for: url, storage: services.fileStorage, logSink: services.logSink) - } - func refreshWorkspace() async { await workspaceFeature.refreshCurrent() } diff --git a/macos/Sources/Lithe/Models/AppModel/AppModelSupportTypes.swift b/macos/Sources/Lithe/Models/AppModel/AppModelSupportTypes.swift index 536d87c19e..66c3e3d9d8 100644 --- a/macos/Sources/Lithe/Models/AppModel/AppModelSupportTypes.swift +++ b/macos/Sources/Lithe/Models/AppModel/AppModelSupportTypes.swift @@ -9,7 +9,6 @@ enum SettingsCategory: String, CaseIterable, Identifiable { case keymap = "Keymap" case toolchainEnvironment = "Runtime Environment" case toolchainSources = "Toolchain Sources" - case project = "Project" case run = "Run configurations" case terminal = "Terminal" case lsp = "LSP" @@ -27,12 +26,7 @@ enum SettingsCategory: String, CaseIterable, Identifiable { case mcp = "MCP Configuration" var id: String { rawValue } - var title: String { - switch self { - case .project: "Project · JDK & Maven" - default: rawValue - } - } + var title: String { rawValue } /// The sidebar group that owns this page, or `nil` for a top-level page. var group: SettingsGroup? { @@ -49,7 +43,6 @@ enum SettingsCategory: String, CaseIterable, Identifiable { case .general: "gearshape" case .editor: "textformat" case .keymap: "keyboard" - case .project: "shippingbox" case .toolchainEnvironment: "shippingbox" case .toolchainSources: "externaldrive" case .run: "play.rectangle" @@ -90,7 +83,7 @@ enum SettingsGroup: String, CaseIterable, Identifiable { switch self { case .appearance: [.general, .updates, .network, .editor, .keymap, .processTermination] case .versionControl: [.git] - case .build: [.toolchainEnvironment, .toolchainSources, .project, .run] + case .build: [.toolchainEnvironment, .toolchainSources, .run] case .languages: [.lsp] case .tools: [.terminal] case .ai: [.providers, .agents] + SettingsSubgroup.library.categories + [.ai] @@ -152,19 +145,6 @@ enum SettingsSidebarItem { ] } -enum JavaLaunchDecisionResolution: Equatable { - case runOnce - case alwaysContinue - case rebuildIndex - case cancel -} - -struct PendingJavaLaunchDecision: Identifiable, Equatable { - let id: UUID - let workspaceURL: URL - let failure: JavaLaunchBuildFailure -} - /// Product-level availability switches for integrations that require external /// credentials or services. Keeping these switches in one place lets the UI /// and application model disable an integration consistently without removing diff --git a/macos/Sources/Lithe/Models/Java/JavaDiagnosticModels.swift b/macos/Sources/Lithe/Models/Editor/DiagnosticModels.swift similarity index 100% rename from macos/Sources/Lithe/Models/Java/JavaDiagnosticModels.swift rename to macos/Sources/Lithe/Models/Editor/DiagnosticModels.swift diff --git a/macos/Sources/Lithe/Models/Editor/EditorDocument.swift b/macos/Sources/Lithe/Models/Editor/EditorDocument.swift index 5039046869..b677c22d8d 100644 --- a/macos/Sources/Lithe/Models/Editor/EditorDocument.swift +++ b/macos/Sources/Lithe/Models/Editor/EditorDocument.swift @@ -110,13 +110,10 @@ final class EditorDocument: ObservableObject, Identifiable, @unchecked Sendable private(set) var diskIdentity: String? /// Invalidates the tab's content-based icon after disk writes or watcher events. @Published private(set) var iconContentRevision: UInt64 = 0 - /// Presentation metadata from the current, revision-checked JDT Run marker response. - @Published var hasRunnableJavaMain = false - @Published var hasJavaTests = false - /// Prefer imported source-root roles over test-name or annotation guesses. - static func isTestSourceFile(_ url: URL, importedSourceRootKind: String?, hasTests: Bool) -> Bool { - let semanticFallback = hasTests && url.pathExtension.lowercased() == "java" - guard let importedSourceRootKind else { return semanticFallback } + /// A file is a test source only when an imported build model assigns its + /// containing source root a test role. + static func isTestSourceFile(importedSourceRootKind: String?) -> Bool { + guard let importedSourceRootKind else { return false } return ["testSource", "testResource", "generatedTestSource"].contains(importedSourceRootKind) } diff --git a/macos/Sources/Lithe/Models/Editor/EditorNavigationModels.swift b/macos/Sources/Lithe/Models/Editor/EditorNavigationModels.swift new file mode 100644 index 0000000000..3317f09db0 --- /dev/null +++ b/macos/Sources/Lithe/Models/Editor/EditorNavigationModels.swift @@ -0,0 +1,99 @@ +import Foundation +import LitheCoreContracts + +struct EditorCaret: Equatable { + let url: URL + let line: Int + let utf16Column: Int +} + +struct EditorNavigationTarget: Equatable, Identifiable { + let id = UUID() + let url: URL + let line: Int + let utf16Column: Int + /// Select the whole target line on arrival (Go to Line); symbol and find + /// navigation keep a zero-length caret. + var selectsWholeLine: Bool = false +} + +struct LanguageNavigationLocation: Identifiable, Hashable, Sendable { + let url: URL + let line: Int + let utf16Column: Int + let isReadOnly: Bool + let displayPath: String? + + init( + url: URL, + line: Int, + utf16Column: Int, + isReadOnly: Bool = false, + displayPath: String? = nil + ) { + self.url = url + self.line = line + self.utf16Column = utf16Column + self.isReadOnly = isReadOnly + self.displayPath = displayPath + } + + var id: String { "\(url.path):\(line):\(utf16Column)" } + + var displayName: String { displayPath?.split(separator: "/").last.map(String.init) ?? url.lastPathComponent } +} + +enum LanguageNavigationResultKind { + case definitions + case references + case implementations + + var title: String { + switch self { + case .definitions: "Definitions" + case .references: "Usages" + case .implementations: "Implementations" + } + } +} + +enum LanguageNavigationState { + case idle + case loading(operationID: UUID, providerID: String, kind: LanguageNavigationResultKind) + case results( + providerID: String?, + kind: LanguageNavigationResultKind, + locations: [LanguageNavigationLocation] + ) + + var providerID: String? { + switch self { + case .idle: nil + case .loading(_, let providerID, _): providerID + case .results(let providerID, _, _): providerID + } + } + + var kind: LanguageNavigationResultKind { + switch self { + case .idle: .definitions + case .loading(_, _, let kind), + .results(_, let kind, _): kind + } + } + + var locations: [LanguageNavigationLocation] { + guard case .results(_, _, let locations) = self else { return [] } + return locations + } + + var isLoading: Bool { + if case .loading = self { return true } + return false + } + + func owns(operationID: UUID) -> Bool { + guard case .loading(let ownedID, _, _) = self else { return false } + return ownedID == operationID + } +} diff --git a/macos/Sources/Lithe/Models/Java/ActiveTestTarget.swift b/macos/Sources/Lithe/Models/Java/ActiveTestTarget.swift deleted file mode 100644 index 0a681dd7d3..0000000000 --- a/macos/Sources/Lithe/Models/Java/ActiveTestTarget.swift +++ /dev/null @@ -1,34 +0,0 @@ -import Foundation -import LitheModuleAPI -import LitheCoreContracts - -/// The selected test scope, preserved when rerunning from the main toolbar. -struct ActiveTestTarget: Equatable, Sendable { - let providerID: String - let scope: LanguageTestScope - /// Upstream launch title, when debug preparation resolves a file to an actual test class. - var resolvedName: String? = nil - - var name: String { - if let resolvedName { return resolvedName } - return switch scope { - case .workspace: L10n.string("Workspace") - case .file(let url): url.lastPathComponent - case .testCase(let identifier, _, _): Self.formattedName(for: identifier) - } - } - - /// Formats identifiers like `demo.CalculatorTest#intentionalFailureForPreview()` - /// into `CalculatorTest.intentionalFailureForPreview`, or `demo.CalculatorTest` into `CalculatorTest`. - static func formattedName(for identifier: String) -> String { - if let hashIndex = identifier.firstIndex(of: "#") { - let className = String(identifier[.. Bool { - guard case .loading(let ownedID, _, _) = self else { return false } - return ownedID == operationID - } -} diff --git a/macos/Sources/Lithe/Models/Java/JavaRunModels.swift b/macos/Sources/Lithe/Models/Java/JavaRunModels.swift deleted file mode 100644 index f63d2dcffc..0000000000 --- a/macos/Sources/Lithe/Models/Java/JavaRunModels.swift +++ /dev/null @@ -1,15 +0,0 @@ -import LitheCoreContracts - -typealias RunOptions = LitheCoreContracts.RunOptions -typealias JavaRunOptions = LitheCoreContracts.RunOptions -typealias RunSession = LitheCoreContracts.RunSession -typealias RunPortConflict = LitheCoreContracts.RunPortConflict -typealias RunConfigurationCapabilities = LitheCoreContracts.RunConfigurationCapabilities -typealias MavenFrameworkKind = LitheCoreContracts.MavenFrameworkKind -typealias RunConfigurationKind = LitheCoreContracts.RunConfigurationKind -typealias RunConfigurationExecution = LitheCoreContracts.RunConfigurationExecution -typealias RunConfiguration = LitheCoreContracts.RunConfiguration -typealias JavaRunSession = LitheCoreContracts.RunSession -typealias JavaRunPortConflict = LitheCoreContracts.RunPortConflict -typealias JavaRunConfigurationKind = LitheCoreContracts.RunConfigurationKind -typealias JavaRunConfiguration = LitheCoreContracts.RunConfiguration diff --git a/macos/Sources/Lithe/Models/Java/MavenModels.swift b/macos/Sources/Lithe/Models/Java/MavenModels.swift deleted file mode 100644 index 1d3013169c..0000000000 --- a/macos/Sources/Lithe/Models/Java/MavenModels.swift +++ /dev/null @@ -1,7 +0,0 @@ -import Foundation -import LitheCoreContracts - -typealias MavenProfile = LitheCoreContracts.MavenProfile -typealias MavenLifecyclePhase = LitheCoreContracts.MavenLifecyclePhase -typealias MavenIssueSeverity = LitheCoreContracts.MavenIssueSeverity -typealias MavenBuildIssue = LitheCoreContracts.MavenBuildIssue diff --git a/macos/Sources/Lithe/Models/Java/MavenResolutionProblems.swift b/macos/Sources/Lithe/Models/Java/MavenResolutionProblems.swift deleted file mode 100644 index 5724b54df2..0000000000 --- a/macos/Sources/Lithe/Models/Java/MavenResolutionProblems.swift +++ /dev/null @@ -1,42 +0,0 @@ -import Foundation - -/// Maven problems JDT LS reports for the open workspace. -/// -/// JDT LS imports Maven projects through m2e and reports every failure to read a -/// POM or resolve an artifact as an error marker on that `pom.xml`. Those markers -/// are the resolution result; without surfacing them a failed import looks -/// successful while every third-party import stays unresolved (#970). Warnings -/// such as an out-of-date project configuration stay in the Problems view. -enum MavenResolutionProblems { - static func problems( - workspaceURL: URL?, - diagnosticsByURL: [URL: [EditorDiagnostic]] - ) -> [EditorDiagnostic] { - guard let workspaceURL else { return [] } - let rootPath = workspaceURL.standardizedFileURL.path - return diagnosticsByURL - .filter { url, _ in - let file = url.standardizedFileURL - return file.lastPathComponent.lowercased() == "pom.xml" - && file.path.hasPrefix(rootPath + "/") - } - .values - .flatMap { $0 } - .filter { $0.severity == .error } - .sorted { - if $0.fileURL.path != $1.fileURL.path { - return $0.fileURL.path.localizedStandardCompare($1.fileURL.path) == .orderedAscending - } - if $0.line != $1.line { return $0.line < $1.line } - if $0.utf16Column != $1.utf16Column { return $0.utf16Column < $1.utf16Column } - return $0.message < $1.message - } - } - - /// Stable identity of a problem set, used to notify once per distinct set. - static func signature(_ problems: [EditorDiagnostic]) -> String { - problems - .map { "\($0.fileURL.path)\u{0}\($0.line)\u{0}\($0.utf16Column)\u{0}\($0.message)" } - .joined(separator: "\n") - } -} diff --git a/macos/Sources/Lithe/Models/Java/MybatisModels.swift b/macos/Sources/Lithe/Models/Java/MybatisModels.swift deleted file mode 100644 index 1c1eaf41dd..0000000000 --- a/macos/Sources/Lithe/Models/Java/MybatisModels.swift +++ /dev/null @@ -1,67 +0,0 @@ -import Foundation - -struct MybatisStatement: Identifiable, Hashable, Sendable { - let id: String - let namespace: String - let statementID: String - let kind: String - let javaURL: URL - let javaLine: Int - let javaColumn: Int - let javaEndLine: Int - let javaEndColumn: Int - let xmlURL: URL - let xmlLine: Int - let xmlColumn: Int - let xmlEndColumn: Int - - /// Zero-based caret hits the Java method name, not the return type or parameters. - func matchesJavaName(line: Int, utf16Column: Int) -> Bool { - MybatisIndexPaths.contains( - line: line, - utf16Column: utf16Column, - symbolLine: javaLine, - symbolColumn: javaColumn, - symbolEndColumn: javaEndColumn - ) - } - - /// Zero-based caret hits the XML statement `id` value. - func matchesXmlId(line: Int, utf16Column: Int) -> Bool { - MybatisIndexPaths.contains( - line: line, - utf16Column: utf16Column, - symbolLine: xmlLine, - symbolColumn: xmlColumn, - symbolEndColumn: xmlEndColumn - ) - } -} - -struct MybatisIndexResult: Sendable { - let statements: [MybatisStatement] - - static let empty = MybatisIndexResult(statements: []) -} - -enum MybatisIndexPaths { - static func matches(_ url: URL) -> Bool { - let ext = url.pathExtension.lowercased() - if ext == "java" { return true } - return ext == "xml" && url.lastPathComponent.lowercased() != "pom.xml" - } - - static func contains( - line: Int, - utf16Column: Int, - symbolLine: Int, - symbolColumn: Int, - symbolEndColumn: Int - ) -> Bool { - let caretLine = line + 1 - let caretColumn = utf16Column + 1 - return caretLine == symbolLine - && caretColumn >= symbolColumn - && caretColumn < symbolEndColumn - } -} diff --git a/macos/Sources/Lithe/Models/Java/SpringModels.swift b/macos/Sources/Lithe/Models/Java/SpringModels.swift deleted file mode 100644 index e9df859f61..0000000000 --- a/macos/Sources/Lithe/Models/Java/SpringModels.swift +++ /dev/null @@ -1,94 +0,0 @@ -import Foundation - -struct SpringProperty: Identifiable, Hashable, Sendable { - let name: String - let typeName: String? - let documentation: String? - let defaultValue: String? - let sourceURL: URL? - let sourceLine: Int? - let sourceColumn: Int? - - var id: String { name } -} - -struct SpringConfigurationValue: Identifiable, Hashable, Sendable { - let key: String - let value: String - let url: URL - let line: Int - let column: Int - let profile: String? - let overridesBaseValue: Bool - let targetURL: URL? - let targetLine: Int? - let targetColumn: Int? - - var id: String { "\(url.path):\(line):\(key)" } -} - -struct SpringPropertyReference: Identifiable, Hashable, Sendable { - let key: String - let url: URL - let line: Int - let column: Int - - var id: String { "\(url.path):\(line):\(column):\(key)" } -} - -struct SpringDiagnostic: Identifiable, Hashable, Sendable { - let url: URL - let line: Int - let column: Int - let severity: String - let message: String - - var id: String { "\(url.path):\(line):\(column):\(message)" } -} - -struct SpringBean: Identifiable, Hashable, Sendable { - let id: String - let name: String - let typeName: String - let url: URL - let line: Int - let column: Int - let kind: String -} - -struct SpringInjection: Identifiable, Hashable, Sendable { - let url: URL - let line: Int - let column: Int - let typeName: String - let qualifier: String? - let beanIDs: [String] - - var id: String { "\(url.path):\(line):\(column):\(typeName)" } -} - -struct SpringEndpoint: Identifiable, Hashable, Sendable { - let id: String - let httpMethods: [String] - let route: String - let controller: String - let method: String - let url: URL - let line: Int - let column: Int -} - -struct SpringIndexResult: Sendable { - let properties: [SpringProperty] - let values: [SpringConfigurationValue] - let propertyReferences: [SpringPropertyReference] - let diagnostics: [SpringDiagnostic] - let beans: [SpringBean] - let injections: [SpringInjection] - let endpoints: [SpringEndpoint] - - static let empty = SpringIndexResult( - properties: [], values: [], propertyReferences: [], diagnostics: [], beans: [], - injections: [], endpoints: [] - ) -} diff --git a/macos/Sources/Lithe/Models/Keymap/LitheCommandCatalog.swift b/macos/Sources/Lithe/Models/Keymap/LitheCommandCatalog.swift index 85b265f778..5b5a2ec269 100644 --- a/macos/Sources/Lithe/Models/Keymap/LitheCommandCatalog.swift +++ b/macos/Sources/Lithe/Models/Keymap/LitheCommandCatalog.swift @@ -134,7 +134,6 @@ enum LitheCommandCatalog { command("save", "Save", "Save the active document", .project, "s", [.command]), command("close-project", "Close Project", "Return to the Welcome screen", .project, "w", [.shift, .command]), command("settings", "Settings", "Configure editor and project behavior", .project, ",", [.command]), - command("rebuild-java-index", "Java: Rebuild Index", "Clear the current project's Java index and rebuild it on next use", .project), command("reveal-in-finder", "Reveal in Finder", "Show the active file in Finder", .project), command("run", "Run", "Run selected configuration", .run, "r", [.control]), @@ -172,7 +171,6 @@ enum LitheCommandCatalog { command("find-usages", "Find Usages", "Find references to the selected symbol", .navigation, "u", [.option, .command]), command("search-in-project", "Find in Files", "Search text across the workspace", .navigation, "f", [.shift, .command]), command("replace-in-project", "Replace in Files", "Replace text across the workspace", .navigation, "r", [.shift, .command]), - command("spring-endpoints", "Spring Endpoints", "Show indexed Spring MVC routes", .navigation), command("show-logs", "Logs", "Open the application log window", .window, "l", [.shift, .command]), command("toggle-terminal", "Toggle Terminal", "Show or hide the Terminal tool window", .window), @@ -198,7 +196,7 @@ enum LitheCommandCatalog { case "toggle-terminal": .terminal case "toggle-git-log": .git case "search-everywhere", "find-action", "search-in-project", "replace-in-project": .search - case "toggle-problems", "spring-endpoints": .languageIntelligence + case "toggle-problems": .languageIntelligence case "local-history", "project-local-history": .localHistory default: nil } @@ -212,7 +210,6 @@ enum LitheCommandCatalog { case "toggle-run": .run case "toggle-tests": .tests case "toggle-debug": .debug - case "spring-endpoints": .spring default: nil } } diff --git a/macos/Sources/Lithe/Models/LitheAction.swift b/macos/Sources/Lithe/Models/LitheAction.swift index 2b0c400f71..f35dec78e4 100644 --- a/macos/Sources/Lithe/Models/LitheAction.swift +++ b/macos/Sources/Lithe/Models/LitheAction.swift @@ -72,7 +72,6 @@ enum LitheActionRegistry { action("close-project", model: model) { model.closeProject() }, action("show-logs", model: model) { model.openLogs() }, action("settings", model: model) { model.showSettings() }, - action("rebuild-java-index", model: model) { model.rebuildJavaIndex() }, action("save", model: model) { model.saveActiveDocument() }, action("search-everywhere", model: model) { model.toggleSearchEverywhere() }, action("find-action", model: model) { model.openFindAction() }, @@ -94,7 +93,6 @@ enum LitheActionRegistry { action("go-to-line", model: model) { model.showGoToLine() }, action("go-to-definition", model: model) { model.goToDefinition() }, action("find-usages", model: model) { model.findReferences() }, - toolWindowAction("spring-endpoints", model: model), action("local-history", model: model) { if let url = model.activeDocument?.url { model.showLocalHistory(for: url) } }, diff --git a/macos/Sources/Lithe/Models/Run/ActiveTestTarget.swift b/macos/Sources/Lithe/Models/Run/ActiveTestTarget.swift new file mode 100644 index 0000000000..bfc7a021ef --- /dev/null +++ b/macos/Sources/Lithe/Models/Run/ActiveTestTarget.swift @@ -0,0 +1,17 @@ +import Foundation +import LitheModuleAPI +import LitheCoreContracts + +/// The selected test scope, preserved when rerunning from the main toolbar. +struct ActiveTestTarget: Equatable, Sendable { + let providerID: String + let scope: LanguageTestScope + + var name: String { + switch scope { + case .workspace: L10n.string("Workspace") + case .file(let url): url.lastPathComponent + case .testCase(let identifier, _, _): identifier + } + } +} diff --git a/macos/Sources/Lithe/Models/Run/RunModelAliases.swift b/macos/Sources/Lithe/Models/Run/RunModelAliases.swift new file mode 100644 index 0000000000..a13f4b22bf --- /dev/null +++ b/macos/Sources/Lithe/Models/Run/RunModelAliases.swift @@ -0,0 +1,10 @@ +import LitheCoreContracts +import LitheExecutionModule + +typealias RunOptions = LitheCoreContracts.RunOptions +typealias RunSession = LitheCoreContracts.RunSession +typealias RunConfigurationCapabilities = LitheCoreContracts.RunConfigurationCapabilities +typealias RunConfigurationKind = LitheCoreContracts.RunConfigurationKind +typealias RunConfigurationExecution = LitheCoreContracts.RunConfigurationExecution +typealias RunConfiguration = LitheCoreContracts.RunConfiguration +typealias RunService = LitheExecutionModule.RunService diff --git a/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeInventory.swift b/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeInventory.swift deleted file mode 100644 index 88fc3a1a93..0000000000 --- a/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeInventory.swift +++ /dev/null @@ -1,116 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheModuleAPI - -enum ProjectRuntimeSubprojectKind: String, Hashable, Sendable { - case projectDefaults - case buildRoot - case buildProject - case other -} - -/// A directory's local tool choices. Build providers own project hierarchy; -/// language declarations can identify directories before a model is loaded. -struct ProjectRuntimeSubproject: Identifiable, Hashable, Sendable { - let id: String - let kind: ProjectRuntimeSubprojectKind - let title: String - let relativePath: String - let usesJava: Bool - let parentID: String? - - var displaysPath: Bool { - kind != .projectDefaults && !relativePath.isEmpty && relativePath != "." - } -} - -enum ProjectRuntimeInventory { - struct BuildSource { - let id: String - let root: String - let displayName: String - let usesJava: Bool - let model: BuildModel? - } - static let projectDefaultsID = "project" - - static func subprojects( - workspaceName: String, - workspaceURL: URL, - files: [URL], - buildSources: [BuildSource], - languageSupports: [LanguageSupportDeclaration] - ) -> [ProjectRuntimeSubproject] { - let root = workspaceURL.standardizedFileURL - var result = [ProjectRuntimeSubproject(id: projectDefaultsID, kind: .projectDefaults, - title: workspaceName, relativePath: "", usesJava: true, parentID: nil)] - let javaMarkers = Set(languageSupports.filter { $0.id == "java" }.flatMap(\.projectFileNames)) - var javaDirectories = Set(files.filter { javaMarkers.contains($0.lastPathComponent.lowercased()) } - .compactMap { relativePath(for: $0.deletingLastPathComponent(), root: root) }) - for source in buildSources where source.usesJava { - javaDirectories.insert(source.root) - javaDirectories.formUnion(source.model?.projects.map(\.path) ?? []) - } - var known = Set(["."]) - var modeledRoots = Set() - for source in buildSources.sorted(by: { ($0.root, $0.id) < ($1.root, $1.id) }) { - guard validPath(source.root) else { continue } - let rootID = directoryID(source.root) - if known.insert(source.root).inserted { - let project = source.model?.projects.first { $0.path == source.root } - result.append(ProjectRuntimeSubproject(id: rootID, kind: .buildRoot, - title: project?.displayName ?? project?.name ?? source.displayName, - relativePath: source.root, usesJava: javaDirectories.contains(source.root), parentID: projectDefaultsID)) - } - guard let model = source.model else { continue } - modeledRoots.insert(source.root) - let projects = Dictionary(model.projects.map { ($0.id, $0.path) }, uniquingKeysWith: { first, _ in first }) - for project in model.projects.sorted(by: { ($0.path, $0.id) < ($1.path, $1.id) }) { - guard validPath(project.path), known.insert(project.path).inserted else { continue } - let parent = project.parentID.flatMap { projects[$0] }.map(directoryID) ?? rootID - result.append(ProjectRuntimeSubproject(id: directoryID(project.path), kind: .buildProject, - title: project.displayName ?? project.name, relativePath: project.path, - usesJava: javaDirectories.contains(project.path), parentID: parent)) - } - } - // Marker matching comes from installed declarations. It supplies only - // directory choices, never guesses modules or overrides an engine model. - for file in files.sorted(by: { $0.path < $1.path }) { - let languages = languageSupports.filter { $0.projectFileNames.contains(file.lastPathComponent.lowercased()) } - guard !languages.isEmpty, - let relative = relativePath(for: file.deletingLastPathComponent(), root: root), - validPath(relative), !known.contains(relative), - !modeledRoots.contains(where: { $0 == "." || relative.hasPrefix($0 + "/") }) else { continue } - known.insert(relative) - result.append(ProjectRuntimeSubproject(id: directoryID(relative), kind: .other, - title: file.deletingLastPathComponent().lastPathComponent, relativePath: relative, - usesJava: languages.contains { $0.id == "java" }, parentID: projectDefaultsID)) - } - return result - } - - static func workspaceRelativePath(modulePath: String?, workingDirectory: String?) -> String { - let directory = ProjectRuntimeSettings.normalizedRelativePath(workingDirectory) - let module = ProjectRuntimeSettings.normalizedRelativePath(modulePath) - if directory.isEmpty { return module } - if module.isEmpty { return directory } - if module == directory || module.hasPrefix(directory + "/") { return module } - return directory + "/" + module - } - - private static func relativePath(for url: URL, root: URL) -> String? { - let path = url.standardizedFileURL.path - let rootPath = root.standardizedFileURL.path - if path == rootPath { return "." } - let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/" - return path.hasPrefix(prefix) ? String(path.dropFirst(prefix.count)) : nil - } - - private static func validPath(_ path: String) -> Bool { - path == "." || !path.isEmpty && !path.contains("\\") && !path.contains(":") - && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) - && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } - } - - private static func directoryID(_ path: String) -> String { path == "." ? projectDefaultsID : "path:" + path } -} diff --git a/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeModels.swift b/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeModels.swift deleted file mode 100644 index d191079886..0000000000 --- a/macos/Sources/Lithe/Models/Runtime/ProjectRuntimeModels.swift +++ /dev/null @@ -1,393 +0,0 @@ -import Foundation -import LitheCoreContracts - -enum MavenHomeSelection: String, CaseIterable, Codable, Identifiable, Sendable { - case automatic - case wrapper - case custom - - var id: String { rawValue } - - var title: String { - switch self { - case .automatic: "Automatic" - case .wrapper: "Maven Wrapper" - case .custom: "Custom Maven Home" - } - } -} - -struct ProjectModuleRuntimeOverride: Codable, Hashable, Sendable, Identifiable { - /// Workspace-relative subproject path, using `/` separators. - var path: String - /// Empty means inherit the project JDK. - var javaHomePath = "" - /// Empty means inherit the project Maven home or wrapper. - var mavenExecutablePath = "" - /// Empty means inherit the project Maven JDK, then the project JDK. - var mavenJavaHomePath = "" - - var id: String { path } - - var hasOverride: Bool { - !normalized(javaHomePath).isEmpty - || !normalized(mavenExecutablePath).isEmpty - || !normalized(mavenJavaHomePath).isEmpty - } - - private func normalized(_ value: String) -> String { - value.trimmingCharacters(in: .whitespacesAndNewlines) - } -} - -struct ProjectRuntimeSettings: Codable, Hashable, Sendable { - /// Empty means use the detected system JDK. - var javaHomePath = "" - var mavenHomeSelection: MavenHomeSelection = .automatic - var mavenHomePath = "" - /// Empty means use the project JDK, then the detected system JDK. - var mavenJavaHomePath = "" - /// Per-subproject JDK and Maven overrides for monorepos. - var moduleOverrides: [ProjectModuleRuntimeOverride] = [] - - enum CodingKeys: String, CodingKey { - case javaHomePath, mavenHomeSelection, mavenHomePath, mavenJavaHomePath - case moduleOverrides - } - - init( - javaHomePath: String = "", - mavenHomeSelection: MavenHomeSelection = .automatic, - mavenHomePath: String = "", - mavenJavaHomePath: String = "", - moduleOverrides: [ProjectModuleRuntimeOverride] = [] - ) { - self.javaHomePath = javaHomePath - self.mavenHomeSelection = mavenHomeSelection - self.mavenHomePath = mavenHomePath - self.mavenJavaHomePath = mavenJavaHomePath - self.moduleOverrides = moduleOverrides - } - - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - javaHomePath = try container.decodeIfPresent(String.self, forKey: .javaHomePath) ?? "" - mavenHomeSelection = try container.decodeIfPresent( - MavenHomeSelection.self, - forKey: .mavenHomeSelection - ) ?? .automatic - mavenHomePath = try container.decodeIfPresent(String.self, forKey: .mavenHomePath) ?? "" - mavenJavaHomePath = try container.decodeIfPresent(String.self, forKey: .mavenJavaHomePath) ?? "" - moduleOverrides = try container.decodeIfPresent( - [ProjectModuleRuntimeOverride].self, - forKey: .moduleOverrides - ) ?? [] - } - - /// Maven executable or home stored for the project-wide toolchain. - var mavenExecutableOverride: String { - switch mavenHomeSelection { - case .automatic: - "" - case .wrapper: - "mvnw" - case .custom: - mavenHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - } - } - - func override(matching workspaceRelativePath: String?) -> ProjectModuleRuntimeOverride? { - let target = Self.normalizedRelativePath(workspaceRelativePath) - guard !target.isEmpty, target != "." else { return nil } - return moduleOverrides - .filter { candidate in - let path = Self.normalizedRelativePath(candidate.path) - guard !path.isEmpty, path != "." else { return false } - return target == path || target.hasPrefix(path + "/") - } - .max { lhs, rhs in - Self.normalizedRelativePath(lhs.path).count < Self.normalizedRelativePath(rhs.path).count - } - } - - func exactOverride(for workspaceRelativePath: String) -> ProjectModuleRuntimeOverride? { - let target = Self.normalizedRelativePath(workspaceRelativePath) - guard !target.isEmpty else { return nil } - return moduleOverrides.first { Self.normalizedRelativePath($0.path) == target } - } - - func overlay( - onto options: RunOptions, - workspaceRelativePath: String? - ) -> RunOptions { - var result = options - let module = override(matching: workspaceRelativePath) - let projectJava = javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - let projectMaven = mavenExecutableOverride - let projectMavenJava = mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - result.javaHomePath = Self.resolvedPath( - configured: options.javaHomePath, - inheritedDefault: projectJava, - override: module?.javaHomePath - ) - result.mavenExecutablePath = Self.resolvedPath( - configured: options.mavenExecutablePath, - inheritedDefault: projectMaven, - override: module?.mavenExecutablePath - ) - result.mavenJavaHomePath = Self.resolvedPath( - configured: options.mavenJavaHomePath, - inheritedDefault: projectMavenJava, - override: module?.mavenJavaHomePath - ) - return result - } - - mutating func setOverride( - path: String, - javaHomePath: String? = nil, - mavenExecutablePath: String? = nil, - mavenJavaHomePath: String? = nil - ) { - let normalizedPath = Self.normalizedRelativePath(path) - guard !normalizedPath.isEmpty, normalizedPath != "." else { return } - var current = exactOverride(for: normalizedPath) ?? ProjectModuleRuntimeOverride(path: normalizedPath) - if let javaHomePath { current.javaHomePath = javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) } - if let mavenExecutablePath { - current.mavenExecutablePath = mavenExecutablePath.trimmingCharacters(in: .whitespacesAndNewlines) - } - if let mavenJavaHomePath { - current.mavenJavaHomePath = mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - } - moduleOverrides.removeAll { Self.normalizedRelativePath($0.path) == normalizedPath } - if current.hasOverride { - moduleOverrides.append(current) - moduleOverrides.sort { $0.path.localizedStandardCompare($1.path) == .orderedAscending } - } - } - - func projectToolchainSelection() -> ProjectToolchainSelection { - ProjectToolchainSelection( - javaHomePath: javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines), - mavenExecutablePath: mavenExecutableOverride, - mavenJavaHomePath: mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines), - pathOverrides: Dictionary(moduleOverrides.filter(\.hasOverride).map { value in - (value.path, ProjectToolchainSelection.PathOverride( - javaHomePath: value.javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines), - mavenExecutablePath: value.mavenExecutablePath.trimmingCharacters(in: .whitespacesAndNewlines), - mavenJavaHomePath: value.mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines))) - }, uniquingKeysWith: { _, last in last }) - ) - } - - mutating func applyProjectToolchain(_ selection: ProjectToolchainSelection) { - javaHomePath = selection.javaHomePath - mavenJavaHomePath = selection.mavenJavaHomePath - moduleOverrides = selection.pathOverrides.sorted { $0.key < $1.key }.map { path, value in - ProjectModuleRuntimeOverride(path: path, javaHomePath: value.javaHomePath, - mavenExecutablePath: value.mavenExecutablePath, mavenJavaHomePath: value.mavenJavaHomePath) - } - let maven = selection.mavenExecutablePath - if maven.isEmpty { - mavenHomeSelection = .automatic - mavenHomePath = "" - } else if maven == "mvnw" || maven == "./mvnw" || maven.hasSuffix("/mvnw") { - mavenHomeSelection = .wrapper - mavenHomePath = "" - } else { - mavenHomeSelection = .custom - mavenHomePath = maven - } - } - - static func normalizedRelativePath(_ path: String?) -> String { - guard let path else { return "" } - let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty || trimmed == "." { return "" } - var normalized = trimmed.replacingOccurrences(of: "\\", with: "/") - while normalized.hasPrefix("./") { - normalized.removeFirst(2) - } - if normalized.hasSuffix("/") { - normalized.removeLast() - } - return normalized - } - - /// A run-configuration path that equals the project default is treated as - /// inheritance so a more specific subproject override can still apply. - static func resolvedPath(configured: String, inheritedDefault: String, override: String?) -> String { - let configuredPath = configured.trimmingCharacters(in: .whitespacesAndNewlines) - let inheritedPath = inheritedDefault.trimmingCharacters(in: .whitespacesAndNewlines) - let overridePath = override?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let isExplicitConfiguration = !configuredPath.isEmpty && configuredPath != inheritedPath - if isExplicitConfiguration { return configuredPath } - if !overridePath.isEmpty { return overridePath } - if !configuredPath.isEmpty { return configuredPath } - return inheritedPath - } -} - -/// Where a resolved runtime came from, shown in place of "automatic". -enum RuntimeChoiceSource: Equatable, Sendable { - /// The explicit path at the level being resolved. - case configured - /// The project default from Settings. - case projectSetting - case javaHomeEnvironment - case detected - /// A Maven JDK that inherits the project JDK. - case projectJDK - case mavenWrapper - case systemMaven -} - -/// Outcome of one runtime selection chain in `ProjectRuntimeService`. -indirect enum RuntimeChoice: Equatable, Sendable { - case found(URL, RuntimeChoiceSource) - case warning(URL, RuntimeChoiceSource, String) - case unavailable(String) - /// A configured path that is not a usable runtime; a launch fails on it. - case invalid(String) - /// A configured path that is not usable, replaced by `to`. - case fallback(invalidPath: String, to: RuntimeChoice) - /// Nothing was configured and nothing usable was detected. - case notFound - - var url: URL? { - switch self { - case .found(let url, _), .warning(let url, _, _): url - case .fallback(_, let choice): choice.url - case .invalid, .notFound, .unavailable: nil - } - } - - /// The same choice presented as inherited from the project JDK. - var inheritedAsProjectJDK: RuntimeChoice { - if case .found(let url, _) = self { return .found(url, .projectJDK) } - if case .warning(let url, _, let message) = self { return .warning(url, .projectJDK, message) } - return self - } -} - -struct JavaRuntimeCandidate: Identifiable, Hashable, Sendable { - /// JDT LS 1.44 and later refuse to start on an older Java runtime. - static let minimumJDTLSMajorVersion = 21 - - let homePath: String - let version: String - let vendor: String - - var id: String { homePath } - - var displayName: String { - let vendor = vendor.isEmpty ? "JDK" : vendor - return "\(vendor) \(version)" - } - - var majorVersion: Int? { - let components = version - .split(whereSeparator: { !$0.isNumber }) - .compactMap { Int($0) } - switch components.first { - case 1: - return components.count > 1 ? components[1] : nil - case let major?: - return major - case nil: - return nil - } - } - - var supportsJDTLS: Bool { - majorVersion.map { $0 >= Self.minimumJDTLSMajorVersion } ?? false - } -} - -struct MavenRuntimeCandidate: Identifiable, Hashable, Sendable { - let homePath: String - let executablePath: String - let version: String - - var id: String { executablePath } - - var displayName: String { - version.isEmpty ? "Maven" : "Maven \(version)" - } -} - -struct RuntimeDiscoveryResult: Sendable { - let javaRuntimes: [JavaRuntimeCandidate] - let mavenRuntimes: [MavenRuntimeCandidate] -} - -enum JavaEnvironmentStatus: Equatable, Sendable { - case checking - case ready - case jdkMissing - case configuredJDKInvalid(path: String) - case probeFailed(message: String) - - var requiresAttention: Bool { - self != .checking && self != .ready - } - - var blocksJavaRun: Bool { - switch self { - case .jdkMissing, .configuredJDKInvalid, .probeFailed: true - case .checking, .ready: false - } - } -} - -struct JavaEnvironmentReport: Equatable, Sendable { - let status: JavaEnvironmentStatus - let projectURL: URL - let javaHomePath: String? - let javaExecutablePath: String? - - static func checking(for projectURL: URL) -> Self { - Self( - status: .checking, - projectURL: projectURL.standardizedFileURL, - javaHomePath: nil, - javaExecutablePath: nil - ) - } - - var title: String { - switch status { - case .checking: "Checking Java environment…" - case .ready: "Java environment ready" - case .jdkMissing: "JDK not found" - case .configuredJDKInvalid: "Configured JDK is invalid" - case .probeFailed: "Runtime discovery failed" - } - } - - var message: String { - switch status { - case .checking: - "Lithe is checking the project JDK." - case .ready: - "A usable JDK is available for this project." - case .jdkMissing: - "This project contains Java sources, but no usable JDK was detected." - case .configuredJDKInvalid(let path): - "The configured JDK path is not a valid JDK: \(path)" - case .probeFailed(let message): message - } - } - - var recovery: String { - switch status { - case .checking, .ready: "" - case .jdkMissing: - "Choose a JDK in Settings → Project or install a full JDK and set JAVA_HOME." - case .configuredJDKInvalid: - "Choose another JDK in Settings → Project or clear the invalid path." - case .probeFailed: - "Check the workspace connection and refresh the available runtimes." - } - } -} diff --git a/macos/Sources/Lithe/Models/Settings/AppSettings.swift b/macos/Sources/Lithe/Models/Settings/AppSettings.swift index c5b61b91be..a93f92a086 100644 --- a/macos/Sources/Lithe/Models/Settings/AppSettings.swift +++ b/macos/Sources/Lithe/Models/Settings/AppSettings.swift @@ -4,11 +4,6 @@ import LitheModuleAPI import LitheCoreContracts import LitheGitModule -enum JavaBuildFailurePolicy: String, Codable { - case ask - case alwaysContinue -} - @MainActor final class AppSettings: ObservableObject { nonisolated static let agentSelectionPreferenceKey = "lithe.agent.welcomeAgentChosen" @@ -33,7 +28,6 @@ final class AppSettings: ObservableObject { static let editorFontFamily = "settings.editorFontFamily" static let editorSoftWrap = "settings.editorSoftWrap" static let editorMinimap = "settings.editorMinimap" - static let javaKeywordNavigationFilter = "settings.javaKeywordNavigationFilter" static let projectTreeRowHeight = "settings.projectTreeRowHeight" static let tabWidth = "settings.tabWidth" static let editorTabLayoutMode = "settings.editorTabLayoutMode" @@ -78,7 +72,6 @@ final class AppSettings: ObservableObject { static let keyboardShortcutPresets = "settings.keyboardShortcutPresets" static let customLogDirectory = "settings.customLogDirectory" static let workbenchBackground = "settings.workbenchBackground" - static let javaBuildFailurePolicies = "settings.javaBuildFailurePolicies" static let processTermination = "settings.processTermination" } @@ -168,11 +161,6 @@ final class AppSettings: ObservableObject { @Published var editorSoftWrapEnabled: Bool { didSet { defaults.set(editorSoftWrapEnabled, forKey: Key.editorSoftWrap) } } - /// 跳过 Java 关键字的定义查询。关键字没有定义,但语言服务器对它们可能要等数秒; - /// 默认开启,关闭后恢复每次都向语言服务器查询的行为。 - @Published var javaKeywordNavigationFilterEnabled: Bool { - didSet { defaults.set(javaKeywordNavigationFilterEnabled, forKey: Key.javaKeywordNavigationFilter) } - } @Published var editorMinimapEnabled: Bool { didSet { defaults.set(editorMinimapEnabled, forKey: Key.editorMinimap) } } @@ -468,7 +456,6 @@ final class AppSettings: ObservableObject { private var fileVisibilityRulesObservers: [UUID: () -> Void] = [:] private var logDirectoryObservers: [UUID: (URL) -> Void] = [:] private let workbenchBackgroundSourceDidChange = PassthroughSubject() - private var javaBuildFailurePolicies: [String: JavaBuildFailurePolicy] = [:] init( store: any KeyValueStore, @@ -512,7 +499,6 @@ final class AppSettings: ObservableObject { ) editorSoftWrapEnabled = defaults.object(forKey: Key.editorSoftWrap) as? Bool ?? false editorMinimapEnabled = defaults.object(forKey: Key.editorMinimap) as? Bool ?? true - javaKeywordNavigationFilterEnabled = defaults.object(forKey: Key.javaKeywordNavigationFilter) as? Bool ?? true projectTreeRowHeight = defaults.object(forKey: Key.projectTreeRowHeight) as? Double ?? 24 editorTabLayoutMode = EditorTabLayoutMode( rawValue: defaults.string(forKey: Key.editorTabLayoutMode) ?? "" @@ -595,10 +581,6 @@ final class AppSettings: ObservableObject { .flatMap { decodeStored([String: UUID].self, from: $0, stage: "StringUUID") } ?? [:] agentAccountSnapshots = defaults.data(forKey: Key.agentAccountSnapshots) .flatMap { decodeStored([String: AgentAccountSnapshot].self, from: $0, stage: "StringAgentAccountSnapshot") } ?? [:] - if let data = defaults.data(forKey: Key.javaBuildFailurePolicies), - let saved = decodeStored([String: JavaBuildFailurePolicy].self, from: data, stage: "StringJavaBuildFailurePolicy") { - javaBuildFailurePolicies = saved - } pendingDecodeFailures = decodeFailures repairImportedAgentProviders() AppThemeRuntime.shared.activate(colorTheme) @@ -732,26 +714,6 @@ final class AppSettings: ObservableObject { terminalShellPathOverride.isEmpty ? terminalShell.path : terminalShellPathOverride } - func javaBuildFailurePolicy(for workspaceURL: URL) -> JavaBuildFailurePolicy { - javaBuildFailurePolicies[Self.javaWorkspacePreferenceKey(workspaceURL)] ?? .ask - } - - func setJavaBuildFailurePolicy(_ policy: JavaBuildFailurePolicy, for workspaceURL: URL) { - let key = Self.javaWorkspacePreferenceKey(workspaceURL) - if policy == .ask { - javaBuildFailurePolicies[key] = nil - } else { - javaBuildFailurePolicies[key] = policy - } - if let data = try? JSONEncoder().encode(javaBuildFailurePolicies) { - defaults.set(data, forKey: Key.javaBuildFailurePolicies) - } - } - - private static func javaWorkspacePreferenceKey(_ workspaceURL: URL) -> String { - workspaceURL.standardizedFileURL.resolvingSymlinksInPath().path - } - func selectTerminalShell(path: String) { terminalShell = .system terminalShellPathOverride = path @@ -851,7 +813,6 @@ final class AppSettings: ObservableObject { editorFontFamily = EditorFontDefaults.monospacedFamily editorSoftWrapEnabled = false editorMinimapEnabled = true - javaKeywordNavigationFilterEnabled = true projectTreeRowHeight = 24 editorTabLayoutMode = .singleLine showCodeVision = true @@ -895,8 +856,6 @@ final class AppSettings: ObservableObject { keyboardShortcutPreset = .macOS defaults.set(KeyboardShortcutPreset.macOS.rawValue, forKey: Key.keyboardShortcutPreset) setKeyboardShortcutOverrides([:]) - javaBuildFailurePolicies = [:] - defaults.set(nil, forKey: Key.javaBuildFailurePolicies) // All stored properties are initialized; the snapshot can now read self. updateNetworkProxyPreferences() } diff --git a/macos/Sources/Lithe/Models/Workspace/ProjectTreeLoader.swift b/macos/Sources/Lithe/Models/Workspace/ProjectTreeLoader.swift index 311820e74b..b46f345db9 100644 --- a/macos/Sources/Lithe/Models/Workspace/ProjectTreeLoader.swift +++ b/macos/Sources/Lithe/Models/Workspace/ProjectTreeLoader.swift @@ -129,8 +129,10 @@ struct ProjectTreeLoader { let key = row.url.standardizedFileURL.path guard let entries = listings[key] else { continue } // Same rule as the full-tree conversion: below a source root, - // directories are packages and single-child chains compact. - let insideSourceRoot = row.isInsideSourceRoot || LitheIcons.isSourceRootDirectory(row.url) + // directories are packages and single-child chains compact. Which + // directories are source roots comes from the row itself, never + // from guessing a language's layout by directory names. + let insideSourceRoot = row.isInsideSourceRoot result[key] = entries.enumerated().map { index, entry in if entry.isDirectory, insideSourceRoot { chains.append(CompactionChain(owner: key, index: index, tip: entry.url)) @@ -154,7 +156,7 @@ struct ProjectTreeLoader { continue } if entries.count == 1, let only = entries.first, only.isDirectory, - LitheIcons.isValidPackageName(only.url.lastPathComponent) { + LitheIcons.isPackageSegmentName(only.url.lastPathComponent) { chain.collapsed.append(chain.tip.path) chain.tip = only.url continuing.append(chain) diff --git a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildNativeConfigurationStore.swift b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildNativeConfigurationStore.swift index 067eaa4eed..a891979c44 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildNativeConfigurationStore.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildNativeConfigurationStore.swift @@ -5,7 +5,7 @@ import LitheModuleAPI /// Generic native-file boundary. The provider owns source discovery and field /// edits; this adapter owns private staging, filesystem -/// validation and conditional publication. No Maven precedence lives here. +/// validation and conditional publication. No build-tool precedence lives here. struct MacBuildNativeConfigurationStore: BuildNativeConfigurationStoring { let storage: any FileStorage let planner: any BuildSystemPlanning diff --git a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildOptionsStore.swift b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildOptionsStore.swift index cece3a2609..976980686f 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildOptionsStore.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildOptionsStore.swift @@ -17,17 +17,6 @@ final class MacBuildOptionsStore: BuildOptionsStoring { self.immutableRoots = immutableRoots } - func migrateLegacyConfiguration(workspaceURL: URL, instances: [BuildSystemInstance]) throws -> Bool { - let roots = instances.filter { - $0.pluginID == "io.github.lithe-idea.maven-build" && $0.buildSystemID == "maven" - }.map(\.root) - guard !roots.isEmpty else { return false } - let files = storage ?? MacFileStorage() - return try MacLegacyMavenConfigurationMigration(storage: files, preferences: store, - runStore: MacRunConfigurationStore(core: RustCoreBridge(), storage: files, preferences: store), - options: self, immutableRoots: immutableRoots).migrate(workspace: workspaceURL, reactorRoots: roots) - } - func options(workspaceURL: URL, buildSystemID: String) throws -> [String: ToolingJSONValue] { let shared = try projectDocument(workspaceURL).document.systems[buildSystemID]?.options ?? [:] return shared.merging(try read([String: ToolingJSONValue].self, key: Self.key(workspaceURL: workspaceURL, buildSystemID: buildSystemID)) ?? [:]) { _, local in local } diff --git a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildProviderSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildProviderSessions.swift index a2578cabe6..3f02046cd8 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildProviderSessions.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildProviderSessions.swift @@ -35,6 +35,8 @@ final class MacBuildProviderSessions: BuildProviderRequesting { private let runtime: any LanguageToolRuntimePort private let core: any LanguageServerRuntimeCore private let remoteLaunches: MacRemotePluginLaunchPreparer? + /// Resolves a provider launch that names a tool definition. + private let definedTools: MacDefinedToolchainResolver? private weak var processRegistry: (any LanguageServerProcessRegistry)? /// Ends the processes carrying a backend's token; `immediately` skips the /// graceful stop. See `MacPluginBackendProcesses`. @@ -66,6 +68,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { core: any LanguageServerRuntimeCore, processRegistry: (any LanguageServerProcessRegistry)?, remoteLaunches: MacRemotePluginLaunchPreparer? = nil, + definedTools: MacDefinedToolchainResolver? = nil, stuckSendGrace: Duration = .seconds(2), endBackendProcesses: @escaping @MainActor (_ token: String, _ immediately: Bool) -> Void = { token, immediately in MacPluginBackendProcesses.end( @@ -80,6 +83,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { self.runtime = runtime self.core = core self.remoteLaunches = remoteLaunches + self.definedTools = definedTools self.processRegistry = processRegistry self.endBackendProcesses = endBackendProcesses self.stuckSendGrace = stuckSendGrace @@ -308,7 +312,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { entry: Running, owner: MacRemotePluginLaunchPreparer.Owner? ) async throws -> LanguageServerRuntimeSession { - var (executableURL, environment) = try await resolveExecutable(process, workspaceURL: target.workspaceURL) + var (executableURL, arguments, environment) = try await resolveExecutable(process, workspaceURL: target.workspaceURL) try Task.checkCancellation() guard running[target] === entry, owner?.isCurrent() != false else { throw CancellationError() } // Every process the backend starts inherits this token, so what it @@ -318,7 +322,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { let session = LanguageServerRuntimeSession( providerID: "buildProvider:\(target.pluginID):\(target.buildSystemID)", executableURL: executableURL, - arguments: process.arguments, + arguments: arguments, environment: environment, initializationOptions: process.initializationOptions, initializeTimeout: 60, @@ -371,7 +375,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { } } do { - try session.start(rootURL: rootURL, workspaceFingerprint: nil) + try session.start(rootURL: rootURL) } catch { finish(.failure(error)) } @@ -380,20 +384,35 @@ final class MacBuildProviderSessions: BuildProviderRequesting { /// A packaged file starts as it is. Commands and runtimes resolve through /// the build tool discovery, so the provider sees the same runtime and - /// `PATH` as the build system's commands. + /// `PATH` as the build system's commands. A tool launch resolves its + /// definitions and takes the command line their template expands to; + /// every other launch keeps the plan's arguments. private func resolveExecutable( _ process: MacPluginLanguageServerLaunchResolver.BuildProviderProcess, workspaceURL: URL - ) async throws -> (URL, [String: String]) { + ) async throws -> (URL, [String], [String: String]) { let runtimes = process.runtimeTools.map { BuildInvocation.RuntimeDependency(id: $0, hostManaged: true) } let invocation: BuildInvocation var requirement: LanguageServerExecutableVersionRequirement? switch process.executable { + case .tool(let launch): + guard remoteLaunches?.identity(workspaceURL) == nil, let definedTools else { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "A build provider that names a tool definition cannot start in this workspace." + ) + } + let command = try await definedTools.command( + for: launch, arguments: process.arguments, workspace: workspaceURL, + environment: runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools), + projectCodeAllowed: process.executesProjectCode + ) + return (command.executableURL, command.arguments, command.environment) case .file(let url): if remoteLaunches?.identity(workspaceURL) == nil { - return (url, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) + return (url, process.arguments, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) } invocation = BuildInvocation(executables: [.setting(id: "pluginPackage", path: url.path)], runtimeDependencies: runtimes) case .commands(let commands): @@ -421,7 +440,7 @@ final class MacBuildProviderSessions: BuildProviderRequesting { return BuildVersionCheck(satisfied: check.satisfied, version: check.version) } ) - return (resolved.executableURL, resolved.environment) + return (resolved.executableURL, process.arguments, resolved.environment) } private func prepareLaunch(_ target: BuildProviderTarget) async throws -> ( diff --git a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildToolResolver.swift b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildToolResolver.swift index 30cb40bb8a..13baab94fc 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildToolResolver.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Build/MacBuildToolResolver.swift @@ -6,7 +6,8 @@ import LitheCoreContracts /// Picks the executable of a build-system run from the candidates Rust Core /// ordered. Runtimes come first, so a tool found through them sees the -/// same `JAVA_HOME` and `PATH` its probe ran with. +/// same `PATH`, and the variables a selected tool definition exports, that +/// its probe ran with. /// /// Bare commands resolve through the host's tool discovery, never to a /// project-local copy: only a declared `projectFile` candidate may run code @@ -60,6 +61,10 @@ final class MacBuildToolResolver: BuildToolResolving { guard runtime.projectURL == workspaceURL.standardizedFileURL else { throw CancellationError() } } var environment = runtime.processEnvironment() + // Variables the selected runtimes contribute, such as a tool + // definition's exports, reach the provider even when the host + // process already has the same value. + var contributed: Set = [] var runtimeExecutables: [String: URL] = [:] for dependency in invocation.runtimeDependencies { runtimeExecutables[dependency.id] = try await resolveRuntime( @@ -67,6 +72,7 @@ final class MacBuildToolResolver: BuildToolResolving { invocation: invocation, workspaceURL: workspaceURL, environment: &environment, + contributed: &contributed, checkVersion: checkVersion ) } @@ -82,17 +88,20 @@ final class MacBuildToolResolver: BuildToolResolving { case .resolved(let choices): for choice in choices { var selectedEnvironment = environment.merging(choice.environment) { _, selected in selected } + let selectedContributed = contributed.union(choice.environment.keys) if choice.terminal { let directory = choice.url.deletingLastPathComponent().path let paths = (selectedEnvironment["PATH"] ?? "").split(separator: ":").map(String.init) selectedEnvironment["PATH"] = ([directory] + paths.filter { $0 != directory }).joined(separator: ":") } if choice.executesProjectCode { - return resolved(choice.url, environment: selectedEnvironment, projectCode: true, version: nil) + return resolved(choice.url, environment: selectedEnvironment, contributed: selectedContributed, + projectCode: true, version: nil) } do { if let tool = try await accept(choice.url, invocation: invocation, environment: selectedEnvironment, - workspaceURL: workspaceURL, checkVersion: checkVersion, problems: &problems) { return tool } + contributed: selectedContributed, workspaceURL: workspaceURL, + checkVersion: checkVersion, problems: &problems) { return tool } } catch is CancellationError { throw CancellationError() } catch { throw BuildToolResolutionError(error.localizedDescription, terminal: choice.terminal) } if choice.terminal { throw BuildToolResolutionError(Self.unavailableMessage(displayName, problems: problems), terminal: true) } @@ -102,43 +111,6 @@ final class MacBuildToolResolver: BuildToolResolving { throw BuildToolResolutionError(Self.unavailableMessage(displayName, problems: problems)) } - /// Project import needs the installation path for global settings, but - /// must not run build code or a version probe merely by opening a project. - func languageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) -> URL? { - guard registry?.contains(workspaceURL) != true else { return nil } - let environment = runtime.processEnvironment() - let resolver = candidateResolver([:], workspaceURL: workspaceURL, passive: true) - for candidate in invocation.executables { - // No runtime selection or version probes during passive import. - switch resolver.resolve(candidate, workspaceURL: workspaceURL, environment: environment, environmentInputs: invocation.environmentInputs) { - case .skip: continue - case .terminalFailure: return nil - case .resolved(let choices): return choices.first?.url - } - } - return nil - } - - func prepareLanguageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) async throws -> URL? { - guard registry?.contains(workspaceURL) == true else { - return languageImportExecutable(invocation, workspaceURL: workspaceURL) - } - try Task.checkCancellation() - guard runtime.projectURL == workspaceURL.standardizedFileURL else { throw CancellationError() } - let environment = runtime.processEnvironment() - let resolver = try await preparedResolver([:], candidates: invocation.executables, - workspaceURL: workspaceURL, environment: environment, consumerID: invocation.toolConsumerID) - for candidate in invocation.executables { - switch resolver.resolve(candidate, workspaceURL: workspaceURL, environment: environment, - environmentInputs: invocation.environmentInputs) { - case .skip: continue - case .terminalFailure: return nil - case .resolved(let choices): return choices.first?.url - } - } - return nil - } - private func preparedResolver( _ runtimes: [String: URL], candidates: [ExecutableCandidate], workspaceURL: URL, environment: [String: String], minimumVersion: String? = nil, @@ -216,8 +188,9 @@ final class MacBuildToolResolver: BuildToolResolving { commands: { [self] in commandCandidates($0) }, runtimes: { runtimes[$0] }, toolchains: { [self] id, root in if let selected = definitions[id + "\n" + root] { return selected } - guard runtime.reloadSettings() else { return .terminalFailure(runtime.settingsError ?? "") } - let options = runtime.settings.overlay(onto: RunOptions(), workspaceRelativePath: root) + // Per-tool choices come from plugin-defined tool definitions and + // the Run document; the host keeps no language-specific defaults. + let options = RunOptions() let project = root == "." ? workspaceURL : workspaceURL.appendingPathComponent(root) do { let tool: ResolvedRunToolchain @@ -250,12 +223,13 @@ final class MacBuildToolResolver: BuildToolResolving { _ url: URL, invocation: BuildInvocation, environment: [String: String], + contributed: Set, workspaceURL: URL, checkVersion: @escaping @Sendable (String?, String) throws -> BuildVersionCheck, problems: inout [String] ) async throws -> ResolvedBuildTool? { guard let arguments = invocation.versionArguments, let minimum = invocation.minimumVersion else { - return resolved(url, environment: environment, projectCode: false, version: nil) + return resolved(url, environment: environment, contributed: contributed, projectCode: false, version: nil) } let output = try await probe(url, arguments: arguments, environment: environment, workspaceURL: workspaceURL) let check = try checkVersion(nil, output) @@ -263,32 +237,37 @@ final class MacBuildToolResolver: BuildToolResolving { problems.append(Self.tooOldMessage(url.path, found: check.version, minimum: minimum)) return nil } - return resolved(url, environment: environment, projectCode: false, version: check.version) + return resolved(url, environment: environment, contributed: contributed, projectCode: false, version: check.version) } - private func resolved(_ url: URL, environment: [String: String], projectCode: Bool, version: String?) -> ResolvedBuildTool { + private func resolved( + _ url: URL, environment: [String: String], contributed: Set, projectCode: Bool, version: String? + ) -> ResolvedBuildTool { let base = runtime.processEnvironment() - let inputs = environment.filter { key, value in key == "JAVA_HOME" || key == "PATH" || base[key] != value } + let inputs = environment.filter { key, value in key == "PATH" || contributed.contains(key) || base[key] != value } return ResolvedBuildTool(executableURL: url, environment: environment, executesProjectCode: projectCode, version: version, providerEnvironment: inputs) } - /// Resolves one runtime and puts it first on `PATH`. `java`, `node`, and - /// `go` follow the user's runtime settings; any other runtime is found - /// through the candidates it declares. + /// Resolves one runtime and puts it first on `PATH`. Host-managed + /// runtimes follow the user's runtime settings. A runtime the plugin does + /// not describe arrives from Core as the toolchain candidate of the tool + /// definition with its ID, which checks `minimumVersion` and whose + /// exports join the environment; any other runtime is found through the + /// candidates it declares. private func resolveRuntime( _ dependency: BuildInvocation.RuntimeDependency, invocation: BuildInvocation, workspaceURL: URL, environment: inout [String: String], + contributed: inout Set, checkVersion: @escaping @Sendable (String?, String) throws -> BuildVersionCheck ) async throws -> URL { let name = dependency.displayName ?? dependency.id - let javaHome = dependency.hostManaged && dependency.id == "java" && dependency.executables.isEmpty ? runtime.javaHomeURL() : nil let sources: [ExecutableCandidate] = dependency.hostManaged && dependency.executables.isEmpty - ? (dependency.id == "java" ? [.runtime("java")] : [.command(dependency.id)]) + ? [.command(dependency.id)] : dependency.executables - let resolver = try await preparedResolver(javaHome.map { ["java": $0.appendingPathComponent("bin/java")] } ?? [:], + let resolver = try await preparedResolver([:], candidates: sources, workspaceURL: workspaceURL, environment: environment, minimumVersion: dependency.minimumVersion, selections: invocation.toolSelections, use: .installation, consumerID: invocation.toolConsumerID) var problems: [String] = [] @@ -302,7 +281,6 @@ final class MacBuildToolResolver: BuildToolResolving { // next to a selected runtime. Failed candidates must not // contribute their environment to the next choice. var selectedEnvironment = environment.merging(choice.environment) { _, selected in selected } - if let javaHome { selectedEnvironment["JAVA_HOME"] = javaHome.path } let directory = choice.url.deletingLastPathComponent().path let path = selectedEnvironment["PATH"] ?? "" selectedEnvironment["PATH"] = path.isEmpty ? directory : directory + ":" + path @@ -319,6 +297,7 @@ final class MacBuildToolResolver: BuildToolResolving { } } environment = selectedEnvironment + contributed.formUnion(choice.environment.keys) return choice.url } } diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPerformanceSampler.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPerformanceSampler.swift index 4c69023ed3..db710a6d1f 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPerformanceSampler.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPerformanceSampler.swift @@ -1,164 +1,10 @@ -import LitheModuleAPI import Foundation -import LitheCoreContracts -/// OpenJDK jstat owns the JVM counters. This adapter only parses its documented -/// -gc columns and combines them with CPU time for the exact launched process. +/// Samples CPU and resident memory for the process tree the debug session +/// launched. The counters are native, so the sampler needs no language runtime +/// tool and no helper process. struct MacDebugPerformanceSampler: DebugPerformanceSampling { - let processRegistry: ManagedProcessRegistry? - var logSink: (any LogSink)? = nil - func samples(for target: DebugPerformanceTarget) -> AsyncThrowingStream { - if target.javaExecutable == nil { - return MacProcessTreePerformanceSampler.samples(processID: target.processID) - } - return AsyncThrowingStream(bufferingPolicy: .bufferingNewest(1)) { continuation in - let session = MacDebugPerformanceSession(target: target, registry: processRegistry, logSink: logSink, continuation: continuation) - continuation.onTermination = { _ in session.stop() } - session.start() - } - } -} - -struct JStatHeapParser { - private var header: [Substring] = [] - private var pending = "" - - mutating func append(_ chunk: String) throws -> [(uptime: Double, used: UInt64, committed: UInt64)] { - pending += chunk - guard pending.utf8.count <= 16_384 else { throw DebugPerformanceError.unavailable("Invalid JVM performance output.") } - var samples: [(Double, UInt64, UInt64)] = [] - while let end = pending.firstIndex(of: "\n") { - let line = String(pending[.. Double? { - guard let index = header.firstIndex(of: Substring(key)), let number = Double(fields[index]), number.isFinite, number >= 0 else { return nil } - return number - } - guard let time = value("Timestamp") else { continue } - let used = ["S0U", "S1U", "EU", "OU"].compactMap(value) - let committed = ["S0C", "S1C", "EC", "OC"].compactMap(value) - guard used.count == 4, committed.count == 4 else { - throw DebugPerformanceError.unavailable("The JVM does not expose supported heap counters through jstat.") - } - let usedBytes = used.reduce(0, +) * 1024 - let committedBytes = committed.reduce(0, +) * 1024 - guard usedBytes < Double(UInt64.max), committedBytes < Double(UInt64.max), usedBytes <= committedBytes else { - throw DebugPerformanceError.unavailable("Invalid JVM heap counters.") - } - samples.append((time, UInt64(usedBytes), UInt64(committedBytes))) - } - return samples - } -} - -private final class MacDebugPerformanceSession: @unchecked Sendable { - private let lock = NSLock() - private let target: DebugPerformanceTarget - private let process: MacStreamingProcess - private var continuation: AsyncThrowingStream.Continuation? - private var parser = JStatHeapParser() - private let cpuSampler = MacProcessMemorySampler() - private var previousCPU: UInt64? - private var previousTime: UInt64? - private var identity: (UInt64, UInt64)? - private var lastSampleTime = DispatchTime.now().uptimeNanoseconds - private var diagnostic = "" - private var watchdog: DispatchSourceTimer? - - init(target: DebugPerformanceTarget, registry: ManagedProcessRegistry?, logSink: (any LogSink)?, - continuation: AsyncThrowingStream.Continuation) { - self.target = target - process = MacStreamingProcess(processRegistry: registry, moduleID: .debug, logSink: logSink) - self.continuation = continuation - } - - func start() { - lock.lock() - guard continuation != nil else { lock.unlock(); return } - guard let executable = target.javaExecutable else { lock.unlock(); finish(nil); return } - let tool = executable.deletingLastPathComponent().appendingPathComponent("jstat") - guard target.processID > 0, executable.lastPathComponent == "java", - FileManager.default.isExecutableFile(atPath: tool.path), - let cpu = cpuSampler.cpuSnapshot(for: target.processID) else { - lock.unlock() - finish(DebugPerformanceError.unavailable("A running local JVM and its JDK jstat tool are required.")); return - } - identity = (cpu.startedSeconds, cpu.startedMicroseconds) - previousCPU = cpu.nanoseconds - previousTime = DispatchTime.now().uptimeNanoseconds - process.onOutput = { [weak self] chunk in self?.receive(chunk) } - process.onTermination = { [weak self] code in - guard let self else { return } - let message = lock.withLock { self.diagnostic } - finish(code == 0 ? nil : DebugPerformanceError.unavailable(message.isEmpty ? "JVM performance monitoring ended." : message)) - } - let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility)) - timer.schedule(deadline: .now() + 2, repeating: 2) - timer.setEventHandler { [weak self] in - guard let self else { return } - let stalled = lock.withLock { DispatchTime.now().uptimeNanoseconds - self.lastSampleTime > 10_000_000_000 } - if stalled { finish(DebugPerformanceError.unavailable("No JVM performance samples received for 10 seconds.")) } - } - watchdog = timer - timer.resume() - var startError: Error? - do { - var environment = ProcessInfo.processInfo.environment - environment["LC_ALL"] = "C" - try process.start(ProcessRequest(executablePath: tool.path, - arguments: ["-gc", "-t", String(target.processID), "1000"], environment: environment)) - } catch { startError = error } - lock.unlock() - if let startError { finish(startError) } - } - - private func receive(_ chunk: String) { - var output: [DebugPerformanceSample] = [] - var failure: Error? - let destination = lock.withLock { () -> AsyncThrowingStream.Continuation? in - guard let continuation else { return nil } - do { - for heap in try parser.append(chunk) { - guard let cpu = cpuSampler.cpuSnapshot(for: target.processID), - let identity, identity.0 == cpu.startedSeconds, identity.1 == cpu.startedMicroseconds else { - throw DebugPerformanceError.unavailable("The monitored JVM has exited or changed.") - } - let now = DispatchTime.now().uptimeNanoseconds - var percent: Double? - if let previousCPU, let previousTime, now > previousTime, cpu.nanoseconds >= previousCPU { - percent = min(100, Double(cpu.nanoseconds - previousCPU) / Double(now - previousTime) - / Double(max(1, ProcessInfo.processInfo.activeProcessorCount)) * 100) - } - previousCPU = cpu.nanoseconds; previousTime = now; lastSampleTime = now - output.append(DebugPerformanceSample(timestamp: heap.uptime, cpuPercent: percent, - memoryUsedBytes: heap.used, memoryCapacityBytes: heap.committed)) - } - if output.isEmpty { diagnostic = String((diagnostic + chunk).suffix(1024)) } - else { diagnostic = "" } - } catch { failure = error } - return continuation - } - if let failure { finish(failure); return } - for sample in output { destination?.yield(sample) } - } - - func stop() { finish(nil) } - - private func finish(_ error: Error?) { - let (destination, timer) = lock.withLock { () -> (AsyncThrowingStream.Continuation?, DispatchSourceTimer?) in - let destination = continuation - continuation = nil - let timer = watchdog - watchdog = nil - return (destination, timer) - } - guard let destination else { return } - timer?.cancel() - process.stop() - destination.finish(throwing: error) + MacProcessTreePerformanceSampler.samples(processID: target.processID) } } diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPortAvailabilityChecker.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPortAvailabilityChecker.swift index 131ee814d4..3b124651c8 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPortAvailabilityChecker.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Debug/MacDebugPortAvailabilityChecker.swift @@ -26,7 +26,8 @@ final class MacDebugPortAvailabilityChecker: DebugPortAvailabilityChecking { return UInt16(bigEndian: address.sin_port) } - /// A bind probe does not connect to or resume a suspended JDWP VM. The + /// A bind probe does not connect to or resume a debuggee that is suspended + /// waiting for its debugger. The /// operation guard also ends the wait when its owning process exits. func waitForLoopbackListener(_ port: UInt16, processID: @escaping @MainActor () -> Int32?, isCurrent: @escaping @MainActor () -> Bool) async throws { let clock = ContinuousClock(), deadline = ContinuousClock.now.advanced(by: .seconds(120)) @@ -44,7 +45,7 @@ final class MacDebugPortAvailabilityChecker: DebugPortAvailabilityChecking { guard isCurrent() else { throw CancellationError() } try await clock.sleep(for: .milliseconds(100)) } - throw RunConfigurationOperationFailure(message: L10n.string("The framework did not open its JVM debug port before the deadline. Check the Run output.")) + throw RunConfigurationOperationFailure(message: L10n.string("The program did not open its debug port before the deadline. Check the Run output.")) } func isPortAvailable(_ port: Int) -> Bool { diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacHostedPortDebugAdapterTransport.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacHostedPortDebugAdapterTransport.swift index e9ef7bca89..97786ef38f 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacHostedPortDebugAdapterTransport.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Debug/MacHostedPortDebugAdapterTransport.swift @@ -3,9 +3,9 @@ import Foundation import LitheCoreContracts /// Connects the macOS product to a debug adapter hosted inside a language -/// server, such as the Java Debug Server inside JDT LS. Language server -/// activation stays in the language module and DAP state stays in Core; this -/// transport owns only asynchronous port discovery and the native TCP socket. +/// server process. Language server activation stays in the language module and +/// DAP state stays in Core; this transport owns only asynchronous port +/// discovery and the native TCP socket. @MainActor final class MacHostedPortDebugAdapterTransport: DebugAdapterDrainingTransport { enum TransportError: LocalizedError { @@ -61,7 +61,7 @@ final class MacHostedPortDebugAdapterTransport: DebugAdapterDrainingTransport { }, core: core, logSink: logSink, deadlineScheduler: deadlineScheduler, - // A cold JDT/project import is endpoint discovery, not a TCP + // A cold project import in the hosting language server is endpoint discovery, not a TCP // connect. Keep it bounded without applying the direct-host budget; // the connect to the discovered port keeps the default short budget. limits: .init(discoveryMilliseconds: 120_000), diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacJavaTestResultServer.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacJavaTestResultServer.swift deleted file mode 100644 index a03bad8836..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacJavaTestResultServer.swift +++ /dev/null @@ -1,230 +0,0 @@ -import LitheModuleAPI -import Foundation -import Network - -enum MacJavaTestResultListenerState { - case ready(port: UInt16) - case failed(message: String) - case cancelled -} - -protocol MacJavaTestResultListening: AnyObject { - var onStateChange: ((MacJavaTestResultListenerState) -> Void)? { get set } - var onConnection: ((NWConnection) -> Void)? { get set } - - func start(queue: DispatchQueue) - func cancel() -} - -final class MacJavaTestResultNetworkListener: MacJavaTestResultListening { - var onStateChange: ((MacJavaTestResultListenerState) -> Void)? - var onConnection: ((NWConnection) -> Void)? - - private let listener: NWListener - - init() throws { - let parameters = NWParameters.tcp - parameters.requiredLocalEndpoint = .hostPort( - host: NWEndpoint.Host("127.0.0.1"), - port: .any - ) - listener = try NWListener(using: parameters) - listener.stateUpdateHandler = { [weak self] state in - guard let self else { return } - switch state { - case .ready: - guard let port = listener.port?.rawValue else { - onStateChange?(.failed(message: "No listening port was assigned.")) - return - } - onStateChange?(.ready(port: port)) - case .failed(let error): - onStateChange?(.failed(message: error.localizedDescription)) - case .cancelled: - onStateChange?(.cancelled) - default: - break - } - } - listener.newConnectionHandler = { [weak self] connection in - self?.onConnection?(connection) - } - } - - func start(queue: DispatchQueue) { - listener.start(queue: queue) - } - - func cancel() { - listener.cancel() - } -} - -/// Owns the loopback listener used by one Java test debug launch. The listener -/// is created on demand, accepts one runner connection, drains it, and releases -/// all native resources when the runner exits or the launch is cancelled. -@MainActor -final class MacJavaTestResultServer: JavaTestResultServing { - enum ServerError: LocalizedError { - case startupFailed(String) - case startupTimedOut - - var errorDescription: String? { - switch self { - case .startupFailed(let message): - L10n.string("Could not start the Java test result listener: \(message)") - case .startupTimedOut: - L10n.string("The Java test result listener did not become ready in time.") - } - } - } - - private let queue = DispatchQueue(label: "app.lithe.debug.java-test-results") - private let startupTimeout: Duration - private let listenerFactory: () throws -> any MacJavaTestResultListening - private var listener: (any MacJavaTestResultListening)? - private var connections: [ObjectIdentifier: NWConnection] = [:] - private var startupContinuation: CheckedContinuation? - private var startupDeadlineTask: Task? - private var generation = UUID() - - init( - startupTimeout: Duration = .seconds(5), - listenerFactory: @escaping () throws -> any MacJavaTestResultListening = { - try MacJavaTestResultNetworkListener() - } - ) { - self.startupTimeout = startupTimeout - self.listenerFactory = listenerFactory - } - - func start() async throws -> UInt16 { - stop() - let listener: any MacJavaTestResultListening - do { - listener = try listenerFactory() - } catch { - throw ServerError.startupFailed(error.localizedDescription) - } - self.listener = listener - generation = UUID() - let currentGeneration = generation - listener.onStateChange = { [weak self] state in - Task { @MainActor [weak self] in - self?.consume(state, generation: currentGeneration) - } - } - listener.onConnection = { [weak self] connection in - Task { @MainActor [weak self] in - self?.accept(connection, generation: currentGeneration) - } - } - return try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - startupContinuation = continuation - listener.start(queue: queue) - startDeadline(generation: currentGeneration) - } - } onCancel: { [weak self] in - Task { @MainActor [weak self] in self?.stop() } - } - } - - func stop() { - generation = UUID() - startupDeadlineTask?.cancel() - startupDeadlineTask = nil - listener?.cancel() - listener = nil - for connection in connections.values { connection.cancel() } - connections = [:] - startupContinuation?.resume(throwing: CancellationError()) - startupContinuation = nil - } - - private func startDeadline(generation: UUID) { - let clock = ContinuousClock() - let deadline = clock.now.advanced(by: startupTimeout) - startupDeadlineTask = Task { [weak self] in - do { - try await clock.sleep(until: deadline) - // log-exempt: 用户取消:停止结果监听时取消启动期限等待 - } catch { - return - } - guard !Task.isCancelled else { return } - await MainActor.run { [weak self] in - guard let self, self.generation == generation else { return } - self.failStartup(ServerError.startupTimedOut) - } - } - } - - private func consume(_ state: MacJavaTestResultListenerState, generation: UUID) { - guard self.generation == generation else { return } - switch state { - case .ready(let port): - startupDeadlineTask?.cancel() - startupDeadlineTask = nil - startupContinuation?.resume(returning: port) - startupContinuation = nil - case .failed(let message): - failStartup(ServerError.startupFailed(message)) - case .cancelled: - break - } - } - - private func failStartup(_ error: Error) { - startupDeadlineTask?.cancel() - startupDeadlineTask = nil - listener?.cancel() - listener = nil - startupContinuation?.resume(throwing: error) - startupContinuation = nil - } - - private func accept(_ connection: NWConnection, generation: UUID) { - guard self.generation == generation else { - connection.cancel() - return - } - // One Java test process owns the result channel. Stop accepting new - // peers after it connects, but keep the accepted socket alive. - listener?.cancel() - listener = nil - let identifier = ObjectIdentifier(connection) - connections[identifier] = connection - connection.stateUpdateHandler = { [weak self, weak connection] state in - guard let connection else { return } - switch state { - case .failed, .cancelled: - Task { @MainActor [weak self] in self?.remove(connection) } - default: - break - } - } - connection.start(queue: queue) - receiveNext(from: connection) - } - - private func receiveNext(from connection: NWConnection) { - connection.receive(minimumIncompleteLength: 1, maximumLength: 1_048_576) { - [weak self, weak connection] _, _, isComplete, error in - guard let self, let connection else { return } - Task { @MainActor [weak self] in - guard let self else { return } - if error != nil || isComplete { - self.remove(connection) - } else { - self.receiveNext(from: connection) - } - } - } - } - - private func remove(_ connection: NWConnection) { - connections[ObjectIdentifier(connection)] = nil - connection.cancel() - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacPluginDebugAdapterTransport.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacPluginDebugAdapterTransport.swift index 612f0319ba..70981ae647 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacPluginDebugAdapterTransport.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Debug/MacPluginDebugAdapterTransport.swift @@ -126,7 +126,7 @@ final class MacPluginDebugAdapterTransport: DebugAdapterDrainingTransport, Debug throw TransportError.commandNotFound(adapterID: adapterID, commands: commands) } executableURL = url - case .runtime: + case .runtime, .tool: throw TransportError.unsupportedExecutable(adapterID: adapterID) } return MacProcessDebugAdapterTransport( diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacProcessTreePerformanceSampler.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacProcessTreePerformanceSampler.swift index edaea5d4bc..e4ef7fc2ec 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacProcessTreePerformanceSampler.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Debug/MacProcessTreePerformanceSampler.swift @@ -1,7 +1,7 @@ import Foundation -/// Native CPU and RSS for a launched root and its descendants (including Maven's -/// forked test JVMs). No JVM attach, process-name scan, or helper process is needed. +/// Native CPU and RSS for a launched root and its descendants (including worker +/// processes it forks). No runtime attach, process-name scan, or helper process is needed. enum MacProcessTreePerformanceSampler { struct CPU: Equatable { let nanoseconds: UInt64 diff --git a/macos/Sources/Lithe/Platform/MacOS/Debug/MacTestJVMPerformance.swift b/macos/Sources/Lithe/Platform/MacOS/Debug/MacTestJVMPerformance.swift deleted file mode 100644 index 1bf85ed654..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Debug/MacTestJVMPerformance.swift +++ /dev/null @@ -1,200 +0,0 @@ -import LitheModuleAPI -import Darwin -import Foundation - -@_silgen_name("proc_pidpath") -private func lithePerformancePIDPath(_ pid: Int32, _ buffer: UnsafeMutableRawPointer, _ size: UInt32) -> Int32 - -/// Only known upstream test launchers descended from the exact owned root are -/// eligible. Maven/Gradle build daemons are not used as a substitute for tests. -struct MacTestJVMPerformance: TestJVMPerformanceProviding { - let processRegistry: ManagedProcessRegistry? - var logSink: (any LogSink)? = nil - - static func javaExecutable(processID: Int32) -> URL? { - var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN)) - guard lithePerformancePIDPath(processID, &path, UInt32(path.count)) > 0 else { return nil } - let url = URL(fileURLWithPath: String(cString: path)) - return url.lastPathComponent == "java" ? url : nil - } - - // ponytail: Only public JUnit/TestNG/Surefire/Gradle worker entry points are - // recognized. Custom/in-process runners stay unavailable; replace this - // classifier when execution providers expose exact worker identities. - static func isTestWorker(arguments: [String]) -> Bool { - // DefaultWorkerProcessBuilder appends a quoted display name as the final argument. - let name = arguments.last?.trimmingCharacters(in: CharacterSet(charactersIn: "'")) ?? "" - let gradleTest = name.hasPrefix("Gradle Test Executor ") - && Int(name.dropFirst("Gradle Test Executor ".count)).map { $0 > 0 } == true - return arguments.contains { argument in - argument == "com.intellij.rt.junit.JUnitStarter" - || argument == "org.junit.platform.console.ConsoleLauncher" - || argument == "org.testng.TestNG" - || argument == "com.intellij.rt.testng.RemoteTestNGStarter" - || (URL(fileURLWithPath: argument).lastPathComponent.hasPrefix("junit-platform-console-standalone") && argument.hasSuffix(".jar")) - || (argument.hasSuffix(".GradleWorkerMain") && gradleTest) - || argument == "org.apache.maven.surefire.booter.ForkedBooter" - || (URL(fileURLWithPath: argument).lastPathComponent.hasPrefix("surefirebooter") && argument.hasSuffix(".jar")) - } - } - - private static func arguments(processID: Int32) -> [String] { - var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, processID] - var size = 1_048_576 - var bytes = [UInt8](repeating: 0, count: size) - guard sysctl(&mib, UInt32(mib.count), &bytes, &size, nil, 0) == 0, size > 4 else { return [] } - let count = bytes.withUnsafeBytes { $0.loadUnaligned(as: Int32.self) } - guard count > 0, count <= 65_536 else { return [] } - var index = 4 - while index < size && bytes[index] != 0 { index += 1 } - while index < size && bytes[index] == 0 { index += 1 } - var result: [String] = [] - for _ in 0.. AsyncThrowingStream<[TestJVMProcess], Error> { - AsyncThrowingStream(bufferingPolicy: .bufferingNewest(1)) { continuation in - let task = Task.detached(priority: .utility) { - let sampler = MacProcessMemorySampler() - guard let root = sampler.cpuSnapshot(for: rootProcessID) else { continuation.finish(); return } - while !Task.isCancelled { - guard let identity = sampler.cpuSnapshot(for: rootProcessID), - identity.startedSeconds == root.startedSeconds, - identity.startedMicroseconds == root.startedMicroseconds else { break } - let owned = sampler.descendantProcessIDs(of: [rootProcessID]) - let all = owned.compactMap { pid -> TestJVMProcess? in - guard let java = Self.javaExecutable(processID: pid), - Self.isTestWorker(arguments: Self.arguments(processID: pid)), - let cpu = sampler.cpuSnapshot(for: pid) else { return nil } - return TestJVMProcess(processID: pid, javaExecutable: java, - startedSeconds: cpu.startedSeconds, startedMicroseconds: cpu.startedMicroseconds) - }.sorted { $0.processID < $1.processID } - continuation.yield(all) - // log-exempt: 用户取消:调用方取消采样或超时等待时结束任务 - do { try await Task.sleep(for: .seconds(1)) } catch { break } - } - continuation.finish() - } - continuation.onTermination = { _ in task.cancel() } - } - } - - private func validate(_ process: TestJVMProcess) throws { - let cpu = MacProcessMemorySampler().cpuSnapshot(for: process.processID) - guard cpu?.startedSeconds == process.startedSeconds, - cpu?.startedMicroseconds == process.startedMicroseconds, - Self.javaExecutable(processID: process.processID) == process.javaExecutable else { - throw DebugPerformanceError.unavailable("The selected test JVM has exited or changed.") - } - } - - func startRecording(_ process: TestJVMProcess) async throws -> TestJVMRecording { - try validate(process) - let id = UUID() - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-jfr-\(id.uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) - let recording = TestJVMRecording(id: id, process: process, - fileURL: directory.appendingPathComponent("recording.jfr"), startedAt: Date()) - do { - _ = try await command(process.javaExecutable, tool: "jcmd", arguments: [String(process.processID), "JFR.start", - "name=\(recording.name)", "settings=profile", "filename=\(Self.quoted(recording.fileURL.path))", - "dumponexit=true", "maxsize=64m", "duration=120s"]) - try validate(process) - try Task.checkCancellation() - return recording - } catch { - // Cleanup must survive cancellation of the request that started JFR. - await Task { - // This unique recording name can only belong to this request, - // including a start/exit race after the initial identity check. - do { _ = try await command(process.javaExecutable, tool: "jcmd", - arguments: [String(process.processID), "JFR.stop", "name=\(recording.name)"]) } - catch { logSink?.emit(AppStorageMaintenanceFailed(error: LogFailure(domain: "debug.recording", code: error is CancellationError ? "cancelled" : "stop_failed"), stage: "recording-stop")) } - await discard(recording) - }.value - throw error - } - } - - func stopRecording(_ recording: TestJVMRecording) async throws { - // The JVM's dumponexit owns the final file if it has already exited. - if (try? validate(recording.process)) != nil { - _ = try await command(recording.process.javaExecutable, tool: "jcmd", - arguments: [String(recording.process.processID), "JFR.stop", "name=\(recording.name)"]) - } - } - - func report(_ recording: TestJVMRecording) async throws -> String { - let size = try recording.fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 - guard size > 0, size <= 80 * 1024 * 1024 else { - throw DebugPerformanceError.unavailable("No completed JFR recording is available.") - } - let java = recording.process.javaExecutable - let summary = try await command(java, tool: "jfr", arguments: ["summary", recording.fileURL.path]) - var result = "JDK Flight Recorder\n\n\(summary)\n" - for view in ["hot-methods", "allocation-by-site"] { - do { - result += "\n\(view)\n\n" + (try await command(java, tool: "jfr", - arguments: ["view", "--width", "140", "--truncate", "end", view, recording.fileURL.path])) - } catch { - try Task.checkCancellation() - // JDKs before 21 can record JFR but do not provide `jfr view`. - result += "\n\(view): \(error.localizedDescription)\n" - } - } - return result - } - - func discard(_ recording: TestJVMRecording) async { - do { try await stopRecording(recording) } - catch { logSink?.emit(AppStorageMaintenanceFailed(error: LogFailure(domain: "debug.recording", code: error is CancellationError ? "cancelled" : "stop_failed"), stage: "recording-stop")) } - let expected = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-jfr-\(recording.id.uuidString)") - guard recording.fileURL.standardizedFileURL == expected.appendingPathComponent("recording.jfr").standardizedFileURL else { return } - do { try FileManager.default.removeItem(at: expected) } - catch let error as CocoaError where error.code == .fileNoSuchFile { /* Recording never produced a file. */ } - catch { logSink?.emit(AppStorageMaintenanceFailed(error: error, stage: "recording-remove")) } - } - - /// jcmd parses a diagnostic command after OS argv; quote that grammar rather - /// than introducing a shell. Paths containing apostrophes use double quotes. - static func quoted(_ path: String) -> String { - "\"" + path.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" - } - - private func command(_ java: URL, tool: String, arguments: [String]) async throws -> String { - let executable = java.deletingLastPathComponent().appendingPathComponent(tool) - guard FileManager.default.isExecutableFile(atPath: executable.path) else { - throw DebugPerformanceError.unavailable("The selected JDK does not provide \(tool).") - } - let process = MacStreamingProcess(processRegistry: processRegistry, moduleID: .execution, logSink: logSink) - let output = JVMToolOutput() - let pair = AsyncThrowingStream.makeStream() - process.onOutput = { output.append($0) } - process.onTermination = { pair.continuation.yield($0); pair.continuation.finish() } - pair.continuation.onTermination = { _ in process.stop() } - defer { process.stop(); pair.continuation.finish() } - return try await withTaskCancellationHandler { - try Task.checkCancellation() - try process.start(ProcessRequest(executablePath: executable.path, arguments: arguments, - timeoutMilliseconds: 10_000)) - var iterator = pair.stream.makeAsyncIterator() - guard let code = try await iterator.next() else { throw CancellationError() } - try Task.checkCancellation() - guard code == 0 else { throw DebugPerformanceError.unavailable(output.value) } - return output.value - } onCancel: { process.stop(); pair.continuation.finish() } - } -} - -private final class JVMToolOutput: @unchecked Sendable { - private let lock = NSLock() - private var text = "" - var value: String { lock.withLock { text } } - func append(_ chunk: String) { lock.withLock { text = String((text + chunk).prefix(262_144)) } } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/MacImportedIDEATheme.swift b/macos/Sources/Lithe/Platform/MacOS/MacImportedIDEATheme.swift index 29f6289170..09c2b9c15a 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MacImportedIDEATheme.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MacImportedIDEATheme.swift @@ -54,9 +54,6 @@ enum MacImportedIDEATheme { ("DEFAULT_CLASS_NAME", ["type", "class"]), ("DEFAULT_INSTANCE_FIELD", ["field", "property"]), ("DEFAULT_PARAMETER", ["parameter"]), ("DEFAULT_FUNCTION_DECLARATION", ["functionDeclaration"]), ("DEFAULT_FUNCTION_CALL", ["functionCall"]), - ("JAVA_LINE_COMMENT", ["comment.line.java"]), ("JAVA_BLOCK_COMMENT", ["comment.block.java"]), - ("JAVA_DOC_COMMENT", ["comment.documentation.java"]), ("JAVA_KEYWORD", ["keyword.java"]), - ("JAVA_STRING", ["string.java"]), ("JAVA_NUMBER", ["number.java"]), ("METHOD_DECLARATION_ATTRIBUTES", ["method.declaration", "functionDeclaration"]), ("METHOD_CALL_ATTRIBUTES", ["method", "functionCall"]), ("STATIC_METHOD_ATTRIBUTES", ["method.static", "method.declaration.static"]), ("INSTANCE_FIELD_ATTRIBUTES", ["field", "property"]), ("STATIC_FIELD_ATTRIBUTES", ["property.static"]), diff --git a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift index 125156c8ac..d6607a0967 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MacServiceContainer.swift @@ -89,7 +89,6 @@ final class MacServiceContainer { moduleLaunchMode: ModuleLaunchMode = .normal, moduleStore providedModuleStore: MacModuleConfigurationStore? = nil, workspaceOperations providedWorkspaceOperations: (any WorkspaceOperations)? = nil, - javaMavenOperations providedJavaMavenOperations: (any JavaMavenOperations)? = nil, runConfigurationOperations providedRunConfigurationOperations: (any RunConfigurationOperations)? = nil, gitWatchContextProvider providedGitWatchContextProvider: (any GitWatchContextProviding)? = nil, runExecutableResolver providedRunExecutableResolver: (any RunExecutableResolving)? = nil, @@ -114,14 +113,6 @@ final class MacServiceContainer { // Declarative plugins have no process of their own to report their // contributions; the host reports each attempt through Core. let pluginOperations = PluginOperationReporter(record: { rustCore.recordPluginOperation($0) }) - let mavenRepositoryURL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".m2/repository", isDirectory: true) - let gradleRepositoryURL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".gradle/caches/modules-2/files-2.1", isDirectory: true) - let javaMavenOperations = providedJavaMavenOperations ?? RustJavaMavenOperations( - core: rustCore, - metadataRepositoryURLs: [mavenRepositoryURL, gradleRepositoryURL] - ) let fileStorage = MacFileStorage(logSink: logSink) // One proxy-aware session factory per process: LitheApp creates it so // the rollback downloader outside this container shares the policy, @@ -391,34 +382,13 @@ final class MacServiceContainer { } let runtimeService = ProjectRuntimeService( runtimeLocator: MacRuntimeLocator(), - settingsStore: MacProjectRuntimeSettingsStore(core: rustCore, storage: fileStorage, preferences: store), toolDiscovery: MacRuntimeToolDiscovery(), - javaSelector: rustCore, workspaceRuntime: { root in guard let binding = remoteWorkspaces.binding(forRoot: root) else { return nil } let locator = MacRemoteRuntimeLocator(binding: binding, host: remoteOperations) return (locator, locator) } ) - let languageServerCacheDirectory = fileStorage.cacheDirectory() - .appendingPathComponent("Lithe/language-servers", isDirectory: true) - // Native integrations a plugin's language server may name in its - // manifest. Each one owns everything specific to its server; the code - // below only routes by the declared ID. - let languageServerHostIntegrations = MacLanguageServerHostIntegrations([ - MacJdtHostIntegration( - launchResolver: pluginLaunchResolver, - runtimeService: runtimeService, - workspaceState: MacJdtWorkspaceState( - core: rustCore, - cacheDirectoryURL: languageServerCacheDirectory - ), logSink: logSink - ) - ]) - languageServerHostIntegrations.pluginsDidLoad( - pluginStartup.registeredPlugins, - installed: pluginStartup.scanSucceeded ? pluginStartup.installedPlugins : nil - ) // Provider processes of plugin build systems, one per plugin, build // system, and workspace. Created eagerly so the language sessions // can be connected; nothing starts until a model or dependency load. @@ -434,7 +404,8 @@ final class MacServiceContainer { runtime: runtimeService, core: rustCore, processRegistry: processRegistry, - remoteLaunches: remotePluginLaunches + remoteLaunches: remotePluginLaunches, + definedTools: definedToolchains ) // Provider processes of plugin VCS providers, one per plugin, VCS, // and workspace; one starts on the first request for a detected root. @@ -445,7 +416,8 @@ final class MacServiceContainer { runtime: runtimeService, core: rustCore, processRegistry: processRegistry, - remoteLaunches: remotePluginLaunches + remoteLaunches: remotePluginLaunches, + definedTools: definedToolchains ) // Plugin backends, one per plugin for the whole application: the // first project window creates them, and every window registers the @@ -521,7 +493,8 @@ final class MacServiceContainer { return (moduleStore.enabledState(for: module.id) ?? (module.defaultState == .enabled)) && !moduleStore.isQuarantined(module.id) }, - hostDispatcher: hostDispatcher + hostDispatcher: hostDispatcher, + definedTools: definedToolchains ) sessions.editorActions = editorActions runHost.backends = sessions @@ -590,18 +563,16 @@ final class MacServiceContainer { // the application's backends. let backendLaunches = MacPluginBackendLaunchPreparer( backends: pluginBackends, contexts: .shared, resolver: pluginLaunchResolver, - tools: providerTools, runtime: runtimeService, core: rustCore, + tools: providerTools, definedTools: definedToolchains, runtime: runtimeService, core: rustCore, workspaceState: pluginWorkspaceState ) let runtimeFactory = StdioLanguageProviderRuntimeFactory( runtimeService: runtimeService, languageServerCore: rustCore, languageServerExecutableResolver: { tools.executableURL(for: $0) }, - hostIntegrationResolver: { languageServerHostIntegrations.launch(for: $0) }, languageServerLaunchResolver: { source, rootURL in try pluginLaunchResolver.resolve(source, workspaceRootURL: rootURL) }, - languageServerCacheDirectory: languageServerCacheDirectory, workspaceSessionFactory: { descriptor, root in LanguageServerRuntimeSession(providerID: descriptor.launchSource?.languageID ?? "remote", executableURL: root, arguments: [], environment: [:], prepareProcess: { workspace in @@ -612,6 +583,27 @@ final class MacServiceContainer { backendLaunchPreparer: { source, root in try await backendLaunches.prepare(source, workspaceURL: root) }, + // A server whose launch names a tool definition: the + // definition's template places the entry, the runtime + // arguments and the plan's arguments. + toolLaunchPreparer: { source, root in + let resolved = try pluginLaunchResolver.resolveToolLaunch(source, workspaceRootURL: root) + let command = try await definedToolchains.command( + for: resolved.process, arguments: resolved.launch.arguments, workspace: root, + environment: runtimeService.languageToolProcessEnvironment(runtimeTools: resolved.runtimeTools), + projectCodeAllowed: false + ) + return PreparedLanguageServerProcess( + executableURL: command.executableURL, environment: command.environment, + launch: ResolvedLanguageServerLaunch( + arguments: command.arguments, + initializationOptions: resolved.launch.initializationOptions, + workspaceConfiguration: resolved.launch.workspaceConfiguration, + sessionPolicy: resolved.launch.sessionPolicy + ), + core: rustCore, release: {} + ) + }, processRegistry: processRegistry ) let runtimes = languagePackDefinitions.packs @@ -639,35 +631,14 @@ final class MacServiceContainer { !workspaceLanguageServerPreferences.disabledProviderIDs(for: workspaceURL) .contains(providerID) }, - workspaceFingerprintProvider: { descriptor, workspaceRootURL in - if remoteWorkspaces.contains(workspaceRootURL) { return nil } - return try languageServerHostIntegrations.workspaceFingerprint( - for: descriptor, - workspaceRootURL: workspaceRootURL - ) - }, - 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 + workspaceStateResetter: { descriptor, workspaceRootURL in + // A plugin's server keeps its state where the host + // created it for the plugin; remote state is not ours. + guard !remoteWorkspaces.contains(workspaceRootURL), + let source = descriptor.languageServerLaunch?.launchSource else { + throw CocoaError(.featureUnsupported) } - try languageServerHostIntegrations.resetWorkspaceState( - for: descriptor, - workspaceRootURL: workspaceRootURL, - fingerprint: fingerprint - ) - }, - workspaceStateCleaner: { descriptor, workspaceRootURL, fingerprint in - if remoteWorkspaces.contains(workspaceRootURL) { return 0 } - return try languageServerHostIntegrations.pruneWorkspaceState( - for: descriptor, - workspaceRootURL: workspaceRootURL, - fingerprint: fingerprint - ) + try pluginWorkspaceState.reset(source, workspaceRootURL: workspaceRootURL) } ) sessions.onLogEvent = { record in logSink?.emit(record) } @@ -694,20 +665,17 @@ final class MacServiceContainer { ) let runService = RunService( logSink: logSink, - runtime: runtimeService, process: MacStreamingProcess(processRegistry: processRegistry, moduleID: .execution, logSink: logSink), processFactory: { MacStreamingProcess(processRegistry: processRegistry, moduleID: .execution, logSink: logSink) }, fileAccess: MacRunFileAccess(storage: fileStorage), preferences: MacRunPreferenceStore(store: store), - serverPortParser: javaMavenOperations, runConfigurationOperations: providedRunConfigurationOperations ?? runConfigurationStore, executableResolver: executableResolver, languageProviderCatalog: languagePackRegistry.catalog, languageRunProviders: languagePackRegistry.runProviders, extensionRequiredLanguageIDs: runExtensionLanguageIDs, languageSupports: installedLanguageSupports, - dependencyStore: MacWorkspaceDependencyStore(storage: fileStorage), - javaLaunchArgumentPreparer: rustCore + dependencyStore: MacWorkspaceDependencyStore(storage: fileStorage) ) let buildSystemPlugins = pluginStartup.registeredPlugins.filter { !$0.descriptor.buildSystems.isEmpty } let buildSystems = buildSystemPlugins.isEmpty ? nil : BuildSystemService( @@ -772,9 +740,7 @@ final class MacServiceContainer { buildSystems: buildSystems ) graph.run.configureLanguageDependencyProvider { languageID, workspace, serviceID in - let capabilityID: ModuleCapabilityID = languageID == "java" - ? .languageIntelligence : .languageServerExtension(languageID) - guard let provider = moduleRuntime.capability(capabilityID) + guard let provider = moduleRuntime.capability(.languageServerExtension(languageID)) as? any LanguageDependencyProviding else { return nil } return provider.dependencySnapshot(workspaceURL: workspace, serviceID: serviceID) } @@ -783,30 +749,6 @@ final class MacServiceContainer { }) try moduleRegistry.register(ModuleFactory(manifest: DebugModule.moduleManifest, contributions: DebugModule.moduleContributions) { DebugModule(makeGraph: { - let debugFactories: [String: () -> (any DebugAdapterSession)?] = [ - "java": { - CoreDebugAdapterProtocolSession( - adapterID: "java", - logSink: logSink, - transport: MacHostedPortDebugAdapterTransport( - portResolver: { rootURL in - guard let capability = try await moduleRuntime - .activateCapability(.languageIntelligence) - as? LanguageIntelligenceCapability else { - throw MacHostedPortDebugAdapterTransport.TransportError - .languageIntelligenceUnavailable - } - return try await capability.sessions.startJavaDebugServer( - rootURL: rootURL - ) - }, - core: rustCore, logSink: logSink - ), - core: rustCore, - deadlineScheduler: MacDebugOperationDeadlineScheduler() - ) - } - ] let adapterSessions = DebugAdapterSessionManager( providersSource: { let languages = debugProviderCache.providers() @@ -816,7 +758,6 @@ final class MacServiceContainer { return languages + qualified }, makeSession: { descriptor, _ in - if let factory = debugFactories[descriptor.id] { return factory() } guard let entry = activeDebugAdapter(descriptor.id) else { return nil } let pluginID = entry.plugin.descriptor.id.rawValue let session = CoreDebugAdapterProtocolSession( @@ -886,16 +827,25 @@ final class MacServiceContainer { return session } ) + adapterSessions.declarationSource = { descriptor in + guard let entry = activeDebugAdapter(descriptor.id) else { return nil } + return DebugProviderDeclaration( + storageKey: entry.providerID, + displayName: entry.adapter.displayName, + behavior: entry.adapter.declaredBehavior + ) + } adapterSessions.makeEndpointSession = { descriptor, endpoint, _ in - let entry = activeDebugAdapter(descriptor.id) - guard descriptor.id == "java" || entry != nil else { return nil } + // Only a declared adapter names the DAP adapterID and + // behavior an external endpoint session speaks. + guard let entry = activeDebugAdapter(descriptor.id) else { return nil } let session = CoreDebugAdapterProtocolSession( - adapterID: entry?.adapter.adapterID ?? "java", + adapterID: entry.adapter.adapterID, logSink: logSink, - consoleCommands: entry?.adapter.consoleCommands ?? [], - consoleCommandPrefix: entry?.adapter.consoleCommandPrefix, - disabledCapabilities: entry?.adapter.disabledCapabilities ?? [], - declaredBehavior: entry?.adapter.declaredBehavior ?? .none, + consoleCommands: entry.adapter.consoleCommands, + consoleCommandPrefix: entry.adapter.consoleCommandPrefix, + disabledCapabilities: entry.adapter.disabledCapabilities, + declaredBehavior: entry.adapter.declaredBehavior, transport: try MacExternalDebugAdapterTransport.make( endpoint: endpoint, validate: { endpoint in @@ -918,9 +868,7 @@ final class MacServiceContainer { initializationTimeoutMilliseconds: try rustCore.debugTransportPolicy().initializationMilliseconds ) - if let entry { - debugAdapterSessionsBox.record(session, pluginID: entry.plugin.descriptor.id.rawValue) - } + debugAdapterSessionsBox.record(session, pluginID: entry.plugin.descriptor.id.rawValue) return session } debugAdapterSessionsBox.manager = adapterSessions @@ -1116,7 +1064,6 @@ final class MacServiceContainer { workspaceLanguageServerPreferences: workspaceLanguageServerPreferences, languageProviderCatalogSnapshot: languageProviderCatalogSnapshot, debugLaunchConfigurationResolver: DebugLaunchConfigurationResolver( - javaTestLaunchResolver: rustCore, providerConnection: { configurationType, adapterID, port in try MacBuildConnectionDebugResolver(planner: declarativePluginOperations, entries: qualifiedDebugAdapters, generation: { liveSnapshotBox.snapshot.generation }) @@ -1127,9 +1074,6 @@ final class MacServiceContainer { entry: { qualifiedDebugAdapters()[$0] }, generation: { liveSnapshotBox.snapshot.generation }) .resolve(source: source, preparation: preparation, workspaceURL: workspaceURL, title: title) }, - javaExecutablePath: { [runtimeService] runtime in - runtimeService.javaExecutableURL(forDebugging: runtime)?.path - }, pluginLaunch: { languageID, documentURL, workspaceURL in guard let entry = activeDebugAdapter(languageID) else { return nil } let targetPath = documentURL.standardizedFileURL.path @@ -1163,15 +1107,14 @@ final class MacServiceContainer { arguments: arguments, adapterProviderID: entry.providerID ) - } + }, + fileLaunch: { languageID in activeDebugAdapter(languageID) != nil } ), debugPortAvailabilityChecker: MacDebugPortAvailabilityChecker(), - javaTestResultServerFactory: { MacJavaTestResultServer() }, debugBreakpointPersistence: debugBreakpointStore, workspaceOperations: workspaceOperations, documentLifecycleDecider: RustDocumentLifecycleDecider(core: rustCore), lineEditing: RustLineEditing(core: rustCore), - javaMavenOperations: javaMavenOperations, markdownRenderer: markdownRenderer, markdownImageImporter: markdownImageImporter, store: store, @@ -1205,8 +1148,7 @@ final class MacServiceContainer { directoryWatcherFactory: MacDirectoryWatcherFactory(registry: remoteWorkspaces, transport: remoteTransport, logSink: logSink), platformUI: platformUI, shortcutDetectorFactory: MacShortcutDetectorFactory(), - debugPerformanceSampler: MacDebugPerformanceSampler(processRegistry: processRegistry, logSink: logSink), - testJVMPerformance: MacTestJVMPerformance(processRegistry: processRegistry, logSink: logSink) + debugPerformanceSampler: MacDebugPerformanceSampler() ) services.logWindowLogging = applicationLogging as? any LogWindowLogging diagnosticsExportService.environmentProvider = { [weak pluginManager] in @@ -1382,9 +1324,6 @@ final class MacServiceContainer { case .failure(let failure): failure.message } }, - recordJavaHome: { root, home in - try await runtimeService.presetJavaHome(home, for: root) - }, saveToolPin: { root, pin in try await MacProjectToolPins.save(pin, in: root, using: toolchainPreferences) } @@ -1519,7 +1458,7 @@ final class MacServiceContainer { // Plugin API 2 arguments are templates: Rust Core expands them // when the server starts. API 1 arguments stay literal and // keep the launch path they have always used. - let launchSource = server.expandsLaunchTemplates + var launchSource = server.expandsLaunchTemplates ? DeclarativeLanguageServerLaunchSource( pluginID: descriptor.id.rawValue, languageID: server.languageID, @@ -1534,6 +1473,9 @@ final class MacServiceContainer { let probe = launchSource.map { (try? launchResolver?.executableProbe(for: $0)) ?? .init() } ?? .init(validationArguments: server.validationArguments) + // A launch that names a tool definition resolves the tool only + // when the server starts, for its workspace root. + launchSource?.launchesThroughTool = probe.launchesThroughTool let configuration = LanguageServerExtensionConfiguration( languageID: server.languageID, displayName: languageNames[server.languageID] ?? server.languageID, @@ -1551,7 +1493,6 @@ final class MacServiceContainer { launchSource: launchSource, pluginID: descriptor.id.rawValue, executableVersionRequirement: probe.versionRequirement, - hostIntegrationID: server.hostIntegrationID, launchRuntimeTool: server.launchRuntimeTool ) return ModuleFactory(manifest: manifest) { diff --git a/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift b/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift index 46c68d1054..c068a4710d 100644 --- a/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift +++ b/macos/Sources/Lithe/Platform/MacOS/MonacoWorkbenchEditor.swift @@ -91,7 +91,6 @@ private struct MonacoWorkbenchDisplayConfiguration: Equatable { let fontFamily: String let wrap: Bool let minimap: Bool - let javaKeywordNavigationFilter: Bool let theme: MonacoWorkbenchThemeConfiguration let appearance: EditorAppearanceSettings @@ -101,7 +100,6 @@ private struct MonacoWorkbenchDisplayConfiguration: Equatable { "fontFamily": fontFamily, "wrap": wrap, "minimap": minimap, - "javaKeywordNavigationFilter": javaKeywordNavigationFilter, "dark": theme.dark, "theme": theme.bridgePayload, "appearance": appearance.monacoOptions @@ -166,7 +164,6 @@ private struct MonacoWorkbenchContent: View { ), wrap: settings.editorSoftWrapEnabled, minimap: settings.editorMinimapEnabled, - javaKeywordNavigationFilter: settings.javaKeywordNavigationFilterEnabled, appearance: settings.editorAppearance, markers: diagnostics.diagnostics(for: document.url), secondaryMarkers: secondaryDocument.map { diagnostics.diagnostics(for: $0.url) } ?? [], @@ -198,7 +195,6 @@ private struct MonacoWorkbenchSurface: NSViewRepresentable { let theme: MonacoWorkbenchThemeConfiguration let wrap: Bool let minimap: Bool - let javaKeywordNavigationFilter: Bool let appearance: EditorAppearanceSettings let markers: [EditorDiagnostic] let secondaryMarkers: [EditorDiagnostic] @@ -215,7 +211,7 @@ private struct MonacoWorkbenchSurface: NSViewRepresentable { coordinator.session.detachView(ownerID: coordinator.ownerID) } func updateNSView(_ view: NSView, context: Context) { - session.update(ownerID: context.coordinator.ownerID, document: document, secondaryDocument: secondaryDocument, preview: preview, markdownScrollPosition: markdownScrollPosition, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, javaKeywordNavigationFilter: javaKeywordNavigationFilter, appearance: appearance, markers: markers, secondaryMarkers: secondaryMarkers, softWrapControl: softWrapControl) + session.update(ownerID: context.coordinator.ownerID, document: document, secondaryDocument: secondaryDocument, preview: preview, markdownScrollPosition: markdownScrollPosition, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, appearance: appearance, markers: markers, secondaryMarkers: secondaryMarkers, softWrapControl: softWrapControl) } } @@ -312,11 +308,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele private var unconfirmedModels: Set = [] private var completionLists: [String: (context: MonacoDocumentContext, revision: Int?, key: String, items: [LanguageServerCompletionItem])] = [:] private var codeActionLists: [String: (context: MonacoDocumentContext, workspace: MonacoWorkspaceContext, revision: Int?, key: String, items: [LanguageServerCodeAction])] = [:] - private var javaNavigationLists: [String: (context: MonacoDocumentContext, revision: Int, url: URL, markers: [JavaImplementationMarker])] = [:] - private var javaNavigationRequests: [String: UUID] = [:] - private var javaRunMarkerLists: [String: (context: MonacoDocumentContext, revision: Int, url: URL, markers: [JavaRunMarker])] = [:] - private var javaRunMarkerRequests: [String: UUID] = [:] - private var javaRunMarkerRefreshSubscription: AnyCancellable? private struct EditorActionList { let context: MonacoDocumentContext let contentVersion: UInt64 @@ -330,8 +321,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele private let pluginProviders = MonacoPluginEditorProviders() private var pluginLanguagesSubscription: AnyCancellable? private var lastPluginLanguages: PluginEditorLanguageSet? - private var testOutcomeSubscription: AnyCancellable? - private var testServiceIdentity: ObjectIdentifier? private var codeActionCommands: [String: (context: MonacoDocumentContext, key: String, root: URL?, command: LanguageServerCommand)] = [:] private var subscriptions: [String: AnyCancellable] = [:] private var readOnlySubscriptions: [String: AnyCancellable] = [:] @@ -355,8 +344,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele private var lastLiveIDs: Set = [] private var debugSubscription: AnyCancellable? private var debugAvailabilitySubscription: AnyCancellable? - private var codeVisionSubscription: AnyCancellable? - private var lastCodeVisionEnabled: Bool? private var debugFeatureIdentity: ObjectIdentifier? private var lastDebugStates: [String: Data] = [:] private var gitSubscription: AnyCancellable? @@ -467,7 +454,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele selectMount() } - func update(ownerID: UUID, document: EditorDocument, secondaryDocument: EditorDocument?, preview: MonacoPreviewConfiguration?, markdownScrollPosition: Binding?, model: AppModel, fontSize: Double, fontFamily: String, theme: MonacoWorkbenchThemeConfiguration, wrap: Bool, minimap: Bool, javaKeywordNavigationFilter: Bool = true, appearance: EditorAppearanceSettings = EditorAppearanceSettings(), markers: [EditorDiagnostic], secondaryMarkers: [EditorDiagnostic], softWrapControl: EditorSoftWrapToggleConfiguration? = nil) { + func update(ownerID: UUID, document: EditorDocument, secondaryDocument: EditorDocument?, preview: MonacoPreviewConfiguration?, markdownScrollPosition: Binding?, model: AppModel, fontSize: Double, fontFamily: String, theme: MonacoWorkbenchThemeConfiguration, wrap: Bool, minimap: Bool, appearance: EditorAppearanceSettings = EditorAppearanceSettings(), markers: [EditorDiagnostic], secondaryMarkers: [EditorDiagnostic], softWrapControl: EditorSoftWrapToggleConfiguration? = nil) { guard mounts[ownerID] != nil else { return } self.model = model observeFind(model: model) @@ -479,11 +466,11 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele ) } mounts[ownerID]?.update = { [weak self, weak document, weak secondaryDocument, weak model] in guard let self, let document, let model else { return } - self.present(document: document, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, javaKeywordNavigationFilter: javaKeywordNavigationFilter, appearance: appearance, markers: markers) + self.present(document: document, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, appearance: appearance, markers: markers) self.presentMarkdownScroll(document: document, binding: markdownScrollPosition) if let secondaryDocument { self.hasSecondaryView = true - self.present(document: secondaryDocument, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, javaKeywordNavigationFilter: javaKeywordNavigationFilter, appearance: appearance, markers: secondaryMarkers, surface: "secondary") + self.present(document: secondaryDocument, model: model, fontSize: fontSize, fontFamily: fontFamily, theme: theme, wrap: wrap, minimap: minimap, appearance: appearance, markers: secondaryMarkers, surface: "secondary") } else if self.hasSecondaryView { self.hasSecondaryView = false self.activeIDs.removeValue(forKey: "secondary") @@ -717,28 +704,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele refreshDebugState(model: model) } - /// Run markers depend on JDT finishing project preparation and on recorded - /// test outcomes; either change asks the editor to request them again. - private func observeJavaRunMarkerInputs(model: AppModel) { - if javaRunMarkerRefreshSubscription == nil { - javaRunMarkerRefreshSubscription = model.languageToolingFeature.$projectPreparation - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in self?.call("window.lithe.refreshJavaRunMarkers()") } - } - let service = model.languageTestServiceIfActive - let identity = service.map(ObjectIdentifier.init) - guard identity != testServiceIdentity else { return } - testServiceIdentity = identity - testOutcomeSubscription = service?.$testOutcomesByProviderID - .map { $0["java"] ?? [] } - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in self?.call("window.lithe.refreshJavaRunMarkers()") } - } - /// Plugin grammars apply without a restart: the editor follows every /// change of the plugins' independent static editor resources. private func observePluginLanguages(model: AppModel) { @@ -812,18 +777,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } } - private func observeCodeVision(model: AppModel) { - if codeVisionSubscription == nil { - codeVisionSubscription = model.javaFeature.$javaCodeVisionHints - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in self?.call("window.lithe.codeVisionRefresh()") } - } - if lastCodeVisionEnabled != model.settings.showCodeVision { - lastCodeVisionEnabled = model.settings.showCodeVision - call("window.lithe.codeVisionRefresh()") - } - } - private func refreshGitState(model: AppModel, loadMissing: Bool = true) { if blameVisibilitySubscription == nil { blameVisibilitySubscription = model.$blameVisibleURL.receive(on: DispatchQueue.main) @@ -886,15 +839,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele private func refreshDebugState(model: AppModel) { let feature = model.genericDebugFeatureIfActive - if let feature, feature.state == .paused, feature.providerID == "java", - let frame = feature.selectedFrame, let url = frame.sourceURL?.standardizedFileURL, - let document = documents.values.first(where: { $0.url.standardizedFileURL == url }) { - // The debug feature deduplicates this frame/expression set and rejects - // responses after its inspection generation or selected frame changes. - feature.requestAutomaticVariables(DebugAutomaticExpressionProjection.javaExpressions( - forLine: max(0, frame.line - 1), in: document.text as NSString - )) - } for (id, document) in documents { guard !unconfirmedModels.contains(id) else { continue } let url = document.url.standardizedFileURL @@ -926,7 +870,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } } - private func present(document: EditorDocument, model: AppModel, fontSize: Double, fontFamily: String, theme: MonacoWorkbenchThemeConfiguration, wrap: Bool, minimap: Bool, javaKeywordNavigationFilter: Bool = true, appearance: EditorAppearanceSettings = EditorAppearanceSettings(), markers: [EditorDiagnostic], surface: String = "primary") { + private func present(document: EditorDocument, model: AppModel, fontSize: Double, fontFamily: String, theme: MonacoWorkbenchThemeConfiguration, wrap: Bool, minimap: Bool, appearance: EditorAppearanceSettings = EditorAppearanceSettings(), markers: [EditorDiagnostic], surface: String = "primary") { guard viewOwnerID != nil else { return } // Before the document: its file may be of a plugin language. observePluginLanguages(model: model) @@ -951,10 +895,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele codeActionCommands[oldID] = nil unconfirmedModels.remove(oldID) lastDebugStates[oldID] = nil - javaNavigationLists[oldID] = nil - javaNavigationRequests[oldID] = nil - javaRunMarkerLists[oldID] = nil - javaRunMarkerRequests[oldID] = nil cancelPluginActions(for: oldID, closing: true) pluginProviders.cancel(documentID: oldID, closing: true) lastGitStates[oldID] = nil @@ -1011,8 +951,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } } observeDebugState(model: model) - observeCodeVision(model: model) - observeJavaRunMarkerInputs(model: model) refreshGitState(model: model) refreshDebugState(model: model) let semanticState = model.semanticHighlightingSessionState @@ -1030,7 +968,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele fontFamily: MacEditorFontCatalog.editorFontStack(fontFamily), wrap: wrap, minimap: minimap, - javaKeywordNavigationFilter: javaKeywordNavigationFilter, theme: theme, appearance: appearance ) @@ -1173,7 +1110,7 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele func allowsMessage(_ type: String) -> Bool { !isReadOnlyPreview || !["format", "codeActions", "resolveCodeAction", "executeCodeAction", - "rename", "resolveCompletion", "javaRunMarkerAction", "pluginEditorAction", + "rename", "resolveCompletion", "pluginEditorAction", "pluginEditorProviderCommand", "setBlameVisibility"].contains(type) } @@ -1256,125 +1193,26 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele binding.wrappedValue = position } reply(["ok": true], nil) - case "javaFolding": - guard let model, !failed, document.url.pathExtension.lowercased() == "java", - let revision = body["revision"] as? Int, revision == revisions[id] else { - reply(["ranges": []], nil); return - } - let url = document.url, source = document.text - Task { @MainActor [weak self, weak document, weak model] in - guard let self, let document, let model, self.isCurrent(context) else { reply(["cancelled": true], nil); return } - // ponytail: reuse Core's lexical folds before Java startup; semantic LSP folds can replace this provider. - let structure = await model.javaStructure(source: source) - guard self.isCurrent(context), self.revisions[id] == revision, document.url == url else { - reply(["cancelled": true], nil); return - } - reply(["ranges": (structure?.foldRegions ?? []).map { - ["start": $0.startLine + 1, "end": $0.endLine + 1, "kind": $0.kind.rawValue] as [String: Any] - }], nil) - } - case "javaNavigation": - guard let model, !failed, document.url.pathExtension.lowercased() == "java", - let revision = body["revision"] as? Int, revision == revisions[id] else { - reply(["markers": []], nil); return - } - let url = document.url - let requestID = UUID() - javaNavigationRequests[id] = requestID - Task { @MainActor [weak self, weak document, weak model] in - guard let self, let document, let model, self.isCurrent(context) else { reply(["cancelled": true], nil); return } - let markers = await model.javaNavigationMarkers(for: document) - guard self.isCurrent(context), self.revisions[id] == revision, document.url == url, - self.javaNavigationRequests[id] == requestID else { - reply(["cancelled": true], nil); return - } - self.javaNavigationLists[id] = (context, revision, url, markers) - reply(["markers": markers.map { ["id": $0.id, "line": $0.line + 1, "direction": $0.direction.rawValue, "relation": $0.relation.rawValue] as [String: Any] }], nil) - } - case "javaRunMarkers": - guard let model, !failed, document.url.pathExtension.lowercased() == "java", - let revision = body["revision"] as? Int, revision == revisions[id] else { - reply(["markers": []], nil); return - } - let url = document.url - let requestID = UUID() - javaRunMarkerRequests[id] = requestID - Task { @MainActor [weak self, weak document, weak model] in - guard let self, let document, let model, self.isCurrent(context) else { reply(["cancelled": true], nil); return } - let markers = await model.javaRunMarkers(for: document) - guard self.isCurrent(context), self.revisions[id] == revision, document.url == url, - self.javaRunMarkerRequests[id] == requestID else { - reply(["cancelled": true], nil); return - } - let hasTests = markers.contains { $0.kind == .testClass || $0.kind == .testMethod } - if document.hasJavaTests != hasTests { document.hasJavaTests = hasTests } - let hasMain = markers.contains { $0.kind == .main } - if document.hasRunnableJavaMain != hasMain { document.hasRunnableJavaMain = hasMain } - self.javaRunMarkerLists[id] = (context, revision, url, markers) - reply(["canDebug": true, "markers": markers.map { marker in - ["id": marker.id, "line": marker.line + 1, "endLine": marker.endLine + 1, - "kind": marker.kind.rawValue, "label": marker.label, "status": marker.status.rawValue] as [String: Any] - }], nil) - } - case "javaRunMarkerAction": - guard let model, !failed, let revision = body["revision"] as? Int, revision == revisions[id], - let list = javaRunMarkerLists[id], isCurrent(list.context), list.revision == revision, list.url == document.url, - let markerID = body["marker"] as? String, - let marker = list.markers.first(where: { $0.id == markerID }), - let action = (body["action"] as? String).flatMap(AppModel.JavaRunMarkerAction.init(rawValue:)) else { - reply(["cancelled": true], nil); return - } - model.editorDidFocus(document) - model.performJavaRunMarker(marker, action: action, in: document.url) - reply(["ok": true], nil) case "pluginEditorActions": guard let model, !failed, !isReadOnlyPreview, let revision = body["revision"] as? Int, revision == revisions[id], - let workspace = model.pluginWebWorkspaceContext, - model.services.pluginWorkspaceContexts?.contexts.contains(where: { $0.reference == workspace && $0.authority == .local }) == true, - let service = model.services.pluginEditorActions, let backends = model.pluginWebBackends, - document.text.utf8.count <= service.host.actionSourceBytes else { reply(["actions": []], nil); return } + let collector = model.pluginEditorActionCollector, + PluginEditorActionCollector.admits(document, service: collector.service) else { reply(["actions": []], nil); return } cancelPluginActions(for: id) - let registrations = service.registrations(context: workspace, filename: document.url.lastPathComponent) + let registrations = collector.registrations(for: document) let text = document.text, version = document.contentVersion, requestID = UUID(), batch = UUID().uuidString - let input: ToolingJSONValue = .object([ - "document": .object(["documentID": .string(id), "version": .integer(Int(clamping: version)), - "path": model.workspaceURL.flatMap { root in - let prefix = root.standardizedFileURL.path + "/", path = document.url.standardizedFileURL.path - return path.hasPrefix(prefix) ? .string(String(path.dropFirst(prefix.count))) : nil - } ?? .null]), - "text": .string(text), - ]) + let path = PluginEditorActionCollector.workspaceRelativePath(of: document.url, root: model.workspaceURL) let task = Task { @MainActor [weak self, weak document] in defer { if self?.pluginActionRequests[id]?.id == requestID { self?.pluginActionRequests.removeValue(forKey: id)?.deadline.cancel() } } - var items: [(key: String, registration: PluginEditorActionRegistration, action: PluginEditorAction)] = [] - let clock = ContinuousClock(), started = clock.now - for registration in registrations { - do { - try Task.checkCancellation() - guard let remaining = PluginEditorActionCollectionBudget.remaining(after: started.duration(to: clock.now)) else { break } - guard service.contains(registration) else { continue } - let result = try await backends.invokePluginFunction(registration.functionID, params: input, - ofPlugin: registration.pluginID, context: workspace, timeout: remaining, progress: { _ in }) - try Task.checkCancellation() - let actions = try service.decode(result, text: text) - guard service.contains(registration), - actions.allSatisfy({ action in action.functionIDs.allSatisfy { service.contains(registration, functionID: $0) } }) - else { continue } - for action in actions { items.append((UUID().uuidString, registration, action)) } - guard items.count <= 1000 else { items = []; break } - } catch { - if Task.isCancelled { break } - if let plugin = LogSegment(registration.pluginID) { self?.model?.services.logSink?.emit(PluginsEditorActionsFailed(error: error, plugin: plugin)) } - } - } + let collected = (try? await collector.collect(documentID: id, version: version, path: path, text: text, + registrations: registrations)) ?? [] + let items = collected.map { (key: UUID().uuidString, registration: $0.registration, action: $0.action) } guard let self, let document, !Task.isCancelled, self.isCurrent(context), document.contentVersion == version, - self.pluginActionRequests[id]?.id == requestID, - items.allSatisfy({ item in item.action.functionIDs.allSatisfy { service.contains(item.registration, functionID: $0) } }) else { + self.pluginActionRequests[id]?.id == requestID, collector.stillRegistered(collected) else { reply(["cancelled": true], nil); return } self.pluginActionRequests.removeValue(forKey: id)?.deadline.cancel() @@ -1398,29 +1236,24 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele let list = pluginActionLists[id], list.batch == body["batch"] as? String, isCurrent(list.context), list.contentVersion == document.contentVersion, let key = body["action"] as? String, let item = list.actions.first(where: { $0.key == key }), - let service = model.services.pluginEditorActions, + let collector = model.pluginEditorActionCollector, let chosen = Self.chosenInvocation(of: item.action, alternativeID: body["alternative"]), - service.contains(item.registration, functionID: chosen.invoke.functionID), - model.pluginWebWorkspaceContext == item.registration.context, - let backends = model.pluginWebBackends, + collector.service.contains(item.registration, functionID: chosen.invoke.functionID), + collector.workspace == item.registration.context, pluginActionExecutions.count < 16 else { reply(["cancelled": true], nil); return } model.editorDidFocus(document) let operation = UUID() - var members: [String: ToolingJSONValue] = [ - "documentID": .string(id), "expectedVersion": .integer(Int(clamping: list.contentVersion)), - "actionID": .string(item.action.id), "data": chosen.invoke.params, - ] - if let alternativeID = chosen.alternativeID { members["alternativeID"] = .string(alternativeID) } - let params = ToolingJSONValue.object(members) + let choice = PluginEditorActionChoice( + item: PluginEditorActionItem(registration: item.registration, action: item.action), + invocation: chosen.invoke, alternativeID: chosen.alternativeID) + let expectedVersion = list.contentVersion let task = Task { @MainActor [weak self] in defer { self?.pluginActionExecutions[operation] = nil } do { - let result = try await backends.invokePluginFunction(chosen.invoke.functionID, params: params, - ofPlugin: item.registration.pluginID, context: item.registration.context, - timeout: .seconds(60), progress: { _ in }) - try Task.checkCancellation() // The plugin may point at places the click led to; showing them is the host's job. - if let reveal = try service.decodeReveal(result) { self?.model?.revealPluginLocations(reveal) } + if let reveal = try await collector.invoke(choice, documentID: id, expectedVersion: expectedVersion) { + self?.model?.revealPluginLocations(reveal) + } reply(["ok": true], nil) } catch { if Task.isCancelled { reply(["cancelled": true], nil) } @@ -1456,17 +1289,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } pluginProviders.open(body: body, document: document, documentID: id, model: model, isCurrent: { [weak self] in self?.isCurrent(context) == true }, reply: reply) - case "javaNavigationAction": - guard let model, !failed, let revision = body["revision"] as? Int, revision == revisions[id], - let list = javaNavigationLists[id], isCurrent(list.context), list.revision == revision, list.url == document.url, - document.url.pathExtension.lowercased() == "java", - let markerID = body["marker"] as? String, - let marker = list.markers.first(where: { $0.id == markerID }) else { - reply(["cancelled": true], nil); return - } - model.editorDidFocus(document) - model.resolveJavaNavigation(marker, in: document.url) - reply(["ok": true], nil) case "setBlameVisibility": guard let model, !failed, body["revision"] as? Int == revisions[id], let visible = body["visible"] as? Bool, @@ -1514,29 +1336,6 @@ final class MonacoWorkbenchSession: NSObject, ObservableObject, WKNavigationDele } reply(["ok": true], nil) } - case "codeVision": - guard let model, body["revision"] as? Int == revisions[id], model.settings.showCodeVision else { - reply(["hints": []], nil); return - } - let hints = model.javaCodeVisionHints[document.url.standardizedFileURL] ?? [] - reply(["hints": hints.map { hint in - ["id": hint.id, "line": hint.line + 1, "usageCount": hint.usageCount, - "implementationCount": hint.implementationCount, "authorName": hint.authorName ?? ""] as [String: Any] - }], nil) - case "codeVisionAction": - guard let model, body["revision"] as? Int == revisions[id], model.settings.showCodeVision, - let hintID = body["hint"] as? String, - let hint = model.javaCodeVisionHints[document.url.standardizedFileURL]?.first(where: { $0.id == hintID }) else { - reply(["cancelled": true], nil); return - } - model.editorDidFocus(document) - switch body["action"] as? String { - case "usages": model.findUsages(for: hint, in: document.url) - case "implementations": model.findJavaImplementations(line: hint.line, utf16Column: hint.utf16Column, in: document.url) - case "author": model.showBlame(for: document.url) - default: reply(nil, "Unknown CodeVision action"); return - } - reply(["ok": true], nil) case "prepareImagePaste": guard !failed, !self.isReadOnly(document), body["revision"] as? Int == revisions[id] else { reply(["cancelled": true], nil); return diff --git a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacDevelopmentProfileMigration.swift b/macos/Sources/Lithe/Platform/MacOS/Persistence/MacDevelopmentProfileMigration.swift index 43372d4dee..21402bbb06 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacDevelopmentProfileMigration.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Persistence/MacDevelopmentProfileMigration.swift @@ -65,7 +65,7 @@ struct MacDevelopmentProfileMigration { let preferences = source.filter { isUserPreference($0.key) && shouldImport($0.key) } // Explicit durable-data allowlist: caches, indexes, plugins, recovery // databases, logs and process connection/lock files are rebuilt by Dev. - let paths = ["Lithe/ai-secrets.json", "Lithe/Maven", "Lithe/PluginMarketplace/sources.json"] + let paths = ["Lithe/ai-secrets.json", "Lithe/PluginMarketplace/sources.json"] let existingPaths = paths.filter { fileManager.fileExists(atPath: base.appendingPathComponent($0).path) } guard !preferences.isEmpty || !existingPaths.isEmpty else { try commit([:], defaults: defaults, domain: destinationDomain, marker: "fresh") diff --git a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenConfigurationMigration.swift b/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenConfigurationMigration.swift deleted file mode 100644 index 8937de5456..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenConfigurationMigration.swift +++ /dev/null @@ -1,270 +0,0 @@ -import CoreFoundation -import CryptoKit -import Foundation -import LitheCoreContracts - -/// One-time data transfer at the Maven consumer cutover. These private formats -/// describe saved versions only; the adapter does not interpret Maven settings. -/// Temporary: retain for the first two stable versions with this migration, then -/// remove before the third. Tracker: D-MIGRATION-REMOVAL in -/// docs/development/issue-1495-plugin-migration-remaining-plan.md. -@MainActor -struct MacLegacyMavenConfigurationMigration { - let storage: any FileStorage - let preferences: any KeyValueStore - let runStore: MacRunConfigurationStore - let options: MacBuildOptionsStore - let immutableRoots: [URL] - - nonisolated static func storageIdentity(workspacePath: String, reactorPath: String) -> String { - workspacePath + "\0" + reactorPath - } - - /// Call only after the old configuration readers and writers are detached. - /// Every source is retained until all destinations have been read back. - @discardableResult - func migrate(workspace: URL, reactorRoots: [String]) throws -> Bool { - let roots = Array(Set(reactorRoots)).sorted() - guard roots.count <= 256, roots.allSatisfy(BuildProjectOptionsDocument.validRoot) else { throw BuildOptionsStorageError.invalid } - let workspace = workspace.standardizedFileURL - let portableURL = workspace.appendingPathComponent(".lithe/maven/config.json") - let portable = try source(Portable.self, at: portableURL, within: workspace, - fields: ["version", "selectedProfiles", "customProfiles", "skipTests"]) - let localDirectory = storage.applicationSupportDirectory().appendingPathComponent("Lithe/Maven") - let local: [(root: String, source: Source)] = try roots.compactMap { root in - let identity = Self.storageIdentity(workspacePath: workspace.path, reactorPath: root) - let digest = SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() - let url = localDirectory.appendingPathComponent(digest + ".json") - return try source(Local.self, at: url, within: localDirectory, - fields: ["version", "settingsPath", "localRepositoryPath", "mavenExecutablePath", "javaHomePath"]) - .map { (root, $0) } - } - let receiptKey = "BuildSystems.Migrations.Maven." + MacPluginStateDirectories.workspaceDigest(workspace) - let receiptBytes = preferences.data(forKey: receiptKey) - if receiptBytes == nil, preferences.object(forKey: receiptKey) != nil { throw BuildOptionsStorageError.invalid } - var receipt = try readReceipt(receiptBytes) - receipt = receipt.filter { storage.fileExists(at: URL(fileURLWithPath: $0.key)) } - guard portable != nil || !local.isEmpty else { - try writeReceipt(receipt, key: receiptKey, expecting: receiptBytes) - return try migrateRuntimePreferences(workspace: workspace, roots: roots) - } - let original = try options.projectDocument(workspace) - var document = original.document - var shared = document.systems["maven"] ?? BuildProjectOptionsDocument.System() - if let portable { - try portable.value.validate() - if shared.instanceDefaults["profiles"] == nil { - shared.instanceDefaults["profiles"] = .array(portable.value.selectedProfiles.map(ToolingJSONValue.string)) - } - if shared.instanceDefaults["skipTests"] == nil { shared.instanceDefaults["skipTests"] = .bool(portable.value.skipTests) } - shared.savedChoices["profiles"] = Array(Set((shared.savedChoices["profiles"] ?? []) + portable.value.customProfiles)).sorted() - } - document.systems["maven"] = shared - let existingDefaults = try options.instanceDefaults(workspaceURL: workspace, buildSystemID: "maven") - let existingWorkspaceOptions = try options.options(workspaceURL: workspace, buildSystemID: "maven") - let previousOptions = try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven") - var instanceOptions = previousOptions - let runURL = workspace.appendingPathComponent(".lithe/run/local.json") - let needsTools = local.contains { $0.source.value.mavenExecutablePath != nil || $0.source.value.javaHomePath != nil } - let runBytes = needsTools ? try readOptional(runURL, within: workspace) : nil - let inspection = needsTools ? runStore.inspect(at: workspace, checkFingerprint: false, javaEntrypoints: nil) : nil - if let inspection, case .invalid = inspection.status { throw BuildOptionsStorageError.invalid } - if needsTools, try readOptional(runURL, within: workspace) != runBytes { throw BuildOptionsStorageError.conflict } - let originalToolchain = inspection?.projectToolchain ?? ProjectToolchainSelection() - var toolchain = originalToolchain - for (root, source) in local { - try source.value.validate() - var values = instanceOptions[root] ?? [:] - if values["settingsFile"] == nil, existingDefaults["settingsFile"] == nil, existingWorkspaceOptions["settingsFile"] == nil, let value = source.value.settingsPath, shared.instanceDefaults["settingsFile"] != .string(value) { values["settingsFile"] = .string(value) } - if values["localRepository"] == nil, existingDefaults["localRepository"] == nil, existingWorkspaceOptions["localRepository"] == nil, let value = source.value.localRepositoryPath, shared.instanceDefaults["localRepository"] != .string(value) { values["localRepository"] = .string(value) } - if !values.isEmpty { instanceOptions[root] = values } - // Reactor-local paths have higher priority than project defaults. - // An existing root entry, even explicitly automatic, wins intact. - if root == "." { - if inspection?.projectToolchain == nil { - toolchain.mavenExecutablePath = source.value.mavenExecutablePath ?? "" - toolchain.mavenJavaHomePath = source.value.javaHomePath ?? "" - } - } else if toolchain.pathOverrides[root] == nil, - source.value.mavenExecutablePath != nil || source.value.javaHomePath != nil { - toolchain.pathOverrides[root] = .init(mavenExecutablePath: source.value.mavenExecutablePath ?? "", - mavenJavaHomePath: source.value.javaHomePath ?? "") - } - } - let sources = (portable.map { [($0.url, $0.bytes)] } ?? []) + local.map { ($0.source.url, $0.source.bytes) } - for (url, bytes) in sources { - let fingerprint = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() - if let earlier = receipt[url.path], earlier != fingerprint { throw BuildOptionsStorageError.conflict } - receipt[url.path] = fingerprint - } - try verifySources(sources) - try writeReceipt(receipt, key: receiptKey, expecting: receiptBytes) - let pendingReceipt = preferences.data(forKey: receiptKey) - // Failures may leave verified destination values. A retry preserves - // those values and completes remaining transfers; it never clears them. - if document != original.document { try options.saveProjectDocument(document, workspace: workspace, expecting: original.bytes) } - guard try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven") == previousOptions else { - throw BuildOptionsStorageError.conflict - } - if instanceOptions != previousOptions { - try options.setInstanceOptions(instanceOptions, workspaceURL: workspace, buildSystemID: "maven") - } - if toolchain != originalToolchain { - try runStore.saveProjectToolchain(toolchain, at: workspace, expecting: runBytes) - } - guard try options.projectDocument(workspace).document == document, - try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven") == instanceOptions else { - throw BuildOptionsStorageError.write - } - if needsTools { - let saved = runStore.inspect(at: workspace, checkFingerprint: false, javaEntrypoints: nil) - if case .invalid = saved.status { throw BuildOptionsStorageError.write } - guard (saved.projectToolchain ?? ProjectToolchainSelection()) == toolchain else { throw BuildOptionsStorageError.write } - } - try verifySources(sources) - guard preferences.data(forKey: receiptKey) == pendingReceipt else { throw BuildOptionsStorageError.conflict } - for (url, bytes) in sources { - guard try storage.removeData(at: url, expecting: bytes) else { throw BuildOptionsStorageError.conflict } - } - for (url, _) in sources { receipt[url.path] = nil } - try writeReceipt(receipt, key: receiptKey, expecting: pendingReceipt) - _ = try migrateRuntimePreferences(workspace: workspace, roots: roots) - return true - } - - /// This is a separate saved source from the reactor files. Only its two - /// retired Maven fields are removed after the private default layer verifies. - private func migrateRuntimePreferences(workspace: URL, roots: [String]) throws -> Bool { - guard !roots.isEmpty else { return false } - let key = MacProjectRuntimeSettingsStore.preferencesKey(workspace) - guard let bytes = preferences.data(forKey: key) else { - guard preferences.object(forKey: key) == nil else { throw BuildOptionsStorageError.invalid } - return false - } - guard bytes.count <= 2 * 1024 * 1024, - var document = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] else { - throw BuildOptionsStorageError.invalid - } - let fields = ["mavenSettingsPath": "settingsFile", "mavenLocalRepositoryPath": "localRepository"] - let receiptKey = "BuildSystems.Migrations.Maven." + MacPluginStateDirectories.workspaceDigest(workspace) + ".Runtime" - guard fields.keys.contains(where: { document[$0] != nil }) else { - // A verified cleanup can survive a failure removing its receipt. - // There is no remaining old Maven field to migrate or overwrite. - if preferences.object(forKey: receiptKey) != nil { preferences.set(nil, forKey: receiptKey) } - return false - } - var incoming: [String: ToolingJSONValue] = [:] - for (field, option) in fields { - guard let raw = document[field] else { continue } - guard let value = raw as? String, value.count <= 32768, !value.contains("\0") else { - throw BuildOptionsStorageError.invalid - } - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty { incoming[option] = .string(trimmed) } - } - let fingerprint = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() - if let previous = preferences.object(forKey: receiptKey) { - guard previous as? String == fingerprint else { throw BuildOptionsStorageError.conflict } - } - var defaults = try options.instanceDefaults(workspaceURL: workspace, buildSystemID: "maven") - for (id, value) in incoming where defaults[id] == nil { defaults[id] = value } - guard preferences.data(forKey: key) == bytes else { throw BuildOptionsStorageError.conflict } - preferences.set(fingerprint, forKey: receiptKey) - guard preferences.string(forKey: receiptKey) == fingerprint else { throw BuildOptionsStorageError.write } - try options.setInstanceDefaults(defaults, workspaceURL: workspace, buildSystemID: "maven") - guard try options.instanceDefaults(workspaceURL: workspace, buildSystemID: "maven") == defaults else { - throw BuildOptionsStorageError.write - } - guard preferences.data(forKey: key) == bytes, - preferences.string(forKey: receiptKey) == fingerprint else { throw BuildOptionsStorageError.conflict } - for field in fields.keys { document.removeValue(forKey: field) } - let cleaned = try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys]) - guard cleaned.count <= 2 * 1024 * 1024 else { throw BuildOptionsStorageError.invalid } - preferences.set(cleaned, forKey: key) - guard preferences.data(forKey: key) == cleaned else { throw BuildOptionsStorageError.write } - preferences.set(nil, forKey: receiptKey) - guard preferences.object(forKey: receiptKey) == nil else { throw BuildOptionsStorageError.write } - return true - } - - private func readReceipt(_ bytes: Data?) throws -> [String: String] { - guard let bytes else { return [:] } - guard bytes.count <= 2 * 1024 * 1024, - let value = try JSONSerialization.jsonObject(with: bytes) as? [String: String], value.count <= 512, - value.allSatisfy({ $0.key.hasPrefix("/") && $0.key.count <= 32768 && !$0.key.contains("\0") && $0.value.count == 64 && $0.value.allSatisfy(\.isHexDigit) }) else { - throw BuildOptionsStorageError.invalid - } - return value - } - - private func writeReceipt(_ value: [String: String], key: String, expecting expected: Data?) throws { - guard preferences.data(forKey: key) == expected else { throw BuildOptionsStorageError.conflict } - let data = value.isEmpty ? nil : try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) - if data == expected { return } - preferences.set(data, forKey: key) - guard preferences.data(forKey: key) == data else { throw BuildOptionsStorageError.write } - } - - private struct Source { - let url: URL - let bytes: Data - let value: Value - } - - private func source(_ type: Value.Type, at url: URL, within root: URL, - fields: Set) throws -> Source? { - guard let bytes = try readOptional(url, within: root) else { return nil } - guard let json = try JSONSerialization.jsonObject(with: bytes) as? [String: Any], - Set(json.keys).isSubset(of: fields), let version = json["version"] as? NSNumber, - CFGetTypeID(version) != CFBooleanGetTypeID(), version == 1 else { throw BuildOptionsStorageError.invalid } - return Source(url: url, bytes: bytes, value: try JSONDecoder().decode(type, from: bytes)) - } - - private func readOptional(_ url: URL, within root: URL) throws -> Data? { - let target = url.resolvingSymlinksInPath().standardizedFileURL.path - let root = root.resolvingSymlinksInPath().standardizedFileURL.path - guard target.hasPrefix(root + "/"), !immutableRoots.contains(where: { - let path = $0.resolvingSymlinksInPath().standardizedFileURL.path - return target == path || target.hasPrefix(path + "/") - }) else { throw BuildOptionsStorageError.invalid } - guard storage.fileExists(at: url) else { return nil } - guard let metadata = storage.metadata(for: url), metadata.isRegularFile, - let count = metadata.byteCount, count <= 2 * 1024 * 1024 else { throw BuildOptionsStorageError.invalid } - let bytes = try storage.readData(from: url, options: []) - guard bytes.count <= 2 * 1024 * 1024 else { throw BuildOptionsStorageError.invalid } - return bytes - } - - private func verifySources(_ sources: [(URL, Data)]) throws { - for (url, bytes) in sources { - guard let metadata = storage.metadata(for: url), metadata.isRegularFile, - metadata.byteCount == bytes.count, - try storage.readData(from: url, options: []) == bytes else { throw BuildOptionsStorageError.conflict } - } - } - - private struct Portable: Decodable { - let version: Int - let selectedProfiles: [String] - let customProfiles: [String] - let skipTests: Bool - func validate() throws { - guard selectedProfiles.count <= 256, customProfiles.count <= 256, - (selectedProfiles + customProfiles).allSatisfy({ !$0.isEmpty && $0.count <= 1024 && !$0.contains("\0") }) else { - throw BuildOptionsStorageError.invalid - } - } - } - - private struct Local: Decodable { - let version: Int - let settingsPath: String? - let localRepositoryPath: String? - let mavenExecutablePath: String? - let javaHomePath: String? - func validate() throws { - guard [settingsPath, localRepositoryPath, mavenExecutablePath, javaHomePath].compactMap({ $0 }) - .allSatisfy({ $0.count <= 32768 && !$0.contains("\0") }) else { throw BuildOptionsStorageError.invalid } - } - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenRunConfigurationMigration.swift b/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenRunConfigurationMigration.swift deleted file mode 100644 index d59ced0d02..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacLegacyMavenRunConfigurationMigration.swift +++ /dev/null @@ -1,532 +0,0 @@ -import CoreFoundation -import Darwin -import Foundation -import LitheCoreContracts -import LitheModuleAPI - -/// Temporary format adapter for saved Run v1/v2 Maven entries, never a launch path. -/// Remove with D-MIGRATION-REMOVAL before stable N+2; see the #1495 remaining plan. -/// Installed packages stay read-only; preferences may create a private workspace local document. -struct MacLegacyMavenRunConfigurationMigration { - struct Write { - let url: URL - let original: Data? - let replacement: Data - } - struct Plan { - let writes: [Write] - var teamDocument: Data? = nil - var localDocument: Data? = nil - var preferenceMarker: (key: String, state: Int)? = nil - var absentPreferenceKeys: [String] = [] - var preferenceSources: [String: Data] = [:] - var preferenceNamespace: (prefix: String, keys: [String])? = nil - var sources: [(url: URL, bytes: Data?)] = [] - } - let storage: any FileStorage - let preferences: any KeyValueStore - let immutableRoots: [URL] - - private static let frameworks = ["spring-boot.maven", "quarkus.maven", "micronaut.maven"] - private static let mavenFields: Set = ["module", "reactorPath", "mainClass", "jvmArguments", "programArguments", "profiles", "skipTests"] - private static let limit = 2 * 1024 * 1024 - - func prepare(workspace: URL, projects: [RunProjectOwnership], runs: [RunProviderConfiguration], - models: [BuildModel] = [], generatedDocument: Data? = nil, lease: RunConfigurationGenerationLease) throws -> Plan { - try lease.check() - let candidates = runs.filter { $0.reference.pluginID == "io.github.lithe-idea.maven-build" && $0.reference.buildSystemID == "maven" } - guard !candidates.isEmpty else { return Plan(writes: []) } - var sources = try ["configurations.json", "local.json"].map { name -> (URL, Data?, [String: Any]) in - let url = workspace.appendingPathComponent(".lithe/run/" + name) - let data = try read(url, workspace: workspace) - let document: [String: Any] - if let data { - guard let parsed = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw unsupported() } - document = try normalizedDocument(parsed) - } else { document = ["version": 2, "configurations": []] } - return (url, data, document) - } - let aliases = legacyAliases(projects: projects, runs: candidates) - let projectKey = workspace.standardizedFileURL.path.replacingOccurrences(of: "/", with: "_") - let markerKey = "lithe.run-configuration-migrated.\(projectKey)" - let marker = try preferenceMarker(markerKey) - let storedIDs = sources.flatMap { ($0.2["configurations"] as? [[String: Any]] ?? []).compactMap { $0["id"] as? String } } - let prefix = "lithe.java-run-options.\(projectKey)." - let listedKeys = marker == 2 ? nil : preferences.keys(withPrefix: prefix) - let preferenceKeys = marker == 2 ? [] : Set(aliases.keys).union(storedIDs).map { prefix + $0 } + (listedKeys ?? []) - guard preferenceKeys.count <= 10_000 else { throw unsupported() } - var preferenceSources: [String: Data] = [:], absentKeys: [String] = [] - var preferenceByteCount = 0 - for key in Set(preferenceKeys).sorted() { - guard let value = preferences.object(forKey: key) else { absentKeys.append(key); continue } - guard let bytes = value as? Data, bytes.count <= Self.limit else { throw unsupported() } - preferenceByteCount += bytes.count - guard preferenceByteCount <= Self.limit else { throw unsupported() } - preferenceSources[key] = bytes - } - let imported = try importPreferences(preferenceSources, prefix: prefix, sources: sources, aliases: aliases, - models: models, generatedDocument: generatedDocument, workspace: workspace, canEnumerate: listedKeys != nil) - sources[1].2 = imported.document - if imported.changed, sources[1].1 == nil { - let runtimeKey = "lithe.project-runtime.\(projectKey)" - if let raw = preferences.object(forKey: runtimeKey) { - guard let bytes = raw as? Data, bytes.count <= Self.limit else { throw unsupported() } - let settings = try JSONDecoder().decode(ProjectRuntimeSettings.self, from: bytes) - guard settings.javaHomePath.isEmpty, settings.mavenJavaHomePath.isEmpty, - settings.mavenHomeSelection == .automatic else { throw unsupported() } - preferenceSources[runtimeKey] = bytes - } else { absentKeys.append(runtimeKey) } - } - var cumulative: [String: [String: Any]] = [:] - var writes: [Write] = [] - for (index, source) in sources.enumerated() { - let (url, bytes, original) = source - try lease.check() - guard let items = original["configurations"] as? [[String: Any]], items.count <= 10_000 else { throw unsupported() } - var document = original, transformed: [[String: Any]] = [], changed = index == 1 && imported.changed - var seen = Set() - for item in items { - guard let id = item["id"] as? String, seen.insert(id).inserted else { throw unsupported() } - let previous = cumulative[id] - let effective = try merge(previous ?? [:], item) - cumulative[id] = effective - let provider = effective["provider"] as? String ?? effective["type"] as? String - if provider == nil && Self.frameworks.contains(where: { id.hasPrefix($0 + ":") }) && aliases[id] == nil { throw unsupported() } - if provider == "build.provider", ((effective["extensions"] as? [String: Any])?["build"] as? [String: Any])?["pluginID"] as? String == "io.github.lithe-idea.maven-build", - ((item["extensions"] as? [String: Any])?["maven"]) != nil { throw unsupported() } - let legacy = provider == "maven.module" || Self.frameworks.contains(provider ?? "") || (provider == nil && aliases[id] != nil) - guard legacy else { transformed.append(item); continue } - let ext = effective["extensions"] as? [String: Any] ?? [:] - if let java = ext["java"] as? [String: Any], let source = java["source"] as? String, source.lowercased().hasSuffix(".java") { - transformed.append(item); continue // JDT-owned Java entries remain stage E. - } - guard effective["command"] == nil else { throw unsupported() } - guard ext["maven"] == nil || ext["maven"] is [String: Any] else { throw unsupported() } - let maven = ext["maven"] as? [String: Any] ?? [:] - guard Set(maven.keys).isSubset(of: Self.mavenFields) else { throw unsupported() } - for field in ["module", "reactorPath", "mainClass"] { - if let value = maven[field], !(value is NSNull), !(value is String) { throw unsupported() } - } - try validateLegacyTools(effective, extensions: ext) - // Linked project defaults need their own consumer model. Do not - // silently discard them merely because this Run can be renamed. - try rejectUnmigratedDefaults(sources[1].2) - for runtimeKey in ["lithe.project-runtime.", "lithe.project-runtime-settings."].map({ $0 + projectKey }) { - if let raw = preferences.object(forKey: runtimeKey) { - guard let bytes = raw as? Data, bytes.count <= Self.limit else { throw unsupported() } - let settings = try JSONDecoder().decode(ProjectRuntimeSettings.self, from: bytes) - guard settings.javaHomePath.isEmpty, settings.mavenJavaHomePath.isEmpty, - settings.mavenHomeSelection == .automatic, settings.moduleOverrides.isEmpty else { throw unsupported() } - preferenceSources[runtimeKey] = bytes - } else { absentKeys.append(runtimeKey) } - } - let execution: BuildExecution = provider == "maven.module" ? .task : .service - var matches = aliases[id] ?? candidates.filter { $0.reference.execution == execution } - matches = matches.filter { candidate in - if let root = maven["reactorPath"] as? String, root != candidate.reference.root { return false } - if let module = maven["module"] as? String { - let path = module == "." ? candidate.reference.root : candidate.reference.root == "." ? module : candidate.reference.root + "/" + module - if path != candidate.projectPath { return false } - } - return candidate.reference.execution == execution - } - guard matches.count == 1, let target = matches.first else { throw unsupported() } - let expectedProvider = provider ?? Self.frameworks.first { id.hasPrefix($0 + ":") } - let modelTargets = models.flatMap { model -> [BuildModel.Target] in - guard model.projects.contains(where: { $0.id == target.reference.projectID && $0.path == target.projectPath }) else { return [] } - return model.targets.filter { $0.projectID == target.reference.projectID && $0.id == target.reference.targetID } - } - guard modelTargets.count == 1, modelTargets.first?.name == expectedProvider else { throw unsupported() } - var result = item - result["provider"] = "build.provider" - result["name"] = effective["name"] as? String ?? target.name - result["execution"] = execution.rawValue - if result["cwd"] == nil && previous == nil { result["cwd"] = target.reference.root } - result.removeValue(forKey: "toolchains"); result.removeValue(forKey: "debug") - let arguments = try strings(maven["programArguments"]) - let effectiveArguments = execution == .task ? try strings(effective["args"]) + arguments : arguments - // Keep even empty goals or unsupported runtime choices as data. - // The provider owns their meaning and validation, never this adapter. - result["args"] = effectiveArguments - var resultExtensions = item["extensions"] as? [String: Any] ?? [:] - guard resultExtensions["build"] == nil, resultExtensions["build-run"] == nil else { throw unsupported() } - resultExtensions.removeValue(forKey: "maven"); resultExtensions.removeValue(forKey: "java") - resultExtensions["build"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(target.reference)) - var choices: [String: Any] = [:], options: [String: Any] = [:] - if let own = (item["extensions"] as? [String: Any])?["maven"] as? [String: Any] { - if own.keys.contains("jvmArguments") { choices["runtimeArguments"] = try strings(own["jvmArguments"]) } - if own.keys.contains("mainClass") { - guard own["mainClass"] == nil || own["mainClass"] is NSNull || own["mainClass"] is String else { throw unsupported() } - choices["entrypoint"] = own["mainClass"] as? String ?? "" - } - } - let profiles = try strings(maven["profiles"]) - if !profiles.isEmpty { options["profiles"] = profiles } - if let skip = maven["skipTests"], !(skip is NSNull) { - guard let bool = skip as? NSNumber, CFGetTypeID(bool) == CFBooleanGetTypeID() else { throw unsupported() } - options["skipTests"] = bool - } - if let ownJava = (item["extensions"] as? [String: Any])?["java"] as? [String: String] { - var tools: [String: Any] = [:] - for (field, id, key) in [("mavenExecutablePath", "io.github.lithe-idea.maven-build:maven", "executable"), - ("mavenJavaHomePath", "java", "home")] { - if let value = ownJava[field] { - tools[id] = value.isEmpty ? NSNull() : [key: value] - } - } - if !tools.isEmpty { choices["tools"] = tools } - } - choices["options"] = options - resultExtensions["build-run"] = choices - result["extensions"] = resultExtensions - transformed.append(result); changed = true - } - if changed { - try validate(url, workspace: workspace) - document["configurations"] = transformed - let replacement = try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes]) - guard replacement.count <= Self.limit else { throw unsupported() } - writes.append(Write(url: url, original: bytes, replacement: replacement)) - } - } - var plan = Plan(writes: writes) - if !writes.isEmpty { - plan.sources = sources.map { (url: $0.0, bytes: $0.1) } - plan.preferenceMarker = (markerKey, marker) - plan.absentPreferenceKeys = absentKeys - plan.preferenceSources = preferenceSources - plan.preferenceNamespace = listedKeys.map { (prefix, $0.sorted()) } - plan.teamDocument = try writes.first { $0.url == sources[0].0 }?.replacement ?? sources[0].1 - ?? JSONSerialization.data(withJSONObject: sources[0].2) - plan.localDocument = try writes.first { $0.url == sources[1].0 }?.replacement ?? sources[1].1 - ?? JSONSerialization.data(withJSONObject: sources[1].2) - } - return plan - } - - /// All plans are prepared before the first write; every publication and rollback uses CAS. - func apply(_ plan: Plan, workspace: URL, lease: RunConfigurationGenerationLease) throws { - try lease.check() - try verifyPreferences(plan) - try verifySources(plan, completed: [], workspace: workspace) - var completed: [Write] = [] - var createdDirectories: [URL] = [] - do { - for write in plan.writes { - try lease.check() - try verifyPreferences(plan) - try verifySources(plan, completed: completed, workspace: workspace) - try validate(write.url, workspace: workspace) - if write.original == nil { - for path in [".lithe", ".lithe/run"] { - let directory = workspace.appendingPathComponent(path) - try validate(directory, workspace: workspace) - if mkdir(directory.path, 0o700) == 0 { createdDirectories.append(directory) } - else if errno != EEXIST { throw CocoaError(.fileWriteNoPermission) } - guard storage.metadata(for: directory)?.isDirectory == true else { throw unsupported() } - } - try lease.check() - try verifySources(plan, completed: completed, workspace: workspace) - } - guard try storage.replaceDataPreservingMetadata(write.replacement, at: write.url, expecting: write.original) else { throw conflict() } - completed.append(write) - MacFileWriteEventSuppression.markWritten(write.url) - } - try lease.check() - try verifyPreferences(plan) - try verifySources(plan, completed: completed, workspace: workspace) - } catch { - var rollbackFailed = false - for write in completed.reversed() { - // Another writer's bytes always win; keep trying the other files - // even when one destination can no longer be rolled back. - do { - try validate(write.url, workspace: workspace) - let restored = try write.original.map { try storage.replaceDataPreservingMetadata($0, at: write.url, expecting: write.replacement) } - ?? storage.removeData(at: write.url, expecting: write.replacement) - if restored { - MacFileWriteEventSuppression.markWritten(write.url) - } else { rollbackFailed = true } - } catch { rollbackFailed = true } - } - for directory in createdDirectories.reversed() { - // rmdir removes only an empty directory; another writer's files survive. - if (try? validate(directory, workspace: workspace)) != nil { _ = rmdir(directory.path) } - } - if rollbackFailed { throw conflict() } - throw error - } - } - - private func verifySources(_ plan: Plan, completed: [Write], workspace: URL) throws { - for source in plan.sources { - let expected = completed.first(where: { $0.url == source.url })?.replacement ?? source.bytes - guard try read(source.url, workspace: workspace) == expected else { throw conflict() } - } - } - - private func preferenceMarker(_ key: String) throws -> Int { - guard let raw = preferences.object(forKey: key) else { return 0 } - guard let value = raw as? NSNumber, CFGetTypeID(value) == CFBooleanGetTypeID() else { throw unsupported() } - return value.boolValue ? 2 : 1 - } - private func verifyPreferences(_ plan: Plan) throws { - if let marker = plan.preferenceMarker { - guard try preferenceMarker(marker.key) == marker.state, - plan.absentPreferenceKeys.allSatisfy({ preferences.object(forKey: $0) == nil }), - plan.preferenceSources.allSatisfy({ preferences.data(forKey: $0.key) == $0.value }) else { throw conflict() } - if let namespace = plan.preferenceNamespace { - guard preferences.keys(withPrefix: namespace.prefix)?.sorted() == namespace.keys else { throw conflict() } - } - } - } - - /// Import all observable active preferences before creating local.json; the - /// old importer uses that file's existence as its cutover boundary, including - /// for Java entries. Existing local fields always win over retired values. - private func importPreferences(_ values: [String: Data], prefix: String, - sources: [(URL, Data?, [String: Any])], aliases: [String: [RunProviderConfiguration]], - models: [BuildModel], generatedDocument: Data?, workspace: URL, - canEnumerate: Bool) throws -> (document: [String: Any], changed: Bool) { - var records: [String: [String: Any]] = [:] - for source in sources { - for item in source.2["configurations"] as? [[String: Any]] ?? [] { - guard let id = item["id"] as? String else { throw unsupported() } - records[id] = try merge(records[id] ?? [:], item) - } - } - let legacyRecord = records.values.contains { item in - let provider = item["provider"] as? String - return provider == "maven.module" || Self.frameworks.contains(provider ?? "") - || (provider == nil && aliases[item["id"] as? String ?? ""] != nil) - } - let hasLegacyPreference = values.keys.contains { key in - let id = String(key.dropFirst(prefix.count)) - return aliases[id] != nil && records[id]?["provider"] as? String != "build.provider" - } - guard legacyRecord || hasLegacyPreference, !values.isEmpty else { return (sources[1].2, false) } - if sources[1].1 == nil && !canEnumerate { throw unsupported() } - var generated: [String: [String: Any]] = [:] - if let generatedDocument { - guard let parsed = try JSONSerialization.jsonObject(with: generatedDocument) as? [String: Any], - let entries = parsed["configurations"] as? [[String: Any]] else { throw unsupported() } - for item in entries { if let id = item["id"] as? String { generated[id] = item } } - } - var document = sources[1].2 - var local = document["configurations"] as? [[String: Any]] ?? [] - var changed = false - for key in values.keys.sorted() { - let id = String(key.dropFirst(prefix.count)) - guard records[id]?["provider"] as? String != "build.provider" else { continue } - var record = records[id] ?? generated[id] ?? [:] - if record["provider"] == nil, let choices = aliases[id] { - guard choices.count == 1, let target = choices.first else { throw unsupported() } - let targets = models.flatMap { $0.targets }.filter { $0.projectID == target.reference.projectID && $0.id == target.reference.targetID } - guard targets.count == 1, let provider = targets.first?.name, Self.frameworks.contains(provider) else { throw unsupported() } - let root = target.reference.root - let module = target.projectPath == root ? "." : root == "." ? target.projectPath : String(target.projectPath.dropFirst(root.count + 1)) - record = ["id": id, "name": target.name, "provider": provider, "execution": "service", "cwd": root, - "extensions": ["maven": ["reactorPath": root, "module": module]]] - } - guard let provider = record["provider"] as? String else { throw unsupported() } - let isMaven = provider == "maven.module" || Self.frameworks.contains(provider) - let options = try legacyPreference(values[key]!) - if isMaven, !options.javaHomePath.isEmpty { throw unsupported() } - var patch: [String: Any] = ["id": id, "env": options.environment] - if !options.workingDirectoryPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - let raw = options.workingDirectoryPath.trimmingCharacters(in: .whitespacesAndNewlines) - let directory = (raw.hasPrefix("/") ? URL(fileURLWithPath: raw) : workspace.appendingPathComponent(raw)).resolvingSymlinksInPath().standardizedFileURL - let root = workspace.resolvingSymlinksInPath().standardizedFileURL.path - guard storage.metadata(for: directory)?.isDirectory == true, - directory.path == root || directory.path.hasPrefix(root + "/") else { throw unsupported() } - patch["cwd"] = directory.path == root ? "." : String(directory.path.dropFirst(root.count + 1)) - } - var java: [String: String] = [:] - for (field, value) in [("homePath", options.javaHomePath), ("mavenExecutablePath", options.mavenExecutablePath), ("mavenJavaHomePath", options.mavenJavaHomePath)] where !value.isEmpty { java[field] = value } - var extensions: [String: Any] = java.isEmpty ? [:] : ["java": java] - if isMaven || ["java.main", "java.current-file"].contains(provider) { - var maven: [String: Any] = ["jvmArguments": legacyArguments(options.vmArguments), "programArguments": legacyArguments(options.programArguments), - "profiles": options.activeProfiles.sorted()] - if let skip = options.mavenSkipTests { maven["skipTests"] = skip } - extensions["maven"] = maven - } else { patch["args"] = legacyArguments(options.programArguments) } - if !extensions.isEmpty { patch["extensions"] = extensions } - // A preference-only Maven record needs its current, proven identity. - if isMaven, records[id] == nil { patch = try merge(record, patch) } - if let index = local.firstIndex(where: { $0["id"] as? String == id }) { - local[index] = try merge(patch, local[index]) - } else { local.append(patch) } - changed = true - } - document["configurations"] = local - return (document, changed) - } - - private func legacyPreference(_ bytes: Data) throws -> RunOptions { - guard let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any], - Set(value.keys).isSubset(of: ["workingDirectoryPath", "arguments", "programArguments", "environment", "java", "javaHomePath", "vmArguments", "activeProfiles"]) else { throw unsupported() } - if let java = value["java"], !(java is NSNull) { - guard let object = java as? [String: Any], Set(object.keys).isSubset(of: ["homePath", "mavenExecutablePath", "mavenJavaHomePath", "vmArguments", "activeMavenProfiles", "skipTests"]) else { throw unsupported() } - } - return try JSONDecoder().decode(RunOptions.self, from: bytes) - } - - /// The retired preference writer used this text grammar, including dropping - /// empty quoted tokens. It performs no expansion or shell execution. - private func legacyArguments(_ text: String) -> [String] { - var result: [String] = [], current = "", quote: Character?, escaped = false - for character in text { - if escaped { current.append(character); escaped = false } - else if character == "\\" && quote != "'" { escaped = true } - else if character == "'" || character == "\"" { - if quote == character { quote = nil } - else if quote == nil { quote = character } - else { current.append(character) } - } else if character.isWhitespace && quote == nil { - if !current.isEmpty { result.append(current); current = "" } - } else { current.append(character) } - } - if escaped { current.append("\\") } - if !current.isEmpty { result.append(current) } - return result - } - - private func legacyAliases(projects: [RunProjectOwnership], runs: [RunProviderConfiguration]) -> [String: [RunProviderConfiguration]] { - var result: [String: [RunProviderConfiguration]] = [:] - for run in runs where run.reference.execution == .service { - guard let owner = projects.first(where: { $0.path == run.projectPath }), let name = owner.name else { continue } - let root = run.reference.root - guard root == "." || run.projectPath == root || run.projectPath.hasPrefix(root + "/") else { continue } - let module = run.projectPath == root ? "." : root == "." ? run.projectPath : String(run.projectPath.dropFirst(root.count + 1)) - // Retired generators used the label or module path. Keep both - // spellings, and reject any collision instead of guessing a root. - for label in Set([name, module]) { - for framework in Self.frameworks { - let id = framework + ":" + (root == "." ? "" : root + "/") + label - result[id, default: []].append(run) - } - } - } - return result - } - - private func validateLegacyTools(_ item: [String: Any], extensions: [String: Any]) throws { - if let debug = item["debug"], !(debug is NSNull) { - guard let values = debug as? [String: String], values == ["adapter": "jdwp"] else { throw unsupported() } - } - if let tools = item["toolchains"] { - guard let values = tools as? [String: String], values.allSatisfy({ key, value in - (key == "java" && value == "project-jdk") || (key == "maven" && value == "project-maven") - }) else { throw unsupported() } - } - if let java = extensions["java"] { - guard let values = java as? [String: String], Set(values.keys).isSubset(of: ["homePath", "mavenExecutablePath", "mavenJavaHomePath"]), - values["homePath", default: ""].isEmpty else { throw unsupported() } - // Validate the inert choice through its typed decoder. Core's full - // preflight validates the lexical absolute path before publication. - for (field, key) in [("mavenExecutablePath", "executable"), ("mavenJavaHomePath", "home")] { - if let value = values[field], !value.isEmpty { - guard value.utf8.count <= 4096, !value.contains(where: \.isNewline) else { throw unsupported() } - _ = try JSONDecoder().decode(FixedToolchainSelection.self, - from: JSONSerialization.data(withJSONObject: [key: value])) - } - } - } - } - - private func rejectUnmigratedDefaults(_ document: [String: Any]) throws { - guard let raw = document["toolchain"] else { return } - guard let tools = raw as? [String: Any] else { throw unsupported() } - for (namespace, fields) in [("java", ["homePath"]), ("maven", ["executablePath", "javaHomePath"])] { - if let raw = tools[namespace] { - guard let values = raw as? [String: String], fields.allSatisfy({ values[$0, default: ""].isEmpty }) else { throw unsupported() } - } - } - if let raw = tools["pathOverrides"] { - guard let overrides = raw as? [String: [String: String]], - overrides.values.allSatisfy({ $0.values.allSatisfy(\.isEmpty) }) else { throw unsupported() } - } - } - - private func merge(_ base: [String: Any], _ patch: [String: Any]) throws -> [String: Any] { - var result = base.merging(patch) { _, value in value } - if let raw = patch["extensions"] { - guard let incoming = raw as? [String: Any], base["extensions"] == nil || base["extensions"] is [String: Any] else { throw unsupported() } - var extensions = base["extensions"] as? [String: Any] ?? [:] - for (namespace, value) in incoming { - if let old = extensions[namespace] as? [String: Any], let values = value as? [String: Any] { - extensions[namespace] = old.merging(values) { _, next in next } - } else { extensions[namespace] = value } - } - result["extensions"] = extensions - } - return result - } - - private func strings(_ value: Any?) throws -> [String] { - guard let value, !(value is NSNull) else { return [] } - guard let strings = value as? [String], strings.count <= 1024, strings.allSatisfy({ !$0.contains("\0") && $0.utf8.count <= 65536 }) else { throw unsupported() } - return strings - } - - /// Retired v1 fields are a private saved format. Convert the whole document - /// when one Maven record changes, so unrelated Java records remain readable. - private func normalizedDocument(_ original: [String: Any]) throws -> [String: Any] { - guard let version = original["version"] as? NSNumber, CFGetTypeID(version) != CFBooleanGetTypeID(), - version == 1 || version == 2 else { throw unsupported() } - guard version == 1 else { return original } - guard let items = original["configurations"] as? [[String: Any]], items.count <= 10_000 else { throw unsupported() } - var document = original - document["version"] = 2 - document["configurations"] = try items.map { item in - guard item["provider"] == nil, item["cwd"] == nil else { throw unsupported() } - var result = item - var extensions = item["extensions"] as? [String: Any] ?? [:] - guard item["extensions"] == nil || item["extensions"] is [String: Any], - extensions["maven"] == nil else { throw unsupported() } - var maven: [String: Any] = [:] - for (old, current) in [("module", "module"), ("mainClass", "mainClass"), ("jvmArguments", "jvmArguments"), - ("programArguments", "programArguments"), ("mavenProfiles", "profiles")] { - if let value = result.removeValue(forKey: old), !(value is NSNull), !((value as? [Any])?.isEmpty == true) { - maven[current] = value - } - } - if !maven.isEmpty { extensions["maven"] = maven } - if !extensions.isEmpty { result["extensions"] = extensions } - if let cwd = result.removeValue(forKey: "workingDirectory") { result["cwd"] = cwd } - if let raw = result.removeValue(forKey: "type") { - guard let provider = raw as? String, !provider.isEmpty else { throw unsupported() } - result["provider"] = provider - result["execution"] = provider == "java.current-file" || provider == "java.main" ? "application" - : Self.frameworks.contains(provider) ? "service" : "task" - result["confidence"] = "native" - if result["debug"] == nil { result["debug"] = ["adapter": "jdwp"] } - } - return result - } - return document - } - - private func validate(_ url: URL, workspace: URL, writable: Bool = true) throws { - let path = url.resolvingSymlinksInPath().standardizedFileURL.path - let root = workspace.resolvingSymlinksInPath().standardizedFileURL.path - guard path.hasPrefix(root + "/"), !writable || !immutableRoots.contains(where: { - let immutable = $0.resolvingSymlinksInPath().standardizedFileURL.path - return path == immutable || path.hasPrefix(immutable + "/") - }) else { throw unsupported() } - } - private func read(_ url: URL, workspace: URL) throws -> Data? { - try validate(url, workspace: workspace, writable: false) - guard storage.fileExists(at: url) else { return nil } - guard let metadata = storage.metadata(for: url), metadata.isRegularFile, let size = metadata.byteCount, size <= Self.limit else { throw unsupported() } - let data = try storage.readData(from: url, options: []) - guard data.count <= Self.limit else { throw unsupported() } - return data - } - private func unsupported() -> any Error { - MacRunConfigurationStoreError.invalidConfiguration(L10n.string("Some saved run configurations cannot be migrated yet. Keep the existing files and retry after updating Lithe and its build plugin.")) - } - private func conflict() -> any Error { - MacRunConfigurationStoreError.invalidConfiguration(L10n.string("Run configuration changed while saving. Reload and try again.")) - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacProjectRuntimeSettingsStore.swift b/macos/Sources/Lithe/Platform/MacOS/Persistence/MacProjectRuntimeSettingsStore.swift deleted file mode 100644 index 13106cbe80..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Persistence/MacProjectRuntimeSettingsStore.swift +++ /dev/null @@ -1,133 +0,0 @@ -import CryptoKit -import Foundation -import LitheCoreContracts -import LitheModuleAPI - -/// Project-wide tool selections live only in the Core-owned local run document. -/// Other legacy preferences remain in their existing store until their owning -/// domain migration can transfer them without losing user data. -struct MacProjectRuntimeSettingsStore: ProjectRuntimeSettingsStoring { - let core: RustCoreBridge - let storage: any FileStorage - let preferences: any KeyValueStore - - private static let toolKeys = ["javaHomePath", "mavenHomeSelection", "mavenHomePath", "mavenJavaHomePath", "moduleOverrides"] - - func load(at workspace: URL, migrateLegacy: Bool) throws -> ProjectRuntimeSettingsSnapshot { - let root = workspace.standardizedFileURL - let key = Self.preferencesKey(root) - let preferenceData = preferences.data(forKey: key) - guard preferenceData != nil || preferences.object(forKey: key) == nil else { - throw ProjectRuntimeSettingsStoreError.readBack - } - let legacy = try preferenceData.map { try JSONDecoder().decode(ProjectRuntimeSettings.self, from: $0) } - ?? ProjectRuntimeSettings() - let before = try localData(root) - let inspection = try inspect(root) - let inspected = inspection.projectToolchain - guard try localData(root) == before else { throw ProjectRuntimeSettingsStoreError.conflict } - if migrateLegacy, let preferenceData, - var document = try JSONSerialization.jsonObject(with: preferenceData) as? [String: Any], - Self.toolKeys.contains(where: { document[$0] != nil }) { - let paths = legacy.moduleOverrides.map(\.path) - let known = Set(["path", "javaHomePath", "mavenExecutablePath", "mavenJavaHomePath"]) - let rawOverrides = document["moduleOverrides"] as? [[String: Any]] ?? [] - guard Set(paths).count == paths.count, - rawOverrides.allSatisfy({ Set($0.keys).isSubset(of: known) }) else { - throw ProjectRuntimeSettingsStoreError.readBack - } - let previous = legacy.projectToolchainSelection() - var selection = inspected ?? previous - if inspected != nil, !inspection.hasSavedToolchainPathOverrides { - selection.pathOverrides = previous.pathOverrides - } - if (inspected == nil && selection != ProjectToolchainSelection()) - || (inspected != nil && !inspection.hasSavedToolchainPathOverrides) { - try runStore.saveProjectToolchain(selection, at: root, expecting: before) - guard try inspect(root).projectToolchain == selection else { throw ProjectRuntimeSettingsStoreError.readBack } - } - // Keep the source until the target has been read successfully. An - // existing (including explicitly automatic) toolchain always wins. - guard preferences.data(forKey: key) == preferenceData else { throw ProjectRuntimeSettingsStoreError.conflict } - for field in Self.toolKeys { document.removeValue(forKey: field) } - let cleaned = try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys]) - preferences.set(cleaned, forKey: key) - guard preferences.data(forKey: key) == cleaned else { throw ProjectRuntimeSettingsStoreError.readBack } - return try load(at: root, migrateLegacy: false) - } - var settings = legacy - settings.applyProjectToolchain(inspected ?? ProjectToolchainSelection()) - return ProjectRuntimeSettingsSnapshot(workspaceURL: root, settings: settings, revision: Self.revision(before, preferenceData), hasSavedToolchain: inspected != nil) - } - - func save(_ settings: ProjectRuntimeSettings, at workspace: URL, - expecting snapshot: ProjectRuntimeSettingsSnapshot) throws -> ProjectRuntimeSettingsSnapshot { - let root = workspace.standardizedFileURL - guard snapshot.workspaceURL == root else { throw ProjectRuntimeSettingsStoreError.conflict } - let current = try load(at: root, migrateLegacy: false) - guard current.revision == snapshot.revision else { throw ProjectRuntimeSettingsStoreError.conflict } - if settings == current.settings { return current } - let before = try localData(root) - let key = Self.preferencesKey(root) - let preferenceData = preferences.data(forKey: key) - guard Self.revision(before, preferenceData) == snapshot.revision else { throw ProjectRuntimeSettingsStoreError.conflict } - let selected = settings.projectToolchainSelection() - if selected != current.settings.projectToolchainSelection() { - try runStore.saveProjectToolchain(selected, at: root, expecting: before) - guard try inspect(root).projectToolchain == selected else { throw ProjectRuntimeSettingsStoreError.readBack } - } - guard preferences.data(forKey: key) == preferenceData else { throw ProjectRuntimeSettingsStoreError.conflict } - // Preserve unrelated legacy fields while removing tool selections now - // owned by the canonical document, including all subproject overrides. - var document = try preferenceData.flatMap { try JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:] - guard let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(settings)) as? [String: Any] else { - throw ProjectRuntimeSettingsStoreError.readBack - } - for (field, value) in encoded where !Self.toolKeys.contains(field) && !["mavenSettingsPath", "mavenLocalRepositoryPath"].contains(field) { document[field] = value } - for field in Self.toolKeys { document.removeValue(forKey: field) } - let saved = try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys]) - preferences.set(saved, forKey: key) - guard preferences.data(forKey: key) == saved else { throw ProjectRuntimeSettingsStoreError.readBack } - return try load(at: root, migrateLegacy: false) - } - - private var runStore: MacRunConfigurationStore { - MacRunConfigurationStore(core: core, storage: storage, preferences: preferences) - } - - private func inspect(_ root: URL) throws -> ProjectRunConfigurationInspection { - let result = runStore.inspect(at: root, checkFingerprint: false, javaEntrypoints: nil) - if case .invalid(let message) = result.status { - throw MacRunConfigurationStoreError.invalidConfiguration(message) - } - return result - } - - private func localData(_ root: URL) throws -> Data? { - let url = root.appendingPathComponent(".lithe/run/local.json") - return storage.fileExists(at: url) ? try storage.readData(from: url, options: []) : nil - } - - static func preferencesKey(_ workspace: URL) -> String { - "lithe.project-runtime-settings." + workspace.standardizedFileURL.path.replacingOccurrences(of: "/", with: "_") - } - - private static func revision(_ local: Data?, _ preferences: Data?) -> String { - // Separate missing from empty and use independent digests to avoid - // ambiguous concatenation of two documents. - [local, preferences].map { data in - data.map { SHA256.hash(data: $0).map { String(format: "%02x", $0) }.joined() } ?? "missing" - }.joined(separator: ":") - } -} - -enum ProjectRuntimeSettingsStoreError: LocalizedError { - case conflict - case readBack - var errorDescription: String? { - switch self { - case .conflict: L10n.string("Project environment settings changed on disk. Reload before saving; your draft has been kept.") - case .readBack: L10n.string("Could not verify the saved project environment settings. The previous preferences have been kept when possible.") - } - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtHostIntegration.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtHostIntegration.swift deleted file mode 100644 index 7e78a0a70a..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtHostIntegration.swift +++ /dev/null @@ -1,141 +0,0 @@ -import LitheModuleAPI -import Foundation -import LitheCoreContracts - -// Note: Java 语言服务器插件化与 jdt 宿主集成见 .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md - -/// The `jdt` host integration: Eclipse JDT LS started through the shared JDT -/// launch in Rust Core. The declaring plugin ships JDT LS and its JDK; this -/// type locates them through the plugin's declaration, runs the server on the -/// plugin's runtime, and owns the per-workspace index in the host cache. -@MainActor -final class MacJdtHostIntegration: MacLanguageServerHostIntegration { - nonisolated static let integrationID = "jdt" - - let id = MacJdtHostIntegration.integrationID - - private let logSink: (any LogSink)? - private let launchResolver: MacPluginLanguageServerLaunchResolver - private let runtimeService: ProjectRuntimeService - private let workspaceState: MacJdtWorkspaceState - private let launchResources = MacJdtLaunchResources() - /// The removal of cached state started by the last `pluginsDidLoad`, so a - /// caller that needs the files gone can wait for it. - private(set) var stateRemoval: Task? - - init( - launchResolver: MacPluginLanguageServerLaunchResolver, - runtimeService: ProjectRuntimeService, - workspaceState: MacJdtWorkspaceState, - logSink: (any LogSink)? = nil - ) { - self.logSink = logSink - self.launchResolver = launchResolver - self.runtimeService = runtimeService - self.workspaceState = workspaceState - } - - /// JDT LS runs on the JDK its plugin ships. The host only learns where - /// that JDK is from the plugin's declaration; without a declaring plugin - /// the Java language service is unavailable. - /// - /// The indexes and Equinox areas JDT LS keeps in the host cache belong to - /// the plugin too. They live outside the plugin's own state directory, so - /// the package store cannot reach them; when no installed plugin declares - /// this integration any more, the integration discards them itself. A - /// package that is installed but rejected at startup, or a scan that - /// failed, is not a removal: the state is kept until the plugin is known - /// to be gone. - func pluginsDidLoad(_ plugins: [InstalledPluginPackage], installed: [InstalledPluginPackage]?) { - runtimeService.setJavaLanguageServerRuntimeHome(runtimeHome(in: plugins)) - guard let installed, - !installed.contains(where: { $0.installation.status != .removed && declaresIntegration($0) }) - else { - stateRemoval = nil - return - } - let cacheDirectoryURL = workspaceState.cacheDirectoryURL - let logSink = logSink - stateRemoval = Task.detached(priority: .utility) { - MacJdtWorkspaceState.removeAllState(in: cacheDirectoryURL, logSink: logSink) - } - } - - private func declaresIntegration(_ plugin: InstalledPluginPackage) -> Bool { - plugin.descriptor.languageServers.contains { $0.hostIntegrationID == id } - } - - func launch( - for source: DeclarativeLanguageServerLaunchSource - ) -> LanguageServerHostIntegrationResolution { - guard let runtimeExecutableURL = runtimeService.javaLanguageServerExecutableURL() else { - return .unavailable( - runtimeService.javaLanguageServerRuntimeFailureMessage() - ?? "The Java Support plugin's runtime is not prepared." - ) - } - do { - guard let declared = try launchResolver.hostIntegration(for: source) else { - return .unavailable("The Java Support plugin does not declare its JDT LS files. Reinstall the plugin.") - } - // JDT LS binds each project to the installed JDK that matches its - // release; the JDK it runs on cannot build a project for a newer - // Java release. - let resources = try launchResources.resources( - from: declared, - javaRuntimes: runtimeService.javaLanguageServiceRuntimes() - ) - return .available(LanguageServerHostIntegrationLaunch( - runtimeExecutableURL: runtimeExecutableURL, - coreLaunch: .jdt(resources) - )) - } catch { - logSink?.emit(PluginsResourcesMaintenanceFailed(error: error, stage: "jdt-launch-resolution")) - return .unavailable(error.localizedDescription) - } - } - - func workspaceFingerprint( - for source: DeclarativeLanguageServerLaunchSource, - workspaceRootURL: URL - ) throws -> String? { - guard let declared = try launchResolver.hostIntegration(for: source) else { return nil } - // The launcher identifies the JDT LS installation whose version and - // location the index depends on. - return try workspaceState.fingerprint( - at: workspaceRootURL, - languageServerExecutableURL: declared.entryURL - ) - } - - func resetWorkspaceState(at workspaceRootURL: URL, fingerprint: String?) throws { - try workspaceState.clearIndex(at: workspaceRootURL, workspaceFingerprint: fingerprint) - } - - func pruneWorkspaceState(at workspaceRootURL: URL, fingerprint: String?) throws -> Int { - try workspaceState.pruneExpiredCaches( - at: workspaceRootURL, - workspaceFingerprint: fingerprint - ).removedWorkspaceKeys.count - } - - /// JDK home of the runtime shipped by the plugin that declares this - /// integration, or `nil` when no installed plugin does. - func runtimeHome(in plugins: [InstalledPluginPackage]) -> URL? { - for installed in plugins { - for server in installed.descriptor.languageServers where server.hostIntegrationID == id { - let source = DeclarativeLanguageServerLaunchSource( - pluginID: installed.descriptor.id.rawValue, - languageID: server.languageID, - manifest: installed.descriptor.normalizedManifest, - packageURL: installed.packageURL - ) - // `/bin/java` - if let java = try? launchResolver.executableProbe(for: source).packagedRuntimeURL { - return java.deletingLastPathComponent().deletingLastPathComponent() - } - } - } - return nil - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtLaunchResources.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtLaunchResources.swift deleted file mode 100644 index ea5320415f..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtLaunchResources.swift +++ /dev/null @@ -1,70 +0,0 @@ -import LitheModuleAPI -import Foundation -import LitheCoreContracts - -// Note: Java 语言服务器插件化与 jdt 宿主集成见 .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md - -/// Maps the files a plugin declares for the `jdt` integration to the JDT LS -/// launch of Rust Core. It hands over exactly the declared files and never -/// searches the app bundle or the machine for JDT LS, so removing the plugin -/// removes Java language support with it. -struct MacJdtLaunchResources { - enum IntegrationError: LocalizedError, Equatable { - case missingResource(String) - - var errorDescription: String? { - switch self { - case .missingResource(let name): - L10n.string("The Java Support plugin does not provide \(name). Reinstall the plugin.") - } - } - } - - private let fileManager: FileManager - - init(fileManager: FileManager = .default) { - self.fileManager = fileManager - } - - func resources( - from integration: MacPluginLanguageServerLaunchResolver.HostIntegration, - javaRuntimes: [JavaLanguageServiceRuntime] - ) throws -> JDTLSLaunchResources { - guard let launcherJarURL = integration.entryURL else { - throw IntegrationError.missingResource("the JDT LS launcher") - } - guard let configurationURL = integration.resource("configuration") else { - throw IntegrationError.missingResource("the JDT LS configuration") - } - guard let lombokAgentURL = integration.resource("lombokAgent") else { - throw IntegrationError.missingResource("the Lombok agent") - } - return JDTLSLaunchResources( - launcherJarURL: launcherJarURL, - // The packaged directory is passed as is: Rust Core gives Equinox a - // writable copy in the host cache and never writes into the package. - configurationDirectoryURL: configurationURL, - lombokAgentURL: lombokAgentURL, - javaExtensionBundleURLs: (integration.resources["extensionBundleDirectories"] ?? []) - .flatMap(bundles(in:)), - javaTestRunnerURL: integration.resource("testRunner"), - javaRuntimes: javaRuntimes - ) - } - - /// JAR files directly inside a declared bundle directory, sorted by name - /// so JDT LS loads the same extensions in the same order on every launch. - private func bundles(in directoryURL: URL) -> [URL] { - let contents = (try? fileManager.contentsOfDirectory( - at: directoryURL, - includingPropertiesForKeys: [.isRegularFileKey], - options: [.skipsHiddenFiles] - )) ?? [] - return contents - .filter { - $0.pathExtension == "jar" - && (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true - } - .sorted { $0.lastPathComponent < $1.lastPathComponent } - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtWorkspaceState.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtWorkspaceState.swift deleted file mode 100644 index 7a10b09382..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/Jdt/MacJdtWorkspaceState.swift +++ /dev/null @@ -1,411 +0,0 @@ -import LitheModuleAPI -import LitheModuleAPI -import Foundation - -/// macOS filesystem adapter for JDT LS workspace fingerprints and cached state. -/// -/// The adapter only inspects immediate build-system inputs. Rust Core remains -/// the sole owner of workspace-key normalization and hashing. -struct MacJdtWorkspaceState { - private static let buildFileNames = ["pom.xml", "build.gradle", "build.gradle.kts"] - private static let mavenDescriptorName = "pom.xml" - private static let manifestName = "manifest.json" - private static let corePluginPrefix = "org.eclipse.jdt.ls.core_" - private static let lastUsedMarkerName = ".lithe-last-used" - - /// Directories of the language-server cache root that hold JDT LS state: - /// per-workspace indexes (`-data`) and Equinox configuration areas - /// (`-configuration`). Rust Core names and fills both. - static let ownedCacheDirectoryNames = ["jdtls", "jdtls-configuration"] - - let cacheDirectoryURL: URL - private let workspaceFingerprintResolver: (( - [RustCoreBridge.JdtBuildFileObservation], - [String], - String - ) throws -> String)? - private let workspaceKeyResolver: (URL, String?) throws -> String - private let cacheRetentionPlanner: (( - UInt64, - String, - [RustCoreBridge.JdtCacheEntry] - ) throws -> RustCoreBridge.JdtCacheRetentionPayload)? - - init(core: RustCoreBridge, cacheDirectoryURL: URL) { - self.init( - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprintResolver: { buildFiles, directMavenModules, jdtlsVersion in - try core.jdtWorkspaceFingerprint( - buildFiles: buildFiles, - directMavenModules: directMavenModules, - jdtlsVersion: jdtlsVersion - ).get() - }, - workspaceKeyResolver: { workspaceRootURL, fingerprint in - try core.jdtWorkspaceKey( - workspaceRootURL: workspaceRootURL, - workspaceFingerprint: fingerprint - ).get() - }, - cacheRetentionPlanner: { nowUnixSeconds, activeWorkspaceKey, entries in - try core.jdtCacheRetention( - nowUnixSeconds: nowUnixSeconds, - activeWorkspaceKey: activeWorkspaceKey, - entries: entries - ).get() - } - ) - } - - init( - cacheDirectoryURL: URL, - workspaceFingerprintResolver: (( - [RustCoreBridge.JdtBuildFileObservation], - [String], - String - ) throws -> String)? = nil, - workspaceKeyResolver: @escaping (URL, String?) throws -> String, - cacheRetentionPlanner: (( - UInt64, - String, - [RustCoreBridge.JdtCacheEntry] - ) throws -> RustCoreBridge.JdtCacheRetentionPayload)? = nil - ) { - self.cacheDirectoryURL = cacheDirectoryURL.standardizedFileURL - self.workspaceFingerprintResolver = workspaceFingerprintResolver - self.workspaceKeyResolver = workspaceKeyResolver - self.cacheRetentionPlanner = cacheRetentionPlanner - } - - /// Builds a deterministic, non-recursive digest input for one Java workspace. - func fingerprint( - at workspaceRootURL: URL, - languageServerExecutableURL: URL? - ) throws -> String { - guard let workspaceFingerprintResolver else { - throw MacJdtWorkspaceStateError.workspaceFingerprintUnavailable - } - let fileManager = FileManager.default - let root = workspaceRootURL.standardizedFileURL - var buildFiles: [RustCoreBridge.JdtBuildFileObservation] = [] - - for name in Self.buildFileNames { - let path = root.appendingPathComponent(name).path - // Only presence counts; JDT LS detects edits itself (see the - // `java.jdtWorkspaceFingerprint` contract). - do { - _ = try fileManager.attributesOfItem(atPath: path) - buildFiles.append(RustCoreBridge.JdtBuildFileObservation(path: name)) - // log-exempt: 预期的缺失:探测的可选文件或目录不存在,按未发现处理 - } catch where isMissingFileError(error) { - continue - } - } - - var modules: [String] = [] - let entries = try fileManager.contentsOfDirectory( - at: root, - includingPropertiesForKeys: [.isDirectoryKey], - options: [] - ) - for entry in entries { - let isDirectory = try entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory - guard isDirectory == true else { continue } - let descriptorPath = entry.appendingPathComponent(Self.mavenDescriptorName).path - do { - let attributes = try fileManager.attributesOfItem(atPath: descriptorPath) - guard attributes[.type] as? FileAttributeType == .typeRegular else { continue } - modules.append(entry.lastPathComponent) - // log-exempt: 预期的缺失:探测的可选文件或目录不存在,按未发现处理 - } catch where isMissingFileError(error) { - continue - } - } - - return try workspaceFingerprintResolver( - buildFiles, - modules, - languageServerCacheIdentity(for: languageServerExecutableURL) - ) - } - - /// Removes every index and configuration area JDT LS wrote, for the case - /// where the plugin that owns them is gone and nothing will read them - /// again. Best effort: it only frees disk space. - nonisolated static func removeAllState(in cacheDirectoryURL: URL, logSink: (any LogSink)? = nil) { - var failures: Int64 = 0 - var lastError: (any Error)? - for name in ownedCacheDirectoryNames { - do { try FileManager.default.removeItem( - at: cacheDirectoryURL.appendingPathComponent(name, isDirectory: true) - ) } - catch let error as CocoaError where error.code == .fileNoSuchFile { /* No cache was created. */ } - catch { failures += 1; lastError = error } - } - if let lastError { logSink?.emit(AppStorageCleanupFailed(count: failures, error: lastError, stage: "jdt-cache")) } - } - - /// Removes only the current workspace/fingerprint directory. Other cached - /// structures remain available if the user later switches back to them. - func clearIndex(at workspaceRootURL: URL, workspaceFingerprint: String?) throws { - let key = try workspaceKeyResolver( - workspaceRootURL.standardizedFileURL, - workspaceFingerprint - ) - try validateWorkspaceKey(key) - - let target = cacheDirectoryURL - .appendingPathComponent("jdtls", isDirectory: true) - .appendingPathComponent(key, isDirectory: true) - .standardizedFileURL - if FileManager.default.fileExists(atPath: target.path) { - try FileManager.default.removeItem(at: target) - } - } - - /// Removes inactive JDT LS caches selected by Rust Core's shared policy. - /// The active directory is marked as recently used before the decision. - func pruneExpiredCaches( - at workspaceRootURL: URL, - workspaceFingerprint: String?, - now: Date = Date() - ) throws -> MacJdtCacheCleanupResult { - guard let cacheRetentionPlanner else { - throw MacJdtWorkspaceStateError.cacheRetentionUnavailable - } - let activeWorkspaceKey = try workspaceKeyResolver( - workspaceRootURL.standardizedFileURL, - workspaceFingerprint - ) - try validateWorkspaceKey(activeWorkspaceKey) - - let jdtlsCacheURL = cacheDirectoryURL.appendingPathComponent("jdtls", isDirectory: true) - let fileManager = FileManager.default - let candidates: [URL] - do { - candidates = try fileManager.contentsOfDirectory( - at: jdtlsCacheURL, - includingPropertiesForKeys: [ - .isDirectoryKey, - .isSymbolicLinkKey, - .contentModificationDateKey, - ], - options: [.skipsHiddenFiles] - ) - // log-exempt: 预期的缺失:探测的可选文件或目录不存在,按未发现处理 - } catch where isMissingFileError(error) { - let plan = try cacheRetentionPlanner( - unixSeconds(now), - activeWorkspaceKey, - [] - ) - return MacJdtCacheCleanupResult( - retentionDays: plan.retentionDays, - removedWorkspaceKeys: [] - ) - } - - var observedKeys: Set = [] - var entries: [RustCoreBridge.JdtCacheEntry] = [] - for candidate in candidates { - let values = try candidate.resourceValues(forKeys: [ - .isDirectoryKey, - .isSymbolicLinkKey, - .contentModificationDateKey, - ]) - guard values.isDirectory == true, values.isSymbolicLink != true else { continue } - let key = candidate.lastPathComponent - guard isWorkspaceKey(key) else { continue } - let markerModified: Date? - if key == activeWorkspaceKey { - try Data(String(unixSeconds(now)).utf8).write( - to: candidate.appendingPathComponent(Self.lastUsedMarkerName), - options: [.atomic] - ) - markerModified = now - } else { - markerModified = try lastUsedDate(at: candidate) - } - let modified = [values.contentModificationDate, markerModified] - .compactMap { $0 } - .max() ?? .distantPast - observedKeys.insert(key) - entries.append(RustCoreBridge.JdtCacheEntry( - workspaceKey: key, - lastModifiedUnixSeconds: unixSeconds(modified) - )) - } - - let plan = try cacheRetentionPlanner( - unixSeconds(now), - activeWorkspaceKey, - entries - ) - var removedWorkspaceKeys: [String] = [] - for key in plan.expiredWorkspaceKeys { - guard key != activeWorkspaceKey, observedKeys.contains(key), isWorkspaceKey(key) else { - throw MacJdtWorkspaceStateError.invalidRetentionPlan - } - let target = jdtlsCacheURL.appendingPathComponent(key, isDirectory: true) - let values = try target.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - guard values.isDirectory == true, values.isSymbolicLink != true else { - throw MacJdtWorkspaceStateError.invalidRetentionTarget - } - try fileManager.removeItem(at: target) - removedWorkspaceKeys.append(key) - } - return MacJdtCacheCleanupResult( - retentionDays: plan.retentionDays, - removedWorkspaceKeys: removedWorkspaceKeys - ) - } - - private func validateWorkspaceKey(_ key: String) throws { - guard isWorkspaceKey(key) else { - throw MacJdtWorkspaceStateError.invalidWorkspaceKey - } - } - - private func isWorkspaceKey(_ key: String) -> Bool { - key.utf8.count == 64 && key.utf8.allSatisfy { byte in - (48...57).contains(byte) || (97...102).contains(byte) - } - } - - private func unixSeconds(_ date: Date) -> UInt64 { - UInt64(max(0, date.timeIntervalSince1970.rounded(.down))) - } - - private func lastUsedDate(at workspaceCacheURL: URL) throws -> Date? { - let markerURL = workspaceCacheURL.appendingPathComponent(Self.lastUsedMarkerName) - do { - return try markerURL.resourceValues(forKeys: [.contentModificationDateKey]) - .contentModificationDate - } catch { - if isMissingFileError(error) { - return nil - } - throw error - } - } - - private func isMissingFileError(_ error: Error) -> Bool { - let cocoaError = error as NSError - return cocoaError.domain == NSCocoaErrorDomain - && (cocoaError.code == NSFileNoSuchFileError - || cocoaError.code == NSFileReadNoSuchFileError) - } - - private func languageServerVersion(for executableURL: URL?) throws -> String { - let fileManager = FileManager.default - var roots: [URL] = [] - if let executableURL { - let bin = executableURL.standardizedFileURL.deletingLastPathComponent() - roots.append(bin) - roots.append(bin.deletingLastPathComponent()) - } - - var visited: Set = [] - for root in roots where visited.insert(root.standardizedFileURL.path).inserted { - let manifestURL = root.appendingPathComponent(Self.manifestName) - do { - let data = try Data(contentsOf: manifestURL) - let manifest: JdtManifest - do { - manifest = try JSONDecoder().decode(JdtManifest.self, from: data) - } catch { - throw MacJdtWorkspaceStateError.invalidLanguageServerManifest( - manifestURL.path - ) - } - let version = manifest.version.trimmingCharacters(in: .whitespacesAndNewlines) - guard !version.isEmpty else { - throw MacJdtWorkspaceStateError.invalidLanguageServerManifest( - manifestURL.path - ) - } - return version - // log-exempt: 预期的缺失:探测的可选文件或目录不存在,按未发现处理 - } catch where isMissingFileError(error) { - // A selected development executable may not ship a manifest; - // the JDT LS core plug-in name remains the next stable source. - } - - let pluginsURL = root.appendingPathComponent("plugins", isDirectory: true) - let names: [String] - do { - names = try fileManager.contentsOfDirectory(atPath: pluginsURL.path) - // log-exempt: 预期的缺失:探测的可选文件或目录不存在,按未发现处理 - } catch where isMissingFileError(error) { - continue - } - if let pluginName = names.sorted().first(where: { - $0.hasPrefix(Self.corePluginPrefix) && $0.hasSuffix(".jar") - }) { - let suffix = pluginName - .dropFirst(Self.corePluginPrefix.count) - .dropLast(".jar".count) - let components = suffix.split(separator: ".") - if components.count >= 3 { - return components.prefix(3).joined(separator: ".") - } - return String(suffix) - } - } - throw MacJdtWorkspaceStateError.languageServerVersionUnavailable - } - - private func languageServerCacheIdentity(for executableURL: URL?) throws -> String { - let version = try languageServerVersion(for: executableURL) - // The installation is only ever the one its plugin declares; there - // is no JDT LS inside the application to fall back to. - guard let executableURL else { - throw MacJdtWorkspaceStateError.languageServerInstallationUnavailable - } - let installationPath = executableURL.standardizedFileURL.path - // JDT LS persists absolute JRE and source paths inside its workspace. - // Relocating an app or Preview build must therefore select a fresh cache. - return "\(version)|installation=\(installationPath)" - } -} - -private struct JdtManifest: Decodable { - let version: String -} - -struct MacJdtCacheCleanupResult: Equatable { - let retentionDays: UInt64 - let removedWorkspaceKeys: [String] -} - -private enum MacJdtWorkspaceStateError: LocalizedError { - case workspaceFingerprintUnavailable - case invalidLanguageServerManifest(String) - case languageServerVersionUnavailable - case languageServerInstallationUnavailable - case invalidWorkspaceKey - case cacheRetentionUnavailable - case invalidRetentionPlan - case invalidRetentionTarget - - var errorDescription: String? { - switch self { - case .workspaceFingerprintUnavailable: - L10n.string("Rust Core workspace-fingerprint resolution is unavailable.") - case .invalidLanguageServerManifest(let path): - L10n.string("The bundled JDT LS manifest is invalid at \(path).") - case .languageServerVersionUnavailable: - L10n.string("The bundled JDT LS version could not be determined.") - case .languageServerInstallationUnavailable: - L10n.string("The bundled JDT LS installation could not be determined.") - case .invalidWorkspaceKey: - L10n.string("Rust Core returned an invalid Java workspace key.") - case .cacheRetentionUnavailable: - L10n.string("Rust Core cache-retention planning is unavailable.") - case .invalidRetentionPlan: - L10n.string("Rust Core returned a Java cache-retention key that was not observed.") - case .invalidRetentionTarget: - L10n.string("A Java cache-retention target is not a removable directory.") - } - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/MacLanguageServerHostIntegrations.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/MacLanguageServerHostIntegrations.swift deleted file mode 100644 index badc1b7219..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/HostIntegrations/MacLanguageServerHostIntegrations.swift +++ /dev/null @@ -1,121 +0,0 @@ -import LitheModuleAPI -import Foundation -import LitheCoreContracts - -// Note: 宿主集成的划分见 .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md - -/// Native host code a plugin's language server names in its manifest through -/// `hostIntegration.id`. Everything specific to one integration lives in its -/// own type; the language-server pipeline and the composition root only see -/// this protocol. -@MainActor -protocol MacLanguageServerHostIntegration { - /// The `hostIntegration.id` this type implements. - var id: String { get } - - /// Called once the installed plugins are known, before any server starts. - /// `plugins` are the accepted packages. `installed` is every package the - /// scan found, or `nil` when the scan itself failed and nothing is known - /// about what is installed. - func pluginsDidLoad(_ plugins: [InstalledPluginPackage], installed: [InstalledPluginPackage]?) - - /// What the integration adds to one start of the declaring server. - func launch( - for source: DeclarativeLanguageServerLaunchSource - ) -> LanguageServerHostIntegrationResolution - - /// Identity of the server state kept for a workspace, or `nil` when the - /// integration keeps none. - func workspaceFingerprint( - for source: DeclarativeLanguageServerLaunchSource, - workspaceRootURL: URL - ) throws -> String? - - /// Discards the state kept for a workspace so the server rebuilds it. - func resetWorkspaceState(at workspaceRootURL: URL, fingerprint: String?) throws - - /// Removes state of workspaces that are no longer used. Returns how many - /// workspaces were removed. - func pruneWorkspaceState(at workspaceRootURL: URL, fingerprint: String?) throws -> Int -} - -/// The integrations this build of Lithe provides, looked up by the ID a -/// language server declares. -@MainActor -struct MacLanguageServerHostIntegrations { - enum IntegrationError: LocalizedError, Equatable { - case notDeclared(String) - - var errorDescription: String? { - switch self { - case .notDeclared(let displayName): - L10n.string("\(displayName) keeps no workspace state that Lithe can reset.") - } - } - } - - private let integrations: [String: any MacLanguageServerHostIntegration] - - init(_ integrations: [any MacLanguageServerHostIntegration]) { - self.integrations = Dictionary(uniqueKeysWithValues: integrations.map { ($0.id, $0) }) - } - - func pluginsDidLoad(_ plugins: [InstalledPluginPackage], installed: [InstalledPluginPackage]?) { - for id in integrations.keys.sorted() { - integrations[id]?.pluginsDidLoad(plugins, installed: installed) - } - } - - /// `nil` when the provider declares no integration. - func launch(for descriptor: LanguageProviderDescriptor) -> LanguageServerHostIntegrationResolution? { - guard let id = descriptor.languageServerLaunch?.hostIntegrationID else { return nil } - guard let declared = declared(by: descriptor) else { - // Rust Core rejects unknown IDs at validation, so this is a - // manifest accepted by a newer contract than this host implements. - return .unavailable("\(descriptor.displayName) needs the \(id) integration, which this build of Lithe does not provide.") - } - return declared.integration.launch(for: declared.source) - } - - func workspaceFingerprint( - for descriptor: LanguageProviderDescriptor, - workspaceRootURL: URL - ) throws -> String? { - guard let declared = declared(by: descriptor) else { return nil } - return try declared.integration.workspaceFingerprint( - for: declared.source, - workspaceRootURL: workspaceRootURL - ) - } - - func resetWorkspaceState( - for descriptor: LanguageProviderDescriptor, - workspaceRootURL: URL, - fingerprint: String? - ) throws { - guard let declared = declared(by: descriptor) else { - throw IntegrationError.notDeclared(descriptor.displayName) - } - try declared.integration.resetWorkspaceState(at: workspaceRootURL, fingerprint: fingerprint) - } - - func pruneWorkspaceState( - for descriptor: LanguageProviderDescriptor, - workspaceRootURL: URL, - fingerprint: String? - ) throws -> Int { - guard let declared = declared(by: descriptor) else { return 0 } - return try declared.integration.pruneWorkspaceState(at: workspaceRootURL, fingerprint: fingerprint) - } - - private func declared(by descriptor: LanguageProviderDescriptor) -> ( - integration: any MacLanguageServerHostIntegration, - source: DeclarativeLanguageServerLaunchSource - )? { - guard let launch = descriptor.languageServerLaunch, - let id = launch.hostIntegrationID, - let integration = integrations[id], - let source = launch.launchSource else { return nil } - return (integration, source) - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacLivePluginRegistry.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacLivePluginRegistry.swift index f8fc570450..8942fb6604 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacLivePluginRegistry.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacLivePluginRegistry.swift @@ -47,13 +47,12 @@ struct PluginDebugAdapterEntry { /// The adapter that launches a debug session for a language's open file, /// first package in ID order first. An adapter that only attaches, or only /// debugs executables and processes, is not chosen for a file. - /// Java keeps the host's own adapter. static func index(of packages: [InstalledPluginPackage]) -> [String: PluginDebugAdapterEntry] { var entries: [String: PluginDebugAdapterEntry] = [:] for plugin in packages.sorted(by: { $0.manifest.id < $1.manifest.id }) { for adapter in plugin.descriptor.debugAdapters { let languageIDs = adapter.fileLaunchLanguageIDs - for languageID in languageIDs where languageID != "java" && entries[languageID] == nil { + for languageID in languageIDs where entries[languageID] == nil { entries[languageID] = PluginDebugAdapterEntry(plugin: plugin, adapter: adapter) } } diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift index 824814f95e..2e0110d5e9 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendLaunchPreparer.swift @@ -35,6 +35,7 @@ final class MacPluginBackendLaunchPreparer { private let contexts: PluginWorkspaceContexts private let resolver: MacPluginLanguageServerLaunchResolver private let tools: any BuildToolResolving + private let definedTools: any DefinedToolchainResolving private let runtime: any LanguageToolRuntimePort private let core: any LanguageServerRuntimeCore private let workspaceState: MacPluginLanguageServerWorkspaceState? @@ -44,6 +45,7 @@ final class MacPluginBackendLaunchPreparer { contexts: PluginWorkspaceContexts, resolver: MacPluginLanguageServerLaunchResolver, tools: any BuildToolResolving, + definedTools: any DefinedToolchainResolving, runtime: any LanguageToolRuntimePort, core: any LanguageServerRuntimeCore, workspaceState: MacPluginLanguageServerWorkspaceState? = nil @@ -52,6 +54,7 @@ final class MacPluginBackendLaunchPreparer { self.contexts = contexts self.resolver = resolver self.tools = tools + self.definedTools = definedTools self.runtime = runtime self.core = core self.workspaceState = workspaceState @@ -67,7 +70,7 @@ final class MacPluginBackendLaunchPreparer { 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 process = try await decide(source, question: question, context: context, workspaceURL: workspaceURL) 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. @@ -86,15 +89,24 @@ final class MacPluginBackendLaunchPreparer { } } - /// Asks the plugin's backend and lets Rust Core check the answer. + /// Asks the plugin's backend and lets Rust Core check the answer. The + /// question carries `tools`, the installations the user's choice and + /// discovery select for the tools the manifest requires, so the backend + /// can configure its server for the same tools the host runs. private func decide( _ source: DeclarativeLanguageServerLaunchSource, question: MacPluginLanguageServerLaunchResolver.BackendLaunchQuestion, - context: PluginWorkspaceContext + context: PluginWorkspaceContext, + workspaceURL: URL ) async throws -> MacPluginLanguageServerLaunchResolver.BackendLaunchProcess { + var params = question.resolveParams + let tools = await resolvedRequiredTools(of: source, workspaceURL: workspaceURL) + if !tools.isEmpty { + params["tools"] = .object(tools) + } let answer = try await backends.invokePluginFunction( question.function, - params: .object(question.resolveParams), + params: .object(params), ofPlugin: source.pluginID, context: context.reference, timeout: .milliseconds(question.timeoutMilliseconds), @@ -105,6 +117,37 @@ final class MacPluginBackendLaunchPreparer { return try resolver.backendLaunchProcess(for: source, question: question, answer: answer) } + /// `{: {executable, home, version}}` for every tool the manifest + /// lists in `requiresTools` that resolves to an installation outside the + /// project. A tool that is missing, unusable, or inside the project is + /// left out: the contract promises only the tools the host could find, + /// and opening a project must not run its code. + private func resolvedRequiredTools( + of source: DeclarativeLanguageServerLaunchSource, workspaceURL: URL + ) async -> [String: ToolingJSONValue] { + var tools: [String: ToolingJSONValue] = [:] + let environment = runtime.languageToolProcessEnvironment() + for tool in Self.requiredTools(of: source.manifest) { + // log-exempt: 找不到或不可用的工具按契约直接省略,后端自行决定缺省行为 + guard let selected = try? await definedTools.resolve( + tool: tool, directory: ".", workspace: workspaceURL, environment: environment, + minimumVersion: nil, projectCodeAllowed: false, fixed: nil, use: .installation, consumerID: nil + ), !selected.projectCode else { continue } + var fields: [String: ToolingJSONValue] = ["executable": .string(selected.executable.path)] + if let home = selected.home { fields["home"] = .string(home) } + if let version = selected.version { fields["version"] = .string(version) } + tools[tool] = .object(fields) + } + return tools + } + + /// The `requiresTools` of the normalized manifest, in manifest order. + private static func requiredTools(of manifest: Data) -> [String] { + guard let object = try? JSONSerialization.jsonObject(with: manifest) as? [String: Any], + let tools = object["requiresTools"] as? [String] else { return [] } + return tools + } + /// The program to start and the environment the host gives it. private struct Target { let url: URL diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift index ee3d1b2057..71b3c51324 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift @@ -85,6 +85,8 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi private let endBackendProcesses: @MainActor (_ token: String, _ immediately: Bool) -> Void private let canStart: @MainActor (String) -> Bool private let stuckSendGrace: Duration + /// Resolves a backend launch that names a tool definition. + private let definedTools: MacDefinedToolchainResolver? /// Serves the host requests of every backend. let hostDispatcher: PluginHostServiceDispatcher private let keymapImportHost = MacKeymapImportHostService() @@ -144,6 +146,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi stuckSendGrace: Duration = .seconds(2), canStart: @escaping @MainActor (String) -> Bool = { _ in true }, hostDispatcher: PluginHostServiceDispatcher? = nil, + definedTools: MacDefinedToolchainResolver? = nil, endBackendProcesses: @escaping @MainActor (_ token: String, _ immediately: Bool) -> Void = { token, immediately in MacPluginBackendProcesses.end( token: token, @@ -162,6 +165,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi self.stuckSendGrace = stuckSendGrace self.canStart = canStart self.endBackendProcesses = endBackendProcesses + self.definedTools = definedTools if let hostDispatcher { self.hostDispatcher = hostDispatcher } else { @@ -714,7 +718,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi await Task.detached(priority: .userInitiated) { prepareState(installation, stateDirectory) }.value try Task.checkCancellation() guard running[pluginID] === entry else { throw CancellationError() } - var (executableURL, environment) = try await resolveExecutable(backend.process, directory: backend.stateDirectory) + var (executableURL, arguments, environment) = try await resolveExecutable(backend.process, directory: backend.stateDirectory) try Task.checkCancellation() guard running[pluginID] === entry else { throw CancellationError() } // Every process the backend starts inherits this token, so what it @@ -728,7 +732,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi let session = LanguageServerRuntimeSession( providerID: "pluginBackend:\(pluginID)", executableURL: executableURL, - arguments: backend.process.arguments, + arguments: arguments, environment: environment, initializationOptions: backend.process.initializationOptions, initializeTimeout: 60, @@ -812,7 +816,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi } } do { - try session.start(rootURL: rootURL, workspaceFingerprint: nil) + try session.start(rootURL: rootURL) } catch { finish(.failure(error)) } @@ -821,19 +825,34 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi /// A packaged file starts as it is. Commands and runtimes resolve through /// the build tool discovery, with the backend's state directory as the - /// place a project-local tool would be looked up. + /// place a project-local tool would be looked up. A tool launch resolves + /// its definitions the same way and takes the command line their + /// template expands to; every other launch keeps the plan's arguments. private func resolveExecutable( _ process: MacPluginLanguageServerLaunchResolver.BuildProviderProcess, directory: URL - ) async throws -> (URL, [String: String]) { + ) async throws -> (URL, [String], [String: String]) { let runtimes = process.runtimeTools.map { BuildInvocation.RuntimeDependency(id: $0, hostManaged: true) } let invocation: BuildInvocation var requirement: LanguageServerExecutableVersionRequirement? switch process.executable { + case .tool(let launch): + guard let definedTools else { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "A plugin backend that names a tool definition cannot start in this host." + ) + } + let command = try await definedTools.command( + for: launch, arguments: process.arguments, workspace: directory, + environment: runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools), + projectCodeAllowed: false + ) + return (command.executableURL, command.arguments, command.environment) case .file(let url): - return (url, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) + return (url, process.arguments, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) case .commands(let commands): invocation = BuildInvocation(executables: commands.map { .command($0) }, runtimeDependencies: runtimes) case .runtime(let tool, let versionRequirement): @@ -859,7 +878,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi return BuildVersionCheck(satisfied: check.satisfied, version: check.version) } ) - return (resolved.executableURL, resolved.environment) + return (resolved.executableURL, process.arguments, resolved.environment) } /// Waits for a shared start. A cancelled caller stops waiting at once, diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift index abaf66bc66..d72eb5f546 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginLanguageServerLaunchResolver.swift @@ -4,7 +4,7 @@ import Foundation import LitheCoreContracts import LitheLanguageIntelligenceModule -// Note: Java 语言服务器插件化与启动计划见 .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md +// Note: 语言服务器插件化与启动计划见 .agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md /// Writable state of declarative plugins' language servers. It lives outside /// both the app bundle and the installed plugin packages, which stay @@ -332,12 +332,17 @@ struct MacPluginLanguageServerLaunchResolver { case commands([String]) /// A runtime the host discovers with the user's settings. case runtime(String, versionRequirement: LanguageServerExecutableVersionRequirement?) + /// A tool definition the host resolves through its four layers, or the + /// runtime the plugin ships. The definition's `launch` template places + /// the entry and runtime arguments, and `arguments` fill `${arguments}`. + case tool(DefinedToolProcessLaunch) } let executable: Executable let arguments: [String] let initializationOptions: ToolingJSONValue? - /// Runtimes the process needs on `PATH`. + /// Runtimes the process needs on `PATH`. Under a tool launch these + /// are only the closed-list runtimes; `.tool` resolves the others. let runtimeTools: [String] let executesProjectCode: Bool let mayUseNetwork: Bool @@ -598,50 +603,81 @@ struct MacPluginLanguageServerLaunchResolver { .runtime(tool, versionRequirement: plan.executableVersionRequirement) } case nil: - throw DeclarativePluginRejection( - code: "plugin.launch.unavailable", - message: "Rust Core returned a provider launch without an executable." - ) + // A tool launch names no executable; its definition starts it. + guard let launch = plan.toolLaunch else { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "Rust Core returned a provider launch without an executable." + ) + } + executable = .tool(try toolProcess(launch, plan: plan, packageURL: root)) } try createRequiredDirectories(of: plan, request: request) return BuildProviderProcess( executable: executable, arguments: plan.arguments, initializationOptions: plan.initializationOptions, - runtimeTools: plan.runtimeRequirements.map(\.tool), + runtimeTools: Self.closedListRuntimeTools(of: plan), executesProjectCode: executesProjectCode, mayUseNetwork: mayUseNetwork, settings: launchSettings ) } - /// A declared host integration with its resources located in the package. - struct HostIntegration: Equatable { - let id: String - /// Entry file of the runtime launch the integration builds on. - let entryURL: URL? - let resources: [String: [URL]] + /// A tool launch with the runtime the plugin ships, when it ships one, + /// checked to be a runnable file inside the package. + private func toolProcess( + _ launch: DeclarativeLanguageServerLaunchPlan.ToolLaunch, + plan: DeclarativeLanguageServerLaunchPlan, + packageURL: URL + ) throws -> DefinedToolProcessLaunch { + DefinedToolProcessLaunch( + launch: launch, + packagedRuntimeURL: try launch.packagedRuntime.map { try packagedExecutable($0, packageURL: packageURL) }, + requirements: plan.runtimeRequirements.filter(\.resolvesThroughDefinition) + ) + } - func resource(_ name: String) -> URL? { resources[name]?.first } + /// The runtimes the host's closed list puts on `PATH`. A tool launch + /// resolves its definition requirements itself, so they are left out; + /// every other launch keeps all of them as before. + private static func closedListRuntimeTools(of plan: DeclarativeLanguageServerLaunchPlan) -> [String] { + guard plan.toolLaunch != nil else { return plan.runtimeRequirements.map(\.tool) } + return plan.runtimeRequirements.filter { !$0.resolvesThroughDefinition }.map(\.tool) } - /// Locates the files a server's host integration consumes. Every path is - /// verified to exist inside the package before host code is given it. - func hostIntegration(for source: DeclarativeLanguageServerLaunchSource) throws -> HostIntegration? { + /// A language server whose launch names a tool definition: the plan is + /// expanded for the workspace, its package paths verified and its + /// directories created. The caller resolves the tool when it starts and + /// expands the command line with `launch.arguments` as `${arguments}`. + func resolveToolLaunch( + _ source: DeclarativeLanguageServerLaunchSource, + workspaceRootURL: URL + ) throws -> (process: DefinedToolProcessLaunch, runtimeTools: [String], launch: ResolvedLanguageServerLaunch) { + let request = request(for: source, workspaceRootURL: workspaceRootURL) let plan = try planner.languageServerLaunchPlan( manifest: source.manifest, languageID: source.languageID, - request: request(for: source, workspaceRootURL: source.packageURL) + request: request ) - guard let integration = plan.hostIntegration else { return nil } + guard let launch = plan.toolLaunch else { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "Rust Core returned no tool launch for \(source.languageID)." + ) + } try verifyPackagePaths(plan.requiredPackagePaths, packageURL: source.packageURL) - let root = source.packageURL.standardizedFileURL - return HostIntegration( - id: integration.id, - entryURL: plan.entryPath.map { root.appendingPathComponent($0).standardizedFileURL }, - resources: integration.resources.mapValues { paths in - paths.map { root.appendingPathComponent($0).standardizedFileURL } - } + let process = try toolProcess(launch, plan: plan, packageURL: source.packageURL.standardizedFileURL) + try createRequiredDirectories(of: plan, request: request) + return ( + process: process, + runtimeTools: Self.closedListRuntimeTools(of: plan), + launch: ResolvedLanguageServerLaunch( + arguments: plan.arguments, + initializationOptions: plan.initializationOptions, + workspaceConfiguration: plan.workspaceConfiguration, + sessionPolicy: plan.sessionPolicy + ) ) } @@ -652,6 +688,9 @@ struct MacPluginLanguageServerLaunchResolver { /// Runtime shipped inside the plugin package. It is the only /// executable the host may start for the server. var packagedRuntimeURL: URL? + /// True when the launch names a tool definition. The host then has no + /// executable to look up or probe; it resolves the tool at each start. + var launchesThroughTool = false } /// Probe of the server's executable. The contract forbids state @@ -667,7 +706,8 @@ struct MacPluginLanguageServerLaunchResolver { versionRequirement: plan.executableVersionRequirement, packagedRuntimeURL: plan.packagedRuntimePath.map { source.packageURL.appendingPathComponent($0).standardizedFileURL - } + }, + launchesThroughTool: plan.toolLaunch != nil ) } diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift index e6cf1dd06b..b8882866b6 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginManager.swift @@ -173,7 +173,7 @@ final class MacPluginManager: PluginManaging { case .packaged, .systemCommand: executableNames = server.executableNames case .runtime, .backend: - // A runtime such as java/node is not the server's name, and a + // A runtime such as node/python 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 diff --git a/macos/Sources/Lithe/Platform/MacOS/ProblemsDemo.swift b/macos/Sources/Lithe/Platform/MacOS/ProblemsDemo.swift index 08d934c6a6..c2d4636ed8 100644 --- a/macos/Sources/Lithe/Platform/MacOS/ProblemsDemo.swift +++ b/macos/Sources/Lithe/Platform/MacOS/ProblemsDemo.swift @@ -44,8 +44,7 @@ final class ProblemsDemo: NSObject, NSApplicationDelegate { self.model = model // Seed only the fixture root; do not start normal workspace scanners or language servers. model.workspaceSessionCoordinator.beginWorkspace(at: workspace) - let root = ProblemsView(initialScope: .file, previewEnabled: true, - runnableFileURLs: [workspace.appendingPathComponent("Main.java")]) + let root = ProblemsView(initialScope: .file, previewEnabled: true) .environmentObject(model).environmentObject(settings) .environmentObject(model.editorDiagnosticsStore) .environment(\.locale, settings.language.locale) @@ -71,7 +70,7 @@ final class ProblemsDemo: NSObject, NSApplicationDelegate { NSApp.activate(ignoringOtherApps: true) loadTask = Task { [weak self] in guard let self else { return } - await model.documentFeature.openFileAsync(workspace.appendingPathComponent("Main.java"), + await model.documentFeature.openFileAsync(workspace.appendingPathComponent("Main.txt"), isReadOnly: true, displayPath: nil, activateWhenReady: true) guard !Task.isCancelled else { return } model.editorDiagnosticsStore.replace(ProblemsDemoData.diagnostics(at: workspace)) @@ -117,34 +116,32 @@ final class ProblemsDemo: NSObject, NSApplicationDelegate { /// Synthetic data never enters the normal workspace or language-server pipeline. enum ProblemsDemoData { static let files: [String: String] = [ - "Main.java": """ - package demo; - public class Main { - public static void main(String[] args) { - int count = "not a number"; - String token = null; - int unused = 0; - oldApi(); - System.out.println("Information: a newer API is available"); - unknownProvider(); - String longMessage = "Demonstrates truncation and a complete tooltip"; - System.out.println("中文 · Unicode · emoji 🔎"); - } - @Deprecated static void oldApi() {} - } + "Main.txt": """ + # Demo document + section demo + begin + count = "not a number" + token = null + unused = 0 + oldApi() + print("Information: a newer API is available") + unknownProvider() + longMessage = "Demonstrates truncation and a complete tooltip" + print("中文 · Unicode · emoji 🔎") + end """, - "config/application.yml": """ + "config/settings.yml": """ server: port: invalid demo: missing-property: true """, - "Clean.java": "class Clean {}\n" + "Clean.txt": "clean\n" ] static func diagnostics(at root: URL) -> [URL: [EditorDiagnostic]] { - let main = root.appendingPathComponent("Main.java") - let config = root.appendingPathComponent("config/application.yml") + let main = root.appendingPathComponent("Main.txt") + let config = root.appendingPathComponent("config/settings.yml") func problem(_ id: String, file: URL, line: Int, severity: DiagnosticSeverity, message: String, tags: Set = [], related: [DiagnosticRelatedInformation] = []) -> EditorDiagnostic { EditorDiagnostic(id: id, fileURL: file, line: line, utf16Column: 4, diff --git a/macos/Sources/Lithe/Platform/MacOS/Process/MacProcessSessionTerminator.swift b/macos/Sources/Lithe/Platform/MacOS/Process/MacProcessSessionTerminator.swift index db65fa92a3..0ff7102a58 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Process/MacProcessSessionTerminator.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Process/MacProcessSessionTerminator.swift @@ -53,7 +53,7 @@ struct MacTerminalSessionOwnership: Equatable, Sendable { /// Stops every process of a POSIX session, not just its leader. /// /// An interactive shell gives each job its own process group, so signalling -/// the shell or the shell's group leaves `mvn spring-boot:run`, `nohup` jobs +/// the shell or the shell's group leaves a build tool's child servers, `nohup` jobs /// and disowned jobs running. All of them keep the session ID of the shell /// that started them, which stays addressable after the shell itself exits. enum MacProcessSessionTerminator { diff --git a/macos/Sources/Lithe/Platform/MacOS/ProjectGeneration/MacProjectGenerationPlatform.swift b/macos/Sources/Lithe/Platform/MacOS/ProjectGeneration/MacProjectGenerationPlatform.swift index 7449c34738..91e73aed22 100644 --- a/macos/Sources/Lithe/Platform/MacOS/ProjectGeneration/MacProjectGenerationPlatform.swift +++ b/macos/Sources/Lithe/Platform/MacOS/ProjectGeneration/MacProjectGenerationPlatform.swift @@ -83,13 +83,9 @@ final class MacProjectGenerationPlatform: ProjectGenerationPlatform, @unchecked onOutput: @escaping @Sendable (String) -> Void ) async throws { let (executable, environment) = await MainActor.run { () -> (URL?, [String: String]) in - var environment = self.environment(overrides) - // A JDK the generator selected also comes first on PATH, so the - // tool and anything it starts use the same Java. - if let javaHome = overrides["JAVA_HOME"], !javaHome.isEmpty { - environment["PATH"] = javaHome + "/bin:" + (environment["PATH"] ?? "") - } - return (self.executable(command.command), environment) + // Generators own their environment through the manifest `environment` + // map; the host only merges it over the process environment. + return (self.executable(command.command), self.environment(overrides)) } guard let executable else { throw ProjectGenerationError(message: String( diff --git a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift index 08722d0b56..2bf5b01e72 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemotePluginLaunchPreparer.swift @@ -64,6 +64,7 @@ final class MacRemotePluginLaunchPreparer { var runtimes = dependencies var requirement: LanguageServerExecutableVersionRequirement? switch process.executable { + case .tool: throw Self.toolLaunchUnavailable case .file(let url): candidates = [.setting(id: "pluginPackage", path: url.path)] case .commands(let commands): candidates = commands.map { .command($0) } case .runtime(let tool, let version): @@ -195,13 +196,22 @@ final class MacRemotePluginLaunchPreparer { case .runtime(let tool)?: executable = plan.packagedRuntimePath.map { .file(root.appendingPathComponent($0)) } ?? .runtime(tool, versionRequirement: plan.executableVersionRequirement) - case nil: throw CocoaError(.fileReadCorruptFile) + case nil: + if plan.toolLaunch != nil { throw Self.toolLaunchUnavailable } + throw CocoaError(.fileReadCorruptFile) } return .init(executable: executable, arguments: plan.arguments, initializationOptions: plan.initializationOptions, runtimeTools: plan.runtimeRequirements.map(\.tool), executesProjectCode: executesProjectCode, mayUseNetwork: mayUseNetwork, settings: settings) } + /// A launch that names a tool definition resolves the tool on this Mac + /// through its four layers; a remote host has no such resolution yet. + private static let toolLaunchUnavailable = DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "A launch that names a tool definition cannot start in a remote workspace yet." + ) + private func digest(_ value: String) -> String { SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined() } diff --git a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemoteRuntimeLocator.swift b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemoteRuntimeLocator.swift index 28993a0f92..6998c556e5 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemoteRuntimeLocator.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Remote/MacRemoteRuntimeLocator.swift @@ -3,22 +3,17 @@ import LitheCoreContracts import LitheModuleAPI /// A workspace-owned host snapshot. UI accessors never perform network I/O or -/// inspect this Mac; only discover runs host probes on the service's worker. +/// inspect this Mac; only `probeHost` runs host probes on the service's worker. final class MacRemoteRuntimeLocator: RuntimeLocator, RuntimeToolDiscovery, @unchecked Sendable { private struct Snapshot { var environment: [String: String] = [:] var executables: Set = [] - var java: [JavaRuntimeCandidate] = [] - var maven: [MavenRuntimeCandidate] = [] - var pathJava: String? var failure: String? - var requirements: ToolingJSONValue? } private let binding: RemoteWorkspaceBinding private let host: any RemoteRuntimeProbing private let lock = NSLock() private var snapshot = Snapshot() - private var configured: [String] = [] private var generation: UInt64 = 0 init(binding: RemoteWorkspaceBinding, host: any RemoteRuntimeProbing) { @@ -28,25 +23,8 @@ final class MacRemoteRuntimeLocator: RuntimeLocator, RuntimeToolDiscovery, @unch var discoveryFailure: String? { lock.withLock { snapshot.failure } } func environment() -> [String: String] { lock.withLock { snapshot.environment } } - func configureProbePaths(_ paths: [String]) { - lock.withLock { - guard configured != paths else { return } - configured = paths - generation &+= 1 - snapshot = Snapshot() - } - } func invalidateProbeCache() { lock.withLock { generation &+= 1; snapshot = Snapshot() } } - func selectJavaRuntime(candidates: [AutomaticJavaCandidate], fallbackID: String?) -> Result? { - let current = lock.withLock { snapshot } - guard let requirements = current.requirements else { - return .failure(.init(code: "runtime_discovery_failed", - message: current.failure ?? L10n.string("Could not discover runtimes on the remote host. Check the connection and refresh."), details: nil)) - } - return RustCoreBridge().selectJavaRuntime(requirements: requirements, candidates: candidates, fallbackID: fallbackID) - } - func normalizedPath(_ path: String, relativeTo root: URL?) -> String { var value = path.trimmingCharacters(in: .whitespacesAndNewlines) if value == "~" || value.hasPrefix("~/") { @@ -62,11 +40,10 @@ final class MacRemoteRuntimeLocator: RuntimeLocator, RuntimeToolDiscovery, @unch return value.hasPrefix("/") ? URL(fileURLWithPath: value).standardizedFileURL.path : value } - func discover() -> RuntimeDiscoveryResult { discover(isCancelled: { false }) } - func discover(isCancelled: @Sendable () -> Bool) -> RuntimeDiscoveryResult { - let (ticket, paths) = lock.withLock { () -> (UInt64, [String]) in + func probeHost(isCancelled: @Sendable () -> Bool) { + let ticket = lock.withLock { () -> UInt64 in generation &+= 1 - return (generation, configured) + return generation } var next = Snapshot() let deadline = ContinuousClock.now.advanced(by: .seconds(60)) @@ -93,45 +70,9 @@ final class MacRemoteRuntimeLocator: RuntimeLocator, RuntimeToolDiscovery, @unch guard values.count <= 16_384 else { throw ProbeError.limit } return values } - func canonical(_ path: String) throws -> String { - try check() - return try host.runtimeRealPath(path, session: binding.sessionID) - } do { try check() next.environment = try host.runtimeEnvironment(session: binding.sessionID) - try check() - next.requirements = try host.runtimeRequirements(binding.remoteRoot, session: binding.sessionID) - guard case .object = next.requirements else { throw ProbeError.invalidRequirements } - if let requirements = next.requirements { - _ = try RustCoreBridge().selectJavaRuntime(requirements: requirements, candidates: [], fallbackID: nil).get() - } - var homes = Set() - if let home = next.environment["JAVA_HOME"], home.hasPrefix("/") { homes.insert(home) } - for path in paths where !path.isEmpty { - // Use the just-read remote HOME, not the previous snapshot. - let expanded = path == "~" || path.hasPrefix("~/") ? (next.environment["HOME"] ?? "~") + path.dropFirst() : path - let resolved = expanded.hasPrefix("/") ? expanded : binding.remoteRoot + "/" + expanded - homes.insert(resolved) - if !(try executable(resolved)) { - for tool in ["mvn", "mvnd"] { - _ = try executable(resolved + "/bin/" + tool) - _ = try executable(resolved + "/" + tool) - } - } - } - let home = next.environment["HOME"] ?? "" - var roots = ["/usr/lib/jvm", "/Library/Java/JavaVirtualMachines"] - if home.hasPrefix("/") { - roots += [home + "/Library/Java/JavaVirtualMachines", - (next.environment["SDKMAN_DIR"] ?? home + "/.sdkman") + "/candidates/java"] - } - for root in roots { - for entry in try entries(root) where entry.isDirectory { - let path = root + "/" + entry.name - homes.insert(root.contains("JavaVirtualMachines") ? path + "/Contents/Home" : path) - } - } // Login PATH already includes the host's configured version managers. let searchPath = (next.environment["PATH"] ?? "").split(separator: ":").map(String.init).filter { $0.hasPrefix("/") } guard searchPath.count <= 64 else { throw ProbeError.limit } @@ -148,87 +89,28 @@ final class MacRemoteRuntimeLocator: RuntimeLocator, RuntimeToolDiscovery, @unch } else if !(try executable(path)) { continue } next.executables.insert(path) guard next.executables.count <= 65_536 else { throw ProbeError.limit } - if entry.name == "java", next.pathJava == nil { - let resolved = try canonical(path) - if resolved != "/usr/bin/java" { - let home = URL(fileURLWithPath: resolved).deletingLastPathComponent().deletingLastPathComponent().path - next.pathJava = home - homes.insert(home) - } - } - } - } - for relative in ["mvnw", "gradlew"] { _ = try executable(binding.remoteRoot + "/" + relative) } - guard homes.count <= 32 else { throw ProbeError.limit } - var seen = Set() - for home in homes.sorted() where try executable(home + "/bin/java") { - let resolved = try canonical(home) - guard seen.insert(resolved).inserted else { continue } - next.executables.insert(resolved + "/bin/java") - try check() - if let java = MacRuntimeDiscovery.javaRuntime(home: URL(fileURLWithPath: resolved), - output: try host.runtimeVersion(home + "/bin/java", session: binding.sessionID)) { - next.java.append(java) - } - } - var mavenPaths = next.executables.filter { ["mvn", "mvnd"].contains(URL(fileURLWithPath: $0).lastPathComponent) }.sorted() - for key in ["MAVEN_HOME", "M2_HOME", "MVND_HOME"] { - if let home = next.environment[key], home.hasPrefix("/") { - let path = home + "/bin/" + (key == "MVND_HOME" ? "mvnd" : "mvn") - if try executable(path) { mavenPaths.insert(path, at: 0) } } } - guard mavenPaths.count <= 16 else { throw ProbeError.limit } - for path in mavenPaths { - try check() - let output = try host.runtimeVersion(path, session: binding.sessionID) - if let version = MacRuntimeDiscovery.mavenVersion(in: output) { - let resolved = try canonical(path) - next.maven.append(MavenRuntimeCandidate(homePath: URL(fileURLWithPath: resolved).deletingLastPathComponent().deletingLastPathComponent().path, - executablePath: path, version: version)) - } - } - next.java.sort { $0.version.localizedStandardCompare($1.version) == .orderedDescending } - next.maven.sort { ($0.executablePath.hasSuffix("/mvnd") ? 1 : 0) < ($1.executablePath.hasSuffix("/mvnd") ? 1 : 0) } // log-exempt: 用户取消:调用方取消远程运行时发现 - } catch is CancellationError { return RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } + } catch is CancellationError { return } catch { // A failed/incomplete host snapshot must never authorize a launch. next = Snapshot() next.failure = L10n.string("Could not discover runtimes on the remote host. Check the connection and refresh.") } - guard !isCancelled() else { return RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } - let published = lock.withLock { () -> Bool in - guard generation == ticket else { return false } + guard !isCancelled() else { return } + lock.withLock { + guard generation == ticket else { return } snapshot = next - return true } - guard published else { return RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } - return RuntimeDiscoveryResult(javaRuntimes: next.java, mavenRuntimes: next.maven) } - private enum ProbeError: Error { case deadline, limit, invalidRequirements } - func discoverJavaRuntimes() -> [JavaRuntimeCandidate] { lock.withLock { snapshot.java } } - func discoverJavaRuntimes(isCancelled: @Sendable () -> Bool) -> [JavaRuntimeCandidate] { isCancelled() ? [] : discoverJavaRuntimes() } - func validJavaHome(path: String) -> URL? { - let path = normalizedPath(path, relativeTo: binding.root) - return isExecutable(at: URL(fileURLWithPath: path + "/bin/java")) ? URL(fileURLWithPath: path) : nil - } - func javaHomeOnPath(in candidates: [JavaRuntimeCandidate]) -> URL? { - lock.withLock { snapshot.pathJava.map { URL(fileURLWithPath: $0) } } - } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { lock.withLock { snapshot.java.first { $0.homePath == homeURL.path } } } + private enum ProbeError: Error { case deadline, limit } func isExecutable(at url: URL) -> Bool { lock.withLock { snapshot.executables.contains(normalizedPathWithoutLock(url.path)) } } private func normalizedPathWithoutLock(_ path: String) -> String { let root = binding.root.path return path == root ? binding.remoteRoot : path.hasPrefix(root + "/") ? binding.remoteRoot + path.dropFirst(root.count) : path } - func systemMavenExecutable() -> URL? { lock.withLock { snapshot.maven.first.map { URL(fileURLWithPath: $0.executablePath) } } } - func mavenExecutable(forHomePath path: String) -> URL? { - let path = normalizedPath(path, relativeTo: binding.root) - return [path, path + "/bin/mvnd", path + "/bin/mvn"].first { isExecutable(at: URL(fileURLWithPath: $0)) }.map { URL(fileURLWithPath: $0) } - } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { lock.withLock { snapshot.maven.first { $0.executablePath == executableURL.path } } } func candidates(for command: String, projectURL: URL?, environment: [String: String]) -> [RuntimeToolCandidate] { guard !command.isEmpty, !command.contains("/") else { return [] } return (environment["PATH"] ?? "").split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent(command) } diff --git a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacJavaLaunchArgumentPreparer.swift b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacJavaLaunchArgumentPreparer.swift deleted file mode 100644 index 7ae6e11924..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacJavaLaunchArgumentPreparer.swift +++ /dev/null @@ -1,168 +0,0 @@ -import LitheModuleAPI -import Darwin -import Foundation -import LitheCoreContracts -import LitheExecutionModule - -/// macOS owns the temporary file while Rust Core owns Java argument-file -/// eligibility, option placement, and quoting. -extension RustCoreBridge: JavaLaunchArgumentPreparing { - private struct Request: Encodable { - let executable: String - let arguments: [String] - let argfilePath: String - let limit: Int? - let javaReleaseContents: [String] - } - - private struct Response: Decodable { - let kind: String - let arguments: [String]? - let argfileContents: String? - } - - func prepareJavaLaunch( - executablePath: String, - arguments: [String] - ) throws -> JavaLaunchArgumentPreparation { - let path = Self.nextArgumentFileURL() - let response: Response = try executeResult( - command: "execution.planLaunchCommand", - payload: Request( - executable: executablePath, - arguments: arguments, - argfilePath: path.path, - limit: nil, - javaReleaseContents: Self.javaReleaseContents(executablePath) - ) - ).get() - - if response.kind == "direct" { - return JavaLaunchArgumentPreparation(arguments: arguments) - } - guard response.kind == "argfile", - let shortened = response.arguments, - let contents = response.argfileContents else { - throw JavaLaunchArgumentError.invalidPlan - } - do { - try FileManager.default.createDirectory( - at: path.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - guard let data = contents.data(using: .utf8) else { - throw JavaLaunchArgumentError.invalidEncoding - } - try Self.writeExclusively(data, to: path, logSink: coreLogSink) - } catch { - throw JavaLaunchArgumentError.writeFailed(path: path.path, reason: error.localizedDescription) - } - return JavaLaunchArgumentPreparation( - arguments: shortened, - lease: MacJavaLaunchArgumentLease(url: path, logSink: coreLogSink) - ) - } - - private static func nextArgumentFileURL() -> URL { - FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-run", isDirectory: true) - .appendingPathComponent("launch-\(UUID().uuidString).argfile") - } - - private static func writeExclusively(_ data: Data, to url: URL, logSink: (any LogSink)?) throws { - let descriptor = Darwin.open( - url.path, - O_WRONLY | O_CREAT | O_EXCL, - S_IRUSR | S_IWUSR - ) - guard descriptor >= 0 else { - throw NSError( - domain: NSPOSIXErrorDomain, - code: Int(errno), - userInfo: [NSLocalizedDescriptionKey: String(cString: strerror(errno))] - ) - } - do { - try data.withUnsafeBytes { bytes in - guard let baseAddress = bytes.baseAddress else { return } - var offset = 0 - while offset < bytes.count { - let written = Darwin.write( - descriptor, - baseAddress.advanced(by: offset), - bytes.count - offset - ) - guard written > 0 else { - throw NSError( - domain: NSPOSIXErrorDomain, - code: written < 0 ? Int(errno) : Int(EIO), - userInfo: [ - NSLocalizedDescriptionKey: written < 0 - ? String(cString: strerror(errno)) - : "The Java launch argument file write made no progress." - ] - ) - } - offset += written - } - } - } catch { - _ = Darwin.close(descriptor) - do { try FileManager.default.removeItem(at: url) } - catch let error as CocoaError where error.code == .fileNoSuchFile { /* No argument file remains. */ } - catch { logSink?.emit(AppStorageMaintenanceFailed(error: error, stage: "java-argfile-remove")) } - throw error - } - _ = Darwin.close(descriptor) - } - - private static func javaReleaseContents(_ executablePath: String) -> [String] { - var directory = URL(fileURLWithPath: executablePath) - .deletingLastPathComponent() - var contents: [String] = [] - for _ in 0..<6 { - let release = directory.appendingPathComponent("release") - if let text = try? String(contentsOf: release, encoding: .utf8) { - contents.append(text) - } - let parent = directory.deletingLastPathComponent() - guard parent != directory else { break } - directory = parent - } - return contents - } -} - -private enum JavaLaunchArgumentError: LocalizedError { - case invalidPlan - case invalidEncoding - case writeFailed(path: String, reason: String) - - var errorDescription: String? { - switch self { - case .invalidPlan: - L10n.string("Rust Core returned an incomplete Java argument-file plan.") - case .invalidEncoding: - L10n.string("The Java argument file could not be encoded as UTF-8.") - case .writeFailed(let path, let reason): - L10n.string("Could not write Java launch argument file at \(path): \(reason)") - } - } -} - -private final class MacJavaLaunchArgumentLease: JavaLaunchArgumentLease, @unchecked Sendable { - private let url: URL - - private let logSink: (any LogSink)? - - init(url: URL, logSink: (any LogSink)?) { - self.logSink = logSink - self.url = url - } - - deinit { - do { try FileManager.default.removeItem(at: url) } - catch let error as CocoaError where error.code == .fileNoSuchFile { /* No argument file remains. */ } - catch { logSink?.emit(AppStorageMaintenanceFailed(error: error, stage: "java-argfile-remove")) } - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunConfigurationStore.swift b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunConfigurationStore.swift index 5af59a855b..05101cf099 100644 --- a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunConfigurationStore.swift +++ b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunConfigurationStore.swift @@ -18,8 +18,8 @@ enum MacRunConfigurationStoreError: LocalizedError, Sendable { } } -/// macOS file and migration adapter for the shared Rust run-configuration domain. -/// It deliberately contains no merge or launch-command logic. +/// macOS file adapter for the shared Rust run-configuration domain. +/// It deliberately contains no merge, launch-command or language logic. struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable { private let core: RustCoreBridge private let documentMutator: any RunConfigurationDocumentMutating @@ -41,53 +41,22 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable self.documentMutator = documentMutator ?? RustRunConfigurationDocumentMutator(core: core) } - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: true, javaEntrypoints: nil) - } - func inspect( at projectURL: URL, checkFingerprint: Bool, - javaEntrypoints: JavaEntrypoints? + providerRuns: [RunProviderConfiguration]? ) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: checkFingerprint, javaEntrypoints: javaEntrypoints, projectOwnership: nil) - } - - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership]) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: false, javaEntrypoints: nil, projectOwnership: projectOwnership) - } - - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership], providerRuns: [RunProviderConfiguration]) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: false, javaEntrypoints: nil, projectOwnership: projectOwnership, providerRuns: providerRuns) - } - - private func inspect(at projectURL: URL, checkFingerprint: Bool, javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration]? = nil) -> ProjectRunConfigurationInspection { switch core.inspectRunConfiguration( at: projectURL, checkFingerprint: checkFingerprint, - javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns + providerRuns: providerRuns ) { case .success(let payload): return ProjectRunConfigurationInspection( status: payload.status == "ready" ? .ready : .missing, diagnostics: diagnostics(from: payload.diagnostics), recoveryAction: payload.status == "ready" ? .none : .regenerate, - projectToolchain: payload.toolchain.flatMap { toolchain -> ProjectToolchainSelection? in - // Generic preferences do not prove legacy defaults were migrated. - guard toolchain.java != nil || toolchain.maven != nil || toolchain.pathOverrides != nil else { return nil } - return - ProjectToolchainSelection( - javaHomePath: toolchain.java?.homePath ?? "", - mavenExecutablePath: toolchain.maven?.executablePath ?? "", - mavenJavaHomePath: toolchain.maven?.javaHomePath ?? "", - pathOverrides: toolchain.pathOverrides ?? [:] - ) - }, - hasSavedToolchainPathOverrides: payload.toolchain?.pathOverrides != nil, requiresGeneration: payload.requiresGeneration ?? (payload.status == "missing") - ) case .failure(let error): return ProjectRunConfigurationInspection( @@ -99,69 +68,23 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable } } - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration]) throws -> RunConfigurationGenerationResult { - try generateCurrent(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns) - } - - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration], - models: [BuildModel], lease: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { - try generateCurrent(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns, models: models, lease: lease) - } - /// Identifies the project's run entries in memory and the application cache. - /// The isolated legacy adapter may convert existing user Run documents. + /// Nothing is written into the workspace; plugins own their provider runs. func generate( at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil + providerRuns: [RunProviderConfiguration]?, + lease: RunConfigurationGenerationLease ) throws -> RunConfigurationGenerationResult { - try generateCurrent(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: nil) - } - - private func generateCurrent(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration]?, - models: [BuildModel] = [], lease suppliedLease: RunConfigurationGenerationLease? = nil) throws -> RunConfigurationGenerationResult { - let lease = suppliedLease ?? RunConfigurationGenerationLease() - defer { if suppliedLease == nil { lease.invalidate() } } try lease.check() let root = projectURL.standardizedFileURL guard storage.metadata(for: root)?.isDirectory == true else { throw MacRunConfigurationStoreError.invalidProject } - let paths = files.compactMap { file -> String? in - let value = file.standardizedFileURL - guard value.path.hasPrefix(root.path + "/") else { return nil } - return String(value.path.dropFirst(root.path.count + 1)) - } - let migration = MacLegacyMavenRunConfigurationMigration(storage: storage, preferences: preferences, immutableRoots: immutableRoots) try lease.check() let result = try core.generateRunConfiguration( at: root, - paths: paths, - modulePaths: modulePaths, - javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns, + providerRuns: providerRuns, cacheDirectoryURL: storage.cacheDirectory() - ).get() try lease.check() - let plan = try providerRuns.map { try migration.prepare(workspace: root, projects: projectOwnership ?? [], runs: $0, - models: models, generatedDocument: JSONEncoder().encode(result.generated), lease: lease) } - if let plan, !plan.writes.isEmpty { - let decoder = JSONDecoder() - let team = try plan.teamDocument.map { try decoder.decode(ToolingJSONValue.self, from: $0) } - let local = try plan.localDocument.map { try decoder.decode(ToolingJSONValue.self, from: $0) } - // Validate both prepared layers against the same generated snapshot - // before any user document is published. Core performs no writes. - _ = try core.resolveRunConfiguration(at: root, toolchainCandidates: [], teamDocument: team, localDocument: local).get() - try lease.check() - try migration.apply(plan, workspace: root, lease: lease) - } return RunConfigurationGenerationResult(entryCount: result.entryCount) } @@ -174,9 +97,7 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable case .success(let value): payload = value case .failure(let error): throw RunConfigurationOperationFailure(message: error.userMessage) } - let argumentLists = payload.configurations.flatMap { value in - [value.maven?.jvmArguments ?? [], value.maven?.programArguments ?? value.args ?? []] - } + let argumentLists = payload.configurations.map { $0.args ?? [] } let argumentTexts: [String] if argumentLists.isEmpty { argumentTexts = [] @@ -189,33 +110,19 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable throw MacRunConfigurationStoreError.invalidConfiguration(L10n.string("Project run configuration is invalid")) } let configurations: [EffectiveRunConfiguration] = payload.configurations.enumerated().map { index, value in - let kind = configurationKind(value.provider) - let maven = value.maven - let java = value.extensions?.java - return EffectiveRunConfiguration( + EffectiveRunConfiguration( configuration: RunConfiguration( id: value.id, name: value.name, - kind: kind, + kind: RunConfigurationKind(rawValue: value.provider) ?? .process(provider: value.provider), execution: value.execution.flatMap(RunConfigurationExecution.init(rawValue:)), - modulePath: (maven?.module ?? java?.module) == "." ? nil : (maven?.module ?? java?.module), - mainClass: maven?.mainClass ?? java?.mainClass, - sourcePath: java?.source, - mavenReactorPath: maven?.reactorPath, debugAdapter: value.debug?.adapter, disabled: value.disabled, - buildProvider: value.extensions?.build, - buildProject: java?.build + buildProvider: value.extensions?.build ), options: RunOptions( - javaHomePath: java?.homePath ?? "", workingDirectoryPath: (value.cwd ?? ".") == "." ? "" : (value.cwd ?? "."), - vmArguments: argumentTexts[index * 2], - programArguments: argumentTexts[index * 2 + 1], - activeProfiles: Set(maven?.profiles ?? []), - mavenSkipTests: maven?.skipTests, - mavenExecutablePath: java?.mavenExecutablePath ?? "", - mavenJavaHomePath: java?.mavenJavaHomePath ?? "", + programArguments: argumentTexts[index], environment: value.env ?? [:], providerRunOptions: value.extensions?.buildRun ), @@ -225,13 +132,7 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable return RunConfigurationResolution( configurations: configurations, diagnostics: diagnostics(from: payload.diagnostics), - defaultConfigurationID: payload.defaultRunConfiguration, - projectToolchain: ProjectToolchainSelection( - javaHomePath: payload.toolchain?.java?.homePath ?? "", - mavenExecutablePath: payload.toolchain?.maven?.executablePath ?? "", - mavenJavaHomePath: payload.toolchain?.maven?.javaHomePath ?? "", - pathOverrides: payload.toolchain?.pathOverrides ?? [:] - ) + defaultConfigurationID: payload.defaultRunConfiguration ) } @@ -242,42 +143,9 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable } } - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - try launchPlan( - at: projectURL, - configurationID: configurationID, - currentFile: currentFile, - classPath: classPath, - debugPort: debugPort, - mavenContext: nil - ) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - javaLaunch: JavaDebugLaunchTarget?, - debugPort: Int?, - mavenContext: MavenLaunchContext? - ) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { let value: RustCoreBridge.LaunchPlanPayload - switch core.createLaunchPlan( - at: projectURL, - configurationID: configurationID, - currentFile: currentFile, - classPath: classPath, - javaLaunch: javaLaunch, - debugPort: debugPort, - mavenContext: mavenContext - ) { + switch core.createLaunchPlan(at: projectURL, configurationID: configurationID) { case .success(let payload): value = payload case .failure(let error): throw RunConfigurationOperationFailure(message: error.userMessage) } @@ -291,33 +159,11 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable message: "The launch plan names neither a toolchain nor a command." ) } - let preLaunchSteps = try (value.preLaunchSteps ?? []).map { step -> SharedLaunchPlan.PreLaunchStep in - let stepExecutable: SharedLaunchPlan.Executable - if let toolchain = step.executable.toolchain { - stepExecutable = .toolchain(toolchain) - } else if let command = step.executable.command { - stepExecutable = .command(command) - } else { - throw RunConfigurationOperationFailure( - message: "A launch plan pre-launch step names neither a toolchain nor a command." - ) - } - return SharedLaunchPlan.PreLaunchStep( - executable: stepExecutable, - tool: step.executable.tool, - arguments: step.arguments, - classpath: step.classpath ?? [], - workingDirectory: step.workingDirectory - ) - } return SharedLaunchPlan( executable: executable, arguments: value.arguments, workingDirectory: value.workingDirectory, - environment: value.env ?? [:], - preLaunchSteps: preLaunchSteps, - classpath: value.classpath ?? [], - modulepath: value.modulepath ?? [] + environment: value.env ?? [:] ) } @@ -339,41 +185,6 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable try writeMutation(mutation, to: url, root: root) } - func saveProjectToolchain(_ toolchain: ProjectToolchainSelection, at projectURL: URL) throws { - let url = projectURL.appendingPathComponent(".lithe/run/local.json") - let expected = storage.fileExists(at: url) ? try storage.readData(from: url, options: []) : nil - try saveProjectToolchain(toolchain, at: projectURL, expecting: expected) - } - - func saveProjectToolchain(_ toolchain: ProjectToolchainSelection, at projectURL: URL, expecting expected: Data?) throws { - try Task.checkCancellation() - let root = projectURL.standardizedFileURL - let url = root.appendingPathComponent(".lithe/run/local.json") - let current = storage.fileExists(at: url) ? try storage.readData(from: url, options: []) : nil - guard current == expected else { throw ProjectRuntimeSettingsStoreError.conflict } - let payload = try core.updateRunConfigurationOptions( - at: root, - configurationID: "", - scope: .local, - options: RunOptions(), - toolchain: toolchain - ).get() - guard let data = payload.document.data(using: .utf8) else { - throw MacRunConfigurationStoreError.writeFailed("Invalid UTF-8 project environment data.") - } - // Settings can be saved before generation creates the normal ignore file. - // Protect machine paths before making the local document visible to Git. - try Task.checkCancellation() - try ensureLocalRunIgnored(at: root) - try validateWriteTarget(url, root: root) - try storage.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try Task.checkCancellation() - guard try storage.replaceDataPreservingMetadata(data, at: url, expecting: expected) else { - throw ProjectRuntimeSettingsStoreError.conflict - } - MacFileWriteEventSuppression.markWritten(url) - } - /// The generic editor replaces only preferences; it must not generate any /// legacy language/build defaults or claim those sources were migrated. func saveToolPreferences(_ preferences: ToolingJSONValue, at projectURL: URL, expecting expected: Data?) throws { @@ -433,7 +244,6 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable func saveEditorChanges( _ options: RunOptions, - toolchain: ProjectToolchainSelection, configurationID: String, scope: RunConfigurationSaveScope, at projectURL: URL @@ -444,8 +254,7 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable at: root, configurationID: configurationID, scope: scope, - options: options, - toolchain: toolchain + options: options ) { case .success(let value): mutation = value case .failure(let error): @@ -497,56 +306,6 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable return id } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { - let root = projectURL.standardizedFileURL - let fileName = draft.scope == .local ? "local.json" : "configurations.json" - let url = root.appendingPathComponent(".lithe/run/\(fileName)") - let mutation = try documentMutator.createConfigurationDocument(at: root, draft: draft) - guard let id = mutation.configurationID else { - throw MacRunConfigurationStoreError.invalidConfiguration( - "The shared core did not return a configuration ID." - ) - } - try writeMutation(mutation, to: url, root: root) - return id - } - - /// Converts the legacy per-project UserDefaults values into local-only JSON once. - /// Existing values are retained as a rollback source for one release cycle. - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws { - let root = projectURL.standardizedFileURL - let projectKey = root.path.replacingOccurrences(of: "/", with: "_") - let markerKey = "lithe.run-configuration-migrated.\(projectKey)" - if preferences.object(forKey: markerKey) as? Bool == true { return } - let localURL = root.appendingPathComponent(".lithe/run/local.json") - if !storage.fileExists(at: localURL) { - let document: [String: Any] = ["version": 1, "configurations": []] - let data = try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys, .prettyPrinted]) - try validateWriteTarget(localURL, root: root) - try storage.createDirectory(at: localURL.deletingLastPathComponent(), withIntermediateDirectories: true) - try atomicWrite(data, to: localURL, root: root) - for id in configurationIDs { - let key = "lithe.java-run-options.\(projectKey).\(id)" - guard let data = preferences.data(forKey: key), - let options = try? JSONDecoder().decode(RunOptions.self, from: data) else { continue } - let mutation = try documentMutator.updateOptionsDocument( - at: root, - configurationID: id, - scope: .local, - options: options - ) - try writeMutation(mutation, to: localURL, root: root) - } - try migrateLegacyToolchainsIntoServices( - root: root, - projectKey: projectKey, - configurationIDs: configurationIDs, - localURL: localURL - ) - } - preferences.set(true, forKey: markerKey) - } - private func atomicWrite(_ data: Data, to url: URL, root: URL) throws { try validateWriteTarget(url, root: root) if storage.fileExists(at: url), @@ -587,59 +346,6 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable ].first(where: message.contains) } - private func migrateLegacyToolchainsIntoServices( - root: URL, - projectKey: String, - configurationIDs: [String], - localURL: URL - ) throws { - let key = "lithe.project-runtime.\(projectKey)" - guard let data = preferences.data(forKey: key), - let settings = try? JSONDecoder().decode(ProjectRuntimeSettings.self, from: data) else { return } - let mavenExecutable = settings.mavenHomeSelection == .custom && !settings.mavenHomePath.isEmpty - ? URL(fileURLWithPath: settings.mavenHomePath).appendingPathComponent("bin/mvn").path - : (settings.mavenHomeSelection == .wrapper ? "./mvnw" : "") - guard !settings.javaHomePath.isEmpty || !mavenExecutable.isEmpty || !settings.mavenJavaHomePath.isEmpty else { return } - for id in configurationIDs { - let legacyKey = "lithe.java-run-options.\(projectKey).\(id)" - var options: RunOptions - do { options = try preferences.data(forKey: legacyKey).map { try JSONDecoder().decode(RunOptions.self, from: $0) } ?? RunOptions() } - catch { - core.coreLogSink?.emit(AppStorageMaintenanceFailed(error: error, stage: "legacy-run-options")) - options = RunOptions() - } - options.javaHomePath = settings.javaHomePath - options.mavenExecutablePath = mavenExecutable - options.mavenJavaHomePath = settings.mavenJavaHomePath - let mutation = try documentMutator.updateOptionsDocument( - at: root, - configurationID: id, - scope: .local, - options: options - ) - try writeMutation(mutation, to: localURL, root: root) - } - } - - private func jsonDocument( - at url: URL, - fallbackKey: String, - fallbackValue: Any = [] - ) throws -> [String: Any] { - guard storage.fileExists(at: url) else { return ["version": 1, fallbackKey: fallbackValue] } - let data = try storage.readData(from: url, options: []) - guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - throw MacRunConfigurationStoreError.writeFailed("Existing local configuration is invalid.") - } - return value - } - - private func set(_ value: String, key: String, in dictionary: inout [String: String]) { - let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines) - if normalized.isEmpty { dictionary.removeValue(forKey: key) } - else { dictionary[key] = normalized } - } - private func ensureLocalRunIgnored(at root: URL) throws { let url = root.appendingPathComponent(".lithe/.gitignore") try validateWriteTarget(url, root: root) @@ -756,19 +462,6 @@ struct MacRunConfigurationStore: RunConfigurationOperations, @unchecked Sendable }) else { throw ProjectRuntimeSettingsStoreError.conflict } } - private func configurationKind(_ value: String) -> RunConfigurationKind { - switch value { - case "java.current-file": .currentFile - case "java.main": .javaMain - case "maven.module": .mavenModule - default: - if let framework = MavenFrameworkKind.allCases.first(where: { $0.provider == value }) { - .mavenFramework(framework) - } else { - .process(provider: value) - } - } - } } private struct PreparedRunDocumentWrite { @@ -798,13 +491,6 @@ private struct RustRunConfigurationDocumentMutator: RunConfigurationDocumentMuta ).get()) } - func createConfigurationDocument( - at projectURL: URL, - draft: RunConfigurationDraft - ) throws -> RunConfigurationDocumentMutation { - try mutation(from: core.createUserRunConfiguration(at: projectURL, draft: draft).get()) - } - private func mutation( from payload: RustCoreBridge.RunConfigurationMutationPayload ) throws -> RunConfigurationDocumentMutation { @@ -816,11 +502,3 @@ private struct RustRunConfigurationDocumentMutator: RunConfigurationDocumentMuta return RunConfigurationDocumentMutation(configurationID: payload.id, document: data) } } - -private extension JSONEncoder { - static var prettySorted: JSONEncoder { - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - return encoder - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunLaunchEnvironment.swift b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunLaunchEnvironment.swift index 73d5aaac49..7752f36d67 100644 --- a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunLaunchEnvironment.swift +++ b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/MacRunLaunchEnvironment.swift @@ -15,8 +15,6 @@ extension RustCoreBridge: RunLaunchEnvironmentResolving { private struct LaunchEnvironmentPayload: Encodable { let toolchain: String? - let javaHome: String? - let mavenJavaHome: String? let inherited: [String: String] let overrides: [String: String] } @@ -26,13 +24,13 @@ extension RustCoreBridge: RunLaunchEnvironmentResolving { } func resolveLaunchEnvironment( - toolchain: String?, selectedHome: String?, + toolchain: String?, inherited: [String: String], overrides: [String: String] ) throws -> [String: String] { let result: LaunchEnvironmentResult = try executeResult( command: "execution.resolveEnvironment", payload: LaunchEnvironmentPayload( - toolchain: toolchain, javaHome: selectedHome, mavenJavaHome: selectedHome, + toolchain: toolchain, inherited: inherited, overrides: overrides ) ).get() diff --git a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/RunServiceCompatibility.swift b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/RunServiceCompatibility.swift index b60b1e0963..524df50c9d 100644 --- a/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/RunServiceCompatibility.swift +++ b/macos/Sources/Lithe/Platform/MacOS/RunConfiguration/RunServiceCompatibility.swift @@ -10,7 +10,6 @@ extension LitheExecutionModule.RunService { processFactory: @escaping () -> any StreamingProcess, fileStorage: any FileStorage, preferences: any KeyValueStore, - javaMavenOperations: any JavaMavenOperations, runConfigurationOperations: any RunConfigurationOperations, executableResolver: (any RunExecutableResolving)? = nil, languageProviderCatalog: LanguageProviderCatalog = .standard, @@ -19,12 +18,10 @@ extension LitheExecutionModule.RunService { ) { let catalog = languagePackRegistry?.catalog ?? languageProviderCatalog self.init( - runtime: runtimeService, process: process, processFactory: processFactory, fileAccess: MacRunFileAccess(storage: fileStorage), preferences: MacRunPreferenceStore(store: preferences), - serverPortParser: javaMavenOperations, runConfigurationOperations: runConfigurationOperations, executableResolver: executableResolver ?? RunExecutableResolver(runtimeService: runtimeService), languageProviderCatalog: catalog, diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacDefinedToolchainResolver.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacDefinedToolchainResolver.swift index 3a674e7b1e..2c7e246c3c 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacDefinedToolchainResolver.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacDefinedToolchainResolver.swift @@ -103,11 +103,20 @@ extension MacDefinedToolchainResolver: DefinedToolLaunching { /// Core expands the template; this adapter only supplies the registry of the /// installed definitions and the installation the user's layers selected. func launch(of selection: ResolvedDefinedToolchain, tool: String, arguments: [String]) throws -> DefinedToolLaunch { + try launch(of: selection, tool: tool, entry: nil, runtimeArguments: [], arguments: arguments) + } + + /// Expands the definition's `launch` template with an entry and runtime + /// arguments as well. Core alone places each part, so the host adds no + /// argument of its own and a template that cannot take a part refuses it. + func launch(of selection: ResolvedDefinedToolchain, tool: String, entry: String?, + runtimeArguments: [String], arguments: [String]) throws -> DefinedToolLaunch { struct Payload: Encodable { let registry: ToolingJSONValue let tool: String let executable: String let home: String? + let entry: String? let runtimeArguments: [String] let arguments: [String] } @@ -121,7 +130,7 @@ extension MacDefinedToolchainResolver: DefinedToolLaunching { throw DefinedToolLaunchRejection(code: "plugin.toolchain.invalidParams", message: "The tool registry is invalid.") } let payload = Payload(registry: registry, tool: tool, executable: selection.executable.path, - home: selection.home, runtimeArguments: [], arguments: arguments) + home: selection.home, entry: entry, runtimeArguments: runtimeArguments, arguments: arguments) let expansion: Expansion = try RustCoreBridge().executeResult( command: "toolchains.instantiateLaunch", payload: payload).get() if let launch = expansion.launch { @@ -132,3 +141,105 @@ extension MacDefinedToolchainResolver: DefinedToolLaunching { message: error?.message ?? "The tool launch could not be expanded.") } } + +/// A process whose launch plan names a tool definition (`launch.kind` `tool`), +/// with the package paths already checked. +struct DefinedToolProcessLaunch: Equatable, Sendable { + /// Tool, entry, runtime arguments and minimum version from Rust Core's plan. + let launch: DeclarativeLanguageServerLaunchPlan.ToolLaunch + /// The runtime the plugin ships, checked to be an executable file inside + /// the package; the host runs it as the tool and never looks the tool up. + let packagedRuntimeURL: URL? + /// Every tool the plan's `runtimeRequirements` asks the host to resolve. + /// Their exports and `PATH` entries join the process environment. + let requirements: [DeclarativeLanguageServerLaunchPlan.RuntimeRequirement] +} + +/// The command line and environment that start a tool-definition launch. +struct DefinedToolCommand: Equatable, Sendable { + let executableURL: URL + /// Every argument after the executable, in the order of the definition's + /// `launch` template. + let arguments: [String] + let environment: [String: String] +} + +extension MacDefinedToolchainResolver { + /// Resolves the tools a process needs through the four layers, then lets + /// Core place the entry, runtime arguments and `arguments` by the launch + /// template. `arguments` are the plugin's own and fill `${arguments}`. + /// + /// A tool no layer resolves is `plugin.host.toolUnresolved`; a template + /// that cannot carry the parts keeps Core's own code. + func command( + for process: DefinedToolProcessLaunch, + arguments: [String], + workspace: URL, + directory: String = ".", + environment: [String: String], + projectCodeAllowed: Bool + ) async throws -> DefinedToolCommand { + let tool = process.launch.tool + var environment = environment + // Each selection's environment already holds the one it was given, so + // resolving in order chains every tool's exports and `PATH` entries. + for requirement in process.requirements where requirement.tool != tool { + environment = try await installation( + of: requirement.tool, minimumVersion: requirement.minimumVersion, workspace: workspace, + directory: directory, environment: environment, projectCodeAllowed: projectCodeAllowed + ).environment + } + let selection: ResolvedDefinedToolchain + if let packaged = process.packagedRuntimeURL { + selection = ResolvedDefinedToolchain(executable: packaged, environment: environment, + projectCode: false, version: nil) + } else { + selection = try await installation( + of: tool, minimumVersion: process.launch.minimumVersion, workspace: workspace, + directory: directory, environment: environment, projectCodeAllowed: projectCodeAllowed + ) + } + let expanded: DefinedToolLaunch + do { + expanded = try launch(of: selection, tool: tool, entry: process.launch.entry, + runtimeArguments: process.launch.runtimeArguments, arguments: arguments) + } catch let rejection as DefinedToolLaunchRejection { + throw DeclarativePluginRejection(code: rejection.code, message: rejection.message) + } + return DefinedToolCommand(executableURL: URL(fileURLWithPath: expanded.executable), + arguments: expanded.arguments, environment: selection.environment) + } + + /// One tool's installation, read without its entry recipe, which `command` + /// expands itself. + private func installation( + of tool: String, + minimumVersion: String?, + workspace: URL, + directory: String, + environment: [String: String], + projectCodeAllowed: Bool + ) async throws -> ResolvedDefinedToolchain { + let selected: ResolvedDefinedToolchain? + do { + selected = try await resolve( + tool: tool, directory: directory, workspace: workspace, environment: environment, + minimumVersion: minimumVersion, projectCodeAllowed: projectCodeAllowed, + fixed: nil, use: .installation, consumerID: nil + ) + } catch is BuildToolResolutionError { + let requirement = minimumVersion.map { " at version \($0) or later" } ?? "" + throw DeclarativePluginRejection( + code: "plugin.host.toolUnresolved", + message: "No usable installation of the tool \(tool)\(requirement) was found (unusable)." + ) + } + guard let selected else { + throw DeclarativePluginRejection( + code: "plugin.host.toolUnresolved", + message: "No enabled plugin defines the tool \(tool) (notFound)." + ) + } + return selected + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacLoginShellEnvironment.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacLoginShellEnvironment.swift index 5d415c1a59..1fbfafa06f 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacLoginShellEnvironment.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacLoginShellEnvironment.swift @@ -9,8 +9,8 @@ import Foundation /// The environment of the user's interactive login shell, for an app started from /// Finder or the Dock. /// -/// launchd gives such an app only `/usr/bin:/bin:/usr/sbin:/sbin`, so Maven, JDKs, -/// Node.js and Gradle installed through Homebrew, mise, SDKMAN, asdf or fnm are +/// launchd gives such an app only `/usr/bin:/bin:/usr/sbin:/sbin`, so tools such as +/// Node.js and Python installed through Homebrew, mise, SDKMAN, asdf or fnm are /// invisible to discovery and to every child process. Patching each tool's lookup /// fixed one tool at a time; reading the shell once fixes all of them. /// diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift deleted file mode 100644 index 7a1ab7fe56..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeDiscovery.swift +++ /dev/null @@ -1,310 +0,0 @@ -import Foundation - -enum MacRuntimeDiscovery { - private static let probeCache = MacRuntimeProbeCache() - - static func invalidateProbeCaches() { probeCache.invalidate() } - - static func discover(environment: [String: String]) -> RuntimeDiscoveryResult { - let javaRuntimes = discoverJavaRuntimes(environment: environment) - let mavenRuntimes = discoverMavenExecutables(environment: environment) - .compactMap(probeMaven) - .sorted { lhs, rhs in - lhs.version.localizedStandardCompare(rhs.version) == .orderedDescending - } - return RuntimeDiscoveryResult(javaRuntimes: javaRuntimes, mavenRuntimes: mavenRuntimes) - } - - static func systemMavenExecutable(environment: [String: String]) -> URL? { - discoverMavenExecutables(environment: environment).first - } - - static func mavenExecutable(forHomePath path: String) -> URL? { - let expanded = (path as NSString).expandingTildeInPath - let url = URL(fileURLWithPath: expanded).standardizedFileURL - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { - return nil - } - let candidates: [URL] - if isDirectory.boolValue { - // A daemon distribution must launch its client, not its embedded Maven. - candidates = [url.appendingPathComponent("bin"), url].flatMap { bin in - ["mvnd", "mvn"].map { bin.appendingPathComponent($0) } - } - } else { - candidates = [url] - } - return candidates.first { MacRuntimeLocator().isExecutable(at: $0) } - } - - static func validJavaHome(_ path: String) -> URL? { - let url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath).standardizedFileURL - return FileManager.default.isExecutableFile(atPath: url.appendingPathComponent("bin/java").path) - ? url - : nil - } - - static func discoverJavaRuntimes( - environment: [String: String], isCancelled: @Sendable () -> Bool = { false } - ) -> [JavaRuntimeCandidate] { - guard !isCancelled() else { return [] } - let homes = discoverJavaHomes(environment: environment) - var runtimes: [JavaRuntimeCandidate] = [] - for home in homes { - guard !isCancelled() else { return [] } - if let runtime = probeJavaHome(home) { runtimes.append(runtime) } - } - return runtimes.sorted { lhs, rhs in - lhs.version.localizedStandardCompare(rhs.version) == .orderedDescending - } - } - - static func javaHomeOnPath(environment: [String: String]) -> URL? { - for directory in (environment["PATH"] ?? "").split(separator: ":") { - let executable = URL(fileURLWithPath: String(directory), isDirectory: true).appendingPathComponent("java") - guard FileManager.default.isExecutableFile(atPath: executable.path) else { continue } - let resolved = executable.resolvingSymlinksInPath() - // Apple's system launcher selects a JDK itself; /usr is not a JDK - // home and must never become JAVA_HOME for child processes. - guard resolved.path != "/usr/bin/java" else { return nil } - return validJavaHome(resolved.deletingLastPathComponent().deletingLastPathComponent().path) - } - return nil - } - - private static func discoverJavaHomes(environment: [String: String]) -> [URL] { - discoverJavaHomes( - environment: environment, - homeDirectory: NSHomeDirectory(), - javaHomePaths: javaHomeOutput(), - directoryEntries: directoryNames(at:) - ) - } - - static func discoverJavaHomes( - environment: [String: String], - homeDirectory: String, - javaHomePaths: [String], - directoryEntries: (String) -> [String] - ) -> [URL] { - var paths: [String: URL] = [:] - func add(_ path: String?) { - guard let path, - let home = validJavaHome(path) else { return } - let identity = home.resolvingSymlinksInPath().path - if paths[identity] == nil { - paths[identity] = home - } - } - - add(environment["JAVA_HOME"]) - for path in javaHomePaths { - add(path) - } - - for root in [ - "/Library/Java/JavaVirtualMachines", - homeDirectory + "/Library/Java/JavaVirtualMachines" - ] { - for entry in directoryEntries(root).sorted() { - add(root + "/" + entry + "/Contents/Home") - } - } - - for root in ["/opt/homebrew/opt", "/usr/local/opt"] { - for entry in directoryEntries(root).sorted() where entry.hasPrefix("openjdk") { - add(root + "/" + entry + "/libexec/openjdk.jdk/Contents/Home") - } - } - - let sdkmanRoot = environment["SDKMAN_DIR"] - .flatMap { $0.isEmpty ? nil : $0 } - ?? homeDirectory + "/.sdkman" - let sdkmanJavaRoot = URL(fileURLWithPath: sdkmanRoot, isDirectory: true) - .appendingPathComponent("candidates/java", isDirectory: true) - .standardizedFileURL.path - for entry in directoryEntries(sdkmanJavaRoot).sorted() { - add(sdkmanJavaRoot + "/" + entry) - } - - // IDEA's downloads, then mise (which keeps a macOS JDK as its bundle) and asdf. - let roots = [homeDirectory + "/.jdks"] - + versionManagerInstallRoots(tool: "java", environment: environment, homeDirectory: homeDirectory) - for root in roots { - for entry in directoryEntries(root).sorted() { - add(root + "/" + entry + "/Contents/Home") - add(root + "/" + entry) - } - } - - return paths.values.sorted { $0.path < $1.path } - } - - /// Install directories of `tool` kept by mise and asdf. Their shims resolve to the - /// manager's own binary rather than a home, so the installs are read directly. - /// Mirrors OpenIDEA's version-manager detection - /// (https://github.com/l0ng-ai/openidea, Apache-2.0); see the repository NOTICE. - static func versionManagerInstallRoots( - tool: String, environment: [String: String], homeDirectory: String - ) -> [String] { - func value(_ key: String) -> String? { environment[key].flatMap { $0.isEmpty ? nil : $0 } } - let mise = value("MISE_DATA_DIR") - ?? (value("XDG_DATA_HOME") ?? homeDirectory + "/.local/share") + "/mise" - let asdf = value("ASDF_DATA_DIR") ?? homeDirectory + "/.asdf" - return [mise + "/installs/" + tool, asdf + "/installs/" + tool] - } - - static func discoverMavenExecutables( - environment: [String: String], - homeDirectory: String = NSHomeDirectory(), - directoryEntries: (String) -> [String] = directoryNames(at:), - isExecutable: (URL) -> Bool = { MacRuntimeLocator().isExecutable(at: $0) } - ) -> [URL] { - var paths: [URL] = [] - var seen = Set() - func add(_ path: String) { - let expanded = (path as NSString).expandingTildeInPath - let url = URL(fileURLWithPath: expanded).standardizedFileURL - // `latest`/`current` aliases of a version manager point at a listed install. - guard isExecutable(url), seen.insert(url.resolvingSymlinksInPath().path).inserted else { return } - paths.append(url) - } - - for key in ["MAVEN_HOME", "M2_HOME"] { - if let home = environment[key], !home.isEmpty { - add(URL(fileURLWithPath: home).appendingPathComponent("bin/mvn").path) - } - } - // A version manager's shim is a link to the manager, not a Maven home; the - // install it stands for is listed below with its real home. - let pathDirectories = (environment["PATH"] ?? "").split(separator: ":").map(String.init) - .filter { URL(fileURLWithPath: $0).lastPathComponent != "shims" } - for directory in pathDirectories { - add(URL(fileURLWithPath: directory).appendingPathComponent("mvn").path) - } - let sdkmanRoot = environment["SDKMAN_DIR"].flatMap { $0.isEmpty ? nil : $0 } ?? homeDirectory + "/.sdkman" - let installRoots = [sdkmanRoot + "/candidates/maven"] - + versionManagerInstallRoots(tool: "maven", environment: environment, homeDirectory: homeDirectory) - for root in installRoots { - for entry in directoryEntries(root).sorted() { - add(root + "/" + entry + "/bin/mvn") - } - } - for path in [ - "/opt/homebrew/opt/maven/bin/mvn", - "/opt/homebrew/bin/mvn", - "/usr/local/opt/maven/bin/mvn", - "/usr/local/bin/mvn", - "/usr/bin/mvn" - ] { - add(path) - } - // Preserve ordinary Maven preference even when mvnd appears earlier on PATH. - // Discovery only inspects files; importing Java must not start a daemon. - if let home = environment["MVND_HOME"], !home.isEmpty { - add(URL(fileURLWithPath: home).appendingPathComponent("bin/mvnd").path) - } - for directory in pathDirectories { - add(URL(fileURLWithPath: directory).appendingPathComponent("mvnd").path) - } - for path in [ - "/opt/homebrew/opt/mvnd/bin/mvnd", - "/opt/homebrew/bin/mvnd", - "/usr/local/opt/mvnd/bin/mvnd", - "/usr/local/bin/mvnd" - ] { - add(path) - } - return paths - } - - static func probeJavaHome(_ home: URL) -> JavaRuntimeCandidate? { - let output = cachedCommandOutput( - executable: home.appendingPathComponent("bin/java"), - arguments: ["-version"], dependencies: [home.appendingPathComponent("release")], - accepts: { firstCapture(pattern: #"version\s+\"([^\"]+)\""#, in: $0) != nil } - ) - return javaRuntime(home: home, output: output) - } - - /// Local and remote probes share the upstream version/banner parser. - static func javaRuntime(home: URL, output: String) -> JavaRuntimeCandidate? { - guard let version = firstCapture(pattern: #"version\s+\"([^\"]+)\""#, in: output) else { - return nil - } - let vendor = output - .split(separator: "\n") - .map(String.init) - .first(where: { $0.contains("Runtime Environment") || $0.contains("VM") })? - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return JavaRuntimeCandidate(homePath: home.path, version: version, vendor: vendor) - } - - static func probeMaven(_ executable: URL) -> MavenRuntimeCandidate? { - let resolvedExecutable = executable.resolvingSymlinksInPath() - let distribution = resolvedExecutable.deletingLastPathComponent().deletingLastPathComponent() - let homeURL = resolvedExecutable.lastPathComponent == "mvnd" - ? distribution.appendingPathComponent("mvn") : distribution - let library = homeURL.appendingPathComponent("lib") - let libraries = directoryNames(at: library.path).filter { $0.hasPrefix("maven-core-") }.sorted() - let wrapper = resolvedExecutable.deletingLastPathComponent().appendingPathComponent(".mvn/wrapper") - let output = cachedCommandOutput( - executable: executable, arguments: ["-version"], - dependencies: [library] + libraries.map { library.appendingPathComponent($0) } - + [wrapper.appendingPathComponent("maven-wrapper.properties"), wrapper.appendingPathComponent("maven-wrapper.jar")], - accepts: { mavenVersion(in: $0) != nil } - ) - guard let version = mavenVersion(in: output) else { return nil } - return MavenRuntimeCandidate(homePath: distribution.path, executablePath: executable.path, version: version) - } - - static func mavenVersion(in output: String) -> String? { - // mvnd prints its own banner before the embedded Apache Maven version. - firstCapture(pattern: #"Apache Maven\s+([0-9][^\s\x1B]*)"#, in: output) - } - - private static func javaHomeOutput() -> [String] { - let roots = ["/Library/Java/JavaVirtualMachines", NSHomeDirectory() + "/Library/Java/JavaVirtualMachines"] - let dependencies = roots.flatMap { root in - [URL(fileURLWithPath: root)] + directoryNames(at: root).sorted().map { - URL(fileURLWithPath: root).appendingPathComponent($0) - } - } - let output = cachedCommandOutput( - executable: URL(fileURLWithPath: "/usr/libexec/java_home"), - arguments: ["-V"], dependencies: dependencies, accepts: { _ in true } - ) - return output - .split(separator: "\n") - .compactMap { line in - firstCapture(pattern: #"(\/[^\s]+\/Contents\/Home)"#, in: String(line)) - } - } - - static func directoryNames(at path: String) -> [String] { - (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? [] - } - - private static func cachedCommandOutput( - executable: URL, arguments: [String], dependencies: [URL], accepts: (String) -> Bool - ) -> String { - probeCache.value(for: MacRuntimeProbeCache.key(executable: executable, dependencies: dependencies)) { - let result = MacProcessRunner().run(ProcessRequest( - executablePath: executable.path, arguments: arguments, timeoutMilliseconds: 5_000 - )) - return result.succeeded && accepts(result.output) ? result.output : nil - } ?? "" - } - - private static func firstCapture(pattern: String, in input: String) -> String? { - guard let expression = try? NSRegularExpression(pattern: pattern), - let match = expression.firstMatch( - in: input, - range: NSRange(input.startIndex.. 1, - let range = Range(match.range(at: 1), in: input) else { return nil } - return String(input[range]) - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeLocator.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeLocator.swift index bd09a7aa65..9414d0ed05 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeLocator.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeLocator.swift @@ -15,36 +15,6 @@ struct MacRuntimeLocator: RuntimeLocator { return String(cString: buffer) } - func discover() -> RuntimeDiscoveryResult { - MacRuntimeDiscovery.discover(environment: environment()) - } - - func discoverJavaRuntimes() -> [JavaRuntimeCandidate] { - MacRuntimeDiscovery.discoverJavaRuntimes(environment: environment()) - } - - func discoverJavaRuntimes(isCancelled: @Sendable () -> Bool) -> [JavaRuntimeCandidate] { - MacRuntimeDiscovery.discoverJavaRuntimes(environment: environment(), isCancelled: isCancelled) - } - - func invalidateProbeCache() { MacRuntimeDiscovery.invalidateProbeCaches() } - - func validJavaHome(path: String) -> URL? { - MacRuntimeDiscovery.validJavaHome(path) - } - - func javaHomeOnPath(in candidates: [JavaRuntimeCandidate]) -> URL? { - guard let home = MacRuntimeDiscovery.javaHomeOnPath(environment: environment()) else { return nil } - return candidates.lazy.compactMap { candidate -> URL? in - let url = URL(fileURLWithPath: candidate.homePath, isDirectory: true) - return url.resolvingSymlinksInPath().path == home.resolvingSymlinksInPath().path ? url : nil - }.first - } - - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { - MacRuntimeDiscovery.probeJavaHome(homeURL) - } - func isExecutable(at url: URL) -> Bool { // Directory execute permission allows traversal, not process launch. // Follow symlinks so linked toolchain homes are rejected as well. @@ -53,16 +23,4 @@ struct MacRuntimeLocator: RuntimeLocator { !isDirectory.boolValue else { return false } return FileManager.default.isExecutableFile(atPath: url.path) } - - func systemMavenExecutable() -> URL? { - MacRuntimeDiscovery.systemMavenExecutable(environment: environment()) - } - - func mavenExecutable(forHomePath path: String) -> URL? { - MacRuntimeDiscovery.mavenExecutable(forHomePath: path) - } - - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { - MacRuntimeDiscovery.probeMaven(executableURL) - } } diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift index 33d101d09c..8e1cff6dca 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacRuntimeToolDiscovery.swift @@ -174,13 +174,6 @@ struct MacRuntimeToolDiscovery: RuntimeToolDiscovery { summary: "Rust tooling (\(command)) was not found.", recovery: "Install Rust with rustup and ensure Cargo's bin directory is on PATH." ) - case "java-debug-adapter", "java-debug": - return RuntimeToolGuidance( - command: command, - displayName: "Java Debug Adapter", - summary: "A Java DAP adapter was not found.", - recovery: "Reinstall Lithe's bundled Java language and Debug Adapter resources." - ) case "intelephense": return RuntimeToolGuidance( command: command, diff --git a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacToolchainPreferencesStore.swift b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacToolchainPreferencesStore.swift index a3036652e1..adc7b2a6b4 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Runtime/MacToolchainPreferencesStore.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Runtime/MacToolchainPreferencesStore.swift @@ -80,7 +80,7 @@ final class MacToolchainPreferencesStore: ToolchainPreferencesStoring { }) else { throw ToolchainSettingsLoadError.readFailed } let bytes = try MacToolchainSettingsLoader.safeNativeRead(url, maximumBytes: 2_097_152) let store = MacRunConfigurationStore(core: core, storage: storage, preferences: MacUserDefaultsStore(), immutableRoots: immutable) - let inspection = store.inspect(at: workspace, checkFingerprint: false, javaEntrypoints: nil) + let inspection = store.inspect(at: workspace, checkFingerprint: false, providerRuns: nil) if case .invalid = inspection.status { throw ToolchainSettingsLoadError.invalidLocal } guard try MacToolchainSettingsLoader.safeNativeRead(url, maximumBytes: 2_097_152) == bytes else { throw ProjectRuntimeSettingsStoreError.conflict } let run = try bytes.map { try JSONDecoder().decode(ToolingJSONValue.self, from: $0) } @@ -93,3 +93,16 @@ final class MacToolchainPreferencesStore: ToolchainPreferencesStoring { return Reading(snapshot: .init(workspace: workspace, document: document, revision: revision), bytes: bytes) } } + +/// Failures shared by the conditional writers of the project's local run +/// document. The messages tell the user that their draft is kept. +enum ProjectRuntimeSettingsStoreError: LocalizedError { + case conflict + case readBack + var errorDescription: String? { + switch self { + case .conflict: L10n.string("Project environment settings changed on disk. Reload before saving; your draft has been kept.") + case .readBack: L10n.string("Could not verify the saved project environment settings. The previous preferences have been kept when possible.") + } + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/ToolchainSettingsDemo.swift b/macos/Sources/Lithe/Platform/MacOS/ToolchainSettingsDemo.swift index 9770b48919..2ed3fd6f9e 100644 --- a/macos/Sources/Lithe/Platform/MacOS/ToolchainSettingsDemo.swift +++ b/macos/Sources/Lithe/Platform/MacOS/ToolchainSettingsDemo.swift @@ -137,7 +137,7 @@ final class ToolchainSettingsDemo: NSObject, NSApplicationDelegate { } let root = scratch.appendingPathComponent("sample-workspace", isDirectory: true) let files = [ - "mise.toml": "[tools]\njava = \"21\"\nnode = \"22\"\n", + "mise.toml": "[tools]\ntool-a = \"21\"\nnode = \"22\"\n", "packages/web/.nvmrc": "22\n", "services/api/.python-version": "3.12\n", ".lithe/toolchains/local.json": """ @@ -182,16 +182,15 @@ final class ToolchainSettingsDemo: NSObject, NSApplicationDelegate { /// Sample manifests standing in for installed official plugins; the host itself knows none of these tools. /// They are complete production manifests, so Core admits them and discovery scans this Mac for real. static let samplePlugins: [ToolchainSettingsPluginSource] = [ - sample("dev.lithe.sample.jvm", "JVM (sample)", definitions: [ - tool("java", "JDK", layout: "bin/java", version: (["-version"], #"version \"(?:1\.)?(\d+(?:\.\d+)*)"#), - variable: "JAVA_HOME", command: "java", - homeLayouts: [["match": "*.jdk", "home": "Contents/Home"], ["match": "*", "home": "."]], - discovery: [absolute("/Library/Java/JavaVirtualMachines", "*.jdk"), - home("Library/Java/JavaVirtualMachines/*.jdk"), home(".sdkman/candidates/java/*"), - absolute("/opt/homebrew/Cellar", "openjdk*/*")]), - tool("maven", "Maven", layout: "bin/mvn", version: (["--version"], #"Apache Maven (\d+(?:\.\d+)*)"#), - variable: "MAVEN_HOME", command: "mvn", - discovery: [absolute("/opt/homebrew/Cellar", "maven/*"), home(".sdkman/candidates/maven/*")]) + sample("dev.lithe.sample.toolkit", "Toolkit (sample)", definitions: [ + tool("tool-a", "Tool A", layout: "bin/tool-a", version: (["--version"], #"tool-a (\d+(?:\.\d+)*)"#), + variable: "TOOL_A_HOME", command: "tool-a", + homeLayouts: [["match": "*.kit", "home": "Contents/Home"], ["match": "*", "home": "."]], + discovery: [home("Library/Kits/*.kit"), home(".local/share/tool-a/*"), + absolute("/opt/homebrew/Cellar", "tool-a/*")]), + tool("tool-b", "Tool B", layout: "bin/tool-b", version: (["--version"], #"tool-b (\d+(?:\.\d+)*)"#), + variable: "TOOL_B_HOME", command: "tool-b", + discovery: [absolute("/opt/homebrew/Cellar", "tool-b/*"), home(".local/share/tool-b/*")]) ]), sample("dev.lithe.sample.node", "Node.js (sample)", definitions: [ tool("node", "Node.js", layout: "bin/node", version: (["--version"], #"v(\d+(?:\.\d+)*)"#), command: "node", @@ -203,7 +202,7 @@ final class ToolchainSettingsDemo: NSObject, NSApplicationDelegate { command: "python3", discovery: [home(".local/share/uv/python/cpython-*")]) ], providers: [provider("uv", "uv", tools: ["python"], watch: [".python-version"])]), sample("dev.lithe.sample.mise", "mise (sample)", providers: [ - provider("mise", "mise", tools: ["java", "maven", "node", "python"], watch: ["mise.toml", ".tool-versions"]) + provider("mise", "mise", tools: ["tool-a", "tool-b", "node", "python"], watch: ["mise.toml", ".tool-versions"]) ]) ] diff --git a/macos/Sources/Lithe/Platform/MacOS/Vcs/MacVcsProviderSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Vcs/MacVcsProviderSessions.swift index 4a9d2bea26..90e4d957f8 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Vcs/MacVcsProviderSessions.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Vcs/MacVcsProviderSessions.swift @@ -29,6 +29,8 @@ final class MacVcsProviderSessions: VcsProviderRequesting { private let runtime: any LanguageToolRuntimePort private let core: any LanguageServerRuntimeCore private let remoteLaunches: MacRemotePluginLaunchPreparer? + /// Resolves a provider launch that names a tool definition. + private let definedTools: MacDefinedToolchainResolver? private weak var processRegistry: (any LanguageServerProcessRegistry)? /// Ends the processes carrying a backend's token; `immediately` skips the /// graceful stop. See `MacPluginBackendProcesses`. @@ -64,6 +66,7 @@ final class MacVcsProviderSessions: VcsProviderRequesting { core: any LanguageServerRuntimeCore, processRegistry: (any LanguageServerProcessRegistry)?, remoteLaunches: MacRemotePluginLaunchPreparer? = nil, + definedTools: MacDefinedToolchainResolver? = nil, endBackendProcesses: @escaping @MainActor (_ token: String, _ immediately: Bool) -> Void = { token, immediately in MacPluginBackendProcesses.end( token: token, @@ -77,6 +80,7 @@ final class MacVcsProviderSessions: VcsProviderRequesting { self.runtime = runtime self.core = core self.remoteLaunches = remoteLaunches + self.definedTools = definedTools self.processRegistry = processRegistry self.endBackendProcesses = endBackendProcesses } @@ -209,10 +213,11 @@ final class MacVcsProviderSessions: VcsProviderRequesting { workspaceRootURL: target.workspaceURL ) let executableURL: URL + let arguments: [String] var environment: [String: String] let toolPath: String? do { - (executableURL, environment) = try await resolveExecutable(provider.process, workspaceURL: target.workspaceURL) + (executableURL, arguments, environment) = try await resolveExecutable(provider.process, workspaceURL: target.workspaceURL) toolPath = try await resolveTool(provider, workspaceURL: target.workspaceURL) try Task.checkCancellation() guard running[target] === entry, prepared?.owner.isCurrent() != false else { throw CancellationError() } @@ -224,7 +229,7 @@ final class MacVcsProviderSessions: VcsProviderRequesting { let session = LanguageServerRuntimeSession( providerID: "vcsProvider:\(target.pluginID):\(target.vcs)", executableURL: executableURL, - arguments: provider.process.arguments, + arguments: arguments, environment: environment, initializationOptions: provider.process.initializationOptions, initializeTimeout: 60, @@ -283,7 +288,7 @@ final class MacVcsProviderSessions: VcsProviderRequesting { } } do { - try session.start(rootURL: rootURL, workspaceFingerprint: nil) + try session.start(rootURL: rootURL) } catch { finish(.failure(error)) } @@ -292,20 +297,35 @@ final class MacVcsProviderSessions: VcsProviderRequesting { /// The provider's own executable: a packaged file as it is, commands and /// runtimes through the build tool discovery, so the provider sees the - /// same runtime settings and `PATH` as other plugin processes. + /// same runtime settings and `PATH` as other plugin processes. A tool + /// launch resolves its definitions and takes the command line their + /// template expands to; every other launch keeps the plan's arguments. private func resolveExecutable( _ process: MacPluginLanguageServerLaunchResolver.BuildProviderProcess, workspaceURL: URL - ) async throws -> (URL, [String: String]) { + ) async throws -> (URL, [String], [String: String]) { let runtimes = process.runtimeTools.map { BuildInvocation.RuntimeDependency(id: $0, hostManaged: true) } let invocation: BuildInvocation var requirement: LanguageServerExecutableVersionRequirement? switch process.executable { + case .tool(let launch): + guard remoteLaunches?.identity(workspaceURL) == nil, let definedTools else { + throw DeclarativePluginRejection( + code: "plugin.launch.unavailable", + message: "A version control provider that names a tool definition cannot start in this workspace." + ) + } + let command = try await definedTools.command( + for: launch, arguments: process.arguments, workspace: workspaceURL, + environment: runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools), + projectCodeAllowed: false + ) + return (command.executableURL, command.arguments, command.environment) case .file(let url): if remoteLaunches?.identity(workspaceURL) == nil { - return (url, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) + return (url, process.arguments, runtime.languageToolProcessEnvironment(runtimeTools: process.runtimeTools)) } invocation = BuildInvocation(executables: [.setting(id: "pluginPackage", path: url.path)], runtimeDependencies: runtimes) case .commands(let commands): @@ -333,7 +353,7 @@ final class MacVcsProviderSessions: VcsProviderRequesting { return BuildVersionCheck(satisfied: check.satisfied, version: check.version) } ) - return (resolved.executableURL, resolved.environment) + return (resolved.executableURL, process.arguments, resolved.environment) } /// The VCS client the provider runs, such as `svn`, found like any other diff --git a/macos/Sources/Lithe/Resources/SyntaxHighlighting/format-mappings.json b/macos/Sources/Lithe/Resources/SyntaxHighlighting/format-mappings.json index 5916ff9f18..1f825e5ee6 100644 --- a/macos/Sources/Lithe/Resources/SyntaxHighlighting/format-mappings.json +++ b/macos/Sources/Lithe/Resources/SyntaxHighlighting/format-mappings.json @@ -3,7 +3,7 @@ "formats": [ { "id": "properties", - "displayName": "Java Properties", + "displayName": "Properties", "fileExtensions": ["properties"], "adapter": "properties" }, diff --git a/macos/Sources/Lithe/Services/Debug/DebugLaunchConfigurationResolver.swift b/macos/Sources/Lithe/Services/Debug/DebugLaunchConfigurationResolver.swift index a5690c0bb8..cd87be7c21 100644 --- a/macos/Sources/Lithe/Services/Debug/DebugLaunchConfigurationResolver.swift +++ b/macos/Sources/Lithe/Services/Debug/DebugLaunchConfigurationResolver.swift @@ -5,10 +5,6 @@ import LitheCoreContracts enum DebugLaunchConfigurationResolutionError: LocalizedError, Equatable { case unsupportedProvider(String) case providerDebugUnavailable - case javaLaunchTargetUnavailable - case invalidJavaAttachHost - case invalidJavaAttachPort - case javaRuntimeUnavailable /// No program to debug: the plugin's setting is empty and none of its /// candidate locations holds one. case executableNotFound(plugin: String, setting: String, searched: [String]) @@ -21,14 +17,6 @@ enum DebugLaunchConfigurationResolutionError: LocalizedError, Equatable { return L10n.string("The \(provider) Debug Adapter is not installed yet.") case .providerDebugUnavailable: return L10n.string("The build provider's debug program or adapter is unavailable. Build it again and check that the plugin is enabled.") - case .javaLaunchTargetUnavailable: - return L10n.string("The Java language service could not resolve a main class for this file.") - case .invalidJavaAttachHost: - return L10n.string("Enter the host name of the running JVM.") - case .invalidJavaAttachPort: - return L10n.string("Enter a JVM debug port between 1 and 65535.") - case .javaRuntimeUnavailable: - return L10n.string("No Java runtime was found. Set JAVA_HOME or install a JDK.") case .executableNotFound(let plugin, let setting, let searched): if searched.isEmpty { return L10n.string("No program to debug was found. Build it first, or choose one in the “\(setting)” setting of \(plugin).") @@ -41,27 +29,6 @@ enum DebugLaunchConfigurationResolutionError: LocalizedError, Equatable { } } -/// The JDK a debugged JVM runs on. Debug stores no JDK of its own: it names -/// the runtime Run uses for the same target, so changing one changes both. -enum DebugJavaRuntime: Equatable { - /// A Java configuration's JDK; no override means the project JDK chain. - case java(homeOverride: String?) - /// The JDK Maven launches with, for Maven-backed configurations and tests. - case maven(homeOverride: String?) - - /// The runtime Run would use for `configuration`; `nil` means a file - /// debugged without a Run configuration. - init(configuration: RunConfiguration?, options: RunOptions?) { - let javaHome = options?.javaHomePath - guard let configuration, configuration.kind.isMavenBacked else { - self = .java(homeOverride: javaHome) - return - } - let mavenHome = options?.mavenJavaHomePath ?? "" - self = .maven(homeOverride: mavenHome.isEmpty ? javaHome : mavenHome) - } -} - /// The adapter registry owns the binding throughout process preparation and attach. @MainActor struct PreparedProviderConnectionDebug { @@ -70,17 +37,18 @@ struct PreparedProviderConnectionDebug { let isCurrent: @MainActor @Sendable () -> Bool } -/// Maps an editor target and the language-neutral run model into adapter launch -/// arguments. It contains no process or UI code, so platform composition can -/// supply only the Java runtime and plugin launch capabilities. +/// Maps an editor target into adapter launch arguments. It contains no process +/// or UI code, so platform composition supplies only the plugin launch +/// capabilities. struct DebugLaunchConfigurationResolver { - private let javaTestLaunchResolver: (any JavaTestDebugLaunchResolving)? - /// Path of the `java` executable Run uses for a runtime. Without it the - /// Java Debug Server picks the JVM, which is the one JDT LS runs on. - private let javaExecutablePath: (@MainActor (DebugJavaRuntime) -> String?)? /// The launch of a language a plugin's debug adapter serves. Returns nil /// when no adapter serves the language. private let pluginLaunch: (@MainActor (_ languageID: String, _ documentURL: URL, _ workspaceURL: URL) throws -> DebugLaunchConfiguration?)? + /// Whether a plugin's debug adapter starts a debug session from an open + /// file of the language. An attach-only adapter, or one that debugs + /// executables and processes, answers false even though it serves the + /// language's sessions started elsewhere. + private let fileLaunch: (@MainActor (_ languageID: String) -> Bool)? private let providerConnection: (@MainActor (String, String?, UInt16) throws -> PreparedProviderConnectionDebug)? private let providerLaunch: (@MainActor (BuildSystemPluginSource, BuildDebugPreparation, URL, String) throws -> DebugLaunchConfiguration)? @@ -99,176 +67,34 @@ struct DebugLaunchConfigurationResolver { } init( - javaTestLaunchResolver: (any JavaTestDebugLaunchResolving)? = nil, providerConnection: (@MainActor (String, String?, UInt16) throws -> PreparedProviderConnectionDebug)? = nil, providerLaunch: (@MainActor (BuildSystemPluginSource, BuildDebugPreparation, URL, String) throws -> DebugLaunchConfiguration)? = nil, - javaExecutablePath: (@MainActor (DebugJavaRuntime) -> String?)? = nil, - pluginLaunch: (@MainActor (String, URL, URL) throws -> DebugLaunchConfiguration?)? = nil + pluginLaunch: (@MainActor (String, URL, URL) throws -> DebugLaunchConfiguration?)? = nil, + fileLaunch: (@MainActor (String) -> Bool)? = nil ) { self.providerConnection = providerConnection self.providerLaunch = providerLaunch self.pluginLaunch = pluginLaunch - self.javaTestLaunchResolver = javaTestLaunchResolver - self.javaExecutablePath = javaExecutablePath - } - - /// `javaExec` for a launch, so the debugged JVM is the one Run starts. - /// An unusable JDK fails the launch exactly as it fails Run. - @MainActor - private func javaExecutableArgument( - for runtime: DebugJavaRuntime - ) throws -> ToolingJSONValue? { - guard let javaExecutablePath else { return nil } - guard let path = javaExecutablePath(runtime) else { - throw DebugLaunchConfigurationResolutionError.javaRuntimeUnavailable - } - return .string(path) + self.fileLaunch = fileLaunch } + /// Whether `resolve` can produce a launch for a file of `languageID`. + /// The Debug button asks before it falls back to the language package's + /// own debug action. @MainActor - func resolveJavaTest( - target: JavaTestDebugLaunchTarget, - resultPort: UInt16 - ) throws -> DebugLaunchConfiguration { - guard let javaTestLaunchResolver else { - throw DebugLaunchConfigurationResolutionError.javaLaunchTargetUnavailable - } - let configuration = try javaTestLaunchResolver.resolveJavaTestDebugLaunch( - target: target, - resultPort: resultPort - ) - // Tests run through Maven, so a debugged test uses Maven's JDK. - guard let javaExecutable = try javaExecutableArgument(for: .maven(homeOverride: nil)) else { - return configuration - } - var arguments = configuration.arguments - arguments["javaExec"] = javaExecutable - return DebugLaunchConfiguration( - name: configuration.name, - request: configuration.request, - arguments: arguments, - steppingFilters: configuration.steppingFilters, - adapterProviderID: configuration.adapterProviderID, - adapterEndpoint: configuration.adapterEndpoint - ) + func launchesFiles(ofLanguage languageID: String) -> Bool { + fileLaunch?(languageID) ?? false } @MainActor func resolve( provider: LanguageProviderDescriptor, documentURL: URL, - workspaceURL: URL, - configurations: [RunConfiguration], - selectedConfiguration: RunConfiguration?, - javaTarget: JavaDebugLaunchTarget? = nil, - options: (RunConfiguration) -> RunOptions - ) throws -> DebugLaunchConfiguration { - switch provider.id { - case "java": - guard let javaTarget else { - throw DebugLaunchConfigurationResolutionError.javaLaunchTargetUnavailable - } - return try javaConfiguration( - documentURL: documentURL, - workspaceURL: workspaceURL, - configurations: configurations, - selectedConfiguration: selectedConfiguration, - target: javaTarget, - options: options - ) - default: - if let configuration = try pluginLaunch?(provider.id, documentURL, workspaceURL) { - return configuration - } - throw DebugLaunchConfigurationResolutionError.unsupportedProvider(provider.displayName) - } - } - - func resolveJavaAttach(host: String, port: Int) throws -> DebugLaunchConfiguration { - let normalizedHost = host.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalizedHost.isEmpty else { - throw DebugLaunchConfigurationResolutionError.invalidJavaAttachHost - } - guard (1...65_535).contains(port) else { - throw DebugLaunchConfigurationResolutionError.invalidJavaAttachPort - } - return DebugLaunchConfiguration( - name: "\(normalizedHost):\(port)", - request: .attach, - arguments: [ - "hostName": .string(normalizedHost), - "port": .integer(port) - ], - adapterProviderID: "java" - ) - } - - @MainActor - private func javaConfiguration( - documentURL: URL, - workspaceURL: URL, - configurations: [RunConfiguration], - selectedConfiguration: RunConfiguration?, - target: JavaDebugLaunchTarget, - options: (RunConfiguration) -> RunOptions + workspaceURL: URL ) throws -> DebugLaunchConfiguration { - // Debug is a second execution mode for the selected Run configuration. - // Keep every Java configuration eligible here so its JDK, Maven, - // working-directory, VM/program arguments, profiles, and environment - // overrides are carried over unchanged. - let configuration = selectedConfiguration.flatMap { selected in - selected.kind.providerID == "java" || selected.kind.isMavenBacked ? selected : nil - } - let runOptions = configuration.map(options) - let mainClass = configuration?.mainClass ?? target.mainClass - let configuredWorkingDirectory = runOptions?.workingDirectoryPath - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let workingDirectory: String - if configuredWorkingDirectory.isEmpty { - workingDirectory = workspaceURL.standardizedFileURL.path - } else { - workingDirectory = URL( - fileURLWithPath: configuredWorkingDirectory, - relativeTo: workspaceURL - ).standardizedFileURL.path - } - var arguments: [String: ToolingJSONValue] = [ - "mainClass": .string(mainClass), - "cwd": .string(workingDirectory), - "console": .string("integratedTerminal") - ] - if let javaExecutable = try javaExecutableArgument( - for: DebugJavaRuntime(configuration: configuration, options: runOptions) - ) { - arguments["javaExec"] = javaExecutable - } - if let projectName = target.projectName { - arguments["projectName"] = .string(projectName) - } - if !target.modulePaths.isEmpty { - arguments["modulePaths"] = .array(target.modulePaths.map(ToolingJSONValue.string)) - } - if !target.classPaths.isEmpty { - arguments["classPaths"] = .array(target.classPaths.map(ToolingJSONValue.string)) - } - if let runOptions { - let programArguments = runOptions.arguments.trimmingCharacters(in: .whitespacesAndNewlines) - if !programArguments.isEmpty { - arguments["args"] = .string(programArguments) - } - if !runOptions.environment.isEmpty { - arguments["env"] = .object(runOptions.environment.mapValues(ToolingJSONValue.string)) - } - let vmArguments = runOptions.vmArguments.trimmingCharacters(in: .whitespacesAndNewlines) - if !vmArguments.isEmpty { - arguments["vmArgs"] = .string(vmArguments) - } + if let configuration = try pluginLaunch?(provider.id, documentURL, workspaceURL) { + return configuration } - return DebugLaunchConfiguration( - name: configuration?.name ?? documentURL.lastPathComponent, - request: .launch, - arguments: arguments - ) + throw DebugLaunchConfigurationResolutionError.unsupportedProvider(provider.displayName) } - } diff --git a/macos/Sources/Lithe/Services/Debug/DebugLaunchSourceResolver.swift b/macos/Sources/Lithe/Services/Debug/DebugLaunchSourceResolver.swift index 1e3e6313b0..83689e4776 100644 --- a/macos/Sources/Lithe/Services/Debug/DebugLaunchSourceResolver.swift +++ b/macos/Sources/Lithe/Services/Debug/DebugLaunchSourceResolver.swift @@ -4,110 +4,17 @@ import LitheCoreContracts /// Selects the source file that anchors a Debug launch without making the /// selected Run configuration depend on whichever editor tab is currently open. struct DebugLaunchSourceResolver { - /// Chooses a project-backed Java target when the remembered Current File - /// entry cannot represent a launchable Java application. IDEA keeps the - /// editor shortcut useful in this situation instead of trying to compile - /// an arbitrary controller, repository, or configuration class alone. - /// - /// `activeDocumentIsLaunchable` is JDT's answer for the editor file; the - /// source text is never scanned for a `main` signature here. - func configurationForDebug( - selected: RunConfiguration, - activeDocumentIsLaunchable: Bool, - configurations: [RunConfiguration] - ) -> RunConfiguration { - guard selected.usesCurrentEditorFile else { - return selected - } - if activeDocumentIsLaunchable { - return selected - } - - return configurations.first { - !$0.usesCurrentEditorFile && $0.kind.mavenFramework != nil - && $0.kind.capabilities.contains(.jdwpDebug) - } ?? configurations.first { - !$0.usesCurrentEditorFile && $0.kind == .javaMain - && $0.kind.capabilities.contains(.jdwpDebug) - } ?? selected - } - + /// Resolves the file a Debug launch is anchored to. Only the current-editor + /// entry follows the active tab; every other configuration is launched by + /// its provider and has no host-side source anchor. Returns nil in that + /// case, so the caller never guesses a file by its extension. func resolve( configuration: RunConfiguration, activeDocumentURL: URL?, projectFiles: [URL], workspaceURL: URL ) -> URL? { - if configuration.usesCurrentEditorFile { - return activeDocumentURL?.standardizedFileURL - } - - if let sourcePath = configuration.sourcePath, - !sourcePath.isEmpty { - let sourceURL = workspaceURL - .appendingPathComponent(sourcePath) - .standardizedFileURL - if projectFiles.map(\.standardizedFileURL).contains(sourceURL) { - return sourceURL - } - } - - let javaFiles = projectFiles - .map(\.standardizedFileURL) - .filter { $0.pathExtension.lowercased() == "java" } - .sorted { $0.path < $1.path } - guard !javaFiles.isEmpty else { return nil } - - // Provider projects carry a generic instance root. Their module paths - // are relative to that root, just like the legacy reactor projection. - let ownerRoot = configuration.buildProject?.root ?? configuration.mavenReactorPath - let moduleFiles = filesInSelectedModule( - javaFiles, - modulePath: configuration.modulePath, - workspaceURL: ownerRoot.map { - workspaceURL.appendingPathComponent($0, isDirectory: true) - } ?? workspaceURL - ) - // A detected owner must never fall back to another instance's class. - let isOwned = ownerRoot != nil - let preferredFiles = moduleFiles.isEmpty && !isOwned ? javaFiles : moduleFiles - - if let sourceSuffix = sourceSuffix(for: configuration.mainClass), - let exactMatch = preferredFiles.first(where: { $0.path.hasSuffix(sourceSuffix) }) - ?? (isOwned ? nil : javaFiles.first(where: { $0.path.hasSuffix(sourceSuffix) })) { - return exactMatch - } - - if let activeDocumentURL = activeDocumentURL?.standardizedFileURL, - preferredFiles.contains(activeDocumentURL) { - return activeDocumentURL - } - return preferredFiles.first - } - - private func filesInSelectedModule( - _ files: [URL], - modulePath: String?, - workspaceURL: URL - ) -> [URL] { - let modulePath = modulePath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "." - let moduleURL = workspaceURL - .appendingPathComponent(modulePath, isDirectory: true) - .standardizedFileURL - let modulePrefix = moduleURL.path.hasSuffix("/") ? moduleURL.path : moduleURL.path + "/" - return files.filter { $0.path.hasPrefix(modulePrefix) } - } - - private func sourceSuffix(for mainClass: String?) -> String? { - guard var mainClass = mainClass?.trimmingCharacters(in: .whitespacesAndNewlines), - !mainClass.isEmpty else { return nil } - if let moduleSeparator = mainClass.lastIndex(of: "/") { - mainClass = String(mainClass[mainClass.index(after: moduleSeparator)...]) - } - if let nestedClassSeparator = mainClass.firstIndex(of: "$") { - mainClass = String(mainClass[.. any JavaTestResultServing - - init( - configurationResolver: DebugLaunchConfigurationResolver, - resultServerFactory: @escaping @MainActor () -> any JavaTestResultServing - ) { - self.configurationResolver = configurationResolver - self.resultServerFactory = resultServerFactory - } - - func prepare( - fileURL: URL, - testIdentifier: String?, - rootURL: URL, - targetResolver: any JavaTestDebugLaunchTargetResolving - ) async throws -> PreparedJavaTestDebugLaunch { - let target = try await targetResolver.resolveJavaTestDebugLaunchTarget( - fileURL: fileURL, - testIdentifier: testIdentifier, - rootURL: rootURL - ) - try Task.checkCancellation() - - let resultServer = resultServerFactory() - do { - let resultPort = try await resultServer.start() - try Task.checkCancellation() - let configuration = try configurationResolver.resolveJavaTest( - target: target, - resultPort: resultPort - ) - return PreparedJavaTestDebugLaunch( - target: target, - configuration: configuration, - resultServer: resultServer - ) - } catch { - resultServer.stop() - throw error - } - } -} diff --git a/macos/Sources/Lithe/Services/Java/JavaCodeVisionService.swift b/macos/Sources/Lithe/Services/Java/JavaCodeVisionService.swift deleted file mode 100644 index 65e1d7a18c..0000000000 --- a/macos/Sources/Lithe/Services/Java/JavaCodeVisionService.swift +++ /dev/null @@ -1,45 +0,0 @@ -import Foundation -import LitheGitModule - -enum JavaCodeVisionService { - static func hints( - for fileURL: URL, - projectFiles: [URL], - workspaceRoot: URL, - blameLines: [GitBlameLine], - operations: any JavaMavenOperations - ) async -> [JavaCodeVisionHint] { - let root = workspaceRoot.standardizedFileURL - let target = fileURL.standardizedFileURL - guard target.path.hasPrefix(root.path + "/"), - let targetPath = relativePath(target, root: root) else { return [] } - let paths = projectFiles.compactMap { file -> String? in - let normalized = file.standardizedFileURL - guard normalized.path.hasPrefix(root.path + "/") else { return nil } - return relativePath(normalized, root: root) - } - let values = await Task.detached(priority: .utility) { - operations.codeVision( - at: root, - targetPath: targetPath, - paths: paths - ) - }.value - let blameByLine = Dictionary(uniqueKeysWithValues: blameLines.map { ($0.line, $0) }) - return values.map { value in - JavaCodeVisionHint( - line: value.line, - utf16Column: value.utf16Column, - symbol: value.symbol, - usageCount: value.usageCount, - implementationCount: 0, - authorName: blameByLine[value.line]?.authorName - ) - } - } - - private static func relativePath(_ file: URL, root: URL) -> String? { - guard file.path.hasPrefix(root.path + "/") else { return nil } - return String(file.path.dropFirst(root.path.count + 1)) - } -} diff --git a/macos/Sources/Lithe/Services/Java/JavaRunService.swift b/macos/Sources/Lithe/Services/Java/JavaRunService.swift deleted file mode 100644 index ac18f718ba..0000000000 --- a/macos/Sources/Lithe/Services/Java/JavaRunService.swift +++ /dev/null @@ -1,4 +0,0 @@ -import LitheExecutionModule - -typealias RunService = LitheExecutionModule.RunService -typealias JavaRunService = LitheExecutionModule.RunService diff --git a/macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift b/macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift deleted file mode 100644 index 20b9f1b70e..0000000000 --- a/macos/Sources/Lithe/Services/Java/ProjectRuntimeService.swift +++ /dev/null @@ -1,792 +0,0 @@ -import Foundation -import LitheCoreContracts - -enum ProjectRuntimeProcessKind: Sendable { - case java - case maven -} - -extension ProjectRuntimeService: RunRuntimePort {} - -extension ProjectRuntimeService: LanguageToolRuntimePort { - package func languageToolProcessEnvironment(runtimeTools: [String]) -> [String: String] { - var environment = processEnvironment() - // Node-based language servers (Intelephense, TypeScript, …) start - // through launchers that read LITHE_NODE_PATH. An app opened from the - // Dock inherits launchd's PATH, which omits Homebrew and Node version - // managers, so pass the discovered executable explicitly. - // Language servers start automatically when a file opens, so a - // project-provided `node` must never be chosen here: an untrusted - // repository could otherwise run its own program. - if environment["LITHE_NODE_PATH"]?.isEmpty ?? true, - let node = executableCandidates("node").first(where: { $0.source != .project }) { - environment["LITHE_NODE_PATH"] = node.executableURL.path - } - // Declared runtime dependencies are also put on PATH because servers - // such as gopls run the tool themselves and cannot be pointed at it - // through a launcher variable. The same project-local exclusion applies. - var searchPath = (environment["PATH"] ?? "").split(separator: ":").map(String.init) - for tool in runtimeTools { - let key = Self.runtimeToolEnvironmentKey(tool) - if environment[key]?.isEmpty ?? true, - let candidate = executableCandidates(tool).first(where: { $0.source != .project }) { - environment[key] = candidate.executableURL.path - } - guard let configured = environment[key], configured.hasPrefix("/") else { continue } - let directory = URL(fileURLWithPath: configured).deletingLastPathComponent().path - if !searchPath.contains(directory) { - searchPath.insert(directory, at: 0) - } - } - if !runtimeTools.isEmpty { - environment["PATH"] = searchPath.joined(separator: ":") - } - return environment - } - - static func runtimeToolEnvironmentKey(_ tool: String) -> String { - LanguageToolEnvironment.runtimeToolKey(tool) - } - - package func missingLanguageToolMessage(_ name: String) -> String { - missingToolMessage(name) - } -} - -@MainActor -final class ProjectRuntimeService: ObservableObject { - enum JavaLanguageServerRuntimePreparation: Equatable { - case unprepared - case ready(executableURL: URL) - case failed(message: String) - } - - @Published private(set) var projectURL: URL? - @Published private(set) var javaRuntimes: [JavaRuntimeCandidate] = [] - @Published private(set) var mavenRuntimes: [MavenRuntimeCandidate] = [] - @Published private(set) var javaEnvironmentReport: JavaEnvironmentReport? - @Published private(set) var isDiscovering = false - @Published private(set) var settings = ProjectRuntimeSettings() - @Published private(set) var settingsError: String? - private(set) var settingsSnapshot: ProjectRuntimeSettingsSnapshot? - private var activeServiceJavaHomePath = "" - private var launchJavaRuntimes: [JavaRuntimeCandidate]? - private var runtimeSessionID = UUID() - - private let javaSelector: any JavaRuntimeSelecting - private let localRuntimeLocator: any RuntimeLocator - private var runtimeLocator: any RuntimeLocator - private let settingsStore: any ProjectRuntimeSettingsStoring - private let localToolDiscovery: any RuntimeToolDiscovery - private var toolDiscovery: any RuntimeToolDiscovery - private let workspaceRuntime: ((URL) -> (any RuntimeLocator, any RuntimeToolDiscovery)?)? - private var usesWorkspaceRuntime = false - private var discoveryTask: Task? - private var activeDiscoveryID: UUID? - private var javaLanguageServerRuntimePreparation: JavaLanguageServerRuntimePreparation = .unprepared - /// JDK home shipped by the plugin that provides Java language support. - private var javaLanguageServerRuntimeHome: URL? - /// Project whose runtimes `javaRuntimes` and `mavenRuntimes` describe. - @Published private var discoveredProjectURL: URL? - - init( - runtimeLocator: any RuntimeLocator, - settingsStore: any ProjectRuntimeSettingsStoring, - toolDiscovery: (any RuntimeToolDiscovery)? = nil, - javaSelector: any JavaRuntimeSelecting = RustCoreBridge(), - workspaceRuntime: ((URL) -> (any RuntimeLocator, any RuntimeToolDiscovery)?)? = nil - ) { - self.javaSelector = javaSelector - self.runtimeLocator = runtimeLocator - self.localRuntimeLocator = runtimeLocator - self.settingsStore = settingsStore - self.toolDiscovery = toolDiscovery ?? DefaultRuntimeToolDiscovery() - self.localToolDiscovery = toolDiscovery ?? DefaultRuntimeToolDiscovery() - self.workspaceRuntime = workspaceRuntime - } - - deinit { - discoveryTask?.cancel() - } - - func openProject(at url: URL) { - runtimeSessionID = UUID() - discoveryTask?.cancel() - activeDiscoveryID = nil - let normalizedURL = url.standardizedFileURL - projectURL = normalizedURL - let selected = workspaceRuntime?(normalizedURL) - usesWorkspaceRuntime = selected != nil - runtimeLocator = selected?.0 ?? localRuntimeLocator - toolDiscovery = selected?.1 ?? localToolDiscovery - javaRuntimes = [] - mavenRuntimes = [] - discoveredProjectURL = nil - launchJavaRuntimes = nil - settings = ProjectRuntimeSettings() - settingsSnapshot = nil - reloadSettings(migrateLegacy: true) - javaEnvironmentReport = .checking(for: normalizedURL) - javaLanguageServerRuntimePreparation = .unprepared - discoveryTask = nil - } - - func closeProject() { - runtimeSessionID = UUID() - discoveryTask?.cancel() - discoveryTask = nil - activeDiscoveryID = nil - projectURL = nil - runtimeLocator = localRuntimeLocator - toolDiscovery = localToolDiscovery - usesWorkspaceRuntime = false - javaRuntimes = [] - mavenRuntimes = [] - discoveredProjectURL = nil - launchJavaRuntimes = nil - settings = ProjectRuntimeSettings() - settingsSnapshot = nil - if settingsError != nil { settingsError = nil } - javaEnvironmentReport = nil - isDiscovering = false - activeServiceJavaHomePath = "" - javaLanguageServerRuntimePreparation = .unprepared - } - - func setActiveServiceJavaHomePath(_ path: String) { - activeServiceJavaHomePath = path.trimmingCharacters(in: .whitespacesAndNewlines) - } - - /// Starts discovery for the open project unless it already ran or is running. - /// Every view that shows an automatic runtime calls this; without it the - /// value stays "Detecting…" when Settings is entered past the project page. - func ensureRuntimesDiscovered() async { - guard projectURL != nil, !hasDiscoveredRuntimes, !isDiscovering else { return } - await performRuntimeRefresh() - } - - /// JDKs for the New Project window, which can open without a project. - /// Leaves the open project's discovery state untouched. - func discoverJavaRuntimesForNewProject() async -> [JavaRuntimeCandidate] { - let runtimeLocator = localRuntimeLocator - return await Self.backgroundProbe { cancelled in - runtimeLocator.discoverJavaRuntimes(isCancelled: cancelled) - } - } - - func refreshAvailableRuntimes() async { - runtimeSessionID = UUID() - runtimeLocator.invalidateProbeCache() - launchJavaRuntimes = nil - discoveryTask?.cancel() - discoveryTask = nil - await performRuntimeRefresh() - } - - private func performRuntimeRefresh() async { - let targetProjectURL = projectURL - let discoveryID = UUID() - activeDiscoveryID = discoveryID - isDiscovering = true - defer { - if activeDiscoveryID == discoveryID { - activeDiscoveryID = nil - isDiscovering = false - } - } - let runtimeLocator = runtimeLocator - runtimeLocator.configureProbePaths([settings.javaHomePath, settings.mavenJavaHomePath, settings.mavenExecutableOverride]) - let result = await Self.backgroundProbe { cancelled in - runtimeLocator.discover(isCancelled: cancelled) - } - guard !Task.isCancelled, - projectURL == targetProjectURL, - activeDiscoveryID == discoveryID else { return } - javaRuntimes = result.javaRuntimes - mavenRuntimes = result.mavenRuntimes - discoveredProjectURL = targetProjectURL - if let message = runtimeLocator.discoveryFailure, let projectURL { - javaEnvironmentReport = JavaEnvironmentReport(status: .probeFailed(message: message), - projectURL: projectURL, javaHomePath: nil, javaExecutablePath: nil) - return - } - refreshJavaEnvironmentReport(using: result.javaRuntimes) - isDiscovering = false - } - - private func javaRuntimesForLaunch() -> [JavaRuntimeCandidate] { - if hasDiscoveredRuntimes { return javaRuntimes } - if let launchJavaRuntimes { return launchJavaRuntimes } - let runtimes = runtimeLocator.discoverJavaRuntimes() - launchJavaRuntimes = runtimes - return runtimes - } - - /// Reuses the launch selection, including explicit JDKs outside discovery roots. - func javaLanguageServiceRuntimes() -> [JavaLanguageServiceRuntime] { - var runtimes = javaRuntimesForLaunch() - let selected = javaHomeURL() - if let selected, !runtimes.contains(where: { $0.homePath == selected.path }), - let runtime = runtimeLocator.javaRuntime(at: selected) { - runtimes.insert(runtime, at: 0) - } - return runtimes.map { - JavaLanguageServiceRuntime(homePath: $0.homePath, version: $0.version, - isDefault: $0.homePath == selected?.path) - } - } - - func javaHomeURL(overridePath: String? = nil) -> URL? { - chooseJavaHome(overridePath: overridePath) { self.javaRuntimesForLaunch() }?.url - } - - /// The single JDK selection chain behind launches and Settings: an explicit - /// override, then the project JDK, then Core's requirement-aware automatic - /// selection. An invalid explicit path does not fall back, so a launch fails on it. - /// - /// `detected` supplies discovered runtimes and is only called when the chain - /// reaches detection; returning `nil` reports that detection is pending. - func chooseJavaHome( - overridePath: String?, - detected: () -> [JavaRuntimeCandidate]? - ) -> RuntimeChoice? { - guard reloadSettings() else { return .unavailable(settingsError ?? "") } - if let overridePath { - let normalizedPath = normalizedOverridePath(overridePath) - if !normalizedPath.isEmpty { - return runtimeLocator.validJavaHome(path: normalizedPath) - .map { RuntimeChoice.found($0, .configured) } ?? .invalid(normalizedPath) - } - } - let configuredProjectJDK = settings.javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - if !configuredProjectJDK.isEmpty { - let path = normalizedOverridePath(configuredProjectJDK) - return runtimeLocator.validJavaHome(path: path).map { RuntimeChoice.found($0, .projectSetting) } ?? .invalid(path) - } - let environmentHome = runtimeLocator.environment()["JAVA_HOME"] - .flatMap { runtimeLocator.validJavaHome(path: normalizedPath($0)) } - if let environmentHome { - // With no project requirement, preserve the old no-probe JAVA_HOME - // fast path. Unknown versions never satisfy a real minimum, so only - // an unconstrained result may bypass discovery here. - let candidate = AutomaticJavaCandidate(id: environmentHome.path, version: "", priority: 0) - switch selectJavaRuntime(candidates: [candidate], fallbackID: candidate.id) { - case .failure(let error): return .unavailable(error.message) - case .success(let selection) where selection.warning == nil: - return .found(environmentHome, .javaHomeEnvironment) - case .success: break - } - } - // Settings supplies cached probes; pending discovery must not synchronously - // launch java -version or temporarily present an incompatible JAVA_HOME. - guard let runtimes = detected() else { return nil } - let pathHome = runtimeLocator.javaHomeOnPath(in: runtimes) - var candidates = runtimes.compactMap { runtime -> AutomaticJavaCandidate? in - guard let home = runtimeLocator.validJavaHome(path: runtime.homePath) else { return nil } - let priority: UInt32 = home.path == environmentHome?.path ? 0 : (home.path == pathHome?.path ? 1 : 2) - return AutomaticJavaCandidate(id: home.path, version: runtime.version, priority: priority) - } - // Preserve the old JAVA_HOME fallback even if its version probe failed. - // An unknown version cannot satisfy a requirement in the shared policy. - if let home = environmentHome, !candidates.contains(where: { $0.id == home.path }) { - candidates.append(AutomaticJavaCandidate(id: home.path, version: "", priority: 0)) - } - let fallback = environmentHome?.path ?? candidates.first?.id - switch selectJavaRuntime(candidates: candidates, fallbackID: fallback) { - case .failure(let error): return .unavailable(error.message) - case .success(let selection): - guard let id = selection.id else { return .notFound } - let url = URL(fileURLWithPath: id).standardizedFileURL - let source: RuntimeChoiceSource = url.path == environmentHome?.path ? .javaHomeEnvironment : .detected - if let warning = selection.warning { return .warning(url, source, warning) } - return .found(url, source) - } - } - - private func selectJavaRuntime( - candidates: [AutomaticJavaCandidate], fallbackID: String? - ) -> Result { - runtimeLocator.selectJavaRuntime(candidates: candidates, fallbackID: fallbackID) - ?? javaSelector.selectJavaRuntime(at: projectURL, candidates: candidates, fallbackID: fallbackID) - } - - func javaExecutableURL(overridePath: String? = nil) -> URL? { - javaHomeURL(overridePath: overridePath)?.appendingPathComponent("bin/java") - } - - /// The `java` a debugged JVM starts on: the same selection Run makes for - /// the same target, so the two never drift apart. - func javaExecutableURL(forDebugging runtime: DebugJavaRuntime) -> URL? { - switch runtime { - case .java(let homeOverride): - return javaExecutableURL(overridePath: homeOverride) - case .maven(let homeOverride): - return mavenJavaHomeURL(overridePath: homeOverride)?.appendingPathComponent("bin/java") - } - } - - /// Resolves only explicit project/settings/environment JDK paths. Unlike - /// `javaExecutableURL()`, this method never falls back to discovery or - /// probes `java -version`, so capability checks can remain inert. - func configuredJavaExecutableURL(overridePath: String? = nil) -> URL? { - let paths: [String?] - if let overridePath { - let normalizedPath = normalizedOverridePath(overridePath) - paths = normalizedPath.isEmpty ? [runtimeLocator.environment()["JAVA_HOME"]] : [normalizedPath] - } else { - paths = [runtimeLocator.environment()["JAVA_HOME"]] - } - for path in paths.compactMap({ $0 }).map(normalizedPath).filter({ !$0.isEmpty }) { - if let home = runtimeLocator.validJavaHome(path: path) { - return home.appendingPathComponent("bin/java") - } - } - return nil - } - - func isJavaLanguageServerRuntimePrepared() -> Bool { - if case .ready = javaLanguageServerRuntimePreparation { return true } - return false - } - - /// Sets the JDK that the Java language server runs on. The composition - /// root reads it from the installed plugin's declaration; `nil` means no - /// installed plugin provides Java language support. - func setJavaLanguageServerRuntimeHome(_ homeURL: URL?) { - javaLanguageServerRuntimeHome = homeURL?.standardizedFileURL - javaLanguageServerRuntimePreparation = .unprepared - } - - /// Probes only the runtime shipped by the Java Support plugin. Project JDKs - /// and user environment variables never influence the language-server process. - @discardableResult - func prepareJavaLanguageServerRuntime() async -> JavaLanguageServerRuntimePreparation { - if javaLanguageServerRuntimePreparation != .unprepared { - return javaLanguageServerRuntimePreparation - } - let runtimeLocator = runtimeLocator - guard let home = javaLanguageServerRuntimeHome else { - // Not cached: installing or restoring the plugin changes the answer. - return .failed( - message: "Java language support is provided by the Java Support plugin, which is not installed. Install or restore it in Settings > Plugins." - ) - } - let preparation = await Task.detached(priority: .utility) { - guard let runtime = runtimeLocator.javaRuntime(at: home) else { - return JavaLanguageServerRuntimePreparation.failed( - message: "The Java Support plugin's runtime is missing or invalid. Reinstall the plugin." - ) - } - guard let majorVersion = runtime.majorVersion, majorVersion >= 21, - let validHome = runtimeLocator.validJavaHome(path: runtime.homePath) else { - return JavaLanguageServerRuntimePreparation.failed( - message: "The Java Support plugin's runtime must be Java 21 or newer; found \(runtime.version). Reinstall the plugin." - ) - } - return JavaLanguageServerRuntimePreparation.ready( - executableURL: validHome.appendingPathComponent("bin/java") - ) - }.value - guard !Task.isCancelled else { return .unprepared } - javaLanguageServerRuntimePreparation = preparation - return preparation - } - - func javaLanguageServerExecutableURL() -> URL? { - guard case .ready(let executableURL) = javaLanguageServerRuntimePreparation else { - return nil - } - return executableURL - } - - func javaLanguageServerRuntimeFailureMessage() -> String? { - guard case .failed(let message) = javaLanguageServerRuntimePreparation else { - return nil - } - return message - } - - func mavenJavaHomeURL(overridePath: String? = nil) -> URL? { - chooseMavenJavaHome(overridePath: overridePath) { self.javaRuntimesForLaunch() }?.url - } - - /// Maven's JDK: an explicit override, then the configured Maven JDK, then - /// the project JDK chain. An unusable configured Maven JDK falls back to the - /// project JDK, which `.fallback` reports instead of hiding. - func chooseMavenJavaHome( - overridePath: String?, - detected: () -> [JavaRuntimeCandidate]? - ) -> RuntimeChoice? { - guard reloadSettings() else { return .unavailable(settingsError ?? "") } - if let overridePath { - let normalizedPath = normalizedOverridePath(overridePath) - if !normalizedPath.isEmpty { - return runtimeLocator.validJavaHome(path: normalizedPath) - .map { RuntimeChoice.found($0, .configured) } ?? .invalid(normalizedPath) - } - } - let configuredMavenJDK = settings.mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - // The project chain may probe every JDK, so it runs only when needed. - guard !configuredMavenJDK.isEmpty else { - return chooseJavaHome(overridePath: nil, detected: detected)?.inheritedAsProjectJDK - } - let path = normalizedOverridePath(configuredMavenJDK) - if let home = runtimeLocator.validJavaHome(path: path) { return .found(home, .projectSetting) } - guard let projectJDK = chooseJavaHome(overridePath: nil, detected: detected) else { return nil } - return .fallback(invalidPath: path, to: projectJDK) - } - - func environment( - for processKind: ProjectRuntimeProcessKind, - javaHomeOverride: String? = nil - ) -> [String: String] { - var environment = runtimeLocator.environment() - let home = processKind == .maven - ? mavenJavaHomeURL(overridePath: javaHomeOverride) - : javaHomeURL(overridePath: javaHomeOverride) - if let home { - environment["JAVA_HOME"] = home.path - let path = environment["PATH"] ?? "" - let javaBin = home.appendingPathComponent("bin").path - environment["PATH"] = javaBin + (path.isEmpty ? "" : ":" + path) - } - return environment - } - - /// Base environment for language-neutral processes such as Go, Python and - /// Node. Overrides are layered on top without injecting Java variables. - func processEnvironment(overrides: [String: String] = [:]) -> [String: String] { - runtimeLocator.environment().merging(overrides) { _, override in override } - } - - func defaultExecutableSearchPath() -> String? { - runtimeLocator.defaultExecutableSearchPath() - } - - /// Returns all known candidates in preference order. The platform - /// adapter can add project-local, Homebrew, Xcode, or registry sources; - /// the locator fallback keeps existing non-platform implementations fully - /// compatible. - func executableCandidates(_ command: String) -> [RuntimeToolCandidate] { - guard !command.isEmpty, !command.contains("/") else { return [] } - let environment = runtimeLocator.environment() - let discovered = toolDiscovery.candidates( - for: command, - projectURL: projectURL, - environment: environment - ) - var candidates = discovered - var seen = Set(discovered.map { $0.executableURL.standardizedFileURL.path }) - for directory in (environment["PATH"] ?? "").split(separator: ":") where !directory.isEmpty { - let candidateURL = URL(fileURLWithPath: String(directory)) - .appendingPathComponent(command) - .standardizedFileURL - guard runtimeLocator.isExecutable(at: candidateURL), - seen.insert(candidateURL.path).inserted else { continue } - candidates.append(RuntimeToolCandidate( - command: command, - executableURL: candidateURL, - source: .path, - detail: String(directory) - )) - } - return candidates - } - - func toolGuidance(_ command: String) -> RuntimeToolGuidance { - toolDiscovery.guidance( - for: command, - projectURL: projectURL, - environment: runtimeLocator.environment() - ) - } - - func missingToolMessage(_ command: String) -> String { - let guidance = toolGuidance(command) - return guidance.message - } - - private func refreshJavaEnvironmentReport(using discoveredJavaRuntimes: [JavaRuntimeCandidate]) { - guard let projectURL else { - javaEnvironmentReport = nil - return - } - - let configuredProjectJDK = settings.javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - if !configuredProjectJDK.isEmpty { - if let javaHome = runtimeLocator.validJavaHome(path: normalizedOverridePath(configuredProjectJDK)) { - publishReadyJavaEnvironmentReport(projectURL: projectURL, javaHome: javaHome) - } else { - javaEnvironmentReport = JavaEnvironmentReport( - status: .configuredJDKInvalid(path: configuredProjectJDK), - projectURL: projectURL, - javaHomePath: configuredProjectJDK, - javaExecutablePath: nil - ) - } - return - } - - // Use the runtimes this discovery just found. `javaHomeURL()` would run - // the whole discovery again, synchronously on the main actor, whenever - // neither a project JDK nor JAVA_HOME is set. - let javaHome = chooseJavaHome(overridePath: nil) { discoveredJavaRuntimes }?.url - guard let javaHome else { - javaEnvironmentReport = JavaEnvironmentReport( - status: .jdkMissing, - projectURL: projectURL, - javaHomePath: nil, - javaExecutablePath: nil - ) - return - } - - publishReadyJavaEnvironmentReport(projectURL: projectURL, javaHome: javaHome) - } - - private func publishReadyJavaEnvironmentReport(projectURL: URL, javaHome: URL) { - javaEnvironmentReport = JavaEnvironmentReport( - status: .ready, - projectURL: projectURL, - javaHomePath: javaHome.path, - javaExecutablePath: javaHome.appendingPathComponent("bin/java").path - ) - } - - /// Resolves a bare program name without starting a process. Returns nil - /// when no candidate is executable. - func executableOnPath(_ command: String) -> URL? { - executableCandidates(command).first?.executableURL - } - - func executableURL(at path: String) -> URL? { - let normalized = normalizedOverridePath(path) - guard !normalized.isEmpty else { return nil } - let url = URL(fileURLWithPath: normalized).standardizedFileURL - return runtimeLocator.isExecutable(at: url) ? url : nil - } - - func mavenExecutable(at rootURL: URL, overridePath: String? = nil) -> URL? { - chooseMavenExecutable(at: rootURL, overridePath: overridePath).url - } - - /// The Maven selection chain behind launches and Settings: an explicit - /// path, then the project `mvnw`, then the system Maven. - func chooseMavenExecutable(at rootURL: URL, overridePath: String? = nil) -> RuntimeChoice { - guard reloadSettings() else { return .unavailable(settingsError ?? "") } - let configured = (overridePath ?? settings.mavenExecutableOverride).trimmingCharacters(in: .whitespacesAndNewlines) - if !configured.isEmpty { - let resolved = URL(fileURLWithPath: runtimeLocator.normalizedPath(configured, relativeTo: rootURL)) - let standardized = resolved.standardizedFileURL - if runtimeLocator.isExecutable(at: standardized) { - return .found(standardized, .configured) - } - return runtimeLocator.mavenExecutable(forHomePath: standardized.path) - .map { RuntimeChoice.found($0, .configured) } ?? .invalid(standardized.path) - } - let wrapper = rootURL.appendingPathComponent("mvnw") - if runtimeLocator.isExecutable(at: wrapper) { - return .found(wrapper, .mavenWrapper) - } - return runtimeLocator.systemMavenExecutable().map { RuntimeChoice.found($0, .systemMaven) } ?? .notFound - } - - /// Whether a runtime discovery has completed for the open project. Until - /// then an automatic JDK cannot be named without probing synchronously. - var hasDiscoveredRuntimes: Bool { discoveredProjectURL == projectURL && projectURL != nil } - - /// Resolves a Gradle wrapper before falling back to a system Gradle. The - /// executable check is delegated to RuntimeLocator so platform adapters - /// can apply their own permissions and path rules. - func gradleExecutable(at rootURL: URL) -> URL? { - let normalizedRoot = rootURL.standardizedFileURL - let wrappers = [ - normalizedRoot.appendingPathComponent("gradlew"), - normalizedRoot.appendingPathComponent("gradlew.bat") - ] - if let wrapper = wrappers.first(where: { runtimeLocator.isExecutable(at: $0) }) { - return wrapper - } - return executableOnPath("gradle") - } - - func activeJavaRuntime() -> JavaRuntimeCandidate? { - guard let home = javaHomeURL()?.path else { return nil } - return javaRuntimes.first { $0.homePath == home } - } - - func loadRunConfigurationToolchainCandidates( - projectRoot: URL? = nil, - javaHomeOverride: String? = nil, mavenExecutableOverride: String? = nil - ) async throws -> [ProjectToolchainCandidate] { - guard reloadSettings() else { throw RunConfigurationOperationFailure(message: settingsError ?? "") } - let sessionID = runtimeSessionID - let capturedSettings = settings - let locator = runtimeLocator - func checkCurrent() throws { - guard reloadSettings(), !Task.isCancelled, runtimeSessionID == sessionID, settings == capturedSettings else { throw CancellationError() } - } - try checkCurrent() - if chooseJavaHome(overridePath: javaHomeOverride, detected: { - self.hasDiscoveredRuntimes ? self.javaRuntimes : self.launchJavaRuntimes - }) == nil { - let runtimes = await Self.backgroundProbe { cancelled in - locator.discoverJavaRuntimes(isCancelled: cancelled) - } - try checkCurrent() - launchJavaRuntimes = runtimes - } - let javaHome = javaHomeURL(overridePath: javaHomeOverride) - let explicitMaven = projectRoot.flatMap { mavenExecutable(at: $0, overridePath: mavenExecutableOverride) } - let fallbackMaven = projectRoot.flatMap { mavenExecutable(at: $0) } - let probed: (JavaRuntimeCandidate?, MavenRuntimeCandidate?) = await Self.backgroundProbe { cancelled in - guard !cancelled() else { return (nil, nil) } - let java = javaHome.flatMap(locator.javaRuntime(at:)) - guard !cancelled() else { return (nil, nil) } - let maven = explicitMaven.flatMap(locator.mavenRuntime(at:)) - guard !cancelled() else { return (nil, nil) } - return (java, maven ?? fallbackMaven.flatMap(locator.mavenRuntime(at:))) - } - try checkCurrent() - return Self.toolchainCandidates(java: probed.0, maven: probed.1) - } - - /// Blocking platform probes run on a worker queue, never a cooperative executor. - private static func backgroundProbe( - _ operation: @escaping @Sendable (@Sendable () -> Bool) -> Value - ) async -> Value { - let cancellation = RuntimeProbeCancellation() - return await withTaskCancellationHandler { - await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: operation { cancellation.isCancelled }) - } - } - } onCancel: { - cancellation.cancel() - } - } - - func runConfigurationToolchainCandidates( - projectRoot: URL? = nil, - javaHomeOverride: String? = nil, - mavenExecutableOverride: String? = nil - ) -> [ProjectToolchainCandidate] { - let java = javaHomeURL(overridePath: javaHomeOverride).flatMap(runtimeLocator.javaRuntime(at:)) - let maven = projectRoot.flatMap { root in - mavenExecutable(at: root, overridePath: mavenExecutableOverride) - .flatMap(runtimeLocator.mavenRuntime(at:)) - } ?? projectRoot.flatMap { root in - mavenExecutable(at: root).flatMap(runtimeLocator.mavenRuntime(at:)) - } - return Self.toolchainCandidates(java: java, maven: maven) - } - - private static func toolchainCandidates(java: JavaRuntimeCandidate?, maven: MavenRuntimeCandidate?) -> [ProjectToolchainCandidate] { - var result: [ProjectToolchainCandidate] = [] - if let java { - result.append(ProjectToolchainCandidate( - id: "project-jdk", - type: "java", - version: java.version, - vendor: java.vendor - )) - } - if let maven { - result.append(ProjectToolchainCandidate( - id: "project-maven", - type: "maven", - version: maven.version, - vendor: "" - )) - } - return result - } - - package func overlayProjectRuntime( - onto options: RunOptions, - modulePath: String?, - workingDirectory: String? - ) -> RunOptions { - reloadSettings() - return settings.overlay( - onto: options, - workspaceRelativePath: ProjectRuntimeInventory.workspaceRelativePath( - modulePath: modulePath, - workingDirectory: workingDirectory - ) - ) - } - - /// An explicit Save action only. The adapter rejects a draft whose source - /// changed externally; failed saves leave the caller's draft intact. - @discardableResult - func updateSettings(_ draft: ProjectRuntimeSettings, expecting expected: ProjectRuntimeSettingsSnapshot? = nil) -> Bool { - guard let projectURL, let settingsSnapshot = expected ?? settingsSnapshot else { return false } - do { - let saved = try settingsStore.save(draft, at: projectURL, expecting: settingsSnapshot) - self.settingsSnapshot = saved - settings = saved.settings - if settingsError != nil { settingsError = nil } - runtimeLocator.configureProbePaths([settings.javaHomePath, settings.mavenJavaHomePath, settings.mavenExecutableOverride]) - if usesWorkspaceRuntime { - discoveredProjectURL = nil - discoveryTask?.cancel() - discoveryTask = Task { [weak self] in await self?.performRuntimeRefresh() } - } - if !javaRuntimes.isEmpty { refreshJavaEnvironmentReport(using: javaRuntimes) } - return true - } catch { - if settingsError != error.localizedDescription { settingsError = error.localizedDescription } - return false - } - } - - /// Selection reads use the same current local document as Run. This is a - /// read-only refresh; observing settings never writes defaults or migrates. - @discardableResult - func reloadSettings(migrateLegacy: Bool = false) -> Bool { - guard let projectURL else { return true } - do { - let loaded = try settingsStore.load(at: projectURL, migrateLegacy: migrateLegacy) - settingsSnapshot = loaded - if settings != loaded.settings { settings = loaded.settings } - if settingsError != nil { settingsError = nil } - return true - } catch { - settingsSnapshot = nil - settings = ProjectRuntimeSettings() - if settingsError != error.localizedDescription { settingsError = error.localizedDescription } - return false - } - } - - /// Project creation is an explicit write, before the project is opened. - /// Existing defaults, including an explicitly automatic choice, win. - func presetJavaHome(_ path: String, for projectURL: URL) throws { - let snapshot = try settingsStore.load(at: projectURL, migrateLegacy: true) - guard !snapshot.hasSavedToolchain else { return } - var draft = snapshot.settings - draft.javaHomePath = path - _ = try settingsStore.save(draft, at: projectURL, expecting: snapshot) - } - - private func normalizedOverridePath(_ path: String) -> String { - let trimmedPath = path.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedPath.isEmpty else { return "" } - return runtimeLocator.normalizedPath(trimmedPath, relativeTo: projectURL) - } - - private func normalizedPath(_ path: String) -> String { - runtimeLocator.normalizedPath(path, relativeTo: nil) - } - -} - -/// Shared only with the owned blocking worker; cancellation stops later probes. -private final class RuntimeProbeCancellation: @unchecked Sendable { - private let lock = NSLock() - private var cancelled = false - var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled } - func cancel() { lock.lock(); defer { lock.unlock() }; cancelled = true } -} diff --git a/macos/Sources/Lithe/Services/Language/LanguagePackRegistry.swift b/macos/Sources/Lithe/Services/Language/LanguagePackRegistry.swift index 8b10d55880..7d12ccc64d 100644 --- a/macos/Sources/Lithe/Services/Language/LanguagePackRegistry.swift +++ b/macos/Sources/Lithe/Services/Language/LanguagePackRegistry.swift @@ -66,8 +66,7 @@ final class LanguagePackRegistry { let hostProvided = extensionRequiredProviderIDs.contains(descriptor.id) ? hostCapabilities[descriptor.id] ?? [] : Set(LanguageHostCapability.allCases) - let runProvider: (any LanguageRunProvider)? = descriptor.id == "java" - || !hostProvided.contains(.run) + let runProvider: (any LanguageRunProvider)? = !hostProvided.contains(.run) ? nil : descriptor.capabilities.contains(.run) ? StandardLanguageRunProvider(descriptor: descriptor) diff --git a/macos/Sources/Lithe/Services/ProjectGeneration/ProjectGenerationService.swift b/macos/Sources/Lithe/Services/ProjectGeneration/ProjectGenerationService.swift index dd52e62476..ba03ccde25 100644 --- a/macos/Sources/Lithe/Services/ProjectGeneration/ProjectGenerationService.swift +++ b/macos/Sources/Lithe/Services/ProjectGeneration/ProjectGenerationService.swift @@ -27,26 +27,22 @@ final class ProjectGenerationService: Sendable { let planner: any ProjectGeneratorPlanning private let platform: any ProjectGenerationPlatform private let initializeGitRepository: @Sendable (URL) -> String? - private let recordJavaHome: @Sendable (URL, String) async throws -> Void private let saveToolPin: @Sendable (URL, ProjectGenerationPlan.ToolPin) async throws -> Void /// - Parameters: /// - initializeGitRepository: Creates a repository at the URL and /// returns an error message, or nil on success. - /// - recordJavaHome: Stores a JDK as the new project's runtime. /// - saveToolPin: Stores the installation a `tool` field chose in the /// project at the URL, where every later tool resolution reads it. init( planner: any ProjectGeneratorPlanning, platform: any ProjectGenerationPlatform, initializeGitRepository: @escaping @Sendable (URL) -> String?, - recordJavaHome: @escaping @Sendable (URL, String) async throws -> Void, saveToolPin: @escaping @Sendable (URL, ProjectGenerationPlan.ToolPin) async throws -> Void = { _, _ in } ) { self.planner = planner self.platform = platform self.initializeGitRepository = initializeGitRepository - self.recordJavaHome = recordJavaHome self.saveToolPin = saveToolPin } @@ -106,9 +102,6 @@ final class ProjectGenerationService: Sendable { throw ProjectGenerationError(message: error.localizedDescription) } - for runtime in plan.runtimes where runtime.runtime == "java" { - try await recordJavaHome(destination, runtime.home) - } let toolPinWarning = await pinTools(of: plan, in: destination) return CreatedProject( url: destination, @@ -124,7 +117,12 @@ final class ProjectGenerationService: Sendable { /// - Returns: The first failure's message, or nil when every pin was saved. private func pinTools(of plan: ProjectGenerationPlan, in destination: URL) async -> String? { var firstFailure: String? - for pin in plan.toolPins { + // A `runtime` field names a tool definition too; its chosen home is + // pinned the same way as a `tool` field's installation. + let runtimePins = plan.runtimes.map { + ProjectGenerationPlan.ToolPin(field: $0.field, tool: $0.runtime, pinAs: "project", home: $0.home, executable: "") + } + for pin in runtimePins + plan.toolPins { do { try await saveToolPin(destination, pin) } catch { diff --git a/macos/Sources/Lithe/Services/Runtime/ProjectRuntimeService+LanguageTools.swift b/macos/Sources/Lithe/Services/Runtime/ProjectRuntimeService+LanguageTools.swift new file mode 100644 index 0000000000..d9be538370 --- /dev/null +++ b/macos/Sources/Lithe/Services/Runtime/ProjectRuntimeService+LanguageTools.swift @@ -0,0 +1,241 @@ +import Foundation +import LitheCoreContracts + +extension ProjectRuntimeService: LanguageToolRuntimePort { + package func languageToolProcessEnvironment(runtimeTools: [String]) -> [String: String] { + var environment = processEnvironment() + // Node-based language servers (Intelephense, TypeScript, …) start + // through launchers that read LITHE_NODE_PATH. An app opened from the + // Dock inherits launchd's PATH, which omits Homebrew and Node version + // managers, so pass the discovered executable explicitly. + // Language servers start automatically when a file opens, so a + // project-provided `node` must never be chosen here: an untrusted + // repository could otherwise run its own program. + if environment["LITHE_NODE_PATH"]?.isEmpty ?? true, + let node = executableCandidates("node").first(where: { $0.source != .project }) { + environment["LITHE_NODE_PATH"] = node.executableURL.path + } + // Declared runtime dependencies are also put on PATH because servers + // such as gopls run the tool themselves and cannot be pointed at it + // through a launcher variable. The same project-local exclusion applies. + var searchPath = (environment["PATH"] ?? "").split(separator: ":").map(String.init) + for tool in runtimeTools { + let key = Self.runtimeToolEnvironmentKey(tool) + if environment[key]?.isEmpty ?? true, + let candidate = executableCandidates(tool).first(where: { $0.source != .project }) { + environment[key] = candidate.executableURL.path + } + guard let configured = environment[key], configured.hasPrefix("/") else { continue } + let directory = URL(fileURLWithPath: configured).deletingLastPathComponent().path + if !searchPath.contains(directory) { + searchPath.insert(directory, at: 0) + } + } + if !runtimeTools.isEmpty { + environment["PATH"] = searchPath.joined(separator: ":") + } + return environment + } + + static func runtimeToolEnvironmentKey(_ tool: String) -> String { + LanguageToolEnvironment.runtimeToolKey(tool) + } + + package func missingLanguageToolMessage(_ name: String) -> String { + missingToolMessage(name) + } +} + +/// Looks up tools and the process environment for the open project, locally or +/// on a remote host. It knows no language: which tools exist and how they are +/// chosen comes from plugin-defined tool definitions (`DefinedToolchains`). +@MainActor +final class ProjectRuntimeService: ObservableObject { + @Published private(set) var projectURL: URL? + private var isDiscovering = false + + private let localRuntimeLocator: any RuntimeLocator + private var runtimeLocator: any RuntimeLocator + private let localToolDiscovery: any RuntimeToolDiscovery + private var toolDiscovery: any RuntimeToolDiscovery + private let workspaceRuntime: ((URL) -> (any RuntimeLocator, any RuntimeToolDiscovery)?)? + private var discoveryTask: Task? + private var activeDiscoveryID: UUID? + /// Project whose host snapshot the locator currently holds. + private var discoveredProjectURL: URL? + + init( + runtimeLocator: any RuntimeLocator, + toolDiscovery: (any RuntimeToolDiscovery)? = nil, + workspaceRuntime: ((URL) -> (any RuntimeLocator, any RuntimeToolDiscovery)?)? = nil + ) { + self.runtimeLocator = runtimeLocator + self.localRuntimeLocator = runtimeLocator + self.toolDiscovery = toolDiscovery ?? DefaultRuntimeToolDiscovery() + self.localToolDiscovery = toolDiscovery ?? DefaultRuntimeToolDiscovery() + self.workspaceRuntime = workspaceRuntime + } + + deinit { + discoveryTask?.cancel() + } + + func openProject(at url: URL) { + discoveryTask?.cancel() + activeDiscoveryID = nil + let normalizedURL = url.standardizedFileURL + projectURL = normalizedURL + let selected = workspaceRuntime?(normalizedURL) + runtimeLocator = selected?.0 ?? localRuntimeLocator + toolDiscovery = selected?.1 ?? localToolDiscovery + discoveredProjectURL = nil + discoveryTask = nil + // The superseded probe no longer owns the flag (its ID was cleared above). + isDiscovering = false + } + + func closeProject() { + discoveryTask?.cancel() + discoveryTask = nil + activeDiscoveryID = nil + projectURL = nil + runtimeLocator = localRuntimeLocator + toolDiscovery = localToolDiscovery + discoveredProjectURL = nil + isDiscovering = false + } + + /// Reads the host snapshot for the open project unless it already ran or is + /// running. A local host answers synchronously, so this matters only for a + /// remote workspace whose environment and PATH must be fetched first. + func ensureRuntimesDiscovered() async { + guard projectURL != nil, !hasDiscoveredRuntimes, !isDiscovering else { return } + await performRuntimeRefresh() + } + + func refreshAvailableRuntimes() async { + runtimeLocator.invalidateProbeCache() + discoveryTask?.cancel() + discoveryTask = nil + await performRuntimeRefresh() + } + + private func performRuntimeRefresh() async { + let targetProjectURL = projectURL + let discoveryID = UUID() + activeDiscoveryID = discoveryID + isDiscovering = true + defer { + if activeDiscoveryID == discoveryID { + activeDiscoveryID = nil + isDiscovering = false + } + } + let runtimeLocator = runtimeLocator + await Self.backgroundProbe { cancelled in + runtimeLocator.probeHost(isCancelled: cancelled) + } + guard !Task.isCancelled, + projectURL == targetProjectURL, + activeDiscoveryID == discoveryID else { return } + discoveredProjectURL = targetProjectURL + } + + /// Whether the host snapshot has been read for the open project. + private var hasDiscoveredRuntimes: Bool { discoveredProjectURL == projectURL && projectURL != nil } + + /// Base environment for launching processes. Overrides are layered on top. + func processEnvironment(overrides: [String: String] = [:]) -> [String: String] { + runtimeLocator.environment().merging(overrides) { _, override in override } + } + + func defaultExecutableSearchPath() -> String? { + runtimeLocator.defaultExecutableSearchPath() + } + + /// Returns all known candidates in preference order. The platform + /// adapter can add project-local, Homebrew, Xcode, or registry sources; + /// the locator fallback keeps existing non-platform implementations fully + /// compatible. + func executableCandidates(_ command: String) -> [RuntimeToolCandidate] { + guard !command.isEmpty, !command.contains("/") else { return [] } + let environment = runtimeLocator.environment() + let discovered = toolDiscovery.candidates( + for: command, + projectURL: projectURL, + environment: environment + ) + var candidates = discovered + var seen = Set(discovered.map { $0.executableURL.standardizedFileURL.path }) + for directory in (environment["PATH"] ?? "").split(separator: ":") where !directory.isEmpty { + let candidateURL = URL(fileURLWithPath: String(directory)) + .appendingPathComponent(command) + .standardizedFileURL + guard runtimeLocator.isExecutable(at: candidateURL), + seen.insert(candidateURL.path).inserted else { continue } + candidates.append(RuntimeToolCandidate( + command: command, + executableURL: candidateURL, + source: .path, + detail: String(directory) + )) + } + return candidates + } + + func toolGuidance(_ command: String) -> RuntimeToolGuidance { + toolDiscovery.guidance( + for: command, + projectURL: projectURL, + environment: runtimeLocator.environment() + ) + } + + func missingToolMessage(_ command: String) -> String { + let guidance = toolGuidance(command) + return guidance.message + } + + /// Resolves a bare program name without starting a process. Returns nil + /// when no candidate is executable. + func executableOnPath(_ command: String) -> URL? { + executableCandidates(command).first?.executableURL + } + + func executableURL(at path: String) -> URL? { + let normalized = normalizedOverridePath(path) + guard !normalized.isEmpty else { return nil } + let url = URL(fileURLWithPath: normalized).standardizedFileURL + return runtimeLocator.isExecutable(at: url) ? url : nil + } + + /// Blocking platform probes run on a worker queue, never a cooperative executor. + private static func backgroundProbe( + _ operation: @escaping @Sendable (@Sendable () -> Bool) -> Value + ) async -> Value { + let cancellation = RuntimeProbeCancellation() + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .utility).async { + continuation.resume(returning: operation { cancellation.isCancelled }) + } + } + } onCancel: { + cancellation.cancel() + } + } + + private func normalizedOverridePath(_ path: String) -> String { + let trimmedPath = path.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedPath.isEmpty else { return "" } + return runtimeLocator.normalizedPath(trimmedPath, relativeTo: projectURL) + } +} + +/// Shared only with the owned blocking worker; cancellation stops later probes. +private final class RuntimeProbeCancellation: @unchecked Sendable { + private let lock = NSLock() + private var cancelled = false + var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled } + func cancel() { lock.lock(); defer { lock.unlock() }; cancelled = true } +} diff --git a/macos/Sources/Lithe/Services/Java/RunExecutableResolver.swift b/macos/Sources/Lithe/Services/Runtime/RunExecutableResolver.swift similarity index 91% rename from macos/Sources/Lithe/Services/Java/RunExecutableResolver.swift rename to macos/Sources/Lithe/Services/Runtime/RunExecutableResolver.swift index e265f8ec54..f9d7bcf33d 100644 --- a/macos/Sources/Lithe/Services/Java/RunExecutableResolver.swift +++ b/macos/Sources/Lithe/Services/Runtime/RunExecutableResolver.swift @@ -48,12 +48,9 @@ final class RunExecutableResolver: RunExecutableResolving { if !toolchainRegistry.contains(identifier: id) { throw RunExecutableResolutionError(message: L10n.string("The selected toolchain is unavailable.")) } - let toolchainProjectURL = id == "project-maven" && plan.workingDirectory != "." - ? projectURL.appending(path: plan.workingDirectory, directoryHint: .isDirectory) - : projectURL let toolchain = try toolchainRegistry.resolve( identifier: id, - projectURL: toolchainProjectURL.standardizedFileURL, + projectURL: projectURL.standardizedFileURL, options: options, runtimeService: runtimeService ) @@ -83,7 +80,7 @@ final class RunExecutableResolver: RunExecutableResolving { let identifier: String? if case .toolchain(let id) = plan.executable { identifier = id } else { identifier = nil } let environment = try environmentResolver.resolveLaunchEnvironment( - toolchain: identifier, selectedHome: resolved.environment["JAVA_HOME"], + toolchain: identifier, inherited: resolved.environment, overrides: planEnvironment ) return ResolvedRunExecutable( @@ -103,8 +100,7 @@ final class RunExecutableResolver: RunExecutableResolving { guard let metadataResolver else { return } let discoveries = toolchainRegistry.discoveries( projectURL: projectURL, - runtimeService: runtimeService, - excludingTypes: ["java", "maven"] + runtimeService: runtimeService ) let metadata = await Task.detached(priority: .utility) { var probeCache: [String: RunToolchainMetadata] = [:] @@ -134,8 +130,7 @@ final class RunExecutableResolver: RunExecutableResolving { return toolchainRegistry .candidates( projectURL: projectURL, - runtimeService: runtimeService, - excludingTypes: ["java", "maven"] + runtimeService: runtimeService ) .map { candidate in guard let value = metadata[candidate.id] else { return candidate } diff --git a/macos/Sources/Lithe/Services/Java/RunLaunchEnvironment.swift b/macos/Sources/Lithe/Services/Runtime/RunLaunchEnvironment.swift similarity index 100% rename from macos/Sources/Lithe/Services/Java/RunLaunchEnvironment.swift rename to macos/Sources/Lithe/Services/Runtime/RunLaunchEnvironment.swift diff --git a/macos/Sources/Lithe/Services/Java/RunToolchainMetadataResolver.swift b/macos/Sources/Lithe/Services/Runtime/RunToolchainMetadataResolver.swift similarity index 91% rename from macos/Sources/Lithe/Services/Java/RunToolchainMetadataResolver.swift rename to macos/Sources/Lithe/Services/Runtime/RunToolchainMetadataResolver.swift index d5ac7a0837..2688b496ba 100644 --- a/macos/Sources/Lithe/Services/Java/RunToolchainMetadataResolver.swift +++ b/macos/Sources/Lithe/Services/Runtime/RunToolchainMetadataResolver.swift @@ -10,9 +10,6 @@ struct ProcessRunToolchainMetadataResolver: RunToolchainMetadataResolving { let probeURLs: [URL] let arguments: [String] switch toolchainType { - case "java", "maven": - // Java and Maven use RuntimeLocator's richer vendor-aware probes. - return RunToolchainMetadata(version: "", vendor: "") case "go": arguments = ["version"] case "python", "node", "rust": diff --git a/macos/Sources/Lithe/Services/Workbench/WorkbenchLayoutStore.swift b/macos/Sources/Lithe/Services/Workbench/WorkbenchLayoutStore.swift index a9b40f139d..32d556b88a 100644 --- a/macos/Sources/Lithe/Services/Workbench/WorkbenchLayoutStore.swift +++ b/macos/Sources/Lithe/Services/Workbench/WorkbenchLayoutStore.swift @@ -21,12 +21,12 @@ struct WorkbenchLayout: Codable, Sendable { static let minimumSidebarWidth = minimumPaneSize static let defaultSidebarWidth: Double = 360 static let defaultTopPaneFraction: Double = 0.72 - static let defaultMavenPaneWidth: Double = 360 + static let defaultRightPaneWidth: Double = 360 var toolWindows: [ToolWindowState]? var groupFractions: [String: Double]? let sidebarWidth: Double let topPaneHeight: Double? - let mavenPaneWidth: Double? + let rightPaneWidth: Double? let branchPopupWidth: Double? let branchPopupHeight: Double? var sidebarToolWindowID: String? @@ -34,10 +34,10 @@ struct WorkbenchLayout: Codable, Sendable { var visibleToolWindowIDs: [String]? var contributionPreferences: [String: WorkbenchFeatureModel.ContributionPreference]? - init(sidebarWidth: Double, topPaneHeight: Double?, mavenPaneWidth: Double? = nil, branchPopupWidth: Double? = nil, branchPopupHeight: Double? = nil) { + init(sidebarWidth: Double, topPaneHeight: Double?, rightPaneWidth: Double? = nil, branchPopupWidth: Double? = nil, branchPopupHeight: Double? = nil) { self.sidebarWidth = sidebarWidth self.topPaneHeight = topPaneHeight - self.mavenPaneWidth = mavenPaneWidth + self.rightPaneWidth = rightPaneWidth self.branchPopupWidth = branchPopupWidth self.branchPopupHeight = branchPopupHeight } @@ -57,7 +57,7 @@ struct WorkbenchLayoutStore { let layout = try? JSONDecoder().decode(WorkbenchLayout.self, from: data), layout.sidebarWidth.isFinite, layout.sidebarWidth >= WorkbenchLayout.minimumPaneSize, - (layout.mavenPaneWidth.map({ $0.isFinite && $0 >= WorkbenchLayout.minimumPaneSize }) ?? true), + (layout.rightPaneWidth.map({ $0.isFinite && $0 >= WorkbenchLayout.minimumPaneSize }) ?? true), (layout.branchPopupWidth.map({ $0.isFinite && $0 > 0 }) ?? true), layout.branchPopupHeight.map({ $0.isFinite && $0 > 0 }) ?? true else { return Self.defaultLayout diff --git a/macos/Sources/Lithe/Theme/JavaFileIconResolver.swift b/macos/Sources/Lithe/Theme/JavaFileIconResolver.swift deleted file mode 100644 index aebf9ae918..0000000000 --- a/macos/Sources/Lithe/Theme/JavaFileIconResolver.swift +++ /dev/null @@ -1,17 +0,0 @@ -import LitheModuleAPI -import Foundation - -enum JavaFileIconResolver { - static func resolve(for url: URL, storage: any FileStorage, logSink: (any LogSink)? = nil) async -> LitheIconKind? { - guard url.pathExtension.lowercased() == "java" else { return nil } - let data = await Task.detached(priority: .utility) { () -> Data? in - do { return try storage.readPrefix(from: url, byteCount: 4 * 1024) } - catch { - logSink?.emit(EditorIconFallbackSelected(error: error, stage: "java")) - return nil - } - }.value - guard let data, let prefix = String(data: data, encoding: .utf8) else { return nil } - return LitheIcons.javaSymbolKind(fromSourcePrefix: prefix) - } -} diff --git a/macos/Sources/Lithe/Theme/LitheIcons.swift b/macos/Sources/Lithe/Theme/LitheIcons.swift index f8aec3cac3..3c9f9c8e95 100644 --- a/macos/Sources/Lithe/Theme/LitheIcons.swift +++ b/macos/Sources/Lithe/Theme/LitheIcons.swift @@ -5,15 +5,11 @@ import SwiftUI /// 项目树、标签页、面包屑和 Search Everywhere 共用的图标分类。 /// 这里是唯一的文件图标分类入口,避免视图层重复判断文件类型。 enum LitheIconKind: Hashable { - // Java 符号 - case javaClass - case javaInterface - case javaEnum - case javaRecord - case javaAnnotation - case javaGeneric - - // 其他语言 + // 符号 + case typeSymbol + case symbol + + // 语言 case swiftSource case kotlinSource case rustSource @@ -34,8 +30,6 @@ enum LitheIconKind: Hashable { case html // 配置与数据 - case maven - case gradle case xml case properties case editorConfig @@ -75,12 +69,8 @@ enum LitheIcons { /// Reused IntelliJ Platform assets; unknown file kinds use the upstream unknown icon. private static let ideaAssetPaths: [LitheIconKind: String] = [ - .javaClass: "nodes/class.svg", - .javaInterface: "nodes/interface.svg", - .javaEnum: "nodes/enum.svg", - .javaRecord: "nodes/record.svg", - .javaAnnotation: "nodes/annotation.svg", - .javaGeneric: "fileTypes/java.svg", + .typeSymbol: "nodes/class.svg", + .symbol: "nodes/variable.svg", .swiftSource: "fileTypes/swiftLang.svg", .kotlinSource: "fileTypes/kotlin.svg", .rustSource: "fileTypes/rust.svg", @@ -99,8 +89,6 @@ enum LitheIcons { .javaScript: "fileTypes/javaScript.svg", .css: "fileTypes/css.svg", .html: "fileTypes/html.svg", - .maven: "maven/mavenProject.svg", - .gradle: "fileTypes/gradle.svg", .xml: "fileTypes/xml.svg", .properties: "fileTypes/properties.svg", .editorConfig: "fileTypes/editorConfig.svg", @@ -145,7 +133,6 @@ enum LitheIcons { "play.fill": "actions/execute.svg", "play.rectangle": "actions/execute.svg", "point.3.connected.trianglepath.dotted": "toolwindows/toolWindowVcs.svg", - "shippingbox": "maven/toolWindowMaven.svg", "ladybug": "toolwindows/toolWindowDebugger.svg", "exclamationmark.triangle": "toolwindows/toolWindowProblems.svg", "ellipsis": "actions/more.svg", @@ -159,7 +146,7 @@ enum LitheIcons { /// 排除目录名:这些目录在 IDEA 里显示为橙色(构建产物)。 private static let excludedDirectoryNames: Set = [ - "target", "build", "out", "bin", "dist", "node_modules", ".gradle", ".idea", ".settings" + "target", "build", "out", "bin", "dist", "node_modules", ".idea" ] /// 依赖锁文件按文件名识别;扩展名为 lock 的其余文件(Cargo.lock、bun.lock 等)走扩展名分支。 @@ -168,9 +155,6 @@ enum LitheIcons { ] private static let licenseFileStems: Set = ["license", "licence", "copying"] - private static let resourceDirectoryNames: Set = ["resources", "res", "webapp", "static"] - private static let sourceDirectoryNames: Set = ["java", "kotlin", "scala", "groovy"] - static func kind(for url: URL, isDirectory: Bool, isInsideSourceRoot: Bool = false) -> LitheIconKind { if isDirectory { return directoryKind(for: url, isInsideSourceRoot: isInsideSourceRoot) } return fileKind( @@ -236,40 +220,19 @@ enum LitheIcons { : "debugger/db_set_breakpoint.svg" } - /// src/main/java、src/test/kotlin 之类的源码根。资源根同样按这个布局 - /// 判断,避免把任意一个叫 resources 的目录标成资源根。 - static func isSourceRootDirectory(_ url: URL) -> Bool { - let name = url.lastPathComponent.lowercased() - guard sourceDirectoryNames.contains(name) || resourceDirectoryNames.contains(name) else { - return false - } - let parent = url.deletingLastPathComponent().lastPathComponent.lowercased() - return parent == "main" || parent == "test" - } - + /// 目录角色(源码根、资源根、模块、包)只来自用户标记或插件导入的构建模型, + /// 这里不按目录名猜测任何语言的工程布局;只有构建产物目录按名字标成排除目录。 + /// 已知位于源码根之下、且名字是合法包段的目录显示为包。 private static func directoryKind(for url: URL, isInsideSourceRoot: Bool) -> LitheIconKind { let name = url.lastPathComponent if excludedDirectoryNames.contains(name.lowercased()) { return .excludedFolder } - - let lowercased = name.lowercased() - let parent = url.deletingLastPathComponent().lastPathComponent.lowercased() - let isStandardLayoutRoot = parent == "main" || parent == "test" - - if sourceDirectoryNames.contains(lowercased), isStandardLayoutRoot { - return .sourceFolder - } - if resourceDirectoryNames.contains(lowercased), isStandardLayoutRoot { - return .resourceFolder - } - // 源码根之下、名字是合法包名的目录才是包。IDEA 的 - // JavaDirectoryIconProvider.isValidPackage 同样要求名字合法, - // 所以 META-INF 这种带连字符的目录仍然是普通文件夹。 - if isInsideSourceRoot, isValidPackageName(name) { return .packageFolder } + if isInsideSourceRoot, isPackageSegmentName(name) { return .packageFolder } return .folder } - /// Java 包名段:首字符是字母或下划线,其余是字母、数字或下划线。 - static func isValidPackageName(_ name: String) -> Bool { + /// 包段名:首字符是字母或下划线,其余是字母、数字或下划线。带连字符或点号的 + /// 目录(例如 META-INF)不是包,仍按普通文件夹显示和展开。 + static func isPackageSegmentName(_ name: String) -> Bool { guard let first = name.unicodeScalars.first else { return false } guard CharacterSet.letters.contains(first) || first == "_" else { return false } return name.unicodeScalars.allSatisfy { @@ -279,7 +242,6 @@ enum LitheIcons { private static func fileKind(fileName: String, pathExtension: String) -> LitheIconKind { let name = fileName.lowercased() - if name == "pom.xml" { return .maven } if name == ".gitignore" || name == ".gitattributes" || name == ".dockerignore" { return .gitignore } if name == "package.json" { return .nodePackage } if lockFileNames.contains(name) { return .lockFile } @@ -289,18 +251,13 @@ enum LitheIcons { let stem = (name as NSString).deletingPathExtension if stem == "readme" { return .readme } if licenseFileStems.contains(stem) || stem.hasPrefix("license-") { return .license } - if name == ".classpath" || name == ".project" || name == ".factorypath" { return .xml } if name == ".editorconfig" { return .editorConfig } if name == "dockerfile" || name.hasPrefix("dockerfile.") || ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"].contains(name) { return .docker } - // build.gradle.kts 是构建脚本,扩展名 kts 会被 Kotlin 抢走。 - if name.hasSuffix(".gradle.kts") { return .gradle } // .env.local、.env.production 的扩展名不是 env。 if name == ".env" || name.hasPrefix(".env.") { return .properties } switch pathExtension.lowercased() { - case "java": return .javaGeneric - case "class", "jar": return .binary case "lock": return .lockFile case "mk", "mak": return .makefile case "swift": return .swiftSource @@ -322,8 +279,7 @@ enum LitheIcons { case "css", "scss", "sass", "less": return .css case "html", "htm", "xhtml", "vue", "svelte": return .html case "toml": return .toml - case "gradle": return .gradle - case "xml", "xsd", "wsdl", "pom": return .xml + case "xml", "xsd", "wsdl": return .xml case "properties", "ini", "cfg", "conf", "env": return .properties case "yml", "yaml": return .yaml case "json", "json5", "jsonl", "jsonlines", "ndjson", "ldjson": return .json @@ -339,62 +295,6 @@ enum LitheIcons { } } - /// 从 Java 源码开头判断是 class / interface / enum / record / @interface。 - /// 只看首个类型声明,读不出来就回退 .javaGeneric。 - static func javaSymbolKind(fromSourcePrefix prefix: String) -> LitheIconKind { - let stripped = strippingCommentsAndStrings(prefix) - let pattern = #"\b(class|interface|enum|record)\s+[\p{L}_$]"# - guard let expression = try? NSRegularExpression(pattern: pattern) else { return .javaGeneric } - let range = NSRange(stripped.startIndex.. String { - var result = "" - let characters = Array(source) - var index = 0 - enum State { case code, lineComment, blockComment, string, character } - var state = State.code - - while index < characters.count { - let character = characters[index] - let next = index + 1 < characters.count ? characters[index + 1] : nil - switch state { - case .code: - if character == "/", next == "/" { state = .lineComment; index += 2; continue } - if character == "/", next == "*" { state = .blockComment; index += 2; continue } - if character == "\"" { state = .string; index += 1; continue } - if character == "'" { state = .character; index += 1; continue } - result.append(character) - case .lineComment: - if character == "\n" { state = .code; result.append(character) } - case .blockComment: - if character == "*", next == "/" { state = .code; index += 2; continue } - case .string: - if character == "\\" { index += 2; continue } - if character == "\"" { state = .code } - case .character: - if character == "\\" { index += 2; continue } - if character == "'" { state = .code } - } - index += 1 - } - return result - } - // MARK: - 外观定义 // MARK: - AppKit 消费入口 @@ -473,38 +373,6 @@ enum LitheIcons { render(key: "\(kind):\(size)", content: LitheIcon(kind: kind, size: size)) } - /// Renders the four IDEA Java gutter variants from relationship and direction. - @MainActor - static func implementationMarkerImage( - isInterface: Bool, - pointingDown: Bool, - size: CGFloat - ) -> NSImage? { - let assetPath = implementationMarkerAssetPath( - isInterface: isInterface, - pointingDown: pointingDown - ) - let cacheKey = "idea:\(assetPath):\(size)" - if let cached = ImageCache.shared.storage[cacheKey] { return cached } - guard let source = ideaImage(resourcePath: assetPath), - let image = source.copy() as? NSImage else { return nil } - image.size = NSSize(width: size, height: size) - ImageCache.shared.storage[cacheKey] = image - return image - } - - static func implementationMarkerAssetPath( - isInterface: Bool, - pointingDown: Bool - ) -> String { - switch (isInterface, pointingDown) { - case (true, true): "gutter/implementedMethod.svg" - case (true, false): "gutter/implementingMethod.svg" - case (false, true): "gutter/overridenMethod.svg" - case (false, false): "gutter/overridingMethod.svg" - } - } - static func appLogo(size: CGFloat = 42) -> LitheLogo { LitheLogo(size: size) } diff --git a/macos/Sources/Lithe/Views/App/ContributedBuildConfigurationSection.swift b/macos/Sources/Lithe/Views/App/ContributedBuildConfigurationSection.swift index 7c56db85a2..989fcab8e0 100644 --- a/macos/Sources/Lithe/Views/App/ContributedBuildConfigurationSection.swift +++ b/macos/Sources/Lithe/Views/App/ContributedBuildConfigurationSection.swift @@ -30,7 +30,7 @@ struct ContributedBuildConfigurationSection: View { guard let access = await model.activateExecutionModule(), let build = access.buildSystems, model.isCurrentWorkspace(identity) else { return } do { - _ = try await build.prepareLanguageImport(workspaceURL: identity.url) + try await build.awaitDetection(workspaceURL: identity.url) try Task.checkCancellation() guard model.isCurrentWorkspace(identity) else { return } feature = build diff --git a/macos/Sources/Lithe/Views/App/EffectiveRuntimeLabel.swift b/macos/Sources/Lithe/Views/App/EffectiveRuntimeLabel.swift deleted file mode 100644 index 67fbe2b848..0000000000 --- a/macos/Sources/Lithe/Views/App/EffectiveRuntimeLabel.swift +++ /dev/null @@ -1,231 +0,0 @@ -import LitheModuleAPI -import SwiftUI - -/// Shows the runtime a launch would use in place of "automatic" or "inherited". -/// -/// The value is drawn as a compact card rather than one long monospaced line: -/// the mode and where the runtime came from are badges, the runtime name is the -/// title, and the path stays selectable underneath. Problems use the same card -/// shape with a warning tint so they stand out without turning into plain red -/// paragraphs. -struct EffectiveRuntimeLabel: View { - enum Kind { case java, maven } - enum Mode { case automatic, inherited, projectJDK, configured } - - @ObservedObject var feature: RuntimeSettingsFeatureModel - /// Evaluated in `body`, so the label follows discovery and settings changes - /// even when its parent does not re-render. `nil` while discovery runs. - let choice: () -> RuntimeChoice? - let kind: Kind - let mode: Mode - /// Core's requirement checks for this toolchain, such as a JDK that is too old. - var requirements: [String] = [] - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - content(choice()) - ForEach(requirements, id: \.self) { message in - Label { - Text(message).fixedSize(horizontal: false, vertical: true) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - } - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.error) - .textSelection(.enabled) - } - } - } - - @ViewBuilder private func content(_ choice: RuntimeChoice?) -> some View { - switch choice { - case nil: - detectingCard - case .found(let url, let source)?: - runtimeCard(url: url, source: source, mode: modeTitle) - case .warning(let url, let source, let message)?: - runtimeCard(url: url, source: source, mode: modeTitle, warning: message) - case .unavailable(let message)?: - problemCard(message) - case .fallback(let invalidPath, let replacement)?: - VStack(alignment: .leading, spacing: 6) { - problemCard(String( - format: L10n.string("Cannot use %@; using the project JDK instead."), - invalidPath - )) - fallbackCard(replacement) - } - case .invalid(let path)?: - problemCard(String(format: L10n.string("Cannot be used: %@"), path)) - case .notFound?: - problemCard(kind == .java - ? L10n.string("No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory.") - : L10n.string("No Maven found. Add a Maven Wrapper to the project or choose a Maven installation.")) - } - } - - @ViewBuilder - private func fallbackCard(_ replacement: RuntimeChoice) -> some View { - switch replacement { - case .found(let url, _): - runtimeCard(url: url, source: .projectJDK, mode: L10n.string("Use Project JDK")) - case .warning(let url, _, let message): - runtimeCard(url: url, source: .projectJDK, mode: L10n.string("Use Project JDK"), warning: message) - case .unavailable(let message): - problemCard(message) - case .invalid(let path), .fallback(let path, _): - problemCard(String(format: L10n.string("Cannot be used: %@"), path)) - case .notFound: - problemCard(kind == .java - ? L10n.string("No JDK found. Set JAVA_HOME, install a JDK, or choose a JDK directory.") - : L10n.string("No Maven found. Add a Maven Wrapper to the project or choose a Maven installation.")) - } - } - - private var detectingCard: some View { - HStack(spacing: 10) { - ProgressView().controlSize(.small) - Text("Detecting…") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - Spacer(minLength: 0) - } - .padding(10) - .frame(maxWidth: .infinity, alignment: .leading) - .cardChrome() - } - - private func runtimeCard( - url: URL, - source: RuntimeChoiceSource, - mode: String, - warning: String? = nil - ) -> some View { - HStack(alignment: .top, spacing: 10) { - iconTile(isWarning: warning != nil) - - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 6) { - Text(mode) - .font(LitheTheme.uiFont(size: 10, weight: .semibold)) - .foregroundStyle(LitheTheme.accent) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(LitheTheme.accent.opacity(0.12)) - .clipShape(Capsule()) - if let source = sourceTitle(source) { - Text(source) - .font(LitheTheme.uiFont(size: 10.5)) - .foregroundStyle(LitheTheme.tertiaryText) - } - } - - Text(runtimeName(at: url)) - .font(LitheTheme.uiFont(size: 12.5, weight: .semibold)) - .foregroundStyle(LitheTheme.primaryText) - .lineLimit(1) - .truncationMode(.middle) - - HStack(spacing: 4) { - Image(systemName: "folder") - .font(LitheTheme.uiFont(size: 9)) - Text(verbatim: url.path) - .lineLimit(1) - .truncationMode(.middle) - .textSelection(.enabled) - .help(Text(verbatim: url.path)) - } - .font(LitheTheme.uiFont(size: 10.5, design: .monospaced)) - .foregroundStyle(LitheTheme.secondaryText) - - if let warning { - Label { - Text(warning).fixedSize(horizontal: false, vertical: true) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - } - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.warning) - .textSelection(.enabled) - } - } - - Spacer(minLength: 0) - } - .padding(10) - .frame(maxWidth: .infinity, alignment: .leading) - .cardChrome() - } - - private func problemCard(_ message: String) -> some View { - HStack(alignment: .top, spacing: 10) { - iconTile(isWarning: true, isError: true) - Text(message) - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.primaryText) - .fixedSize(horizontal: false, vertical: true) - .textSelection(.enabled) - Spacer(minLength: 0) - } - .padding(10) - .frame(maxWidth: .infinity, alignment: .leading) - .background(LitheTheme.error.opacity(0.06)) - .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) - .overlay { - RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(LitheTheme.error.opacity(0.28), lineWidth: 1) - } - } - - private func iconTile(isWarning: Bool, isError: Bool = false) -> some View { - let tint = isError ? LitheTheme.error : (isWarning ? LitheTheme.warning : LitheTheme.accent) - return RoundedRectangle(cornerRadius: 7, style: .continuous) - .fill(tint.opacity(0.12)) - .frame(width: 30, height: 30) - .overlay { - Image(systemName: isWarning - ? "exclamationmark.triangle.fill" - : (kind == .java ? "cup.and.saucer.fill" : "shippingbox.fill")) - .font(LitheTheme.uiFont(size: 13, weight: .semibold)) - .foregroundStyle(tint) - } - } - - private var modeTitle: String { - switch mode { - case .automatic: L10n.string("Automatic") - case .inherited: L10n.string("Inherited from project") - case .projectJDK: L10n.string("Use Project JDK") - case .configured: L10n.string("Selected runtime") - } - } - - private func runtimeName(at url: URL) -> String { - switch kind { - case .java: feature.javaRuntimeName(at: url) ?? "JDK" - case .maven: feature.mavenRuntimeName(at: url) ?? "Maven" - } - } - - /// The mode already names configured and inherited values. - private func sourceTitle(_ source: RuntimeChoiceSource) -> String? { - switch source { - case .configured, .projectSetting, .projectJDK: nil - case .javaHomeEnvironment: L10n.string("from JAVA_HOME") - case .detected: L10n.string("detected on this Mac") - case .mavenWrapper: L10n.string("project Maven Wrapper") - case .systemMaven: L10n.string("system Maven") - } - } -} - -private extension View { - func cardChrome() -> some View { - background(LitheTheme.settingsControlBackground) - .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) - .overlay { - RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(LitheTheme.settingsControlBorder.opacity(0.8), lineWidth: 1) - } - } -} diff --git a/macos/Sources/Lithe/Views/App/LocalHistorySettingsControl.swift b/macos/Sources/Lithe/Views/App/LocalHistorySettingsControl.swift index 99f4f61a6b..0412fc7cf6 100644 --- a/macos/Sources/Lithe/Views/App/LocalHistorySettingsControl.swift +++ b/macos/Sources/Lithe/Views/App/LocalHistorySettingsControl.swift @@ -54,7 +54,7 @@ struct LocalHistorySettingsControl: View { .font(LitheTheme.uiFont(size: 11)) .foregroundStyle(LitheTheme.tertiaryText) LitheInfoTip("Type a path inside the project to check it against the rules above as you edit them: whether local history records the file, and whether Git ignores it. Git ignore rules do not affect local history.") - LitheTextField(verbatim: "src/generated/Api.java", text: $testPath) + LitheTextField(verbatim: "src/generated/api.txt", text: $testPath) .frame(maxWidth: 260) .accessibilityLabel(Text("Test path")) testResult diff --git a/macos/Sources/Lithe/Views/App/McpSettingsView.swift b/macos/Sources/Lithe/Views/App/McpSettingsView.swift index 25830e145d..565a8ba1dd 100644 --- a/macos/Sources/Lithe/Views/App/McpSettingsView.swift +++ b/macos/Sources/Lithe/Views/App/McpSettingsView.swift @@ -15,7 +15,7 @@ struct McpSettingsView: View { LitheSettingsSection( title: "Lithe IDE access", accessory: { - LitheInfoTip("Authorize this project to expose environment, Maven, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant.") + LitheInfoTip("Authorize this project to expose its environment, build tools, run configurations and output to connected agents. Output may contain sensitive project data. Access ends when this project or Lithe closes, and the project-level server registration is removed. Enabled plugins can also use this project grant.") }, content: { if workspaceURL == nil { @@ -25,8 +25,8 @@ struct McpSettingsView: View { statusCard accessRow( isOn: $feature.allowConfigure, - title: "Allow project environment and Maven configuration changes", - info: "Connected agents can change the project JDK, Maven and run configuration settings." + title: "Allow project environment and build configuration changes", + info: "Connected agents can change the project toolchain, build and run configuration settings." ) accessRow( isOn: $feature.allowExecute, diff --git a/macos/Sources/Lithe/Views/App/NetworkSettingsView.swift b/macos/Sources/Lithe/Views/App/NetworkSettingsView.swift index 552490fef7..b52f146ed6 100644 --- a/macos/Sources/Lithe/Views/App/NetworkSettingsView.swift +++ b/macos/Sources/Lithe/Views/App/NetworkSettingsView.swift @@ -6,7 +6,7 @@ import SwiftUI /// Three proxy modes for the application's own HTTP traffic. The custom mode /// exposes the full server configuration: type, host, port, optional /// credentials, an exclusion list and a connectivity check. Terminal -/// commands, Git, JVM dependency downloads and the built-in updater keep +/// commands, Git, build-tool dependency downloads and the built-in updater keep /// their own network settings; the updater always follows the system proxy. struct NetworkSettingsView: View { @EnvironmentObject private var settingsContext: SettingsModelContext @@ -29,7 +29,7 @@ struct NetworkSettingsView: View { var body: some View { VStack(alignment: .leading, spacing: 10) { LitheSettingsSection(title: "Proxy server", accessory: { - LitheInfoTip("These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, JVM dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests.") + LitheInfoTip("These settings apply to Lithe's own requests: the plugin marketplace, GitHub and AI providers. Terminal commands, Git, build tool dependency downloads and the built-in updater keep their own network settings; the updater always follows the system proxy. Changes apply to new requests.") }) { row( "Proxy mode", diff --git a/macos/Sources/Lithe/Views/App/PluginManagementView.swift b/macos/Sources/Lithe/Views/App/PluginManagementView.swift index 9ef4a7e583..02e6bed356 100644 --- a/macos/Sources/Lithe/Views/App/PluginManagementView.swift +++ b/macos/Sources/Lithe/Views/App/PluginManagementView.swift @@ -684,12 +684,6 @@ struct PluginManagementListContent { tint: LitheTheme.accent, summary: "Retired official Go plugin. Go support is now the community plugin Go Support in Lithe Store." ) - case OfficialPluginCatalog.javaPluginID: - Presentation( - systemImage: "cup.and.saucer", - tint: LitheTheme.warning, - summary: "Adds Java language intelligence through the Eclipse JDT language server, with Lombok, debugging, and test support. Ships its own Java runtime." - ) case OfficialPluginCatalog.phpPluginID: Presentation( systemImage: "globe", diff --git a/macos/Sources/Lithe/Views/App/ProcessTerminationSettingsView.swift b/macos/Sources/Lithe/Views/App/ProcessTerminationSettingsView.swift index ff3a73c4ee..11b4564436 100644 --- a/macos/Sources/Lithe/Views/App/ProcessTerminationSettingsView.swift +++ b/macos/Sources/Lithe/Views/App/ProcessTerminationSettingsView.swift @@ -18,7 +18,7 @@ struct ProcessTerminationSettingsView: View { }) { row( "Run services", - info: "Run configurations and Maven goals started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." + info: "Run configurations and build tasks started in Lithe. They always stop when their project or window closes or Lithe quits, together with the processes they started; this only decides whether Lithe lists them and asks first." ) { select(\.runServicesOnExit, options: RunServiceExitPolicy.allCases, label: "Run services") { switch $0 { @@ -30,7 +30,7 @@ struct ProcessTerminationSettingsView: View { row( "Terminals with running programs", - info: "A terminal is busy when a program other than the shell still runs in it, such as a Spring Boot app, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." + info: "A terminal is busy when a program other than the shell still runs in it, such as a dev server, npm run dev or a job you sent to the background. Idle terminals always close without asking. Ending a terminal ends every program started in it." ) { select(\.terminalOnQuit, options: TerminalQuitPolicy.allCases, label: "Terminals with running programs") { switch $0 { diff --git a/macos/Sources/Lithe/Views/App/ProjectRuntimeSettingsView.swift b/macos/Sources/Lithe/Views/App/ProjectRuntimeSettingsView.swift deleted file mode 100644 index f543a465e2..0000000000 --- a/macos/Sources/Lithe/Views/App/ProjectRuntimeSettingsView.swift +++ /dev/null @@ -1,556 +0,0 @@ -import Foundation -import LitheModuleAPI -import SwiftUI -import LitheCoreContracts - -struct ProjectRuntimeSettingsView: View { - /// Observes the model: this page shows live run and Maven feature state, - /// which the settings window's `SettingsModelContext` does not republish. - @EnvironmentObject private var model: AppModel - @ObservedObject var feature: RuntimeSettingsFeatureModel - @State private var selectedSubprojectID = ProjectRuntimeInventory.projectDefaultsID - /// Editing waits for the canonical toolchain snapshot. Opening is read-only. - @State private var isPrepared = false - - var body: some View { - VStack(spacing: 0) { - header - if let message = feature.settingsError { - Text(message).font(LitheTheme.smallFont).foregroundStyle(LitheTheme.error).padding(8) - } - if model.workspaceURL == nil { - emptyWorkspace - } else { - HStack(spacing: 0) { - subprojectList - Rectangle().fill(LitheTheme.divider).frame(width: 1) - detail - } - .disabled(!isPrepared || feature.isSaving) - } - } - .background(LitheTheme.settingsSurface) - .task(id: model.currentWorkspaceIdentity) { - let identity = model.currentWorkspaceIdentity - isPrepared = false - await model.prepareProjectRuntimeSettings() - guard !Task.isCancelled, model.currentWorkspaceIdentity == identity else { return } - if feature.subprojects.contains(where: { $0.id == selectedSubprojectID }) == false { - selectedSubprojectID = ProjectRuntimeInventory.projectDefaultsID - } - isPrepared = true - } - } - - private var header: some View { - HStack { - if model.workspaceURL != nil { - Text("This computer · This project") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - } - Text(verbatim: ".lithe/run/local.json") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - Spacer() - Button("Cancel") { feature.cancelChanges() } - .buttonStyle(LitheActionButtonStyle()) - .disabled(!feature.hasChanges || feature.isSaving) - Button("Save") { Task { await model.persistProjectRuntimeSettings() } } - .buttonStyle(LitheActionButtonStyle()) - .disabled(!isPrepared || !feature.hasChanges || feature.isSaving) - if feature.isDiscovering { - ProgressView() - .controlSize(.small) - Text("Discovering…") - .font(LitheTheme.uiFont(size: 11.5)) - .foregroundStyle(LitheTheme.secondaryText) - } else if !isPrepared && model.workspaceURL != nil { - ProgressView() - .controlSize(.small) - Text("Loading project environment…") - .font(LitheTheme.uiFont(size: 11.5)) - .foregroundStyle(LitheTheme.secondaryText) - } - Button { - Task { - await feature.refreshAvailableRuntimes() - await model.prepareProjectRuntimeSettings() - } - } label: { - Label("Refresh detected runtimes", systemImage: "arrow.clockwise") - } - .buttonStyle(LitheActionButtonStyle()) - .disabled(feature.isDiscovering || feature.isSaving) - } - .padding(.horizontal, 16) - .frame(height: 40) - .background(LitheTheme.settingsSurface) - } - - private var emptyWorkspace: some View { - VStack(alignment: .leading, spacing: 8) { - Text("Open a project to configure its JDK and Maven runtime.") - .font(LitheTheme.uiFont(size: 13, weight: .medium)) - .foregroundStyle(LitheTheme.primaryText) - Text("Application-wide editor and terminal settings remain available in the other categories.") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - } - .padding(16) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - } - - private var subprojectList: some View { - LitheTreeList( - feature.subprojects, - selection: Binding(get: { selectedSubprojectID }, set: { if let id = $0 { selectedSubprojectID = id } }), - hierarchy: { .init(depth: $0.parentID == nil ? 0 : 1) }, multiline: true - ) { subproject in - subprojectRow(subproject) - } - .frame(width: 230) - .frame(maxHeight: .infinity) - .background(LitheTheme.settingsSurface) - } - - private func subprojectRow(_ subproject: ProjectRuntimeSubproject) -> some View { - let isSelected = selectedSubprojectID == subproject.id - return - HStack(spacing: 8) { - Image(systemName: icon(for: subproject.kind)) - .font(LitheTheme.uiFont(size: 12, weight: .medium)) - .frame(width: 16) - VStack(alignment: .leading, spacing: 1) { - Text(subproject.title) - .font( - LitheTheme.uiFont( - size: 12.5, weight: subproject.kind == .projectDefaults ? .semibold : .regular) - ) - .lineLimit(1) - if subproject.displaysPath { - Text(subproject.relativePath) - .font(LitheTheme.uiFont(size: 10.5, design: .monospaced)) - .foregroundStyle( - isSelected ? LitheTheme.settingsSelectionText.opacity(0.8) : LitheTheme.tertiaryText - ) - .lineLimit(1) - } - } - Spacer(minLength: 4) - } - .padding(.horizontal, 10) - .padding(.vertical, 6) - .frame(maxWidth: .infinity, alignment: .leading) - .foregroundStyle(LitheTheme.primaryText) - } - - private var selectedSubproject: ProjectRuntimeSubproject? { - feature.subprojects.first { $0.id == selectedSubprojectID } - ?? feature.subprojects.first - } - - private var detail: some View { - ScrollView { - VStack(alignment: .leading, spacing: 8) { - if let subproject = selectedSubproject { - HStack(spacing: 4) { - Text(subproject.title) - .font(LitheTheme.uiFont(size: 13, weight: .semibold)) - .foregroundStyle(LitheTheme.primaryText) - LitheInfoTip("These defaults apply only to this project on this computer. Run configurations inherit them unless overridden. Use the Project save scope in a run configuration to share settings with your team.") - } - .padding(.top, 8) - .padding(.bottom, 4) - if subproject.kind == .projectDefaults { - projectDefaultsDetail - } else if subproject.usesJava { - javaSubprojectDetail(subproject) - } else { - otherSubprojectDetail(subproject) - } - } - } - .padding(.horizontal, 16) - .padding(.bottom, 20) - .frame(maxWidth: .infinity, alignment: .leading) - } - .litheScrollViewChrome(alwaysShowVertical: true, usesCompactScrollers: true) - } - - private var projectDefaultsDetail: some View { - VStack(alignment: .leading, spacing: 10) { - group("Java SDK", info: "Maven, Run, and Debug use this JDK unless a subproject or run configuration overrides it.") { - row("Project JDK") { - HStack(spacing: 6) { - runtimePicker( - selection: javaHomeBinding, - options: javaHomeOptions(current: feature.settings.javaHomePath), - accessibilityLabel: "Project JDK", - title: { feature.javaRuntimeTitle(for: $0, automaticTitle: "Detected JDK") } - ) - chooseDirectoryButton( - value: javaHomeBinding, - title: "Choose a JDK directory", - help: L10n.string("Choose JDK directory") - ) - } - } - EffectiveRuntimeLabel( - feature: feature, - choice: { feature.javaChoice(overridePath: nil) }, - kind: .java, - mode: feature.settings.javaHomePath.isEmpty ? .automatic : .configured, - requirements: requirementMessages(for: "project-jdk") - ) - } - - group("Maven", info: "Automatic uses a project mvnw first, then detected Maven, then mvnd.") { - row("Maven source") { - LitheSettingsSelect( - selection: mavenHomeSelectionBinding, - options: MavenHomeSelection.allCases, - width: 220, - accessibilityLabel: "Maven source", - title: \MavenHomeSelection.title - ) - } - if feature.settings.mavenHomeSelection == .custom { - pathField( - title: "Maven Home", - value: mavenHomePathBinding, - placeholder: "Choose Maven or mvnd home, bin, or executable", - chooseTitle: "Choose Maven or mvnd home, bin, or executable", - fileOrDirectory: true - ) - } - if let workspaceURL = model.workspaceURL { - EffectiveRuntimeLabel( - feature: feature, - choice: { - feature.mavenChoice( - at: workspaceURL, - overridePath: feature.settings.mavenExecutableOverride - ) - }, - kind: .maven, - // A custom source without a path still resolves automatically. - mode: feature.settings.mavenExecutableOverride.isEmpty ? .automatic : .configured, - requirements: requirementMessages(for: "project-maven") - ) - } - row("Maven JDK") { - HStack(spacing: 6) { - runtimePicker( - selection: mavenJavaHomeBinding, - options: javaHomeOptions(current: feature.settings.mavenJavaHomePath, includeAutomatic: true), - accessibilityLabel: "Maven JDK", - title: { feature.javaRuntimeTitle(for: $0, automaticTitle: "Use Project JDK") } - ) - chooseDirectoryButton( - value: mavenJavaHomeBinding, - title: "Choose a JDK directory", - help: L10n.string("Choose Maven JDK") - ) - } - } - EffectiveRuntimeLabel( - feature: feature, - choice: { feature.mavenJavaChoice(overridePath: nil) }, - kind: .java, - mode: feature.settings.mavenJavaHomePath.isEmpty ? .projectJDK : .configured - ) - - } - - Text("Project runtime settings are saved locally for this project.") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - if let error = model.runFeatureIfActive?.configurationSaveError { - Text(error) - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.error) - } - } - } - - private func javaSubprojectDetail(_ subproject: ProjectRuntimeSubproject) -> some View { - let override = feature.settings.exactOverride(for: subproject.relativePath) - let effectiveJavaHome = feature.effectiveJavaHome(for: subproject) - return VStack(alignment: .leading, spacing: 10) { - group("Java SDK", info: "This subproject can use a different JDK from other backends in the same workspace.") { - row("Project JDK") { - HStack(spacing: 6) { - runtimePicker( - selection: moduleJavaHomeBinding(for: subproject), - options: javaHomeOptions(current: override?.javaHomePath ?? "", includeAutomatic: true), - accessibilityLabel: "Project JDK", - title: { feature.javaRuntimeTitle(for: $0, automaticTitle: "Inherit project JDK") } - ) - chooseDirectoryButton( - value: moduleJavaHomeBinding(for: subproject), - title: "Choose a JDK directory", - help: L10n.string("Choose JDK directory") - ) - } - } - EffectiveRuntimeLabel( - feature: feature, - choice: { feature.javaChoice(overridePath: effectiveJavaHome.isEmpty ? nil : effectiveJavaHome) }, - kind: .java, - mode: (override?.javaHomePath ?? "").isEmpty ? .inherited : .configured - ) - } - - group("Maven") { - pathField( - title: "Maven Home", - value: moduleMavenHomeBinding(for: subproject), - placeholder: "Inherit project Maven", - chooseTitle: "Choose Maven or mvnd home, bin, or executable", - fileOrDirectory: true - ) - row("Maven JDK") { - runtimePicker( - selection: moduleMavenJavaHomeBinding(for: subproject), - options: javaHomeOptions( - current: override?.mavenJavaHomePath ?? "", - includeAutomatic: true - ), - accessibilityLabel: "Maven JDK", - title: { feature.javaRuntimeTitle(for: $0, automaticTitle: "Inherit project Maven JDK") } - ) - } - } - } - } - - private func otherSubprojectDetail(_ subproject: ProjectRuntimeSubproject) -> some View { - VStack(alignment: .leading, spacing: 10) { - HStack(spacing: 4) { - Text("This subproject does not use a JDK.") - .font(LitheTheme.uiFont(size: 13, weight: .medium)) - LitheInfoTip("Frontend and other non-Java roots keep the workspace editor and terminal settings. Java and Maven SDKs only apply to the backends listed on the left.") - } - if subproject.displaysPath { - labeledValue("Path", subproject.relativePath) - } - } - } - - private func requirementMessages(for toolchain: String) -> [String] { - model.runFeatureIfActive?.configurationDiagnostics.toolchainRequirementMessages(for: toolchain) ?? [] - } - - private func labeledValue(_ title: String, _ value: String) -> some View { - VStack(alignment: .leading, spacing: 4) { - Text(LocalizedStringKey(title)) - .font(LitheTheme.uiFont(size: 11.5, weight: .medium)) - .foregroundStyle(LitheTheme.secondaryText) - Text(value) - .font(LitheTheme.uiFont(size: 11.5, design: .monospaced)) - .foregroundStyle(LitheTheme.primaryText) - .textSelection(.enabled) - .lineLimit(2) - } - } - - private func runtimePicker( - selection: Binding, - options: [String], - accessibilityLabel: String, - title: @escaping (String) -> String - ) -> some View { - LitheSettingsSelect( - selection: selection, - options: options, - width: 280, - accessibilityLabel: accessibilityLabel, - title: title, - expandsToFitOptions: true - ) - } - - private func chooseDirectoryButton( - value: Binding, - title: String, - help: String - ) -> some View { - Button { - if let url = model.platformUI.chooseDirectory(title: title, prompt: "Choose") { - value.wrappedValue = url.standardizedFileURL.path - } - } label: { - Image(systemName: "folder") - } - .litheIconButton() - .help(help) - } - - private func pathField( - title: String, - value: Binding, - placeholder: String, - chooseTitle: String, - fileOrDirectory: Bool, - directoryOnly: Bool = false - ) -> some View { - VStack(alignment: .leading, spacing: 5) { - Text(LocalizedStringKey(title)) - .font(LitheTheme.uiFont(size: 11.5, weight: .medium)) - HStack(spacing: 6) { - LitheTextField(LocalizedStringKey(placeholder), text: value) - .help(Text(verbatim: placeholder)) - Button { - value.wrappedValue = "" - } label: { - Image(systemName: "xmark") - } - .litheIconButton() - .help("Use automatic value") - Button { - let url: URL? - if directoryOnly { - url = model.platformUI.chooseDirectory(title: chooseTitle, prompt: "Choose") - } else if fileOrDirectory { - url = model.platformUI.chooseDirectory(title: chooseTitle, prompt: "Choose") - ?? model.platformUI.chooseFile(title: chooseTitle, prompt: "Choose") - } else { - url = model.platformUI.chooseFile(title: chooseTitle, prompt: "Choose") - } - if let url { - value.wrappedValue = url.standardizedFileURL.path - } - } label: { - Image(systemName: "folder") - } - .litheIconButton() - .help("Choose path") - } - } - } - - private func group( - _ title: String, - info: LocalizedStringKey? = nil, - @ViewBuilder content: () -> Content - ) -> some View { - VStack(alignment: .leading, spacing: 8) { - HStack(spacing: 8) { - HStack(spacing: 4) { - Text(LocalizedStringKey(title)) - .font(LitheTheme.uiFont(size: 12, weight: .medium)) - .foregroundStyle(LitheTheme.secondaryText) - .fixedSize() - if let info { - LitheInfoTip(info) - } - } - Rectangle().fill(LitheTheme.divider).frame(height: 1) - } - content() - } - .font(LitheTheme.uiFont(size: 12.5)) - .foregroundStyle(LitheTheme.primaryText) - .padding(.top, 10) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private func row(_ title: String, @ViewBuilder content: () -> Content) -> some View { - HStack(spacing: 8) { - LitheSettingsLabel(LocalizedStringKey(title)) - .fixedSize(horizontal: true, vertical: false) - Spacer(minLength: 16) - content() - } - .frame(minHeight: 28) - } - - private func icon(for kind: ProjectRuntimeSubprojectKind) -> String { - switch kind { - case .projectDefaults: "internaldrive" - case .buildRoot: "shippingbox" - case .buildProject: "cube" - case .other: "globe" - } - } - - private func javaHomeOptions(current: String, includeAutomatic: Bool = true) -> [String] { - var options: [String] = includeAutomatic ? [""] : [] - options.append(contentsOf: feature.javaRuntimes.map(\.homePath)) - let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty, !options.contains(trimmed) { - options.append(trimmed) - } - return options - } - - private var javaHomeBinding: Binding { - Binding( - get: { feature.settings.javaHomePath }, - set: { value in - feature.updateSettings { $0.javaHomePath = value } - } - ) - } - - private var mavenHomeSelectionBinding: Binding { - Binding( - get: { feature.settings.mavenHomeSelection }, - set: { value in - feature.updateSettings { $0.mavenHomeSelection = value } - } - ) - } - - private var mavenHomePathBinding: Binding { - Binding( - get: { feature.settings.mavenHomePath }, - set: { value in - feature.updateSettings { $0.mavenHomePath = value } - } - ) - } - - private var mavenJavaHomeBinding: Binding { - Binding( - get: { feature.settings.mavenJavaHomePath }, - set: { value in - feature.updateSettings { $0.mavenJavaHomePath = value } - } - ) - } - - private func moduleJavaHomeBinding(for subproject: ProjectRuntimeSubproject) -> Binding { - Binding( - get: { feature.settings.exactOverride(for: subproject.relativePath)?.javaHomePath ?? "" }, - set: { value in - feature.updateSettings { - $0.setOverride(path: subproject.relativePath, javaHomePath: value) - } - } - ) - } - - private func moduleMavenHomeBinding(for subproject: ProjectRuntimeSubproject) -> Binding { - Binding( - get: { feature.settings.exactOverride(for: subproject.relativePath)?.mavenExecutablePath ?? "" }, - set: { value in - feature.updateSettings { - $0.setOverride(path: subproject.relativePath, mavenExecutablePath: value) - } - } - ) - } - - private func moduleMavenJavaHomeBinding(for subproject: ProjectRuntimeSubproject) -> Binding { - Binding( - get: { feature.settings.exactOverride(for: subproject.relativePath)?.mavenJavaHomePath ?? "" }, - set: { value in - feature.updateSettings { - $0.setOverride(path: subproject.relativePath, mavenJavaHomePath: value) - } - } - ) - } -} diff --git a/macos/Sources/Lithe/Views/App/RunConfigurationSettingsView.swift b/macos/Sources/Lithe/Views/App/RunConfigurationSettingsView.swift index f62b5cfe90..7216b6fd5f 100644 --- a/macos/Sources/Lithe/Views/App/RunConfigurationSettingsView.swift +++ b/macos/Sources/Lithe/Views/App/RunConfigurationSettingsView.swift @@ -28,7 +28,7 @@ struct RunConfigurationSettingsView: View { // A newer activation task owns the selection once this one is cancelled. guard !Task.isCancelled else { return } selection.finishActivation(activated) - // The editor shows the JDK an automatic or inherited value resolves to. + // The editor shows the toolchain an automatic or inherited value resolves to. await model.runtimeFeature.ensureRuntimesDiscovered() } } diff --git a/macos/Sources/Lithe/Views/App/SettingsSearchVocabulary.swift b/macos/Sources/Lithe/Views/App/SettingsSearchVocabulary.swift index fc7b4f3eb8..7d534127d2 100644 --- a/macos/Sources/Lithe/Views/App/SettingsSearchVocabulary.swift +++ b/macos/Sources/Lithe/Views/App/SettingsSearchVocabulary.swift @@ -21,14 +21,12 @@ enum SettingsSearchVocabulary { ["Editor", "Display", "Editor tabs", "tabs", "Font", "Font size", "Search fonts", "File tree row height", "Show minimap", "Minimap", "Indentation", "Tab width", "Line spacing", "Font ligatures", "Syntax highlighting", "Editor color scheme", "Italic comments", "Colorize bracket pairs", "Line numbers", "Render whitespace", "Soft wrap", "Show indent guides", "Highlight current line", "Sticky scroll", "Smooth scrolling", "Scroll beyond last line", "Cursor style", "Cursor blinking"] case .keymap: ["Keymap", "Keyboard shortcuts", "Shortcuts", "Actions"] - case .project: - ["Project", "Java SDK", "JDK", "Project JDK", "Maven", "Maven Home", "Maven Wrapper", "Maven JDK"] case .toolchainEnvironment: ["Runtime Environment", "Tools", "Directories", "Version files", "Fixed", "Project requirements", "Global defaults", "Automatic discovery"] case .toolchainSources: ["Toolchain Sources", "Login shell", "Shell", "PATH", "Version managers", "Watched files"] case .run: - ["Run configurations", "Program arguments", "VM options", "Environment variables", "Working directory", "Services"] + ["Run configurations", "Program arguments", "Environment variables", "Working directory", "Services"] case .terminal: ["Terminal", "Shell", "Default shell", "Scrollback", "Terminal scrollback", "Scrollback lines"] case .lsp: diff --git a/macos/Sources/Lithe/Views/App/SettingsView.swift b/macos/Sources/Lithe/Views/App/SettingsView.swift index 5fb7d0588e..9ebcceb655 100644 --- a/macos/Sources/Lithe/Views/App/SettingsView.swift +++ b/macos/Sources/Lithe/Views/App/SettingsView.swift @@ -389,9 +389,6 @@ struct SettingsView: View { } else if viewState.selection == .run { RunConfigurationSettingsView() .frame(maxWidth: .infinity, maxHeight: .infinity) - } else if viewState.selection == .project { - ProjectRuntimeSettingsView(feature: model.runtimeFeature) - .frame(maxWidth: .infinity, maxHeight: .infinity) } else if viewState.selection == .toolchainEnvironment { ToolchainEnvironmentSettingsView(feature: model.toolchainSettingsFeature, onOpenPlugins: { viewState.selection = .plugins @@ -428,7 +425,6 @@ struct SettingsView: View { case .keymap: EmptyView() case .terminal: terminalSettings case .lsp: EmptyView() - case .project: EmptyView() case .toolchainEnvironment, .toolchainSources: EmptyView() case .run: EmptyView() case .ai: aiSettings @@ -674,10 +670,6 @@ struct SettingsView: View { isOn: $settings.editorMinimapEnabled, title: "Show minimap" ) - LitheSettingsCheckbox( - isOn: $settings.javaKeywordNavigationFilterEnabled, - title: "Skip definition lookups for Java keywords" - ) } editorAppearanceOptions group("Editor tabs") { diff --git a/macos/Sources/Lithe/Views/Debug/DebugPerformancePane.swift b/macos/Sources/Lithe/Views/Debug/DebugPerformancePane.swift index c729bd93c8..d9bfe8dc08 100644 --- a/macos/Sources/Lithe/Views/Debug/DebugPerformancePane.swift +++ b/macos/Sources/Lithe/Views/Debug/DebugPerformancePane.swift @@ -5,7 +5,6 @@ struct DebugConsoleWithPerformance: View { @ObservedObject var feature: DebugPerformanceFeatureModel @Binding var isExpanded: Bool @Binding var width: CGFloat - var residentMemory = false @ViewBuilder let console: () -> Console @Environment(\.colorScheme) private var colorScheme @State private var hoveredTime: TimeInterval? @@ -55,20 +54,13 @@ struct DebugConsoleWithPerformance: View { if let message = feature.errorMessage { Text(LocalizedStringKey(message)).font(LitheTheme.uiFont(size: 12)).foregroundStyle(LitheTheme.secondaryText) .frame(maxWidth: .infinity, alignment: .leading).padding(12) - } else if feature.samples.isEmpty { - Text(LocalizedStringKey(feature.isSampling - ? (residentMemory ? "Waiting for process performance data…" : "Waiting for JVM performance data…") - : (residentMemory ? "Run tests to view process performance." : "Start a local Java debug session to view performance."))) - .font(LitheTheme.uiFont(size: 12)).foregroundStyle(LitheTheme.secondaryText) - .frame(maxWidth: .infinity, alignment: .leading).padding(12) - } - DebugPerformanceChart(samples: feature.samples, cpu: true, residentMemory: residentMemory, hoveredTime: $hoveredTime) - DebugPerformanceChart(samples: feature.samples, cpu: false, residentMemory: residentMemory, hoveredTime: $hoveredTime) - if residentMemory { - Text("Test process tree · Resident memory") + } else if feature.samples.isEmpty, feature.isSampling { + Text("Waiting for process performance data…") .font(LitheTheme.uiFont(size: 12)).foregroundStyle(LitheTheme.secondaryText) .frame(maxWidth: .infinity, alignment: .leading).padding(12) } + DebugPerformanceChart(samples: feature.samples, cpu: true, hoveredTime: $hoveredTime) + DebugPerformanceChart(samples: feature.samples, cpu: false, hoveredTime: $hoveredTime) Spacer(minLength: 0) } .litheWorkbenchSurface(LitheTheme.editor) @@ -81,11 +73,10 @@ struct DebugPerformanceChart: View { static let visibleDuration: TimeInterval = 60 let samples: [DebugPerformanceSample] let cpu: Bool - var residentMemory = false @Binding var hoveredTime: TimeInterval? @Environment(\.colorScheme) private var colorScheme - private var title: String { cpu ? "CPU" : (residentMemory ? "Resident Memory" : "Heap Memory") } + private var title: String { cpu ? "CPU" : "Resident Memory" } private var color: Color { cpu ? LitheTheme.success : LitheTheme.accent } private var selected: DebugPerformanceSample? { hoveredTime.flatMap { Self.nearestSample(in: visibleSamples, to: $0) } ?? samples.last diff --git a/macos/Sources/Lithe/Views/Debug/DebugToolbarPresentation.swift b/macos/Sources/Lithe/Views/Debug/DebugToolbarPresentation.swift index 35ddf7d707..5e10635897 100644 --- a/macos/Sources/Lithe/Views/Debug/DebugToolbarPresentation.swift +++ b/macos/Sources/Lithe/Views/Debug/DebugToolbarPresentation.swift @@ -29,31 +29,8 @@ enum DebugToolbarPresentation { } } - static func stackFrameLabel(_ frame: DebugStackFrame, showsSourceName: Bool) -> String { - guard showsSourceName, let source = frame.sourceURL, source.pathExtension.lowercased() == "java" else { - return frame.name - } - let suffix = ", " + source.deletingPathExtension().lastPathComponent - // ponytail: remove only an exact redundant provider suffix; richer labels need structured DAP segments. - return frame.name.count > suffix.count && frame.name.hasSuffix(suffix) ? String(frame.name.dropLast(suffix.count)) : frame.name - } - - static func stackFrameText(_ frame: DebugStackFrame, showsSourceName: Bool, isDark: Bool) -> AttributedString { - let label = stackFrameLabel(frame, showsSourceName: showsSourceName) - var result = DiffSyntaxHighlighter.styled(label, fileExtension: frame.sourceURL?.pathExtension ?? "", highlight: nil) - guard frame.sourceURL?.pathExtension.lowercased() == "java", - let location = label.range(of: ":\(frame.line)", options: .backwards), - location.upperBound == label.endIndex || label[location.upperBound...].hasPrefix(", ") else { return result } - let methodAndType = label[.. AttributedString { + DiffSyntaxHighlighter.styled(frame.name, fileExtension: frame.sourceURL?.pathExtension ?? "", highlight: nil) } static let primaryActions: [DebugToolbarActionID] = [ diff --git a/macos/Sources/Lithe/Views/Debug/ExternalDebugAdapterView.swift b/macos/Sources/Lithe/Views/Debug/ExternalDebugAdapterView.swift index 51745796a2..aa1bb983f4 100644 --- a/macos/Sources/Lithe/Views/Debug/ExternalDebugAdapterView.swift +++ b/macos/Sources/Lithe/Views/Debug/ExternalDebugAdapterView.swift @@ -23,7 +23,7 @@ struct ExternalDebugAdapterView: View { VStack(alignment: .leading, spacing: 14) { LitheSettingsLabel( Text("Connect to Debug Adapter"), - info: L10n.string("Connect to an already running DAP server using the active file's installed debugger. This is not a JVM JDWP or gdbserver port. No proxy or tunnel is created.") + info: L10n.string("Connect to an already running DAP server using the active file's installed debugger. This is not a gdbserver port. No proxy or tunnel is created.") ) .font(LitheTheme.uiFont(size: 14, weight: .semibold)) HStack(alignment: .top, spacing: 10) { diff --git a/macos/Sources/Lithe/Views/Debug/GenericDebugView.swift b/macos/Sources/Lithe/Views/Debug/GenericDebugView.swift index e5ae604d57..1098cb638f 100644 --- a/macos/Sources/Lithe/Views/Debug/GenericDebugView.swift +++ b/macos/Sources/Lithe/Views/Debug/GenericDebugView.swift @@ -22,9 +22,8 @@ struct GenericDebugView: View { @State private var watchEditor: WatchEditorContext? @State private var smartStepTargets: [DebugStepInTarget] = [] @State private var isSmartStepPickerPresented = false - @State private var isJavaAttachPresented = false @State private var externalAdapterSource: ExternalAdapterSource? - @State private var isJavaSteppingSettingsPresented = false + @State private var isSteppingFiltersPresented = false @State private var selectedContent: DebugContent = .console @State private var showsMemory = false @State private var memoryInput = "" @@ -58,24 +57,18 @@ struct GenericDebugView: View { feature.setVariable(variable, value: $0) } } - .sheet(isPresented: $isJavaAttachPresented) { - JavaAttachView { host, port in - model.attachJavaDebugger(host: host, port: port) - } - } .sheet(item: $externalAdapterSource) { source in ExternalDebugAdapterView { configuration in await model.connectExternalDebugAdapter(configuration: configuration, fileURL: source.url) } } - .sheet(isPresented: $isJavaSteppingSettingsPresented) { - if let filters = feature.javaSteppingFilters { - JavaSteppingFiltersView( - filters: filters, - onSave: feature.updateJavaSteppingFilters, - onReset: feature.resetJavaSteppingFilters - ) - } + .sheet(isPresented: $isSteppingFiltersPresented) { + SteppingFiltersView( + providers: feature.steppingFilterProviders, + load: feature.steppingFilters(for:), + onSave: feature.updateSteppingFilters(_:for:), + onReset: feature.resetSteppingFilters(for:) + ) } .onAppear { synchronizePerformanceSession() } .onChange(of: feature.activeSessionID) { _ in synchronizePerformanceSession() } @@ -255,16 +248,6 @@ struct GenericDebugView: View { toolbarDivider } } - if feature.canUpdateJavaService { - Button { model.applyDebugServiceUpdate() } label: { - Image(systemName: "bolt.fill") - } - .litheToolbarIconButton() - .padding(.horizontal, 2) - .disabled(feature.updatingServiceSessionID != nil) - .help("Apply code changes to this service") - .accessibilityLabel("Apply code changes") - } if feature.canApplyDeclaredCodeChanges { Button { model.applyDeclaredDebugCodeChanges() } label: { Image(systemName: "bolt.fill") @@ -275,10 +258,6 @@ struct GenericDebugView: View { .help("Apply code changes to the running program") .accessibilityLabel("Apply code changes") } - if feature.serviceUpdateFailed && feature.canUpdateJavaService { - Button("Restart service") { model.restartUpdatedDebugService() } - .disabled(feature.updatingServiceSessionID != nil) - } if let message = feature.serviceUpdateMessage { Text(message).font(.caption).lineLimit(1).help(message) } @@ -458,15 +437,12 @@ struct GenericDebugView: View { LitheContextMenuItem.action("Step Back") { feature.execute(.stepBack) } .disabled(!feature.canStepBack) } - if feature.javaSteppingFilters != nil { - LitheContextMenuItem.action("Java Stepping Filters…") { - isJavaSteppingSettingsPresented = true - } - .disabled(feature.isSessionActive) + // Shown only while some installed adapter declared `features.stepFilters`. + if !feature.steppingFilterProviders.isEmpty { + LitheContextMenuItem.action("Stepping Filters…") { isSteppingFiltersPresented = true } + .disabled(feature.isSessionActive) } LitheContextMenuItem.separator - LitheContextMenuItem.action("Connect to Running JVM…") { isJavaAttachPresented = true } - .disabled(feature.isSessionActive) LitheContextMenuItem.action("Connect to Debug Adapter…") { if let url = model.activeDocument?.url { externalAdapterSource = ExternalAdapterSource(url: url) @@ -691,11 +667,7 @@ struct GenericDebugView: View { resourcePath: "expui/general/moreHorizontal.svg", size: 16, preservesOriginalColors: true) } - Text( - DebugToolbarPresentation.stackFrameText( - frame, - showsSourceName: showsStackSourceName, isDark: colorScheme == .dark) - ) + Text(DebugToolbarPresentation.stackFrameText(frame)) .font(LitheTheme.uiFont(size: 13, weight: .regular)) .lineLimit(1) .truncationMode(.middle) @@ -774,7 +746,6 @@ struct GenericDebugView: View { .frame(maxWidth: .infinity, alignment: .leading) } .buttonStyle(.litheNoPress) - .help("Show JDK, proxy, and framework frames") } } } @@ -2149,60 +2120,78 @@ private struct ExternalAdapterSource: Identifiable { var id: URL { url } } -private struct JavaAttachView: View { +/// Edits the stepping policy of debuggers whose adapters declared +/// `features.stepFilters`. Pattern syntax belongs to the adapter, so patterns +/// are stored and forwarded exactly as typed. +private struct SteppingFiltersView: View { @Environment(\.dismiss) private var dismiss - @State private var host = "localhost" - @State private var port = "5005" - let onAttach: (String, Int) -> Void + let providers: [DebugProviderDeclaration] + let load: (DebugProviderDeclaration) -> DebugSteppingFilters + let onSave: (DebugSteppingFilters, DebugProviderDeclaration) -> Void + let onReset: (DebugProviderDeclaration) -> Void + @State private var selectedKey: String - private var parsedPort: Int? { - guard let value = Int(port), (1...65_535).contains(value) else { return nil } - return value + init( + providers: [DebugProviderDeclaration], + load: @escaping (DebugProviderDeclaration) -> DebugSteppingFilters, + onSave: @escaping (DebugSteppingFilters, DebugProviderDeclaration) -> Void, + onReset: @escaping (DebugProviderDeclaration) -> Void + ) { + self.providers = providers + self.load = load + self.onSave = onSave + self.onReset = onReset + _selectedKey = State(initialValue: providers.first?.storageKey ?? "") + } + + private var selected: DebugProviderDeclaration? { + providers.first { $0.storageKey == selectedKey } ?? providers.first } var body: some View { VStack(alignment: .leading, spacing: 14) { - Text("Connect to Running JVM") - .font(LitheTheme.uiFont(size: 14, weight: .semibold)) - Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10) { - GridRow { - Text("Host") - TextField("localhost", text: $host) - .textFieldStyle(.roundedBorder) - } - GridRow { - Text("Port") - TextField("5005", text: $port) - .textFieldStyle(.roundedBorder) + VStack(alignment: .leading, spacing: 3) { + Text("Stepping Filters") + .font(LitheTheme.uiFont(size: 15, weight: .semibold)) + Text("Controls where Step Into stops. Changes apply to the next debug session of this debugger.") + .font(LitheTheme.smallFont) + .foregroundStyle(LitheTheme.secondaryText) + } + if providers.count > 1 { + Picker("Debugger", selection: $selectedKey) { + ForEach(providers, id: \.storageKey) { provider in + Text(verbatim: provider.displayName).tag(provider.storageKey) + } } + .font(LitheTheme.uiFont(size: 11)) } - HStack(spacing: LitheTheme.ActionButton.spacing) { - Spacer() - Button("Cancel", role: .cancel) { dismiss() }.buttonStyle(LitheActionButtonStyle()) - .keyboardShortcut(.cancelAction) - Button("Connect") { - guard let parsedPort else { return } - onAttach(host.trimmingCharacters(in: .whitespacesAndNewlines), parsedPort) - dismiss() - }.buttonStyle(LitheActionButtonStyle(isPrimary: true)) - .keyboardShortcut(.defaultAction) - .disabled( - host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - || parsedPort == nil + if let selected { + SteppingFiltersEditor( + filters: load(selected), + onSave: { filters in + onSave(filters, selected) + dismiss() + }, + onReset: { + onReset(selected) + dismiss() + }, + onCancel: { dismiss() } ) + // A different debugger starts from its own saved policy. + .id(selected.storageKey) } } .padding(18) - .frame(width: 360) + .frame(width: 560, height: providers.count > 1 ? 500 : 470) + .litheWorkbenchSurface(LitheTheme.editor) } } -private struct JavaSteppingFiltersView: View { - @Environment(\.dismiss) private var dismiss +private struct SteppingFiltersEditor: View { let onSave: (DebugSteppingFilters) -> Void let onReset: () -> Void - @State private var skipJDK: Bool - @State private var skipLibraries: Bool + let onCancel: () -> Void @State private var skipSynthetics: Bool @State private var skipStaticInitializers: Bool @State private var skipConstructors: Bool @@ -2212,36 +2201,22 @@ private struct JavaSteppingFiltersView: View { init( filters: DebugSteppingFilters, onSave: @escaping (DebugSteppingFilters) -> Void, - onReset: @escaping () -> Void + onReset: @escaping () -> Void, + onCancel: @escaping () -> Void ) { self.onSave = onSave self.onReset = onReset - _skipJDK = State(initialValue: filters.classNameFilters.contains("$JDK")) - _skipLibraries = State(initialValue: filters.classNameFilters.contains("$Libraries")) + self.onCancel = onCancel _skipSynthetics = State(initialValue: filters.skipSynthetics) _skipStaticInitializers = State(initialValue: filters.skipStaticInitializers) _skipConstructors = State(initialValue: filters.skipConstructors) _hideFilteredStackFrames = State(initialValue: filters.hideFilteredStackFrames) - _classPatterns = State(initialValue: filters.classNameFilters - .filter { $0 != "$JDK" && $0 != "$Libraries" } - .joined(separator: "\n")) + _classPatterns = State(initialValue: filters.classNameFilters.joined(separator: "\n")) } var body: some View { VStack(alignment: .leading, spacing: 14) { - VStack(alignment: .leading, spacing: 3) { - Text("Java Stepping Filters") - .font(LitheTheme.uiFont(size: 15, weight: .semibold)) - Text("Controls where Step Into stops. Changes apply to the next Java debug session.") - .font(LitheTheme.smallFont) - .foregroundStyle(LitheTheme.secondaryText) - } - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) { - GridRow { - Toggle("Skip JDK and reflection code", isOn: $skipJDK) - Toggle("Skip third-party libraries", isOn: $skipLibraries) - } GridRow { Toggle("Skip synthetic methods", isOn: $skipSynthetics) Toggle("Skip static initializers", isOn: $skipStaticInitializers) @@ -2257,7 +2232,7 @@ private struct JavaSteppingFiltersView: View { VStack(alignment: .leading, spacing: 6) { Text("Additional class patterns") .font(LitheTheme.uiFont(size: 11, weight: .semibold)) - Text("One pattern per line, for example org.mockito.* or com.example.generated.*") + Text("One pattern per line. The debugger defines the pattern syntax.") .font(LitheTheme.smallFont) .foregroundStyle(LitheTheme.secondaryText) TextEditor(text: $classPatterns) @@ -2273,35 +2248,28 @@ private struct JavaSteppingFiltersView: View { } HStack(spacing: LitheTheme.ActionButton.spacing) { - Button("Reset Defaults") { - onReset() - dismiss() - } - .buttonStyle(LitheActionButtonStyle()) + Button("Reset Defaults", action: onReset) + .buttonStyle(LitheActionButtonStyle()) Spacer() - Button("Cancel", role: .cancel) { dismiss() }.buttonStyle(LitheActionButtonStyle()) + Button("Cancel", role: .cancel, action: onCancel) + .buttonStyle(LitheActionButtonStyle()) .keyboardShortcut(.cancelAction) Button("Save") { - var patterns = classPatterns - .split(whereSeparator: \Character.isNewline) - .map(String.init) - if skipJDK { patterns.append("$JDK") } - if skipLibraries { patterns.append("$Libraries") } onSave(DebugSteppingFilters( - classNameFilters: patterns, + classNameFilters: classPatterns + .split(whereSeparator: \Character.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty }, skipSynthetics: skipSynthetics, skipStaticInitializers: skipStaticInitializers, skipConstructors: skipConstructors, hideFilteredStackFrames: hideFilteredStackFrames )) - dismiss() - }.buttonStyle(LitheActionButtonStyle(isPrimary: true)) + } + .buttonStyle(LitheActionButtonStyle(isPrimary: true)) .keyboardShortcut(.defaultAction) } } - .padding(18) - .frame(width: 560, height: 470) - .litheWorkbenchSurface(LitheTheme.editor) } } diff --git a/macos/Sources/Lithe/Views/Diagnostics/LogWindowView.swift b/macos/Sources/Lithe/Views/Diagnostics/LogWindowView.swift index 5f3610cac0..e3b76ecc8c 100644 --- a/macos/Sources/Lithe/Views/Diagnostics/LogWindowView.swift +++ b/macos/Sources/Lithe/Views/Diagnostics/LogWindowView.swift @@ -121,7 +121,7 @@ struct LogWindowView: View { } private var toolbar: some View { LogToolbarLayout { - LitheSearchField("Filter: server:jdtls level>=warn -event:lsp.trace.received /regex/ op:c0ffee", + LitheSearchField("Filter: server:gopls level>=warn -event:lsp.trace.received /regex/ op:c0ffee", text: Binding(get: { model.query.expression }, set: model.setExpression), focus: $filterFocused) { LitheInfoTip("logs.window.filterHelp") Text(verbatim: "⌘F").font(LitheTheme.uiFont(size: 11, design: .monospaced)) diff --git a/macos/Sources/Lithe/Views/Editor/EditorAreaView.swift b/macos/Sources/Lithe/Views/Editor/EditorAreaView.swift index 8ed776224d..009cdf2869 100644 --- a/macos/Sources/Lithe/Views/Editor/EditorAreaView.swift +++ b/macos/Sources/Lithe/Views/Editor/EditorAreaView.swift @@ -14,13 +14,6 @@ enum EditorDocumentIconResolver { ) -> LitheIconKind { resolvedKind ?? LitheIcons.kind(for: url, isDirectory: false) } - - static func overlayResourcePath(for url: URL, hasTests: Bool, hasMain: Bool) -> String? { - guard url.pathExtension.lowercased() == "java" else { return nil } - if hasTests { return "expui/nodes/junitTestMark.svg" } - return hasMain ? "expui/nodes/runnableMark.svg" : nil - } - } private struct EditorDocumentTabStyle: ViewModifier { @@ -32,7 +25,7 @@ private struct EditorDocumentTabStyle: ViewModifier { func body(content: Content) -> some View { content.modifier(LitheToolWindowTabStyle(isSelected: isSelected, isActive: isActive, - fileColor: EditorDocument.isTestSourceFile(document.url, importedSourceRootKind: importedSourceRootKind, hasTests: document.hasJavaTests) + fileColor: EditorDocument.isTestSourceFile(importedSourceRootKind: importedSourceRootKind) ? LitheToolWindowTabStyle.testSourceColor(for: colorScheme) : nil)) } } @@ -59,13 +52,6 @@ private struct EditorDocumentTabIcon: View { kind: EditorDocumentIconResolver.kind(for: document.url, resolvedKind: resolvedKind), size: size ) - .overlay { - if let resource = EditorDocumentIconResolver.overlayResourcePath( - for: document.url, hasTests: document.hasJavaTests, hasMain: document.hasRunnableJavaMain - ) { - LitheIDEAIcon(resourcePath: resource, size: size, preservesOriginalColors: true) - } - } .onChange(of: resolvedKind) { kind in onResolvedKind?(EditorDocumentIconResolver.kind(for: document.url, resolvedKind: kind)) } @@ -73,11 +59,7 @@ private struct EditorDocumentTabIcon: View { let key = resolutionKey let url = document.url resolvedKind = nil - if url.pathExtension.lowercased() == "java" { - guard let kind = await model.javaIconKind(for: url), - !Task.isCancelled, resolutionKey == key else { return } - resolvedKind = kind - } else if LitheIcons.kind(for: url, isDirectory: false) == .generic { + if LitheIcons.kind(for: url, isDirectory: false) == .generic { let resolved = await WorkspaceFileIconResolver.resolve( for: url, suggested: .generic, diff --git a/macos/Sources/Lithe/Views/Editor/MonacoEditorContextMenu.swift b/macos/Sources/Lithe/Views/Editor/MonacoEditorContextMenu.swift index b12040f0a4..cb51b20ab8 100644 --- a/macos/Sources/Lithe/Views/Editor/MonacoEditorContextMenu.swift +++ b/macos/Sources/Lithe/Views/Editor/MonacoEditorContextMenu.swift @@ -52,8 +52,6 @@ final class MonacoEditorContextMenu { case "editor.action.clipboardCopyAction", "editor.action.clipboardCopyWithSyntaxHighlightingAction": "expui/general/copy.svg" case "editor.action.clipboardPasteAction": "expui/general/paste.svg" case "editor.action.formatDocument", "editor.action.formatSelection": "expui/actions/reformatCode.svg" - case "lithe.javaRun.run", "lithe.javaRun.popup.run": "debugger/run.svg" - case "lithe.javaRun.debug", "lithe.javaRun.popup.debug": "debugger/debug.svg" case "lithe.runToCursor": "debugger/runToCursor.svg" default: nil } diff --git a/macos/Sources/Lithe/Views/Editor/SyntaxHighlighting/PropertiesSyntaxHighlightingAdapter.swift b/macos/Sources/Lithe/Views/Editor/SyntaxHighlighting/PropertiesSyntaxHighlightingAdapter.swift index 3f1f0851fb..a3340d5472 100644 --- a/macos/Sources/Lithe/Views/Editor/SyntaxHighlighting/PropertiesSyntaxHighlightingAdapter.swift +++ b/macos/Sources/Lithe/Views/Editor/SyntaxHighlighting/PropertiesSyntaxHighlightingAdapter.swift @@ -1,6 +1,6 @@ import AppKit -/// Highlights Java properties keys, values, continuations, and line comments. +/// Highlights `.properties` keys, values, continuations, and line comments. enum PropertiesSyntaxHighlightingAdapter { private static let numberExpression = expression( #"(? 0, !highlights.isEmpty else { return } - let basePalette = CodeEditorPalette(isDark: isDark, theme: LitheTheme.activeTheme) - let palette = SyntaxHighlightingColorConfiguration.bundled.palette( - formatID: SyntaxHighlightingRegistry.bundled.format( - fileName: nil, - fileExtension: "java" - )?.id, - base: basePalette - ) - let fullRange = NSRange(location: 0, length: storage.length) - let target = NSIntersectionRange(targetRange ?? fullRange, fullRange) - storage.beginEditing() - for highlight in highlights { - guard let role = SyntaxHighlightingColorRole(rawValue: highlight.role) else { continue } - guard highlight.range.location >= 0, highlight.range.location <= storage.length, - highlight.range.length > 0, - highlight.range.length <= storage.length - highlight.range.location else { continue } - let range = NSIntersectionRange(highlight.range, target) - guard range.length > 0 else { continue } - storage.addAttribute(.foregroundColor, value: palette.color(for: role), range: range) - } - storage.endEditing() - } - static func apply( to storage: NSTextStorage, font: NSFont, diff --git a/macos/Sources/Lithe/Views/Git/GitLogView.swift b/macos/Sources/Lithe/Views/Git/GitLogView.swift index caec5b2429..17c0e3b175 100644 --- a/macos/Sources/Lithe/Views/Git/GitLogView.swift +++ b/macos/Sources/Lithe/Views/Git/GitLogView.swift @@ -823,7 +823,7 @@ struct GitLogView: View { content: AnyView( HStack(spacing: LitheTheme.Tree.iconTextGap) { LitheIDEAIcon( - resourcePath: "maven/toolWindowMaven.svg", size: LitheTheme.Tree.iconSize, + resourcePath: "expui/nodes/folder.svg", size: LitheTheme.Tree.iconSize, preservesOriginalColors: true) if let index = gitRepositoryColorIndex(for: repository.repositoryRoot) { Circle().fill(GitRepositoryColor.color(at: index)).frame(width: 8, height: 8) diff --git a/macos/Sources/Lithe/Views/Language/LSPControlCenterView.swift b/macos/Sources/Lithe/Views/Language/LSPControlCenterView.swift index 90196bd43b..75a56d0cd6 100644 --- a/macos/Sources/Lithe/Views/Language/LSPControlCenterView.swift +++ b/macos/Sources/Lithe/Views/Language/LSPControlCenterView.swift @@ -97,12 +97,6 @@ struct LSPControlCenterContent: View { private func languageRow(_ descriptor: LanguageProviderDescriptor) -> some View { let status = serverStatus(for: descriptor) let isEnabled = !model.isLanguageServerDisabledInCurrentWorkspace(providerID: descriptor.id) - let mavenResults: [MavenProfileProjectResult]? = model.languageToolingSessionsIfActive.map { - Array($0.mavenProfileProjectResults.values) - } - let mavenState = descriptor.id == "java" - ? LSPControlCenterPresenter.mavenProfileState(mavenResults ?? []) - : .idle return VStack(alignment: .leading, spacing: 12) { HStack(spacing: 10) { @@ -113,7 +107,7 @@ struct LSPControlCenterContent: View { Text(descriptor.displayName) .font(LitheTheme.uiFont(size: 13, weight: .semibold)) .foregroundStyle(LitheTheme.primaryText) - Text(statusDescription(for: descriptor, status: status)) + Text(statusDescription(status)) .font(LitheTheme.uiFont(size: 11)) .foregroundStyle(status == .error ? LitheTheme.error : LitheTheme.secondaryText) .lineLimit(2) @@ -127,15 +121,6 @@ struct LSPControlCenterContent: View { accessibilityLabel: LocalizedStringKey(settings.language.localizedFormat("native.inline.enableArg1LanguageServer", String(describing: descriptor.displayName))) ) } - if descriptor.id == "java", case .partiallyFailed = mavenState, - let sessions = model.languageToolingSessionsIfActive - { - Button(settings.language.localizedString("native.inline.retryMavenConfiguration")) { - sessions.retryMavenProfiles(providerID: descriptor.id) - } - .buttonStyle(LitheActionButtonStyle()) - } - } .padding(14) .background( @@ -274,23 +259,7 @@ struct LSPControlCenterContent: View { ) } - private func statusDescription( - for descriptor: LanguageProviderDescriptor, - status: LSPServerStatus - ) -> String { - if descriptor.id == "java", let manager = model.languageToolingSessionsIfActive { - let mavenState = LSPControlCenterPresenter.mavenProfileState( - Array(manager.mavenProfileProjectResults.values) - ) - switch mavenState { - case .applying: - return settings.language.localizedString("native.inline.languageServiceConnectedApplyingMavenConfiguration") - case .partiallyFailed(let failed, let total): - return settings.language.localizedFormat("native.inline.someModulesFailedArg1Arg2LanguageServiceRemainsAvailable", String(describing: failed), String(describing: total)) - case .idle, .complete: - break - } - } + private func statusDescription(_ status: LSPServerStatus) -> String { switch status { case .starting: return settings.language.localizedString("native.inline.starting") case .initializing: return settings.language.localizedString("native.inline.initializingProjectIndex") @@ -300,9 +269,6 @@ struct LSPControlCenterContent: View { case .stopped: return settings.language.localizedString("native.inline.startsOnDemandWhenAMatchingFileIsOpened") case .error: - if descriptor.id == "java" { - return settings.language.localizedString("native.inline.failedToStartCheckTheLspRuntimeJdk") - } return settings.language.localizedString("native.inline.failedToStartCheckTheLanguageServerConfiguration") } } diff --git a/macos/Sources/Lithe/Views/Language/JavaReferencesView.swift b/macos/Sources/Lithe/Views/Language/LanguageReferencesView.swift similarity index 100% rename from macos/Sources/Lithe/Views/Language/JavaReferencesView.swift rename to macos/Sources/Lithe/Views/Language/LanguageReferencesView.swift diff --git a/macos/Sources/Lithe/Views/Language/LanguageTestLocalization.swift b/macos/Sources/Lithe/Views/Language/LanguageTestLocalization.swift index f9937d55ee..a71cae7453 100644 --- a/macos/Sources/Lithe/Views/Language/LanguageTestLocalization.swift +++ b/macos/Sources/Lithe/Views/Language/LanguageTestLocalization.swift @@ -22,14 +22,6 @@ struct LanguageTestLocalization { } func error(_ message: String) -> String { - for framework in ["Maven", "JUnit"] { - let prefix = framework + " test run timed out after " - let suffix = " seconds." - guard message.hasPrefix(prefix), message.hasSuffix(suffix) else { continue } - let seconds = String(message.dropFirst(prefix.count).dropLast(suffix.count)) - guard Int(seconds) != nil else { return message } - return String(format: text("%@ test run timed out after %@ seconds."), framework, seconds) - } - return text(message) + text(message) } } diff --git a/macos/Sources/Lithe/Views/Language/LanguageTestsView.swift b/macos/Sources/Lithe/Views/Language/LanguageTestsView.swift index d0ea2454a9..4abddc5236 100644 --- a/macos/Sources/Lithe/Views/Language/LanguageTestsView.swift +++ b/macos/Sources/Lithe/Views/Language/LanguageTestsView.swift @@ -14,7 +14,7 @@ struct LanguageTestsView: View { @AppStorage("lithe.tests.itemListWidth") private var itemListWidth = 250.0 @AppStorage("lithe.tests.itemListCollapsed") private var isItemListCollapsed = false @Environment(\.colorScheme) private var colorScheme - @State private var inspectorTab = "Performance" + @State private var inspectorTab = "Details" @State private var detailsExpanded = false @AppStorage("lithe.tests.detailsWidth") private var detailsWidth = 300.0 @State private var wrapsLines = false @@ -81,7 +81,6 @@ struct LanguageTestsView: View { .background(LitheToolWindowActivityTracker(isActive: $testToolActive)) .onAppear { selectDefaultItemIfNeeded() - syncPerformance() updateResultsAndDurations() } .onChange(of: service.results) { _ in @@ -135,7 +134,7 @@ struct LanguageTestsView: View { private func testRunTab(_ title: String) -> some View { HStack(spacing: 0) { HStack(spacing: 6) { - LitheIDEAIcon(resourcePath: "expui/runConfigurations/junit.svg", size: 16, + LitheIDEAIcon(resourcePath: "expui/run/run.svg", size: 16, fallbackSystemImage: "play", preservesOriginalColors: true) Text(title) .font(LitheTheme.uiFont(size: 13)) @@ -173,18 +172,6 @@ struct LanguageTestsView: View { .help("Stop test run") .disabled(!service.isRunning) - if let item = selectedItem, item.providerID == "java", item.kind != .workspace { - Button(action: UserActionTrace.action("tests.debug", surface: .toolbar) { - model.debugTest(providerID: item.providerID, scope: scope(for: item)) - }) { - LitheIDEAIcon(resourcePath: "expui/run/debug.svg", size: 16, - fallbackSystemImage: "ladybug", preservesOriginalColors: true, usesIDEADisabledAppearance: true) - } - .litheToolbarIconButton() - .help("Debug selected test") - .disabled(service.isRunning || item.fileURL == nil) - } - Button(action: UserActionTrace.action("tests.refresh", surface: .toolbar, model.refreshTests)) { LitheIDEAIcon(resourcePath: "expui/general/refresh.svg", size: 16, fallbackSystemImage: "arrow.clockwise", preservesOriginalColors: true, usesIDEADisabledAppearance: true) @@ -494,10 +481,6 @@ struct LanguageTestsView: View { } } } - .onAppear { updatePerformanceVisibility() } - .onChange(of: detailsExpanded) { _ in updatePerformanceVisibility() } - .onChange(of: inspectorTab) { _ in updatePerformanceVisibility() } - .onDisappear { model.testPerformanceFeature.setVisible(false) } } private func updateResultsAndDurations() { @@ -506,18 +489,10 @@ struct LanguageTestsView: View { testDurations = Self.reportDurations(outcomes) } - private func syncPerformance() { - model.testPerformanceFeature.bind(to: service) - } - - private func updatePerformanceVisibility() { - model.testPerformanceFeature.setVisible(detailsExpanded && inspectorTab == "Performance") - } - private var testInspector: some View { VStack(spacing: 0) { HStack(spacing: 0) { - ForEach(["Performance", "Details"], id: \.self) { tab in + ForEach(["Details"], id: \.self) { tab in Button { inspectorTab = tab } label: { Text(LocalizedStringKey(tab)) .font(LitheTheme.ActionStripe.titleFont) @@ -547,11 +522,7 @@ struct LanguageTestsView: View { .padding(.horizontal, 6) .frame(height: LitheTheme.Metrics.toolbarHeight) LitheToolWindowHeaderDivider() - if inspectorTab == "Performance" { - TestJVMPerformanceView(feature: model.testPerformanceFeature) - } else { - ScrollView { if let item = selectedItem { testDetail(item) } }.litheScrollViewChrome() - } + ScrollView { if let item = selectedItem { testDetail(item) } }.litheScrollViewChrome() } .litheWorkbenchSurface(LitheTheme.editor) } @@ -811,7 +782,6 @@ struct LanguageTestsView: View { private static func iconKind(for providerID: String) -> LitheIconKind? { switch providerID { - case "java": .javaGeneric case "go": .goSource case "python": .pythonSource case "node": .javaScript diff --git a/macos/Sources/Lithe/Views/Language/JavaProblemsView.swift b/macos/Sources/Lithe/Views/Language/ProblemsView.swift similarity index 94% rename from macos/Sources/Lithe/Views/Language/JavaProblemsView.swift rename to macos/Sources/Lithe/Views/Language/ProblemsView.swift index 74a9852366..4115630518 100644 --- a/macos/Sources/Lithe/Views/Language/JavaProblemsView.swift +++ b/macos/Sources/Lithe/Views/Language/ProblemsView.swift @@ -4,18 +4,14 @@ import SwiftUI struct ProblemsView: View { @EnvironmentObject private var model: AppModel @EnvironmentObject private var diagnosticsStore: EditorDiagnosticsStore - private let runnableFileURLs: Set @State private var scope = ProblemsPanelScope.file @State private var toolWindowActive = false @State private var previewEnabled = false @State private var selectedDiagnosticID: String? - @State private var resolvedFileIcons: [URL: LitheIconKind] = [:] @State private var severityFilter = Set(DiagnosticSeverity.allCases) @State private var queryResult = ProblemsQueryResult.empty - init(initialScope: ProblemsPanelScope = .file, previewEnabled: Bool = false, - runnableFileURLs: Set = []) { - self.runnableFileURLs = runnableFileURLs + init(initialScope: ProblemsPanelScope = .file, previewEnabled: Bool = false) { _scope = State(initialValue: initialScope) _previewEnabled = State(initialValue: previewEnabled) } @@ -253,20 +249,8 @@ struct ProblemsView: View { private func fileHeader(_ url: URL, count: Int) -> some View { HStack(spacing: LitheTheme.Tree.iconTextGap) { - LitheIcon(kind: resolvedFileIcons[url] ?? LitheIcons.kind(for: url, isDirectory: false), + LitheIcon(kind: LitheIcons.kind(for: url, isDirectory: false), size: LitheTheme.Tree.iconSize) - .overlay { - if runnableFileURLs.contains(url) || model.runFeatureIfActive?.configurations.contains(where: { - $0.sourcePath == model.relativePath(for: url) && $0.mainClass?.isEmpty == false - }) == true { - LitheIDEAIcon(resourcePath: "expui/nodes/runnableMark.svg", - size: LitheTheme.Tree.iconSize, preservesOriginalColors: true) - } - } - .task(id: url) { - guard let kind = await model.javaIconKind(for: url), !Task.isCancelled else { return } - resolvedFileIcons[url] = kind - } Text(url.lastPathComponent) .truncationMode(.middle) .layoutPriority(1) diff --git a/macos/Sources/Lithe/Views/Language/TestJVMPerformanceView.swift b/macos/Sources/Lithe/Views/Language/TestJVMPerformanceView.swift deleted file mode 100644 index 4e7fcfbba5..0000000000 --- a/macos/Sources/Lithe/Views/Language/TestJVMPerformanceView.swift +++ /dev/null @@ -1,110 +0,0 @@ -import LitheModuleAPI -import SwiftUI - -struct TestJVMPerformanceView: View { - @ObservedObject var feature: TestJVMPerformanceFeatureModel - @Environment(\.locale) private var locale - - var body: some View { - VStack(spacing: 0) { - if feature.usesJVM { - HStack(spacing: 4) { - Button(action: feature.isRecording ? feature.stopRecording : feature.startRecording) { - LitheIDEAIcon(resourcePath: feature.isRecording ? "expui/run/stop.svg" : "expui/profiler/rec.svg", - size: 16, preservesOriginalColors: true, usesIDEADisabledAppearance: true) - } - .buttonStyle(LitheIconButtonStyle(size: LitheTheme.Metrics.toolbarIconButtonSize, disabledOpacity: 1)) - .disabled(feature.isBusy || (!feature.isRecording && !feature.canStartRecording)) - .help(feature.isRecording ? "Stop Recording" : "Start Recording") - .accessibilityLabel(feature.isRecording ? "Stop Recording" : "Start Recording") - Button("Show Results", action: feature.showResults) - .buttonStyle(LitheActionButtonStyle()) - .disabled(feature.recording == nil || feature.isRecording || feature.isBusy) - if feature.isBusy { ProgressView().controlSize(.small) } - Spacer(minLength: 0) - if let recording = feature.recording { - TimelineView(.periodic(from: recording.startedAt, by: 1)) { context in - Text(Duration.seconds(feature.isRecording - ? min(120, max(0, context.date.timeIntervalSince(recording.startedAt))) - : feature.recordingDuration).formatted(.time(pattern: .minuteSecond))) - .font(LitheTheme.uiFont(size: 11, design: .monospaced)) - .foregroundStyle(LitheTheme.secondaryText) - } - } else { - Text("00:00").font(LitheTheme.uiFont(size: 11, design: .monospaced)) - .foregroundStyle(LitheTheme.secondaryText) - } - } - .padding(.horizontal, 10).padding(.vertical, 6) - if !feature.processes.isEmpty { - LitheMenu { - feature.processes.map { process in - LitheContextMenuItem.action("JVM · PID \(process.processID)", - checked: feature.selectedProcess == process, - isEnabled: !feature.isRecording && !feature.isBusy) { feature.select(process) } - } - } label: { - Text(feature.selectedProcess.map { "JVM · PID \($0.processID)" } ?? "Select test JVM") - .font(LitheTheme.uiFont(size: 11)).foregroundStyle(LitheTheme.secondaryText) - } - .buttonStyle(.litheNoPress) - .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 12) - } else if feature.recording == nil { - Text("Waiting for a local test JVM…") - .font(LitheTheme.uiFont(size: 12)).foregroundStyle(LitheTheme.secondaryText) - .frame(maxWidth: .infinity, alignment: .leading).padding(12) - } - } - if let error = feature.errorMessage { - Text(error).font(LitheTheme.uiFont(size: 12)).foregroundStyle(LitheTheme.error) - .frame(maxWidth: .infinity, alignment: .leading).padding(12) - } - if feature.usesJVM, feature.selectedProcess != nil, !feature.isProcessRunning { - Text("Process Terminated").font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.secondaryText).padding(12) - } - TestJVMLiveCharts(feature: feature.metrics, residentMemory: !feature.usesJVM) - } - .background(LitheCenteredPopup(isPresented: Binding( - get: { feature.report != nil }, set: { if !$0 { feature.report = nil } } - ), dialogTitle: L10n.string("Performance Results", locale: locale)) { - VStack(spacing: 10) { - OutputTextView(output: feature.report ?? "", searchRoots: [], fileExists: { _ in false }, - emptyMessage: "No profiling events were recorded.", wrapsLines: false) { _, _, _ in } - HStack { - Spacer() - Button("Close") { feature.report = nil } - .buttonStyle(LitheActionButtonStyle()) - .keyboardShortcut(.cancelAction) - } - } - .padding(.horizontal, 12).padding(.vertical, 10) - .frame(width: 760, height: 500) - .foregroundStyle(LitheTheme.primaryText) - .background(LitheCommitDialogStyle.background) - .environment(\.lithePointingHandCursorEnabled, false) - .onExitCommand { feature.report = nil } - }.frame(width: 0, height: 0).allowsHitTesting(false)) - } -} - -private struct TestJVMLiveCharts: View { - @ObservedObject var feature: DebugPerformanceFeatureModel - let residentMemory: Bool - @State private var hoveredTime: TimeInterval? - - var body: some View { - ScrollView { - VStack(spacing: 0) { - if let error = feature.errorMessage { - Text(LocalizedStringKey(error)).font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.secondaryText).padding(12) - } - DebugPerformanceChart(samples: feature.samples, cpu: true, - residentMemory: residentMemory, hoveredTime: $hoveredTime).frame(height: 160) - DebugPerformanceChart(samples: feature.samples, cpu: false, - residentMemory: residentMemory, hoveredTime: $hoveredTime).frame(height: 160) - } - }.litheScrollViewChrome() - } -} diff --git a/macos/Sources/Lithe/Views/Run/BuildSystemToolWindowView.swift b/macos/Sources/Lithe/Views/Run/BuildSystemToolWindowView.swift index 42f4fa9877..8d7b7554c8 100644 --- a/macos/Sources/Lithe/Views/Run/BuildSystemToolWindowView.swift +++ b/macos/Sources/Lithe/Views/Run/BuildSystemToolWindowView.swift @@ -5,8 +5,8 @@ import SwiftUI // Note: 构建系统插件契约见 .agents/notes/implemented/architecture/2026-10-17-build-system-plugin-contract.md -/// The tool window of one plugin build system, laid out like IDEA's Maven -/// and Gradle windows: a toolbar with run, refresh, and the plugin's toolbar +/// The tool window of one plugin build system, laid out like IDEA's build +/// tool windows: a toolbar with run, refresh, and the plugin's toolbar /// options; a tree with the plugin's tree options, then projects with their /// tasks, tests, and dependencies. Everything comes from Rust Core through /// `BuildSystemsFeatureModel`, and the build system's declaration decides @@ -564,7 +564,7 @@ struct BuildSystemToolWindowView: View { for task in tasks { leafRow( id: nodeID + ":" + task.id, title: task.displayName, help: task.description, - iconPath: "maven/task.svg", entryID: entry.id, project: project, + iconPath: "expui/build/taskGroup.svg", entryID: entry.id, project: project, runnable: .task( BuildTaskRequest(task: task.id, project: BuildSelection(project: project), target: BuildSelection(target: target)), title: Self.title(task.displayName, scope: target.name), needsArguments: task.requiresUserArguments @@ -654,7 +654,7 @@ struct BuildSystemToolWindowView: View { for item in leaves { nodes.append( leafRow( - id: ownerID + ":" + item.id, title: item.title, help: item.help, iconPath: "maven/task.svg", + id: ownerID + ":" + item.id, title: item.title, help: item.help, iconPath: "expui/build/taskGroup.svg", entryID: entryID, project: item.project, runnable: item.runnable )) } diff --git a/macos/Sources/Lithe/Views/Run/JavaLaunchDecisionDialog.swift b/macos/Sources/Lithe/Views/Run/JavaLaunchDecisionDialog.swift deleted file mode 100644 index 5632441bbb..0000000000 --- a/macos/Sources/Lithe/Views/Run/JavaLaunchDecisionDialog.swift +++ /dev/null @@ -1,109 +0,0 @@ -import SwiftUI -import LitheCoreContracts - -struct JavaLaunchDecisionDialog: View { - @EnvironmentObject private var model: AppModel - @EnvironmentObject private var settings: AppSettings - let request: PendingJavaLaunchDecision - - private var report: JavaBuildReport? { request.failure.report } - - var body: some View { - VStack(alignment: .leading, spacing: 14) { - Label( - settings.language.localizedString("native.inline.javaBuildDidNotSucceed"), - systemImage: "exclamationmark.triangle.fill" - ) - .font(LitheTheme.uiFont(.headline)) - .foregroundStyle(LitheTheme.warning) - - Text(explanation) - .font(LitheTheme.uiFont(size: 13)) - Text(request.failure.message) - .font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.secondaryText) - - if let report { - VStack(alignment: .leading, spacing: 5) { - evidenceRow( - settings.language.localizedString("native.inline.markerScope"), - value: report.markerScope == .workspace - ? (settings.language.localizedString("native.inline.workspaceMayIncludeUnrelatedModules")) - : (settings.language.localizedString("native.inline.requestedLaunchTargetAndDependencies")) - ) - evidenceRow( - settings.language.localizedString("native.inline.buildElapsed"), - value: "\(report.elapsedMilliseconds) ms" - ) - } - .padding(10) - .background(LitheTheme.sidebar.opacity(0.65)) - .clipShape(RoundedRectangle(cornerRadius: 6)) - } - - Text(settings.language.localizedString("native.inline.runAnywayContinuesThisLaunchWithTheResolvedOutputAndDoesNotBuildAgain")) - .font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.secondaryText) - - ViewThatFits(in: .horizontal) { - HStack(spacing: LitheTheme.ActionButton.spacing) { actionButtons } - VStack(alignment: .leading, spacing: LitheTheme.ActionButton.spacing) { actionButtons } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - .buttonStyle(LitheActionButtonStyle()) - .padding(20) - .frame(width: 590) - .interactiveDismissDisabled() - } - - @ViewBuilder - private var actionButtons: some View { - Button(settings.language.localizedString("native.inline.runAnyway")) { - model.completeJavaLaunchDecision(.runOnce, requestID: request.id) - } - .buttonStyle(LitheActionButtonStyle(isPrimary: true)) - .accessibilityIdentifier("java-build-run-anyway") - - Button(settings.language.localizedString("native.inline.alwaysContinueInThisWorkspace")) { - model.completeJavaLaunchDecision(.alwaysContinue, requestID: request.id) - } - .accessibilityIdentifier("java-build-always-continue") - - if report?.recovery == .rebuildJavaIndex { - Button(settings.language.localizedString("native.inline.rebuildJavaIndex")) { - model.completeJavaLaunchDecision(.rebuildIndex, requestID: request.id) - } - .accessibilityIdentifier("java-build-rebuild-index") - } - - Button(settings.language.localizedString("native.inline.openLogs")) { - model.completeJavaLaunchDecision(.cancel, requestID: request.id) - model.openLogs() - } - .accessibilityIdentifier("java-build-open-logs") - Button(settings.language.localizedString("native.inline.cancel"), role: .cancel) { - model.completeJavaLaunchDecision(.cancel, requestID: request.id) - } - .keyboardShortcut(.cancelAction) - .accessibilityIdentifier("java-build-cancel") - } - - private var explanation: String { - if request.failure.code == "javaBuildFailed" - || report?.builderFailedEarlier == true { - return settings.language.localizedString("native.inline.theJavaLanguageServiceBuilderFailedInThisSessionSoTheseErrorMarkersMayBeSta") - } - return settings.language.localizedString("native.inline.theJavaLanguageServiceReportedCompilationErrorsWhichMayComeFromDependencies") - } - - private func evidenceRow(_ label: String, value: String) -> some View { - HStack(alignment: .firstTextBaseline, spacing: 8) { - Text(label + ":") - .foregroundStyle(LitheTheme.secondaryText) - Text(value) - .textSelection(.enabled) - } - .font(LitheTheme.uiFont(size: 12)) - } -} diff --git a/macos/Sources/Lithe/Views/Run/JavaRunConfigurationEditorView.swift b/macos/Sources/Lithe/Views/Run/RunConfigurationEditorView.swift similarity index 61% rename from macos/Sources/Lithe/Views/Run/JavaRunConfigurationEditorView.swift rename to macos/Sources/Lithe/Views/Run/RunConfigurationEditorView.swift index 534d1d1731..4d33fc368d 100644 --- a/macos/Sources/Lithe/Views/Run/JavaRunConfigurationEditorView.swift +++ b/macos/Sources/Lithe/Views/Run/RunConfigurationEditorView.swift @@ -21,8 +21,7 @@ struct RunConfigurationEditorView: View { self.configuration = configuration self.onClose = onClose let initialOptions = feature.options(for: configuration) - let projectToolchain = feature.projectToolchain - _options = State(initialValue: Self.configurationOverrides(initialOptions, defaults: projectToolchain)) + _options = State(initialValue: initialOptions) _environmentText = State(initialValue: Self.environmentText(from: initialOptions.environment)) } @@ -34,17 +33,14 @@ struct RunConfigurationEditorView: View { ScrollView { VStack(alignment: .leading, spacing: 10) { saveScopeRow - configurationDetails projectToolchainSection - runtimeSection + if capabilities.contains(.workingDirectory) { + runtimeSection + } argumentsSection - if effectiveCapabilities.contains(.environment) { + if capabilities.contains(.environment) { environmentSection } - if effectiveCapabilities.contains(.mavenSkipTests) - || (effectiveCapabilities.contains(.mavenProfiles) && !feature.mavenProfiles.isEmpty) { - mavenOptionsSection - } } .font(LitheTheme.settingsFont) .frame(maxWidth: 760, alignment: .leading) @@ -106,17 +102,14 @@ struct RunConfigurationEditorView: View { } } - private var effectiveCapabilities: RunConfigurationCapabilities { - configuration.effectiveCapabilities( - for: model.activeDocument?.url, - catalog: model.languageProviderCatalog - ) + private var capabilities: RunConfigurationCapabilities { + configuration.kind.capabilities } private var saveScopeInfo: LocalizedStringKey { saveScope == .local ? "Saved only for this project on this computer in .lithe/run/local.json and excluded from Git." - : "Saved in .lithe/run/configurations.json for the whole team. Local JDK paths are never shared." + : "Saved in .lithe/run/configurations.json for the whole team. Local tool paths are never shared." } private var saveScopeRow: some View { @@ -215,19 +208,6 @@ struct RunConfigurationEditorView: View { } } - @ViewBuilder private var configurationDetails: some View { - if configuration.mainClass != nil || configuration.modulePath != nil { - section(title: "Configuration details") { - if let mainClass = configuration.mainClass { - summaryRow(title: "Main class", value: mainClass, isCode: true) - } - if let modulePath = configuration.modulePath { - summaryRow(title: "Maven module", value: modulePath) - } - } - } - } - private var sourceTitle: String { switch feature.source(for: configuration) { case .generated: L10n.string("Automatically generated") @@ -241,57 +221,6 @@ struct RunConfigurationEditorView: View { title: "Configuration overrides", info: "These overrides affect only this run configuration. Clear a path to inherit the project environment." ) { - if effectiveCapabilities.contains(.javaRuntime) { - pathRow( - title: "JDK Home", - placeholder: "Use project default", - text: stringBinding(\.javaHomePath), - chooseDirectory: { chooseDirectory(for: \.javaHomePath) } - ) - EffectiveRuntimeLabel( - feature: model.runtimeFeature, - choice: { model.runtimeFeature.javaChoice(overridePath: nonEmpty(options.javaHomePath)) }, - kind: .java, - mode: options.javaHomePath.isEmpty ? .inherited : .configured, - requirements: requirementMessages(for: "project-jdk") - ) - } - if configuration.kind.isMavenBacked { - pathRow( - title: "Maven home or executable", - placeholder: "Use project default", - text: stringBinding(\.mavenExecutablePath), - chooseDirectory: { chooseFileOrDirectory(for: \.mavenExecutablePath) }, - chooseHelp: "Choose Maven executable or home" - ) - if let workspaceURL = model.workspaceURL { - EffectiveRuntimeLabel( - feature: model.runtimeFeature, - choice: { - model.runtimeFeature.mavenChoice( - at: workspaceURL, - overridePath: nonEmpty(options.mavenExecutablePath) - ?? model.runtimeFeature.settings.mavenExecutableOverride - ) - }, - kind: .maven, - mode: options.mavenExecutablePath.isEmpty ? .inherited : .configured, - requirements: requirementMessages(for: "project-maven") - ) - } - pathRow( - title: "Maven JDK Home", - placeholder: "Use project default", - text: stringBinding(\.mavenJavaHomePath), - chooseDirectory: { chooseDirectory(for: \.mavenJavaHomePath) } - ) - EffectiveRuntimeLabel( - feature: model.runtimeFeature, - choice: { model.runtimeFeature.mavenJavaChoice(overridePath: effectiveMavenJavaOverride) }, - kind: .java, - mode: options.mavenJavaHomePath.isEmpty ? .inherited : .configured - ) - } pathRow( title: "Working directory", placeholder: "Use project or file directory", @@ -301,39 +230,20 @@ struct RunConfigurationEditorView: View { } } - private func nonEmpty(_ path: String) -> String? { - path.isEmpty ? nil : path - } - - /// Mirrors the Maven toolchain provider: Core fills empty overrides with the - /// project defaults, and an empty Maven JDK then uses this configuration's JDK. - private var effectiveMavenJavaOverride: String? { - let defaults = model.runtimeFeature.settings - let mavenJDK = nonEmpty(options.mavenJavaHomePath) ?? nonEmpty(defaults.mavenJavaHomePath) - return mavenJDK ?? nonEmpty(options.javaHomePath) ?? nonEmpty(defaults.javaHomePath) - } - - private func requirementMessages(for toolchain: String) -> [String] { - feature.configurationDiagnostics.toolchainRequirementMessages( - for: toolchain, - configurationID: configuration.id - ) - } - private var projectToolchainSection: some View { section( title: "Project environment", - info: "Run configurations inherit the project JDK and Maven unless overridden below." + info: "Run configurations inherit the project runtime environment unless overridden below." ) { Button { onClose() - model.showSettings(category: .project) + model.showSettings(category: .toolchainEnvironment) } label: { HStack(spacing: 8) { Image(systemName: "slider.horizontal.3") .font(LitheTheme.uiFont(size: 12)) .foregroundStyle(LitheTheme.accent) - Text("Configure project JDK and Maven…") + Text("Configure runtime environment…") .foregroundStyle(LitheTheme.primaryText) Spacer(minLength: 8) Image(systemName: "chevron.right") @@ -354,18 +264,10 @@ struct RunConfigurationEditorView: View { section(title: "Arguments") { if configuration.buildProvider != nil { ProviderRunOptionsEditor(value: $options.providerRunOptions) - } else if effectiveCapabilities.contains(.javaVMArguments) { - argumentField( - title: "VM options", - placeholder: "-Xmx1g -Dserver.port=8080", - text: stringBinding(\.vmArguments) - ) } argumentField( title: "Program arguments", - placeholder: configuration.kind.isMavenBacked - ? "--spring.profiles.active=dev" - : "Arguments passed to the program", + placeholder: "Arguments passed to the program", text: stringBinding(\.arguments) ) } @@ -377,42 +279,6 @@ struct RunConfigurationEditorView: View { } } - private var mavenOptionsSection: some View { - section(title: "Maven") { - if effectiveCapabilities.contains(.mavenSkipTests) { - HStack(spacing: 12) { - LitheSettingsLabel("Tests") - Spacer(minLength: 16) - LitheSettingsSegmentedControl( - selection: Binding( - get: { options.mavenSkipTests }, - set: { options.mavenSkipTests = $0 } - ), - options: [nil, false, true], - width: 300 - ) { value in - switch value { - case nil: "Project default" - case false: "Run tests" - case true: "Skip tests" - } - } - } - .frame(minHeight: 28) - } - if effectiveCapabilities.contains(.mavenProfiles) { - VStack(alignment: .leading, spacing: 6) { - ForEach(feature.mavenProfiles) { profile in - LitheSettingsCheckbox( - isOn: profileBinding(for: profile), - title: LocalizedStringKey(profile.id) - ) - } - } - } - } - } - private func section( title: String, info: LocalizedStringKey? = nil, @@ -425,30 +291,11 @@ struct RunConfigurationEditorView: View { }, content: content) } - private func summaryRow(title: String, value: String, isCode: Bool = false) -> some View { - HStack(alignment: .firstTextBaseline, spacing: 12) { - Text(LocalizedStringKey(title)) - .foregroundStyle(LitheTheme.secondaryText) - .frame(width: 100, alignment: .leading) - Text(verbatim: value) - .font(isCode - ? LitheTheme.uiFont(size: 11.5, design: .monospaced) - : LitheTheme.settingsFont) - .lineLimit(1) - .truncationMode(.middle) - .textSelection(.enabled) - .help(value) - Spacer(minLength: 0) - } - .font(LitheTheme.settingsFont) - } - private func pathRow( title: String, placeholder: String, text: Binding, - chooseDirectory: @escaping () -> Void, - chooseHelp: String = "Choose directory" + chooseDirectory: @escaping () -> Void ) -> some View { HStack(spacing: 8) { Text(LocalizedStringKey(title)) @@ -459,7 +306,7 @@ struct RunConfigurationEditorView: View { LitheSystemIcon(systemImage: "folder") } .litheIconButton() - .help(chooseHelp) + .help("Choose directory") } .font(LitheTheme.settingsFont) } @@ -485,27 +332,10 @@ struct RunConfigurationEditorView: View { } - private func profileBinding(for profile: MavenProfile) -> Binding { - Binding( - get: { options.activeProfiles.contains(profile.id) }, - set: { enabled in - if enabled { - options.activeProfiles.insert(profile.id) - } else { - options.activeProfiles.remove(profile.id) - } - } - ) - } - private func chooseDirectory(for keyPath: WritableKeyPath) { presentPathPicker(.directory(keyPath)) } - private func chooseFileOrDirectory(for keyPath: WritableKeyPath) { - presentPathPicker(.fileOrDirectory(keyPath)) - } - private func presentPathPicker(_ picker: PathPicker) { activePathPicker = picker @@ -542,12 +372,7 @@ struct RunConfigurationEditorView: View { return nil } var scopedOptions = options - for keyPath in [ - \.javaHomePath, - \.mavenExecutablePath, - \.mavenJavaHomePath, - \.workingDirectoryPath - ] as [WritableKeyPath] { + for keyPath in [\.workingDirectoryPath] as [WritableKeyPath] { let value = scopedOptions[keyPath: keyPath].trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty else { continue } guard let relativePath = projectRelativePath(value, root: projectURL) else { @@ -572,37 +397,20 @@ struct RunConfigurationEditorView: View { private enum PathPicker { case directory(WritableKeyPath) - case fileOrDirectory(WritableKeyPath) - var allowedContentTypes: [UTType] { - switch self { - case .directory: [.folder] - case .fileOrDirectory: [.item] - } - } + var allowedContentTypes: [UTType] { [.folder] } func assign( _ path: String, options: inout RunOptions ) { switch self { - case .directory(let keyPath), .fileOrDirectory(let keyPath): + case .directory(let keyPath): options[keyPath: keyPath] = path } } } - private static func configurationOverrides( - _ options: RunOptions, - defaults: ProjectToolchainSelection - ) -> RunOptions { - var overrides = options - if overrides.javaHomePath == defaults.javaHomePath { overrides.javaHomePath = "" } - if overrides.mavenExecutablePath == defaults.mavenExecutablePath { overrides.mavenExecutablePath = "" } - if overrides.mavenJavaHomePath == defaults.mavenJavaHomePath { overrides.mavenJavaHomePath = "" } - return overrides - } - private static func environmentText(from environment: [String: String]) -> String { environment.keys.sorted().map { key in key + "=" + (environment[key] ?? "") @@ -621,5 +429,3 @@ struct RunConfigurationEditorView: View { return result } } - -typealias JavaRunConfigurationEditorView = RunConfigurationEditorView diff --git a/macos/Sources/Lithe/Views/Run/RunConfigurationIcon.swift b/macos/Sources/Lithe/Views/Run/RunConfigurationIcon.swift index e91b0d5c96..b3b18adc7d 100644 --- a/macos/Sources/Lithe/Views/Run/RunConfigurationIcon.swift +++ b/macos/Sources/Lithe/Views/Run/RunConfigurationIcon.swift @@ -3,7 +3,9 @@ import SwiftUI /// Presents the ecosystem behind a run configuration instead of using one /// generic process symbol for every language. The imported SVG catalog keeps /// these marks crisp in compact IDE rows and preserves their recognizable -/// brand colors in both light and dark appearances. +/// brand colors in both light and dark appearances. Providers the host does +/// not know fall back to the kind's system symbol; plugin-owned marks arrive +/// through the plugin's icon resources, not through host branches. struct RunConfigurationIcon: View { let kind: RunConfigurationKind var size: CGFloat = 16 @@ -11,12 +13,7 @@ struct RunConfigurationIcon: View { var body: some View { Group { - if case .javaMain = kind, !isGroup { - ZStack { - LitheIDEAIcon(resourcePath: "expui/nodes/class.svg", size: size, preservesOriginalColors: true) - LitheIDEAIcon(resourcePath: "expui/nodes/runnableMark.svg", size: size, preservesOriginalColors: true) - } - } else if let resourcePath { + if let resourcePath { LitheIDEAIcon(resourcePath: resourcePath, size: size, preservesOriginalColors: true) } else if let iconKind = Self.iconKind(for: kind) { @@ -33,10 +30,6 @@ struct RunConfigurationIcon: View { private var resourcePath: String? { switch kind { - case .javaMain: - return "expui/fileTypes/java.svg" - case .mavenFramework, .mavenModule: - return "java/expui/maven.svg" case .process(let provider) where ["make", "just", "procfile"].contains(provider.split(separator: ".").first.map(String.init) ?? ""): return isGroup ? "expui/build/taskGroup.svg" : "expui/fileTypes/shell.svg" default: @@ -48,10 +41,6 @@ struct RunConfigurationIcon: View { switch kind { case .currentFile: return .plainText - case .mavenFramework, .javaMain: - return .javaGeneric - case .mavenModule: - return .maven case .process(let provider): switch provider.split(separator: ".").first.map(String.init) { case "npm", "node", "bun", "deno": @@ -64,12 +53,6 @@ struct RunConfigurationIcon: View { return .goSource case "cargo", "rust": return .rustSource - case "maven": - return .maven - case "gradle": - return .gradle - case "java": - return .javaGeneric case "kotlin": return .kotlinSource case "swift": diff --git a/macos/Sources/Lithe/Views/Run/RunView.swift b/macos/Sources/Lithe/Views/Run/RunView.swift index 07890b6121..7c5be2f9f1 100644 --- a/macos/Sources/Lithe/Views/Run/RunView.swift +++ b/macos/Sources/Lithe/Views/Run/RunView.swift @@ -33,20 +33,9 @@ struct RunView: View { || feature.isRunning || feature.lastExitCode != nil || feature.hasPluginRun { runToolbar } - if feature.serviceUpdateSessionID == selectedModuleSession?.id, - feature.serviceUpdateExecutionID == selectedModuleSession?.executionID, - selectedModuleSession?.isRunning == true, - let message = feature.serviceUpdateMessage { - Text(message).font(.caption).textSelection(.enabled).padding(8) - } - if feature.hasBuildProviderRun, let error = feature.configurationSaveError { LitheBanner(status: .warning, layout: .editor) { Text(verbatim: error).textSelection(.enabled) } } - if !feature.portConflicts.isEmpty { - portConflictBanner - } - if let notice = configurationNotice { configurationNoticeBanner(notice) } @@ -208,29 +197,11 @@ struct RunView: View { } if let diagnostic = feature.configurationDiagnostics.first(where: { $0.code == "toolchainVendorMismatch" }) { return ( - runText("Different JDK vendor selected"), + runText("Different toolchain vendor selected"), diagnostic.message, "info.circle.fill" ) } - switch feature.javaDiscoveryStatus { - case .loading: - return ( - runText("Waiting for the Java language service"), - runText("Java entries appear after the Java language service lists runnable classes."), - "clock.fill" - ) - case .stale: - return ( - runText("Refreshing Java entries"), - runText("Showing the previous Java entries while the Java language service prepares the project."), - "clock.fill" - ) - case .failed(let message): - return (runText("Java entries could not be refreshed"), message, "exclamationmark.triangle.fill") - case .idle, .ready: - break - } switch feature.generationState { case .projectNotReady: return ( @@ -272,7 +243,7 @@ struct RunView: View { Button("Identify Again", action: UserActionTrace.action("run.configurations.generate") { feature.requestRunConfigurationGeneration() }) } else if feature.blockingToolchainDiagnostic != nil { - Button("Project · JDK & Maven") { model.showSettings(category: .project) } + Button("Runtime Environment") { model.showSettings(category: .toolchainEnvironment) } } } } @@ -450,17 +421,6 @@ struct RunView: View { .help("Stop run") .accessibilityLabel("Stop run") - if let session = selectedModuleSession, feature.canUpdateService(session) { - Button(action: UserActionTrace.action("run.service.update") { model.updateRunningService(session) }) { - Image(systemName: "bolt.fill") - } - .buttonStyle(runActionButtonStyle) - .padding(.horizontal, 2) - .disabled(feature.updatingServiceExecutionID != nil) - .help("Compile changes for Spring Boot DevTools. The application context may restart.") - .accessibilityLabel("Update running service") - } - Button(action: UserActionTrace.action("run.configurations.generate") { feature.requestRunConfigurationGeneration() }) { @@ -523,14 +483,6 @@ struct RunView: View { !runnableConfigurations.isEmpty } - private var portConflictBanner: some View { - LitheBanner(status: .warning, layout: .editor) { - ForEach(feature.portConflicts) { conflict in - Text(conflict.title).lineLimit(2) - } - } - } - private var selectedModuleSession: RunSession? { guard let selectedSessionID else { return nil } return feature.moduleSessions.first(where: { $0.id == selectedSessionID }) @@ -910,10 +862,6 @@ struct RunView: View { session: RunSession? ) -> some View { let options = feature.options(for: configuration) - let capabilities = configuration.effectiveCapabilities( - for: model.activeDocument?.url, - catalog: model.languageProviderCatalog - ) let workingDirectory = options.workingDirectoryPath.isEmpty ? (model.workspaceURL?.standardizedFileURL.path ?? runText("Project root")) : options.workingDirectoryPath @@ -953,45 +901,13 @@ struct RunView: View { configurationLinkRow("Address", url: serviceURL) } - if let modulePath = nonEmpty(configuration.modulePath) { - configurationDetailRow("Module", value: modulePath, monospaced: true) - } - if let mainClass = nonEmpty(configuration.mainClass) { - configurationDetailRow("Main class", value: mainClass, monospaced: true) - } - if capabilities.contains(.javaRuntime), - let javaHome = nonEmpty(options.javaHomePath) { - configurationDetailRow("JDK home", value: javaHome, monospaced: true) - } - if configuration.kind.isMavenBacked, - let mavenExecutable = nonEmpty(options.mavenExecutablePath) { - configurationDetailRow("Maven", value: mavenExecutable, monospaced: true) - } - if configuration.kind.isMavenBacked, - let mavenJavaHome = nonEmpty(options.mavenJavaHomePath) { - configurationDetailRow("Maven JDK", value: mavenJavaHome, monospaced: true) - } - if capabilities.contains(.javaVMArguments), - let vmArguments = nonEmpty(options.vmArguments) { - configurationDetailRow("VM arguments", value: vmArguments, monospaced: true) - } if let programArguments = nonEmpty(options.programArguments) { configurationDetailRow("Program arguments", value: programArguments, monospaced: true) } - if capabilities.contains(.mavenProfiles), !options.activeProfiles.isEmpty { - configurationDetailRow( - "Active profiles", - value: options.activeProfiles.sorted().joined(separator: ", "), - monospaced: true - ) - } } Group { - if (!capabilities.contains(.javaRuntime) || options.javaHomePath.isEmpty), - (!capabilities.contains(.javaVMArguments) || options.vmArguments.isEmpty), - options.programArguments.isEmpty, - (!capabilities.contains(.mavenProfiles) || options.activeProfiles.isEmpty) { + if options.programArguments.isEmpty { configurationDetailRow("Options", value: runText("Default options")) } diff --git a/macos/Sources/Lithe/Views/Run/SpringEndpointsView.swift b/macos/Sources/Lithe/Views/Run/SpringEndpointsView.swift deleted file mode 100644 index 9edfe23af9..0000000000 --- a/macos/Sources/Lithe/Views/Run/SpringEndpointsView.swift +++ /dev/null @@ -1,86 +0,0 @@ -import LitheModuleAPI -import SwiftUI - -struct SpringEndpointsView: View { - @EnvironmentObject private var model: AppModel - @State private var query = "" - - var body: some View { - VStack(spacing: 0) { - LitheToolWindowHeader( - title: "Spring Endpoints", - subtitle: L10n.string("\(filteredEndpoints.count) routes"), - onMinimize: { model.workbenchFeature.setVisibility(.spring, isVisible: false) } - ) - HStack(spacing: 7) { - Image(systemName: "magnifyingglass") - .foregroundStyle(LitheTheme.secondaryText) - TextField("Filter route, controller, or method", text: $query) - .textFieldStyle(.plain) - } - .padding(.horizontal, 10) - .frame(height: 34) - .litheWorkbenchSurface(LitheTheme.editor) - if model.isIndexingSpring { - ProgressView("Indexing Spring project…") - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else if filteredEndpoints.isEmpty { - Text("No Spring MVC endpoints found") - .font(LitheTheme.uiFont) - .foregroundStyle(LitheTheme.secondaryText) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else { - ScrollView(.vertical) { - LazyVStack(spacing: 1) { - ForEach(filteredEndpoints) { endpoint in - Button { model.openSpringEndpoint(endpoint) } label: { - HStack(spacing: 9) { - Text(endpoint.httpMethods.joined(separator: ",")) - .font(LitheTheme.uiFont(size: 10.5, weight: .bold, design: .monospaced)) - .foregroundStyle(methodColor(endpoint.httpMethods.first)) - .frame(width: 58, alignment: .leading) - Text(endpoint.route) - .font(LitheTheme.uiFont(size: 12.5, weight: .medium, design: .monospaced)) - Text("\(endpoint.controller).\(endpoint.method)") - .font(LitheTheme.uiFont(size: 10.5)) - .foregroundStyle(LitheTheme.secondaryText) - Spacer() - Text(model.relativePath(for: endpoint.url)) - .font(LitheTheme.uiFont(size: 10.5)) - .foregroundStyle(LitheTheme.secondaryText) - .lineLimit(1) - } - .foregroundStyle(LitheTheme.primaryText) - .padding(.horizontal, 10) - .frame(maxWidth: .infinity, minHeight: 30) - .contentShape(Rectangle()) - } - .buttonStyle(.litheNoPress) - .lithePointer() - } - } - .padding(6) - } - } - } - .litheWorkbenchSurface(LitheTheme.sidebar) - } - - private var filteredEndpoints: [SpringEndpoint] { - let value = query.trimmingCharacters(in: .whitespacesAndNewlines) - guard !value.isEmpty else { return model.springEndpoints } - return model.springEndpoints.filter { - [$0.route, $0.controller, $0.method, $0.httpMethods.joined(separator: " ")] - .contains { $0.localizedCaseInsensitiveContains(value) } - } - } - - private func methodColor(_ method: String?) -> Color { - switch method { - case "GET": LitheTheme.success - case "POST": LitheTheme.accent - case "DELETE": LitheTheme.error - default: LitheTheme.warning - } - } -} diff --git a/macos/Sources/Lithe/Views/Search/SearchEverywhereView.swift b/macos/Sources/Lithe/Views/Search/SearchEverywhereView.swift index 0491b93137..3112e38979 100644 --- a/macos/Sources/Lithe/Views/Search/SearchEverywhereView.swift +++ b/macos/Sources/Lithe/Views/Search/SearchEverywhereView.swift @@ -637,7 +637,7 @@ private struct SearchEverywhereContent: View { return parent } - /// 结果归属的 Maven 模块 artifactID;非 Maven 项目或匹配不到时回退到顶层目录名。 + /// 结果归属的构建系统项目名;匹配不到时回退到顶层目录名。 private func moduleLabel(for url: URL) -> String { moduleLabel(url) } @@ -693,9 +693,9 @@ private struct SearchEverywhereContent: View { case .file, .content: return LitheIcons.kind(for: result.url, isDirectory: false) case .type: - return .javaClass + return .typeSymbol case .symbol: - return .javaGeneric + return .symbol } } diff --git a/macos/Sources/Lithe/Views/Workbench/LitheConsoleStyle.swift b/macos/Sources/Lithe/Views/Workbench/LitheConsoleStyle.swift index 16b35a6542..9e5c65f5d4 100644 --- a/macos/Sources/Lithe/Views/Workbench/LitheConsoleStyle.swift +++ b/macos/Sources/Lithe/Views/Workbench/LitheConsoleStyle.swift @@ -61,70 +61,20 @@ struct ConsoleFoldRegion: Equatable { } /// Presentation ranges only: source logs, ANSI attributes and DAP output are unchanged. -/// Rules adapted from Apache-2.0 Community StackTraceFolding and JavaPlugin.xml. +/// Frame shape rules adapted from Apache-2.0 Community StackTraceFolding. Which frames count +/// as "internal" is runtime-specific, so callers inject those prefixes (plugins own them); +/// with none, only long stacks fold. enum ConsoleStackTraceFolding { - static let internalPatterns: [String] = [ - "at java.awt.EventDispatchThread", - "at java.awt.Window.dispatchEventImpl(", - "at java.awt.Container.dispatchEventImpl(", - "at java.awt.LightweightDispatcher.", - "at java.awt.Component.dispatchEvent(", - "at java.awt.event.InvocationEvent.dispatch(", - "at java.awt.EventQueue", - "at java.awt.Component.dispatchEventImpl(", - "at java.awt.Container.processEvent(", - "at javax.swing.JComponent.processMouseEvent(", - "at javax.swing.plaf.basic.BasicMenuItemUI", - "at java.awt.Component.processMouseEvent(", - "at javax.swing.AbstractButton.doClick(", - "at java.awt.Component.processEvent(", - "at java.awt.Container.dispatchEventImpl(", - "at javax.swing.DefaultButtonModel.fireActionPerformed(", - "at javax.swing.DefaultButtonModel.setPressed(", - "at javax.swing.AbstractButton.fireActionPerformed(", - "at javax.swing.AbstractButton$Handler.actionPerformed(", - "at java.security.AccessControlContext$1.doIntersectionPrivilege(", - "at java.awt.EventQueue.dispatchEventImpl(", - "at java.security.AccessController.doPrivileged(Native Method)", - "at java.security.ProtectionDomain$1.doIntersectionPrivilege(", - "at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(", - "at com.jgoodies.binding.beans.ExtendedPropertyChangeSupport.firePropertyChange0(", - "at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(", - "at java.util.ArrayList$ArrayListSpliterator", - "at java.util.stream.ReferencePipeline", - "at java.util.Spliterators$", - "at java.util.stream.AbstractPipeline.evaluate(", - "at java.util.stream.AbstractPipeline.copyInto(", - "at java.util.stream.AbstractPipeline.wrapAndCopyInto(", - "at java.util.stream.DistinctOps", - "at java.util.stream.FindOps", - "at java.util.stream.ForEachOps", - "at java.util.stream.MatchOps", - "at java.util.stream.ReduceOps", - "at java.util.stream.SliceOps", - "at java.util.stream.WhileOps", - "at java.util.concurrent.Executors$", - "at java.util.concurrent.ThreadPoolExecutor", - "at java.util.concurrent.FutureTask.", - "at java.util.concurrent.CompletableFuture$AsyncSupply.run(", - "java.lang.Thread.run(", - "java.lang.reflect.Method.invoke(", - "java.lang.reflect.Constructor.newInstance(", - "at java.base/jdk.internal", - "at java.security.AccessController.doPrivileged(", - "at sun.reflect.", - "at java.rmi.", - "at sun.rmi.", - "at com.sun.proxy.$Proxy", - "at com.intellij.rt.execution." - ] - private static let internalExpression = try! NSRegularExpression( - pattern: internalPatterns.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") - ) + /// Compiles literal frame prefixes into one alternation; nil means nothing is internal. + static func internalExpression(for patterns: [String]) -> NSRegularExpression? { + let escaped = patterns.filter { !$0.isEmpty }.map(NSRegularExpression.escapedPattern(for:)) + guard !escaped.isEmpty else { return nil } + return try? NSRegularExpression(pattern: escaped.joined(separator: "|")) + } private static let enclosedMore = try! NSRegularExpression(pattern: #"^\t\.\.\. \d+ more$"#) private static let modulePrefix = try! NSRegularExpression(pattern: #"(?<=at )[^\s/]+/"#) - static func regions(in text: String) -> [ConsoleFoldRegion] { + static func regions(in text: String, internalExpression: NSRegularExpression? = nil) -> [ConsoleFoldRegion] { let source = text as NSString var frames = 0 var longStart: Int? @@ -173,10 +123,11 @@ enum ConsoleStackTraceFolding { } else { finishLong(); frames = 0 } let normalized = line.contains("/") ? modulePrefix.stringByReplacingMatches(in: line, range: NSRange(location: 0, length: (line as NSString).length), withTemplate: "") : line - let matchesInternal = internalExpression.firstMatch(in: line, - range: NSRange(location: 0, length: (line as NSString).length)) != nil - || (normalized != line && internalExpression.firstMatch(in: normalized, - range: NSRange(location: 0, length: (normalized as NSString).length)) != nil) + let matchesInternal = internalExpression.map { expression in + expression.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) != nil + || (normalized != line && expression.firstMatch(in: normalized, + range: NSRange(location: 0, length: (normalized as NSString).length)) != nil) + } ?? false if matchesInternal { if internalStart == nil { internalStart = range.location @@ -199,16 +150,22 @@ extension NSAttributedString.Key { @MainActor final class ConsoleFoldPresentation { + /// Runtime-specific "internal" frame prefixes; empty by default. + let internalExpression: NSRegularExpression? var regions: [ConsoleFoldRegion] = [] var expanded: Set = [] var fontSize = LitheConsoleStyle.defaultFontSize var inputSessionID: UUID? var inputDraft = "" + init(internalPatterns: [String] = []) { + internalExpression = ConsoleStackTraceFolding.internalExpression(for: internalPatterns) + } + func project(_ raw: NSAttributedString, dark: Bool, fontSize: CGFloat) -> NSAttributedString { // ponytail: Debug caps output at 400k characters and publishes at 10Hz. This // bounded scan preserves nested rules; above that ceiling index dirty lines. - regions = ConsoleStackTraceFolding.regions(in: raw.string) + regions = ConsoleStackTraceFolding.regions(in: raw.string, internalExpression: internalExpression) expanded.formIntersection(Set(regions.map(\.id))) let result = NSMutableAttributedString() var offset = 0 diff --git a/macos/Sources/Lithe/Views/Workbench/OutputTextView.swift b/macos/Sources/Lithe/Views/Workbench/OutputTextView.swift index 531bcf37c3..2acc3fd765 100644 --- a/macos/Sources/Lithe/Views/Workbench/OutputTextView.swift +++ b/macos/Sources/Lithe/Views/Workbench/OutputTextView.swift @@ -6,7 +6,7 @@ import SwiftUI /// 构建/运行输出的统一渲染视图: /// - 支持 ANSI 转义序列着色(复用终端渲染器) -/// - Maven 错误行 `[ERROR] path:[line,col]` 与 Java 堆栈行 `at x.y.Foo.bar(Foo.java:42)` 可点击跳转源码 +/// - 通用源码位置 `path:line[:col]`、`path:[line,col]`(可带 `[ERROR]`/`[WARNING]` 级别前缀)可点击跳转;工具专属格式由插件 `outputLinks` 提供 /// - 智能滚动:用户上翻后不强制拉底,并显示 "Jump to latest" 按钮 /// - 右上角一键复制全部输出 /// - 可选自动换行:调用方提供切换回调时,右键菜单附带「自动换行」勾选项 @@ -239,7 +239,7 @@ struct OutputTextView: View { // MARK: - 错误位置匹配 private struct OutputLocation { - enum Kind { case error, warning, stack } + enum Kind { case error, warning, location } let range: Range let kind: Kind let url: URL @@ -247,12 +247,14 @@ struct OutputTextView: View { let column: Int? } - private static let mavenExpression = try! NSRegularExpression( - pattern: #"\[(ERROR|WARNING)\]\s+(.+?):\[(\d+)(?:,(\d+))?\]"# - ) - - private static let stackExpression = try! NSRegularExpression( - pattern: #"\bat\s+([\w.$]+(?:\$[\w$]+)?)\.([\w$<>]+)\(([\w$]+\.java):(\d+)\)"# + /// Tool-neutral source location: a path with an extension followed by + /// `:line`, `:line:col` or `:[line,col]`, optionally preceded by an + /// `[ERROR]` / `[WARNING]` level word. The path must exist under one of the + /// command's roots before the token becomes a link, so hosts and ports or + /// version strings never turn into links. Tool-specific formats (stack + /// frames, test ids) are contributed by plugins through `outputLinks`. + private static let locationExpression = try! NSRegularExpression( + pattern: #"(?:\[(ERROR|WARNING)\]\s+)?((?:[A-Za-z]:)?(?:/|\.{1,2}/|~/)?[^\s:\[\]()'"<>|]*?\.\w+):\[?(\d+)(?:[,:](\d+))?\]?(?=[\s:,)\]]|$)"# ) private static func matchLocations( @@ -268,48 +270,29 @@ struct OutputTextView: View { guard let line = substring, !line.isEmpty else { return } let lineNSRange = NSRange(line.startIndex.. Bool - ) -> URL? { - let outerClassName = className.split(separator: "$", maxSplits: 1).first.map(String.init) ?? className - let relativePath = outerClassName.replacingOccurrences(of: ".", with: "/") + ".java" - let candidates = ["src/main/java/", "src/test/java/"].map { $0 + relativePath } - var matches: [URL] = [] - for root in searchRoots { - for candidate in candidates { - let url = root.appendingPathComponent(candidate).standardizedFileURL - if fileExists(url) { - if !requiresUniqueMatch { return url } - if !matches.contains(where: { $0.path == url.path }) { matches.append(url) } - } - } - } - return requiresUniqueMatch && matches.count == 1 ? matches[0] : nil - } - // MARK: - 链接编码 static func locationURL(path: String, line: Int, column: Int?) -> URL { @@ -1280,7 +1240,7 @@ final class OutputSoftWrapMenuItem: NSMenuItem { // MARK: - ANSI 渲染器 /// 将含 ANSI 转义序列的文本解析为「干净文本 + 样式段」,再组装成 NSAttributedString。 -/// 终端、Maven 构建输出与运行输出共用。 +/// 终端、构建输出与运行输出共用。 enum ANSIOutputRenderer { struct Style { var foreground: NSColor diff --git a/macos/Sources/Lithe/Views/Workbench/ProjectPreparationStatusView.swift b/macos/Sources/Lithe/Views/Workbench/ProjectPreparationStatusView.swift deleted file mode 100644 index 1f2795f6de..0000000000 --- a/macos/Sources/Lithe/Views/Workbench/ProjectPreparationStatusView.swift +++ /dev/null @@ -1,86 +0,0 @@ -import SwiftUI -import LitheCoreContracts - -/// Both placements read the same session-owned snapshot; opening details starts no work. -struct ProjectPreparationStatusView: View { - @EnvironmentObject private var model: AppModel - var compact = false - - var body: some View { - ProjectPreparationContent(feature: model.languageToolingFeature, compact: compact) - } -} - -private struct ProjectPreparationContent: View { - @EnvironmentObject private var model: AppModel - @EnvironmentObject private var settings: AppSettings - @ObservedObject var feature: LanguageToolingFeatureModel - var compact: Bool - @State private var showingDetails = false - - private var snapshot: ProjectPreparationSnapshot? { - feature.projectPreparation - } - - var body: some View { - if let snapshot, snapshot.phase != "stopped", !compact || snapshot.status != "ready" { - Button { showingDetails.toggle() } label: { - HStack(spacing: 6) { - if snapshot.status == "loading" { - ProgressView().controlSize(.mini) - } else { - Image(systemName: snapshot.status == "failed" ? "exclamationmark.triangle" : "checkmark.circle") - } - Text(snapshot.status == "failed" - ? (settings.language.localizedString("native.inline.javaProjectPreparationFailed")) - : phaseTitle(snapshot.phase)) - .lineLimit(1) - } - .font(LitheTheme.uiFont(size: 11)) - } - .buttonStyle(.litheNoPress) - .help(settings.language.localizedString("native.inline.viewProjectPreparationDetails")) - .litheDropdown(isPresented: $showingDetails, opensUpward: !compact) { - VStack(alignment: .leading, spacing: 12) { - Text(phaseTitle(snapshot.phase)).font(LitheTheme.uiFont(.headline)) - ForEach(["starting", "importing", "configuring", "building"], id: \.self) { phase in - Text((snapshot.phase == phase ? "› " : "· ") + phaseTitle(phase)) - .font(LitheTheme.uiFont(size: 12, weight: snapshot.phase == phase ? .semibold : .regular)) - } - Text(settings.language.localizedString("native.inline.theJavaWorkspaceMustFinishPreparationBeforeLaunchBackgroundIndexingDoesNotB")) - .font(LitheTheme.uiFont(size: 12)) - Button(settings.language.localizedString("native.inline.languageServiceSettingsAndRetry")) { - showingDetails = false - model.showSettings(category: .lsp) - } - Button(settings.language.localizedString("native.inline.viewLogs")) { - showingDetails = false - model.openLogs() - } - if model.alwaysContinuesAfterJavaBuildFailures { - Divider() - Text(settings.language.localizedString("native.inline.javaLaunchesAlwaysContinueAfterBuildFailuresInThisWorkspace")) - .font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.secondaryText) - Button(settings.language.localizedString("native.inline.askAgain")) { - model.askAgainForJavaBuildFailures() - } - } - } - .padding(16) - .frame(width: 330) - } - } - } - - private func phaseTitle(_ phase: String) -> String { - switch phase { - case "starting": settings.language.localizedString("native.inline.startingJavaService") - case "importing": settings.language.localizedString("native.inline.importingJavaProjectAndDependencies") - case "configuring": settings.language.localizedString("native.inline.synchronizingJavaProjectConfiguration") - case "building": settings.language.localizedString("native.inline.buildingJavaProject") - case "ready": settings.language.localizedString("native.inline.javaProjectModelReady") - default: settings.language.localizedString("native.inline.javaProjectPreparationStopped") - } - } -} diff --git a/macos/Sources/Lithe/Views/Workbench/WorkbenchModuleUIComposition.swift b/macos/Sources/Lithe/Views/Workbench/WorkbenchModuleUIComposition.swift index 0dbd74709f..2f327b32ef 100644 --- a/macos/Sources/Lithe/Views/Workbench/WorkbenchModuleUIComposition.swift +++ b/macos/Sources/Lithe/Views/Workbench/WorkbenchModuleUIComposition.swift @@ -284,8 +284,7 @@ enum WorkbenchModuleUIComposition { contributions: LanguageIntelligenceModule.moduleContributions, actions: [ .init(id: "language.problems.toggle", perform: { $0.toggleProblems() }), - .init(id: "language.references.toggle", perform: { $0.workbenchFeature.toggleVisibility(.references) }), - .init(id: "language.spring.toggle", perform: { $0.toggleSpringEndpoints() }) + .init(id: "language.references.toggle", perform: { $0.workbenchFeature.toggleVisibility(.references) }) ], renderers: [ .init( @@ -298,11 +297,7 @@ enum WorkbenchModuleUIComposition { .init(id: "language.references", ideaAssetPath: "expui/toolwindows/toolWindowComponents@20x20.svg", isVisible: { $0.workbenchFeature.isVisible(.references) }, isSelected: { $0.workbenchFeature.isVisible(.references) }, - content: { _ in AnyView(LanguageReferencesView()) }), - .init(id: "language.spring", ideaAssetPath: "expui/toolwindows/toolWindowComponents@20x20.svg", - isVisible: { $0.workbenchFeature.isVisible(.spring) }, - isSelected: { $0.workbenchFeature.isVisible(.spring) }, - content: { _ in AnyView(SpringEndpointsView()) }) + content: { _ in AnyView(LanguageReferencesView()) }) ] ) diff --git a/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift b/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift index 5530f4065a..1012c94a49 100644 --- a/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift +++ b/macos/Sources/Lithe/Views/Workbench/WorkbenchView.swift @@ -284,7 +284,7 @@ struct WorkbenchView: View { @StateObject private var toolContentStore = WorkbenchToolContentStore() @State private var sidebarWidth = CGFloat(WorkbenchLayout.defaultSidebarWidth) @State private var rightSidebarWidth: CGFloat = 380 - @State private var mavenPaneWidth = CGFloat(WorkbenchLayout.defaultMavenPaneWidth) + @State private var rightPaneWidth = CGFloat(WorkbenchLayout.defaultRightPaneWidth) @State private var branchPopupHeight: CGFloat? @State private var branchPopupWidth = LitheDropdownMetrics.branchMinimumWidth @State private var topPaneHeight: CGFloat? @@ -371,12 +371,6 @@ struct WorkbenchView: View { .frame(minWidth: 640, minHeight: 420) } } - .sheet(item: Binding( - get: { model.pendingJavaLaunchDecision }, - set: { _ in } - )) { request in - JavaLaunchDecisionDialog(request: request) - } .onAppear { updateWorkbenchBackgroundImage(model.workbenchBackgroundFeature.imageData) model.setNotificationsApplicationActive(NSApplication.shared.isActive) @@ -1108,7 +1102,7 @@ struct WorkbenchView: View { HStack(spacing: 6) { if let target = model.activeTestTarget { LitheIDEAIcon( - resourcePath: "expui/runConfigurations/junit.svg", + resourcePath: "expui/nodes/testGroup.svg", size: LitheTheme.MainToolbar.iconSize, preservesOriginalColors: true ) @@ -1161,7 +1155,7 @@ struct WorkbenchView: View { } label: { HStack(spacing: 10) { LitheIDEAIcon( - resourcePath: "expui/runConfigurations/junit.svg", + resourcePath: "expui/nodes/testGroup.svg", size: 16, preservesOriginalColors: true ) @@ -1369,7 +1363,7 @@ struct WorkbenchView: View { let state = moduleUIRegistry.state(for: entry, model: model) return state.isVisible && state.isEnabled } - return (tool == .references || tool == .spring) && model.workbenchFeature.isVisible(tool) + return tool == .references && model.workbenchFeature.isVisible(tool) } private func isToolEntryVisible(_ tool: WorkbenchFeatureModel.ToolWindow) -> Bool { @@ -1508,7 +1502,6 @@ struct WorkbenchView: View { @ViewBuilder private func toolContent(_ tool: WorkbenchFeatureModel.ToolWindow?) -> some View { if tool == .references { LanguageReferencesView().modifier(LitheToolWindowHoverRegion()) } - else if tool == .spring { SpringEndpointsView().modifier(LitheToolWindowHoverRegion()) } else if let tool, let entry = contribution(for: tool), let renderer = moduleUIRegistry.renderer(for: entry) { let content = ModuleToolContent(rendererID: renderer.id, contentIdentity: renderer.contentIdentity(model), content: renderer.content(model)).equatable() @@ -1549,7 +1542,7 @@ struct WorkbenchView: View { guard let runFeature = model.runFeatureIfActive else { return } let intent = runFeature.generationIntent Task { - // Through the app model so JDT is asked which classes can be launched. + // Through the app model so the language backend is asked which entry points can be launched. await model.generateRunConfigurations() guard runFeature.configurationStatus == .ready else { return } switch intent { @@ -1595,7 +1588,7 @@ struct WorkbenchView: View { WorkbenchWorkspaceSplitView( sidebarWidth: sidebarWidth, isSidebarVisible: hasVisibleTool(on: .left), - rightToolWidth: mavenPaneWidth, + rightToolWidth: rightPaneWidth, isRightToolVisible: hasVisibleTool(on: .right), topPaneHeight: topPaneHeight, isBottomToolVisible: isBottomToolVisible, @@ -1612,7 +1605,7 @@ struct WorkbenchView: View { model.closeGitLog() }, onRightToolWidthCommitted: { width in - mavenPaneWidth = width + rightPaneWidth = width saveLayout(sidebarWidth: sidebarWidth, topPaneHeight: topPaneHeight) } ), @@ -1639,7 +1632,7 @@ struct WorkbenchView: View { bottomTool: { dockContent(on: .bottom) }, rightTool: { dockContent(on: .right) } ) - .background(ToolWindowWorkspaceAnchor(drag: toolWindowDrag, sideWidths: [.left: sidebarWidth, .right: mavenPaneWidth])) + .background(ToolWindowWorkspaceAnchor(drag: toolWindowDrag, sideWidths: [.left: sidebarWidth, .right: rightPaneWidth])) } @ViewBuilder @@ -1647,7 +1640,7 @@ struct WorkbenchView: View { if toolWindowDrag.source != nil, toolWindowDrag.targetsEditor { GeometryReader { geometry in let leading = hasVisibleTool(on: .left) ? min(sidebarWidth, geometry.size.width) : 0 - let trailing = hasVisibleTool(on: .right) ? min(mavenPaneWidth, geometry.size.width - leading) : 0 + let trailing = hasVisibleTool(on: .right) ? min(rightPaneWidth, geometry.size.width - leading) : 0 let height = isBottomToolVisible ? min(topPaneHeight ?? geometry.size.height * WorkbenchLayout.defaultTopPaneFraction, geometry.size.height) : geometry.size.height Rectangle().fill(LitheTheme.toolWindowDropArea) @@ -1828,7 +1821,6 @@ struct WorkbenchView: View { .help(LocalizedStringKey( model.activeDocument?.isReadOnly == true ? "Read-only document" : "Save" )) - ProjectPreparationStatusView(compact: true) PluginServerStatusView() LanguageServerStatusView() MemoryUsageStatusView() @@ -1840,7 +1832,6 @@ struct WorkbenchView: View { private var compactStatusItems: some View { HStack(spacing: 10) { EditorCaretPositionLabel(chrome: model.editorChrome) { model.showGoToLine() } - ProjectPreparationStatusView(compact: true) PluginServerStatusView() LanguageServerStatusView() MemoryUsageStatusView() @@ -1871,7 +1862,7 @@ struct WorkbenchView: View { let layout = model.loadWorkbenchLayout(for: workspaceURL) sidebarWidth = CGFloat(layout.sidebarWidth) topPaneHeight = layout.topPaneHeight.map { CGFloat($0) } - mavenPaneWidth = CGFloat(layout.mavenPaneWidth ?? WorkbenchLayout.defaultMavenPaneWidth) + rightPaneWidth = CGFloat(layout.rightPaneWidth ?? WorkbenchLayout.defaultRightPaneWidth) branchPopupHeight = layout.branchPopupHeight.map { CGFloat($0) } branchPopupWidth = layout.branchPopupWidth.map { CGFloat($0) } ?? LitheDropdownMetrics.branchMinimumWidth didRestoreLayout = true @@ -1886,7 +1877,7 @@ struct WorkbenchView: View { WorkbenchLayout( sidebarWidth: Double(sidebarWidth), topPaneHeight: topPaneHeight.map(Double.init), - mavenPaneWidth: Double(mavenPaneWidth), + rightPaneWidth: Double(rightPaneWidth), branchPopupWidth: Double(branchPopupWidth), branchPopupHeight: branchPopupHeight.map { Double($0) } ), diff --git a/macos/Sources/Lithe/Views/Workspace/NewProjectView.swift b/macos/Sources/Lithe/Views/Workspace/NewProjectView.swift index 6f2f5a71b4..e73aa2ca18 100644 --- a/macos/Sources/Lithe/Views/Workspace/NewProjectView.swift +++ b/macos/Sources/Lithe/Views/Workspace/NewProjectView.swift @@ -60,20 +60,6 @@ struct NewProjectView: View { get: { if case .generator(let id) = feature.selection { return "generator:" + id }; return "empty" }, set: { _ in })) Rectangle().fill(LitheTheme.divider).frame(height: 1) - if feature.isJavaSupportMissing { - Button { - feature.openMarketplace(searching: "Java Support") - } label: { - Text("Install Java Support for Java, Maven and Spring templates…") - .font(LitheTheme.uiFont(size: 12)) - .foregroundStyle(LitheTheme.link) - .frame(maxWidth: .infinity, alignment: .leading) - } - .buttonStyle(.litheNoPress) - .lithePointer() - .padding(.horizontal, 14) - .padding(.vertical, 10) - } Button { feature.openMarketplace(searching: "") } label: { @@ -354,32 +340,38 @@ struct NewProjectView: View { } } + /// Picks one installation of the tool definition the field's `runtime` + /// names, from the same lookup tool fields use. When none is found the + /// field says why, as a tool field does. @ViewBuilder private func runtimeControl(_ field: ProjectGeneratorField) -> some View { - if feature.javaRuntimes.isEmpty, feature.hasLoadedJavaRuntimes { - Text(LocalizedStringKey("No JDK was found. Install a JDK, then reopen this window.")) - .foregroundStyle(LitheTheme.secondaryText) - } else if feature.javaRuntimes.isEmpty { - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text(LocalizedStringKey("Looking for installed JDKs…")) - .foregroundStyle(LitheTheme.secondaryText) - } - } else { + let installations = feature.runtimeInstallations(for: field) + if let error = feature.toolListingError(for: field) { + toolListingFailure(error) + } else if !installations.isEmpty { LitheSettingsSelect( selection: Binding( get: { feature.selectedRuntimeHome(for: field) }, set: { feature.selectRuntime(home: $0, for: field) } ), - options: feature.javaRuntimes.map(\.homePath), + options: installations.map(\.home), width: 420, accessibilityLabel: field.title, title: { home in - guard let runtime = feature.javaRuntimes.first(where: { $0.homePath == home }) else { return home } - return "\(runtime.displayName) — \((home as NSString).abbreviatingWithTildeInPath)" + guard let installation = installations.first(where: { $0.home == home }) else { return home } + return "\(installation.version) — \((home as NSString).abbreviatingWithTildeInPath)" }, localizesTitles: false, - searchPrompt: feature.javaRuntimes.count > 8 ? "Search JDKs" : nil + searchPrompt: installations.count > 8 ? "Search" : nil ) + } else if feature.isListingTools { + HStack(spacing: 6) { + ProgressView().controlSize(.small) + Text(LocalizedStringKey("Looking for installed tools…")) + .foregroundStyle(LitheTheme.secondaryText) + } + } else { + Text(LocalizedStringKey("No installation of this tool was found.")) + .foregroundStyle(LitheTheme.secondaryText) } } diff --git a/macos/Sources/Lithe/Views/Workspace/ProjectSidebarView.swift b/macos/Sources/Lithe/Views/Workspace/ProjectSidebarView.swift index 197fd19627..f9c0631eb1 100644 --- a/macos/Sources/Lithe/Views/Workspace/ProjectSidebarView.swift +++ b/macos/Sources/Lithe/Views/Workspace/ProjectSidebarView.swift @@ -625,9 +625,6 @@ private final class ProjectTreeActions: @unchecked Sendable { nonisolated func showProjectLocalHistory() { Task { @MainActor in self.model.showProjectLocalHistory() } } - func javaIconKind(_ url: URL) async -> LitheIconKind? { - await model.javaIconKind(for: url) - } func fileIcon(_ url: URL, suggested: LitheIconKind) async -> (kind: LitheIconKind, isExecutable: Bool) { await WorkspaceFileIconResolver.resolve( for: url, @@ -714,7 +711,6 @@ private struct FileNodeRow: View { let visibleRows: [ProjectTreeSelection.VisibleRow] @Binding var expandedDirectoryPaths: Set @Binding var contextMenuPath: String? - @State private var resolvedJavaIconKind: LitheIconKind? @State private var resolvedFileIconKind: LitheIconKind? @State private var isExecutableFile = false @@ -840,7 +836,7 @@ private struct FileNodeRow: View { } label: { HStack(spacing: LitheTheme.Tree.iconTextGap) { Color.clear.frame(width: LitheTheme.Tree.disclosureSlot) - LitheIcon(kind: resolvedJavaIconKind ?? resolvedFileIconKind ?? node.iconKind, size: LitheTheme.Metrics.treeIconSize) + LitheIcon(kind: resolvedFileIconKind ?? node.iconKind, size: LitheTheme.Metrics.treeIconSize) .frame(width: LitheTheme.Metrics.treeIconSize) Text(node.name) .font(LitheTheme.uiFont(size: LitheTheme.Metrics.treeFontSize)) @@ -882,9 +878,6 @@ private struct FileNodeRow: View { let resolved = await actions.fileIcon(node.url, suggested: node.iconKind) resolvedFileIconKind = resolved.kind isExecutableFile = resolved.isExecutable && resolved.kind == .binary - if node.url.pathExtension.lowercased() == "java" { - resolvedJavaIconKind = await actions.javaIconKind(node.url) - } } } @@ -1049,18 +1042,6 @@ private struct FileNodeRow: View { if let currentDirectoryMark { return LitheIcons.kind(for: currentDirectoryMark) } - var ancestor = node.url.deletingLastPathComponent() - let rootPath = projectRootURL.standardizedFileURL.path - while ancestor.standardizedFileURL.path.hasPrefix(rootPath) { - if let mark = directoryMarks[relativeDirectoryPath(for: ancestor)] { - if mark == .sources, LitheIcons.isValidPackageName(node.url.lastPathComponent) { - return .packageFolder - } - break - } - guard ancestor.standardizedFileURL.path != rootPath else { break } - ancestor.deleteLastPathComponent() - } return node.iconKind } diff --git a/macos/Sources/Lithe/Views/Workspace/ProjectTreeSelection.swift b/macos/Sources/Lithe/Views/Workspace/ProjectTreeSelection.swift index 941ec3980d..6609e2fc50 100644 --- a/macos/Sources/Lithe/Views/Workspace/ProjectTreeSelection.swift +++ b/macos/Sources/Lithe/Views/Workspace/ProjectTreeSelection.swift @@ -67,8 +67,9 @@ struct ProjectTreeSelection: Equatable { if focusedPath.map({ !paths.contains($0) }) ?? true { focusedPath = first } } - /// Uses tree structure instead of path components because compacted Java - /// packages display below an ancestor that is not their filesystem parent. + /// Uses tree structure instead of path components because compacted + /// single-child directory chains display below an ancestor that is not + /// their filesystem parent. private static func displayedParent(of path: String, in node: FileNode) -> FileNode? { for child in node.children ?? [] { if child.url.path == path { return node } diff --git a/macos/Sources/LitheCoreContracts/Debug/DebugAdapterContracts.swift b/macos/Sources/LitheCoreContracts/Debug/DebugAdapterContracts.swift index 1f75c6bb2c..be125df4c9 100644 --- a/macos/Sources/LitheCoreContracts/Debug/DebugAdapterContracts.swift +++ b/macos/Sources/LitheCoreContracts/Debug/DebugAdapterContracts.swift @@ -79,6 +79,9 @@ public struct DebugLaunchConfiguration: Codable, Equatable, Sendable { public let name: String public let request: DebugRequestKind public let arguments: [String: ToolingJSONValue] + /// User-edited stepping policy. Absent means the adapter's declared + /// defaults; Core only forwards either to adapters that declared + /// `features.stepFilters`. public let steppingFilters: DebugSteppingFilters? /// Host-selected Registry identity (`pluginID/adapterID` for plugins). /// A missing identity selects by source file; an unavailable explicit @@ -215,6 +218,8 @@ public protocol DebugAdapterRunInTerminalSession: AnyObject { var onRunInTerminalRequest: DebugRunInTerminalRequestHandler? { get set } } +/// Portable stepping policy for adapters that declared `features.stepFilters`. +/// Pattern syntax belongs to the adapter; the host only stores and forwards it. public struct DebugSteppingFilters: Codable, Equatable, Sendable { public let classNameFilters: [String] public let skipSynthetics: Bool @@ -235,111 +240,20 @@ public struct DebugSteppingFilters: Codable, Equatable, Sendable { self.skipConstructors = skipConstructors self.hideFilteredStackFrames = hideFilteredStackFrames } -} - -/// JDT LS-owned identity for one Java launch target. `mainClass` may include -/// the JPMS module prefix (`module/name.Type`) required by Java Debug Server. -public struct JavaDebugLaunchTarget: Codable, Hashable, Sendable { - public let mainClass: String - public let projectName: String? - public let modulePaths: [String] - public let classPaths: [String] - /// The host completed the current build provider preparation before JDT launch resolution. - public let buildPrepared: Bool - - public init(mainClass: String, projectName: String?, modulePaths: [String] = [], classPaths: [String] = []) { - self.init(mainClass: mainClass, projectName: projectName, modulePaths: modulePaths, classPaths: classPaths, buildPrepared: false) - } - - public init( - mainClass: String, - projectName: String?, - modulePaths: [String] = [], - classPaths: [String] = [], - buildPrepared: Bool - ) { - self.mainClass = mainClass - self.projectName = projectName - self.modulePaths = modulePaths - self.classPaths = classPaths - self.buildPrepared = buildPrepared - } - - private enum CodingKeys: String, CodingKey { case mainClass, projectName, modulePaths, classPaths, buildPrepared } - - /// Core's shared Java preparation has no host resource receipt. An absent - /// receipt must retain Maven preparation rather than bypass it. - public init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - self.init(mainClass: try values.decode(String.self, forKey: .mainClass), - projectName: try values.decodeIfPresent(String.self, forKey: .projectName), - modulePaths: try values.decode([String].self, forKey: .modulePaths), - classPaths: try values.decode([String].self, forKey: .classPaths), - buildPrepared: try values.decodeIfPresent(Bool.self, forKey: .buildPrepared) ?? false) - } - -} - -/// Java test runner family reported by the JDT LS Java Test extension. -public enum JavaTestDebugFramework: String, Codable, Equatable, Sendable { - case junit - case testng -} -/// JDT LS-owned metadata required to launch one Java test selection through DAP. -public struct JavaTestDebugLaunchTarget: Equatable, Sendable { - public let fileURL: URL - public let name: String - public let framework: JavaTestDebugFramework - public let workingDirectory: String - public let mainClass: String - public let projectName: String? - public let classPaths: [String] - public let modulePaths: [String] - public let vmArguments: [String] - public let programArguments: [String] - public let testNGRunnerPath: String? - public let testNGTestNames: [String] - - public init( - fileURL: URL, - name: String, - framework: JavaTestDebugFramework, - workingDirectory: String, - mainClass: String, - projectName: String?, - classPaths: [String], - modulePaths: [String], - vmArguments: [String], - programArguments: [String], - testNGRunnerPath: String? = nil, - testNGTestNames: [String] = [] - ) { - self.fileURL = fileURL.standardizedFileURL - self.name = name - self.framework = framework - self.workingDirectory = workingDirectory - self.mainClass = mainClass - self.projectName = projectName - self.classPaths = classPaths - self.modulePaths = modulePaths - self.vmArguments = vmArguments - self.programArguments = programArguments - self.testNGRunnerPath = testNGRunnerPath - self.testNGTestNames = testNGTestNames + /// The policy an adapter declared in `defaults.stepFilters`, or no + /// filtering when it declared none. + public init(declared: DebugAdapterDeclaredBehavior.DefaultStepFilters?) { + self.init( + classNameFilters: declared?.classNameFilters ?? [], + skipSynthetics: declared?.skipSynthetics ?? false, + skipStaticInitializers: declared?.skipStaticInitializers ?? false, + skipConstructors: declared?.skipConstructors ?? false, + hideFilteredStackFrames: declared?.hideFilteredStackFrames ?? false + ) } } -/// Resolves a Java test selection through the active language-service project model. -@MainActor -public protocol JavaTestDebugLaunchTargetResolving: AnyObject { - func resolveJavaTestDebugLaunchTarget( - fileURL: URL, - testIdentifier: String?, - rootURL: URL - ) async throws -> JavaTestDebugLaunchTarget -} - /// One exact editor replacement using zero-based, document-relative UTF-16 offsets. public struct DebugSourceEdit: Codable, Equatable, Sendable { public let startUTF16Offset: Int diff --git a/macos/Sources/LitheCoreContracts/Debug/DebugProtocolCore.swift b/macos/Sources/LitheCoreContracts/Debug/DebugProtocolCore.swift index e5372b31a2..ca6cfe7b71 100644 --- a/macos/Sources/LitheCoreContracts/Debug/DebugProtocolCore.swift +++ b/macos/Sources/LitheCoreContracts/Debug/DebugProtocolCore.swift @@ -413,7 +413,7 @@ public struct DebugCoreExceptionDetails: Decodable, Equatable, Sendable { public let innerExceptions: [DebugCoreExceptionDetails] } -/// Focused policy boundary for portable debugger stepping defaults and validation. +/// Focused policy boundary for portable debugger stepping validation. @MainActor public protocol DebugSteppingFilterResolving: Sendable { func resolveDebugSteppingFilters( @@ -422,15 +422,6 @@ public protocol DebugSteppingFilterResolving: Sendable { ) throws -> DebugSteppingFilters } -/// Focused shared-Core boundary for deterministic Java test launch arguments. -@MainActor -public protocol JavaTestDebugLaunchResolving: Sendable { - func resolveJavaTestDebugLaunch( - target: JavaTestDebugLaunchTarget, - resultPort: UInt16 - ) throws -> DebugLaunchConfiguration -} - /// Focused shared-Core boundary for moving source breakpoints with editor text. @MainActor public protocol DebugBreakpointRelocating: Sendable { diff --git a/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift b/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift index 153b9a8235..c5b34b61b5 100644 --- a/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift @@ -481,7 +481,7 @@ package struct BuildInvocation: Equatable, Sendable { package struct RuntimeDependency: Equatable, Sendable { package let id: String package let displayName: String? - /// `java`, `node`, and `go` follow the user's runtime settings. + /// Host-managed runtimes follow the user's runtime settings. package let hostManaged: Bool package let minimumVersion: String? package let executables: [Executable] @@ -575,17 +575,6 @@ package protocol BuildToolResolving: AnyObject { workspaceURL: URL, checkVersion: @escaping @Sendable (_ runtime: String?, _ output: String) throws -> BuildVersionCheck ) async throws -> ResolvedBuildTool - /// Passive discovery for project import; must never probe or execute tools. - func languageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) -> URL? - /// Host discovery may require I/O; project import still never runs code. - func prepareLanguageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) async throws -> URL? -} - -package extension BuildToolResolving { - func languageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) -> URL? { nil } - func prepareLanguageImportExecutable(_ invocation: BuildInvocation, workspaceURL: URL) async throws -> URL? { - languageImportExecutable(invocation, workspaceURL: workspaceURL) - } } // MARK: Options @@ -1202,27 +1191,6 @@ package struct BuildSyncState: Equatable, Sendable, Decodable { } } -// MARK: Language import - -/// The result of `build.languageImport`; the kind is a language-server -/// capability, independent of the plugin and build-system identifiers. -package enum BuildLanguageImport: Equatable, Sendable, Decodable { - case maven(MavenLaunchContext) - case gradle(JavaGradleImportConfiguration) - - package init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - switch try values.decode(String.self, forKey: .kind) { - case "maven": self = .maven(try values.decode(MavenLaunchContext.self, forKey: .mavenContext)) - case "gradle": self = .gradle(try values.decode(JavaGradleImportConfiguration.self, forKey: .javaGradle)) - default: - throw DecodingError.dataCorruptedError(forKey: .kind, in: values, debugDescription: "Unknown language import kind") - } - } - - private enum CodingKeys: String, CodingKey { case kind, mavenContext, javaGradle } -} - // MARK: Core operations /// The `build.*` commands of Rust Core. Implementations throw @@ -1241,13 +1209,6 @@ package protocol BuildSystemPlanning: Sendable { instanceOptions: [String: [String: [String: ToolingJSONValue]]], instanceDefaults: [String: [String: ToolingJSONValue]] ) throws -> BuildDetection - func languageImport( - _ target: BuildSystemTarget, - workspaceURL: URL, - root: String, - options: [String: ToolingJSONValue], - executableURL: URL? - ) throws -> BuildLanguageImport? func invocationPlan( _ target: BuildSystemTarget, root: String, settings: [String: ToolingJSONValue] ) throws -> BuildInvocation diff --git a/macos/Sources/LitheCoreContracts/Execution/ExecutionContracts.swift b/macos/Sources/LitheCoreContracts/Execution/ExecutionContracts.swift index 12cb25f020..e36f96e993 100644 --- a/macos/Sources/LitheCoreContracts/Execution/ExecutionContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/ExecutionContracts.swift @@ -1,50 +1,9 @@ import Foundation package struct RunOptions: Codable, Hashable, Sendable { - package struct JavaCapability: Codable, Hashable, Sendable { - package var homePath = "" - package var mavenExecutablePath = "" - package var mavenJavaHomePath = "" - package var vmArguments = "" - package var activeMavenProfiles: Set = [] - package var skipTests: Bool? - - private enum CodingKeys: String, CodingKey { - case homePath, mavenExecutablePath, mavenJavaHomePath, vmArguments, activeMavenProfiles - case skipTests - } - - package init( - homePath: String = "", - mavenExecutablePath: String = "", - mavenJavaHomePath: String = "", - vmArguments: String = "", - activeMavenProfiles: Set = [], - skipTests: Bool? = nil - ) { - self.homePath = homePath - self.mavenExecutablePath = mavenExecutablePath - self.mavenJavaHomePath = mavenJavaHomePath - self.vmArguments = vmArguments - self.activeMavenProfiles = activeMavenProfiles - self.skipTests = skipTests - } - - package init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - homePath = try container.decodeIfPresent(String.self, forKey: .homePath) ?? "" - mavenExecutablePath = try container.decodeIfPresent(String.self, forKey: .mavenExecutablePath) ?? "" - mavenJavaHomePath = try container.decodeIfPresent(String.self, forKey: .mavenJavaHomePath) ?? "" - vmArguments = try container.decodeIfPresent(String.self, forKey: .vmArguments) ?? "" - activeMavenProfiles = try container.decodeIfPresent(Set.self, forKey: .activeMavenProfiles) ?? [] - skipTests = try container.decodeIfPresent(Bool.self, forKey: .skipTests) - } - } - package var workingDirectoryPath = "" package var arguments = "" package var environment: [String: String] = [:] - package var java = JavaCapability() package var providerRunOptions: BuildProviderRunOptions? /// Reset emits explicit clears for inherited per-Run tools. Omitting this @@ -55,14 +14,8 @@ package struct RunOptions: Codable, Hashable, Sendable { } package init( - javaHomePath: String = "", workingDirectoryPath: String = "", - vmArguments: String = "", programArguments: String = "", - activeProfiles: Set = [], - mavenSkipTests: Bool? = nil, - mavenExecutablePath: String = "", - mavenJavaHomePath: String = "", environment: [String: String] = [:], providerRunOptions: BuildProviderRunOptions? = nil ) { @@ -70,48 +23,16 @@ package struct RunOptions: Codable, Hashable, Sendable { arguments = programArguments self.environment = environment self.providerRunOptions = providerRunOptions - java = JavaCapability( - homePath: javaHomePath, - mavenExecutablePath: mavenExecutablePath, - mavenJavaHomePath: mavenJavaHomePath, - vmArguments: vmArguments, - activeMavenProfiles: activeProfiles, - skipTests: mavenSkipTests - ) } - package var javaHomePath: String { - get { java.homePath } - set { java.homePath = newValue } - } - package var vmArguments: String { - get { java.vmArguments } - set { java.vmArguments = newValue } - } - package var mavenExecutablePath: String { - get { java.mavenExecutablePath } - set { java.mavenExecutablePath = newValue } - } - package var mavenJavaHomePath: String { - get { java.mavenJavaHomePath } - set { java.mavenJavaHomePath = newValue } - } package var programArguments: String { get { arguments } set { arguments = newValue } } - package var activeProfiles: Set { - get { java.activeMavenProfiles } - set { java.activeMavenProfiles = newValue } - } - package var mavenSkipTests: Bool? { - get { java.skipTests } - set { java.skipTests = newValue } - } private enum CodingKeys: String, CodingKey { - case workingDirectoryPath, arguments, environment, java, providerRunOptions - case javaHomePath, vmArguments, programArguments, activeProfiles + case workingDirectoryPath, arguments, environment, providerRunOptions + case programArguments } package init(from decoder: Decoder) throws { @@ -122,11 +43,6 @@ package struct RunOptions: Codable, Hashable, Sendable { ?? "" environment = try container.decodeIfPresent([String: String].self, forKey: .environment) ?? [:] providerRunOptions = try container.decodeIfPresent(BuildProviderRunOptions.self, forKey: .providerRunOptions) - java = try container.decodeIfPresent(JavaCapability.self, forKey: .java) ?? JavaCapability( - homePath: try container.decodeIfPresent(String.self, forKey: .javaHomePath) ?? "", - vmArguments: try container.decodeIfPresent(String.self, forKey: .vmArguments) ?? "", - activeMavenProfiles: try container.decodeIfPresent(Set.self, forKey: .activeProfiles) ?? [] - ) } package func encode(to encoder: Encoder) throws { @@ -134,7 +50,6 @@ package struct RunOptions: Codable, Hashable, Sendable { try container.encode(workingDirectoryPath, forKey: .workingDirectoryPath) try container.encode(arguments, forKey: .arguments) try container.encode(environment, forKey: .environment) - try container.encode(java, forKey: .java) try container.encodeIfPresent(providerRunOptions, forKey: .providerRunOptions) } } @@ -145,69 +60,21 @@ package struct SharedLaunchPlan: Sendable { case command(String) } - /// One compiler or generator invocation the host must run to completion, - /// in order, before the main process. Standalone Java uses this to compile - /// with `javac` so JDK 8 can then launch by class name (JEP 330's - /// single-file source launcher is JDK 11+ only). - package struct PreLaunchStep: Sendable { - package let executable: Executable - /// Sibling tool to run from the toolchain's `bin` directory, e.g. - /// `"javac"`. Nil means the toolchain's default launcher. - package let tool: String? - package let arguments: [String] - /// Classpath entries the host joins with the platform separator and - /// prepends as `-cp` before this step's arguments. - package let classpath: [String] - /// Project-relative run directory for this step, and the root the host - /// resolves its toolchain from. Nil inherits the plan's - /// `workingDirectory`, which may be a user override this step must not - /// resolve or run from (for example a Maven resource step that has to - /// find the project wrapper next to its reactor POM). - package let workingDirectory: String? - - package init( - executable: Executable, - tool: String? = nil, - arguments: [String], - classpath: [String] = [], - workingDirectory: String? = nil - ) { - self.executable = executable - self.tool = tool - self.arguments = arguments - self.classpath = classpath - self.workingDirectory = workingDirectory - } - } - package let executable: Executable package let arguments: [String] package let workingDirectory: String package var environment: [String: String] - /// Ordered compile/generate steps to run before the main process. - package let preLaunchSteps: [PreLaunchStep] - /// Run classpath entries the host joins with the platform separator (`:` on - /// POSIX, `;` on Windows) and prepends as `-cp` before `arguments`. - package let classpath: [String] - /// Java module-path entries joined by the host with its platform separator. - package let modulepath: [String] package init( executable: Executable, arguments: [String], workingDirectory: String, - environment: [String: String] = [:], - preLaunchSteps: [PreLaunchStep] = [], - classpath: [String] = [], - modulepath: [String] = [] + environment: [String: String] = [:] ) { self.executable = executable self.arguments = arguments self.workingDirectory = workingDirectory self.environment = environment - self.preLaunchSteps = preLaunchSteps - self.classpath = classpath - self.modulepath = modulepath } package var toolchainID: String? { @@ -253,69 +120,6 @@ package extension RunExecutableResolving { func prepare(_ plan: SharedLaunchPlan, projectURL: URL, options: RunOptions) async throws -> ResolvedRunExecutable? { nil } func refreshCandidates(projectURL _: URL) async {} func candidates(projectURL _: URL) -> [ProjectToolchainCandidate] { [] } - - /// Resolves a pre-launch step by reusing the main executable resolution and, - /// when the step names a sibling `tool` (e.g. `javac`), swapping the launcher - /// for that tool in the same `bin` directory. The step inherits the plan's - /// environment and, unless it declares its own `workingDirectory`, the - /// plan's working directory. - func resolve( - step: SharedLaunchPlan.PreLaunchStep, - plan: SharedLaunchPlan, - projectURL: URL, - options: RunOptions - ) throws -> ResolvedRunExecutable { - let syntheticPlan = SharedLaunchPlan( - executable: step.executable, - arguments: step.arguments, - workingDirectory: step.workingDirectory ?? plan.workingDirectory, - environment: plan.environment - ) - let resolved = try resolve(syntheticPlan, projectURL: projectURL, options: options) - guard let tool = step.tool, !tool.isEmpty else { return resolved } - let toolURL = resolved.executableURL - .deletingLastPathComponent() - .appendingPathComponent(tool) - return ResolvedRunExecutable( - executableURL: toolURL, - environment: resolved.environment - ) - } -} - -@MainActor -package protocol RunRuntimePort: AnyObject { - func setActiveServiceJavaHomePath(_ path: String) - func javaHomeURL(overridePath: String?) -> URL? - func mavenJavaHomeURL(overridePath: String?) -> URL? - func runConfigurationToolchainCandidates( - projectRoot: URL?, - javaHomeOverride: String?, - mavenExecutableOverride: String? - ) -> [ProjectToolchainCandidate] - /// Project restoration awaits version probes instead of running them on the UI executor. - func loadRunConfigurationToolchainCandidates( - projectRoot: URL?, - javaHomeOverride: String?, - mavenExecutableOverride: String? - ) async throws -> [ProjectToolchainCandidate] - /// Applies workspace and subproject JDK/Maven defaults when a run - /// configuration does not set its own explicit toolchain paths. - func overlayProjectRuntime( - onto options: RunOptions, - modulePath: String?, - workingDirectory: String? - ) -> RunOptions -} - -package extension RunRuntimePort { - func overlayProjectRuntime( - onto options: RunOptions, - modulePath _: String?, - workingDirectory _: String? - ) -> RunOptions { - options - } } package protocol RunFileAccess: Sendable { @@ -331,10 +135,6 @@ package protocol RunPreferenceStore: AnyObject { func setString(_ value: String, forKey key: String) } -package protocol RunServerPortParsing: Sendable { - func serverPort(content: String, fileExtension: String) -> Int? -} - package enum LanguageTestItemKind: String, Equatable, Sendable { case workspace, file, testCase } diff --git a/macos/Sources/LitheCoreContracts/Execution/LanguageRunContracts.swift b/macos/Sources/LitheCoreContracts/Execution/LanguageRunContracts.swift index 16e83a9d24..48282262f0 100644 --- a/macos/Sources/LitheCoreContracts/Execution/LanguageRunContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/LanguageRunContracts.swift @@ -152,7 +152,6 @@ package struct LanguageRunProviderRegistry: Sendable { Self(providers: catalog.descriptors .filter { $0.capabilities.contains(.run) - && $0.id != "java" && $0.id != "go" } .map(StandardLanguageRunProvider.init)) diff --git a/macos/Sources/LitheCoreContracts/Execution/MavenContracts.swift b/macos/Sources/LitheCoreContracts/Execution/MavenContracts.swift deleted file mode 100644 index 2d2646e22e..0000000000 --- a/macos/Sources/LitheCoreContracts/Execution/MavenContracts.swift +++ /dev/null @@ -1,159 +0,0 @@ -import Foundation - -package struct MavenProfile: Identifiable, Hashable, Sendable { - package let id: String - package let isActiveByDefault: Bool - - package init(id: String, isActiveByDefault: Bool) { - self.id = id - self.isActiveByDefault = isActiveByDefault - } -} - -package enum MavenLifecyclePhase: String, CaseIterable, Identifiable, Sendable { - case clean, validate, compile, test - case packagePhase = "package" - case verify, install, site, deploy - - package var id: String { rawValue } - package var title: String { rawValue } - package var systemImage: String { - switch self { - case .clean: "trash" - case .validate: "checkmark.seal" - case .compile: "hammer" - case .test: "checkmark.circle" - case .packagePhase: "shippingbox" - case .verify: "checkmark.shield" - case .install: "arrow.down.to.line" - case .site: "globe" - case .deploy: "arrow.up.to.line" - } - } -} - -package enum MavenIssueSeverity: String, Sendable { - case error, warning, info - - package var systemImage: String { - switch self { - case .error: "xmark.octagon.fill" - case .warning: "exclamationmark.triangle.fill" - case .info: "info.circle.fill" - } - } -} - -package struct MavenBuildIssue: Identifiable, Hashable, Sendable { - package let id: String - package let fileURL: URL? - package let line: Int? - package let column: Int? - package let severity: MavenIssueSeverity - package let message: String - - package init(id: String, fileURL: URL?, line: Int?, column: Int?, severity: MavenIssueSeverity, message: String) { - self.id = id - self.fileURL = fileURL - self.line = line - self.column = column - self.severity = severity - self.message = message - } - - package var locationTitle: String { - guard let fileURL else { return "Build output" } - let location = [line, column].compactMap { $0.map(String.init) }.joined(separator: ":") - return location.isEmpty ? fileURL.lastPathComponent : fileURL.lastPathComponent + ":" + location - } -} - -package struct MavenLaunchContext: Codable, Equatable, Sendable { - package static let currentVersion = 1 - - package let version: Int - package let reactorPath: String - package let profiles: [String] - package let settingsPath: String? - package let localRepositoryPath: String? - package let skipTests: Bool - package let mavenExecutablePath: String? - package let javaHomePath: String? - - /// Language-import contexts omit execution-only choices such as Skip Tests. - package init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - version = try values.decode(Int.self, forKey: .version) - reactorPath = try values.decode(String.self, forKey: .reactorPath) - profiles = try values.decode([String].self, forKey: .profiles) - settingsPath = try values.decodeIfPresent(String.self, forKey: .settingsPath) - localRepositoryPath = try values.decodeIfPresent(String.self, forKey: .localRepositoryPath) - skipTests = try values.decodeIfPresent(Bool.self, forKey: .skipTests) ?? false - mavenExecutablePath = try values.decodeIfPresent(String.self, forKey: .mavenExecutablePath) - javaHomePath = try values.decodeIfPresent(String.self, forKey: .javaHomePath) - } - - package init( - version: Int = currentVersion, - reactorPath: String, - profiles: [String], - settingsPath: String?, - localRepositoryPath: String? = nil, - skipTests: Bool, - mavenExecutablePath: String?, - javaHomePath: String? - ) { - self.version = version - self.reactorPath = reactorPath - self.profiles = profiles - self.settingsPath = settingsPath - self.localRepositoryPath = localRepositoryPath - self.skipTests = skipTests - self.mavenExecutablePath = mavenExecutablePath - self.javaHomePath = javaHomePath - } -} - -package func redactedMavenArgumentsForDisplay(_ arguments: [String]) -> [String] { - var result: [String] = [] - var index = 0 - while index < arguments.count { - let argument = arguments[index] - if argument == "-s" || argument == "--settings" { - result.append(argument) - if arguments.indices.contains(index + 1) { - result.append("") - index += 2 - } else { - index += 1 - } - } else if argument.hasPrefix("--settings=") || argument.hasPrefix("-s=") { - result.append(String(argument.prefix { $0 != "=" }) + "=") - index += 1 - } else if argument.hasPrefix("-Dmaven.repo.local=") { - result.append("-Dmaven.repo.local=") - index += 1 - } else { - result.append(argument) - index += 1 - } - } - return result -} - -package struct MavenOperationError: LocalizedError, Equatable, Sendable { - package let code: String - package let message: String - package let details: String? - - package init(code: String, message: String, details: String? = nil) { - self.code = code - self.message = message - self.details = details - } - - package var errorDescription: String? { - guard let details, !details.isEmpty else { return message } - return message + ": " + details - } -} diff --git a/macos/Sources/LitheCoreContracts/Execution/RunConfigurationContracts.swift b/macos/Sources/LitheCoreContracts/Execution/RunConfigurationContracts.swift index 06ff7fb16d..5fc116bee5 100644 --- a/macos/Sources/LitheCoreContracts/Execution/RunConfigurationContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/RunConfigurationContracts.swift @@ -1,38 +1,6 @@ import LitheModuleAPI import Foundation -/// Exact owner of a current build-model project, independent of build semantics. -package struct RunBuildProjectReference: Codable, Equatable, Hashable, Sendable { - package let pluginID: String - package let buildSystemID: String - package let root: String - package let projectID: String - package init(pluginID: String, buildSystemID: String, root: String, projectID: String) { - self.pluginID = pluginID; self.buildSystemID = buildSystemID - self.root = root; self.projectID = projectID - } -} - -/// Read-only ownership projected from the current Provider model and import. -/// Run generation must not reconstruct these facts from build descriptors. -package struct RunProjectOwnership: Codable, Equatable, Sendable { - package struct SourceRoot: Codable, Equatable, Sendable { - package let path: String - package let kind: String - package init(path: String, kind: String) { self.path = path; self.kind = kind } - } - package let path: String - package let name: String? - package let minimumJavaVersion: String? - package let build: RunBuildProjectReference? - package let contentRoots: [SourceRoot] - package init(path: String, build: RunBuildProjectReference?, contentRoots: [SourceRoot], name: String? = nil, minimumJavaVersion: String? = nil) { - self.minimumJavaVersion = minimumJavaVersion - self.name = name - self.path = path; self.build = build; self.contentRoots = contentRoots - } -} - /// Revokes user-document and native-state publication when generation loses its owner. package final class RunConfigurationGenerationLease: @unchecked Sendable { private let lock = NSLock() @@ -115,7 +83,7 @@ package struct RunConfigurationDiagnostic: Equatable, Identifiable, Sendable { package let configurationID: String? package let code: String package let message: String - /// Toolchain requirement ID the diagnostic is about, such as `project-jdk`. + /// Toolchain requirement ID the diagnostic is about, such as `project-node`. package let toolchain: String? package init(configurationID: String?, code: String, message: String, toolchain: String? = nil) { @@ -128,23 +96,6 @@ package struct RunConfigurationDiagnostic: Equatable, Identifiable, Sendable { package var id: String { [configurationID, code, message].compactMap { $0 }.joined(separator: ":") } } -package extension Array where Element == RunConfigurationDiagnostic { - /// Core's requirement checks for one toolchain, such as a JDK older than the - /// project requires. Without `configurationID`, every configuration's result - /// counts, because project defaults apply to all of them. - func toolchainRequirementMessages(for toolchain: String, configurationID: String? = nil) -> [String] { - let codes: Set = ["missingToolchain", "toolchainVersionMismatch", "toolchainVendorMismatch"] - var seen = Set() - return filter { diagnostic in - codes.contains(diagnostic.code) - && diagnostic.toolchain == toolchain - && (configurationID == nil || diagnostic.configurationID == configurationID) - } - .map(\.message) - .filter { seen.insert($0).inserted } - } -} - package struct ProjectRunConfigurationInspection: Equatable, Sendable { package let status: ProjectRunConfigurationStatus /// Saved tasks can be ready while this process still needs to detect other entries. @@ -152,28 +103,19 @@ package struct ProjectRunConfigurationInspection: Equatable, Sendable { package let diagnostics: [RunConfigurationDiagnostic] package var recoveryAction: RunConfigurationRecoveryAction = .none package var recoveryPath: String? = nil - /// Project defaults saved in the machine-local run layer. `nil` means that - /// layer holds no defaults yet, which differs from explicitly automatic ones. - package var projectToolchain: ProjectToolchainSelection? = nil - package var hasSavedToolchainPathOverrides = false package init( status: ProjectRunConfigurationStatus, diagnostics: [RunConfigurationDiagnostic], recoveryAction: RunConfigurationRecoveryAction = .none, recoveryPath: String? = nil, - projectToolchain: ProjectToolchainSelection? = nil, - hasSavedToolchainPathOverrides: Bool = false, requiresGeneration: Bool = false - ) { self.status = status self.requiresGeneration = requiresGeneration self.diagnostics = diagnostics self.recoveryAction = recoveryAction self.recoveryPath = recoveryPath - self.projectToolchain = projectToolchain - self.hasSavedToolchainPathOverrides = hasSavedToolchainPathOverrides } } @@ -195,8 +137,7 @@ package enum ProjectLoadState: Equatable, Sendable { return boundWorkspace == workspace.standardizedFileURL } - /// Whether the run documents of `workspace`, including its project toolchain, - /// have been read. Unlike `hasReadyInventory`, a project without generated + /// Whether the run documents of `workspace` have been read. Unlike `hasReadyInventory`, a project without generated /// configurations counts once inspection bound it. package func hasLoadedDocuments(for workspace: URL) -> Bool { switch self { @@ -208,39 +149,6 @@ package enum ProjectLoadState: Equatable, Sendable { } } -/// Outcome of asking JDT which classes can be launched, taken before a -/// generation. Whether a class is launchable is JDT's answer; Lithe never -/// derives entry points from source text. -/// -/// Note: 入口点归属见 .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md -package enum JavaEntrypointDiscovery: Equatable, Sendable { - /// The workspace has no Java sources, so there is nothing to ask. - case notJava - case discovered(JavaEntrypoints) - /// The Java service is starting or still importing the project. - case pending - case failed(String) - - /// JDT's answer, or `nil` so Core keeps the previous generation's entries. - package var entrypoints: JavaEntrypoints? { - if case .discovered(let entrypoints) = self { return entrypoints } - return nil - } -} - -/// Where the Java entries shown in the Run list come from. -/// -/// `ready` is JDT's current answer; `stale` shows the previous answer while the -/// Java service prepares the project; `loading` has no previous answer yet; -/// `failed` keeps the previous list and says why it could not refresh. -package enum JavaDiscoveryStatus: Equatable, Sendable { - case idle - case loading - case ready - case stale - case failed(String) -} - package enum RunConfigurationGenerationState: Equatable, Sendable { case idle case projectNotReady @@ -282,18 +190,15 @@ package struct RunConfigurationResolution: Sendable { package let configurations: [EffectiveRunConfiguration] package let diagnostics: [RunConfigurationDiagnostic] package let defaultConfigurationID: String? - package let projectToolchain: ProjectToolchainSelection package init( configurations: [EffectiveRunConfiguration], diagnostics: [RunConfigurationDiagnostic], - defaultConfigurationID: String?, - projectToolchain: ProjectToolchainSelection = ProjectToolchainSelection() + defaultConfigurationID: String? ) { self.configurations = configurations self.diagnostics = diagnostics self.defaultConfigurationID = defaultConfigurationID - self.projectToolchain = projectToolchain } } @@ -337,28 +242,6 @@ package struct RunConfigurationGenerationResult: Sendable { package init(entryCount: Int) { self.entryCount = entryCount } } -package struct RunConfigurationDraft: Sendable { - package let name: String - package let kind: RunConfigurationKind - package let modulePath: String - package let mainClass: String - package let scope: RunConfigurationSaveScope - - package init( - name: String, - kind: RunConfigurationKind, - modulePath: String, - mainClass: String, - scope: RunConfigurationSaveScope - ) { - self.name = name - self.kind = kind - self.modulePath = modulePath - self.mainClass = mainClass - self.scope = scope - } -} - package struct RunConfigurationDocumentMutation: Sendable { package let configurationID: String? package let document: Data @@ -376,56 +259,6 @@ package protocol RunConfigurationDocumentMutating: Sendable { scope: RunConfigurationSaveScope, options: RunOptions ) throws -> RunConfigurationDocumentMutation - func createConfigurationDocument( - at projectURL: URL, - draft: RunConfigurationDraft - ) throws -> RunConfigurationDocumentMutation -} - -package struct ProjectToolchainSelection: Codable, Equatable, Sendable { - package struct PathOverride: Codable, Equatable, Sendable { - package var javaHomePath: String - package var mavenExecutablePath: String - package var mavenJavaHomePath: String - package init(javaHomePath: String = "", mavenExecutablePath: String = "", mavenJavaHomePath: String = "") { - self.javaHomePath = javaHomePath - self.mavenExecutablePath = mavenExecutablePath - self.mavenJavaHomePath = mavenJavaHomePath - } - package init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - javaHomePath = try values.decodeIfPresent(String.self, forKey: .javaHomePath) ?? "" - mavenExecutablePath = try values.decodeIfPresent(String.self, forKey: .mavenExecutablePath) ?? "" - mavenJavaHomePath = try values.decodeIfPresent(String.self, forKey: .mavenJavaHomePath) ?? "" - } - private enum CodingKeys: String, CodingKey { case javaHomePath, mavenExecutablePath, mavenJavaHomePath } - } - package var javaHomePath = "" - package var mavenExecutablePath = "" - package var mavenJavaHomePath = "" - package var pathOverrides: [String: PathOverride] = [:] - - package init( - javaHomePath: String = "", - mavenExecutablePath: String = "", - mavenJavaHomePath: String = "", - pathOverrides: [String: PathOverride] = [:] - ) { - self.javaHomePath = javaHomePath - self.mavenExecutablePath = mavenExecutablePath - self.mavenJavaHomePath = mavenJavaHomePath - self.pathOverrides = pathOverrides - } - - package init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - javaHomePath = try values.decodeIfPresent(String.self, forKey: .javaHomePath) ?? "" - mavenExecutablePath = try values.decodeIfPresent(String.self, forKey: .mavenExecutablePath) ?? "" - mavenJavaHomePath = try values.decodeIfPresent(String.self, forKey: .mavenJavaHomePath) ?? "" - pathOverrides = try values.decodeIfPresent([String: PathOverride].self, forKey: .pathOverrides) ?? [:] - } - - private enum CodingKeys: String, CodingKey { case javaHomePath, mavenExecutablePath, mavenJavaHomePath, pathOverrides } } /// Core resolves document layers without assembling the provider's command line. @@ -474,156 +307,56 @@ package struct ProviderLaunchInputs: Decodable, Equatable, Sendable { package protocol RunConfigurationOperations: Sendable { func providerLaunchInputs(at projectURL: URL, configurationID: String, providerRoot: String) throws -> ProviderLaunchInputs func saveBuildProviderConfiguration(_ reference: BuildProviderRunReference, name: String, at projectURL: URL) throws -> String - /// Saves project defaults without modifying any service or requiring generated configurations. - func saveProjectToolchain(_ toolchain: ProjectToolchainSelection, at projectURL: URL) throws - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection - /// Checks generated facts against the current Provider snapshot without hashing source files. - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership]) -> ProjectRunConfigurationInspection - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership], providerRuns: [RunProviderConfiguration]) -> ProjectRunConfigurationInspection - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration]) throws -> RunConfigurationGenerationResult - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration], - models: [BuildModel], lease: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult /// `checkFingerprint: false` validates the documents without reading project - /// inputs. `javaEntrypoints`, JDT's current answer, additionally reports - /// whether the generated Java entries still match it. + /// inputs. `providerRuns` is the current Provider snapshot; `nil` skips the + /// staleness comparison, an empty list compares against "no Provider runs". func inspect( at projectURL: URL, checkFingerprint: Bool, - javaEntrypoints: JavaEntrypoints? + providerRuns: [RunProviderConfiguration]? ) -> ProjectRunConfigurationInspection - /// `javaEntrypoints` is JDT's current answer; `nil` keeps the previous - /// generation's Java entries while the Java service prepares the project. func generate( at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? + providerRuns: [RunProviderConfiguration]?, + lease: RunConfigurationGenerationLease ) throws -> RunConfigurationGenerationResult func resolve( at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate] ) throws -> RunConfigurationResolution - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int?, - mavenContext: MavenLaunchContext? - ) throws -> SharedLaunchPlan - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - javaLaunch: JavaDebugLaunchTarget?, - debugPort: Int?, - mavenContext: MavenLaunchContext? - ) throws -> SharedLaunchPlan + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan func saveEditorChanges( _ options: RunOptions, - toolchain: ProjectToolchainSelection, configurationID: String, scope: RunConfigurationSaveScope, at projectURL: URL ) throws - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws } package extension RunConfigurationOperations { - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration], - models: [BuildModel], lease: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { - try lease.check() - return try generate(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, - projectOwnership: projectOwnership, providerRuns: providerRuns) + func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + inspect(at: projectURL, checkFingerprint: true, providerRuns: nil) } - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership], providerRuns: [RunProviderConfiguration]) -> ProjectRunConfigurationInspection { - guard providerRuns.isEmpty else { - return .init(status: .invalid(L10n.string("Load the current build model and enable its provider before running this configuration.")), diagnostics: []) - } - return inspectProviderGeneration(at: projectURL, projectOwnership: projectOwnership) + + /// Checks generated facts against the current Provider snapshot without hashing source files. + func inspectProviderGeneration(at projectURL: URL, providerRuns: [RunProviderConfiguration]) -> ProjectRunConfigurationInspection { + inspect(at: projectURL, checkFingerprint: false, providerRuns: providerRuns) } - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration]) throws -> RunConfigurationGenerationResult { - guard providerRuns.isEmpty else { throw RunConfigurationOperationFailure(message: L10n.string("Load the current build model and enable its provider before running this configuration.")) } - return try generate(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, projectOwnership: projectOwnership) + + func generate(at projectURL: URL, providerRuns: [RunProviderConfiguration]?) throws -> RunConfigurationGenerationResult { + try generate(at: projectURL, providerRuns: providerRuns, lease: RunConfigurationGenerationLease()) } func providerLaunchInputs(at projectURL: URL, configurationID: String, providerRoot: String) throws -> ProviderLaunchInputs { throw RunConfigurationOperationFailure(message: L10n.string("Load the current build model and enable its provider before running this configuration.")) } - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership]) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: false, javaEntrypoints: nil) - } - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?) throws -> RunConfigurationGenerationResult { - try generate(at: projectURL, files: files, modulePaths: modulePaths, - javaEntrypoints: javaEntrypoints, projectOwnership: nil) - } func saveBuildProviderConfiguration(_: BuildProviderRunReference, name: String, at _: URL) throws -> String { throw RunConfigurationOperationFailure(message: L10n.string("Saving build provider run configurations is unavailable.")) } - func inspect( - at projectURL: URL, - checkFingerprint _: Bool, - javaEntrypoints _: JavaEntrypoints? - ) -> ProjectRunConfigurationInspection { - inspect(at: projectURL) - } - func saveProjectToolchain(_: ProjectToolchainSelection, at _: URL) throws { - throw RunConfigurationEditorSaveFailure(stage: .prepare, message: "Project environment saving is unavailable.") - } - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int?, - mavenContext _: MavenLaunchContext? - ) throws -> SharedLaunchPlan { - try launchPlan( - at: projectURL, - configurationID: configurationID, - currentFile: currentFile, - classPath: classPath, - debugPort: debugPort - ) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - javaLaunch _: JavaDebugLaunchTarget?, - debugPort: Int?, - mavenContext: MavenLaunchContext? - ) throws -> SharedLaunchPlan { - try launchPlan( - at: projectURL, - configurationID: configurationID, - currentFile: currentFile, - classPath: classPath, - debugPort: debugPort, - mavenContext: mavenContext - ) - } func saveEditorChanges( _: RunOptions, - toolchain _: ProjectToolchainSelection, configurationID _: String, scope _: RunConfigurationSaveScope, at _: URL diff --git a/macos/Sources/LitheCoreContracts/Execution/RunModels.swift b/macos/Sources/LitheCoreContracts/Execution/RunModels.swift index 672410c532..ac835a09a7 100644 --- a/macos/Sources/LitheCoreContracts/Execution/RunModels.swift +++ b/macos/Sources/LitheCoreContracts/Execution/RunModels.swift @@ -9,9 +9,6 @@ package struct RunSession: Identifiable, Hashable, Sendable { package var output: String package var isRunning: Bool package var exitCode: Int32? - /// Immutable runtime inputs from this execution, never the current editor selection. - package var javaUpdateTarget: JavaDebugLaunchTarget? - package var javaUpdateSource: URL? package init( executionID: String = UUID().uuidString, @@ -32,22 +29,7 @@ package struct RunSession: Identifiable, Hashable, Sendable { } } -package struct RunPortConflict: Identifiable, Hashable, Sendable { - package let port: Int - package let configurationNames: [String] - - package init(port: Int, configurationNames: [String]) { - self.port = port - self.configurationNames = configurationNames - } - - package var id: String { String(port) } - - package var title: String { - "Port \(port) is used by " + configurationNames.joined(separator: ", ") - } -} - +/// Fields a run configuration exposes in the shared editor. package struct RunConfigurationCapabilities: OptionSet, Hashable, Sendable { package let rawValue: Int package init(rawValue: Int) { self.rawValue = rawValue } @@ -55,68 +37,20 @@ package struct RunConfigurationCapabilities: OptionSet, Hashable, Sendable { package static let workingDirectory = Self(rawValue: 1 << 0) package static let arguments = Self(rawValue: 1 << 1) package static let environment = Self(rawValue: 1 << 2) - package static let javaRuntime = Self(rawValue: 1 << 3) - package static let javaVMArguments = Self(rawValue: 1 << 4) - package static let mavenProfiles = Self(rawValue: 1 << 5) - package static let jdwpDebug = Self(rawValue: 1 << 6) - package static let mavenSkipTests = Self(rawValue: 1 << 7) package static let process: Self = [.workingDirectory, .arguments, .environment] } -/// A JVM framework launched by a Maven goal rather than by spawning a process. -/// -/// These share Spring Boot's capabilities exactly -- the core assembles the goal -/// and the property names its arguments travel under -- so they are one case -/// carrying the framework rather than three parallel cases. -package enum MavenFrameworkKind: String, Hashable, Sendable, CaseIterable { - case springBoot - case quarkus - case micronaut - - /// The core provider this framework is reported as. - package var provider: String { - switch self { - case .springBoot: "spring-boot.maven" - case .quarkus: "quarkus.maven" - case .micronaut: "micronaut.maven" - } - } - - package var title: String { - switch self { - case .springBoot: "Spring Boot" - case .quarkus: "Quarkus" - case .micronaut: "Micronaut" - } - } - - /// Only Spring Boot's goal accepts a main class; Quarkus and Micronaut - /// resolve it from the build, so naming one would be ignored. - package var namesMainClass: Bool { self == .springBoot } -} - package enum RunConfigurationKind: Hashable, Identifiable, Sendable { case currentFile - case javaMain - case mavenModule - /// A JVM framework whose service is started by a Maven goal. - case mavenFramework(MavenFrameworkKind) - /// Any provider this build has no first-class handling for. Carrying the - /// raw provider keeps unknown ecosystems visible and runnable instead of - /// silently dropping them at the decode boundary. + /// Any provider reported by Core or a plugin. Carrying the raw provider + /// keeps every ecosystem visible and runnable instead of dropping it at + /// the decode boundary. case process(provider: String) - package static let springBoot: Self = .mavenFramework(.springBoot) - package init?(rawValue: String) { switch rawValue { case "currentFile": self = .currentFile - case "springBoot": self = .springBoot - case "javaMain": self = .javaMain - case "mavenModule": self = .mavenModule - case "quarkus": self = .mavenFramework(.quarkus) - case "micronaut": self = .mavenFramework(.micronaut) default: return nil } } @@ -124,45 +58,22 @@ package enum RunConfigurationKind: Hashable, Identifiable, Sendable { package var id: String { switch self { case .currentFile: "currentFile" - case .javaMain: "javaMain" - case .mavenModule: "mavenModule" - case .mavenFramework(let framework): framework.rawValue case .process(let provider): provider } } + /// The provider namespace; Current File belongs to no provider. package var providerID: String { switch self { - case .currentFile, .javaMain: "java" - case .mavenModule, .mavenFramework: "maven" + case .currentFile: "" case .process(let provider): provider.split(separator: ".").first.map(String.init) ?? provider } } - /// The framework whose Maven goal starts this configuration, if any. - package var mavenFramework: MavenFrameworkKind? { - if case .mavenFramework(let framework) = self { return framework } - return nil - } - - /// True for the Maven-backed kinds that support JDWP debugging and Maven - /// profiles. Callers should branch on this rather than enumerating cases. - package var isMavenBacked: Bool { - self == .mavenModule || mavenFramework != nil - } - package var capabilities: RunConfigurationCapabilities { switch self { - case .currentFile, .javaMain: - return [.workingDirectory, .arguments, .environment, .javaRuntime, .javaVMArguments, .jdwpDebug] - case .mavenModule: - return [.workingDirectory, .arguments, .environment, .javaRuntime, - .javaVMArguments, .mavenProfiles, .mavenSkipTests] - case .mavenFramework: - return [ - .workingDirectory, .arguments, .environment, .javaRuntime, - .javaVMArguments, .mavenProfiles, .mavenSkipTests, .jdwpDebug - ] + case .currentFile: + return .process case .process(let provider): return provider == "build.provider" ? [] : .process } @@ -171,9 +82,6 @@ package enum RunConfigurationKind: Hashable, Identifiable, Sendable { package var title: String { switch self { case .currentFile: "Current File" - case .javaMain: "Java Application" - case .mavenModule: "Maven Module" - case .mavenFramework(let framework): framework.title case .process(let provider): Self.displayTitle(for: provider) } } @@ -181,11 +89,6 @@ package enum RunConfigurationKind: Hashable, Identifiable, Sendable { package var systemImage: String { switch self { case .currentFile: "doc.text" - case .javaMain: "cup.and.heat.waves" - case .mavenModule: "shippingbox" - // All three are long-running JVM services started the same way, so they - // share one symbol rather than implying a difference that is not there. - case .mavenFramework: "leaf" case .process(let provider): Self.symbol(for: provider) } } @@ -242,33 +145,12 @@ package struct RunConfiguration: Identifiable, Hashable, Sendable { package let name: String package let kind: RunConfigurationKind package let execution: RunConfigurationExecution - package let modulePath: String? - package let mainClass: String? - /// Workspace-relative Java source that owns this launch target, when known. - package let sourcePath: String? - /// Detected ownership from Core, independent of an overridden working directory. - package let mavenReactorPath: String? package let debugAdapter: String? package let disabled: Bool package let buildProvider: BuildProviderRunReference? - package let buildProject: RunBuildProjectReference? package var usesCurrentEditorFile: Bool { kind == .currentFile } - /// These persisted configurations depend on current Provider generation facts. - package var requiresProviderGeneration: Bool { - guard buildProvider == nil else { return false } - switch kind { - case .javaMain, .mavenModule, .mavenFramework: return true - case .currentFile, .process: return false - } - } - - /// Only launches backed by a JDT project wait for workspace preparation. - package var usesJavaProjectPreparation: Bool { - (kind == .javaMain || (kind == .springBoot && sourcePath?.lowercased().hasSuffix(".java") == true)) && (buildProject != nil || mavenReactorPath != nil) - } - /// Saved provider services may attach through their declared registry type. package var usesProviderConnectionDebug: Bool { buildProvider?.execution == .service @@ -279,78 +161,27 @@ package struct RunConfiguration: Identifiable, Hashable, Sendable { name: String, kind: RunConfigurationKind, execution: RunConfigurationExecution? = nil, - modulePath: String?, - mainClass: String?, - sourcePath: String? = nil, - mavenReactorPath: String? = nil, debugAdapter: String? = nil, disabled: Bool = false, - buildProvider: BuildProviderRunReference? = nil, - buildProject: RunBuildProjectReference? = nil + buildProvider: BuildProviderRunReference? = nil ) { self.id = id self.name = name self.kind = kind - self.execution = execution ?? Self.defaultExecution(for: kind) - self.modulePath = modulePath - self.mainClass = mainClass - self.sourcePath = sourcePath - self.mavenReactorPath = mavenReactorPath + self.execution = execution ?? .application self.debugAdapter = debugAdapter self.disabled = disabled self.buildProvider = buildProvider - self.buildProject = buildProject } package var systemImage: String { kind.systemImage } - /// Current File is a language-neutral entry. Java keeps its legacy JDK - /// capability, while other Providers expose only the shared process - /// fields in the configuration editor. - package func effectiveCapabilities( - for currentFileURL: URL?, - catalog: LanguageProviderCatalog = .compatibilityFallback - ) -> RunConfigurationCapabilities { - guard kind == .currentFile else { return kind.capabilities } - guard let currentFileURL, - let descriptor = catalog.provider(for: currentFileURL) else { - // An unknown extension is still a language-neutral Current File - // entry. Showing JDK/Maven controls here would make an unsupported - // language look like a Java project and leak provider assumptions - // into the shared editor. - return .process - } - guard descriptor.id == "java" else { - return .process - } - return kind.capabilities - } - package static var currentFile: RunConfiguration { RunConfiguration( id: currentFileID, name: "Current File", kind: .currentFile, - execution: .application, - modulePath: nil, - mainClass: nil + execution: .application ) } - - private static func defaultExecution( - for kind: RunConfigurationKind - ) -> RunConfigurationExecution { - switch kind { - case .mavenFramework: .service - case .currentFile, .javaMain, .process: .application - case .mavenModule: .task - } - } } - -// Temporary source compatibility at the Java-debug boundary. These aliases do -// not own behavior; the canonical models above are language neutral. -package typealias JavaRunSession = RunSession -package typealias JavaRunPortConflict = RunPortConflict -package typealias JavaRunConfigurationKind = RunConfigurationKind -package typealias JavaRunConfiguration = RunConfiguration diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageExtensionContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageExtensionContracts.swift index b90c88fbf0..7e95ab89c0 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageExtensionContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageExtensionContracts.swift @@ -111,10 +111,8 @@ public struct LanguageServerExtensionConfiguration: Equatable, Sendable { /// and still starts as a host-owned process. public let pluginID: String? /// Minimum version a discovered executable must report, for a server - /// started by a runtime such as `java`. + /// started by a runtime such as `node`. public let executableVersionRequirement: LanguageServerExecutableVersionRequirement? - /// Native host integration the provider declares, such as `jdt`. - public let hostIntegrationID: String? /// Runtime tool, such as `node`, the host starts the server with. The /// executable the host selects for it is also what the server's own /// commands resolve by name. @@ -133,7 +131,6 @@ public struct LanguageServerExtensionConfiguration: Equatable, Sendable { launchSource: DeclarativeLanguageServerLaunchSource? = nil, pluginID: String? = nil, executableVersionRequirement: LanguageServerExecutableVersionRequirement? = nil, - hostIntegrationID: String? = nil, launchRuntimeTool: String? = nil ) { self.languageID = languageID @@ -148,7 +145,6 @@ public struct LanguageServerExtensionConfiguration: Equatable, Sendable { self.launchSource = launchSource self.pluginID = pluginID ?? launchSource?.pluginID self.executableVersionRequirement = executableVersionRequirement - self.hostIntegrationID = hostIntegrationID self.launchRuntimeTool = launchRuntimeTool } } diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageServerHostIntegrationContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageServerHostIntegrationContracts.swift deleted file mode 100644 index 6158649b5f..0000000000 --- a/macos/Sources/LitheCoreContracts/Language/LanguageServerHostIntegrationContracts.swift +++ /dev/null @@ -1,45 +0,0 @@ -import Foundation - -// Note: 宿主集成的划分见 .agents/notes/implemented/architecture/2026-10-13-java-language-server-as-declarative-plugin.md - -/// Start parameters of the Rust Core launch a host integration builds on. -/// The set is closed: an integration is host code a plugin names in its -/// manifest, never something a plugin can add. -package enum LanguageServerHostIntegrationCoreLaunch: Equatable, Sendable { - case jdt(JDTLSLaunchResources) - - package var jdtlsLaunchResources: JDTLSLaunchResources? { - switch self { - case .jdt(let resources): resources - } - } -} - -/// What a host integration adds to one start of the language server that -/// declares it. The language-server pipeline carries this value from the -/// integration to Rust Core without interpreting it. -package struct LanguageServerHostIntegrationLaunch: Equatable, Sendable { - /// Runtime the server process runs on, when the integration supplies one. - package let runtimeExecutableURL: URL? - package let coreLaunch: LanguageServerHostIntegrationCoreLaunch? - - package init( - runtimeExecutableURL: URL? = nil, - coreLaunch: LanguageServerHostIntegrationCoreLaunch? = nil - ) { - self.runtimeExecutableURL = runtimeExecutableURL?.standardizedFileURL - self.coreLaunch = coreLaunch - } -} - -package enum LanguageServerHostIntegrationResolution: Equatable, Sendable { - case available(LanguageServerHostIntegrationLaunch) - /// The integration cannot start the server; the message tells the user why. - case unavailable(String) -} - -/// Resolves the host integration a provider declares for one start. `nil` -/// means the provider declares none and starts as a plain language server. -package typealias LanguageServerHostIntegrationResolver = @MainActor ( - LanguageProviderDescriptor -) -> LanguageServerHostIntegrationResolution? diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift index c319b57ec9..570bfb4f98 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift @@ -1,25 +1,6 @@ import Foundation import LitheModuleAPI -/// What a running Java session was asked to do with a Maven configuration. -/// -/// Every step runs asynchronously inside JDT LS; resolution problems arrive -/// later as `pom.xml` diagnostics. -package struct LanguageServerMavenConfigurationUpdate: Decodable, Equatable, Sendable { - /// New settings documents were sent, so JDT LS re-imports every Maven project. - package let settingsChanged: Bool - /// Settings were unchanged, so a forced project update was requested. - package let projectsReloaded: Bool - /// Changed profiles are being applied. - package let profilesUpdating: Bool - - package init(settingsChanged: Bool, projectsReloaded: Bool, profilesUpdating: Bool) { - self.settingsChanged = settingsChanged - self.projectsReloaded = projectsReloaded - self.profilesUpdating = profilesUpdating - } -} - package struct LanguageServerRuntimeFailure: Error, Equatable, Sendable { package let code: String package let message: String @@ -49,60 +30,6 @@ package struct LanguageServerRuntimeStart: Equatable, Sendable { } } -/// An installed JDK the Java language service may compile projects against. -package struct JavaLanguageServiceRuntime: Equatable, Sendable { - package let isDefault: Bool - package let homePath: String - /// Version reported by `java -version`, such as `25.0.4` or `1.8.0_402`. - package let version: String - - package init(homePath: String, version: String, isDefault: Bool = false) { - self.isDefault = isDefault - self.homePath = homePath - self.version = version - } -} - -package struct JDTLSLaunchResources: Equatable, Sendable { - package let launcherJarURL: URL - package let configurationDirectoryURL: URL - package let lombokAgentURL: URL - /// Ordered OSGi bundles contributed by Java tooling extensions. The Java - /// Debug Server remains first for compatibility with older Rust cores. - package let javaExtensionBundleURLs: [URL] - /// Standalone TestNG runner used only when a TestNG debug launch is requested. - package let javaTestRunnerURL: URL? - /// Installed JDKs, most preferred first. Without them JDT LS knows only the - /// JDK it runs on and cannot build a project for a newer release. - package let javaRuntimes: [JavaLanguageServiceRuntime] - - package init( - launcherJarURL: URL, - configurationDirectoryURL: URL, - lombokAgentURL: URL, - javaDebugBundleURL: URL? = nil, - javaExtensionBundleURLs: [URL] = [], - javaTestRunnerURL: URL? = nil, - javaRuntimes: [JavaLanguageServiceRuntime] = [] - ) { - self.javaRuntimes = javaRuntimes - self.launcherJarURL = launcherJarURL.standardizedFileURL - self.configurationDirectoryURL = configurationDirectoryURL.standardizedFileURL - self.lombokAgentURL = lombokAgentURL.standardizedFileURL - var seen = Set() - self.javaExtensionBundleURLs = ([javaDebugBundleURL].compactMap { $0 } + javaExtensionBundleURLs) - .map(\.standardizedFileURL) - .filter { seen.insert($0.path).inserted } - self.javaTestRunnerURL = javaTestRunnerURL?.standardizedFileURL - } - - package var javaDebugBundleURL: URL? { - javaExtensionBundleURLs.first { - $0.lastPathComponent.hasPrefix("com.microsoft.java.debug.plugin-") - } - } -} - package struct LanguageServerRuntimeOperation: Equatable, Sendable { package let operationID: String @@ -173,45 +100,12 @@ package struct LanguageServerWorkspaceFileChange: Equatable, Sendable { } } -package enum JavaNavigationDirection: String, Codable, Equatable, Sendable { - case up - case down -} - -package enum JavaNavigationRelation: String, Codable, Equatable, Sendable { - case interface - case inheritance -} - -package struct JavaNavigationMarker: Equatable, Sendable { - package let line: Int - package let utf16Column: Int - package let implementationCount: Int - package let direction: JavaNavigationDirection - package let relation: JavaNavigationRelation - - package init( - line: Int, - utf16Column: Int, - implementationCount: Int, - direction: JavaNavigationDirection, - relation: JavaNavigationRelation - ) { - self.line = line - self.utf16Column = utf16Column - self.implementationCount = implementationCount - self.direction = direction - self.relation = relation - } -} - package struct LanguageServerRuntimeError: Equatable, Sendable { package let code: String package let stage: String package let message: String package let underlyingMessage: String? package let processExitCode: Int? - package let javaBuildReport: JavaBuildReport? /// 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? @@ -225,7 +119,6 @@ package struct LanguageServerRuntimeError: Equatable, Sendable { message: String, underlyingMessage: String?, processExitCode: Int?, - javaBuildReport: JavaBuildReport? = nil, pluginErrorCode: String? = nil, details: ToolingJSONValue? = nil ) { @@ -234,66 +127,16 @@ package struct LanguageServerRuntimeError: Equatable, Sendable { self.message = message self.underlyingMessage = underlyingMessage self.processExitCode = processExitCode - self.javaBuildReport = javaBuildReport self.pluginErrorCode = pluginErrorCode self.details = details } } -package enum JavaBuildMarkerScope: String, Codable, Equatable, Sendable { - case launchTarget - case workspace -} - -package enum JavaBuildRecovery: String, Codable, Equatable, Sendable { - case none - case rebuildJavaIndex -} - -/// Evidence reported by Core for one terminal Java build verdict. -package struct JavaBuildReport: Codable, Equatable, Sendable { - package let markerScope: JavaBuildMarkerScope - package let builderFailedEarlier: Bool - package let elapsedMilliseconds: UInt64 - package let recovery: JavaBuildRecovery - - package init( - markerScope: JavaBuildMarkerScope, - builderFailedEarlier: Bool, - elapsedMilliseconds: UInt64, - recovery: JavaBuildRecovery - ) { - self.markerScope = markerScope - self.builderFailedEarlier = builderFailedEarlier - self.elapsedMilliseconds = elapsedMilliseconds - self.recovery = recovery - } -} - -package struct JavaLaunchBuildFailure: Codable, Equatable, Sendable { - package let code: String - package let message: String - package let report: JavaBuildReport? - - package init(code: String, message: String, report: JavaBuildReport?) { - self.code = code - self.message = message - self.report = report - } -} - -package enum JavaLaunchPreparation: Equatable, Sendable { - case ready(JavaDebugLaunchTarget) - case buildFailed(target: JavaDebugLaunchTarget, failure: JavaLaunchBuildFailure) -} - package struct LanguageServerRuntimeEvent: Equatable, Sendable { /// Optional structured fact on any runtime event, including stateChanged; independent of type. package let coreLog: CoreLogRecord? package let pluginID: String? package let role: String? - package let mavenProfileTask: String? - package let mavenProfileProject: MavenProfileProjectResult? package let type: String package let state: String? package let operationID: String? @@ -322,15 +165,11 @@ package struct LanguageServerRuntimeEvent: Equatable, Sendable { level: String? = nil, message: String? = nil, detail: String? = nil, - mavenProfileTask: String? = nil, - mavenProfileProject: MavenProfileProjectResult? = nil, method: String? = nil, coreLog: CoreLogRecord? = nil, pluginID: String? = nil, role: String? = nil ) { self.coreLog = coreLog; self.pluginID = pluginID; self.role = role self.method = method - self.mavenProfileTask = mavenProfileTask - self.mavenProfileProject = mavenProfileProject self.type = type self.state = state self.operationID = operationID @@ -346,30 +185,6 @@ package struct LanguageServerRuntimeEvent: Equatable, Sendable { } } -/// Core-normalized Buildship options, fixed for one Java session's lifetime. -package struct JavaGradleImportConfiguration: Codable, Equatable, Sendable { - package let wrapperPresent: Bool - package let offline: Bool? - package let userHome: String? - - package init(wrapperPresent: Bool, offline: Bool? = nil, userHome: String? = nil) { - self.wrapperPresent = wrapperPresent - self.offline = offline - self.userHome = userHome - } -} - -/// Maven and Gradle can coexist in a workspace; each keeps its own import input. -package struct JavaLanguageImportConfiguration: Equatable, Sendable { - package let mavenContext: MavenLaunchContext? - package let javaGradle: JavaGradleImportConfiguration? - - package init(mavenContext: MavenLaunchContext? = nil, javaGradle: JavaGradleImportConfiguration? = nil) { - self.mavenContext = mavenContext - self.javaGradle = javaGradle - } -} - /// Explicit process ownership supplied by each launcher, never inferred from IDs. package enum LanguageServerLogRole: String, Sendable { case languageServer = "language_server", vcs, build, toolchain, backend } @@ -390,61 +205,12 @@ package protocol LanguageServerRuntimeCore: Sendable { rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result - func startLanguageServer( - providerID: String, - executableURL: URL, - arguments: [String], - environment: [String: String], - rootURL: URL, - workingDirectoryURL: URL, - initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result - - func startLanguageServer( - providerID: String, - executableURL: URL, - arguments: [String], - environment: [String: String], - rootURL: URL, - workingDirectoryURL: URL, - initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval ) -> Result func stopLanguageServer(sessionID: String) - /// Retries a failed Maven profile task without restarting the server. - func retryMavenProfiles(sessionID: String) -> Result - /// Sends a changed Maven context to a running Java session, or with - /// `reloadProjects` forces JDT LS to re-resolve its Maven projects. - func updateMavenConfiguration( - sessionID: String, - context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result func syncLanguageServerDocument( sessionID: String, fileURL: URL, @@ -471,22 +237,6 @@ package protocol LanguageServerRuntimeCore: Sendable { codeAction: LanguageServerCodeAction?, command: LanguageServerCommand? ) -> Result - func prepareJavaLaunch( - sessionID: String, - fileURL: URL, - mainClass: String? - ) -> Result - func requestJavaNavigationMarkers( - sessionID: String, - fileURL: URL, - documentVersion: Int - ) -> Result - func resolveJavaNavigation( - sessionID: String, - fileURL: URL, - marker: JavaNavigationMarker, - documentVersion: Int - ) -> Result /// Sends a request of the negotiated build-provider protocol. Its /// completion arrives as a `requestCompleted` event with the reply under /// `result.value`. @@ -580,11 +330,6 @@ package protocol LanguageServerRuntimeCore: Sendable { initializationOptions: ToolingJSONValue?, workspaceConfiguration: ToolingJSONValue?, hostServices: [String], - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -604,8 +349,6 @@ package protocol LanguageServerRuntimeCore: Sendable { workspaceConfiguration: ToolingJSONValue?, sessionPolicy: ToolingJSONValue, hostServices: [String], - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -711,75 +454,6 @@ package extension LanguageServerRuntimeCore { } func requiresBackgroundLanguageServerStart(rootURL _: URL) -> Bool { false } - - func startLanguageServer( - providerID: String, executableURL: URL, arguments: [String], environment: [String: String], - rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, jdtlsLaunchResources: JDTLSLaunchResources?, cacheDirectoryURL: URL?, - workspaceFingerprint: String?, mavenContext: MavenLaunchContext?, javaGradle: JavaGradleImportConfiguration?, - initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval - ) -> Result { - guard javaGradle == nil else { - return .failure(LanguageServerRuntimeFailure(code: "unsupported", message: "This language runtime cannot apply Gradle import settings.")) - } - return startLanguageServer( - providerID: providerID, executableURL: executableURL, arguments: arguments, environment: environment, - rootURL: rootURL, workingDirectoryURL: workingDirectoryURL, initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, workspaceFingerprint: workspaceFingerprint, mavenContext: mavenContext, - initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout - ) - } - - func retryMavenProfiles(sessionID _: String) -> Result { .success(()) } - - /// Runtimes without in-place Maven updates report that they cannot take - /// one, so callers fall back to restarting the session. - func updateMavenConfiguration( - sessionID _: String, - context _: MavenLaunchContext, - reloadProjects _: Bool - ) -> Result { - .failure(LanguageServerRuntimeFailure( - code: "unsupported", - message: "This language runtime cannot update Maven settings in place." - )) - } - - func startLanguageServer( - providerID: String, - executableURL: URL, - arguments: [String], - environment: [String: String], - rootURL: URL, - workingDirectoryURL: URL, - initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext _: MavenLaunchContext?, - initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result { - startLanguageServer( - providerID: providerID, - executableURL: executableURL, - arguments: arguments, - environment: environment, - rootURL: rootURL, - workingDirectoryURL: workingDirectoryURL, - initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - initializeTimeout: initializeTimeout, - requestTimeout: requestTimeout, - shutdownTimeout: shutdownTimeout - ) - } } package extension LanguageServerRuntimeCore { @@ -790,37 +464,6 @@ package extension LanguageServerRuntimeCore { .success(()) } - func prepareJavaLaunch( - sessionID _: String, - fileURL _: URL, - mainClass _: String? - ) -> Result { - .failure(LanguageServerRuntimeFailure(code: "not_supported", message: L10n.string("Java launch preparation is not supported by this runtime."))) - } - - func requestJavaNavigationMarkers( - sessionID _: String, - fileURL _: URL, - documentVersion _: Int - ) -> Result { - .failure(LanguageServerRuntimeFailure( - code: "not_supported", - message: "Java navigation markers are not supported by this runtime." - )) - } - - func resolveJavaNavigation( - sessionID _: String, - fileURL _: URL, - marker _: JavaNavigationMarker, - documentVersion _: Int - ) -> Result { - .failure(LanguageServerRuntimeFailure( - code: "not_supported", - message: "Java navigation is not supported by this runtime." - )) - } - func requestBuildProvider( sessionID _: String, method _: String, @@ -919,8 +562,7 @@ package extension LanguageServerRuntimeCore { startLanguageServer( providerID: providerID, executableURL: executableURL, arguments: arguments, environment: environment, rootURL: rootURL, workingDirectoryURL: rootURL, initializationOptions: initializationOptions, - runtimeExecutableURL: nil, jdtlsLaunchResources: nil, cacheDirectoryURL: nil, - workspaceFingerprint: nil, initializeTimeout: initializeTimeout, + initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout ) } @@ -939,8 +581,6 @@ package extension LanguageServerRuntimeCore { workspaceConfiguration _: ToolingJSONValue?, sessionPolicy _: ToolingJSONValue, hostServices: [String], - cacheDirectoryURL _: URL?, - workspaceFingerprint _: String?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -964,28 +604,10 @@ package extension LanguageServerRuntimeCore { initializationOptions: ToolingJSONValue?, workspaceConfiguration _: ToolingJSONValue?, hostServices: [String], - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval ) -> Result { - if let hostIntegrationLaunch, hostServices.isEmpty { - return startLanguageServer( - providerID: providerID, executableURL: executableURL, arguments: arguments, - environment: environment, rootURL: rootURL, workingDirectoryURL: rootURL, - initializationOptions: initializationOptions, - runtimeExecutableURL: hostIntegrationLaunch.runtimeExecutableURL, - jdtlsLaunchResources: hostIntegrationLaunch.coreLaunch?.jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, javaGradle: javaGradle, - initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, - shutdownTimeout: shutdownTimeout - ) - } return startPluginLanguageServer( pluginID: pluginID, providerID: providerID, executableURL: executableURL, arguments: arguments, environment: environment, rootURL: rootURL, initializationOptions: initializationOptions, @@ -1284,16 +906,3 @@ package protocol LanguageServerProcessRegistry: AnyObject { func registerLanguageServerProcess(pid: Int32, moduleID: ModuleID) func unregisterLanguageServerProcess(pid: Int32, moduleID: ModuleID) } - -/// Read-only preparation facts published by Rust; ready does not imply a successful build. -package struct ProjectPreparationSnapshot: Codable, Equatable, Sendable { - package let phase: String - package let status: String - package let blocksRun: Bool - - package init(phase: String, status: String, blocksRun: Bool) { - self.phase = phase - self.status = status - self.blocksRun = blocksRun - } -} diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift index 845023e501..47094c58bc 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageToolingContracts.swift @@ -76,8 +76,6 @@ package struct LanguageServerLaunchDescriptor: Hashable, Sendable { package let pluginID: String? /// See `LanguageServerExtensionConfiguration.executableVersionRequirement`. package let executableVersionRequirement: LanguageServerExecutableVersionRequirement? - /// Native host integration the provider declares, such as `jdt`. - package let hostIntegrationID: String? /// See `LanguageServerExtensionConfiguration.launchRuntimeTool`. package let launchRuntimeTool: String? @@ -92,7 +90,6 @@ package struct LanguageServerLaunchDescriptor: Hashable, Sendable { launchSource: DeclarativeLanguageServerLaunchSource? = nil, pluginID: String? = nil, executableVersionRequirement: LanguageServerExecutableVersionRequirement? = nil, - hostIntegrationID: String? = nil, launchRuntimeTool: String? = nil ) { self.executableNames = executableNames @@ -105,7 +102,6 @@ package struct LanguageServerLaunchDescriptor: Hashable, Sendable { self.launchSource = launchSource self.pluginID = pluginID ?? launchSource?.pluginID self.executableVersionRequirement = executableVersionRequirement - self.hostIntegrationID = hostIntegrationID self.launchRuntimeTool = launchRuntimeTool } } @@ -217,11 +213,6 @@ package struct LanguageProviderCatalog: Sendable { /// Minimal fallback used only when the Rust core is not linked. The full /// market language catalog is registered by Rust's dedicated LSP config. package static let compatibilityFallback = LanguageProviderCatalog(descriptors: [ - LanguageProviderDescriptor( - id: "java", displayName: "Java", fileExtensions: ["java"], - capabilities: [.run, .languageServer, .debugAdapter, .formatting, .testing], - activationPolicy: .onDemand - ), LanguageProviderDescriptor( id: "go", displayName: "Go", fileExtensions: ["go"], capabilities: [.run, .languageServer, .formatting, .testing], @@ -446,254 +437,8 @@ package enum LanguageServerOperation: String, Equatable, Sendable { case semanticTokens case codeLens /// Resolving a server-owned source that has no file on disk, such as a - /// decompiled class behind a `jdt://` URI. + /// generated source behind a server-defined URI scheme. case virtualDocument - /// JDT's launchable Java classes in the session workspace, normalized by - /// Core into workspace-relative entries. - case javaEntrypoints - /// Java Test extension classes and methods in one source file, normalized - /// by Core into a typed tree. - case javaTestItems - /// JDT's launchable `main` methods in one source file, with the range of - /// each method name, normalized by Core. - case javaMainMethods -} - -/// A class JDT confirmed the JVM can launch, as normalized by Core. -/// -/// Note: 入口点归属见 .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md -package struct JavaEntrypoint: Codable, Equatable, Sendable { - /// Workspace-relative source path with `/` separators. - package let sourcePath: String - /// Class name as JDT reports it, possibly prefixed with `module/`. - package let mainClass: String - /// JDT project that owns the class; only a hint for resolving the launch. - package let projectName: String? - - package init(sourcePath: String, mainClass: String, projectName: String? = nil) { - self.sourcePath = sourcePath - self.mainClass = mainClass - self.projectName = projectName - } -} - -/// Core's `javaEntrypoints` answer. Whether a class is launchable is JDT's -/// decision; Lithe never derives entry points from source text. -package struct JavaEntrypoints: Codable, Equatable, Sendable { - /// A JDT result Core could not turn into an entry, with the reason. - package struct Diagnostic: Codable, Equatable, Sendable { - package let code: String - package let mainClass: String? - package let detail: String? - } - - package let schemaVersion: Int - package let entries: [JavaEntrypoint] - package let diagnostics: [Diagnostic] - - package init(schemaVersion: Int = 1, entries: [JavaEntrypoint], diagnostics: [Diagnostic] = []) { - self.schemaVersion = schemaVersion - self.entries = entries - self.diagnostics = diagnostics - } -} - -/// A zero-based UTF-16 source range reported by JDT for a Java test item. -package struct JavaTestRange: Codable, Equatable, Sendable { - package let startLine: Int - package let startUtf16Column: Int - package let endLine: Int - package let endUtf16Column: Int -} - -/// One test class or method whose semantic identity comes from Java Test/JDT. -package struct JavaTestItem: Codable, Equatable, Sendable { - package let id: String - package let label: String - package let fullName: String - package let projectName: String - package let kind: Int - package let level: Int - package let jdtHandler: String? - package let sortText: String? - package let range: JavaTestRange? - package let children: [JavaTestItem] - - package init( - id: String, - label: String, - fullName: String, - projectName: String, - kind: Int, - level: Int, - jdtHandler: String? = nil, - sortText: String? = nil, - range: JavaTestRange? = nil, - children: [JavaTestItem] = [] - ) { - self.id = id - self.label = label - self.fullName = fullName - self.projectName = projectName - self.kind = kind - self.level = level - self.jdtHandler = jdtHandler - self.sortText = sortText - self.range = range - self.children = children - } - - private enum CodingKeys: String, CodingKey { - case id, label, fullName, projectName, jdtHandler, sortText, range, children - case kind = "testKind" - case level = "testLevel" - } - - package func matches(identifier: String) -> Bool { - id == identifier || label == identifier || fullName == identifier || jdtHandler == identifier - } -} - -/// One `main` method JDT confirmed the JVM can launch, as normalized by Core. -/// -/// Note: 设计见 .agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md -package struct JavaMainMethod: Codable, Equatable, Sendable { - /// Matches the `mainClass` of the workspace entry point for the same file. - package let mainClass: String - package let projectName: String? - /// Zero-based UTF-16 range of the method name. - package let range: JavaTestRange - - package init(mainClass: String, projectName: String? = nil, range: JavaTestRange) { - self.mainClass = mainClass - self.projectName = projectName - self.range = range - } -} - -/// Core's `javaMainMethods` answer for one source file. -package struct JavaMainMethods: Codable, Equatable, Sendable { - package struct Diagnostic: Codable, Equatable, Sendable { - package let code: String - package let mainClass: String? - } - - package let schemaVersion: Int - package let methods: [JavaMainMethod] - package let diagnostics: [Diagnostic] - - package init(schemaVersion: Int = 1, methods: [JavaMainMethod], diagnostics: [Diagnostic] = []) { - self.schemaVersion = schemaVersion - self.methods = methods - self.diagnostics = diagnostics - } -} - -/// One IDEA-style editor gutter marker projected by Core's `java.runMarkers`. -package struct JavaRunMarker: Codable, Equatable, Sendable { - package enum Kind: String, Codable, Sendable { - case main - case testClass - case testMethod - } - - package enum Status: String, Codable, Sendable { - case none - case passed - case failed - case skipped - } - - /// Zero-based line of the declaration name. - package let line: Int - /// Last line of the declaration: body end for tests, name line for `main`. - package let endLine: Int - package let kind: Kind - /// Menu target such as `App.main()`, `OrderTest`, or `OrderTest.creates`. - package let label: String - package let mainClass: String? - package let projectName: String? - package let testClass: String? - package let testMethod: String? - package let testItemId: String? - package let status: Status - - package init( - line: Int, - endLine: Int, - kind: Kind, - label: String, - mainClass: String? = nil, - projectName: String? = nil, - testClass: String? = nil, - testMethod: String? = nil, - testItemId: String? = nil, - status: Status = .none - ) { - self.line = line - self.endLine = endLine - self.kind = kind - self.label = label - self.mainClass = mainClass - self.projectName = projectName - self.testClass = testClass - self.testMethod = testMethod - self.testItemId = testItemId - self.status = status - } - - /// Stable identity within one projection, used by editor bridges. - package var id: String { "\(kind.rawValue):\(line):\(label)" } - - /// The test identifier the Test workflow expects. Runs build a Maven - /// `-Dtest` selector (`Class#method`); debugging resolves the Java Test - /// item again, which matches its JDT `id` but not a parameterless name, - /// because JDT names methods `Class#method()` or `Class#method(Type)`. - package func testIdentifier(forDebugging: Bool) -> String? { - guard kind != .main, let testClass else { return nil } - if forDebugging, let testItemId { return testItemId } - if kind == .testMethod, let testMethod { return "\(testClass)#\(testMethod)" } - return testClass - } - - /// The marker a caret line refers to, following IDEA: the innermost test - /// method or class whose declaration contains the line, otherwise the - /// `main` on that line, otherwise the file's first `main`. - package static func forLine(_ line: Int, in markers: [JavaRunMarker]) -> JavaRunMarker? { - var enclosing: JavaRunMarker? - for marker in markers where marker.kind != .main && marker.line <= line && line <= marker.endLine { - if let current = enclosing, - marker.line < current.line || (marker.line == current.line && marker.kind != .testMethod) { - continue - } - enclosing = marker - } - if let enclosing { return enclosing } - let mains = markers.filter { $0.kind == .main } - return mains.first { $0.line == line } ?? mains.first - } -} - -/// Core's normalized Java Test discovery answer. -package struct JavaTestItems: Codable, Equatable, Sendable { - package struct Diagnostic: Codable, Equatable, Sendable { - package let code: String - package let detail: String? - } - - package let schemaVersion: Int - package let items: [JavaTestItem] - package let diagnostics: [Diagnostic] - - package init( - schemaVersion: Int = 1, - items: [JavaTestItem], - diagnostics: [Diagnostic] = [] - ) { - self.schemaVersion = schemaVersion - self.items = items - self.diagnostics = diagnostics - } } /// Server-normalized semantic tokens use zero-based UTF-16 positions. @@ -782,18 +527,6 @@ package struct LanguageServerInfo: Equatable, Sendable { } } -package struct MavenProfileProjectResult: Equatable, Sendable { - package let projectURI: URL - package let status: String - package let errorDetails: String? - - package init(projectURI: URL, status: String, errorDetails: String? = nil) { - self.projectURI = projectURI - self.status = status - self.errorDetails = errorDetails - } -} - package struct LanguageServerTextEdit: Equatable, Sendable { package let range: LanguageServerRange package let newText: String @@ -851,15 +584,10 @@ package protocol LanguageServerSession: AnyObject { /// attempt before launch or hands it to Core with the start request. /// 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 } - /// Packaged Java Test runner, if this JDT LS session was launched with one. - var javaTestRunnerURL: URL? { get } var onDiagnostics: ((URL, [LanguageServerDiagnostic]) -> Void)? { get set } var onCoreLog: ((CoreLogRecord) -> Void)? { get set } var onLog: ((LanguageServerLogLevel, String, String?, String?) -> Void)? { get set } @@ -873,29 +601,7 @@ package protocol LanguageServerSession: AnyObject { var serverInfo: LanguageServerInfo? { get } var onServerInfoChange: ((LanguageServerInfo?) -> Void)? { get set } /// Start the language server for the given workspace root. - /// - Parameter workspaceFingerprint: An opaque digest of the workspace's - /// build-system structure. When non-nil, JDT LS uses a per-fingerprint - /// state directory so structural changes (add/remove module, edit root - /// pom.xml) never reuse a stale project model. - func start(rootURL: URL, workspaceFingerprint: String?) throws - func start( - rootURL: URL, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext? - ) throws - func start( - rootURL: URL, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration? - ) throws - func retryMavenProfiles() - /// Hands a changed Maven context to the running server. A failure means the - /// session cannot take it and should be restarted. - func updateMavenConfiguration( - _ context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result + func start(rootURL: URL) throws func synchronize(fileURL: URL, text: String, languageID: String) throws func notifyWorkspaceFilesChanged(_ changes: [LanguageServerWorkspaceFileChange]) throws func closeDocument(_ fileURL: URL) @@ -969,37 +675,28 @@ package protocol LanguageServerSession: AnyObject { uri: String, completion: @escaping (Result) -> Void ) throws - /// JDT's launchable classes in the session workspace, normalized by Core. - func javaEntrypoints( - completion: @escaping (Result) -> Void - ) throws - /// Awaited launch discovery owns cancellation of its queued Core operation. - func javaEntrypoints() async throws -> JavaEntrypoints - /// Prepares one saved source through Core's shared Java launch operation. - func prepareJavaLaunch(fileURL: URL, mainClass: String?) async throws -> JavaLaunchPreparation - /// Test classes and methods JDT reports for one source file. - func javaTestItems( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws - /// Launchable `main` methods JDT reports for one source file. - func javaMainMethods( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws - func javaNavigationMarkers( - fileURL: URL, - completion: @escaping (Result<[JavaNavigationMarker], Error>) -> Void - ) throws - func resolveJavaNavigation( - fileURL: URL, - marker: JavaNavigationMarker, - completion: @escaping (Result<[LanguageServerLocation], Error>) -> Void - ) throws /// Sends a `lithe/build/*` request Core planned and returns the reply /// undecoded. Cancelling the task cancels the request in the process. func buildRequest(method: String, params: ToolingJSONValue, timeout: TimeInterval) async throws -> ToolingJSONValue + /// Sends one request of the owning plugin's backend to this server. These + /// two are requirements, not just extension defaults: the manager holds + /// sessions as `any LanguageServerSession`, and an extension-only method + /// is dispatched statically to the default that refuses every call. + func requestPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue, + timeout: TimeInterval? + ) async -> Result + /// Sends one notification of the owning plugin's backend to this server. + func notifyPluginServer( + pluginID: String, + serverID: String, + method: String, + params: ToolingJSONValue + ) async -> Result /// Replaces the configuration a plugin's server reads through /// `workspace/configuration` and announces it; false when the session /// cannot take it, so the caller offers a restart instead. @@ -1106,60 +803,13 @@ package extension LanguageServerSession { func semanticTokens(fileURL: URL, completion: @escaping (Result) -> Void) throws { completion(.success(.empty)) } - var onProjectPreparation: ((ProjectPreparationSnapshot) -> Void)? { - get { nil } - set {} - } var onPluginServerNotification: ((PluginServerNotification) -> Void)? { get { nil } set {} } - var onMavenProfileTask: ((String) -> Void)? { - get { nil } - set {} - } - var onMavenProfileProject: ((MavenProfileProjectResult) -> Void)? { - get { nil } - set {} - } - func retryMavenProfiles() {} - - func updateMavenConfiguration( - _: MavenLaunchContext, - reloadProjects _: Bool - ) -> Result { - .failure(LanguageServerRuntimeFailure( - code: "unsupported", - message: "This language session cannot update Maven settings in place." - )) - } - - func start( - rootURL: URL, - workspaceFingerprint: String?, - mavenContext _: MavenLaunchContext? - ) throws { - try start(rootURL: rootURL, workspaceFingerprint: workspaceFingerprint) - } - - func start( - rootURL: URL, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration? - ) throws { - guard javaGradle == nil else { - throw LanguageServerRuntimeFailure(code: "unsupported", message: "This language session cannot apply Gradle import settings.") - } - try start(rootURL: rootURL, workspaceFingerprint: workspaceFingerprint, mavenContext: mavenContext) - } } package extension LanguageServerSession { - func prepareJavaLaunch(fileURL _: URL, mainClass _: String?) async throws -> JavaLaunchPreparation { - throw LanguageServerRuntimeFailure(code: "not_supported", message: L10n.string("Java launch preparation is not supported by this runtime.")) - } - func executeReturningValue(_ command: LanguageServerCommand, fileURL: URL) async throws -> ToolingJSONValue { try Task.checkCancellation() let (stream, continuation) = AsyncThrowingStream.makeStream() @@ -1211,15 +861,6 @@ package extension LanguageServerSession { } } var serverInfo: LanguageServerInfo? { nil } - func javaEntrypoints() async throws -> JavaEntrypoints { - try Task.checkCancellation() - let value: JavaEntrypoints = try await withCheckedThrowingContinuation { continuation in - do { try javaEntrypoints { continuation.resume(with: $0) } } - catch { continuation.resume(throwing: error) } - } - try Task.checkCancellation() - return value - } var onServerInfoChange: ((LanguageServerInfo?) -> Void)? { get { nil } set {} @@ -1227,45 +868,6 @@ package extension LanguageServerSession { func closeDocument(_: URL) {} func notifyDocumentSaved(_: URL, text _: String) throws {} func notifyWorkspaceFilesChanged(_: [LanguageServerWorkspaceFileChange]) throws {} - func javaTestItems( - fileURL _: URL, - completion: @escaping (Result) -> Void - ) throws { - completion(.failure(LanguageServerFeatureUnavailable.javaTests)) - } - func javaMainMethods( - fileURL _: URL, - completion: @escaping (Result) -> Void - ) throws { - completion(.failure(LanguageServerFeatureUnavailable.javaMainMethods)) - } - func javaNavigationMarkers( - fileURL _: URL, - completion: @escaping (Result<[JavaNavigationMarker], Error>) -> Void - ) throws { - completion(.failure(LanguageServerFeatureUnavailable.javaNavigation)) - } - func resolveJavaNavigation( - fileURL _: URL, - marker _: JavaNavigationMarker, - completion: @escaping (Result<[LanguageServerLocation], Error>) -> Void - ) throws { - completion(.failure(LanguageServerFeatureUnavailable.javaNavigation)) - } -} - -private enum LanguageServerFeatureUnavailable: LocalizedError { - case javaNavigation - case javaTests - case javaMainMethods - - var errorDescription: String? { - switch self { - case .javaNavigation: L10n.string("Java navigation is not supported by this language server.") - case .javaTests: L10n.string("Java test discovery is not supported by this language server.") - case .javaMainMethods: L10n.string("Java main-method discovery is not supported by this language server.") - } - } } @MainActor diff --git a/macos/Sources/LitheCoreContracts/Output/OutputTimestamper.swift b/macos/Sources/LitheCoreContracts/Output/OutputTimestamper.swift index 0ed463062f..ff5c785970 100644 --- a/macos/Sources/LitheCoreContracts/Output/OutputTimestamper.swift +++ b/macos/Sources/LitheCoreContracts/Output/OutputTimestamper.swift @@ -2,10 +2,10 @@ import Foundation /// Prefixes streamed process output with the time each line was received. /// -/// Maven and most build tools emit `[INFO]`/`[ERROR]` lines with no clock at -/// all, which makes "when did this stall" unanswerable from the log alone. -/// Spring Boot already prints its own timestamp, so those lines are left -/// untouched rather than carrying two clocks. +/// Many build tools emit `[INFO]`/`[ERROR]` lines with no clock at all, which +/// makes "when did this stall" unanswerable from the log alone. Tools that +/// already print their own timestamp are left untouched rather than carrying +/// two clocks. package enum OutputTimestamper { private static let formatter: DateFormatter = { let formatter = DateFormatter() @@ -16,7 +16,7 @@ package enum OutputTimestamper { /// Matches a leading clock in the shapes tools actually emit: bare /// `10:12:33`, ISO `2026-08-08T10:12:33.123`, and the space-separated - /// variant Spring Boot uses. + /// variant `2026-08-08 10:12:33.123`. private static let leadingTimeExpression = try! NSRegularExpression( pattern: #"^\s*(?:\d{4}-\d{2}-\d{2}[T ])?\d{2}:\d{2}:\d{2}"# ) diff --git a/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift b/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift index c04a6da42f..cc83802581 100644 --- a/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift +++ b/macos/Sources/LitheCoreContracts/Plugins/DeclarativePluginContracts.swift @@ -61,10 +61,6 @@ public struct DeclarativeLanguageServer: Equatable, Sendable { /// True from plugin API 2 on, where arguments are launch templates that /// Rust Core expands with host directories before the server starts. public let expandsLaunchTemplates: Bool - /// Native host integration the server declares, such as `jdt`. The host - /// 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. @@ -136,6 +132,11 @@ public struct DeclarativeLanguageServerLaunchSource: Hashable, Sendable { /// 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 + /// True when the launch plan names a tool definition (`launch.kind` + /// `tool`): the host resolves that tool when the server starts and Rust + /// Core places the entry and arguments by the template of the definition, + /// so there is no executable to look up beforehand either. + public var launchesThroughTool: 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? @@ -146,7 +147,8 @@ public struct DeclarativeLanguageServerLaunchSource: Hashable, Sendable { manifest: Data, packageURL: URL, resolvesLaunchWithBackend: Bool = false, - stateRetention: DeclarativeLanguageServer.StateRetention? = nil + stateRetention: DeclarativeLanguageServer.StateRetention? = nil, + launchesThroughTool: Bool = false ) { self.pluginID = pluginID self.languageID = languageID @@ -154,6 +156,7 @@ public struct DeclarativeLanguageServerLaunchSource: Hashable, Sendable { self.packageURL = packageURL self.resolvesLaunchWithBackend = resolvesLaunchWithBackend self.stateRetention = stateRetention + self.launchesThroughTool = launchesThroughTool } } @@ -483,20 +486,60 @@ public struct DeclarativeLanguageServerLaunchPlan: Equatable, Sendable { public struct RuntimeRequirement: Equatable, Sendable { public let tool: String public let minimumVersion: String? + /// True when Core marks the requirement `kind` `tool`: the host resolves + /// it through a tool definition instead of its closed runtime list. + public let resolvesThroughDefinition: Bool - public init(tool: String, minimumVersion: String?) { + public init(tool: String, minimumVersion: String?, resolvesThroughDefinition: Bool = false) { self.tool = tool self.minimumVersion = minimumVersion + self.resolvesThroughDefinition = resolvesThroughDefinition } } - /// Complete argument list after the executable. + /// A process that names a tool definition (`launch.kind` `tool`). The host + /// resolves the tool through its definition, or runs the packaged runtime, + /// and Rust Core places every value below by the definition's `launch` + /// template, so the host never adds or orders arguments itself. + public struct ToolLaunch: Equatable, Sendable { + /// ID of the tool definition the process runs with. + public let tool: String + /// Absolute path of the entry file inside the installed package. + public let entry: String + /// Values for `${runtimeArguments}`, already expanded by Rust Core. + public let runtimeArguments: [String] + /// Lowest version of the tool the process accepts. + public let minimumVersion: String? + /// Package-relative runtime the plugin ships for this platform; when + /// present the host runs this file instead of looking the tool up. + public let packagedRuntime: String? + + public init( + tool: String, + entry: String, + runtimeArguments: [String], + minimumVersion: String?, + packagedRuntime: String? + ) { + self.tool = tool + self.entry = entry + self.runtimeArguments = runtimeArguments + self.minimumVersion = minimumVersion + self.packagedRuntime = packagedRuntime + } + } + + /// Complete argument list after the executable. For a tool launch this + /// holds only the plugin's own arguments, which fill `${arguments}`. public let arguments: [String] public let validationArguments: [String] public let initializationOptions: ToolingJSONValue? /// What the server reads through `workspace/configuration`, expanded with /// the current settings; `nil` when the server declares none. public var workspaceConfiguration: ToolingJSONValue? = nil + /// The tool-definition launch, or nil when the process starts a packaged + /// file, a system command or a closed-list runtime. + public var toolLaunch: ToolLaunch? = nil /// A declared host integration with its package-relative resource paths. public struct HostIntegration: Equatable, Sendable { public let id: String @@ -810,7 +853,6 @@ public struct DeclarativePluginDescriptor: Equatable, Sendable { validationArguments: server.validationArguments, runtimeTools: server.runtimeDependencies.map(\.tool), expandsLaunchTemplates: decoded.pluginAPIVersion >= 2, - hostIntegrationID: server.hostIntegration?.id, stateRetention: server.state?.retention.map { DeclarativeLanguageServer.StateRetention(maxEntries: $0.maxEntries, maxAgeDays: $0.maxAgeDays) } diff --git a/macos/Sources/LitheCoreContracts/Workspace/NaturalNameOrder.swift b/macos/Sources/LitheCoreContracts/Workspace/NaturalNameOrder.swift index 6a835feb2c..0fe973bf11 100644 --- a/macos/Sources/LitheCoreContracts/Workspace/NaturalNameOrder.swift +++ b/macos/Sources/LitheCoreContracts/Workspace/NaturalNameOrder.swift @@ -34,7 +34,7 @@ package enum NaturalNameOrder { /// The upstream natural-name comparator compares digit runs without an /// integer conversion, including leading-zero length and a case tie-break. - /// UTF-16 preserves Java's ordering for supplementary characters as well. + /// UTF-16 code units preserve the upstream ordering for supplementary characters as well. /// `likeFileNames` ranks `-` next to `_` (IDEA-80435). package static func compare( _ a: [UInt16], @@ -117,13 +117,13 @@ package enum NaturalNameOrder { } private static func caseUnit(_ value: UInt16, uppercase: Bool) -> UInt16 { - // U+0130 has a two-scalar full lowercase mapping, but Java Character - // uses its simple mapping to U+0069. + // U+0130 has a two-scalar full lowercase mapping, but the upstream + // per-character mapping uses its simple mapping to U+0069. if !uppercase && value == 0x0130 { return 0x0069 } guard let scalar = UnicodeScalar(value) else { return value } let string = String(scalar) let mapped = Array((uppercase ? string.uppercased() : string.lowercased()).utf16) - // Java Character mappings stay one UTF-16 unit, never expand a letter. + // The upstream per-character mappings stay one UTF-16 unit, never expand a letter. return mapped.count == 1 ? mapped[0] : value } } diff --git a/macos/Sources/LitheDebugModule/Application/DebugBreakpointLocationValidator.swift b/macos/Sources/LitheDebugModule/Application/DebugBreakpointLocationValidator.swift index da85a991cf..c468d9df2e 100644 --- a/macos/Sources/LitheDebugModule/Application/DebugBreakpointLocationValidator.swift +++ b/macos/Sources/LitheDebugModule/Application/DebugBreakpointLocationValidator.swift @@ -1,7 +1,7 @@ import Foundation -/// Placement is distinct from binding: the adapter owns Java syntax and bytecode -/// locations, including brace and declaration lines that may never suspend. +/// Placement is distinct from binding: the adapter owns language syntax and +/// executable-location rules, including brace and declaration lines that may never suspend. public enum DebugBreakpointLocationValidator { public static func canSetSourceBreakpoint(source: String, line: Int) -> Bool { line > 0 && line <= source.components(separatedBy: .newlines).count diff --git a/macos/Sources/LitheDebugModule/Application/GenericDebugFeatureModel.swift b/macos/Sources/LitheDebugModule/Application/GenericDebugFeatureModel.swift index 6fb1e788ff..c4b18c81c8 100644 --- a/macos/Sources/LitheDebugModule/Application/GenericDebugFeatureModel.swift +++ b/macos/Sources/LitheDebugModule/Application/GenericDebugFeatureModel.swift @@ -215,54 +215,12 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu @Published public private(set) var serviceUpdateMessage: String? @Published public private(set) var serviceUpdateFailed = false @Published public private(set) var updatingServiceSessionID: DebugSessionID? - private var javaUpdateTargets: [DebugSessionID: JavaDebugLaunchTarget] = [:] /// Sessions whose cleanup already ran, so re-entrant state callbacks cannot repeat it. private var forgottenSessionIDs: Set = [] - public func registerJavaUpdateTarget(_ target: JavaDebugLaunchTarget) { - guard let id = activeSessionID else { return } - javaUpdateTargets[id] = target - } - - public var canUpdateJavaService: Bool { - guard let id = activeSessionID else { return false } - return providerID == "java" && canControl && javaUpdateTargets[id] != nil - && !adapterDeclaredCodeChanges - } - - public func applyJavaServiceUpdate( - prepare: (JavaDebugLaunchTarget, URL, URL) async throws -> Void - ) async { - guard updatingServiceSessionID == nil, canUpdateJavaService, - let id = activeSessionID, let target = javaUpdateTargets[id], - let request = lastStartRequest, let session = activeSession else { return } - updatingServiceSessionID = id - serviceUpdateFailed = false - serviceUpdateMessage = "Saving and compiling code changes…" - defer { updatingServiceSessionID = nil } - do { - try await prepare(target, request.fileURL, request.rootURL) - guard activeSessionID == id, isSessionActive else { return } - serviceUpdateMessage = "Applying code changes…" - let classes: [String] = try await withCheckedThrowingContinuation { continuation in - session.redefineClasses { continuation.resume(with: $0) } - } - guard activeSessionID == id, isSessionActive else { return } - serviceUpdateMessage = classes.isEmpty ? "No code changes to apply." : "Code changes applied." - append((serviceUpdateMessage ?? "") + "\n") - if state == .paused { inspectThreads() } - } catch { - guard activeSessionID == id, isSessionActive else { return } - serviceUpdateFailed = true - serviceUpdateMessage = "Could not apply changes: " + error.localizedDescription - + " Restart the service if this change is not supported." - append((serviceUpdateMessage ?? "") + "\n") - } - } - /// Whether the active session's adapter declared a way to apply changed code to the running - /// program (`features.hotCodeReplace`). The declaration wins over the host's own service - /// update, which only remains for adapters that declared nothing, so one button shows. + /// program (`features.hotCodeReplace`). Only that declaration enables the action; the host + /// never infers it from the adapter's name. public var canApplyDeclaredCodeChanges: Bool { canControl && adapterDeclaredCodeChanges } @@ -304,41 +262,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu } } - /// Explicit restart preserves the original launch options and re-resolves runtime paths. - public func restartJavaService( - prepare: (URL, URL) async throws -> JavaDebugLaunchTarget - ) async { - guard updatingServiceSessionID == nil, canUpdateJavaService, - let id = activeSessionID, let request = lastStartRequest else { return } - updatingServiceSessionID = id - serviceUpdateFailed = false - serviceUpdateMessage = "Preparing service restart…" - defer { updatingServiceSessionID = nil } - do { - let target = try await prepare(request.fileURL, request.rootURL) - guard activeSessionID == id, isSessionActive else { return } - var arguments = request.configuration.arguments - arguments["mainClass"] = .string(target.mainClass) - arguments["projectName"] = target.projectName.map(ToolingJSONValue.string) - arguments["classPaths"] = .array(target.classPaths.map(ToolingJSONValue.string)) - arguments["modulePaths"] = .array(target.modulePaths.map(ToolingJSONValue.string)) - stop() - // stop() may select another live session; do not stop that replacement too. - if startAdditional(fileURL: request.fileURL, rootURL: request.rootURL, - configuration: DebugLaunchConfiguration( - name: request.configuration.name, request: request.configuration.request, - arguments: arguments, steppingFilters: request.configuration.steppingFilters, - adapterProviderID: request.configuration.adapterProviderID, - adapterEndpoint: request.configuration.adapterEndpoint)) { - registerJavaUpdateTarget(target) - } - } catch { - guard activeSessionID == id, isSessionActive else { return } - serviceUpdateFailed = true - serviceUpdateMessage = "Could not restart service: " + error.localizedDescription - } - } - @Published public private(set) var providerID: String? @Published public private(set) var activeSessionID: DebugSessionID? { didSet { @@ -392,7 +315,9 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu /// The frame currently selected in the call stack, which may differ from /// the frame that initially caused the stop. @Published public private(set) var selectedFrame: DebugStackFrame? - @Published public private(set) var javaSteppingFilters: DebugSteppingFilters? + /// Effective stepping policy of each live session, used to decide whether + /// filtered frames collapse. Sessions without an entry use their adapter's defaults. + private var steppingFiltersBySession: [DebugSessionID: DebugSteppingFilters] = [:] @Published public private(set) var consoleHistory: [String] = [] @Published public private(set) var areFilteredStackFramesExpanded = false /// Prevents overlapping execution requests while the adapter is still @@ -572,7 +497,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu ) } } - loadJavaSteppingFilters() } public var isSessionActive: Bool { @@ -587,9 +511,9 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu public var canControl: Bool { state == .running || state == .paused } public var canRestart: Bool { - // Some Java adapters (notably older JDT LS builds) do not advertise - // DAP `restart`. We can still provide the IDEA-style rerun action by - // relaunching the exact saved request after stopping this session. + // Some adapters do not advertise DAP `restart`. The rerun action is + // still offered by relaunching the exact saved request after + // stopping this session. canControl && (capabilities.supportsRestartRequest || lastStartRequest != nil) } public var canTerminate: Bool { @@ -613,7 +537,7 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu return rows } /// Root-scope values plus source-referenced expressions evaluated for the - /// selected frame, matching the compact variable list used by Java IDEs. + /// selected frame, matching the compact variable list of an IDE. public var presentedVariables: [DebugVariable] { var knownNames = Set() var result: [DebugVariable] = [] @@ -624,8 +548,7 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu return result } public var visibleStackFrameRows: [GenericDebugStackFrameRow] { - guard javaSteppingFilters?.hideFilteredStackFrames == true, - !areFilteredStackFramesExpanded else { + guard activeSteppingFiltersHideFrames, !areFilteredStackFramesExpanded else { return stackFrames.map(stackFrameRow) } var rows: [GenericDebugStackFrameRow] = [] @@ -737,7 +660,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu /// Stops one session. Inactive sessions do not disturb the currently /// displayed debugger state. public func stopSession(_ sessionID: DebugSessionID) { - javaUpdateTargets[sessionID] = nil if activeSessionID == sessionID { stop() return @@ -752,7 +674,7 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu private func forgetStoppedSession(_ sessionID: DebugSessionID) { guard forgottenSessionIDs.insert(sessionID).inserted else { return } - javaUpdateTargets[sessionID] = nil + steppingFiltersBySession[sessionID] = nil sessionSnapshots[sessionID] = nil disassembly.forget(sessionID: sessionID) onSessionStopped?(sessionID) @@ -844,19 +766,17 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu if !dataBreakpoints.isEmpty { try sessions.setDataBreakpoints(coreDataBreakpoints, for: request.fileURL, adapterProviderID: providerID) } - let effectiveConfiguration: DebugLaunchConfiguration - if providerID == "java", let javaSteppingFilters { - effectiveConfiguration = request.configuration.applying( - steppingFilters: javaSteppingFilters - ) - } else { - effectiveConfiguration = request.configuration - } + let effectiveConfiguration = configurationApplyingSavedSteppingFilters( + request.configuration, providerID: providerID + ) let launched = try sessions.launchNew( for: request.fileURL, rootURL: request.rootURL, configuration: effectiveConfiguration ) + if let filters = effectiveConfiguration.steppingFilters { + steppingFiltersBySession[launched.id] = filters + } activeSessionID = launched.id state = launched.session.state sessionSummaries = sessions.sessionSummaries @@ -882,7 +802,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu } public func stop() { - if let id = activeSessionID { javaUpdateTargets[id] = nil } serviceUpdateMessage = nil serviceUpdateFailed = false invalidateInspectionRequests() @@ -930,8 +849,8 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu } public func reset() { - javaUpdateTargets.removeAll() forgottenSessionIDs.removeAll() + steppingFiltersBySession.removeAll() serviceUpdateMessage = nil serviceUpdateFailed = false invalidateInspectionRequests() @@ -1349,31 +1268,80 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu } } - public func updateJavaSteppingFilters(_ filters: DebugSteppingFilters) { + /// Debuggers whose adapters declared `features.stepFilters`, one entry per + /// adapter even when a language default also selects it. + public var steppingFilterProviders: [DebugProviderDeclaration] { + var seen = Set() + return sessions.providers.compactMap { descriptor in + guard let declaration = sessions.declarationSource?(descriptor), + declaration.behavior.features?.stepFilters != nil, + seen.insert(declaration.storageKey).inserted else { return nil } + return declaration + } + } + + /// The user's saved policy for one debugger, or the defaults its adapter declared. + public func steppingFilters(for declaration: DebugProviderDeclaration) -> DebugSteppingFilters { + let defaults = DebugSteppingFilters(declared: declaration.behavior.defaults?.stepFilters) + do { + guard let saved = try steppingFilterPersistence?.loadSteppingFilters( + adapterID: declaration.storageKey + ) else { return defaults } + return try steppingFilterResolver?.resolveDebugSteppingFilters( + adapterID: declaration.storageKey, filters: saved + ) ?? saved + } catch { + record(error) + return defaults + } + } + + public func updateSteppingFilters(_ filters: DebugSteppingFilters, for declaration: DebugProviderDeclaration) { do { let normalized = try steppingFilterResolver?.resolveDebugSteppingFilters( - adapterID: "java", + adapterID: declaration.storageKey, filters: filters ) ?? filters - javaSteppingFilters = normalized areFilteredStackFramesExpanded = false - try steppingFilterPersistence?.saveSteppingFilters(normalized, adapterID: "java") + try steppingFilterPersistence?.saveSteppingFilters(normalized, adapterID: declaration.storageKey) } catch { record(error) } } - public func resetJavaSteppingFilters() { - guard let steppingFilterResolver else { return } + public func resetSteppingFilters(for declaration: DebugProviderDeclaration) { + updateSteppingFilters( + DebugSteppingFilters(declared: declaration.behavior.defaults?.stepFilters), + for: declaration + ) + } + + /// A launch without its own policy takes the user's saved one for that + /// debugger; with nothing saved, Core sends the adapter's declared defaults. + private func configurationApplyingSavedSteppingFilters( + _ configuration: DebugLaunchConfiguration, + providerID: String? + ) -> DebugLaunchConfiguration { + guard configuration.steppingFilters == nil, + let providerID, + let declaration = sessions.declaration(forProviderID: providerID), + declaration.behavior.features?.stepFilters != nil else { return configuration } + let saved: DebugSteppingFilters? do { - let defaults = try steppingFilterResolver.resolveDebugSteppingFilters( - adapterID: "java", - filters: nil - ) - updateJavaSteppingFilters(defaults) + saved = try steppingFilterPersistence?.loadSteppingFilters(adapterID: declaration.storageKey) } catch { record(error) + saved = nil + } + guard let saved else { return configuration } + return configuration.applying(steppingFilters: saved) + } + + private var activeSteppingFiltersHideFrames: Bool { + if let activeSessionID, let filters = steppingFiltersBySession[activeSessionID] { + return filters.hideFilteredStackFrames } + return activeSession?.declaredBehavior.defaults?.stepFilters?.hideFilteredStackFrames == true } public func expandFilteredStackFrames() { @@ -1578,8 +1546,8 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu ) } - /// Evaluates identifiers referenced by the paused source line so fields - /// such as Java's `service` appear beside locals and as editor inlays. + /// Evaluates identifiers referenced by the paused source line so values + /// the adapter does not list as locals appear beside them and as editor inlays. public func requestAutomaticVariables(_ expressions: [String]) { guard state == .paused, let frameID = selectedFrameID, @@ -1614,7 +1582,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu evaluateAutomaticVariable( expression, evaluatedExpression: expression, - allowsJavaFieldFallback: true, orderedExpressions: orderedExpressions, frameID: frameID, generation: generation, @@ -1626,7 +1593,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu private func evaluateAutomaticVariable( _ expression: String, evaluatedExpression: String, - allowsJavaFieldFallback: Bool, orderedExpressions: [String], frameID: Int, generation: Int, @@ -1656,24 +1622,10 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu ) self.publishAutomaticVariables(orderedExpressions) case .failure: - if allowsJavaFieldFallback, - self.providerID == "java", - !expression.contains(".") { - self.evaluateAutomaticVariable( - expression, - evaluatedExpression: "this.\(expression)", - allowsJavaFieldFallback: false, - orderedExpressions: orderedExpressions, - frameID: frameID, - generation: generation, - session: session - ) - } else { - // Source-driven evaluation is speculative. Invalid - // candidates should not flood the user's Debug Console. - self.automaticExpressionResults.removeValue(forKey: expression) - self.publishAutomaticVariables(orderedExpressions) - } + // Source-driven evaluation is speculative. Invalid + // candidates should not flood the user's Debug Console. + self.automaticExpressionResults.removeValue(forKey: expression) + self.publishAutomaticVariables(orderedExpressions) } } } @@ -2029,9 +1981,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu let normalized = debuggeeOutputNormalizer.normalize(rawOutput) guard !normalized.isEmpty else { return } append(normalized) - if let diagnostic = launchDiagnostic(in: normalized) { - errorMessage = diagnostic - } } private func resetInspectionState() { @@ -2413,8 +2362,8 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu clearStoppedInspection() } - /// Prefer a source-backed, unfiltered frame after a stop so Java's - /// synthetic reflection and method-handle frames do not become the user's + /// Prefer a source-backed, unfiltered frame after a stop so runtime-internal + /// frames the adapter marks as filtered do not become the user's /// initial inspection location. The full stack remains available and can /// still be expanded from the filtered-frame group. private func preferredStoppedFrame(in frames: [DebugStackFrame]) -> DebugStackFrame? { @@ -2444,42 +2393,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu return inspectionGeneration } - private func loadJavaSteppingFilters() { - guard let steppingFilterResolver else { return } - let persisted: DebugSteppingFilters? - do { - persisted = try steppingFilterPersistence?.loadSteppingFilters(adapterID: "java") - } catch { - record(error) - loadDefaultJavaSteppingFilters(using: steppingFilterResolver) - return - } - do { - javaSteppingFilters = try steppingFilterResolver.resolveDebugSteppingFilters( - adapterID: "java", - filters: persisted - ) - } catch { - record(error) - if persisted != nil { - loadDefaultJavaSteppingFilters(using: steppingFilterResolver) - } - } - } - - private func loadDefaultJavaSteppingFilters( - using steppingFilterResolver: any DebugSteppingFilterResolving - ) { - do { - javaSteppingFilters = try steppingFilterResolver.resolveDebugSteppingFilters( - adapterID: "java", - filters: nil - ) - } catch { - record(error) - } - } - private func stackFrameRow(_ frame: DebugStackFrame) -> GenericDebugStackFrameRow { GenericDebugStackFrameRow( id: "frame-\(frame.id)", @@ -3022,20 +2935,6 @@ public final class GenericDebugFeatureModel: ObservableObject, GenericDebugFeatu outputPresentation.replace(with: text) } - private func launchDiagnostic(in output: String) -> String? { - let pattern = #"(?i)\bport\s+(\d{1,5})\s+was already in use\b"# - guard let expression = try? NSRegularExpression(pattern: pattern), - let match = expression.firstMatch( - in: output, - range: NSRange(output.startIndex..., in: output) - ), - let portRange = Range(match.range(at: 1), in: output) else { - return nil - } - let port = output[portRange] - return "Port \(port) is already in use. Stop the process using it or change server.port in the Run configuration." - } - /// Trim only at complete SGR boundaries and replay the retained text's style. private func trimOutput(_ output: inout String) { let count = output.count diff --git a/macos/Sources/LitheDebugModule/Runtime/DebugAdapterSessionManager.swift b/macos/Sources/LitheDebugModule/Runtime/DebugAdapterSessionManager.swift index b204eadcb1..00d1596906 100644 --- a/macos/Sources/LitheDebugModule/Runtime/DebugAdapterSessionManager.swift +++ b/macos/Sources/LitheDebugModule/Runtime/DebugAdapterSessionManager.swift @@ -57,6 +57,20 @@ public struct DebugSessionHandle { } } +/// The adapter declaration behind one debug provider, keyed by the adapter's +/// stable registry identity rather than by whichever descriptor selected it. +public struct DebugProviderDeclaration: Equatable, Sendable { + public let storageKey: String + public let displayName: String + public let behavior: DebugAdapterDeclaredBehavior + + public init(storageKey: String, displayName: String, behavior: DebugAdapterDeclaredBehavior) { + self.storageKey = storageKey + self.displayName = displayName + self.behavior = behavior + } +} + /// Owns every DAP session, breakpoint projection, and debug callback. /// /// This is deliberately separate from `LanguageToolingSessionManager`: an LSP @@ -116,6 +130,12 @@ public final class DebugAdapterSessionManager: ObservableObject { DebugProviderDescriptor, DebugAdapterEndpoint, URL ) throws -> (any DebugAdapterSession)?)? + /// What a provider's adapter declared, read without starting a session so + /// settings that apply to the next session can be edited first. Several + /// descriptors (a language default and the adapter's own qualified + /// identity) can share one declaration; its `storageKey` is that identity. + public var declarationSource: (@MainActor (DebugProviderDescriptor) -> DebugProviderDeclaration?)? + /// Read at every lookup: a host that registers debug adapters while it /// runs hands back the current set instead of the one it started with. private let providersSource: @MainActor () -> [DebugProviderDescriptor] @@ -180,6 +200,13 @@ public final class DebugAdapterSessionManager: ObservableObject { providersSource().first { $0.id == id } } + /// Every current registration, in the order lookups consult them. + public var providers: [DebugProviderDescriptor] { providersSource() } + + public func declaration(forProviderID id: String) -> DebugProviderDeclaration? { + provider(id: id).flatMap { declarationSource?($0) } + } + @discardableResult public func activate(for fileURL: URL, rootURL: URL, adapterProviderID: String? = nil) throws -> any DebugAdapterSession { let descriptor = try descriptor(for: fileURL, adapterProviderID: adapterProviderID) diff --git a/macos/Sources/LitheExecutionModule/Application/BuildSystemsFeatureModel.swift b/macos/Sources/LitheExecutionModule/Application/BuildSystemsFeatureModel.swift index 7a435e2922..7d37642f8d 100644 --- a/macos/Sources/LitheExecutionModule/Application/BuildSystemsFeatureModel.swift +++ b/macos/Sources/LitheExecutionModule/Application/BuildSystemsFeatureModel.swift @@ -35,14 +35,11 @@ package final class BuildSystemsFeatureModel: ObservableObject { package var hasActiveWork: Bool { service.hasActiveWork } package var hasBuildSystemPlugins: Bool { service.hasBuildSystemPlugins } package var workspaceURL: URL? { service.workspaceURL } - package var languageImport: JavaLanguageImportConfiguration? { service.languageImport } + /// True once the current workspace detection finished and normalized its options. + package var isDetectionSettled: Bool { service.isDetectionSettled } package var inputRevision: UInt64 { service.inputRevision } - package var onLanguageImportChanged: ((URL) -> Void)? { - get { service.onLanguageImportChanged } - set { service.onLanguageImportChanged = newValue } - } - package func prepareLanguageImport(workspaceURL: URL) async throws -> JavaLanguageImportConfiguration { - try await service.prepareLanguageImport(workspaceURL: workspaceURL) + package func awaitDetection(workspaceURL: URL) async throws { + try await service.awaitDetection(workspaceURL: workspaceURL) } package func entry(_ id: String) -> BuildSystemEntry? { service.entry(id) } @@ -98,15 +95,14 @@ package final class BuildSystemsFeatureModel: ObservableObject { try await service.prepareLanguageTestModels(selectorKind: selectorKind, reference: reference, workspace: workspace) } package func prepareRunGenerationModels(workspace: URL) async throws { - _ = try await service.prepareLanguageImport(workspaceURL: workspace) + try await service.awaitDetection(workspaceURL: workspace) try await service.prepareLanguageTestModels(allModels: true, workspace: workspace) - _ = try await service.prepareLanguageImport(workspaceURL: workspace) + try await service.awaitDetection(workspaceURL: workspace) } - @discardableResult package func prepareLanguageRun(fileURL: URL, workspace: URL, purpose: String, optionOverrides: [String: ToolingJSONValue] = [:], tool: @MainActor (String) throws -> BuildProviderHints? = { _ in nil }, - isCurrent: @escaping @MainActor () -> Bool) async throws -> BuildLanguageImport? { + isCurrent: @escaping @MainActor () -> Bool) async throws { try await service.prepareLanguageRun(fileURL: fileURL, workspace: workspace, purpose: purpose, optionOverrides: optionOverrides, tool: tool, isCurrent: isCurrent) } package func languageTestEntries(selectorKind: String, fileURL: URL?, workspace: URL) -> [BuildSystemEntry] { diff --git a/macos/Sources/LitheExecutionModule/Application/ExecutionFeatureModels.swift b/macos/Sources/LitheExecutionModule/Application/ExecutionFeatureModels.swift index a9126c6d80..bc61dc705c 100644 --- a/macos/Sources/LitheExecutionModule/Application/ExecutionFeatureModels.swift +++ b/macos/Sources/LitheExecutionModule/Application/ExecutionFeatureModels.swift @@ -12,44 +12,6 @@ package enum RunConfigurationGenerationIntent: Sendable { @MainActor package final class RunFeatureModel: ObservableObject { - @Published package private(set) var updatingServiceExecutionID: String? - @Published package private(set) var serviceUpdateMessage: String? - @Published package private(set) var serviceUpdateSessionID: String? - @Published package private(set) var serviceUpdateExecutionID: String? - - package func canUpdateService(_ session: RunSession) -> Bool { - guard session.isRunning, let target = session.javaUpdateTarget, - session.javaUpdateSource != nil else { return false } - return target.classPaths.contains { - URL(fileURLWithPath: $0).lastPathComponent.hasPrefix("spring-boot-devtools-") - && $0.hasSuffix(".jar") - } - } - - package func updateService( - _ session: RunSession, - build: (JavaDebugLaunchTarget, URL) async throws -> Void - ) async { - guard updatingServiceExecutionID == nil, canUpdateService(session), - let target = session.javaUpdateTarget, let source = session.javaUpdateSource else { return } - updatingServiceExecutionID = session.executionID - serviceUpdateSessionID = session.id - serviceUpdateExecutionID = session.executionID - serviceUpdateMessage = "Saving and compiling service changes…" - defer { updatingServiceExecutionID = nil } - func isCurrent() -> Bool { - moduleSessions.contains { $0.executionID == session.executionID && $0.isRunning } - } - do { - try await build(target, source) - guard isCurrent() else { serviceUpdateMessage = nil; return } - serviceUpdateMessage = "Compilation finished. Check service logs for the DevTools restart. If a trigger file is configured, update it to restart." - } catch { - guard isCurrent() else { serviceUpdateMessage = nil; return } - serviceUpdateMessage = "Could not update service: " + error.localizedDescription - } - } - private let service: RunService private var observation: AnyCancellable? @Published package var isGenerationConfirmationPresented = false @@ -101,14 +63,12 @@ package final class RunFeatureModel: ObservableObject { package var runningTitle: String? { service.runningTitle } package var output: String { service.output } package var lastExitCode: Int32? { service.lastExitCode } - package var mavenProfiles: [MavenProfile] { service.mavenProfiles } package var primaryExecutionID: String? { service.primaryExecutionID } package var providerDebugEnded: AnyPublisher { service.providerDebugEnded.eraseToAnyPublisher() } package func prepareProviderDebug(_ configuration: RunConfiguration, debug: @escaping @MainActor (String) throws -> BuildLaunchOptions.Debug, - languageImport: @escaping @MainActor (BuildLanguageImport) async throws -> Void = { _ in }, isCurrent: @escaping @MainActor @Sendable () -> Bool) async throws -> String { - try await service.prepareProviderDebug(configuration, debug: debug, languageImport: languageImport, isCurrent: isCurrent) + try await service.prepareProviderDebug(configuration, debug: debug, isCurrent: isCurrent) } package func isProviderDebugActive(_ operation: String) -> Bool { service.isProviderDebugActive(operation) } package func providerDebugProcessID(_ operation: String) -> Int32? { service.providerDebugProcessID(operation) } @@ -125,19 +85,15 @@ package final class RunFeatureModel: ObservableObject { package func pluginRunProcessID(_ runID: String) -> Int32? { service.pluginRunProcessID(runID) } package func stopPluginRun(_ runID: String) { service.stopPluginRun(runID) } package var moduleSessions: [RunSession] { service.moduleSessions } - package var portConflicts: [RunPortConflict] { service.portConflicts } package var configurationStatus: ProjectRunConfigurationStatus { service.configurationStatus } package var requiresConfigurationGeneration: Bool { service.requiresConfigurationGeneration } package var configurationDiagnostics: [RunConfigurationDiagnostic] { service.configurationDiagnostics } package var generationState: RunConfigurationGenerationState { service.generationState } - package var javaDiscoveryStatus: JavaDiscoveryStatus { service.javaDiscoveryStatus } package var projectLoadState: ProjectLoadState { service.projectLoadState } package func reportGenerationProjectNotReady() { service.reportGenerationProjectNotReady() } package var recoveryAction: RunConfigurationRecoveryAction { service.recoveryAction } package var recoveryPath: String? { service.recoveryPath } package var configurationSaveError: String? { service.configurationSaveError } - package var projectToolchain: ProjectToolchainSelection { service.projectToolchain } - package var savedProjectToolchain: ProjectToolchainSelection? { service.savedProjectToolchain } package var blockingToolchainDiagnostic: RunConfigurationDiagnostic? { service.blockingToolchainDiagnostic(for: service.selectedConfiguration) } @@ -180,24 +136,16 @@ package final class RunFeatureModel: ObservableObject { package func isProjectReady(for workspace: URL, snapshotID: UUID?) -> Bool { service.isProjectReady(for: workspace, snapshotID: snapshotID) } package func hasReadyInventory(for workspace: URL) -> Bool { service.hasReadyInventory(for: workspace) } - package func validateProviderGeneration(for configuration: RunConfiguration) throws { - try service.validateProviderGeneration(for: configuration) - } - package func options(for configuration: RunConfiguration) -> RunOptions { service.options(for: configuration) } - package func configuredServerPort(for configuration: RunConfiguration) -> Int? { - service.configuredServerPort(for: configuration) - } - package func source(for configuration: RunConfiguration) -> RunConfigurationSource { service.source(for: configuration) } - /// Applies the same selected configuration side effects used by Run, - /// including project-scoped Java runtime selection, before Debug starts. + /// Applies the same selected configuration side effects used by Run + /// before Debug starts. package func select(_ configuration: RunConfiguration) { service.select(configuration) } @@ -206,11 +154,6 @@ package final class RunFeatureModel: ObservableObject { service.serviceURL(for: configuration) } - @discardableResult - package func saveProjectToolchain(_ toolchain: ProjectToolchainSelection) -> Bool { - service.saveProjectToolchain(toolchain) - } - @discardableResult package func saveEditorChanges( _ options: RunOptions, @@ -228,15 +171,8 @@ package final class RunFeatureModel: ObservableObject { service.resetOptions(for: configuration) } - @discardableResult - package func createConfiguration(_ draft: RunConfigurationDraft) -> Bool { - service.createConfiguration(draft) - } - - package func runAllServices( - javaLaunches: [String: JavaDebugLaunchTarget] = [:] - ) { - service.runAllServices(javaLaunches: javaLaunches) + package func runAllServices() { + service.runAllServices() } package func stopAllServices() { @@ -267,17 +203,9 @@ package final class RunFeatureModel: ObservableObject { await service.loadProject(at: workspaceURL, files: files, snapshotID: snapshotID) } - /// Adds JDT's view of the generated Java entries to the Run diagnostics. - package func reportJavaEntrypointFreshness(_ entrypoints: JavaEntrypoints) async { - await service.reportJavaEntrypointFreshness(entrypoints) - } - - package func generateRunConfigurations( - javaDiscovery: JavaEntrypointDiscovery = .notJava, - automatic: Bool = false - ) async { + package func generateRunConfigurations(automatic: Bool = false) async { isGenerationConfirmationPresented = false - await service.generateRunConfigurations(javaDiscovery: javaDiscovery, automatic: automatic) + await service.generateRunConfigurations(automatic: automatic) } package func requestRunConfigurationGeneration(intent: RunConfigurationGenerationIntent = .identifyOnly) { @@ -297,20 +225,14 @@ package final class RunFeatureModel: ObservableObject { package func unregisterLanguageRunExtension(languageID: String) { service.unregisterLanguageRunExtension(languageID: languageID) } - package func runSelected( - currentFileURL: URL?, - javaLaunch: JavaDebugLaunchTarget? = nil - ) { - service.runSelected(currentFileURL: currentFileURL, javaLaunch: javaLaunch) + package func runSelected(currentFileURL: URL?) { + service.runSelected(currentFileURL: currentFileURL) } - package func startConfiguration( - _ configuration: RunConfiguration, - javaLaunch: JavaDebugLaunchTarget? = nil - ) { - service.startConfiguration(configuration, javaLaunch: javaLaunch) + package func startConfiguration(_ configuration: RunConfiguration) { + service.startConfiguration(configuration) } - package func restart(javaLaunch: JavaDebugLaunchTarget? = nil) { - service.restart(javaLaunch: javaLaunch) + package func restart() { + service.restart() } package func stop() { service.stop() } package func reset() { service.reset() } @@ -329,5 +251,3 @@ package final class ProjectDevelopmentFeatureModel { await runFeature.loadProject(at: workspaceURL, files: files, snapshotID: snapshotID) } } - -package typealias JavaRunFeatureModel = RunFeatureModel diff --git a/macos/Sources/LitheExecutionModule/Dependencies/RunServiceDependencyProvider.swift b/macos/Sources/LitheExecutionModule/Dependencies/RunServiceDependencyProvider.swift index ea0d2b4e75..d92df8c551 100644 --- a/macos/Sources/LitheExecutionModule/Dependencies/RunServiceDependencyProvider.swift +++ b/macos/Sources/LitheExecutionModule/Dependencies/RunServiceDependencyProvider.swift @@ -169,16 +169,6 @@ package struct RunServiceDependencyProvider: WorkspaceDependencyProvider { /// Compatibility fallback for providers without a language plugin manifest. /// A declared file list always takes precedence, including an empty list. private static let managementFileNames: [String: Set] = [ - "java": [ - "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", - "settings.gradle.kts", "gradle.properties", "libs.versions.toml", - "extensions.xml" - ], - "maven": ["pom.xml", "extensions.xml"], - "gradle": [ - "build.gradle", "build.gradle.kts", "settings.gradle", - "settings.gradle.kts", "gradle.properties", "libs.versions.toml" - ], "npm": [ "package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb" diff --git a/macos/Sources/LitheExecutionModule/Module/ExecutionFeatureGraph.swift b/macos/Sources/LitheExecutionModule/Module/ExecutionFeatureGraph.swift index 577262bffd..195c787c01 100644 --- a/macos/Sources/LitheExecutionModule/Module/ExecutionFeatureGraph.swift +++ b/macos/Sources/LitheExecutionModule/Module/ExecutionFeatureGraph.swift @@ -27,13 +27,6 @@ package final class ExecutionFeatureGraph: NSObject, ExecutionServiceGraph { buildSystemsFeature = buildSystems.map(BuildSystemsFeatureModel.init(service:)) runFeature = RunFeatureModel(service: run) projectDevelopment = ProjectDevelopmentFeatureModel(runFeature: runFeature) - run.configureBuildLanguageImportProvider { [weak buildSystems] workspace, root in - try buildSystems?.languageImport(workspaceURL: workspace, root: root) ?? JavaLanguageImportConfiguration() - } - run.configureBuildProjectImportProvider { [weak buildSystems] workspace, project in - guard let buildSystems else { throw CancellationError() } - return try buildSystems.languageImport(workspaceURL: workspace, project: project) - } run.configureBuildProviderRuns(start: { [weak buildSystems] configuration, workspace in buildSystems?.runProviderConfiguration(configuration, workspace: workspace) }, cancel: { [weak buildSystems] id in buildSystems?.cancelRun(id) }) @@ -45,13 +38,12 @@ package final class ExecutionFeatureGraph: NSObject, ExecutionServiceGraph { buildSystems?.entries.filter { $0.modelState == .loaded && !$0.isReloadRequired }.compactMap(\.model) ?? [] } run.configureProviderRunConfigurations { [weak buildSystems] in try buildSystems?.providerRunConfigurations() ?? [] } - run.configureBuildProjectOwnership { [weak buildSystems] in try buildSystems?.runProjectOwnership() ?? [] } run.configureProviderConfigurationRuns(source: { [weak buildSystems] inputs, root in buildSystems?.configurationRunSource(inputs: inputs, instanceRoot: root) - }) { [weak buildSystems] inputs, root, workspace, hints, current, progress, languageImport in + }) { [weak buildSystems] inputs, root, workspace, hints, current, progress in guard let buildSystems else { throw CancellationError() } return try await buildSystems.prepareConfigurationRun(inputs: inputs, instanceRoot: root, workspace: workspace, - tool: hints, isCurrent: current, progress: progress, onLanguageImport: languageImport) + tool: hints, isCurrent: current, progress: progress) } buildSystems?.providerSourcesChanged.sink { [weak run] sources in diff --git a/macos/Sources/LitheExecutionModule/Services/BuildLanguageTests.swift b/macos/Sources/LitheExecutionModule/Services/BuildLanguageTests.swift index b0abd34185..cebf054be3 100644 --- a/macos/Sources/LitheExecutionModule/Services/BuildLanguageTests.swift +++ b/macos/Sources/LitheExecutionModule/Services/BuildLanguageTests.swift @@ -99,11 +99,10 @@ package extension BuildSystemService { /// Selects a declared preparation by purpose and the owning model source role. /// Task identity and execution semantics remain with the build provider. - @discardableResult func prepareLanguageRun(fileURL: URL, workspace: URL, purpose: String, optionOverrides: [String: ToolingJSONValue] = [:], tool: @MainActor (String) throws -> BuildProviderHints?, - isCurrent: @escaping @MainActor () -> Bool) async throws -> BuildLanguageImport? { + isCurrent: @escaping @MainActor () -> Bool) async throws { let previous = operation?.id try await prepareLanguageTestModels(preparationPurpose: purpose, workspace: workspace) let revision = inputRevision @@ -125,11 +124,10 @@ package extension BuildSystemService { let (events, continuation) = AsyncStream.makeStream(of: BuildRunEnd.self) let observation = runEnded.sink { continuation.yield($0) } defer { observation.cancel(); continuation.finish() } - var preparedImport: BuildLanguageImport? guard inputRevision == revision, isCurrent(), operation?.id == previous, let id = runTask(entry.id, request: BuildTaskRequest(task: initialTask.id, optionOverrides: optionOverrides, tool: hints), title: entry.instance.displayName, - onLanguageImport: { preparedImport = $0 }, selectFromModel: { model in + selectFromModel: { model in guard !model.truncated else { throw BuildSystemServiceError(L10n.string("Load the current build model and enable its provider before running this configuration.")) } @@ -168,7 +166,7 @@ package extension BuildSystemService { if case .failed(let message) = ended.state { throw BuildSystemServiceError(message) } throw BuildSystemServiceError(L10n.string("The build provider returned an invalid launch plan.")) } - return preparedImport + return } throw CancellationError() } onCancel: { [weak self] in Task { @MainActor in self?.cancelRun(id) } } diff --git a/macos/Sources/LitheExecutionModule/Services/BuildSystemService.swift b/macos/Sources/LitheExecutionModule/Services/BuildSystemService.swift index 888452a80d..131721c921 100644 --- a/macos/Sources/LitheExecutionModule/Services/BuildSystemService.swift +++ b/macos/Sources/LitheExecutionModule/Services/BuildSystemService.swift @@ -144,19 +144,15 @@ package final class BuildSystemService: ObservableObject { let revision: Int } package private(set) var workspaceURL: URL? - /// Nil while detection is pending. An empty value means no plugin import. - @Published package private(set) var languageImport: JavaLanguageImportConfiguration? { + /// False while detection is pending; true once the current detection has + /// finished and normalized the stored options. + @Published package private(set) var isDetectionSettled = false { didSet { runGenerationInputsChanged.send() } } - private var languageImportsByRoot: [String: JavaLanguageImportConfiguration] = [:] - private var languageImportsByEntryID: [String: BuildLanguageImport] = [:] { - didSet { runGenerationInputsChanged.send() } - } - package var onLanguageImportChanged: ((URL) -> Void)? - private var languageImportFailure: String? + private var detectionFailure: String? private var detectionID: UUID? - private var importWaiters: [UUID: CheckedContinuation] = [:] - private var importTimeouts: [UUID: Task] = [:] + private var detectionWaiters: [UUID: CheckedContinuation] = [:] + private var detectionTimeouts: [UUID: Task] = [:] private let planner: any BuildSystemPlanning private let tools: any BuildToolResolving @@ -341,9 +337,6 @@ package final class BuildSystemService: ObservableObject { dependencyRevisions[affected.id, default: 0] += 1 } invalidateProducerConfiguration(buildSystemID: buildSystemID) - // The selected path can stay the same while its native content changes. - // Language import must re-read that source before its next project sync. - onLanguageImportChanged?(workspaceURL) } // MARK: Workspace @@ -381,16 +374,14 @@ package final class BuildSystemService: ObservableObject { detectionTask?.cancel() let detectionID = UUID() self.detectionID = detectionID - languageImport = nil - languageImportsByRoot = [:] - languageImportsByEntryID = [:] - languageImportFailure = nil + isDetectionSettled = false + detectionFailure = nil let sources = sources() guard !sources.isEmpty else { entries = [] issues = [] isDetecting = false - publishLanguageImport(JavaLanguageImportConfiguration(), workspaceURL: workspaceURL) + settleDetection() return } isDetecting = true @@ -425,7 +416,7 @@ package final class BuildSystemService: ObservableObject { } catch { entries = [] isDetecting = false - failLanguageImport(error) + failDetection(error) return } let previous = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) }) @@ -463,7 +454,7 @@ package final class BuildSystemService: ObservableObject { } catch { self.entries = [] self.issues = [] - self.failLanguageImport(error) + self.failDetection(error) return } let current = Dictionary(uniqueKeysWithValues: self.entries.map { ($0.id, $0) }) @@ -496,75 +487,20 @@ package final class BuildSystemService: ObservableObject { } if publishedBefore != self.entries.filter({ $0.declaration.sharesModel }) { self.invalidateModelInputs() } self.issues = detected.issues - let inputs: [LanguageImportInput] do { try self.persistDroppedOptions() try self.restoreSavedChoices(workspaceURL: workspaceURL) - inputs = try self.entries.map { entry in - LanguageImportInput( - entry: entry, - options: try self.storedOptions(for: entry, workspaceURL: workspaceURL) - ) - } } catch { self.entries = [] - self.failLanguageImport(error) + self.failDetection(error) return } - // Discovery is passive: importing a project cannot execute a - // wrapper or probe the build tool before user confirmation. - let normalized = await Task.detached(priority: .userInitiated) { - Result { try Self.languageImports(planner: planner, workspaceURL: workspaceURL, inputs: inputs) } - }.value - guard self.generation == generation, self.detectionID == detectionID, - !Task.isCancelled else { return } - switch normalized { - case .success(let imports): - var executables: [String: URL] = [:] - for input in inputs { - guard case .maven? = imports[input.entry.id], - let invocation = try? planner.invocationPlan( - input.entry.target, root: input.entry.instance.root, - settings: self.settings(input.entry.source.pluginID) - ) - else { continue } - do { - executables[input.entry.id] = try await self.tools.prepareLanguageImportExecutable(invocation, workspaceURL: workspaceURL) - } catch { - guard self.generation == generation, self.detectionID == detectionID, - !Task.isCancelled else { return } - self.failLanguageImport(error) - return - } - guard self.generation == generation, self.detectionID == detectionID, - !Task.isCancelled else { return } - } - let withExecutables = executables - let configured = await Task.detached(priority: .userInitiated) { - Result { - try Self.languageImports( - planner: planner, workspaceURL: workspaceURL, inputs: inputs, - executables: withExecutables, initial: imports - ) - } - }.value - guard self.generation == generation, self.detectionID == detectionID, - !Task.isCancelled else { return } - switch configured { - case .success(let values): - self.languageImportsByEntryID = values - self.languageImportsByRoot = Dictionary(uniqueKeysWithValues: Set(inputs.map { $0.entry.instance.root }).map { root in - (root, Self.workspaceImport(inputs: inputs.filter { $0.entry.instance.root == root }, imports: values)) - }) - self.publishLanguageImport(Self.workspaceImport(inputs: inputs, imports: values), workspaceURL: workspaceURL) - case .failure(let error): self.failLanguageImport(error) - } - case .failure(let error): self.failLanguageImport(error) - } + self.settleDetection() case .failure(let error): self.entries = [] self.issues = [error.localizedDescription] - self.failLanguageImport(error) + self.detectionFailure = error.localizedDescription + self.finishDetectionWaiters(.failure(error)) } } } @@ -644,13 +580,11 @@ package final class BuildSystemService: ObservableObject { providerConfigurationRevision += 1 if providerRunID != nil { stopRun() } // Reject the old input immediately; consumers wait for the coalesced - // detection instead of starting Java with pre-save import settings. + // detection instead of starting with pre-save option values. detectionTask?.cancel(); detectionTask = nil detectionID = nil - languageImport = nil - languageImportsByRoot = [:] - languageImportsByEntryID = [:] - languageImportFailure = nil + isDetectionSettled = false + detectionFailure = nil isDetecting = false redetectTask?.cancel() let waitForRedetection = waitForRedetection @@ -663,26 +597,7 @@ package final class BuildSystemService: ObservableObject { } } - // MARK: Language import - - /// Only current, complete upstream projects reach the generator. An empty - /// snapshot is authoritative when no build provider is enabled. - package func runProjectOwnership() throws -> [RunProjectOwnership] { - guard workspaceURL != nil, languageImport != nil else { throw CancellationError() } - return try entries.filter { $0.instance.modelSource != nil && languageImportsByEntryID[$0.id] != nil }.flatMap { entry in - guard entry.modelState == .loaded, !entry.isReloadRequired, let model = entry.model, !model.truncated else { - throw BuildSystemServiceError(L10n.string("Load the current build model and enable its provider before running this configuration.")) - } - return model.projects.map { project in - return RunProjectOwnership(path: project.path, build: RunBuildProjectReference( - pluginID: entry.instance.pluginID, buildSystemID: entry.instance.buildSystemID, - root: entry.instance.root, projectID: project.id), - contentRoots: model.contentRoots.filter { $0.projectID == project.id && ["source", "testSource", "generatedSource", "generatedTestSource"].contains($0.kind) } - .map { RunProjectOwnership.SourceRoot(path: $0.path, kind: $0.kind) }, - name: project.name, minimumJavaVersion: project.properties["java.minimumVersion"]) - } - } - } + // MARK: Detection /// Run discovery is language-neutral and never reads provider-specific properties. package func providerRunConfigurations() throws -> [RunProviderConfiguration] { @@ -715,133 +630,52 @@ package final class BuildSystemService: ObservableObject { return configurations } - /// Run preparation uses the same accepted options as Java import, scoped to - /// its recorded build root. Pending detection must never reuse an old root. - package func languageImport(workspaceURL: URL, root: String?) throws -> JavaLanguageImportConfiguration { - guard self.workspaceURL == workspaceURL.standardizedFileURL else { throw CancellationError() } - if let languageImportFailure { throw BuildSystemServiceError(languageImportFailure) } - guard let languageImport else { - throw BuildSystemServiceError(L10n.string("Build-system language import is still preparing. Retry when project loading completes.")) - } - guard let root else { return languageImport } - return languageImportsByRoot[root] ?? JavaLanguageImportConfiguration() - } - - /// Routes only an exact current model identity; names and directory guesses - /// cannot select another plugin's language preparation inputs. - package func languageImport(workspaceURL: URL, project: RunBuildProjectReference) throws -> JavaLanguageImportConfiguration { - guard self.workspaceURL == workspaceURL.standardizedFileURL, languageImportFailure == nil, - languageImport != nil else { throw CancellationError() } - let current = sources() - let matches = entries.filter { entry in - entry.instance.pluginID == project.pluginID && entry.instance.buildSystemID == project.buildSystemID - && entry.instance.root == project.root && current.contains(entry.source) - && entry.modelState == .loaded && !entry.isReloadRequired && entry.model?.truncated == false - && entry.model?.projects.contains(where: { $0.id == project.projectID }) == true - } - guard matches.count == 1, let entry = matches.first, let imported = languageImportsByEntryID[entry.id] else { throw CancellationError() } - switch imported { - case .maven(let value): return JavaLanguageImportConfiguration(mavenContext: value) - case .gradle(let value): return JavaLanguageImportConfiguration(javaGradle: value) - } - } - /// Waits for the current detection, including option normalization. A /// cancelled waiter never cancels detection shared by other consumers. - package func prepareLanguageImport(workspaceURL: URL) async throws -> JavaLanguageImportConfiguration { + package func awaitDetection(workspaceURL: URL) async throws { guard self.workspaceURL == workspaceURL.standardizedFileURL else { throw CancellationError() } - if let languageImport { return languageImport } - if let languageImportFailure { throw BuildSystemServiceError(languageImportFailure) } + if isDetectionSettled { return } + if let detectionFailure { throw BuildSystemServiceError(detectionFailure) } let id = UUID() - return try await withTaskCancellationHandler { + try await withTaskCancellationHandler { try Task.checkCancellation() - return try await withCheckedThrowingContinuation { continuation in - importWaiters[id] = continuation - importTimeouts[id] = Task { @MainActor [weak self] in + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + detectionWaiters[id] = continuation + detectionTimeouts[id] = Task { @MainActor [weak self] in // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 try? await Task.sleep(for: .seconds(30)) guard !Task.isCancelled else { return } - self?.finishImportWaiter(id, result: .failure(BuildSystemServiceError( + self?.finishDetectionWaiter(id, result: .failure(BuildSystemServiceError( L10n.string("Build-system language import preparation timed out. Retry project loading.") ))) } } } onCancel: { Task { @MainActor [weak self] in - self?.finishImportWaiter(id, result: .failure(CancellationError())) + self?.finishDetectionWaiter(id, result: .failure(CancellationError())) } } } - private func publishLanguageImport(_ value: JavaLanguageImportConfiguration, workspaceURL: URL) { - languageImport = value - languageImportFailure = nil - finishImportWaiters(.success(value)) - onLanguageImportChanged?(workspaceURL) + private func settleDetection() { + detectionFailure = nil + isDetectionSettled = true + finishDetectionWaiters(.success(())) } - private func failLanguageImport(_ error: Error) { - languageImportFailure = error.localizedDescription + private func failDetection(_ error: Error) { + detectionFailure = error.localizedDescription issues.append(error.localizedDescription) - finishImportWaiters(.failure(error)) + finishDetectionWaiters(.failure(error)) } - private func finishImportWaiter(_ id: UUID, result: Result) { - importTimeouts.removeValue(forKey: id)?.cancel() - importWaiters.removeValue(forKey: id)?.resume(with: result) + private func finishDetectionWaiter(_ id: UUID, result: Result) { + detectionTimeouts.removeValue(forKey: id)?.cancel() + detectionWaiters.removeValue(forKey: id)?.resume(with: result) } - private func finishImportWaiters(_ result: Result) { - for id in Array(importWaiters.keys) { finishImportWaiter(id, result: result) } - } - - private struct LanguageImportInput: Sendable { - let entry: BuildSystemEntry - let options: [String: ToolingJSONValue] - } - - nonisolated private static func languageImports( - planner: any BuildSystemPlanning, workspaceURL: URL, inputs: [LanguageImportInput], - executables: [String: URL] = [:], initial: [String: BuildLanguageImport]? = nil - ) throws -> [String: BuildLanguageImport] { - var imports = initial ?? [:] - for input in inputs { - try Task.checkCancellation() - if initial != nil && executables[input.entry.id] == nil { continue } - let resolution = try planner.resolveOptions( - input.entry.target, options: input.options, modelValues: input.entry.model?.optionValues - ) - imports[input.entry.id] = try planner.languageImport( - input.entry.target, workspaceURL: workspaceURL, root: input.entry.instance.root, - options: effectiveOptionValues(resolution, stored: input.options), - executableURL: executables[input.entry.id] - ) - } - return imports - } - - /// JDT accepts one context of each kind. Prefer the workspace root, then - /// the shallowest instance, with stable path/ID ordering for ties. Never - /// combine Profiles or machine paths from unrelated reactors. - nonisolated private static func workspaceImport( - inputs: [LanguageImportInput], imports: [String: BuildLanguageImport] - ) -> JavaLanguageImportConfiguration { - let ordered = inputs.sorted { - let left = $0.entry.instance, right = $1.entry.instance - let leftDepth = left.root == "." ? 0 : left.root.split(separator: "/").count - let rightDepth = right.root == "." ? 0 : right.root.split(separator: "/").count - return (leftDepth, left.root, left.id, left.pluginID) < (rightDepth, right.root, right.id, right.pluginID) - } - var maven: MavenLaunchContext? - var gradle: JavaGradleImportConfiguration? - for input in ordered { - switch imports[input.entry.id] { - case .maven(let context)?: if maven == nil { maven = context } - case .gradle(let context)?: if gradle == nil { gradle = context } - case nil: break - } - } - return JavaLanguageImportConfiguration(mavenContext: maven, javaGradle: gradle) + private func finishDetectionWaiters(_ result: Result) { + for id in Array(detectionWaiters.keys) { finishDetectionWaiter(id, result: result) } } // MARK: Model @@ -857,7 +691,7 @@ package final class BuildSystemService: ObservableObject { let configurationRevision = providerConfigurationRevision let sourcesRevision = fileRevision let ids = entries.filter { entry in - if allModels { return entry.instance.modelSource != nil && languageImportsByEntryID[entry.id] != nil } + if allModels { return entry.instance.modelSource != nil } if let reference { return entry.instance.pluginID == reference.pluginID && entry.instance.buildSystemID == reference.buildSystemID && entry.instance.root == reference.root } if let preparationPurpose { return entry.declaration.tasks.contains { $0.preparation?.purpose == preparationPurpose } } return selectorKind.map(entry.declaration.testSelectorKinds.contains) ?? entry.declaration.tasks.contains { taskIDs.contains($0.id) } @@ -947,7 +781,7 @@ package final class BuildSystemService: ObservableObject { do { try self.refreshOptions(buildSystemID: entry.instance.buildSystemID) } catch { self.entries = [] - self.failLanguageImport(error) + self.failDetection(error) return } // Model-provided choices may remove an import option even @@ -1078,7 +912,7 @@ package final class BuildSystemService: ObservableObject { let launchOptions = declaration.execution == .application ? nil : BuildLaunchOptions( execution: declaration.execution, arguments: request.userArguments) let origin = configuration ?? RunConfiguration(id: "build:" + entryID + ":" + request.run + ":" + request.targetID, - name: title, kind: .process(provider: "build.provider"), execution: declaration.execution == .service ? .service : (declaration.execution == .task ? .task : .application), modulePath: nil, mainClass: nil, + name: title, kind: .process(provider: "build.provider"), execution: declaration.execution == .service ? .service : (declaration.execution == .task ? .task : .application), buildProvider: BuildProviderRunReference(pluginID: entry.instance.pluginID, buildSystemID: entry.instance.buildSystemID, root: entry.instance.root, run: request.run, projectID: request.projectID, targetID: request.targetID, userArguments: request.userArguments, execution: declaration.execution == .application ? nil : declaration.execution)) @@ -1170,8 +1004,7 @@ package final class BuildSystemService: ObservableObject { /// Independent service preparations share provider sessions, never the single Build task slot. package func prepareConfigurationRun(inputs: ProviderLaunchInputs, instanceRoot: String, workspace: URL, tool: BuildProviderHints, isCurrent: @escaping @MainActor @Sendable () -> Bool, - progress: @escaping @MainActor @Sendable (BuildProviderProgress) -> Void, - onLanguageImport: @escaping @MainActor (BuildLanguageImport) async throws -> Void = { _ in }) async throws -> BuildRunPreparation { + progress: @escaping @MainActor @Sendable (BuildProviderProgress) -> Void) async throws -> BuildRunPreparation { guard workspace.standardizedFileURL == workspaceURL, let providers else { throw CancellationError() } let candidates = entries.filter { $0.instance.root == instanceRoot && $0.instance.buildSystemID == inputs.buildSystemID && (inputs.reference == nil || inputs.reference?.pluginID == $0.instance.pluginID) @@ -1242,15 +1075,6 @@ package final class BuildSystemService: ObservableObject { && (inputs.reference == nil || $0.id == inputs.reference?.run) && ($0.targetTags.isEmpty || !Set($0.targetTags).isDisjoint(with: selected.tags)) } guard runs.count == 1, let run = runs.first else { throw BuildSystemServiceError(Self.providerUnsupportedMessage) } - if inputs.launchOptions.debug != nil { - let resolution = try planner.resolveOptions(entry.target, options: context.options, modelValues: model.optionValues) - if let imported = try planner.languageImport(entry.target, workspaceURL: workspace, root: context.root, - options: Self.effectiveOptionValues(resolution, stored: context.options), executableURL: launchTool.toolExecutable) { - guard valid() else { throw CancellationError() } - try await onLanguageImport(imported) - } - guard valid() else { throw CancellationError() } - } let opaqueArguments = inputs.opaqueReferenceArguments let launchOptions = opaqueArguments == nil ? inputs.launchOptions : nil let request = try planner.prepareRunPlan(entry.target, context: context, run: run.id, project: BuildSelection(project: project), @@ -1346,7 +1170,6 @@ package final class BuildSystemService: ObservableObject { /// Runs a declared task, or a model task through its template. @discardableResult package func runTask(_ entryID: String, request: BuildTaskRequest, title: String, - onLanguageImport: (@MainActor (BuildLanguageImport?) -> Void)? = nil, selectFromModel: (@MainActor (BuildModel) throws -> BuildTaskRequest)? = nil) -> UUID? { guard let workspaceURL, let entry = entry(entryID) else { return nil } return startRun(entryID, title: title) { service, run in @@ -1360,10 +1183,6 @@ package final class BuildSystemService: ObservableObject { } let context = BuildPlanContext(root: base.root, options: proposed, pluginDirectory: base.pluginDirectory, workspaceStateDirectory: base.workspaceStateDirectory, modelInputs: base.modelInputs) - if let onLanguageImport { - onLanguageImport(try service.planner.languageImport(entry.target, workspaceURL: workspaceURL, - root: context.root, options: context.options, executableURL: request.tool?.toolExecutable)) - } var selectedRequest = request if let selectFromModel { let model: BuildModel @@ -1507,12 +1326,10 @@ package final class BuildSystemService: ObservableObject { detectionTask?.cancel(); detectionTask = nil detectionID = nil redetectTask?.cancel(); redetectTask = nil - languageImport = nil - languageImportsByRoot = [:] - languageImportsByEntryID = [:] - languageImportFailure = nil + isDetectionSettled = false + detectionFailure = nil isDetecting = false - finishImportWaiters(.failure(CancellationError())) + finishDetectionWaiters(.failure(CancellationError())) stopRun() testDiscoveries = [:] discoverySnapshots = [:] diff --git a/macos/Sources/LitheExecutionModule/Services/JavaLaunchArguments.swift b/macos/Sources/LitheExecutionModule/Services/JavaLaunchArguments.swift deleted file mode 100644 index 0dbf5323b1..0000000000 --- a/macos/Sources/LitheExecutionModule/Services/JavaLaunchArguments.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation - -/// Owns one temporary Java argument file until its process has terminated. -package protocol JavaLaunchArgumentLease: AnyObject, Sendable {} - -/// Result of shortening one Java process launch. -package struct JavaLaunchArgumentPreparation: Sendable { - package let arguments: [String] - package let lease: (any JavaLaunchArgumentLease)? - - package init(arguments: [String], lease: (any JavaLaunchArgumentLease)? = nil) { - self.arguments = arguments - self.lease = lease - } -} - -/// Platform adapter for the shared Rust Java command-line planner. -package protocol JavaLaunchArgumentPreparing: Sendable { - func prepareJavaLaunch( - executablePath: String, - arguments: [String] - ) throws -> JavaLaunchArgumentPreparation -} diff --git a/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift b/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift index f9d1c52a04..1be457681c 100644 --- a/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift +++ b/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift @@ -43,7 +43,6 @@ package final class LanguageTestService: ObservableObject { private var lastBackendRun: (@MainActor () -> Void)? private var lastRun: LastRun? private let maximumOutputCharacters = 400_000 - private static let javaTestTimeoutMilliseconds = 120_000 package init( outcomeResolver: any TestRunOutcomeResolving, @@ -213,7 +212,6 @@ package final class LanguageTestService: ObservableObject { state = .running timedOutOperationID = nil append("$ \(resolved.executableURL.lastPathComponent) \(plan.launchPlan.arguments.joined(separator: " "))\n\n") - let timeoutMilliseconds = Self.testTimeoutMilliseconds(for: plan.frameworkID) if let extensionProvider { let session = extensionProvider.makeTestExecutionSession() configureExtensionSession( @@ -228,7 +226,7 @@ package final class LanguageTestService: ObservableObject { arguments: plan.launchPlan.arguments, workingDirectory: workingDirectory.path, environment: resolved.environment, - timeoutMilliseconds: timeoutMilliseconds + timeoutMilliseconds: nil )) } else { let process = processFactory() @@ -244,7 +242,7 @@ package final class LanguageTestService: ObservableObject { arguments: plan.launchPlan.arguments, workingDirectory: workingDirectory.path, environment: resolved.environment, - timeoutMilliseconds: timeoutMilliseconds + timeoutMilliseconds: nil )) } return true @@ -601,13 +599,6 @@ package final class LanguageTestService: ObservableObject { } } - private static func testTimeoutMilliseconds(for frameworkID: String?) -> Int? { - switch frameworkID { - case "junit": return javaTestTimeoutMilliseconds - default: return nil - } - } - private func relativeProjectPaths(_ files: [URL], workspaceURL: URL) -> [String] { files.compactMap { relativePath($0, workspaceURL: workspaceURL) }.sorted() } diff --git a/macos/Sources/LitheExecutionModule/Services/RunService.swift b/macos/Sources/LitheExecutionModule/Services/RunService.swift index 41ec775f97..b52cbc0fcf 100644 --- a/macos/Sources/LitheExecutionModule/Services/RunService.swift +++ b/macos/Sources/LitheExecutionModule/Services/RunService.swift @@ -24,23 +24,12 @@ package final class RunService: ObservableObject, BuildRunLaunching { package private(set) var primaryExecutionID: String? @Published package private(set) var lastExitCode: Int32? @Published package private(set) var optionsByConfigurationID: [String: RunOptions] = [:] { didSet { providerLaunchRevision &+= 1 } } - @Published package private(set) var projectToolchain = ProjectToolchainSelection() { didSet { providerLaunchRevision &+= 1 } } - /// Defaults saved in `.lithe/run/local.json`, read even before generation. - /// `nil` until that layer saves defaults or while it cannot be read. - @Published package private(set) var savedProjectToolchain: ProjectToolchainSelection? @Published package private(set) var effectiveSourcesByConfigurationID: [String: RunConfigurationSource] = [:] - /// Presentation choices come from current provider models, never a second POM scan. - package var mavenProfiles: [MavenProfile] { - Array(Set(buildModels().flatMap { $0.optionValues["profiles"] ?? [] })).sorted() - .map { MavenProfile(id: $0, isActiveByDefault: false) } - } @Published package private(set) var moduleSessions: [RunSession] = [] - @Published package private(set) var portConflicts: [RunPortConflict] = [] @Published package private(set) var configurationStatus: ProjectRunConfigurationStatus = .missing @Published package private(set) var requiresConfigurationGeneration = false @Published package private(set) var configurationDiagnostics: [RunConfigurationDiagnostic] = [] @Published package private(set) var generationState: RunConfigurationGenerationState = .idle - @Published package private(set) var javaDiscoveryStatus: JavaDiscoveryStatus = .idle @Published package private(set) var recoveryAction: RunConfigurationRecoveryAction = .regenerate @Published package private(set) var recoveryPath: String? @Published package private(set) var configurationSaveError: String? @@ -94,7 +83,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { configurationSaveError = nil do { let id = try runConfigurationOperations.saveBuildProviderConfiguration(reference, name: configuration.name, at: workspace) - let resolution = try resolveWithServiceToolchains(operations: runConfigurationOperations, projectURL: workspace, preferredConfigurationID: id) + let resolution = try resolveWithToolchainCandidates(operations: runConfigurationOperations, projectURL: workspace) guard let saved = resolution.configurations.first(where: { $0.configuration.id == id }), saved.configuration.buildProvider == reference else { throw RunConfigurationEditorSaveFailure(stage: .reload, @@ -102,7 +91,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { } configurationStatus = .ready configurationDiagnostics = resolution.diagnostics - apply(resolution.configurations, projectToolchain: resolution.projectToolchain, preferredConfigurationID: id) + apply(resolution.configurations, preferredConfigurationID: id) lastRunConfiguration = saved.configuration return true } catch { configurationSaveError = error.localizedDescription; return false } @@ -112,7 +101,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { private let processFactory: () -> any StreamingProcess private let fileAccess: any RunFileAccess private let preferences: any RunPreferenceStore - private let serverPortParser: any RunServerPortParsing private let runConfigurationOperations: any RunConfigurationOperations private let languageProviderCatalog: LanguageProviderCatalog private let languageRunProviders: LanguageRunProviderRegistry @@ -125,7 +113,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { private var projectURL: URL? private var projectFiles: [URL] = [] private var buildModels: () -> [BuildModel] = { [] } - private var buildProjectOwnership: () throws -> [RunProjectOwnership]? = { nil } private var providerRunConfigurations: () throws -> [RunProviderConfiguration]? = { nil } private var dependencyWorkspaceURL: URL? private var dependencyConfiguration = WorkspaceDependencyConfiguration() @@ -133,8 +120,8 @@ package final class RunService: ObservableObject, BuildRunLaunching { private var languageSnapshots: [String: LanguageDependencySnapshot] = [:] private var dependencySources: [String: DependencyServiceDescriptor] = [:] private var projectLoadID = UUID() - /// Advances on every regeneration so a JDT freshness answer computed against - /// the previous document cannot be attached to the new one. + /// Advances on every regeneration so an answer computed against the previous + /// document cannot be attached to the new one. private var generationRevision = 0 private var generationLease: RunConfigurationGenerationLease? private var providerInspectionRevision: UInt64 = 0 @@ -146,14 +133,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { private var lastCurrentFileURL: URL? private var moduleProcesses: [String: any StreamingProcess] = [:] private var moduleLanguageExecutionSessions: [String: any LanguageExecutionSession] = [:] - private var activeLaunchArgumentLease: (any JavaLaunchArgumentLease)? - private var moduleLaunchArgumentLeases: [String: any JavaLaunchArgumentLease] = [:] private var activeOperationID: String? - private var activePreLaunchProcess: (any StreamingProcess)? - /// Pre-launch steps of a running module session, keyed like - /// `moduleProcesses`, so Stop and reconciliation cancel them before the JVM - /// exists and a stopped session cannot still start one. - private var modulePreLaunchProcesses: [String: any StreamingProcess] = [:] private var moduleOperationIDs: [String: String] = [:] private var primaryProviderSource: BuildSystemPluginSource? private var providerDebugOperationID: String? @@ -182,29 +162,28 @@ package final class RunService: ObservableObject, BuildRunLaunching { private var providerPrimaryPreparation: Task? private var providerModulePreparations: [String: Task] = [:] private typealias ConfigurationRunPreparer = @MainActor (ProviderLaunchInputs, String, URL, BuildProviderHints, - @escaping @MainActor @Sendable () -> Bool, @escaping @MainActor @Sendable (BuildProviderProgress) -> Void, - @escaping @MainActor (BuildLanguageImport) async throws -> Void) async throws -> BuildRunPreparation + @escaping @MainActor @Sendable () -> Bool, + @escaping @MainActor @Sendable (BuildProviderProgress) -> Void) async throws -> BuildRunPreparation private var configurationRunPreparer: ConfigurationRunPreparer? private var configurationRunSource: (@MainActor (ProviderLaunchInputs, String) -> BuildSystemPluginSource?)? package func configureProviderConfigurationRuns( source: (@MainActor (ProviderLaunchInputs, String) -> BuildSystemPluginSource?)? = nil, _ prepare: @escaping @MainActor (ProviderLaunchInputs, String, URL, BuildProviderHints, - @escaping @MainActor @Sendable () -> Bool, @escaping @MainActor @Sendable (BuildProviderProgress) -> Void, - @escaping @MainActor (BuildLanguageImport) async throws -> Void) async throws -> BuildRunPreparation) { + @escaping @MainActor @Sendable () -> Bool, + @escaping @MainActor @Sendable (BuildProviderProgress) -> Void) async throws -> BuildRunPreparation) { configurationRunPreparer = prepare configurationRunSource = source } - private func needsProviderLaunch(_ configuration: RunConfiguration, javaLaunch: JavaDebugLaunchTarget?) -> Bool { - configurationRunPreparer != nil && javaLaunch == nil && configuration.buildProvider?.execution != nil + private func needsProviderLaunch(_ configuration: RunConfiguration) -> Bool { + configurationRunPreparer != nil && configuration.buildProvider?.execution != nil } /// Debug uses the same canonical inputs and process owner as Run. Only the /// registered adapter and local connection cross the boundary, never runtime flags. package func prepareProviderDebug(_ configuration: RunConfiguration, debug: @escaping @MainActor (String) throws -> BuildLaunchOptions.Debug, - languageImport: @escaping @MainActor (BuildLanguageImport) async throws -> Void = { _ in }, isCurrent: @escaping @MainActor @Sendable () -> Bool) async throws -> String { guard configuration.usesProviderConnectionDebug, projectURL != nil, configurationRunPreparer != nil else { throw CancellationError() } stop() @@ -212,7 +191,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { let task = Task { try Task.checkCancellation() guard self.providerDebugPreparation?.id == owner else { throw CancellationError() } - return try await self.prepareProviderDebugExecution(configuration, debug: debug, languageImport: languageImport, isCurrent: isCurrent) + return try await self.prepareProviderDebugExecution(configuration, debug: debug, isCurrent: isCurrent) } providerDebugPreparation = (owner, { task.cancel() }) defer { if providerDebugPreparation?.id == owner { providerDebugPreparation = nil } } @@ -221,7 +200,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { private func prepareProviderDebugExecution(_ configuration: RunConfiguration, debug: @escaping @MainActor (String) throws -> BuildLaunchOptions.Debug, - languageImport: @escaping @MainActor (BuildLanguageImport) async throws -> Void, isCurrent: @escaping @MainActor @Sendable () -> Bool) async throws -> String { guard let workspace = projectURL, let prepare = configurationRunPreparer else { throw CancellationError() } let identity = UUID().uuidString, load = projectLoadID, revision = providerLaunchRevision, generated = generationRevision @@ -262,18 +240,13 @@ package final class RunService: ObservableObject, BuildRunLaunching { tools: original.tools) let prepared = try await prepare(inputs, root, workspace, BuildProviderHints(), valid, { [weak self] value in if valid() { self?.append(value.output ?? value.message.map { $0 + "\n" } ?? "") } - }) { value in - guard valid() else { throw CancellationError() } - try await languageImport(value) - guard valid() else { throw CancellationError() } - } + }) let latest = try await Task.detached(priority: .userInitiated) { try operations.providerLaunchInputs(at: workspace, configurationID: configuration.id, providerRoot: root) }.value guard valid(), latest == original else { throw CancellationError() } let executable = try await prepareRunExecutable(prepared, workspaceURL: workspace, configuration: configuration) guard valid() else { throw CancellationError() } - try validateProviderGeneration(for: configuration) // Handoff is synchronous. Internal process replacement must not cancel // the preparation that has just produced this process. providerDebugPreparation = nil @@ -336,14 +309,13 @@ package final class RunService: ObservableObject, BuildRunLaunching { guard let self, current() else { return } let text = value.output ?? value.message.map { $0 + "\n" } ?? "" if primary { self.append(text) } else { self.appendModuleOutput(text, sessionID: configuration.id) } - }) { _ in } + }) let latest = try await Task.detached(priority: .userInitiated) { try operations.providerLaunchInputs(at: workspace, configurationID: configuration.id, providerRoot: providerRoot) }.value guard current(), latest == inputs else { throw CancellationError() } let executable = try await self.prepareRunExecutable(prepared, workspaceURL: workspace, configuration: configuration) guard current() else { throw CancellationError() } - try self.validateProviderGeneration(for: configuration) if primary { self.providerPrimaryPreparation = nil _ = try self.launchPreparedRun(prepared, workspaceURL: workspace, title: configuration.name, configuration: configuration, retainingIdentity: operationID, resolvedExecutable: executable) @@ -371,49 +343,34 @@ package final class RunService: ObservableObject, BuildRunLaunching { } private let maximumOutputCharacters = 500_000 - /// The same bound the Windows pre-launch runner applies (`PRE_LAUNCH_TIMEOUT` - /// in `windows/tauri/src-tauri/src/run.rs`). A resource step is a Maven - /// build, so a step that never finishes must fail the run on both platforms - /// instead of leaving it "running" until a manual Stop. - private static let preLaunchStepTimeoutMilliseconds = 600_000 - private let runtime: any RunRuntimePort private let executableResolver: any RunExecutableResolving - private let javaLaunchArgumentPreparer: (any JavaLaunchArgumentPreparing)? - private var buildLanguageImportProvider: @MainActor (URL, String?) throws -> JavaLanguageImportConfiguration = { _, _ in .init() } - private var buildProjectImportProvider: @MainActor (URL, RunBuildProjectReference) throws -> JavaLanguageImportConfiguration = { _, _ in throw CancellationError() } private var languageDependencyProvider: @MainActor (String, URL, String) -> LanguageDependencySnapshot? = { _, _, _ in nil } package init( logSink: (any LogSink)? = nil, - runtime: any RunRuntimePort, process: any StreamingProcess, processFactory: @escaping () -> any StreamingProcess, fileAccess: any RunFileAccess, preferences: any RunPreferenceStore, - serverPortParser: any RunServerPortParsing, runConfigurationOperations: any RunConfigurationOperations, executableResolver: any RunExecutableResolving, languageProviderCatalog: LanguageProviderCatalog, languageRunProviders: LanguageRunProviderRegistry, extensionRequiredLanguageIDs: Set = [], languageSupports: [LanguageSupportDeclaration] = [], - dependencyStore: (any WorkspaceDependencyStoring)? = nil, - javaLaunchArgumentPreparer: (any JavaLaunchArgumentPreparing)? = nil + dependencyStore: (any WorkspaceDependencyStoring)? = nil ) { self.logSink = logSink - self.runtime = runtime self.process = process self.processFactory = processFactory self.fileAccess = fileAccess self.preferences = preferences - self.serverPortParser = serverPortParser self.runConfigurationOperations = runConfigurationOperations self.languageProviderCatalog = languageProviderCatalog self.languageRunProviders = languageRunProviders self.extensionRequiredLanguageIDs = extensionRequiredLanguageIDs - self.javaLaunchArgumentPreparer = javaLaunchArgumentPreparer dependencyDeclarations = Dictionary(uniqueKeysWithValues: languageSupports.compactMap { support in support.dependencies.map { (support.id, $0) } }) @@ -474,18 +431,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { generationState = .projectNotReady } - package func configureBuildLanguageImportProvider( - _ provider: @escaping @MainActor (URL, String?) throws -> JavaLanguageImportConfiguration - ) { - buildLanguageImportProvider = provider - } - - package func configureBuildProjectImportProvider( - _ provider: @escaping @MainActor (URL, RunBuildProjectReference) throws -> JavaLanguageImportConfiguration - ) { - buildProjectImportProvider = provider - } - /// Looks up only an already active plugin capability; opening the tree must /// never activate a language server or launch a dependency resolver. package func configureLanguageDependencyProvider( @@ -529,10 +474,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { providerRunConfigurations = configurations } - package func configureBuildProjectOwnership(_ ownership: @escaping () throws -> [RunProjectOwnership]?) { - buildProjectOwnership = ownership - } - package func cancelProviderGenerationInspection() { providerInspectionRevision &+= 1 providerInspectionOwner = UUID() @@ -562,13 +503,10 @@ package final class RunService: ObservableObject, BuildRunLaunching { providerInspectionRevision &+= 1 let ticket = providerInspectionRevision guard configurationStatus == .ready, let projectURL, - configurations.contains(where: { $0.requiresProviderGeneration || $0.buildProvider != nil }) else { return } + configurations.contains(where: { $0.buildProvider != nil }) else { return } let loadID = projectLoadID, revision = generationRevision - let ownership: [RunProjectOwnership] - let providerRuns: [RunProviderConfiguration]? - do { guard let current = try buildProjectOwnership() else { return }; ownership = current - providerRuns = try providerRunConfigurations() - } + let providerRuns: [RunProviderConfiguration] + do { guard let current = try providerRunConfigurations() else { return }; providerRuns = current } catch { publishProviderDiagnostics([RunConfigurationDiagnostic(configurationID: nil, code: "providerModelNotReady", message: L10n.string("Load the current build model and enable its provider before running this configuration."))]) @@ -577,9 +515,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { let operations = runConfigurationOperations let inspection = await withCheckedContinuation { continuation in DispatchQueue.global(qos: .utility).async { - let result = providerRuns.map { operations.inspectProviderGeneration(at: projectURL, projectOwnership: ownership, providerRuns: $0) } - ?? operations.inspectProviderGeneration(at: projectURL, projectOwnership: ownership) - continuation.resume(returning: result) + continuation.resume(returning: operations.inspectProviderGeneration(at: projectURL, providerRuns: providerRuns)) } } guard !Task.isCancelled, providerInspectionRevision == ticket, projectLoadID == loadID, @@ -594,32 +530,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { configurationDiagnostics += diagnostics } - /// Called immediately before every generated Java/Maven launch, including - /// Agent and service entry points. Displayed diagnostics are never authority. - package func validateProviderGeneration(for configuration: RunConfiguration) throws { - guard configuration.requiresProviderGeneration else { return } - providerInspectionRevision &+= 1 - guard let projectURL else { throw CancellationError() } - do { - guard let ownership = try buildProjectOwnership() else { return } - let inspection: ProjectRunConfigurationInspection - if let runs = try providerRunConfigurations() { - inspection = runConfigurationOperations.inspectProviderGeneration(at: projectURL, projectOwnership: ownership, providerRuns: runs) - } else { inspection = runConfigurationOperations.inspectProviderGeneration(at: projectURL, projectOwnership: ownership) } - if case .invalid(let message) = inspection.status { - throw RunConfigurationOperationFailure(message: message) - } - let diagnostics = inspection.diagnostics.filter { $0.code == "staleProviderModel" } - publishProviderDiagnostics(diagnostics) - if let first = diagnostics.first { throw RunConfigurationOperationFailure(message: first.message) } - } catch { - if error is CancellationError { - throw RunConfigurationOperationFailure(message: L10n.string("Load the current build model and enable its provider before running this configuration.")) - } - throw error - } - } - /// A language capability explicitly opts into the dependency browser. /// This registration is independent of the run configuration inventory. package func registerDependencySource(languageID: String, displayName: String) { @@ -841,7 +751,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { configurationDiagnostics = inspection.diagnostics recoveryAction = inspection.recoveryAction recoveryPath = inspection.recoveryPath - savedProjectToolchain = inspection.projectToolchain generationState = .idle if inspection.status == .ready { do { @@ -849,18 +758,15 @@ package final class RunService: ObservableObject, BuildRunLaunching { guard !Task.isCancelled, projectLoadID == loadID else { return } let preferredID = selectedConfigurationIDsByProject[projectURL.standardizedFileURL.path] ?? preferences.string(forKey: selectionPreferenceKey(for: projectURL.standardizedFileURL)) - let resolution = try await resolveLoadedProjectToolchains( + let resolution = try resolveWithToolchainCandidates( operations: operations, - projectURL: projectURL, - preferredConfigurationID: preferredID, - loadID: loadID + projectURL: projectURL ) guard !Task.isCancelled, projectLoadID == loadID else { return } configurationDiagnostics += resolution.diagnostics defaultConfigurationID = resolution.defaultConfigurationID apply( resolution.configurations, - projectToolchain: resolution.projectToolchain, preferredConfigurationID: preferredID ?? resolution.defaultConfigurationID ) } catch { @@ -876,7 +782,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { optionsByConfigurationID = [:] effectiveSourcesByConfigurationID = [:] reconcileModuleSessions(validConfigurationIDs: []) - refreshPortConflicts() } // Whether the existing configuration parses is `configurationStatus`, not // this state. Keeping them apart is what lets identification run after @@ -889,30 +794,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { await refreshProviderGeneration() } - /// Adds what JDT reports about the generated Java entries. - /// - /// `entrypoints` is JDT's current answer. Inspection runs off the main actor, - /// and an answer that arrives after a reload or regeneration is dropped. - package func reportJavaEntrypointFreshness(_ entrypoints: JavaEntrypoints) async { - guard configurationStatus == .ready, let projectURL else { return } - let loadID = projectLoadID - let revision = generationRevision - let operations = runConfigurationOperations - let inspection = await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: operations.inspect( - at: projectURL, - checkFingerprint: false, - javaEntrypoints: entrypoints - )) - } - } - guard !Task.isCancelled, projectLoadID == loadID, generationRevision == revision, - self.projectURL == projectURL else { return } - let shown = configurationDiagnostics - configurationDiagnostics += inspection.diagnostics.filter { !shown.contains($0) } - } - /// Diagnostics after a run document edit. Editing `.lithe` changes no /// project input, so the freshness already reported still holds and the /// inputs are not read again on the main actor. @@ -924,7 +805,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { let inspected = runConfigurationOperations.inspect( at: projectURL, checkFingerprint: false, - javaEntrypoints: nil + providerRuns: nil ).diagnostics var diagnostics = freshness for diagnostic in inspected + resolution where !diagnostics.contains(diagnostic) { @@ -933,29 +814,12 @@ package final class RunService: ObservableObject, BuildRunLaunching { return diagnostics } - private static func javaDiscoveryStatus( - _ discovery: JavaEntrypointDiscovery, - showsJavaEntries: Bool - ) -> JavaDiscoveryStatus { - switch discovery { - case .notJava: return .idle - case .discovered: return .ready - case .failed(let message): return .failed(message) - case .pending: return showsJavaEntries ? .stale : .loading - } - } - /// Identifies the project's run entries. Core keeps them in memory, not in /// the workspace. /// - /// `javaDiscovery` is what JDT answered just before; while it is pending, - /// Core keeps the previous generation's Java entries so the list does not - /// empty during a cold start. `automatic` marks identification Lithe starts - /// itself, which reports problems but not the entry count. - package func generateRunConfigurations( - javaDiscovery: JavaEntrypointDiscovery = .notJava, - automatic: Bool = false - ) async { + /// `automatic` marks identification Lithe starts itself, which reports + /// problems but not the entry count. + package func generateRunConfigurations(automatic: Bool = false) async { guard recoveryAction != .upgradeApplication else { generationState = .failed(L10n.string("Upgrade Lithe to use this run configuration version.")) return @@ -982,28 +846,14 @@ package final class RunService: ObservableObject, BuildRunLaunching { lease.invalidate() } let operations = runConfigurationOperations - let files = projectFiles - let models = buildModels() - let modulePaths = Array(Set(models.flatMap { $0.projects.map(\.path) })).sorted() - let projectOwnership: [RunProjectOwnership]? let providerRuns: [RunProviderConfiguration]? - do { projectOwnership = try buildProjectOwnership(); providerRuns = try providerRunConfigurations() } + do { providerRuns = try providerRunConfigurations() } catch { generationState = .failed(error.localizedDescription); return } let result = await withTaskCancellationHandler { await withCheckedContinuation { continuation in DispatchQueue.global(qos: .userInitiated).async { continuation.resume(returning: Result { - if let providerRuns { - return try operations.generate(at: projectURL, files: files, modulePaths: modulePaths, - javaEntrypoints: javaDiscovery.entrypoints, projectOwnership: projectOwnership, providerRuns: providerRuns, models: models, lease: lease) - } - return try operations.generate( - at: projectURL, - files: files, - modulePaths: modulePaths, - javaEntrypoints: javaDiscovery.entrypoints, - projectOwnership: projectOwnership - ) + try operations.generate(at: projectURL, providerRuns: providerRuns, lease: lease) }) } } @@ -1014,20 +864,9 @@ package final class RunService: ObservableObject, BuildRunLaunching { do { await executableResolver.refreshCandidates(projectURL: projectURL) guard !Task.isCancelled, projectLoadID == loadID, generationRevision == generationTicket, lease.isCurrent else { return } - var resolution = try resolveWithServiceToolchains( - operations: operations, - projectURL: projectURL, - preferredConfigurationID: nil - ) - try operations.migrateLegacySettings( - at: projectURL, - configurationIDs: resolution.configurations.map { $0.configuration.id } - ) - resolution = try resolveWithServiceToolchains( + let resolution = try resolveWithToolchainCandidates( operations: operations, - projectURL: projectURL, - preferredConfigurationID: selectedConfigurationIDsByProject[projectURL.standardizedFileURL.path] - ?? resolution.defaultConfigurationID + projectURL: projectURL ) configurationStatus = .ready requiresConfigurationGeneration = false @@ -1039,21 +878,13 @@ package final class RunService: ObservableObject, BuildRunLaunching { configurationDiagnostics = operations.inspect( at: projectURL, checkFingerprint: false, - javaEntrypoints: nil + providerRuns: nil ).diagnostics + resolution.diagnostics generationState = result.entryCount == 0 ? .noEntries : automatic ? .idle : .succeeded(entryCount: result.entryCount) - javaDiscoveryStatus = Self.javaDiscoveryStatus( - javaDiscovery, - // JDT's entries all generate as `java.main` configurations. - showsJavaEntries: resolution.configurations.contains { - $0.configuration.kind == .javaMain - } - ) apply( resolution.configurations, - projectToolchain: resolution.projectToolchain, preferredConfigurationID: selectedConfigurationIDsByProject[projectURL.standardizedFileURL.path] ?? resolution.defaultConfigurationID ) @@ -1076,9 +907,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { package func select(_ configuration: RunConfiguration) { selectedConfigurationID = configuration.id - if configuration.kind.capabilities.contains(.javaRuntime) { - runtime.setActiveServiceJavaHomePath(options(for: configuration).javaHomePath) - } } private func selectionPreferenceKey(for projectURL: URL) -> String { @@ -1090,13 +918,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { optionsByConfigurationID[configuration.id] ?? RunOptions() } - /// Returns the service port explicitly configured for this run target, or - /// a Spring-style framework's conventional 8080 default when no override exists. - package func configuredServerPort(for configuration: RunConfiguration) -> Int? { - configuredPort(for: configuration) - ?? (configuration.kind.mavenFramework != nil ? 8080 : nil) - } - package func source(for configuration: RunConfiguration) -> RunConfigurationSource { effectiveSourcesByConfigurationID[configuration.id] ?? .generated } @@ -1110,38 +931,8 @@ package final class RunService: ObservableObject, BuildRunLaunching { return URL(string: "http://127.0.0.1:\(port)") } - @discardableResult - package func saveProjectToolchain(_ toolchain: ProjectToolchainSelection) -> Bool { - configurationSaveError = nil - guard let projectURL else { return false } - do { - try runConfigurationOperations.saveProjectToolchain(toolchain, at: projectURL) - projectToolchain = toolchain - savedProjectToolchain = toolchain - } catch { - configurationSaveError = editorSaveFailureMessage(error, fallbackStage: .write) - return false - } - do { - if configurationStatus == .ready { - let resolution = try resolveWithServiceToolchains( - operations: runConfigurationOperations, - projectURL: projectURL, - preferredConfigurationID: selectedConfiguration?.id - ) - configurationDiagnostics = resolution.diagnostics - apply(resolution.configurations, projectToolchain: resolution.projectToolchain, - preferredConfigurationID: selectedConfiguration?.id) - } - return true - } catch { - configurationSaveError = editorSaveFailureMessage(error, fallbackStage: .reload) - return false - } - } - - /// Reads current project defaults at save time. The configuration editor - /// never writes a runtime-settings mirror back over the local document. + /// Writes the editor's values to the chosen layer, then reloads the effective + /// configuration so the editor shows exactly what Core now resolves. @discardableResult package func saveEditorChanges( _ options: RunOptions, @@ -1153,30 +944,26 @@ package final class RunService: ObservableObject, BuildRunLaunching { configurationSaveError = "Identify the project before editing its run configuration." return false } - let inspection = runConfigurationOperations.inspect(at: projectURL, checkFingerprint: false, javaEntrypoints: nil) + let inspection = runConfigurationOperations.inspect(at: projectURL, checkFingerprint: false, providerRuns: nil) if case .invalid(let message) = inspection.status { configurationSaveError = message return false } - let projectDefaults = inspection.projectToolchain ?? ProjectToolchainSelection() do { try runConfigurationOperations.saveEditorChanges( options, - toolchain: projectDefaults, configurationID: configuration.id, scope: scope, at: projectURL ) - savedProjectToolchain = projectDefaults } catch { configurationSaveError = editorSaveFailureMessage(error, fallbackStage: .write) return false } do { - let resolution = try resolveWithServiceToolchains( + let resolution = try resolveWithToolchainCandidates( operations: runConfigurationOperations, - projectURL: projectURL, - preferredConfigurationID: configuration.id + projectURL: projectURL ) configurationDiagnostics = diagnosticsAfterDocumentEdit( at: projectURL, @@ -1184,7 +971,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { ) apply( resolution.configurations, - projectToolchain: resolution.projectToolchain, preferredConfigurationID: configuration.id ) } catch { @@ -1205,48 +991,9 @@ package final class RunService: ObservableObject, BuildRunLaunching { ) } - @discardableResult - package func createConfiguration(_ draft: RunConfigurationDraft) -> Bool { - configurationSaveError = nil - guard configurationStatus == .ready, let projectURL else { - configurationSaveError = "Identify the project before creating a run configuration." - return false - } - do { - let id = try runConfigurationOperations.createConfiguration(draft, at: projectURL) - let resolution = try resolveWithServiceToolchains( - operations: runConfigurationOperations, - projectURL: projectURL, - preferredConfigurationID: id - ) - guard resolution.configurations.contains(where: { $0.configuration.id == id }) else { - throw RunConfigurationOperationFailure( - message: "The new configuration did not pass project validation. Check its module and main class." - ) - } - configurationDiagnostics = diagnosticsAfterDocumentEdit( - at: projectURL, - resolution: resolution.diagnostics - ) - apply( - resolution.configurations, - projectToolchain: resolution.projectToolchain, - preferredConfigurationID: id - ) - selectedConfigurationIDsByProject[projectURL.path] = id - return true - } catch { - configurationSaveError = error.localizedDescription - return false - } - } - - package func runSelected( - currentFileURL: URL?, - javaLaunch: JavaDebugLaunchTarget? = nil - ) { + package func runSelected(currentFileURL: URL?) { guard let configuration = selectedConfiguration else { return } - run(configuration: configuration, currentFileURL: currentFileURL, javaLaunch: javaLaunch) + run(configuration: configuration, currentFileURL: currentFileURL) } /// A build provider has already prepared and Core has validated the launch. @@ -1254,13 +1001,11 @@ package final class RunService: ObservableObject, BuildRunLaunching { package func prepareRunExecutable(_ preparation: BuildRunPreparation, workspaceURL: URL, configuration: RunConfiguration?) async throws -> ResolvedRunExecutable? { let options: RunOptions if let configuration { - options = effectiveOptions(for: configuration, mavenContext: try mavenContext(for: configuration)) + options = self.options(for: configuration) } else { - let inspection = runConfigurationOperations.inspect(at: workspaceURL, checkFingerprint: false, javaEntrypoints: nil) + let inspection = runConfigurationOperations.inspect(at: workspaceURL, checkFingerprint: false, providerRuns: nil) if case .invalid(let message) = inspection.status { throw RunConfigurationOperationFailure(message: message) } - let toolchain = inspection.projectToolchain ?? ProjectToolchainSelection() - options = RunOptions(javaHomePath: toolchain.javaHomePath, mavenExecutablePath: toolchain.mavenExecutablePath, - mavenJavaHomePath: toolchain.mavenJavaHomePath) + options = RunOptions() } return try await executableResolver.prepare(preparation.launchPlan, projectURL: workspaceURL, options: options) } @@ -1287,22 +1032,14 @@ package final class RunService: ObservableObject, BuildRunLaunching { fileAccess.isDirectory(at: directory) else { throw RunConfigurationOperationFailure(message: L10n.string("The build provider returned an invalid launch plan.")) } - // Read the workspace's actual defaults even before Run configurations + // Read the workspace's actual documents even before Run configurations // are generated; a cached selection may belong to a different workspace. - let inspection = runConfigurationOperations.inspect(at: workspace, checkFingerprint: false, javaEntrypoints: nil) + let inspection = runConfigurationOperations.inspect(at: workspace, checkFingerprint: false, providerRuns: nil) if case .invalid(let message) = inspection.status { throw RunConfigurationOperationFailure(message: message) } - let toolchain = inspection.projectToolchain ?? ProjectToolchainSelection() - let options: RunOptions - if let configuration { - options = effectiveOptions(for: configuration, mavenContext: try mavenContext(for: configuration)) - } else { - options = RunOptions(javaHomePath: toolchain.javaHomePath, - mavenExecutablePath: toolchain.mavenExecutablePath, mavenJavaHomePath: toolchain.mavenJavaHomePath) - } + let options = configuration.map { self.options(for: $0) } ?? RunOptions() let resolved = try resolvedExecutable ?? executableResolver.resolve(plan, projectURL: workspace, options: options) - let arguments = try prepareJavaLaunch(executablePath: resolved.executableURL.path, arguments: plan.arguments) // The preparation is handing off successfully, so Stop must not cancel // the provider request that is currently returning this application. let runIdentity = retainingIdentity ?? (buildPreparationID == nil ? nil : primaryExecutionID) @@ -1322,16 +1059,14 @@ package final class RunService: ObservableObject, BuildRunLaunching { primaryExecutionID = runIdentity ?? operationID activeOperationID = operationID configurePrimaryProcess(operationID: operationID) - activeLaunchArgumentLease = arguments.lease runningTitle = title isRunning = true append("$ " + resolved.executableURL.lastPathComponent + " " + plan.arguments.joined(separator: " ") + "\n\n") do { try process.start(ProcessRequest(operationID: operationID, executablePath: resolved.executableURL.path, - arguments: arguments.arguments, workingDirectory: directory.path, environment: resolved.environment)) + arguments: plan.arguments, workingDirectory: directory.path, environment: resolved.environment)) return operationID } catch { - activeLaunchArgumentLease = nil activeOperationID = nil isRunning = false runningTitle = nil @@ -1416,47 +1151,26 @@ package final class RunService: ObservableObject, BuildRunLaunching { pluginRunEnded.send(PluginRunEnd(runID: runID, exitCode: exitCode)) } - package func restart(javaLaunch: JavaDebugLaunchTarget? = nil) { + package func restart() { guard let lastRunConfiguration else { return } - run( - configuration: lastRunConfiguration, - currentFileURL: lastCurrentFileURL, - javaLaunch: javaLaunch - ) + run(configuration: lastRunConfiguration, currentFileURL: lastCurrentFileURL) } - package func run( - configuration: RunConfiguration, - currentFileURL: URL?, - javaLaunch: JavaDebugLaunchTarget? = nil - ) { + package func run(configuration: RunConfiguration, currentFileURL: URL?) { providerDebugConfigurationID = nil - if configuration.buildProvider != nil && !needsProviderLaunch(configuration, javaLaunch: javaLaunch) { startBuildProviderRun(configuration); return } + if configuration.buildProvider != nil && !needsProviderLaunch(configuration) { startBuildProviderRun(configuration); return } stop() - do { try validateProviderGeneration(for: configuration) } - catch { fail(error.localizedDescription); return } output = "" lastExitCode = nil primaryExecutionID = UUID().uuidString lastRunConfiguration = configuration lastCurrentFileURL = currentFileURL - if needsProviderLaunch(configuration, javaLaunch: javaLaunch), let projectURL { + if needsProviderLaunch(configuration), let projectURL { prepareProviderConfiguration(configuration, workspace: projectURL, primary: true) return } - let mavenContext: MavenLaunchContext? - do { mavenContext = try self.mavenContext(for: configuration) } - catch { fail(error.localizedDescription); return } - let options = effectiveOptions(for: configuration, mavenContext: mavenContext) - let usesGenericCurrentFile = configuration.kind == .currentFile - && isGenericCurrentFile(currentFileURL) - if !usesGenericCurrentFile { - let configuredJavaHome = options.javaHomePath.trimmingCharacters(in: .whitespacesAndNewlines) - if !configuredJavaHome.isEmpty && runtime.javaHomeURL(overridePath: configuredJavaHome) == nil { - fail("JDK Home does not point to a directory: " + configuredJavaHome) - return - } - } + let options = self.options(for: configuration) + let usesCurrentFile = configuration.kind == .currentFile guard configurationStatus == .ready, let projectURL else { fail("Project run configuration is missing. Identify the project before running.") @@ -1466,12 +1180,11 @@ package final class RunService: ObservableObject, BuildRunLaunching { fail(diagnostic.message) return } - if configuration.kind == .currentFile, currentFileURL == nil { + if usesCurrentFile, currentFileURL == nil { fail(L10n.string("Open a source file before running Current File.")) return } - let currentFile = currentFileURL.flatMap { relativePath(for: $0, root: projectURL) } - let requiredExtensionLanguageID = configuration.kind == .currentFile + let requiredExtensionLanguageID = usesCurrentFile ? currentFileURL.flatMap { languageProviderCatalog.provider(for: $0)?.id } : configuration.kind.providerID if let requiredExtensionLanguageID, @@ -1483,7 +1196,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { let plan: SharedLaunchPlan var extensionSession: (any LanguageExecutionSession)? do { - if usesGenericCurrentFile, let currentFileURL { + if usesCurrentFile, let currentFileURL { if let provider = languageRunExtension(for: currentFileURL) { guard let relativeFilePath = relativePath(for: currentFileURL, root: projectURL) else { throw LanguageRunPlanError.fileOutsideWorkspace(currentFileURL) @@ -1506,12 +1219,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { } else { plan = try runConfigurationOperations.launchPlan( at: projectURL, - configurationID: configuration.id, - currentFile: currentFile, - classPath: nil, - javaLaunch: javaLaunch, - debugPort: nil, - mavenContext: mavenContext + configurationID: configuration.id ) extensionSession = languageRunExtension( providerID: configuration.kind.providerID @@ -1522,122 +1230,70 @@ package final class RunService: ObservableObject, BuildRunLaunching { return } let resolved: ResolvedRunExecutable - let preparedSteps: [PreparedLaunchStep] do { resolved = try executableResolver.resolve(plan, projectURL: projectURL, options: options) - preparedSteps = try plan.preLaunchSteps.map { step in - let stepResolved = try executableResolver.resolve( - step: step, plan: plan, projectURL: projectURL, options: options - ) - return PreparedLaunchStep( - executablePath: stepResolved.executableURL.path, - arguments: Self.launchArguments(step.arguments, classpath: step.classpath), - environment: stepResolved.environment, - displayName: stepResolved.executableURL.lastPathComponent, - workingDirectory: resolvedWorkingDirectory( - step.workingDirectory ?? plan.workingDirectory, - fallback: projectURL - ).path - ) - } } catch { fail(error.localizedDescription) return } - let requestedArguments = Self.launchArguments( - plan.arguments, - classpath: plan.classpath, - modulepath: plan.modulepath - ) let workingDirectory = resolvedWorkingDirectory(plan.workingDirectory, fallback: projectURL) runningTitle = configuration.name isRunning = true - let displayedArguments = configuration.kind.isMavenBacked - ? redactedMavenArgumentsForDisplay(requestedArguments) - : requestedArguments append( "$ " + resolved.executableURL.lastPathComponent + " " - + displayedArguments.joined(separator: " ") + "\n\n" + + plan.arguments.joined(separator: " ") + "\n\n" ) let operationID = UUID().uuidString activeOperationID = operationID configurePrimaryProcess(operationID: operationID) - // The main process starts only after every compile step exits zero, so a - // standalone Java file is compiled with `javac` before `java `. - let startMain: @MainActor () -> Void = { [weak self] in - guard let self, self.activeOperationID == operationID else { return } - do { - let preparation = try self.prepareJavaLaunch( + do { + if let extensionSession { + activeLanguageExecutionSession = extensionSession + configureLanguageExecutionSession(extensionSession) + try extensionSession.start(LanguageExecutionProcessRequest( + operationID: operationID, executablePath: resolved.executableURL.path, - arguments: requestedArguments - ) - self.activeLaunchArgumentLease = preparation.lease - if let extensionSession { - self.activeLanguageExecutionSession = extensionSession - self.configureLanguageExecutionSession(extensionSession) - try extensionSession.start(LanguageExecutionProcessRequest( - operationID: operationID, - executablePath: resolved.executableURL.path, - arguments: preparation.arguments, - workingDirectory: workingDirectory.path, - environment: resolved.environment - )) - } else { - try self.process.start(ProcessRequest( - operationID: operationID, - executablePath: resolved.executableURL.path, - arguments: preparation.arguments, - workingDirectory: workingDirectory.path, - environment: resolved.environment - )) - } - } catch { - self.activeLaunchArgumentLease = nil - self.activeLanguageExecutionSession = nil - self.fail("Unable to start " + configuration.name + ": " + error.localizedDescription) + arguments: plan.arguments, + workingDirectory: workingDirectory.path, + environment: resolved.environment + )) + } else { + try process.start(ProcessRequest( + operationID: operationID, + executablePath: resolved.executableURL.path, + arguments: plan.arguments, + workingDirectory: workingDirectory.path, + environment: resolved.environment + )) } - } - if preparedSteps.isEmpty { - startMain() - } else { - runPreLaunchStep( - at: 0, - steps: preparedSteps, - owner: applicationPreLaunchOwner(operationID: operationID), - onSuccess: startMain - ) + } catch { + activeLanguageExecutionSession = nil + fail("Unable to start " + configuration.name + ": " + error.localizedDescription) } } - package func runAllServices( - javaLaunches: [String: JavaDebugLaunchTarget] = [:] - ) { + package func runAllServices() { providerDebugConfigurationID = nil let serviceConfigurations = configurations.filter { $0.execution == .service } guard !serviceConfigurations.isEmpty else { fail(L10n.string("No runnable services were detected in this project.")) return } - do { for configuration in serviceConfigurations { try validateProviderGeneration(for: configuration) } } - catch { fail(error.localizedDescription); return } stopAllServices() moduleSessions = [] for configuration in serviceConfigurations { - startModuleSession(configuration, javaLaunch: javaLaunches[configuration.id]) + startModuleSession(configuration) } } - package func startConfiguration( - _ configuration: RunConfiguration, - javaLaunch: JavaDebugLaunchTarget? = nil - ) { + package func startConfiguration(_ configuration: RunConfiguration) { providerDebugConfigurationID = nil - if configuration.buildProvider != nil && !needsProviderLaunch(configuration, javaLaunch: javaLaunch) { startBuildProviderRun(configuration); return } + if configuration.buildProvider != nil && !needsProviderLaunch(configuration) { startBuildProviderRun(configuration); return } guard configuration.kind != .currentFile else { return } stopModule(sessionID: configuration.id) - startModuleSession(configuration, javaLaunch: javaLaunch) + startModuleSession(configuration) } package func stopModule(_ session: RunSession) { @@ -1652,19 +1308,17 @@ package final class RunService: ObservableObject, BuildRunLaunching { startModuleSession(configuration) } - /// Whether any service session still owns a process, a pre-launch step, - /// or a language-extension execution. + /// Whether any service session still owns a process or a + /// language-extension execution. package var hasRunningServices: Bool { !moduleProcesses.isEmpty || !moduleLanguageExecutionSessions.isEmpty - || !modulePreLaunchProcesses.isEmpty || !providerModulePreparations.isEmpty } package func stopAllServices() { let sessionIDs = Set(moduleProcesses.keys) .union(moduleLanguageExecutionSessions.keys) - .union(modulePreLaunchProcesses.keys) .union(providerModulePreparations.keys) for sessionID in sessionIDs { stopModule(sessionID: sessionID) @@ -1695,10 +1349,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { if let preparation { cancelBuildRun?(preparation) } activeLanguageExecutionSession?.stop() activeLanguageExecutionSession = nil - activePreLaunchProcess?.stop() - activePreLaunchProcess = nil process.stop() - activeLaunchArgumentLease = nil isRunning = false runningTitle = nil activeOperationID = nil @@ -1729,11 +1380,8 @@ package final class RunService: ObservableObject, BuildRunLaunching { defaultConfigurationID = nil selectedConfigurationID = RunConfiguration.currentFileID optionsByConfigurationID = [:] - projectToolchain = ProjectToolchainSelection() - savedProjectToolchain = nil effectiveSourcesByConfigurationID = [:] moduleSessions = [] - portConflicts = [] configurationStatus = .missing requiresConfigurationGeneration = false configurationDiagnostics = [] @@ -1883,14 +1531,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { ).localizedDescription } - private func isGenericCurrentFile(_ fileURL: URL?) -> Bool { - guard let fileURL else { return false } - guard let descriptor = languageProviderCatalog.provider(for: fileURL) else { - return true - } - return descriptor.id != "java" - } - package func blockingToolchainDiagnostic( for configuration: RunConfiguration? ) -> RunConfigurationDiagnostic? { @@ -1905,80 +1545,28 @@ package final class RunService: ObservableObject, BuildRunLaunching { diagnostic.code == "missingToolchain" || diagnostic.code == "toolchainVersionMismatch" } - private func toolchainCandidates( - projectURL: URL, - options: RunOptions? = nil - ) -> [ProjectToolchainCandidate] { - let runtimeCandidates = runtime.runConfigurationToolchainCandidates( - projectRoot: projectURL, - javaHomeOverride: options?.javaHomePath, - mavenExecutableOverride: options?.mavenExecutablePath - ) - return mergingExecutableCandidates(runtimeCandidates, projectURL: projectURL) - } - - private func mergingExecutableCandidates(_ runtimeCandidates: [ProjectToolchainCandidate], projectURL: URL) -> [ProjectToolchainCandidate] { - var candidatesByID = Dictionary(uniqueKeysWithValues: runtimeCandidates.map { ($0.id, $0) }) + /// Resolves the stored run configurations against the toolchain + /// candidates the registered executable providers can currently see. + private func resolveWithToolchainCandidates( + operations: any RunConfigurationOperations, + projectURL: URL + ) throws -> RunConfigurationResolution { + var candidatesByID: [String: ProjectToolchainCandidate] = [:] for candidate in executableResolver.candidates(projectURL: projectURL) where candidatesByID[candidate.id] == nil { candidatesByID[candidate.id] = candidate } - return candidatesByID.values.sorted { $0.id < $1.id } - } - - private func resolveLoadedProjectToolchains( - operations: any RunConfigurationOperations, - projectURL: URL, - preferredConfigurationID: String?, - loadID: UUID - ) async throws -> RunConfigurationResolution { - func candidates(options: RunOptions? = nil) async throws -> [ProjectToolchainCandidate] { - let runtimeCandidates = try await runtime.loadRunConfigurationToolchainCandidates( - projectRoot: projectURL, - javaHomeOverride: options?.javaHomePath, - mavenExecutableOverride: options?.mavenExecutablePath - ) - guard !Task.isCancelled, projectLoadID == loadID else { throw CancellationError() } - return mergingExecutableCandidates(runtimeCandidates, projectURL: projectURL) - } - let initial = try operations.resolve(at: projectURL, toolchainCandidates: await candidates()) - guard let options = javaServiceOptions(in: initial, preferredID: preferredConfigurationID) else { return initial } - return try operations.resolve(at: projectURL, toolchainCandidates: await candidates(options: options)) - } - - private func javaServiceOptions(in resolution: RunConfigurationResolution, preferredID: String?) -> RunOptions? { - let preferred = resolution.configurations.first { $0.configuration.id == preferredID } - return (preferred ?? resolution.configurations.first { - $0.configuration.kind.capabilities.contains(.javaRuntime) && !$0.options.javaHomePath.isEmpty - })?.options - } - - private func resolveWithServiceToolchains( - operations: any RunConfigurationOperations, - projectURL: URL, - preferredConfigurationID: String? - ) throws -> RunConfigurationResolution { - let initial = try operations.resolve( - at: projectURL, - toolchainCandidates: toolchainCandidates(projectURL: projectURL) - ) - guard let options = javaServiceOptions(in: initial, preferredID: preferredConfigurationID) else { return initial } - let candidates = toolchainCandidates( - projectURL: projectURL, - options: options - ) + let candidates = candidatesByID.values.sorted { $0.id < $1.id } return try operations.resolve(at: projectURL, toolchainCandidates: candidates) } private func apply( _ effective: [EffectiveRunConfiguration], - projectToolchain: ProjectToolchainSelection = ProjectToolchainSelection(), preferredConfigurationID: String? = nil ) { // Keep the language-neutral Current File entry available even when a // project has no declared service. Its launch plan is selected by the - // active language Provider at run time; Java projects still fall back - // to the legacy core path. + // active language Provider at run time. var seenConfigurationIDs = Set() var resolved = effective.filter { seenConfigurationIDs.insert($0.configuration.id).inserted @@ -1997,25 +1585,16 @@ package final class RunService: ObservableObject, BuildRunLaunching { optionsByConfigurationID = Dictionary(uniqueKeysWithValues: resolved.map { ($0.configuration.id, $0.options) }) - self.projectToolchain = projectToolchain - let preferredJava = resolved.first { item in - item.configuration.id == preferredConfigurationID - && item.configuration.kind.capabilities.contains(.javaRuntime) - } ?? resolved.first { $0.configuration.kind.capabilities.contains(.javaRuntime) } - runtime.setActiveServiceJavaHomePath(preferredJava?.options.javaHomePath ?? "") effectiveSourcesByConfigurationID = Dictionary(uniqueKeysWithValues: resolved.map { ($0.configuration.id, $0.source) }) dependencyRevision &+= 1 reconcileModuleSessions(validConfigurationIDs: Set(configurations.map(\.id))) - refreshPortConflicts() if let preferredConfigurationID, configurations.contains(where: { $0.id == preferredConfigurationID }) { selectedConfigurationID = preferredConfigurationID } else if !configurations.contains(where: { $0.id == selectedConfigurationID }) { - selectedConfigurationID = configurations.first(where: { $0.kind.mavenFramework != nil })?.id - ?? configurations.first?.id - ?? RunConfiguration.currentFileID + selectedConfigurationID = configurations.first?.id ?? RunConfiguration.currentFileID } } @@ -2031,7 +1610,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { let debugOperation = providerDebugOperationID providerDebugOperationID = nil activeLanguageExecutionSession = nil - activeLaunchArgumentLease = nil isRunning = false runningTitle = nil lastExitCode = exitCode @@ -2040,19 +1618,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { endPluginRun(exitCode: exitCode) } - private func prepareJavaLaunch( - executablePath: String, - arguments: [String] - ) throws -> JavaLaunchArgumentPreparation { - guard let javaLaunchArgumentPreparer else { - return JavaLaunchArgumentPreparation(arguments: arguments) - } - return try javaLaunchArgumentPreparer.prepareJavaLaunch( - executablePath: executablePath, - arguments: arguments - ) - } - private func consumeLifecycle(_ event: ProcessLifecycleEvent) { guard event.operationID == activeOperationID else { return } switch event.state { @@ -2148,185 +1713,8 @@ package final class RunService: ObservableObject, BuildRunLaunching { } } - /// A pre-launch compile step whose executable, arguments, and working - /// directory are already resolved to absolute values. - private struct PreparedLaunchStep { - let executablePath: String - let arguments: [String] - let environment: [String: String] - let displayName: String - /// The step's own run directory: a Maven resource step has to run from - /// the reactor that holds its wrapper, not from an overridden app cwd. - let workingDirectory: String - } - - /// The per-run bookkeeping a pre-launch chain reads and writes. The - /// application run and each module session supply their own, so a step is - /// cancelled with its owner and a superseded run cannot resume the chain. - private struct PreLaunchOwner: Sendable { - let operationID: String - let isActive: @MainActor @Sendable () -> Bool - let setStepProcess: @MainActor @Sendable ((any StreamingProcess)?) -> Void - let append: @MainActor @Sendable (String) -> Void - /// Marks the owning run failed and releases its operation so a later - /// step, or the process the chain guards, cannot start. - let fail: @MainActor @Sendable (Int32) -> Void - } - - /// Merges the plan's structured classpath into the launch arguments. The - /// separator stays host-owned (`:` on macOS) because the Rust core emits a - /// list, not a platform-specific string. When the user already passes a - /// `-cp`/`-classpath`/`--class-path`, our entries are prepended into that - /// same flag's value (the compiled output must lead, and a second `-cp` - /// would simply override the user's — the JVM honors only the last one). - /// Otherwise a leading `-cp` is inserted; JVM options may precede the main - /// class in any order. - private static func launchArguments( - _ base: [String], - classpath: [String], - modulepath: [String] = [] - ) -> [String] { - var merged = mergePath( - classpath, - flags: ["-cp", "-classpath", "--class-path"], - into: base - ) - merged = mergePath(modulepath, flags: ["-p", "--module-path"], into: merged) - return merged - } - - private static func mergePath( - _ paths: [String], - flags: Set, - into base: [String] - ) -> [String] { - guard !paths.isEmpty else { return base } - let joined = paths.joined(separator: ":") - // Merge into the last existing flag: that is the value the JVM would use. - for index in stride(from: base.count - 2, through: 0, by: -1) - where flags.contains(base[index]) { - var merged = base - merged[index + 1] = joined + ":" + base[index + 1] - return merged - } - return [flags.contains("-cp") ? "-cp" : "--module-path", joined] + base - } - - /// Runs one pre-launch step, then chains to the next on a zero exit or aborts - /// the run and surfaces the step's output on a non-zero exit. Uses a fresh - /// process per step so the owning run's process wiring stays untouched. - private func runPreLaunchStep( - at index: Int, - steps: [PreparedLaunchStep], - owner: PreLaunchOwner, - onSuccess: @escaping @MainActor () -> Void - ) { - guard owner.isActive() else { return } - guard index < steps.count else { - onSuccess() - return - } - let step = steps[index] - owner.append("$ " + step.displayName + " " + step.arguments.joined(separator: " ") + "\n") - let stepProcess = processFactory() - owner.setStepProcess(stepProcess) - stepProcess.onOutput = { chunk in - Task { @MainActor in owner.append(chunk) } - } - // The platform stops a step that passes its deadline with this message. - // Name the deadline in the Run's own wording, as the test service and - // the Windows runner do; a user Stop uses another message and stays - // silent, because the Stop itself is already visible. - let timedOutNotice = - "\nPre-launch step timed out after \(Self.preLaunchStepTimeoutMilliseconds / 1_000) seconds.\n" - stepProcess.onStateChange = { event in - guard event.state == .stopping, event.message == "Process timed out" else { return } - Task { @MainActor in owner.append(timedOutNotice) } - } - stepProcess.onTermination = { exitCode in - Task { @MainActor in - owner.setStepProcess(nil) - guard owner.isActive() else { return } - if exitCode == 0 { - self.runPreLaunchStep( - at: index + 1, - steps: steps, - owner: owner, - onSuccess: onSuccess - ) - } else { - owner.append("\nPre-launch step failed (exit code \(exitCode)).\n") - owner.fail(exitCode) - } - } - } - do { - try stepProcess.start(ProcessRequest( - operationID: owner.operationID, - executablePath: step.executablePath, - arguments: step.arguments, - workingDirectory: step.workingDirectory, - environment: step.environment, - timeoutMilliseconds: Self.preLaunchStepTimeoutMilliseconds - )) - } catch { - owner.setStepProcess(nil) - guard owner.isActive() else { return } - owner.append( - "\nUnable to start " + step.displayName + ": " + error.localizedDescription + "\n" - ) - owner.fail(1) - } - } - - /// Pre-launch bookkeeping for the application run: the chain stops as soon - /// as the run is stopped or replaced, and a failed step leaves the same - /// state a failed main process would. - private func applicationPreLaunchOwner(operationID: String) -> PreLaunchOwner { - PreLaunchOwner( - operationID: operationID, - isActive: { [weak self] in self?.activeOperationID == operationID }, - setStepProcess: { [weak self] process in self?.activePreLaunchProcess = process }, - append: { [weak self] value in self?.append(value) }, - fail: { [weak self] exitCode in - guard let self else { return } - self.isRunning = false - self.runningTitle = nil - self.activeOperationID = nil - self.lastExitCode = exitCode - } - ) - } - - /// Pre-launch bookkeeping for a module session: the chain owns the session's - /// pre-launch process so Stop, restart, and reconciliation cancel it before - /// the JVM exists, and a failed step makes the session fail instead of - /// launching against stale resources. - private func modulePreLaunchOwner(sessionID: String, operationID: String) -> PreLaunchOwner { - PreLaunchOwner( - operationID: operationID, - isActive: { [weak self] in self?.moduleOperationIDs[sessionID] == operationID }, - setStepProcess: { [weak self] process in - self?.modulePreLaunchProcesses[sessionID] = process - }, - append: { [weak self] value in - self?.appendModuleOutput(value, sessionID: sessionID) - }, - fail: { [weak self] exitCode in - guard let self else { return } - self.modulePreLaunchProcesses[sessionID] = nil - self.moduleOperationIDs[sessionID] = nil - if let index = self.moduleSessions.firstIndex(where: { $0.id == sessionID }) { - self.moduleSessions[index].isRunning = false - self.moduleSessions[index].exitCode = exitCode - } - } - ) - } - private func startModuleSession( _ configuration: RunConfiguration, - javaLaunch: JavaDebugLaunchTarget? = nil, preparedPlan: SharedLaunchPlan? = nil, preparationOperationID: String? = nil, resolvedExecutable: ResolvedRunExecutable? = nil @@ -2336,12 +1724,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { let preparingSession = preparedPlan == nil ? nil : moduleSessions.first(where: { $0.id == configuration.id }) let preparationOutput = preparingSession?.output ?? "" moduleSessions.removeAll { $0.id == configuration.id } - do { try validateProviderGeneration(for: configuration) } - catch { - moduleSessions.append(RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, id: configuration.id, configurationID: configuration.id, - title: configuration.name, output: error.localizedDescription + "\n", isRunning: false, exitCode: 1)) - return - } if let diagnostic = blockingToolchainDiagnostic(for: configuration) { moduleSessions.append(RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, id: configuration.id, @@ -2365,49 +1747,19 @@ package final class RunService: ObservableObject, BuildRunLaunching { )) return } - if preparedPlan == nil && needsProviderLaunch(configuration, javaLaunch: javaLaunch) { + if preparedPlan == nil && needsProviderLaunch(configuration) { prepareProviderConfiguration(configuration, workspace: projectURL, primary: false) return } - let mavenContext: MavenLaunchContext? - do { mavenContext = try self.mavenContext(for: configuration) } - catch { - moduleSessions.append(RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, id: configuration.id, configurationID: configuration.id, - title: configuration.name, output: error.localizedDescription + "\n", isRunning: false, exitCode: 1)) - return - } - let options = effectiveOptions(for: configuration, mavenContext: mavenContext) - let launchesJavaDirectly = configuration.kind == .javaMain || javaLaunch != nil - let configuredJavaHome = (launchesJavaDirectly || options.mavenJavaHomePath.isEmpty - ? options.javaHomePath - : options.mavenJavaHomePath).trimmingCharacters(in: .whitespacesAndNewlines) - let resolvedJavaHome = launchesJavaDirectly - ? runtime.javaHomeURL(overridePath: configuredJavaHome) - : runtime.mavenJavaHomeURL(overridePath: configuredJavaHome) - if !configuredJavaHome.isEmpty && resolvedJavaHome == nil { - moduleSessions.append(RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, - id: configuration.id, - configurationID: configuration.id, - title: configuration.name, - output: "JDK Home does not point to a directory: " + configuredJavaHome + "\n", - isRunning: false, - exitCode: 1 - )) - return - } + let options = self.options(for: configuration) let plan: SharedLaunchPlan do { if let preparedPlan { plan = preparedPlan } else { - plan = try runConfigurationOperations.launchPlan( - at: projectURL, - configurationID: configuration.id, - currentFile: nil, - classPath: nil, - javaLaunch: javaLaunch, - debugPort: nil, - mavenContext: mavenContext - ) + plan = try runConfigurationOperations.launchPlan( + at: projectURL, + configurationID: configuration.id + ) } } catch { moduleSessions.append(RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, @@ -2422,24 +1774,8 @@ package final class RunService: ObservableObject, BuildRunLaunching { } let resolved: ResolvedRunExecutable - let preparedSteps: [PreparedLaunchStep] do { resolved = try resolvedExecutable ?? executableResolver.resolve(plan, projectURL: projectURL, options: options) - preparedSteps = try plan.preLaunchSteps.map { step in - let stepResolved = try executableResolver.resolve( - step: step, plan: plan, projectURL: projectURL, options: options - ) - return PreparedLaunchStep( - executablePath: stepResolved.executableURL.path, - arguments: Self.launchArguments(step.arguments, classpath: step.classpath), - environment: stepResolved.environment, - displayName: stepResolved.executableURL.lastPathComponent, - workingDirectory: resolvedWorkingDirectory( - step.workingDirectory ?? plan.workingDirectory, - fallback: projectURL - ).path - ) - } } catch { // A service that cannot start still becomes a session so the panel // shows which one failed and why, rather than silently omitting it. @@ -2453,114 +1789,74 @@ package final class RunService: ObservableObject, BuildRunLaunching { )) return } - let requestedArguments = Self.launchArguments( - plan.arguments, - classpath: plan.classpath, - modulepath: plan.modulepath - ) let workingDirectory = resolvedWorkingDirectory(plan.workingDirectory, fallback: projectURL) - var session = RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, + let session = RunSession(executionID: preparingSession?.executionID ?? UUID().uuidString, id: configuration.id, configurationID: configuration.id, title: configuration.name, output: preparationOutput + "$ " + resolved.executableURL.lastPathComponent + " " - + (configuration.kind.isMavenBacked - ? redactedMavenArgumentsForDisplay(requestedArguments) - : requestedArguments).joined(separator: " ") + "\n\n", + + plan.arguments.joined(separator: " ") + "\n\n", isRunning: true, exitCode: nil ) - session.javaUpdateTarget = javaLaunch - if let sourcePath = configuration.sourcePath { - session.javaUpdateSource = projectURL.appendingPathComponent(sourcePath) - } moduleSessions.append(session) let operationID = preparationOperationID ?? UUID().uuidString moduleOperationIDs[configuration.id] = operationID - // The JVM waits for every pre-launch step, so an entry source with a - // Maven resource step starts against the resources the step just wrote. - let startMainProcess: @MainActor () -> Void = { [weak self] in - guard let self, self.moduleOperationIDs[configuration.id] == operationID else { - return - } - do { - let preparation = try self.prepareJavaLaunch( + do { + if let provider = languageRunExtension( + providerID: configuration.kind.providerID + ) { + let extensionSession = provider.makeExecutionSession() + configureModuleLanguageExecutionSession( + extensionSession, + sessionID: configuration.id + ) + moduleLanguageExecutionSessions[configuration.id] = extensionSession + try extensionSession.start(LanguageExecutionProcessRequest( + operationID: operationID, + executablePath: resolved.executableURL.path, + arguments: plan.arguments, + workingDirectory: workingDirectory.path, + environment: resolved.environment + )) + } else { + let process = processFactory() + configureModuleProcess(process, sessionID: configuration.id) + moduleProcesses[configuration.id] = process + try process.start(ProcessRequest( + operationID: operationID, executablePath: resolved.executableURL.path, - arguments: requestedArguments + arguments: plan.arguments, + workingDirectory: workingDirectory.path, + environment: resolved.environment + )) + } + } catch { + moduleProcesses[configuration.id] = nil + moduleLanguageExecutionSessions[configuration.id] = nil + moduleOperationIDs[configuration.id] = nil + if let index = moduleSessions.firstIndex(where: { $0.id == configuration.id }) { + moduleSessions[index].isRunning = false + moduleSessions[index].exitCode = 1 + appendModuleOutput( + "Unable to start " + configuration.name + ": " + + error.localizedDescription + "\n", + sessionID: configuration.id ) - self.moduleLaunchArgumentLeases[configuration.id] = preparation.lease - if let provider = self.languageRunExtension( - providerID: configuration.kind.providerID - ) { - let extensionSession = provider.makeExecutionSession() - self.configureModuleLanguageExecutionSession( - extensionSession, - sessionID: configuration.id - ) - self.moduleLanguageExecutionSessions[configuration.id] = extensionSession - try extensionSession.start(LanguageExecutionProcessRequest( - operationID: operationID, - executablePath: resolved.executableURL.path, - arguments: preparation.arguments, - workingDirectory: workingDirectory.path, - environment: resolved.environment - )) - } else { - let process = self.processFactory() - self.configureModuleProcess(process, sessionID: configuration.id) - self.moduleProcesses[configuration.id] = process - try process.start(ProcessRequest( - operationID: operationID, - executablePath: resolved.executableURL.path, - arguments: preparation.arguments, - workingDirectory: workingDirectory.path, - environment: resolved.environment - )) - } - } catch { - self.moduleLaunchArgumentLeases[configuration.id] = nil - self.moduleProcesses[configuration.id] = nil - self.moduleLanguageExecutionSessions[configuration.id] = nil - self.moduleOperationIDs[configuration.id] = nil - if let index = self.moduleSessions.firstIndex(where: { $0.id == configuration.id }) { - self.moduleSessions[index].isRunning = false - self.moduleSessions[index].exitCode = 1 - self.appendModuleOutput( - "Unable to start " + configuration.name + ": " - + error.localizedDescription + "\n", - sessionID: configuration.id - ) - } } } - if preparedSteps.isEmpty { - startMainProcess() - } else { - runPreLaunchStep( - at: 0, - steps: preparedSteps, - owner: modulePreLaunchOwner( - sessionID: configuration.id, - operationID: operationID - ), - onSuccess: startMainProcess - ) - } } private func stopModule(sessionID: String) { moduleProviderSources[sessionID] = nil moduleOperationIDs[sessionID] = nil providerModulePreparations.removeValue(forKey: sessionID)?.cancel() - modulePreLaunchProcesses[sessionID]?.stop() - modulePreLaunchProcesses[sessionID] = nil moduleProcesses[sessionID]?.stop() moduleProcesses[sessionID] = nil moduleLanguageExecutionSessions[sessionID]?.stop() moduleLanguageExecutionSessions[sessionID] = nil - moduleLaunchArgumentLeases[sessionID] = nil moduleOperationIDs[sessionID] = nil if let index = moduleSessions.firstIndex(where: { $0.id == sessionID }) { moduleSessions[index].isRunning = false @@ -2576,7 +1872,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { } moduleProcesses[sessionID] = nil moduleLanguageExecutionSessions[sessionID] = nil - moduleLaunchArgumentLeases[sessionID] = nil moduleOperationIDs[sessionID] = nil } @@ -2605,7 +1900,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { private func reconcileModuleSessions(validConfigurationIDs: Set) { let activeSessionIDs = Set(moduleProcesses.keys) .union(moduleLanguageExecutionSessions.keys) - .union(modulePreLaunchProcesses.keys) .union(providerModulePreparations.keys) let staleSessionIDs = activeSessionIDs.filter { !validConfigurationIDs.contains($0) } for sessionID in staleSessionIDs { @@ -2685,59 +1979,14 @@ package final class RunService: ObservableObject, BuildRunLaunching { } } - private func refreshPortConflicts() { - let moduleConfigurations = configurations.filter { $0.kind == .mavenModule } - var configurationsByPort: [Int: [String]] = [:] - for configuration in moduleConfigurations { - let port = configuredPort(for: configuration) ?? 8080 - guard (1...65_535).contains(port) else { continue } - configurationsByPort[port, default: []].append(configuration.name) - } - portConflicts = configurationsByPort - .filter { $0.value.count > 1 } - .map { port, names in - RunPortConflict( - port: port, - configurationNames: names.sorted { - $0.localizedStandardCompare($1) == .orderedAscending - } - ) - } - .sorted { $0.port < $1.port } - } - + /// The port a service listens on, taken only from what the stored + /// options declare: a `--port`/`-p` argument or a `PORT` variable. Port + /// conventions of individual frameworks belong to the plugin that owns + /// the run configuration, not to the host. private func configuredPort(for configuration: RunConfiguration) -> Int? { let options = self.options(for: configuration) - if let port = Self.port(in: options.programArguments) ?? Self.port(in: options.vmArguments) { - return port - } - for key in ["PORT", "SERVER_PORT", "QUARKUS_HTTP_PORT", "MICRONAUT_SERVER_PORT"] { - if let value = options.environment[key], let port = Int(value), port > 0 { - return port - } - } - - let moduleRoot = configuration.modulePath.flatMap { path in - buildModels().flatMap(\.projects).first(where: { $0.path == path }) - .flatMap { project in projectURL?.appendingPathComponent(project.path, isDirectory: true) } - } ?? projectURL - guard let moduleRoot else { return nil } - let resourceFiles = projectFiles.filter { fileURL in - let name = fileURL.lastPathComponent.lowercased() - return Self.isInside(fileURL, directory: moduleRoot) && - (name == "application.properties" || name == "application.yml" || name == "application.yaml" || - (name.hasPrefix("application-") && - (name.hasSuffix(".properties") || name.hasSuffix(".yml") || name.hasSuffix(".yaml")))) - } - for fileURL in resourceFiles { - guard let data = try? fileAccess.readData(from: fileURL), - let contents = String(data: data, encoding: .utf8), - let port = serverPortParser.serverPort( - content: contents, - fileExtension: fileURL.pathExtension.lowercased() - ) else { - continue - } + if let port = Self.port(in: options.programArguments) { return port } + if let value = options.environment["PORT"], let port = Int(value), port > 0 { return port } return nil @@ -2746,11 +1995,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { private static func port(in input: String) -> Int? { let tokens = RunArgumentParser.parse(input) for (index, token) in tokens.enumerated() { - let keys = [ - "--server.port=", "-Dserver.port=", "--server.port", "-Dserver.port", - "--port=", "--port", "-p=", "-p" - ] - for key in keys where token.hasPrefix(key) { + for key in ["--port=", "--port", "-p=", "-p"] where token.hasPrefix(key) { let value: String if token == key { guard tokens.indices.contains(index + 1) else { continue } @@ -2764,44 +2009,6 @@ package final class RunService: ObservableObject, BuildRunLaunching { return nil } - private static func isInside(_ fileURL: URL, directory: URL) -> Bool { - let filePath = fileURL.standardizedFileURL.path - let directoryPath = directory.standardizedFileURL.path - return filePath.hasPrefix(directoryPath + "/") - } - - private func effectiveOptions( - for configuration: RunConfiguration, - mavenContext: MavenLaunchContext? - ) -> RunOptions { - let stored = self.options(for: configuration) - var options = runtime.overlayProjectRuntime( - onto: stored, - modulePath: configuration.modulePath, - workingDirectory: stored.workingDirectoryPath - ) - guard let mavenContext else { return options } - if options.mavenExecutablePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - options.mavenExecutablePath = mavenContext.mavenExecutablePath ?? "" - } - if options.mavenJavaHomePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - options.mavenJavaHomePath = mavenContext.javaHomePath ?? "" - } - return options - } - - private func mavenContext(for configuration: RunConfiguration) throws -> MavenLaunchContext? { - if let projectURL, let project = configuration.buildProject { - return try buildProjectImportProvider(projectURL, project).mavenContext - } - guard let projectURL, configuration.mavenReactorPath != nil || configuration.kind.isMavenBacked, - let context = try buildLanguageImportProvider(projectURL, configuration.mavenReactorPath).mavenContext else { return nil } - if let reactor = configuration.mavenReactorPath { - return reactor == context.reactorPath ? context : nil - } - return configuration.kind.isMavenBacked ? context : nil - } - private func resolvedWorkingDirectory(_ path: String, fallback: URL) -> URL { let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return fallback } @@ -2816,16 +2023,7 @@ package final class RunService: ObservableObject, BuildRunLaunching { private func optionsKey(for configurationID: String) -> String? { guard let projectURL else { return nil } let projectKey = projectURL.path.replacingOccurrences(of: "/", with: "_") - return "lithe.java-run-options.\(projectKey).\(configurationID)" - } - - private func loadOptions(for configurationID: String) -> RunOptions { - guard let key = optionsKey(for: configurationID), - let data = preferences.data(forKey: key), - let options = try? JSONDecoder().decode(RunOptions.self, from: data) else { - return RunOptions() - } - return options + return "lithe.run-options.\(projectKey).\(configurationID)" } private func persist(_ options: RunOptions, for configurationID: String) { @@ -2925,10 +2123,6 @@ private final class RegisteredLanguageRunExtension { } } -/// Compatibility name retained while Java debug remains a provider-specific -/// consumer of the generic run service. -package typealias JavaRunService = RunService - /// A process a plugin backend asked the host to run. The host has already /// resolved the executable and merged the environment; the service only runs it. package struct PluginRunLaunch { diff --git a/macos/Sources/LitheExecutionModule/Services/StandardLanguageTestProvider.swift b/macos/Sources/LitheExecutionModule/Services/StandardLanguageTestProvider.swift index b553ef1b4e..6912e63b71 100644 --- a/macos/Sources/LitheExecutionModule/Services/StandardLanguageTestProvider.swift +++ b/macos/Sources/LitheExecutionModule/Services/StandardLanguageTestProvider.swift @@ -21,7 +21,6 @@ package enum LanguageTestPlanError: LocalizedError, Equatable, Sendable { package struct StandardLanguageTestProvider: LanguageTestProvider { private enum StandardTestFramework: String { - case gradle case go case pytest case npm @@ -42,13 +41,11 @@ package struct StandardLanguageTestProvider: LanguageTestProvider { } /// Real workspace discovery carries project markers so a plain source - /// directory is not misidentified as Maven/npm/Cargo merely because it + /// directory is not misidentified as an npm/Cargo project merely because it /// contains a file whose name looks like a test. The legacy overload above /// remains permissive for callers that only have a file list. package func discoverTests(context: LanguageTestContext) -> [LanguageTestItem] { - guard descriptor.id == "java" || framework(for: descriptor.id, context: context) != nil else { return [] } - if descriptor.id == "java", !context.projectFiles.contains(where: { descriptor.handles(fileURL: $0) }), - context.projectFileNames.isDisjoint(with: ["build.gradle", "build.gradle.kts", "gradlew"]) { return [] } + guard framework(for: descriptor.id, context: context) != nil else { return [] } return makeTestItems( workspaceURL: context.workspaceURL, files: context.projectFiles @@ -91,12 +88,6 @@ package struct StandardLanguageTestProvider: LanguageTestProvider { } let plan: SharedLaunchPlan switch framework { - case .gradle: - plan = SharedLaunchPlan( - executable: .toolchain("project-gradle"), - arguments: try gradleArguments(scope: scope, root: root), - workingDirectory: "." - ) case .go: plan = SharedLaunchPlan( executable: .toolchain("project-go"), @@ -140,13 +131,6 @@ package struct StandardLanguageTestProvider: LanguageTestProvider { ) -> StandardTestFramework? { let names = context.projectFileNames switch providerID { - case "java": - if names.contains("build.gradle") - || names.contains("build.gradle.kts") - || names.contains("gradlew") { - return .gradle - } - return nil case "go": return context.projectFiles.isEmpty || names.contains("go.mod") @@ -171,11 +155,6 @@ package struct StandardLanguageTestProvider: LanguageTestProvider { let name = url.lastPathComponent.lowercased() let relative = relativePath(url, root: root).lowercased() switch descriptor.id { - case "java": - // JDT/Java Test owns semantic test discovery. Every Java source is - // offered to it so inherited tests, custom composed annotations, - // and non-conventional file names are not filtered out locally. - return true case "go": return name.hasSuffix("_test.go") case "python": @@ -190,33 +169,6 @@ package struct StandardLanguageTestProvider: LanguageTestProvider { } } - private func gradleArguments(scope: LanguageTestScope, root: URL) throws -> [String] { - // Keep test workers in this invocation's owned process tree, including - // when an unrelated reusable Gradle daemon is already running. - var arguments = ["test", "--no-daemon"] - switch scope { - case .workspace: - break - case .file(let url): - arguments.append(contentsOf: ["--tests", try gradleSelector(for: url, root: root)]) - case .testCase(let identifier, _, _): - arguments.append(contentsOf: [ - "--tests", - normalizedJavaTestIdentifier(identifier).replacingOccurrences(of: "#", with: "."), - ]) - } - return arguments - } - - private func normalizedJavaTestIdentifier(_ identifier: String) -> String { - identifier.hasSuffix("()") ? String(identifier.dropLast(2)) : identifier - } - - private func gradleSelector(for url: URL, root: URL) throws -> String { - _ = try checkedRelativePath(url, root: root) - return url.deletingPathExtension().lastPathComponent - } - private func goArguments(scope: LanguageTestScope, root: URL) throws -> [String] { switch scope { case .workspace: diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Module/LanguageIntelligenceModule.swift b/macos/Sources/LitheLanguageIntelligenceModule/Module/LanguageIntelligenceModule.swift index 6bbade7690..767d7c40d1 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Module/LanguageIntelligenceModule.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Module/LanguageIntelligenceModule.swift @@ -20,7 +20,7 @@ package protocol LanguageIntelligenceServiceGraph: AnyObject { } @MainActor -public final class LanguageIntelligenceCapability: NSObject, LanguageDependencyProviding { +public final class LanguageIntelligenceCapability: NSObject { package let sessions: LanguageToolingSessionManager package let tools: LanguageServerToolService @@ -28,15 +28,6 @@ public final class LanguageIntelligenceCapability: NSObject, LanguageDependencyP sessions = graph.sessions tools = graph.tools } - - public func dependencySnapshot(workspaceURL: URL, serviceID: String) -> LanguageDependencySnapshot? { - guard serviceID == "language:java" else { return nil } - return sessions.dependencySnapshot(workspaceURL: workspaceURL) - } - - public func setDependencySnapshotChangeHandler(_ handler: (@MainActor () -> Void)?) { - sessions.onJavaDependencySnapshotChange = handler - } } @MainActor diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift index 34d444c8f6..ae041ed476 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageProviderRuntime.swift @@ -66,6 +66,15 @@ package typealias BackendLanguageServerLaunchPreparer = @MainActor ( URL ) async throws -> PreparedLanguageServerProcess +/// Resolves, for one workspace root, a server whose launch names a tool +/// definition (`serverProcess` 4). The host resolves the tool and expands +/// the definition's template with the plugin's entry and arguments, so the +/// executable is known only when the session starts. +package typealias ToolLanguageServerLaunchPreparer = @MainActor ( + DeclarativeLanguageServerLaunchSource, + URL +) async throws -> PreparedLanguageServerProcess + @MainActor package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { package let descriptor: LanguageProviderDescriptor @@ -73,11 +82,10 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { private let languageServerLaunch: LanguageServerLaunchDescriptor? private let languageServerCore: any LanguageServerRuntimeCore private let languageServerExecutableResolver: ((LanguageProviderDescriptor) -> URL?)? - private let hostIntegrationResolver: LanguageServerHostIntegrationResolver? private let languageServerLaunchResolver: LanguageServerLaunchResolver? - private let languageServerCacheDirectory: URL? private let workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? private let backendLaunchPreparer: BackendLanguageServerLaunchPreparer? + private let toolLaunchPreparer: ToolLanguageServerLaunchPreparer? private weak var processRegistry: (any LanguageServerProcessRegistry)? private let moduleID: ModuleID private var runtimeUnavailableMessage: String? @@ -98,11 +106,10 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { languageServerLaunch: LanguageServerLaunchDescriptor? = nil, languageServerCore: any LanguageServerRuntimeCore, languageServerExecutableResolver: ((LanguageProviderDescriptor) -> URL?)? = nil, - hostIntegrationResolver: LanguageServerHostIntegrationResolver? = nil, languageServerLaunchResolver: LanguageServerLaunchResolver? = nil, - languageServerCacheDirectory: URL? = nil, workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? = nil, backendLaunchPreparer: BackendLanguageServerLaunchPreparer? = nil, + toolLaunchPreparer: ToolLanguageServerLaunchPreparer? = nil, processRegistry: (any LanguageServerProcessRegistry)? = nil, moduleID: ModuleID = .languageIntelligence ) { @@ -111,11 +118,10 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { self.languageServerLaunch = languageServerLaunch self.languageServerCore = languageServerCore self.languageServerExecutableResolver = languageServerExecutableResolver - self.hostIntegrationResolver = hostIntegrationResolver self.languageServerLaunchResolver = languageServerLaunchResolver - self.languageServerCacheDirectory = languageServerCacheDirectory self.workspaceSessionFactory = workspaceSessionFactory self.backendLaunchPreparer = backendLaunchPreparer + self.toolLaunchPreparer = toolLaunchPreparer self.processRegistry = processRegistry self.moduleID = moduleID } @@ -126,6 +132,9 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { if let source = languageServerLaunch.launchSource, source.resolvesLaunchWithBackend { return makeBackendLaunchedSession(source) } + if let source = languageServerLaunch.launchSource, source.launchesThroughTool { + return makeToolLaunchedSession(source, launch: languageServerLaunch) + } let executableURL = if let languageServerExecutableResolver { languageServerExecutableResolver(descriptor) } else if let pinned = languageServerLaunch.executableURL { @@ -136,23 +145,12 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { }).first } guard let executableURL else { return nil } - let hostIntegrationLaunch: LanguageServerHostIntegrationLaunch? - switch hostIntegrationResolver?(descriptor) { - case nil: - hostIntegrationLaunch = nil - case .available(let launch): - hostIntegrationLaunch = launch - case .unavailable(let message): - runtimeUnavailableMessage = message - return nil - } var environment = runtimeService.languageToolProcessEnvironment( runtimeTools: languageServerLaunch.runtimeTools ) - // A host integration owns the environment of its server. Any other - // server started by a runtime gets the runtime selected above, not + // A server started by a runtime gets the runtime selected above, not // another one the inherited PATH may list first. - if let tool = languageServerLaunch.launchRuntimeTool, hostIntegrationLaunch == nil { + if let tool = languageServerLaunch.launchRuntimeTool { environment = LanguageToolEnvironment.exportingRuntime( tool: tool, executableURL: executableURL, @@ -179,8 +177,6 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { environment: environment, initializationOptions: languageServerLaunch.initializationOptions, launchResolver: launchResolver, - hostIntegrationLaunch: hostIntegrationLaunch, - cacheDirectoryURL: languageServerCacheDirectory, core: languageServerCore, processRegistry: processRegistry, moduleID: moduleID, @@ -192,8 +188,10 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { 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 { + // host, which has no backend to answer the launch question and + // no tool definitions to resolve a tool launch with. + if let source = languageServerLaunch.launchSource, + source.resolvesLaunchWithBackend || source.launchesThroughTool { runtimeUnavailableMessage = L10n.string( "\(descriptor.displayName) cannot start in a remote workspace yet." ) @@ -230,6 +228,43 @@ package final class StdioLanguageProviderRuntime: LanguageProviderRuntime { ) } + /// The session of a server whose launch names a tool definition. The + /// tool resolves only for a workspace root, so the session starts with a + /// placeholder that `prepareProcess` replaces on every start. The + /// configured environment still wins over the resolved one. + private func makeToolLaunchedSession( + _ source: DeclarativeLanguageServerLaunchSource, + launch languageServerLaunch: LanguageServerLaunchDescriptor + ) -> (any LanguageServerSession)? { + guard let toolLaunchPreparer else { + runtimeUnavailableMessage = L10n.string( + "\(descriptor.displayName) needs a launch this build of Lithe cannot resolve." + ) + return nil + } + let configured = languageServerLaunch.environment + return LanguageServerRuntimeSession( + providerID: descriptor.id, + executableURL: source.packageURL, + arguments: [], + environment: [:], + prepareProcess: { rootURL in + let prepared = try await toolLaunchPreparer(source, rootURL) + var environment = prepared.environment + environment.merge(configured) { _, configured in configured } + return PreparedLanguageServerProcess( + executableURL: prepared.executableURL, environment: environment, launch: prepared.launch, + core: prepared.core, release: prepared.release + ) + }, + core: languageServerCore, + processRegistry: processRegistry, + moduleID: moduleID, + pluginID: source.pluginID, + role: .languageServer + ) + } + } @MainActor @@ -237,11 +272,10 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime private let runtimeService: any LanguageToolRuntimePort private let languageServerCore: any LanguageServerRuntimeCore private let languageServerExecutableResolver: ((LanguageProviderDescriptor) -> URL?)? - private let hostIntegrationResolver: LanguageServerHostIntegrationResolver? private let languageServerLaunchResolver: LanguageServerLaunchResolver? - private let languageServerCacheDirectory: URL? private let workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? private let backendLaunchPreparer: BackendLanguageServerLaunchPreparer? + private let toolLaunchPreparer: ToolLanguageServerLaunchPreparer? private weak var processRegistry: (any LanguageServerProcessRegistry)? private let moduleID: ModuleID @@ -249,22 +283,20 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime runtimeService: any LanguageToolRuntimePort, languageServerCore: any LanguageServerRuntimeCore, languageServerExecutableResolver: ((LanguageProviderDescriptor) -> URL?)? = nil, - hostIntegrationResolver: LanguageServerHostIntegrationResolver? = nil, languageServerLaunchResolver: LanguageServerLaunchResolver? = nil, - languageServerCacheDirectory: URL? = nil, workspaceSessionFactory: WorkspaceLanguageServerSessionFactory? = nil, backendLaunchPreparer: BackendLanguageServerLaunchPreparer? = nil, + toolLaunchPreparer: ToolLanguageServerLaunchPreparer? = nil, processRegistry: (any LanguageServerProcessRegistry)? = nil, moduleID: ModuleID = .languageIntelligence ) { self.runtimeService = runtimeService self.languageServerCore = languageServerCore self.languageServerExecutableResolver = languageServerExecutableResolver - self.hostIntegrationResolver = hostIntegrationResolver self.languageServerLaunchResolver = languageServerLaunchResolver - self.languageServerCacheDirectory = languageServerCacheDirectory self.workspaceSessionFactory = workspaceSessionFactory self.backendLaunchPreparer = backendLaunchPreparer + self.toolLaunchPreparer = toolLaunchPreparer self.processRegistry = processRegistry self.moduleID = moduleID } @@ -282,11 +314,10 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime languageServerLaunch: languageServerLaunch, languageServerCore: languageServerCore, languageServerExecutableResolver: languageServerExecutableResolver, - hostIntegrationResolver: hostIntegrationResolver, languageServerLaunchResolver: languageServerLaunchResolver, - languageServerCacheDirectory: languageServerCacheDirectory, workspaceSessionFactory: workspaceSessionFactory, backendLaunchPreparer: backendLaunchPreparer, + toolLaunchPreparer: toolLaunchPreparer, processRegistry: processRegistry, moduleID: moduleID ) @@ -303,11 +334,10 @@ package final class StdioLanguageProviderRuntimeFactory: LanguageProviderRuntime languageServerLaunch: languageServerLaunch, languageServerCore: languageServerCore, languageServerExecutableResolver: languageServerExecutableResolver, - hostIntegrationResolver: hostIntegrationResolver, languageServerLaunchResolver: languageServerLaunchResolver, - languageServerCacheDirectory: languageServerCacheDirectory, workspaceSessionFactory: workspaceSessionFactory, backendLaunchPreparer: backendLaunchPreparer, + toolLaunchPreparer: toolLaunchPreparer, processRegistry: processRegistry, moduleID: ownerModuleID ) diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift index da03f97076..4a0e17b72f 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift @@ -52,8 +52,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { } private let launchResolver: (@MainActor (URL) throws -> ResolvedLanguageServerLaunch)? - private let hostIntegrationLaunch: LanguageServerHostIntegrationLaunch? - private let cacheDirectoryURL: URL? private let initializeTimeout: TimeInterval private let requestTimeout: TimeInterval private let shutdownTimeout: TimeInterval @@ -131,9 +129,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { package var onCoreLog: ((CoreLogRecord) -> Void)? package var onLog: ((LanguageServerLogLevel, String, String?, String?) -> Void)? package var onLogIssue: ((Bool, String, String, Int?, String?) -> Void)? - package var onProjectPreparation: ((ProjectPreparationSnapshot) -> Void)? - package var onMavenProfileTask: ((String) -> Void)? - package var onMavenProfileProject: ((MavenProfileProjectResult) -> Void)? package var onStateChange: ((LanguageServerSessionState) -> Void)? package private(set) var features: LanguageServerFeatureSet = [] package var onSemanticTokensRefresh: (() -> Void)? @@ -164,9 +159,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { /// Shortcut import providers selected by this backend during initialization. package private(set) var keymapImportProviders: [String] = [] package var onServerInfoChange: ((LanguageServerInfo?) -> Void)? - package var javaTestRunnerURL: URL? { - hostIntegrationLaunch?.coreLaunch?.jdtlsLaunchResources?.javaTestRunnerURL - } package init( providerID: String, @@ -176,8 +168,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { initializationOptions: ToolingJSONValue? = nil, prepareProcess: (@MainActor (URL) async throws -> PreparedLanguageServerProcess)? = nil, launchResolver: (@MainActor (URL) throws -> ResolvedLanguageServerLaunch)? = nil, - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch? = nil, - cacheDirectoryURL: URL? = nil, initializeTimeout: TimeInterval = 30, requestTimeout: TimeInterval = 30, shutdownTimeout: TimeInterval = 2, @@ -198,8 +188,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { self.initializationOptions = initializationOptions self.prepareProcess = prepareProcess self.launchResolver = launchResolver - self.hostIntegrationLaunch = hostIntegrationLaunch - self.cacheDirectoryURL = cacheDirectoryURL self.initializeTimeout = initializeTimeout self.requestTimeout = requestTimeout self.shutdownTimeout = shutdownTimeout @@ -226,24 +214,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { } } - package func start(rootURL: URL, workspaceFingerprint: String?) throws { - try start( - rootURL: rootURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: nil - ) - } - - package func start(rootURL: URL, workspaceFingerprint: String?, mavenContext: MavenLaunchContext?) throws { - try start(rootURL: rootURL, workspaceFingerprint: workspaceFingerprint, mavenContext: mavenContext, javaGradle: nil) - } - - package func start( - rootURL: URL, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration? - ) throws { + package func start(rootURL: URL) throws { guard sessionID == nil, startupGeneration == nil else { return } let normalizedRoot = rootURL.standardizedFileURL transition(to: .startingProcess) @@ -272,8 +243,7 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { self.startingPreparedProcess = true defer { self.startingPreparedProcess = false } do { - try self.start(rootURL: normalizedRoot, workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, javaGradle: javaGradle) + try self.start(rootURL: normalizedRoot) } catch { self.releaseSession() } @@ -339,8 +309,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { let initializeTimeout = initializeTimeout let requestTimeout = requestTimeout let shutdownTimeout = shutdownTimeout - let hostIntegrationLaunch = hostIntegrationLaunch - let cacheDirectoryURL = cacheDirectoryURL let resolvedArguments = arguments let resolvedOptions = initializationOptions let resolvedConfiguration = workspaceConfiguration @@ -369,9 +337,8 @@ 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. + } else if let pluginID, let resolvedPolicy { + // A server with session fields belongs to its plugin. core.startPluginLanguageServer( pluginID: pluginID, providerID: providerID, @@ -383,8 +350,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { workspaceConfiguration: resolvedConfiguration, sessionPolicy: resolvedPolicy, hostServices: hostServices, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -400,11 +365,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { initializationOptions: resolvedOptions, workspaceConfiguration: resolvedConfiguration, hostServices: hostServices, - hostIntegrationLaunch: hostIntegrationLaunch, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, - javaGradle: javaGradle, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -418,12 +378,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { rootURL: normalizedRoot, workingDirectoryURL: normalizedRoot, initializationOptions: resolvedOptions, - runtimeExecutableURL: hostIntegrationLaunch?.runtimeExecutableURL, - jdtlsLaunchResources: hostIntegrationLaunch?.coreLaunch?.jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, - javaGradle: javaGradle, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -640,80 +594,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { core.closeLanguageServerDocument(sessionID: sessionID, fileURL: fileURL.standardizedFileURL) } - package func javaNavigationMarkers( - fileURL: URL, - completion: @escaping (Result<[JavaNavigationMarker], Error>) -> Void - ) throws { - let normalizedURL = fileURL.standardizedFileURL - guard let sessionID, state == .ready else { - throw LanguageServerRuntimeSessionError.notReady - } - guard let documentVersion = documentVersions[normalizedURL] else { - throw LanguageServerRuntimeSessionError.documentNotSynchronized - } - switch core.requestJavaNavigationMarkers( - sessionID: sessionID, - fileURL: normalizedURL, - documentVersion: documentVersion - ) { - case .success(let operation): - registerPendingOperation( - operation, - name: "javaNavigationMarkers" - ) { [weak self] result in - guard let self else { return } - completion(result.flatMap { - Self.decodeEventResult($0, as: JavaNavigationMarkersPayload.self) - }.flatMap { payload in - guard self.documentVersions[normalizedURL] == payload.documentVersion else { - return .failure(LanguageServerRuntimeSessionError.staleDocument) - } - return .success(payload.makeModels()) - }) - } - case .failure(let error): - throw LanguageServerRuntimeSessionError.requestRejected(error.userMessage) - } - } - - package func resolveJavaNavigation( - fileURL: URL, - marker: JavaNavigationMarker, - completion: @escaping (Result<[LanguageServerLocation], Error>) -> Void - ) throws { - let normalizedURL = fileURL.standardizedFileURL - guard let sessionID, state == .ready else { - throw LanguageServerRuntimeSessionError.notReady - } - guard let documentVersion = documentVersions[normalizedURL] else { - throw LanguageServerRuntimeSessionError.documentNotSynchronized - } - switch core.resolveJavaNavigation( - sessionID: sessionID, - fileURL: normalizedURL, - marker: marker, - documentVersion: documentVersion - ) { - case .success(let operation): - registerPendingOperation( - operation, - name: "javaResolveNavigation" - ) { [weak self] result in - guard let self else { return } - completion(result.flatMap { - Self.decodeEventResult($0, as: JavaNavigationLocationsPayload.self) - }.flatMap { payload in - guard self.documentVersions[normalizedURL] == payload.documentVersion else { - return .failure(LanguageServerRuntimeSessionError.staleDocument) - } - return .success(payload.makeModels()) - }) - } - case .failure(let error): - throw LanguageServerRuntimeSessionError.requestRejected(error.userMessage) - } - } - package func completions( fileURL: URL, position: LanguageServerPosition, @@ -1302,120 +1182,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { ) } - /// Waits for Core's composed preparation; cancellation addresses the same - /// operation throughout entry discovery, build and classpath resolution. - package func prepareJavaLaunch(fileURL: URL, mainClass: String?) async throws -> JavaLaunchPreparation { - try Task.checkCancellation() - guard let sessionID, state == .ready else { - throw LanguageServerRuntimeSessionError.notReady - } - let operation: LanguageServerRuntimeOperation - switch await send(timeout: requestTimeout, { core in - core.prepareJavaLaunch(sessionID: sessionID, fileURL: fileURL, mainClass: mainClass) - }) { - case .success(let started): operation = started - case .failure(let error): - sendsInFlight -= 1 - try Task.checkCancellation() - throw LanguageServerRuntimeSessionError.requestRejected(error.userMessage) - } - let preparation: JavaLaunchPreparation = try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - registerPendingOperation(operation, name: "java.prepareLaunch") { result in - continuation.resume(with: result.flatMap { - Self.decodeEventResult($0, as: JavaLaunchPayload.self) - }.flatMap { payload in - switch payload.kind { - case .ready: return .success(.ready(payload.target)) - case .buildFailed: - guard let failure = payload.failure else { - return .failure(LanguageServerRuntimeSessionError.missingResult) - } - return .success(.buildFailed(target: payload.target, failure: JavaLaunchBuildFailure( - code: failure.code, message: L10n.string(key: failure.message), report: failure.report))) - } - }) - } - sendsInFlight -= 1 - } - } onCancel: { - Task { @MainActor [weak self] in self?.cancelOffMain(operation.operationID) } - } - try Task.checkCancellation() - return preparation - } - - private struct JavaLaunchPayload: Decodable { - enum Kind: String, Decodable { case ready, buildFailed } - let kind: Kind - let target: JavaDebugLaunchTarget - let failure: JavaLaunchBuildFailure? - } - - /// Asks JDT, through Core, which classes in the workspace can be launched. - package func javaEntrypoints() async throws -> JavaEntrypoints { - try Task.checkCancellation() - guard let sessionID, state == .ready else { throw LanguageServerRuntimeSessionError.notReady } - let operation: LanguageServerRuntimeOperation - switch await send(timeout: requestTimeout, { core in - core.requestLanguageServerOperation(sessionID: sessionID, operation: .javaEntrypoints, fileURL: nil, - virtualURI: nil, position: nil, newName: nil, range: nil, diagnostics: [], - completionContext: nil, completionItem: nil, codeAction: nil, command: nil) - }) { - case .success(let started): operation = started - case .failure(let error): - sendsInFlight -= 1 - try Task.checkCancellation() - throw LanguageServerRuntimeSessionError.requestRejected(error.userMessage) - } - let value: JavaEntrypoints = try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - registerPendingOperation(operation, name: LanguageServerOperation.javaEntrypoints.rawValue) { result in - continuation.resume(with: result.flatMap { Self.decodeEventResult($0, as: JavaEntrypoints.self) }) - } - sendsInFlight -= 1 - } - } onCancel: { - Task { @MainActor [weak self] in self?.cancelOffMain(operation.operationID) } - } - try Task.checkCancellation() - return value - } - - /// Callback discovery is retained for presentation clients. - package func javaEntrypoints( - completion: @escaping (Result) -> Void - ) throws { - try request(.javaEntrypoints, fileURL: nil) { result in - completion(result.flatMap { - Self.decodeEventResult($0, as: JavaEntrypoints.self) - }) - } - } - - package func javaTestItems( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws { - try request(.javaTestItems, fileURL: fileURL) { result in - completion(result.flatMap { - Self.decodeEventResult($0, as: JavaTestItems.self) - }) - } - } - - /// Asks JDT, through Core, which `main` methods in one file can be launched. - package func javaMainMethods( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws { - try request(.javaMainMethods, fileURL: fileURL) { result in - completion(result.flatMap { - Self.decodeEventResult($0, as: JavaMainMethods.self) - }) - } - } - package func resolveVirtualDocument( uri: String, completion: @escaping (Result) -> Void @@ -1534,38 +1300,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { return true } - package func retryMavenProfiles() { - guard let sessionID, isRunning else { return } - if case .failure(let failure) = core.retryMavenProfiles(sessionID: sessionID) { - onLogIssue?(false, "mavenProfileRetry", failure.code, nil, nil) - onLog?(.error, "Maven profile retry failed", failure.message, nil) - } - } - - /// Hands a changed Maven context to the running server. A failure means the - /// session cannot take it and the caller should restart the session. - package func updateMavenConfiguration( - _ context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result { - guard let sessionID, isRunning else { - return .failure(LanguageServerRuntimeFailure( - code: "sessionStopped", - message: "The Java language session is no longer running." - )) - } - let result = core.updateMavenConfiguration( - sessionID: sessionID, - context: context, - reloadProjects: reloadProjects - ) - if case .failure(let failure) = result { - onLogIssue?(true, "mavenConfigurationUpdate", failure.code, nil, nil) - onLog?(.warning, "Maven configuration update failed", failure.userMessage, nil) - } - return result - } - // MARK: - Requests private func request( @@ -1664,14 +1398,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { if let onCoreLog { onCoreLog(record) } else { core.emitCoreLog(record) } } switch event.type { - case "projectPreparation": - switch Self.decodeEventResult(event, as: ProjectPreparationSnapshot.self) { - case .success(let snapshot): onProjectPreparation?(snapshot) - case .failure(let error): onLogIssue?(false, "projectPreparation", "invalidProjectPreparationEvent", nil, nil) - onLog?(.error, "Invalid project preparation event", error.localizedDescription, nil) - } - return false - case "stateChanged": return handleStateChange(event) case "requestCompleted": @@ -1806,8 +1532,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { onServerInfoChange?(updated) return false case "log": - if let status = event.mavenProfileTask { onMavenProfileTask?(status) } - if let result = event.mavenProfileProject { onMavenProfileProject?(result) } let level = event.level == "warn" ? .warning : event.level.flatMap(LanguageServerLogLevel.init(rawValue:)) ?? .info if event.coreLog == nil && (level == .warning || level == .error) { onLogIssue?(level == .warning, event.error?.stage ?? "runtime", @@ -2068,7 +1792,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { case unsupportedNavigation(String) case missingResult case sessionStopped - case staleDocument var errorDescription: String? { switch self { @@ -2088,8 +1811,6 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { L10n.string("Language server response did not include a result.") case .sessionStopped: L10n.string("Language server session stopped before the request completed.") - case .staleDocument: - L10n.string("The document changed before Java navigation completed.") } } } @@ -2213,63 +1934,6 @@ private struct NavigationPayload: Decodable { func makeModels() -> [LanguageServerLocation] { locations.compactMap { $0.makeModel() } } } -private struct JavaNavigationMarkersPayload: Decodable { - struct Marker: Decodable { - let line: Int - let utf16Column: Int - let implementationCount: Int - let direction: JavaNavigationDirection - let relation: JavaNavigationRelation - - func makeModel() -> JavaNavigationMarker { - JavaNavigationMarker( - line: line, - utf16Column: utf16Column, - implementationCount: implementationCount, - direction: direction, - relation: relation - ) - } - } - - let documentVersion: Int - let markers: [Marker] - - func makeModels() -> [JavaNavigationMarker] { markers.map { $0.makeModel() } } -} - -private struct JavaNavigationLocationsPayload: Decodable { - struct Location: Decodable { - let uri: String? - let filePath: String? - let range: RangePayload - let isReadOnly: Bool - let displayPath: String? - - func makeModel() -> LanguageServerLocation? { - let url: URL - if let filePath { - url = URL(fileURLWithPath: filePath) - } else if let uri, let virtualURL = URL(string: uri) { - url = virtualURL - } else { - return nil - } - return LanguageServerLocation( - url: url, - range: range.makeModel(), - isReadOnly: isReadOnly, - displayPath: displayPath - ) - } - } - - let documentVersion: Int - let locations: [Location] - - func makeModels() -> [LanguageServerLocation] { locations.compactMap { $0.makeModel() } } -} - private struct VirtualDocumentPayload: Decodable { let text: String } diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift b/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift index 906635e923..c7e208807b 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Services/LanguageToolingSessionManager.swift @@ -9,7 +9,6 @@ package enum LanguageToolingSessionError: LocalizedError, Equatable, Sendable { case providerDisabled(String) case toolingUnavailable(String) case capabilityUnavailable(provider: String, capability: String) - case invalidJavaDebugServerPort case invalidDebugAdapterPort(provider: String) case languageServerNotOwnedByPlugin(languageID: String) @@ -25,8 +24,6 @@ package enum LanguageToolingSessionError: LocalizedError, Equatable, Sendable { return message case .capabilityUnavailable(let provider, let capability): return L10n.string("The \(provider) provider does not support \(capability).") - case .invalidJavaDebugServerPort: - return L10n.string("The Java Debug Server returned an invalid TCP port.") case .invalidDebugAdapterPort(let provider): return L10n.string("The \(provider) language server returned an invalid TCP port for its debug adapter.") case .languageServerNotOwnedByPlugin(let languageID): @@ -38,22 +35,13 @@ package enum LanguageToolingSessionError: LocalizedError, Equatable, Sendable { /// UI-facing façade that routes language features across active LSP sessions /// and lightweight local providers without exposing either implementation. @MainActor -package final class LanguageToolingSessionManager: ObservableObject, - JavaTestDebugLaunchTargetResolving -{ +package final class LanguageToolingSessionManager: ObservableObject { @Published package private(set) var diagnostics: [URL: [LanguageServerDiagnostic]] = [:] @Published package private(set) var semanticTokensGeneration: UInt64 = 0 @Published package private(set) var languageServerFeatures: [String: LanguageServerFeatureSet] = [:] /// Application composition persists lifecycle facts without raw protocol payloads. package var onLogEvent: ((CoreLogRecord) -> Void)? package var onLogIssue: ((String, String?, Bool, String, String, Int?) -> Void)? - @Published package private(set) var projectPreparation: ProjectPreparationSnapshot? - package var onJavaDependencySnapshotChange: (@MainActor () -> Void)? - private var javaDependencyWorkspaceURL: URL? - private var javaDependencySnapshot: LanguageDependencySnapshot? - private var javaDependencyRefreshTask: Task? - private var javaDependencyChangeTask: Task? - @Published package private(set) var mavenProfileProjectResults: [URL: MavenProfileProjectResult] = [:] @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. @@ -93,24 +81,12 @@ package final class LanguageToolingSessionManager: ObservableObject, private let policyCore: (any LanguageToolingPolicyCore)? /// Monotonic milliseconds for the activation policy; tests inject a clock. package var monotonicNowMs: () -> UInt64 = { DispatchTime.now().uptimeNanoseconds / 1_000_000 } - /// Core can clear Maven settings only for a session launched with Maven - /// inputs. Keep this with the session so a pure Gradle start stays nil. - private var languageServerMavenContexts: [String: MavenLaunchContext] = [:] - /// Ephemeral import changes also revoke in-flight launch metadata (including ABA). - private var javaPreparationCancellations: [UUID: @MainActor () -> Void] = [:] - package private(set) var javaImportRevision: UInt64 = 0 { - didSet { for cancel in javaPreparationCancellations.values { cancel() } } - } - private var languageServerWorkspaceFingerprints: [String: String] = [:] private var languageServerSessionIdentities: [String: ObjectIdentifier] = [:] private var diagnosticsByProviderID: [String: [URL: [LanguageServerDiagnostic]]] = [:] private var languageFeatureProviders: [any LanguageFeatureProvider] private var languageServerFeatureProviders: [String: LanguageServerFeatureProvider] = [:] private var languageServerReadyWaiters: [UUID: LanguageServerReadyWaiter] = [:] - private let workspaceFingerprintProvider: (LanguageProviderDescriptor, URL) throws -> String? - private let workspaceStateResetter: ((LanguageProviderDescriptor, URL, String?) throws -> Void)? - private let workspaceStateCleaner: ((LanguageProviderDescriptor, URL, String?) throws -> Int)? - private var javaLanguageImportProvider: ((LanguageProviderDescriptor, URL) throws -> JavaLanguageImportConfiguration)? + private let workspaceStateResetter: ((LanguageProviderDescriptor, URL) throws -> Void)? private let pluginOperations: PluginOperationReporter @@ -126,9 +102,7 @@ package final class LanguageToolingSessionManager: ObservableObject, languageFeatureProviders: [any LanguageFeatureProvider] = [], extensionRequiredProviderIDs: Set = [], isLanguageServerEnabled: @escaping (String, URL) -> Bool = { _, _ in true }, - workspaceFingerprintProvider: @escaping (LanguageProviderDescriptor, URL) throws -> String? = { _, _ in nil }, - workspaceStateResetter: ((LanguageProviderDescriptor, URL, String?) throws -> Void)? = nil, - workspaceStateCleaner: ((LanguageProviderDescriptor, URL, String?) throws -> Int)? = nil + workspaceStateResetter: ((LanguageProviderDescriptor, URL) throws -> Void)? = nil ) { self.pluginOperations = pluginOperations self.policyCore = policyCore @@ -138,9 +112,7 @@ package final class LanguageToolingSessionManager: ObservableObject, self.runtimeFactory = runtimeFactory self.extensionRequiredProviderIDs = extensionRequiredProviderIDs self.isLanguageServerEnabled = isLanguageServerEnabled - self.workspaceFingerprintProvider = workspaceFingerprintProvider self.workspaceStateResetter = workspaceStateResetter - self.workspaceStateCleaner = workspaceStateCleaner self.languageFeatureProviders = languageFeatureProviders + [ BuiltinLanguageFeatureProvider(core: builtinCore ?? UnavailableBuiltinLanguageFeatureCore()) ] @@ -156,118 +128,6 @@ package final class LanguageToolingSessionManager: ObservableObject, }) } - package func dependencySnapshot(workspaceURL: URL) -> LanguageDependencySnapshot? { - guard javaDependencyWorkspaceURL == workspaceURL.standardizedFileURL else { return nil } - return javaDependencySnapshot - } - - private func refreshJavaDependenciesWhenReady() { - guard projectPreparation?.status == "ready", - languageServerStates["java"] == .ready, - let workspace = languageServerRoots["java"], - let session = languageServers["java"], session.isRunning, - let identity = languageServerSessionIdentities["java"] else { return } - javaDependencyRefreshTask?.cancel() - javaDependencyRefreshTask = Task { [weak self] in - guard let self else { return } - do { - let snapshot = try await self.resolvedJavaDependencies(workspace: workspace) - guard !Task.isCancelled, - self.languageServerSessionIdentities["java"] == identity, - self.languageServerRoots["java"] == workspace else { return } - guard self.javaDependencyWorkspaceURL != workspace - || self.javaDependencySnapshot != snapshot else { return } - self.javaDependencyWorkspaceURL = workspace - self.javaDependencySnapshot = snapshot - self.onJavaDependencySnapshotChange?() - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - } catch is CancellationError { - return - } catch { - self.recordLogIssue("java", nil, true, "dependencies", "dependencyProjectionUnavailable", nil) - } - } - } - - private func scheduleJavaDependencyRefresh(after changes: [LanguageServerWorkspaceFileChange]) { - let managementFiles: Set = [ - "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", - "settings.gradle.kts", "gradle.properties", "libs.versions.toml", "extensions.xml" - ] - guard changes.contains(where: { managementFiles.contains($0.fileURL.lastPathComponent.lowercased()) }) else { - return - } - javaDependencyChangeTask?.cancel() - javaDependencyChangeTask = Task { [weak self] in - // Watched-file notifications have no acknowledgement. Give JDT LS time to - // start a configuration job; its ready transition takes precedence. - // log-exempt: 用户取消:调用方取消等待或替换旧任务时结束延迟,不代表操作失败 - try? await Task.sleep(for: .milliseconds(750)) - guard !Task.isCancelled, let self else { return } - self.refreshJavaDependenciesWhenReady() - } - } - - /// `java.project.getClasspaths` options selecting the runtime classpath. - /// - /// JDT LS deserializes this argument only from JSON text, as its own - /// VS Code client sends it; a JSON object leaves the options null and the - /// command fails inside the server. - private static let javaRuntimeClasspathOptions = #"{"scope":"runtime"}"# - - private func resolvedJavaDependencies(workspace: URL) async throws -> LanguageDependencySnapshot { - let projects = try await executeJavaCommand("java.project.getAll", arguments: [], rootURL: workspace) - guard case .array(let values) = projects else { - throw LanguageToolingSessionError.toolingUnavailable("The Java service returned an invalid project list.") - } - var dependencyPaths: Set = [] - for case .string(let projectURI) in values { - try Task.checkCancellation() - guard let projectURL = URL(string: projectURI), projectURL.isFileURL, - Self.isLocated(projectURL, within: workspace) else { continue } - let response = try await executeJavaCommand( - "java.project.getClasspaths", - arguments: [.string(projectURI), .string(Self.javaRuntimeClasspathOptions)], - rootURL: workspace - ) - guard case .object(let paths) = response else { - throw LanguageToolingSessionError.toolingUnavailable("The Java service returned an invalid classpath.") - } - for path in Self.stringValues(paths["classpaths"] ?? .array([])) - + Self.stringValues(paths["modulepaths"] ?? .array([])) { - guard (path as NSString).isAbsolutePath else { continue } - let url = URL(fileURLWithPath: path).standardizedFileURL - guard !Self.isLocated(url, within: workspace) else { continue } - dependencyPaths.insert(url.path) - } - } - return LanguageDependencySnapshot(dependencyRoots: dependencyPaths.sorted().map { - URL(fileURLWithPath: $0) - }) - } - - /// The host must prepare plugin imports before any entry point can start - /// Java. Throwing here prevents a synchronous document/run path from using - /// a previous workspace's context while that preparation is pending. - package func configureJavaLanguageImportProvider( - _ provider: @escaping (LanguageProviderDescriptor, URL) throws -> JavaLanguageImportConfiguration - ) { - javaLanguageImportProvider = provider - } - - private func javaLanguageImport( - _ descriptor: LanguageProviderDescriptor, rootURL: URL - ) throws -> JavaLanguageImportConfiguration { - guard descriptor.id == "java" else { return JavaLanguageImportConfiguration() } - if let javaLanguageImportProvider { return try javaLanguageImportProvider(descriptor, rootURL) } - return JavaLanguageImportConfiguration() - } - - package func retryMavenProfiles(providerID: String) { - guard let session = languageServers[providerID] else { return } - session.retryMavenProfiles() - } - package func updateCatalog(_ catalog: LanguageProviderCatalog) { let previousDescriptors = Dictionary( uniqueKeysWithValues: self.catalog.descriptors.map { ($0.id, $0) } @@ -315,7 +175,8 @@ package final class LanguageToolingSessionManager: ObservableObject, // A server its plugin backend launches names no executable // until it starts. !configuration.executableNames.isEmpty - || configuration.launchSource?.resolvesLaunchWithBackend == true, + || configuration.launchSource?.resolvesLaunchWithBackend == true + || configuration.launchSource?.launchesThroughTool == true, // The module that owns this provider already stopped it. !provider.lifecycle.isRetired, let runtimeFactory else { return false } @@ -336,7 +197,6 @@ package final class LanguageToolingSessionManager: ObservableObject, launchSource: configuration.launchSource, pluginID: configuration.pluginID, executableVersionRequirement: configuration.executableVersionRequirement, - hostIntegrationID: configuration.hostIntegrationID, launchRuntimeTool: configuration.launchRuntimeTool ) let descriptor = LanguageProviderDescriptor( @@ -479,104 +339,6 @@ package final class LanguageToolingSessionManager: ObservableObject, return languageServerOperationIDs[providerID] ?? operationID } - /// Outcome of handing the workspace's Maven context to its Java session. - package enum JavaMavenConfigurationOutcome: Equatable { - /// The running session took the change and re-resolves in place. - case updated(LanguageServerMavenConfigurationUpdate) - /// No Java session runs for this root; the next start reads the context. - case noSession - /// A session runs but could not take the change and needs a restart. - case failed(LanguageServerRuntimeFailure) - } - - /// Sends the workspace's current Maven context to the running Java session. - /// - /// JDT LS re-resolves on its own: changed settings make it force-update every - /// Maven project, and `reloadProjects` re-resolves even when nothing changed. - /// A restart would reuse the workspace state and skip every project whose - /// `pom.xml` did not change, keeping unresolved artifacts missing (#970). - @discardableResult - package func updateJavaMavenConfiguration( - rootURL: URL, - reloadProjects: Bool - ) -> JavaMavenConfigurationOutcome { - let root = rootURL.standardizedFileURL - // The workspace preference is rechecked like every other entry point; - // a disabled provider reports no session, so a reload fails where a - // start would. - guard isLanguageServerEnabled("java", root), - let session = languageServers["java"], - session.isRunning, - languageServerRoots["java"] == root, - let descriptor = catalog.descriptors.first(where: { $0.id == "java" }) else { - return .noSession - } - let context: MavenLaunchContext - do { - if let configured = try javaLanguageImport(descriptor, rootURL: root).mavenContext { - context = configured - } else if let previous = languageServerMavenContexts["java"] { - // Removing the build plugin must clear its old Profiles, - // settings and repository instead of leaving them in JDT LS. - context = MavenLaunchContext( - reactorPath: previous.reactorPath, profiles: [], settingsPath: nil, - localRepositoryPath: nil, skipTests: false, mavenExecutablePath: nil, javaHomePath: nil - ) - } else { - return .noSession - } - } catch { - recordHostFailure(providerID: "java", stage: "language-import", error: error) - return .failed(LanguageServerRuntimeFailure(code: "languageImportUnavailable", message: error.localizedDescription)) - } - switch session.updateMavenConfiguration(context, reloadProjects: reloadProjects) { - case .success(let update): - if languageServerMavenContexts["java"] != context || reloadProjects { javaImportRevision &+= 1 } - languageServerMavenContexts["java"] = context - return .updated(update) - case .failure(let failure): return .failed(failure) - } - } - - /// Reloads Java Maven projects and waits for readiness, preserving other - /// providers. A running session re-resolves in place; a restart is only the - /// recovery for a session that cannot take the update, or the way to start - /// one. Cancellation terminates only a session created by this reload. - package func reloadJavaWorkspace(rootURL: URL) async throws { - if case .updated = updateJavaMavenConfiguration(rootURL: rootURL, reloadProjects: true) { - try await waitUntilLanguageServerReady(providerID: "java", rootURL: rootURL) - return - } - stopLanguageServer(providerID: "java") - let operationID = try startLanguageServer(providerID: "java", rootURL: rootURL) - do { - try await waitUntilLanguageServerReady(providerID: "java", rootURL: rootURL) - try Task.checkCancellation() - } catch { - if languageServerOperationIDs["java"] == operationID { - stopLanguageServer(providerID: "java") - } - throw error - } - } - - /// Starts or reuses JDT LS, then asks its bundled Java Debug extension for - /// the loopback DAP port. The caller remains responsible for the socket. - package func startJavaDebugServer(rootURL: URL) async throws -> UInt16 { - let normalizedRoot = rootURL.standardizedFileURL - _ = try startLanguageServer(providerID: "java", rootURL: normalizedRoot) - try await waitUntilLanguageServerReady(providerID: "java", rootURL: normalizedRoot) - let value = try await executeJavaCommand( - "vscode.java.startDebugSession", - arguments: [], - rootURL: normalizedRoot - ) - guard let port = Self.debugAdapterPort(from: value) else { - throw LanguageToolingSessionError.invalidJavaDebugServerPort - } - return port - } - /// The loopback port a language server answers a debug-start command /// with: an integer or a numeric string, 1...65535. package static func debugAdapterPort(from value: ToolingJSONValue) -> UInt16? { @@ -631,500 +393,6 @@ package final class LanguageToolingSessionManager: ObservableObject, return port } - /// Resolves the current Java source through JDT LS project metadata instead - /// of deriving package or module names from its filesystem path. - package func resolveJavaDebugLaunchTarget( - fileURL: URL, - rootURL: URL - ) async throws -> JavaDebugLaunchTarget { - switch try await prepareJavaLaunchTarget(fileURL: fileURL, rootURL: rootURL) { - case .ready(let target): - return target - case .buildFailed(_, let failure): - throw LanguageToolingSessionError.toolingUnavailable(failure.message) - } - } - - /// Builds the owning Java project and resolves the exact runtime paths used - /// by both Run and Debug. Java Debug Server owns these project-model rules. - package func prepareJavaRunLaunchTarget( - fileURL: URL, - rootURL: URL, - mainClass: String? = nil - ) async throws -> JavaLaunchPreparation { - try await prepareJavaLaunchTarget(fileURL: fileURL, rootURL: rootURL, mainClass: mainClass) - } - - /// The exact options of the successful build preparation, without saving - /// a project override or reconstructing a second Maven configuration. - package func prepareJavaRunLaunchTarget(fileURL: URL, rootURL: URL, - languageImport: JavaLanguageImportConfiguration, mainClass: String? = nil) async throws -> JavaLaunchPreparation { - try await prepareJavaLaunchTarget(fileURL: fileURL, rootURL: rootURL, mainClass: mainClass, languageImport: languageImport) - } - - /// Rebuilds the original running target without allowing a failed build to proceed. - package func buildJavaServiceUpdate( - target: JavaDebugLaunchTarget, fileURL: URL, rootURL: URL - ) async throws { - // Match launch preparation: JDT owns test-root and dependency selection. - let paths = try await executeJavaCommand( - "vscode.java.resolveClasspath", - arguments: [.string(target.mainClass), .string(target.projectName ?? "")], - rootURL: rootURL - ) - guard case .array(let groups) = paths, groups.count == 2, - Self.stringValues(groups[0]) == target.modulePaths, - Self.stringValues(groups[1]) == target.classPaths else { - throw LanguageToolingSessionError.toolingUnavailable( - "Runtime paths changed. Restart the service to use the new dependencies." - ) - } - let payload = JavaWorkspaceBuildRequest( - mainClass: target.mainClass, projectName: target.projectName, - filePath: fileURL.path, isFullBuild: false - ) - let json = String(decoding: try JSONEncoder().encode(payload), as: UTF8.self) - let result = try await executeJavaCommand( - "vscode.java.buildWorkspace", arguments: [.string(json)], rootURL: rootURL - ) - guard result == .integer(1) || result == .string("1") else { - throw LanguageToolingSessionError.toolingUnavailable("Java compilation did not complete successfully.") - } - } - - /// JDT's launchable classes for the workspace, starting the Java service - /// when needed. Lithe never derives entry points from source text. - /// - /// Note: 入口点归属见 .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md - package func javaEntrypoints(rootURL: URL) async throws -> JavaEntrypoints { - try prepareJavaImportSession(rootURL: rootURL.standardizedFileURL) - let revision = javaImportRevision - let value = try await javaEntrypoints(in: rootURL.standardizedFileURL) - guard javaImportRevision == revision else { throw CancellationError() } - return value - } - - /// Reuse the current session when Core can update it in place. A session - /// originally started without Maven inputs must restart with those inputs. - private func prepareJavaImportSession(rootURL: URL, override: JavaLanguageImportConfiguration? = nil) throws { - guard let descriptor = catalog.descriptors.first(where: { $0.id == "java" }) else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - let configuration = try override ?? javaLanguageImport(descriptor, rootURL: rootURL) - let session = try ensureLanguageServerSession(descriptor: descriptor, rootURL: rootURL, - operationID: nil, javaImportOverride: configuration) - if let context = configuration.mavenContext, languageServerMavenContexts["java"] != context { - switch session.updateMavenConfiguration(context, reloadProjects: false) { - case .success: - javaImportRevision &+= 1 - languageServerMavenContexts["java"] = context - case .failure: - stopLanguageServer(providerID: "java") - _ = try ensureLanguageServerSession(descriptor: descriptor, rootURL: rootURL, - operationID: nil, javaImportOverride: configuration) - } - } else if configuration.mavenContext == nil, languageServerMavenContexts["java"] != nil { - if case .failed(let failure) = updateJavaMavenConfiguration(rootURL: rootURL, reloadProjects: false) { - throw LanguageToolingSessionError.toolingUnavailable(failure.userMessage) - } - } - } - - private func javaEntrypoints(in normalizedRoot: URL) async throws -> JavaEntrypoints { - _ = try startLanguageServer(providerID: "java", rootURL: normalizedRoot) - try await waitUntilLanguageServerReady(providerID: "java", rootURL: normalizedRoot) - guard let session = languageServers["java"], session.isRunning else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - return try await session.javaEntrypoints() - } - - /// `file` relative to `root` with `/` separators, comparing the paths - /// with symbolic links resolved so `/var` and `/private/var` agree. - private static func workspaceRelativePath(of file: URL, in root: URL) -> String? { - let rootPath = root.resolvingSymlinksInPath().standardizedFileURL.path - let filePath = file.resolvingSymlinksInPath().standardizedFileURL.path - let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/" - guard filePath.hasPrefix(prefix) else { return nil } - return String(filePath.dropFirst(prefix.count)) - } - - /// Whether `url` is `root` or lies below it, with symbolic links resolved. - /// JDT reports canonical locations, such as `/private/var`, for a - /// workspace that was opened through a link, such as `/var`. - private static func isLocated(_ url: URL, within root: URL) -> Bool { - url.resolvingSymlinksInPath().standardizedFileURL.path - == root.resolvingSymlinksInPath().standardizedFileURL.path - || workspaceRelativePath(of: url, in: root) != nil - } - - private func prepareJavaLaunchTarget( - fileURL: URL, rootURL: URL, mainClass: String? = nil, - languageImport: JavaLanguageImportConfiguration? = nil - ) async throws -> JavaLaunchPreparation { - let normalizedRoot = rootURL.standardizedFileURL - let resolvedFile = fileURL.standardizedFileURL.resolvingSymlinksInPath() - try prepareJavaImportSession(rootURL: normalizedRoot, override: languageImport) - let revision = javaImportRevision, sessionIdentity = languageServerSessionIdentities["java"] - func checkInputs() throws { - try Task.checkCancellation() - guard javaImportRevision == revision, languageServerRoots["java"] == normalizedRoot, - languageServerSessionIdentities["java"] == sessionIdentity else { throw CancellationError() } - } - try await waitUntilLanguageServerReady(providerID: "java", rootURL: normalizedRoot) - try checkInputs() - guard let session = languageServers["java"], session.isRunning else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - let preparation = try await awaitJavaPreparation { - try await session.prepareJavaLaunch(fileURL: resolvedFile, mainClass: mainClass) - } - try checkInputs() - return preparation - } - - /// Framework goals build with Maven; only synchronize the same import and - /// await Core's configuration barrier, without a second JDT build or launch. - package func applyJavaRunImport(rootURL: URL, languageImport: JavaLanguageImportConfiguration) async throws { - let root = rootURL.standardizedFileURL - try prepareJavaImportSession(rootURL: root, override: languageImport) - let revision = javaImportRevision, identity = languageServerSessionIdentities["java"] - try await waitUntilLanguageServerReady(providerID: "java", rootURL: root) - guard javaImportRevision == revision, languageServerRoots["java"] == root, - languageServerSessionIdentities["java"] == identity, - let session = languageServers["java"], session.isRunning else { throw CancellationError() } - _ = try await awaitJavaPreparation { try await session.javaEntrypoints() } - try Task.checkCancellation() - guard javaImportRevision == revision, languageServerRoots["java"] == root, - languageServerSessionIdentities["java"] == identity else { throw CancellationError() } - } - - private func awaitJavaPreparation(_ operation: @escaping @MainActor () async throws -> T) async throws -> T { - let id = UUID(), task = Task { try await operation() } - javaPreparationCancellations[id] = { task.cancel() } - defer { javaPreparationCancellations[id] = nil; task.cancel() } - return try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel() } - } - - /// Resolves one Java source file or discovered test item through the Java - /// Test extension and returns the metadata required by shared Debug Core. - package func resolveJavaTestDebugLaunchTarget( - fileURL: URL, - testIdentifier: String? = nil, - rootURL: URL - ) async throws -> JavaTestDebugLaunchTarget { - let normalizedFile = fileURL.standardizedFileURL - let normalizedRoot = rootURL.standardizedFileURL - let discovered = try await resolvedJavaTestItems( - fileURL: normalizedFile, - rootURL: normalizedRoot - ) - let selected: [JavaTestItem] - if let testIdentifier, !testIdentifier.isEmpty { - selected = Self.flattenJavaTestItems(discovered).filter { - $0.matches(identifier: testIdentifier) - } - } else { - selected = discovered.filter { $0.level == 5 } - } - guard !selected.isEmpty else { - let target = testIdentifier ?? normalizedFile.lastPathComponent - throw LanguageToolingSessionError.toolingUnavailable( - "No Java test was found for \(target)." - ) - } - guard Set(selected.map(\.projectName)).count == 1, - Set(selected.map(\.kind)).count == 1, - Set(selected.map(\.level)).count == 1, - let projectName = selected.first?.projectName, - let kind = selected.first?.kind, - let level = selected.first?.level else { - throw LanguageToolingSessionError.toolingUnavailable( - "Debug one Java test framework and project at a time." - ) - } - let framework: JavaTestDebugFramework - switch kind { - case 0, 1: framework = .junit - case 2: framework = .testng - default: - throw LanguageToolingSessionError.toolingUnavailable( - "The selected Java test framework is not supported." - ) - } - let launchTestNames: [String] - if framework == .junit, level == 6 { - launchTestNames = selected.compactMap(\.jdtHandler) - } else { - launchTestNames = selected.map(\.fullName) - } - guard launchTestNames.count == selected.count else { - throw LanguageToolingSessionError.toolingUnavailable( - "The Java language service returned incomplete test identifiers." - ) - } - let launchRequest = ToolingJSONValue.object([ - "projectName": .string(projectName), - "testLevel": .integer(level), - "testKind": .integer(kind), - "testNames": .array(launchTestNames.map(ToolingJSONValue.string)), - ]) - let requestData = try JSONSerialization.data( - withJSONObject: launchRequest.foundationObject, - options: [.sortedKeys] - ) - guard let requestJSON = String(data: requestData, encoding: .utf8) else { - throw LanguageToolingSessionError.toolingUnavailable( - "Could not encode the Java test launch request." - ) - } - let launchValue = try await executeJavaTestCommand( - "vscode.java.test.junit.argument", - arguments: [.string(requestJSON)], - rootURL: normalizedRoot - ) - let launch = try Self.javaTestLaunchArguments(launchValue) - let testNGTestNames = framework == .testng - ? selected.flatMap(Self.javaTestNGMethodNames) - : [] - let testNGRunnerPath: String? - let mainClass: String - if framework == .testng { - guard let runnerURL = languageServers["java"]?.javaTestRunnerURL else { - throw LanguageToolingSessionError.toolingUnavailable( - "The packaged Java TestNG runner is unavailable. Reinstall Lithe." - ) - } - guard !testNGTestNames.isEmpty else { - throw LanguageToolingSessionError.toolingUnavailable( - "No TestNG test method was found in \(normalizedFile.lastPathComponent)." - ) - } - testNGRunnerPath = runnerURL.standardizedFileURL.path - mainClass = "com.microsoft.java.test.runner.Launcher" - } else { - guard let resolvedMainClass = launch.mainClass else { - throw LanguageToolingSessionError.toolingUnavailable( - "The Java language service returned no JUnit runner main class." - ) - } - testNGRunnerPath = nil - mainClass = resolvedMainClass - } - return JavaTestDebugLaunchTarget( - fileURL: normalizedFile, - name: selected.count == 1 ? selected[0].label : normalizedFile.lastPathComponent, - framework: framework, - workingDirectory: launch.workingDirectory, - mainClass: mainClass, - projectName: launch.projectName, - classPaths: launch.classPaths, - modulePaths: launch.modulePaths, - vmArguments: launch.vmArguments, - programArguments: launch.programArguments, - testNGRunnerPath: testNGRunnerPath, - testNGTestNames: testNGTestNames - ) - } - - /// Discovers the Java test classes and methods in one source file for the - /// native Tests tree. This reuses the same identifiers accepted by Debug. - /// JDT owns semantic identities and file membership. Build providers consume - /// these public fullName values unchanged; the host never derives a selector - /// from a filename, package declaration or method spelling. - package func javaBuildTestSelectors(fileURL: URL, identifier: String?, rootURL: URL) async throws -> [String] { - let items = try await resolvedJavaTestItems(fileURL: fileURL.standardizedFileURL, rootURL: rootURL.standardizedFileURL) - let selected: [JavaTestItem] - if let identifier { - selected = Self.flattenJavaTestItems(items).filter { $0.matches(identifier: identifier) } - } else { - selected = items - } - let values = Array(Set(selected.map(\.fullName).filter { !$0.isEmpty })).sorted() - guard !values.isEmpty, values.count <= 64, identifier == nil || values.count == 1 else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - return values - } - - package func discoverJavaTestItems( - fileURL: URL, - rootURL: URL - ) async throws -> [LanguageTestItem] { - let normalizedFile = fileURL.standardizedFileURL - let discovered = try await resolvedJavaTestItems( - fileURL: normalizedFile, - rootURL: rootURL.standardizedFileURL - ) - return Self.projectJavaTestItems( - discovered, - fileURL: normalizedFile, - depth: 1 - ) - } - - private func executeJavaCommand( - _ commandID: String, - arguments: [ToolingJSONValue], - rootURL: URL - ) async throws -> ToolingJSONValue { - guard isLanguageServerEnabled("java", rootURL.standardizedFileURL) else { - throw LanguageToolingSessionError.providerDisabled("Java") - } - let command = LanguageServerCommand( - title: commandID, - command: commandID, - arguments: arguments - ) - guard let session = languageServers["java"], session.isRunning, - languageServerRoots["java"] == rootURL.standardizedFileURL else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - return try await session.executeReturningValue(command, fileURL: rootURL) - } - - private func executeJavaTestCommand( - _ commandID: String, - arguments: [ToolingJSONValue], - rootURL: URL - ) async throws -> ToolingJSONValue { - try await executeJavaCommand(commandID, arguments: arguments, rootURL: rootURL) - } - - private func resolvedJavaTestItems( - fileURL: URL, - rootURL: URL - ) async throws -> [JavaTestItem] { - try prepareJavaImportSession(rootURL: rootURL) - let revision = javaImportRevision - try await waitUntilLanguageServerReady(providerID: "java", rootURL: rootURL) - guard let session = languageServers["java"], session.isRunning else { - throw LanguageToolingSessionError.toolingUnavailable("Java") - } - let items: [JavaTestItem] = try await withCheckedThrowingContinuation { continuation in - do { - try session.javaTestItems(fileURL: fileURL) { result in - continuation.resume(with: result.map(\.items)) - } - } catch { - continuation.resume(throwing: error) - } - } - try Task.checkCancellation() - guard javaImportRevision == revision else { throw CancellationError() } - return items - } - - private static func stringValues(_ value: ToolingJSONValue) -> [String] { - guard case .array(let values) = value else { return [] } - return values.compactMap { value in - guard case .string(let value) = value, !value.isEmpty else { return nil } - return value - } - } - - private static func integerValue(_ value: ToolingJSONValue?) -> Int? { - switch value { - case .integer(let value): value - case .string(let value): Int(value) - default: nil - } - } - - private static func flattenJavaTestItems( - _ items: [JavaTestItem] - ) -> [JavaTestItem] { - items.flatMap { [$0] + flattenJavaTestItems($0.children) } - } - - private static func projectJavaTestItems( - _ items: [JavaTestItem], - fileURL: URL, - depth: Int - ) -> [LanguageTestItem] { - sortedJavaTestItems(items).flatMap { item in - [LanguageTestItem( - id: item.id, - providerID: "java", - label: item.label, - kind: .testCase, - fileURL: fileURL, - testIdentifier: item.fullName, - depth: depth, - reportIdentity: javaTestReportIdentity(item) - )] + projectJavaTestItems( - item.children, - fileURL: fileURL, - depth: depth + 1 - ) - } - } - - /// Keep JDT's display-name convention in its existing language adapter; - /// the generic Tests view never parses report names or execution selectors. - private static func javaTestReportIdentity(_ item: JavaTestItem) -> LanguageTestItem.ReportIdentity? { - if item.level == 5 { return .init(suite: item.fullName) } - guard item.level == 6, let separator = item.fullName.firstIndex(of: "#") else { return nil } - let name = item.fullName[item.fullName.index(after: separator)...] - return .init(suite: String(item.fullName[.. [JavaTestItem] { - items.sorted { - ($0.sortText ?? $0.label, $0.label, $0.id) - < ($1.sortText ?? $1.label, $1.label, $1.id) - } - } - - private static func javaTestNGMethodNames(_ item: JavaTestItem) -> [String] { - if item.level == 6 { return [item.fullName] } - return item.children.flatMap(javaTestNGMethodNames) - } - - private static func javaTestLaunchArguments( - _ value: ToolingJSONValue - ) throws -> ResolvedJavaTestLaunchArguments { - guard case .object(let response) = value else { - throw LanguageToolingSessionError.toolingUnavailable( - "The Java language service returned invalid test launch arguments." - ) - } - if case .string(let message)? = response["errorMessage"], !message.isEmpty { - throw LanguageToolingSessionError.toolingUnavailable(message) - } - guard case .object(let body)? = response["body"], - case .string(let workingDirectory)? = body["workingDirectory"], - !workingDirectory.isEmpty else { - throw LanguageToolingSessionError.toolingUnavailable( - "The Java language service returned incomplete test launch arguments." - ) - } - let mainClass: String? - if case .string(let value)? = body["mainClass"], !value.isEmpty { - mainClass = value - } else { - mainClass = nil - } - let projectName: String? - if case .string(let value)? = body["projectName"], !value.isEmpty { - projectName = value - } else { - projectName = nil - } - return ResolvedJavaTestLaunchArguments( - workingDirectory: workingDirectory, - mainClass: mainClass, - projectName: projectName, - classPaths: stringValues(body["classpath"] ?? .array([])), - modulePaths: stringValues(body["modulepath"] ?? .array([])), - vmArguments: stringValues(body["vmArguments"] ?? .array([])), - programArguments: stringValues(body["programArguments"] ?? .array([])) - ) - } - package func notifyWorkspaceFilesChanged( providerID: String, changes: [LanguageServerWorkspaceFileChange] @@ -1133,7 +401,6 @@ package final class LanguageToolingSessionManager: ObservableObject, let session = languageServers[providerID], session.isRunning else { return } try session.notifyWorkspaceFilesChanged(changes) - if providerID == "java" { scheduleJavaDependencyRefresh(after: changes) } } package func notifyDocumentSaved(_ fileURL: URL, text: String, currentText: String) throws { @@ -1227,15 +494,6 @@ package final class LanguageToolingSessionManager: ObservableObject, private func removeLanguageServer(providerID: String, stopSession: Bool) { languageServerActivation[providerID] = nil - if providerID == "java" { projectPreparation = nil } - if providerID == "java" { - javaDependencyChangeTask?.cancel() - javaDependencyChangeTask = nil - javaDependencyRefreshTask?.cancel() - javaDependencyRefreshTask = nil - javaDependencyWorkspaceURL = nil - javaDependencySnapshot = nil - } let operationID = languageServerOperationIDs[providerID] if languageServers[providerID] != nil { let wasPreparing = switch languageServerStates[providerID] { @@ -1248,14 +506,10 @@ package final class LanguageToolingSessionManager: ObservableObject, operationID: operationID?.uuidString) } clearDiagnostics(providerID: providerID) - if providerID == "java" { mavenProfileProjectResults.removeAll() } languageServerSessionIdentities[providerID] = nil let removed = languageServers.removeValue(forKey: providerID) if stopSession { removed?.stop() } languageServerRoots[providerID] = nil - if providerID == "java" { javaImportRevision &+= 1 } - languageServerMavenContexts[providerID] = nil - languageServerWorkspaceFingerprints[providerID] = nil languageServerFeatures[providerID] = nil languageServerInfos[providerID] = nil languageServerFeatureProviders[providerID] = nil @@ -1283,8 +537,6 @@ package final class LanguageToolingSessionManager: ObservableObject, languageServerInfos = [:] languageServers = [:] languageServerRoots = [:] - languageServerMavenContexts = [:] - languageServerWorkspaceFingerprints = [:] languageServerSessionIdentities = [:] languageServerFeatureProviders = [:] languageServerStates = [:] @@ -1346,15 +598,8 @@ package final class LanguageToolingSessionManager: ObservableObject, } let normalizedRoot = rootURL.standardizedFileURL - let fingerprint: String? - if languageServerRoots[providerID] == normalizedRoot, - let activeFingerprint = languageServerWorkspaceFingerprints[providerID] { - fingerprint = activeFingerprint - } else { - fingerprint = try workspaceFingerprintProvider(descriptor, normalizedRoot) - } stopLanguageServer(providerID: providerID) - try workspaceStateResetter(descriptor, normalizedRoot, fingerprint) + try workspaceStateResetter(descriptor, normalizedRoot) } package func navigate( @@ -1693,54 +938,6 @@ package final class LanguageToolingSessionManager: ObservableObject, try session.resolveVirtualDocument(uri: uri.absoluteString, completion: completion) } - package func javaNavigationMarkers( - fileURL: URL, - completion: @escaping (Result<[JavaNavigationMarker], Error>) -> Void - ) throws { - guard let session = readyLanguageServerSession(for: fileURL) else { - throw unavailableLanguageServerError(for: fileURL) - } - try session.javaNavigationMarkers(fileURL: fileURL, completion: completion) - } - - /// Launchable `main` methods in one file, from an already running Java session. - package func javaMainMethods( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws { - guard let session = readyLanguageServerSession(for: fileURL) else { - throw unavailableLanguageServerError(for: fileURL) - } - try session.javaMainMethods(fileURL: fileURL, completion: completion) - } - - /// Test classes and methods in one file, from an already running Java - /// session. Unlike test-tool-window discovery, it never starts the server. - package func javaTestItems( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws { - guard let session = readyLanguageServerSession(for: fileURL) else { - throw unavailableLanguageServerError(for: fileURL) - } - try session.javaTestItems(fileURL: fileURL, completion: completion) - } - - package func resolveJavaNavigation( - fileURL: URL, - marker: JavaNavigationMarker, - completion: @escaping (Result<[LanguageServerLocation], Error>) -> Void - ) throws { - guard let session = readyLanguageServerSession(for: fileURL) else { - throw unavailableLanguageServerError(for: fileURL) - } - try session.resolveJavaNavigation( - fileURL: fileURL, - marker: marker, - completion: completion - ) - } - package func resolveCompletion( _ item: LanguageServerCompletionItem, fileURL: URL, @@ -1805,15 +1002,14 @@ package final class LanguageToolingSessionManager: ObservableObject, private func ensureLanguageServerSession( descriptor: LanguageProviderDescriptor, rootURL: URL, - operationID requestedOperationID: UUID?, - javaImportOverride: JavaLanguageImportConfiguration? = nil + operationID requestedOperationID: UUID? ) throws -> any LanguageServerSession { guard stoppingServers[descriptor.id] == nil else { throw LanguageToolingSessionError.toolingUnavailable( L10n.string("The language server is still stopping. Try again after it has stopped.") ) } - // All entry points, including Maven reload, testing, and debugging, must + // All entry points, including reload, testing, and debugging, must // recheck the current workspace preference before creating or reusing a session. guard isLanguageServerEnabled(descriptor.id, rootURL) else { throw LanguageToolingSessionError.providerDisabled(descriptor.displayName) @@ -1891,43 +1087,6 @@ package final class LanguageToolingSessionManager: ObservableObject, throw LanguageToolingSessionError.toolingUnavailable(message) } - let workspaceFingerprint: String? - do { - workspaceFingerprint = try workspaceFingerprintProvider( - descriptor, - rootURL - ) - } catch { - startupAttempt?.end(throwing: error) - let state = LanguageServerSessionState.failed(LanguageServerSessionFailure( - code: "workspace_fingerprint_failed", - stage: "workspaceFingerprint", - message: error.localizedDescription - )) - languageServerStates[descriptor.id] = state - recordActivation(.startFailed, providerID: descriptor.id, rootURL: rootURL) - recordLogIssue(descriptor.id, operationID.uuidString, false, "workspaceFingerprint", "workspace_fingerprint_failed", nil) - onLanguageServerStateChange?(descriptor.id, state, operationID) - throw error - } - if let workspaceFingerprint, let workspaceStateCleaner { - do { - let removedCount = try workspaceStateCleaner( - descriptor, - rootURL, - workspaceFingerprint - ) - if let logSink, let server = logSubject(for: descriptor.id) { - logSink.emit(LspCacheCleaned(removed: Int64(removedCount), server: server, - operationID: operationID.uuidString)) - } - } catch { - // Cache maintenance is best-effort and must not prevent the - // current workspace's language server from starting. - recordLogIssue(descriptor.id, operationID.uuidString, true, "cacheCleanup", "cacheCleanupFailed", nil) - } - } - if let startupAttempt { created.observePluginStartup(startupAttempt) } let featureProvider = LanguageServerFeatureProvider( providerID: descriptor.id, @@ -1942,7 +1101,6 @@ package final class LanguageToolingSessionManager: ObservableObject, languageServerFeatureProviders[descriptor.id] = featureProvider languageServers[descriptor.id] = created languageServerRoots[descriptor.id] = rootURL - languageServerWorkspaceFingerprints[descriptor.id] = workspaceFingerprint configureLanguageServerCallbacks( created, providerID: descriptor.id, @@ -1959,15 +1117,7 @@ package final class LanguageToolingSessionManager: ObservableObject, ) do { - let importConfiguration = try javaImportOverride ?? javaLanguageImport(descriptor, rootURL: rootURL) - if descriptor.id == "java" { javaImportRevision &+= 1 } - languageServerMavenContexts[descriptor.id] = importConfiguration.mavenContext - try created.start( - rootURL: rootURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: importConfiguration.mavenContext, - javaGradle: importConfiguration.javaGradle - ) + try created.start(rootURL: rootURL) } catch { // Before the session handed the attempt to Core; a no-op after. startupAttempt?.end(throwing: error) @@ -2027,14 +1177,10 @@ package final class LanguageToolingSessionManager: ObservableObject, stop: Bool ) { guard languageServerSessionIdentities[providerID] == sessionIdentity else { return } - if providerID == "java" { mavenProfileProjectResults.removeAll() } clearDiagnostics(providerID: providerID) languageServerSessionIdentities[providerID] = nil let session = languageServers.removeValue(forKey: providerID) languageServerRoots[providerID] = nil - if providerID == "java" { javaImportRevision &+= 1 } - languageServerMavenContexts[providerID] = nil - languageServerWorkspaceFingerprints[providerID] = nil languageServerFeatures[providerID] = nil languageServerInfos[providerID] = nil languageServerFeatureProviders[providerID] = nil @@ -2273,27 +1419,6 @@ package final class LanguageToolingSessionManager: ObservableObject, self.languageServerInfos[providerID] = info } } - session.onProjectPreparation = { [weak self] snapshot in - guard let self, self.languageServerSessionIdentities[providerID] == sessionIdentity else { return } - if providerID == "java" { - let previous = self.projectPreparation - self.projectPreparation = snapshot - if snapshot.status != "ready" { - self.javaDependencyChangeTask?.cancel() - self.javaDependencyRefreshTask?.cancel() - } else if previous != snapshot { - self.refreshJavaDependenciesWhenReady() - } - } - } - session.onMavenProfileTask = { [weak self] status in - guard let self, self.languageServerSessionIdentities[providerID] == sessionIdentity else { return } - if status == "running" { self.mavenProfileProjectResults.removeAll() } - } - session.onMavenProfileProject = { [weak self] result in - guard let self, self.languageServerSessionIdentities[providerID] == sessionIdentity else { return } - self.mavenProfileProjectResults[result.projectURI] = result - } // Retiring sessions still own their terminal facts after UI state is cleared. // Core records carry their own identity, so do not apply the UI stale-session gate. let sink = logSink @@ -2331,20 +1456,6 @@ package final class LanguageToolingSessionManager: ObservableObject, ) { guard languageServerSessionIdentities[providerID] == sessionIdentity else { return } languageServerStates[providerID] = state - if providerID == "java" { - switch state { - case .startingProcess: projectPreparation = .init(phase: "starting", status: "loading", blocksRun: true) - case .initializing: projectPreparation = .init(phase: "importing", status: "loading", blocksRun: true) - case .failed: - let phase = projectPreparation?.phase - projectPreparation = .init( - phase: phase == "ready" ? "starting" : (phase ?? "starting"), - status: "failed", blocksRun: true - ) - case .stopped, .stopping: projectPreparation = nil - case .ready: break // Rust may still be synchronizing project configuration. - } - } resumeLanguageServerReadyWaiters( providerID: providerID, state: state, @@ -2355,14 +1466,6 @@ package final class LanguageToolingSessionManager: ObservableObject, } switch state { case .stopped, .failed: - if providerID == "java" { - javaDependencyChangeTask?.cancel() - javaDependencyChangeTask = nil - javaDependencyRefreshTask?.cancel() - javaDependencyRefreshTask = nil - javaDependencyWorkspaceURL = nil - javaDependencySnapshot = nil - } clearLanguageServerSession( providerID: providerID, sessionIdentity: sessionIdentity, @@ -2380,7 +1483,6 @@ package final class LanguageToolingSessionManager: ObservableObject, } languageServerFeatures[providerID] = session.features languageServerInfos[providerID] = session.serverInfo - if providerID == "java" { refreshJavaDependenciesWhenReady() } } onLanguageServerStateChange?( providerID, @@ -2458,23 +1560,6 @@ package final class LanguageToolingSessionManager: ObservableObject, let continuation: CheckedContinuation } - private struct JavaWorkspaceBuildRequest: Encodable { - let mainClass: String - let projectName: String? - let filePath: String - let isFullBuild: Bool - } - - private struct ResolvedJavaTestLaunchArguments { - let workingDirectory: String - let mainClass: String? - let projectName: String? - let classPaths: [String] - let modulePaths: [String] - let vmArguments: [String] - let programArguments: [String] - } - private func replaceDiagnostics( _ updatedDiagnostics: [LanguageServerDiagnostic], for fileURL: URL, diff --git a/macos/Sources/LitheModuleAPI/Catalog/BuiltInModuleCatalog.swift b/macos/Sources/LitheModuleAPI/Catalog/BuiltInModuleCatalog.swift index e4ed57ba30..bf5f513491 100644 --- a/macos/Sources/LitheModuleAPI/Catalog/BuiltInModuleCatalog.swift +++ b/macos/Sources/LitheModuleAPI/Catalog/BuiltInModuleCatalog.swift @@ -120,7 +120,6 @@ public enum BuiltInModuleCatalog { .languageIntelligence: [ ModuleContribution(id: "language.problems", kind: .toolWindow, title: "Problems", icon: "exclamationmark.triangle", order: 300, actionID: "language.problems.toggle", rendererID: "language.problems"), ModuleContribution(id: "language.references", kind: .toolWindow, title: "Usages", order: 310, actionID: "language.references.toggle", rendererID: "language.references"), - ModuleContribution(id: "language.spring", kind: .toolWindow, title: "Spring Endpoints", order: 320, actionID: "language.spring.toggle", rendererID: "language.spring"), ModuleContribution(id: "language.settings", kind: .settings, title: "Language Servers", icon: "server.rack") ], .localHistory: [ @@ -241,20 +240,8 @@ public enum OfficialPluginCatalog { public static let phpPluginID = PluginID("dev.lithe.plugin.php-support") public static let goPluginID = PluginID("dev.lithe.plugin.go-support") - public static let javaPluginID = PluginID("dev.lithe.plugin.java-support") public static let entries: [Entry] = [ - Entry( - id: javaPluginID, - displayName: "Java Support", - signatureRequirement: .publisherPackage, - bundledSignatureRequirement: .sameTeamAsHost, - distribution: .download, - languageID: "java", - languageDisplayName: "Java", - fileExtensions: ["java"], - projectFileNames: ["pom.xml", "build.gradle", "build.gradle.kts"] - ), Entry( id: goPluginID, displayName: "Go Support", diff --git a/macos/Sources/LitheModuleAPI/Catalog/BundledLanguagePluginCatalog.swift b/macos/Sources/LitheModuleAPI/Catalog/BundledLanguagePluginCatalog.swift index 22be45eab4..6787a6147f 100644 --- a/macos/Sources/LitheModuleAPI/Catalog/BundledLanguagePluginCatalog.swift +++ b/macos/Sources/LitheModuleAPI/Catalog/BundledLanguagePluginCatalog.swift @@ -41,7 +41,7 @@ public struct BundledLanguagePluginSpecification: Sendable { } // Note: Go 与 PHP 由声明式官方插件提供,不属于内置清单,见 .agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md -/// Describes bundled non-Java language recognition and the process-backed +/// Describes bundled language recognition and the process-backed /// features that are independently manageable as plugins. Go and PHP are /// official declarative packages and are therefore not duplicated here. public enum BundledLanguagePluginCatalog { @@ -68,7 +68,7 @@ public enum BundledLanguagePluginCatalog { .init(id: "astro", displayName: "Astro", fileExtensions: ["astro"]), .init(id: "json", displayName: "JSON", fileExtensions: ["json", "jsonc", "json5"]), .init(id: "yaml", displayName: "YAML", fileExtensions: ["yml", "yaml"], executableNames: ["yaml-language-server"], arguments: ["--stdio"]), - .init(id: "xml", displayName: "XML", fileExtensions: ["xml", "xsd", "wsdl", "pom"]), + .init(id: "xml", displayName: "XML", fileExtensions: ["xml", "xsd", "wsdl"]), .init(id: "markdown", displayName: "Markdown", fileExtensions: ["md", "markdown", "mdx"]), .init(id: "sql", displayName: "SQL", fileExtensions: ["sql"]), .init(id: "terraform", displayName: "Terraform", fileExtensions: ["tf", "tfvars"]), diff --git a/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift b/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift index 7b8b645c0f..3d5ea8ebd8 100644 --- a/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift +++ b/macos/Sources/LitheModuleAPI/Logging/LogEvents.generated.swift @@ -2037,394 +2037,12 @@ public struct EditorWorkspaceEditRollbackFailed: LogEvent { } } -public struct LspBuildExecutionFailed: LogEvent { - public static let id = "lsp.build.execution.failed" - public static let level: LogLevel = .error - public static let messageTemplate = "Language service project build for server {server} failed" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`builderFailedEarlier`: (Bool)? = nil, `duration`: Duration, `error`: any Error, `markerScope`: (String)? = nil, `outcome`: (String)? = nil, `recovery`: (Bool)? = nil, `server`: LogSegment, `waited`: (Duration)? = nil, `waiters`: Int64, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `builderFailedEarlier` { _logValues["builder_failed_earlier"] = .bool(value) } - _logValues["duration"] = .duration(`duration`) - _logValues["error"] = .error(`error`) - if let value = `markerScope` { _logValues["marker_scope"] = .token(value) } - if let value = `outcome` { _logValues["outcome"] = .token(value) } - if let value = `recovery` { _logValues["recovery"] = .bool(value) } - _logValues["server"] = .id(`server`) - if let value = `waited` { _logValues["waited"] = .duration(value) } - _logValues["waiters"] = .int(`waiters`) - self.fields = _logValues - } -} - -public struct LspBuildExecutionFinished: LogEvent { - public static let id = "lsp.build.execution.finished" - public static let level: LogLevel = .info - public static let messageTemplate = "Language service project build for server {server} finished" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`builderFailedEarlier`: (Bool)? = nil, `duration`: Duration, `markerScope`: (String)? = nil, `outcome`: (String)? = nil, `recovery`: (Bool)? = nil, `server`: LogSegment, `waited`: (Duration)? = nil, `waiters`: Int64, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `builderFailedEarlier` { _logValues["builder_failed_earlier"] = .bool(value) } - _logValues["duration"] = .duration(`duration`) - if let value = `markerScope` { _logValues["marker_scope"] = .token(value) } - if let value = `outcome` { _logValues["outcome"] = .token(value) } - if let value = `recovery` { _logValues["recovery"] = .bool(value) } - _logValues["server"] = .id(`server`) - if let value = `waited` { _logValues["waited"] = .duration(value) } - _logValues["waiters"] = .int(`waiters`) - self.fields = _logValues - } -} - -public struct LspBuildExecutionStarted: LogEvent { - public static let id = "lsp.build.execution.started" - public static let level: LogLevel = .debug - public static let messageTemplate = "Language service project build for server {server} started" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = true - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`builderFailedEarlier`: (Bool)? = nil, `markerScope`: (String)? = nil, `outcome`: (String)? = nil, `recovery`: (Bool)? = nil, `server`: LogSegment, `waited`: (Duration)? = nil, `waiters`: Int64, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `builderFailedEarlier` { _logValues["builder_failed_earlier"] = .bool(value) } - if let value = `markerScope` { _logValues["marker_scope"] = .token(value) } - if let value = `outcome` { _logValues["outcome"] = .token(value) } - if let value = `recovery` { _logValues["recovery"] = .bool(value) } - _logValues["server"] = .id(`server`) - if let value = `waited` { _logValues["waited"] = .duration(value) } - _logValues["waiters"] = .int(`waiters`) - self.fields = _logValues - } -} - -public struct LspBuildWaiting: LogEvent { - public static let id = "lsp.build.waiting" - public static let level: LogLevel = .info - public static let messageTemplate = "Project build waiting for server {server}: {reason}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`reason`: String, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["reason"] = .token(`reason`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - public struct LspCacheCleaned: LogEvent { public static let id = "lsp.cache.cleaned" public static let level: LogLevel = .debug - public static let messageTemplate = "Language server {server} cache cleaned" - public static let ratePerMinute = 60 - public static let owner = "LanguageToolingSessionManager" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`removed`: Int64, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["removed"] = .int(`removed`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspConfigurationCleaned: LogEvent { - public static let id = "lsp.configuration.cleaned" - public static let level: LogLevel = .info - public static let messageTemplate = "Unused server configuration areas removed for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`removed`: Int64, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["removed"] = .int(`removed`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspConfigurationCleanupFailed: LogEvent { - public static let id = "lsp.configuration.cleanup_failed" - public static let level: LogLevel = .warn - public static let messageTemplate = "Server configuration cleanup failed for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`error`: any Error, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["error"] = .error(`error`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspHostOperationFailed: LogEvent { - public static let id = "lsp.host.operation_failed" - public static let level: LogLevel = .warn - public static let messageTemplate = "Language host operation failed at {stage}" - public static let ratePerMinute = 120 - public static let owner = "LitheLanguageIntelligenceModule" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`error`: any Error, `server`: LogSegment, `stage`: String, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["error"] = .error(`error`) - _logValues["server"] = .id(`server`) - _logValues["stage"] = .token(`stage`) - self.fields = _logValues - } -} - -public struct LspMavenApplicationStarted: LogEvent { - public static let id = "lsp.maven.application_started" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven profile application started for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`projects`: (Int64)? = nil, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `projects` { _logValues["projects"] = .int(value) } - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenApplied: LogEvent { - public static let id = "lsp.maven.applied" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven profiles applied for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenCancelled: LogEvent { - public static let id = "lsp.maven.cancelled" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven profile application cancelled for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenConfigurationUpdated: LogEvent { - public static let id = "lsp.maven.configuration_updated" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven configuration updated for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`profilesUpdating`: Bool, `projectsReloaded`: Bool, `server`: LogSegment, `settingsChanged`: Bool, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["profiles_updating"] = .bool(`profilesUpdating`) - _logValues["projects_reloaded"] = .bool(`projectsReloaded`) - _logValues["server"] = .id(`server`) - _logValues["settings_changed"] = .bool(`settingsChanged`) - self.fields = _logValues - } -} - -public struct LspMavenPartiallyApplied: LogEvent { - public static let id = "lsp.maven.partially_applied" - public static let level: LogLevel = .warn - public static let messageTemplate = "Maven profiles partially applied for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenProjectFailed: LogEvent { - public static let id = "lsp.maven.project_failed" - public static let level: LogLevel = .error - public static let messageTemplate = "Maven profile project {project} update failed for server {server} with outcome {outcome}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`error`: any Error, `outcome`: String, `project`: URL, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["error"] = .error(`error`) - _logValues["outcome"] = .token(`outcome`) - _logValues["project"] = .path(`project`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenProjectFinished: LogEvent { - public static let id = "lsp.maven.project_finished" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven profile project {project} update finished for server {server} with outcome {outcome}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`duration`: (Duration)? = nil, `outcome`: String, `project`: URL, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `duration` { _logValues["duration"] = .duration(value) } - _logValues["outcome"] = .token(`outcome`) - _logValues["project"] = .path(`project`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenSettingsForwarded: LogEvent { - public static let id = "lsp.maven.settings_forwarded" - public static let level: LogLevel = .warn - public static let messageTemplate = "Maven settings forwarded unchanged for server {server}: {reason}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" + public static let messageTemplate = "Language server {server} cache cleaned" + public static let ratePerMinute = 60 + public static let owner = "LanguageToolingSessionManager" public static let debugOnly = false public let channel: LogChannel public let fields: [String: LogFieldValue] @@ -2433,22 +2051,22 @@ public struct LspMavenSettingsForwarded: LogEvent { LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) } - public init(`reason`: String, `server`: LogSegment, operationID: String? = nil) { + public init(`removed`: Int64, `server`: LogSegment, operationID: String? = nil) { self.operationID = operationID self.channel = LogChannel(.lsp, segments: [`server`]) var _logValues: [String: LogFieldValue] = [:] - _logValues["reason"] = .token(`reason`) + _logValues["removed"] = .int(`removed`) _logValues["server"] = .id(`server`) self.fields = _logValues } } -public struct LspMavenStartFailed: LogEvent { - public static let id = "lsp.maven.start_failed" +public struct LspHostOperationFailed: LogEvent { + public static let id = "lsp.host.operation_failed" public static let level: LogLevel = .warn - public static let messageTemplate = "Pending Maven profile update failed to start for server {server}" + public static let messageTemplate = "Language host operation failed at {stage}" public static let ratePerMinute = 120 - public static let owner = "lithe-core" + public static let owner = "LitheLanguageIntelligenceModule" public static let debugOnly = false public let channel: LogChannel public let fields: [String: LogFieldValue] @@ -2457,59 +2075,13 @@ public struct LspMavenStartFailed: LogEvent { LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) } - public init(`error`: any Error, `server`: LogSegment, operationID: String? = nil) { + public init(`error`: any Error, `server`: LogSegment, `stage`: String, operationID: String? = nil) { self.operationID = operationID self.channel = LogChannel(.lsp, segments: [`server`]) var _logValues: [String: LogFieldValue] = [:] _logValues["error"] = .error(`error`) _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspMavenTaskUpdated: LogEvent { - public static let id = "lsp.maven.task_updated" - public static let level: LogLevel = .info - public static let messageTemplate = "Maven profile task state updated" - public static let ratePerMinute = 60 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, `state`: String, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) - _logValues["state"] = .token(`state`) - self.fields = _logValues - } -} - -public struct LspMavenTimedOut: LogEvent { - public static let id = "lsp.maven.timed_out" - public static let level: LogLevel = .error - public static let messageTemplate = "Maven profile application timed out for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) + _logValues["stage"] = .token(`stage`) self.fields = _logValues } } @@ -2714,113 +2286,6 @@ public struct LspMessageWarningShown: LogEvent { } } -public struct LspNavigationCacheHit: LogEvent { - public static let id = "lsp.navigation.cache_hit" - public static let level: LogLevel = .debug - public static let messageTemplate = "Navigation markers served from cache for server {server} for {document}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`document`: URL, `documentVersion`: Int64, `markers`: Int64, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["document"] = .path(`document`) - _logValues["document_version"] = .int(`documentVersion`) - _logValues["markers"] = .int(`markers`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspNavigationLimited: LogEvent { - public static let id = "lsp.navigation.limited" - public static let level: LogLevel = .warn - public static let messageTemplate = "Navigation marker batch limited for server {server} for {document}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`document`: URL, `limit`: Int64, `server`: LogSegment, `tasks`: Int64, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["document"] = .path(`document`) - _logValues["limit"] = .int(`limit`) - _logValues["server"] = .id(`server`) - _logValues["tasks"] = .int(`tasks`) - self.fields = _logValues - } -} - -public struct LspNavigationMarkerFailed: LogEvent { - public static let id = "lsp.navigation.marker_failed" - public static let level: LogLevel = .warn - public static let messageTemplate = "Navigation marker verification failed for server {server} for {document}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`document`: URL, `documentVersion`: Int64, `error`: any Error, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["document"] = .path(`document`) - _logValues["document_version"] = .int(`documentVersion`) - _logValues["error"] = .error(`error`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspNavigationResolved: LogEvent { - public static let id = "lsp.navigation.resolved" - public static let level: LogLevel = .debug - public static let messageTemplate = "Navigation markers resolved for server {server} for {document}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`codeLenses`: Int64, `document`: URL, `documentVersion`: Int64, `duration`: Duration, `markers`: Int64, `server`: LogSegment, `tasks`: Int64, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["code_lenses"] = .int(`codeLenses`) - _logValues["document"] = .path(`document`) - _logValues["document_version"] = .int(`documentVersion`) - _logValues["duration"] = .duration(`duration`) - _logValues["markers"] = .int(`markers`) - _logValues["server"] = .id(`server`) - _logValues["tasks"] = .int(`tasks`) - self.fields = _logValues - } -} - public struct LspNotificationReceived: LogEvent { public static let id = "lsp.notification.received" public static let level: LogLevel = .info @@ -3161,128 +2626,6 @@ public struct LspTraceReceived: LogEvent { } } -public struct LspWorkspaceImportFinished: LogEvent { - public static let id = "lsp.workspace.import_finished" - public static let level: LogLevel = .info - public static let messageTemplate = "Language service project import finished for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`duration`: (Duration)? = nil, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `duration` { _logValues["duration"] = .duration(value) } - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspWorkspaceLegacyRemoved: LogEvent { - public static let id = "lsp.workspace.legacy_removed" - public static let level: LogLevel = .info - public static let messageTemplate = "Legacy project files removed for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`removedFiles`: Int64, `server`: LogSegment, `stateReset`: Bool, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["removed_files"] = .int(`removedFiles`) - _logValues["server"] = .id(`server`) - _logValues["state_reset"] = .bool(`stateReset`) - self.fields = _logValues - } -} - -public struct LspWorkspaceProgressReceived: LogEvent { - public static let id = "lsp.workspace.progress_received" - public static let level: LogLevel = .info - public static let messageTemplate = "Workspace import progress received for server {server} at {phase}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`completed`: (Int64)? = nil, `phase`: String, `server`: LogSegment, `total`: (Int64)? = nil, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - if let value = `completed` { _logValues["completed"] = .int(value) } - _logValues["phase"] = .token(`phase`) - _logValues["server"] = .id(`server`) - if let value = `total` { _logValues["total"] = .int(value) } - self.fields = _logValues - } -} - -public struct LspWorkspaceStalled: LogEvent { - public static let id = "lsp.workspace.stalled" - public static let level: LogLevel = .warn - public static let messageTemplate = "Workspace import progress stalled for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`duration`: Duration, `server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["duration"] = .duration(`duration`) - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - -public struct LspWorkspaceWaiting: LogEvent { - public static let id = "lsp.workspace.waiting" - public static let level: LogLevel = .info - public static let messageTemplate = "Workspace import waiting for service readiness for server {server}" - public static let ratePerMinute = 120 - public static let owner = "lithe-core" - public static let debugOnly = false - public let channel: LogChannel - public let fields: [String: LogFieldValue] - public let operationID: String? - public var reference: LogRecordReference { - LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) - } - - public init(`server`: LogSegment, operationID: String? = nil) { - self.operationID = operationID - self.channel = LogChannel(.lsp, segments: [`server`]) - var _logValues: [String: LogFieldValue] = [:] - _logValues["server"] = .id(`server`) - self.fields = _logValues - } -} - public struct PerfAppSampled: LogEvent { public static let id = "perf.app.sampled" public static let level: LogLevel = .debug @@ -4030,7 +3373,7 @@ public struct PluginsHostProtocolInitialized: LogEvent { public struct PluginsHostRequestFailed: LogEvent { public static let id = "plugins.host.request_failed" public static let level: LogLevel = .error - public static let messageTemplate = "Plugin host request failed" + public static let messageTemplate = "Plugin host request {method} failed with {code}" public static let ratePerMinute = 60 public static let owner = "Lithe" public static let debugOnly = false @@ -4041,11 +3384,13 @@ public struct PluginsHostRequestFailed: LogEvent { LogRecordReference(channel: channel.rawValue, event: Self.id, op: operationID) } - public init(`error`: any Error, `plugin`: LogSegment, operationID: String? = nil) { + public init(`code`: String, `error`: any Error, `method`: String, `plugin`: LogSegment, operationID: String? = nil) { self.operationID = operationID self.channel = LogChannel(.plugins, segments: [`plugin`, LogSegment("host")!]) var _logValues: [String: LogFieldValue] = [:] + _logValues["code"] = .token(`code`) _logValues["error"] = .error(`error`) + _logValues["method"] = .token(`method`) _logValues["plugin"] = .id(`plugin`) self.fields = _logValues } @@ -6046,40 +5391,6 @@ public struct EditorSyncFreezeSpan: Sendable { } } -public struct LspBuildExecutionSpan: Sendable { - private var state: LogSpanState - private let emit: @Sendable (any LogEvent) -> Void - private let `server`: LogSegment - private let `waiters`: Int64 - - private init(`server`: LogSegment, `waiters`: Int64, operationID: String, clock: LogSpanClock, emit: @escaping @Sendable (any LogEvent) -> Void) { - state = LogSpanState(operationID: operationID, clock: clock) - self.emit = emit - self.`server` = `server` - self.`waiters` = `waiters` - } - - public static func begin(`server`: LogSegment, `waiters`: Int64, operationID: String = UUID().uuidString.lowercased(), clock: LogSpanClock = .continuous, emit: @escaping @Sendable (any LogEvent) -> Void) -> Self { - let span = Self(server: `server`, waiters: `waiters`, operationID: operationID, clock: clock, emit: emit) - // Started is a DEBUG event; the sink drops it unless verbose diagnostics are on. - emit(LspBuildExecutionStarted(server: `server`, waiters: `waiters`, operationID: operationID)) - return span - } - - public mutating func finish(`builderFailedEarlier`: (Bool)? = nil, `markerScope`: (String)? = nil, `outcome`: (String)? = nil, `recovery`: (Bool)? = nil, `waited`: (Duration)? = nil) { - guard let duration = state.end() else { return } - emit(LspBuildExecutionFinished(builderFailedEarlier: `builderFailedEarlier`, duration: `duration`, markerScope: `markerScope`, outcome: `outcome`, recovery: `recovery`, server: `server`, waited: `waited`, waiters: `waiters`, operationID: state.operationID)) - } - - @discardableResult - public mutating func fail(_ error: any Error, `builderFailedEarlier`: (Bool)? = nil, `markerScope`: (String)? = nil, `outcome`: (String)? = nil, `recovery`: (Bool)? = nil, `waited`: (Duration)? = nil) -> LogRecordReference? { - guard let duration = state.end() else { return nil } - let event = LspBuildExecutionFailed(builderFailedEarlier: `builderFailedEarlier`, duration: `duration`, error: `error`, markerScope: `markerScope`, outcome: `outcome`, recovery: `recovery`, server: `server`, waited: `waited`, waiters: `waiters`, operationID: state.operationID) - emit(event) - return event.reference - } -} - public struct RunProcessExecutionSpan: Sendable { private var state: LogSpanState private let emit: @Sendable (any LogEvent) -> Void diff --git a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift index 362376c33f..ef1d422d6c 100644 --- a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift +++ b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift @@ -530,7 +530,9 @@ public struct PluginManifest: Equatable, Codable, Sendable { "languages": [1, 2], "outputLinkMatchers": [1], "projectGenerators": [1, 2], - "serverProcess": [1, 3], + // 4: a runtime launch names a tool definition that the host resolves + // through its four layers and starts with the definition's template. + "serverProcess": [1, 3, 4], "settings": [1, 2], "toolDefinitions": [1], "toolchainProviders": [1], diff --git a/macos/Sources/LitheSearchModule/Models/SearchModels.swift b/macos/Sources/LitheSearchModule/Models/SearchModels.swift index f605cd2e65..cfd2d1760d 100644 --- a/macos/Sources/LitheSearchModule/Models/SearchModels.swift +++ b/macos/Sources/LitheSearchModule/Models/SearchModels.swift @@ -9,7 +9,7 @@ public struct ProjectSearchOptions: Hashable, Sendable { public var regularExpression = false /// 替换时让结果沿用命中处的大小写形态(fooBar/FooBar/FOOBAR)。 public var preserveCase = false - /// 逗号分隔的 glob 掩码,如 `*.java, *.kt`;为空表示不过滤。 + /// 逗号分隔的 glob 掩码,如 `*.swift, *.toml`;为空表示不过滤。 public var fileMask = "" public static let `default` = ProjectSearchOptions() diff --git a/macos/Sources/LitheWorkspaceModule/Application/WorkspaceFeatureModel.swift b/macos/Sources/LitheWorkspaceModule/Application/WorkspaceFeatureModel.swift index d731fdaca6..2159b49a58 100644 --- a/macos/Sources/LitheWorkspaceModule/Application/WorkspaceFeatureModel.swift +++ b/macos/Sources/LitheWorkspaceModule/Application/WorkspaceFeatureModel.swift @@ -582,7 +582,7 @@ package final class WorkspaceFeatureModel: ObservableObject { scheduleSearchIndexWarm(at: workspaceURL, rules: rules) // The tree is usable as soon as the shared snapshot is ready. Service - // preparation below may involve Git, Java, and local history work. + // preparation below may involve Git, language tooling, and local history work. if isInitialLoad { isLoadingWorkspace = false } else { @@ -1673,7 +1673,6 @@ package final class WorkspaceFeatureModel: ObservableObject { ) guard !Task.isCancelled, self.workspaceURL == workspaceURL, workspaceGeneration == generation else { return } let requiresProjectServiceReload = changedURLs.contains { url in - let name = url.lastPathComponent.lowercased() let dependencyIndex = workspaceURL.standardizedFileURL .appendingPathComponent(".lithe", isDirectory: true) .appendingPathComponent("dependencies", isDirectory: true) @@ -1682,10 +1681,7 @@ package final class WorkspaceFeatureModel: ObservableObject { let isLitheConfiguration = url.pathExtension.lowercased() == "json" && url.path.hasPrefix(workspaceURL.appendingPathComponent(".lithe").path + "/") && url.standardizedFileURL != dependencyIndex - let isBuildManagementFile = name == "pom.xml" - || name == "build.gradle" - || name == "build.gradle.kts" - return isLitheConfiguration || isBuildManagementFile + return isLitheConfiguration } if requiresProjectServiceReload, !reloadedProjectServices { await reloadProjectServices?() } } diff --git a/macos/Tests/LitheCoreVerifier/CoreVerification.swift b/macos/Tests/LitheCoreVerifier/CoreVerification.swift index c5bd71108b..5e7020ac5e 100644 --- a/macos/Tests/LitheCoreVerifier/CoreVerification.swift +++ b/macos/Tests/LitheCoreVerifier/CoreVerification.swift @@ -159,15 +159,15 @@ struct CoreVerification { private static func verifyDiffParser() { let patch = """ - diff --git a/Example.java b/Example.java - --- a/Example.java - +++ b/Example.java + diff --git a/example.txt b/example.txt + --- a/example.txt + +++ b/example.txt @@ -1,3 +1,4 @@ - class Example { - - return 1; - + return 2; - + // added - } + [section] + -value = 1 + +value = 2 + +# added + end """ let document = DiffParser.parseDocument(patch) require(document.hunks.count == 1, "expected one diff hunk") diff --git a/macos/Tests/LitheDebugModuleTests/DebugModuleTests.swift b/macos/Tests/LitheDebugModuleTests/DebugModuleTests.swift index e39c4857fe..ea2e2af84a 100644 --- a/macos/Tests/LitheDebugModuleTests/DebugModuleTests.swift +++ b/macos/Tests/LitheDebugModuleTests/DebugModuleTests.swift @@ -86,22 +86,6 @@ struct DebugModuleTests { #expect(manager.activeSessionIDs.isEmpty) } - @Test - func explicitHotUpdateRestartReplacesTheOriginalSessionWithNewRuntimePaths() async { - let session = DeferredInspectionDebugSession() - let feature = makeDeferredFeature(session: session, rootPath: "/workspace/hot-update-restart") - defer { feature.stop() } - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app")) - let previousID = feature.activeSessionID - await feature.restartJavaService { _, _ in - JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app", classPaths: ["/workspace/new-output"]) - } - #expect(feature.activeSessionID != previousID) - #expect(session.startCount == 2) - #expect(session.launchConfigurations.last?.arguments["classPaths"] == .array([.string("/workspace/new-output")])) - #expect(feature.canUpdateJavaService) - } - @Test func adapterSelectionMatchesTheSharedHostFixture() throws { struct Fixture: Decodable { @@ -154,17 +138,14 @@ struct DebugModuleTests { } @Test - func explicitAdapterIdentitySurvivesCodingAndSteppingFilterChanges() throws { + func explicitAdapterIdentitySurvivesCoding() throws { let configuration = DebugLaunchConfiguration( name: "engine target", request: .launch, arguments: ["program": .string("bin/example")], adapterProviderID: "dev.example.native/lldb", adapterEndpoint: DebugAdapterEndpoint(host: "localhost", port: 5678) ) - let filters = DebugSteppingFilters(classNameFilters: [], skipSynthetics: true, - skipStaticInitializers: false, skipConstructors: false, hideFilteredStackFrames: true) - let updated = configuration.applying(steppingFilters: filters) - let decoded = try JSONDecoder().decode(DebugLaunchConfiguration.self, from: JSONEncoder().encode(updated)) - #expect(decoded == updated) + let decoded = try JSONDecoder().decode(DebugLaunchConfiguration.self, from: JSONEncoder().encode(configuration)) + #expect(decoded == configuration) #expect(decoded.adapterProviderID == "dev.example.native/lldb") #expect(decoded.adapterEndpoint == configuration.adapterEndpoint) let oldJSON = Data(#"{"name":"file","request":"launch","arguments":{}}"#.utf8) @@ -382,34 +363,6 @@ struct DebugModuleTests { #expect(manager.provider(for: source) == nil) } - @Test - func hotUpdateRestartKeepsOtherDebugSessionsAlive() async throws { - let descriptor = DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"]) - var createdSessions: [DeferredInspectionDebugSession] = [] - let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in - let session = DeferredInspectionDebugSession() - createdSessions.append(session) - return session - } - let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - defer { feature.reset() } - let root = URL(fileURLWithPath: "/workspace/hot-update-multiple", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") - let configuration = DebugLaunchConfiguration( - name: "Main", request: .launch, arguments: ["mainClass": .string("example.Main")] - ) - #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) - let firstID = try #require(feature.activeSessionID) - #expect(feature.startAdditional(fileURL: source, rootURL: root, configuration: configuration)) - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app")) - await feature.restartJavaService { _, _ in JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app") } - #expect(createdSessions.count == 3) - #expect(createdSessions[0].isRunning) - #expect(!createdSessions[1].isRunning) - #expect(feature.sessionSummaries.contains { $0.id == firstID }) - #expect(feature.sessionSummaries.count == 2) - } - /// A plugin that goes away ends its own sessions. Another plugin's session /// of the same language, which a language-keyed stop would also end, keeps /// running. @@ -441,52 +394,6 @@ struct DebugModuleTests { #expect(feature.sessionSummaries.count == 1) } - @Test - func hotUpdateBuildFailureNeverTouchesRunningClasses() async { - let session = DeferredInspectionDebugSession() - let feature = makeDeferredFeature(session: session, rootPath: "/workspace/hot-update") - defer { feature.stop() } - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget( - mainClass: "example.Main", projectName: "app", classPaths: ["/workspace/hot-update/bin"] - )) - await feature.applyJavaServiceUpdate { _, _, _ in - throw NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "Compilation errors"]) - } - #expect(session.redefineCount == 0) - #expect(feature.serviceUpdateMessage?.contains("Compilation errors") == true) - #expect(feature.updatingServiceSessionID == nil) - } - - @Test - func hotUpdateStopsBeforeApplyingWhenExecutionEndsDuringBuild() async { - let session = DeferredInspectionDebugSession() - let feature = makeDeferredFeature(session: session, rootPath: "/workspace/hot-update-stop") - defer { feature.stop() } - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app")) - await feature.applyJavaServiceUpdate { _, _, _ in feature.stop() } - #expect(session.redefineCount == 0) - #expect(feature.serviceUpdateMessage == nil) - } - - @Test - func hotUpdateAppliesAfterBuildAndDoesNotResumeExecution() async { - let session = DeferredInspectionDebugSession() - let feature = makeDeferredFeature(session: session, rootPath: "/workspace/hot-update-success") - defer { feature.stop() } - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app")) - var built = false - await feature.applyJavaServiceUpdate { target, source, root in - #expect(target.mainClass == "example.Main") - #expect(source == root.appendingPathComponent("src/Main.java")) - #expect(session.redefineCount == 0) - built = true - } - #expect(built) - #expect(session.redefineCount == 1) - #expect(session.executionCommands.isEmpty) - #expect(feature.serviceUpdateMessage == "Code changes applied.") - } - @Test func anAdapterThatDeclaredHotCodeReplaceOffersApplyingChangesAndSendsItAfterPreparing() async { let session = DeferredInspectionDebugSession() @@ -510,20 +417,6 @@ struct DebugModuleTests { #expect(feature.updatingServiceSessionID == nil) } - @Test - func aDeclaredHotCodeReplaceReplacesTheHostServiceUpdateSoOneButtonShows() async { - let session = DeferredInspectionDebugSession() - session.declaredBehavior = DebugAdapterDeclaredBehavior( - features: .init(hotCodeReplace: .init(request: "script.reload")) - ) - let feature = makeDeferredFeature(session: session, rootPath: "/workspace/declared-over-service") - defer { feature.stop() } - feature.registerJavaUpdateTarget(JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app")) - - #expect(feature.canApplyDeclaredCodeChanges) - #expect(!feature.canUpdateJavaService) - } - @Test func anAdapterThatDeclaredNothingOffersNoApplyChangesAction() async { let session = DeferredInspectionDebugSession() @@ -582,7 +475,7 @@ struct DebugModuleTests { func boundedConsoleOutputPreservesSGRAcrossChunksAndSessions(background: Bool, padding: Int) throws { var adapters: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [ - DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"]) + DebugProviderDescriptor(id: "tool-a", displayName: "Tool A", fileExtensions: ["txt"]) ]) { _, _ in let adapter = DeferredInspectionDebugSession() adapters.append(adapter) @@ -591,7 +484,7 @@ struct DebugModuleTests { let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) defer { feature.reset() } let root = URL(fileURLWithPath: "/workspace/bounded-output") - let source = root.appendingPathComponent("Main.java") + let source = root.appendingPathComponent("Main.txt") let configuration = DebugLaunchConfiguration(name: "Main", request: .launch, arguments: [:]) #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) let first = try #require(feature.activeSessionID) @@ -658,23 +551,12 @@ struct DebugModuleTests { #expect(presentation.text == "replacement") } - @Test - func springPortConflictOutputProducesAnActionableDiagnostic() { - let manager = DebugAdapterSessionManager(providers: []) { _, _ in nil } - let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - - feature.appendDebuggeeOutput("Web server failed to start. Port 8080 was already in use.\n") - - #expect(feature.errorMessage == "Port 8080 is already in use. Stop the process using it or change server.port in the Run configuration.") - #expect(feature.output.contains("Port 8080 was already in use.")) - } - @Test func staleSessionCallbacksCannotOverwriteAReplacementSession() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -682,12 +564,12 @@ struct DebugModuleTests { createdSessions.append(session) return session } - let root = URL(fileURLWithPath: "/tmp/java-debug-reconnect", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-reconnect", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") _ = try manager.activate(for: source, rootURL: root) let first = try #require(createdSessions.first) - manager.stop(providerID: "java") + manager.stop(providerID: "tool-a") _ = try manager.activate(for: source, rootURL: root) let second = try #require(createdSessions.dropFirst().first) @@ -695,17 +577,17 @@ struct DebugModuleTests { first.emit(.output(category: "stderr", output: "stale\n")) first.fail() - #expect(manager.lastEvents["java"] == .output(category: "stdout", output: "current\n")) - #expect(manager.states["java"] == .ready) + #expect(manager.lastEvents["tool-a"] == .output(category: "stdout", output: "current\n")) + #expect(manager.states["tool-a"] == .ready) manager.stopAll() } @Test func independentSessionsShareBreakpointsButKeepStateAndCallbacksSeparate() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -718,8 +600,8 @@ struct DebugModuleTests { receivedEvents.append((sessionID, providerID, event)) } - let root = URL(fileURLWithPath: "/tmp/java-debug-multiple", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-multiple", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let first = try manager.activateNew(for: source, rootURL: root) let second = try manager.activateNew(for: source, rootURL: root) let firstSession = try #require(createdSessions.first) @@ -727,8 +609,8 @@ struct DebugModuleTests { #expect(first.id != second.id) #expect(manager.sessionSummaries.map(\.id) == [first.id, second.id]) - #expect(manager.activeAdapterIDs == ["java"]) - #expect(manager.session(providerID: "java") === secondSession) + #expect(manager.activeAdapterIDs == ["tool-a"]) + #expect(manager.session(providerID: "tool-a") === secondSession) try manager.setBreakpoints([ DebugSourceBreakpoint(line: 12, enabled: true) @@ -739,30 +621,30 @@ struct DebugModuleTests { firstSession.emit(.output(category: "stdout", output: "old\n")) secondSession.emit(.output(category: "stdout", output: "new\n")) #expect(receivedEvents.map { $0.0 } == [first.id, second.id]) - #expect(manager.lastEvents["java"] == .output(category: "stdout", output: "new\n")) + #expect(manager.lastEvents["tool-a"] == .output(category: "stdout", output: "new\n")) #expect(manager.select(sessionID: first.id)) firstSession.emit(.output(category: "stdout", output: "selected-first\n")) - #expect(manager.lastEvents["java"] == .output(category: "stdout", output: "selected-first\n")) + #expect(manager.lastEvents["tool-a"] == .output(category: "stdout", output: "selected-first\n")) manager.stop(sessionID: second.id) - #expect(manager.session(providerID: "java") === firstSession) + #expect(manager.session(providerID: "tool-a") === firstSession) #expect(manager.activeSessionIDs == [first.id]) - #expect(manager.states["java"] == .ready) + #expect(manager.states["tool-a"] == .ready) #expect(manager.sessionSummaries.map(\.id) == [first.id]) manager.stop(sessionID: first.id) #expect(manager.activeSessionIDs.isEmpty) #expect(manager.activeAdapterIDs.isEmpty) - #expect(manager.states["java"] == .idle) + #expect(manager.states["tool-a"] == .idle) } @Test func sessionAwareRunInTerminalRequestsKeepTheirOwningSessionIdentity() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -775,15 +657,15 @@ struct DebugModuleTests { requests.append((sessionID, request)) completion(.success(DebugRunInTerminalResponse(processID: 42))) } - let root = URL(fileURLWithPath: "/tmp/java-debug-terminal-routing", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-terminal-routing", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let first = try manager.activateNew(for: source, rootURL: root) let second = try manager.activateNew(for: source, rootURL: root) let request = DebugRunInTerminalRequest( kind: .integrated, title: "Second", cwd: root.path, - args: ["/usr/bin/java", "example.Second"], + args: ["/usr/bin/tool-a", "example.Second"], environment: [], argsCanBeInterpretedByShell: false ) @@ -798,9 +680,9 @@ struct DebugModuleTests { @Test func consoleHistoryIsBoundedDeduplicatedAndScopedToTheSelectedSession() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -809,12 +691,12 @@ struct DebugModuleTests { return session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-console-history", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-console-history", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let configuration = DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) @@ -890,9 +772,9 @@ struct DebugModuleTests { @Test func featureSwitchesSessionsWithoutMixingTheirConsoleState() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -901,17 +783,17 @@ struct DebugModuleTests { return session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-feature-sessions", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-feature-sessions", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let firstConfiguration = DebugLaunchConfiguration( name: "First", request: .launch, - arguments: ["mainClass": .string("example.First")] + arguments: ["program": .string("example.First")] ) let secondConfiguration = DebugLaunchConfiguration( name: "Second", request: .launch, - arguments: ["mainClass": .string("example.Second")] + arguments: ["program": .string("example.Second")] ) #expect(feature.start( @@ -954,9 +836,9 @@ struct DebugModuleTests { @Test func additionalSessionLaunchFailureRestoresTheOriginalActiveSession() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -968,17 +850,17 @@ struct DebugModuleTests { return session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-additional-failure", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-additional-failure", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let firstConfiguration = DebugLaunchConfiguration( name: "First", request: .launch, - arguments: ["mainClass": .string("example.First")] + arguments: ["program": .string("example.First")] ) let secondConfiguration = DebugLaunchConfiguration( name: "Second", request: .launch, - arguments: ["mainClass": .string("example.Second")] + arguments: ["program": .string("example.Second")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: firstConfiguration)) @@ -1006,9 +888,9 @@ struct DebugModuleTests { @Test func stoppingActiveSessionPromotesTheMostRecentRemainingSession() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) var createdSessions: [DeferredInspectionDebugSession] = [] let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in @@ -1017,17 +899,17 @@ struct DebugModuleTests { return session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-stop-promotion", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-stop-promotion", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let firstConfiguration = DebugLaunchConfiguration( name: "First", request: .launch, - arguments: ["mainClass": .string("example.First")] + arguments: ["program": .string("example.First")] ) let secondConfiguration = DebugLaunchConfiguration( name: "Second", request: .launch, - arguments: ["mainClass": .string("example.Second")] + arguments: ["program": .string("example.Second")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: firstConfiguration)) @@ -1124,14 +1006,14 @@ struct DebugModuleTests { let core = RecordingDebugProtocolCore() let deadlines = RecordingDebugDeadlineScheduler() let session = CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-session", + sessionID: "tool-a-session", deadlineScheduler: deadlines ) - try session.start(rootURL: URL(fileURLWithPath: "/tmp/java-core", isDirectory: true)) + try session.start(rootURL: URL(fileURLWithPath: "/tmp/tool-a-core", isDirectory: true)) #expect(session.state == .initializing) #expect(transport.sentData == [Data("initialize-frame".utf8)]) @@ -1256,15 +1138,15 @@ struct DebugModuleTests { "result": [ "kind": "exceptionInfo", "exceptionInfo": [ - "exceptionId": "java.lang.IllegalStateException", - "description": "java.lang.IllegalStateException: session expired", + "exceptionId": "example.StateError", + "description": "example.StateError: session expired", "breakMode": "always", "details": [ "message": "session expired", "typeName": "IllegalStateException", - "fullTypeName": "java.lang.IllegalStateException", + "fullTypeName": "example.StateError", "evaluateName": "exception", - "stackTrace": "at example.Main.run(Main.java:12)", + "stackTrace": "at example.Main.run(Main.txt:12)", "innerExceptions": [[ "message": "token expired", "typeName": "TokenExpiredException", @@ -1277,15 +1159,15 @@ struct DebugModuleTests { ]]) transport.emitData(Data("exception-info-response".utf8)) #expect(try exceptionInfoResult?.get() == DebugExceptionInfo( - exceptionID: "java.lang.IllegalStateException", - description: "java.lang.IllegalStateException: session expired", + exceptionID: "example.StateError", + description: "example.StateError: session expired", breakMode: "always", details: DebugExceptionDetails( message: "session expired", typeName: "IllegalStateException", - fullTypeName: "java.lang.IllegalStateException", + fullTypeName: "example.StateError", evaluateName: "exception", - stackTrace: "at example.Main.run(Main.java:12)", + stackTrace: "at example.Main.run(Main.txt:12)", innerExceptions: [DebugExceptionDetails( message: "token expired", typeName: "TokenExpiredException", @@ -1313,7 +1195,7 @@ struct DebugModuleTests { var gotoTargetsResult: Result<[DebugGotoTarget], Error>? session.requestGotoTargets( - fileURL: URL(fileURLWithPath: "/tmp/Main.java"), + fileURL: URL(fileURLWithPath: "/tmp/Main.txt"), line: 20, column: 5 ) { gotoTargetsResult = $0 } @@ -1324,7 +1206,7 @@ struct DebugModuleTests { "operationId": gotoTargetsOperationID, "result": [ "kind": "gotoTargets", - "targets": [["id": 31, "label": "Main.java:20", "line": 20]] + "targets": [["id": 31, "label": "Main.txt:20", "line": 20]] ] ]]) transport.emitData(Data("goto-targets-response".utf8)) @@ -1345,7 +1227,7 @@ struct DebugModuleTests { #expect(throws: (any Error).self) { try timedOutResult?.get() } session.stop() #expect(session.state == .idle) - #expect(core.destroyedSessionIDs == ["java-session"]) + #expect(core.destroyedSessionIDs == ["tool-a-session"]) #expect(transport.stopCalls == 1) } @@ -1511,10 +1393,10 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let session = CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-run-in-terminal", + sessionID: "tool-a-run-in-terminal", deadlineScheduler: RecordingDebugDeadlineScheduler() ) var receivedRequest: DebugRunInTerminalRequest? @@ -1523,26 +1405,26 @@ struct DebugModuleTests { completion(.success(DebugRunInTerminalResponse(processID: 4242))) } - try session.start(rootURL: URL(fileURLWithPath: "/tmp/java-run-in-terminal")) + try session.start(rootURL: URL(fileURLWithPath: "/tmp/tool-a-run-in-terminal")) defer { session.stop() } #expect(core.lastSupportsRunInTerminalRequest == true) - core.enqueueReceive(sessionID: "java-run-in-terminal", state: "launching", events: [[ + core.enqueueReceive(sessionID: "tool-a-run-in-terminal", state: "launching", events: [[ "sequence": 2, "type": "runInTerminalRequested", "requestId": "runInTerminal-44", "request": [ "kind": "integrated", "title": "Debug Main", - "cwd": "/tmp/java-run-in-terminal", - "args": ["/opt/jdk/bin/java", "example.Main"], - "environment": [["name": "JAVA_HOME", "value": "/opt/jdk"]], + "cwd": "/tmp/tool-a-run-in-terminal", + "args": ["/opt/tool-a/bin/tool-a", "example.Main"], + "environment": [["name": "TOOL_A_HOME", "value": "/opt/tool-a"]], "argsCanBeInterpretedByShell": false ] ]]) transport.emitData(Data("run-in-terminal-request".utf8)) - #expect(receivedRequest?.args == ["/opt/jdk/bin/java", "example.Main"]) + #expect(receivedRequest?.args == ["/opt/tool-a/bin/tool-a", "example.Main"]) #expect(core.runInTerminalCompletions == [RecordingRunInTerminalCompletion( requestID: "runInTerminal-44", response: DebugRunInTerminalResponse(processID: 4242), @@ -1556,25 +1438,25 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let session = CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-run-in-terminal-stop", + sessionID: "tool-a-run-in-terminal-stop", deadlineScheduler: RecordingDebugDeadlineScheduler() ) var pendingCompletion: DebugRunInTerminalCompletion? session.onRunInTerminalRequest = { _, completion in pendingCompletion = completion } - try session.start(rootURL: URL(fileURLWithPath: "/tmp/java-run-in-terminal-stop")) - core.enqueueReceive(sessionID: "java-run-in-terminal-stop", state: "launching", events: [[ + try session.start(rootURL: URL(fileURLWithPath: "/tmp/tool-a-run-in-terminal-stop")) + core.enqueueReceive(sessionID: "tool-a-run-in-terminal-stop", state: "launching", events: [[ "sequence": 2, "type": "runInTerminalRequested", "requestId": "runInTerminal-45", "request": [ "kind": "integrated", - "cwd": "/tmp/java-run-in-terminal-stop", - "args": ["/opt/jdk/bin/java"], + "cwd": "/tmp/tool-a-run-in-terminal-stop", + "args": ["/opt/tool-a/bin/tool-a"], "environment": [], "argsCanBeInterpretedByShell": false ] @@ -1629,13 +1511,13 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let session = CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-no-capabilities", + sessionID: "tool-a-no-capabilities", deadlineScheduler: RecordingDebugDeadlineScheduler() ) - try session.start(rootURL: URL(fileURLWithPath: "/tmp/java-no-capabilities")) + try session.start(rootURL: URL(fileURLWithPath: "/tmp/tool-a-no-capabilities")) defer { session.stop() } var dataResult: Result? @@ -1890,13 +1772,13 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let session = CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-variable-paging", + sessionID: "tool-a-variable-paging", deadlineScheduler: RecordingDebugDeadlineScheduler() ) - try session.start(rootURL: URL(fileURLWithPath: "/tmp/java-variable-paging")) + try session.start(rootURL: URL(fileURLWithPath: "/tmp/tool-a-variable-paging")) defer { session.stop() } var result: Result<[DebugVariable], Error>? @@ -1913,7 +1795,7 @@ struct DebugModuleTests { #expect(core.inspectionRequests.last?.count == 2) let operationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-variable-paging", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-variable-paging", state: "paused", events: [[ "sequence": 2, "type": "operationCompleted", "operationId": operationID, @@ -1944,22 +1826,22 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-stopped-context", + sessionID: "tool-a-stopped-context", deadlineScheduler: RecordingDebugDeadlineScheduler() ) } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-stopped-context", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-stopped-context", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") var stoppedLocation: (URL, Int, Int)? feature.onStoppedLocation = { stoppedLocation = ($0, $1, $2) } #expect(feature.start( @@ -1968,12 +1850,12 @@ struct DebugModuleTests { configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 1, "type": "capabilities", "capabilities": [ @@ -2002,7 +1884,7 @@ struct DebugModuleTests { "type": "stopped", "reason": "exception", "threadId": 13, - "description": "java.lang.IllegalStateException: session expired" + "description": "example.StateError: session expired" ]]) transport.emitData(Data("stopped-event".utf8)) #expect(core.inspectionRequests.map(\.kind) == ["exceptionInfo", "threads"]) @@ -2010,7 +1892,7 @@ struct DebugModuleTests { let threadsOperationID = try #require( core.inspectionRequests.first(where: { $0.kind == "threads" })?.operationID ) - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 2, "type": "operationCompleted", "operationId": threadsOperationID, @@ -2031,7 +1913,7 @@ struct DebugModuleTests { let stackOperationID = try #require( core.inspectionRequests.first(where: { $0.kind == "stackTrace" })?.operationID ) - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 3, "type": "operationCompleted", "operationId": stackOperationID, @@ -2055,7 +1937,7 @@ struct DebugModuleTests { let scopesOperationID = try #require( core.inspectionRequests.first(where: { $0.kind == "scopes" })?.operationID ) - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 4, "type": "operationCompleted", "operationId": scopesOperationID, @@ -2087,7 +1969,7 @@ struct DebugModuleTests { let variablesOperationID = try #require( core.inspectionRequests.first(where: { $0.kind == "variables" })?.operationID ) - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 5, "type": "operationCompleted", "operationId": variablesOperationID, @@ -2117,23 +1999,23 @@ struct DebugModuleTests { let exceptionOperationID = try #require( core.inspectionRequests.first(where: { $0.kind == "exceptionInfo" })?.operationID ) - core.enqueueReceive(sessionID: "java-stopped-context", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "paused", events: [[ "sequence": 6, "type": "operationCompleted", "operationId": exceptionOperationID, "result": [ "kind": "exceptionInfo", "exceptionInfo": [ - "exceptionId": "java.lang.IllegalStateException", - "description": "java.lang.IllegalStateException: session expired", + "exceptionId": "example.StateError", + "description": "example.StateError: session expired", "breakMode": "always" ] ] ]]) transport.emitData(Data("late-exception-response".utf8)) - #expect(feature.exceptionInfo?.exceptionID == "java.lang.IllegalStateException") + #expect(feature.exceptionInfo?.exceptionID == "example.StateError") - core.enqueueReceive(sessionID: "java-stopped-context", state: "running", events: [[ + core.enqueueReceive(sessionID: "tool-a-stopped-context", state: "running", events: [[ "sequence": 7, "type": "continued", "threadId": 13 @@ -2142,140 +2024,18 @@ struct DebugModuleTests { #expect(feature.stoppedThreadIDs.isEmpty) } - @Test - func javaSteppingFiltersLoadDefaultsAndPersistNormalizedOverrides() { - let defaults = DebugSteppingFilters( - classNameFilters: ["$JDK", "org.junit.*"], - skipSynthetics: true, - skipStaticInitializers: true, - skipConstructors: false, - hideFilteredStackFrames: true - ) - let normalized = DebugSteppingFilters( - classNameFilters: ["$JDK", "org.mockito.*"], - skipSynthetics: true, - skipStaticInitializers: false, - skipConstructors: true, - hideFilteredStackFrames: true - ) - let resolver = RecordingDebugSteppingFilterResolver( - defaults: defaults, - normalizedOverride: normalized - ) - let persistence = RecordingDebugSteppingFilterPersistence() - let manager = DebugAdapterSessionManager(providers: []) { _, _ in nil } - let feature = GenericDebugFeatureModel( - paging: LinkedCoreDebugPaging(), - sessions: manager, - steppingFilterResolver: resolver, - steppingFilterPersistence: persistence - ) - - #expect(feature.javaSteppingFilters == defaults) - #expect(resolver.requests == [RecordingDebugSteppingFilterResolution( - adapterID: "java", - filters: nil - )]) - - let override = DebugSteppingFilters( - classNameFilters: [" org.mockito.* ", "$JDK", "org.mockito.*", ""], - skipSynthetics: true, - skipStaticInitializers: false, - skipConstructors: true, - hideFilteredStackFrames: true - ) - feature.updateJavaSteppingFilters(override) - - #expect(resolver.requests.last == RecordingDebugSteppingFilterResolution( - adapterID: "java", - filters: override - )) - #expect(feature.javaSteppingFilters == normalized) - #expect(persistence.filtersByAdapterID["java"] == normalized) - } - - @Test - func javaSteppingFiltersFallBackToDefaultsWhenPersistenceCannotBeRead() { - let defaults = DebugSteppingFilters( - classNameFilters: ["$JDK", "org.junit.*"], - skipSynthetics: true, - skipStaticInitializers: true, - skipConstructors: false, - hideFilteredStackFrames: true - ) - let resolver = RecordingDebugSteppingFilterResolver( - defaults: defaults, - normalizedOverride: defaults - ) - let manager = DebugAdapterSessionManager(providers: []) { _, _ in nil } - let feature = GenericDebugFeatureModel( - paging: LinkedCoreDebugPaging(), - sessions: manager, - steppingFilterResolver: resolver, - steppingFilterPersistence: FailingDebugSteppingFilterPersistence() - ) - - #expect(feature.javaSteppingFilters == defaults) - #expect(feature.errorMessage != nil) - #expect(resolver.requests == [RecordingDebugSteppingFilterResolution( - adapterID: "java", - filters: nil - )]) - } - - @Test - func javaLaunchAppliesResolvedSteppingFilters() throws { - let transport = RecordingTransport() - let core = RecordingDebugProtocolCore() - let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] - ) - let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in - CoreDebugAdapterProtocolSession( - adapterID: "java", - transport: transport, - core: core, - sessionID: "java-stepping-launch", - deadlineScheduler: RecordingDebugDeadlineScheduler() - ) - } - let feature = GenericDebugFeatureModel( - paging: LinkedCoreDebugPaging(), - sessions: manager, - steppingFilterResolver: core - ) - let root = URL(fileURLWithPath: "/tmp/java-stepping-launch", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") - - #expect(feature.start( - fileURL: source, - rootURL: root, - configuration: DebugLaunchConfiguration( - name: "Main", - request: .launch, - arguments: ["mainClass": .string("example.Main")] - ) - )) - defer { feature.stop() } - - #expect(feature.javaSteppingFilters == core.defaultSteppingFilters) - #expect(core.lastLaunchConfiguration?.steppingFilters == core.defaultSteppingFilters) - } - @Test func emptyStateFollowsRetainedContentRatherThanRunningStateOrOutput() { let session = DeferredInspectionDebugSession() let manager = DebugAdapterSessionManager(providers: [ - DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"]) + DebugProviderDescriptor(id: "tool-a", displayName: "Tool A", fileExtensions: ["txt"]) ]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) defer { feature.reset() } let root = URL(fileURLWithPath: "/workspace/debug-empty-state", isDirectory: true) - let source = root.appendingPathComponent("Main.java") + let source = root.appendingPathComponent("Main.txt") let configuration = DebugLaunchConfiguration( - name: "Main", request: .launch, arguments: ["mainClass": .string("Main")] + name: "Main", request: .launch, arguments: ["program": .string("Main")] ) #expect(feature.showsEmptyState) @@ -2330,18 +2090,18 @@ struct DebugModuleTests { func failedSessionCanRetryUsingTheLastLaunchRequest() throws { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-retry", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-retry", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let configuration = DebugLaunchConfiguration( name: "Retry Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) @@ -2359,18 +2119,18 @@ struct DebugModuleTests { func restartFallsBackToRelaunchWhenAdapterDoesNotAdvertiseRestart() throws { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-restart-fallback", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-restart-fallback", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let configuration = DebugLaunchConfiguration( name: "Restart Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) @@ -2389,18 +2149,18 @@ struct DebugModuleTests { func executionControlsIgnoreOverlappingRequestsUntilSessionLeavesPausedState() throws { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-debug-execution-lock", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-debug-execution-lock", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") let configuration = DebugLaunchConfiguration( name: "Execution lock", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) #expect(feature.start(fileURL: source, rootURL: root, configuration: configuration)) @@ -2422,35 +2182,25 @@ struct DebugModuleTests { func filteredStackFramesCollapseByConsecutiveRunsAndRestoreOrder() { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } - let defaults = DebugSteppingFilters( - classNameFilters: ["$JDK"], - skipSynthetics: true, - skipStaticInitializers: true, - skipConstructors: false, - hideFilteredStackFrames: true - ) - let feature = GenericDebugFeatureModel( - paging: LinkedCoreDebugPaging(), - sessions: manager, - steppingFilterResolver: RecordingDebugSteppingFilterResolver( - defaults: defaults, - normalizedOverride: defaults - ) + // The adapter's declared default decides whether filtered frames collapse. + session.declaredBehavior = DebugAdapterDeclaredBehavior( + defaults: .init(stepFilters: .init(hideFilteredStackFrames: true)) ) - let root = URL(fileURLWithPath: "/tmp/java-filtered-stack", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) + let root = URL(fileURLWithPath: "/tmp/tool-a-filtered-stack", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") #expect(feature.start( fileURL: source, rootURL: root, configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } @@ -2466,7 +2216,7 @@ struct DebugModuleTests { ), DebugStackFrame( id: 2, - name: "java.lang.reflect.Method.invoke", + name: "runtime.reflect.Method.invoke", sourceURL: nil, line: 1, column: 1, @@ -2474,7 +2224,7 @@ struct DebugModuleTests { ), DebugStackFrame( id: 3, - name: "org.springframework.cglib.Proxy.invoke", + name: "vendor.proxy.Proxy.invoke", sourceURL: nil, line: 1, column: 1, @@ -2489,7 +2239,7 @@ struct DebugModuleTests { ), DebugStackFrame( id: 5, - name: "jdk.proxy1.$Proxy0.invoke", + name: "runtime.proxy1.$Proxy0.invoke", sourceURL: nil, line: 1, column: 1, @@ -2517,32 +2267,32 @@ struct DebugModuleTests { func stoppedStackPrefersTheFirstSourceBackedUnfilteredFrame() throws { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-preferred-frame", isDirectory: true) - let source = root.appendingPathComponent("src/UserService.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-preferred-frame", isDirectory: true) + let source = root.appendingPathComponent("src/UserService.txt") #expect(feature.start( fileURL: source, rootURL: root, configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } - // Java adapters can report a synthetic method-handle frame above the + // Adapters can report a synthetic runtime frame above the // actual application frame. The initial inspection must land on the // application source while retaining the synthetic frame in the list. feature.selectThread(DebugThread(id: 7, name: "http-worker")) let synthetic = DebugStackFrame( id: 1, - name: "java.lang.invoke.MethodHandle.invokeVirtual", + name: "runtime.invoke.MethodHandle.invokeVirtual", sourceURL: nil, line: 1, column: 1, @@ -2567,21 +2317,21 @@ struct DebugModuleTests { func rapidInspectionSelectionDiscardsOutOfOrderResults() throws { let session = DeferredInspectionDebugSession() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-inspection-selection", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-inspection-selection", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") #expect(feature.start( fileURL: source, rootURL: root, configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } @@ -2698,14 +2448,14 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-running-inspection-reset" + rootPath: "/tmp/tool-a-running-inspection-reset" ) defer { feature.stop() } let thread = DebugThread(id: 7, name: "http-worker") let frame = DebugStackFrame( id: 70, name: "UserController.list()", - sourceURL: URL(fileURLWithPath: "/tmp/java-running-inspection-reset/src/UserController.java"), + sourceURL: URL(fileURLWithPath: "/tmp/tool-a-running-inspection-reset/src/UserController.txt"), line: 23, column: 1 ) @@ -2749,17 +2499,17 @@ struct DebugModuleTests { } @Test - func automaticVariableInspectionRunsAfterFrameResetAndFallsBackToJavaField() { + func automaticVariableInspectionRunsAfterFrameResetAndDropsAFailedExpression() { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-automatic-variable-inspection" + rootPath: "/tmp/tool-a-automatic-variable-inspection" ) defer { feature.stop() } let frame = DebugStackFrame( id: 31, name: "UserController.list()", - sourceURL: URL(fileURLWithPath: "/tmp/java-automatic-variable-inspection/src/UserController.java"), + sourceURL: URL(fileURLWithPath: "/tmp/tool-a-automatic-variable-inspection/src/UserController.txt"), line: 23, column: 1 ) @@ -2770,7 +2520,7 @@ struct DebugModuleTests { } #expect(feature.state == .paused) - #expect(feature.providerID == "java") + #expect(feature.providerID == "tool-a") feature.selectFrame(frame) #expect(requestedFrameID == frame.id) #expect(session.evaluateExpressions == ["service"]) @@ -2778,21 +2528,10 @@ struct DebugModuleTests { guard session.evaluateExpressions.count == 1 else { return } session.completeEvaluation(at: 0, with: .failure(DeferredDebugSessionError.launchFailed)) - #expect(session.evaluateExpressions == ["service", "this.service"]) - - let service = DebugVariable( - id: "service", - name: "this.service", - value: "UserService@72", - type: "UserService", - evaluateName: "this.service", - variablesReference: 72 - ) - guard session.evaluateExpressions.count == 2 else { return } - session.completeEvaluation(at: 1, with: .success(service)) - #expect(feature.automaticVariables.map(\.name) == ["service"]) - #expect(feature.automaticVariables.map(\.value) == ["UserService@72"]) + // A failed expression is not retried under another spelling. + #expect(session.evaluateExpressions == ["service"]) + #expect(feature.automaticVariables.isEmpty) } @Test @@ -2800,7 +2539,7 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-large-variable-pages" + rootPath: "/tmp/tool-a-large-variable-pages" ) defer { feature.stop() } let frame = DebugStackFrame(id: 70, name: "main", sourceURL: nil, line: 12, column: 1) @@ -2862,7 +2601,7 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-named-indexed-pages" + rootPath: "/tmp/tool-a-named-indexed-pages" ) defer { feature.stop() } let frame = DebugStackFrame(id: 71, name: "main", sourceURL: nil, line: 12, column: 1) @@ -2910,7 +2649,7 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-ignored-variable-paging" + rootPath: "/tmp/tool-a-ignored-variable-paging" ) defer { feature.stop() } let frame = DebugStackFrame(id: 72, name: "main", sourceURL: nil, line: 12, column: 1) @@ -2946,7 +2685,7 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-stale-variable-page" + rootPath: "/tmp/tool-a-stale-variable-page" ) defer { feature.stop() } let firstFrame = DebugStackFrame(id: 80, name: "first", sourceURL: nil, line: 12, column: 1) @@ -2995,21 +2734,21 @@ struct DebugModuleTests { ) let session = DeferredInspectionDebugSession(capabilities: capabilities) let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-exception-info", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-exception-info", isDirectory: true) + let source = root.appendingPathComponent("src/Main.txt") #expect(feature.start( fileURL: source, rootURL: root, configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } @@ -3058,7 +2797,7 @@ struct DebugModuleTests { let session = DeferredInspectionDebugSession() let feature = makeDeferredFeature( session: session, - rootPath: "/tmp/java-self-referential-variable" + rootPath: "/tmp/tool-a-self-referential-variable" ) defer { feature.stop() } @@ -3099,22 +2838,22 @@ struct DebugModuleTests { let transport = RecordingTransport() let core = RecordingDebugProtocolCore() let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in CoreDebugAdapterProtocolSession( - adapterID: "java", + adapterID: "tool-a", transport: transport, core: core, - sessionID: "java-breakpoints", + sessionID: "tool-a-breakpoints", deadlineScheduler: RecordingDebugDeadlineScheduler() ) } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) - let root = URL(fileURLWithPath: "/tmp/java-breakpoints", isDirectory: true) - let source = root.appendingPathComponent("Main.java") + let root = URL(fileURLWithPath: "/tmp/tool-a-breakpoints", isDirectory: true) + let source = root.appendingPathComponent("Main.txt") feature.toggleBreakpoint(fileURL: source, line: 12) feature.updateBreakpoint( @@ -3138,7 +2877,7 @@ struct DebugModuleTests { configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) #expect(core.breakpointUpdates.last == [DebugSourceBreakpoint( @@ -3149,7 +2888,7 @@ struct DebugModuleTests { logMessage: "value = {value}" )]) - core.enqueueReceive(sessionID: "java-breakpoints", state: "ready", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "ready", events: [[ "sequence": 2, "type": "capabilities", "capabilities": [ @@ -3216,7 +2955,7 @@ struct DebugModuleTests { hitCondition: "2" ) ]) - core.enqueueReceive(sessionID: "java-breakpoints", state: "ready", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "ready", events: [[ "sequence": 3, "type": "breakpoint", "breakpoint": [ @@ -3228,7 +2967,7 @@ struct DebugModuleTests { transport.emitData(Data("function-breakpoint-response".utf8)) #expect(feature.functionBreakpoints.first?.verified == true) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 4, "type": "stopped", "reason": "breakpoint" @@ -3238,7 +2977,7 @@ struct DebugModuleTests { let staleWatchOperationID = try #require(core.lastInspectionOperationID) feature.updateWatch(try #require(feature.watches.first), expression: "count + 1") let watchOperationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 5, "type": "operationCompleted", "operationId": staleWatchOperationID, @@ -3255,7 +2994,7 @@ struct DebugModuleTests { transport.emitData(Data("stale-watch-response".utf8)) #expect(feature.watches.first?.expression == "count + 1") #expect(feature.watches.first?.value == nil) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 6, "type": "operationCompleted", "operationId": watchOperationID, @@ -3275,7 +3014,7 @@ struct DebugModuleTests { var hoverValue: DebugVariable? feature.evaluateForHover("count") { hoverValue = $0 } let hoverOperationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 7, "type": "operationCompleted", "operationId": hoverOperationID, @@ -3295,7 +3034,7 @@ struct DebugModuleTests { var staleHoverValue: DebugVariable? feature.evaluateForHover("count") { staleHoverValue = $0 } let staleHoverOperationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "running", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "running", events: [[ "sequence": 8, "type": "stateChanged", "state": "running" @@ -3315,7 +3054,7 @@ struct DebugModuleTests { ]]) transport.emitData(Data("stale-hover-response".utf8)) #expect(staleHoverValue == nil) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 10, "type": "stopped", "reason": "breakpoint" @@ -3332,7 +3071,7 @@ struct DebugModuleTests { containerReference: 42 )) let dataOperationID = try #require(core.lastDataBreakpointInfoOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 5, "type": "operationCompleted", "operationId": dataOperationID, @@ -3354,7 +3093,7 @@ struct DebugModuleTests { feature.loadVariables(reference: 100) let rootVariablesOperationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 7, "type": "operationCompleted", "operationId": rootVariablesOperationID, @@ -3372,7 +3111,7 @@ struct DebugModuleTests { let user = try #require(feature.variables.first) feature.toggleVariableExpansion(user) let childVariablesOperationID = try #require(core.lastInspectionOperationID) - core.enqueueReceive(sessionID: "java-breakpoints", state: "paused", events: [[ + core.enqueueReceive(sessionID: "tool-a-breakpoints", state: "paused", events: [[ "sequence": 8, "type": "operationCompleted", "operationId": childVariablesOperationID, @@ -3407,14 +3146,14 @@ struct DebugModuleTests { @Test func projectBreakpointsPersistWithRelativePathsAndRestoreDeterministically() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let persistence = RecordingBreakpointPersistence() - let root = URL(fileURLWithPath: "/tmp/persisted-java-breakpoints", isDirectory: true) - let main = root.appendingPathComponent("src/Main.java") - let service = root.appendingPathComponent("src/Service.java") + let root = URL(fileURLWithPath: "/tmp/persisted-tool-a-breakpoints", isDirectory: true) + let main = root.appendingPathComponent("src/Main.txt") + let service = root.appendingPathComponent("src/Service.txt") let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in nil } let feature = GenericDebugFeatureModel( paging: LinkedCoreDebugPaging(), @@ -3437,9 +3176,9 @@ struct DebugModuleTests { let saved = try #require(persistence.snapshots[root.standardizedFileURL]) #expect(saved.areBreakpointsMuted) - #expect(saved.breakpoints.map(\.relativePath) == ["src/Main.java", "src/Service.java"]) + #expect(saved.breakpoints.map(\.relativePath) == ["src/Main.txt", "src/Service.txt"]) #expect(saved.breakpoints.first == PersistedDebugBreakpoint( - relativePath: "src/Main.java", + relativePath: "src/Main.txt", line: 8, enabled: false, condition: "ready", @@ -3464,9 +3203,9 @@ struct DebugModuleTests { @Test func sourceEditRelocatesPersistsAndResynchronizesBreakpoints() throws { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let session = DeferredInspectionDebugSession() let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } @@ -3474,8 +3213,8 @@ struct DebugModuleTests { let relocator = RecordingBreakpointRelocator(result: [ DebugSourceBreakpoint(line: 3, condition: "ready") ]) - let root = URL(fileURLWithPath: "/tmp/relocated-java-breakpoints", isDirectory: true) - let sourceURL = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/relocated-tool-a-breakpoints", isDirectory: true) + let sourceURL = root.appendingPathComponent("src/Main.txt") let feature = GenericDebugFeatureModel( paging: LinkedCoreDebugPaging(), sessions: manager, @@ -3498,7 +3237,7 @@ struct DebugModuleTests { configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) defer { feature.stop() } @@ -3533,13 +3272,13 @@ struct DebugModuleTests { @Test func inlineEditSkipsRelocationForLineOnlyBreakpoints() { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let relocator = RecordingBreakpointRelocator(result: []) - let root = URL(fileURLWithPath: "/tmp/inline-java-breakpoint-edit", isDirectory: true) - let sourceURL = root.appendingPathComponent("src/Main.java") + let root = URL(fileURLWithPath: "/tmp/inline-tool-a-breakpoint-edit", isDirectory: true) + let sourceURL = root.appendingPathComponent("src/Main.txt") let feature = GenericDebugFeatureModel( paging: LinkedCoreDebugPaging(), sessions: DebugAdapterSessionManager(providers: [descriptor]) { _, _ in nil }, @@ -3566,18 +3305,18 @@ struct DebugModuleTests { @Test func projectBreakpointRestoreRejectsPathsOutsideTheWorkspace() { - let root = URL(fileURLWithPath: "/tmp/safe-java-breakpoints", isDirectory: true) + let root = URL(fileURLWithPath: "/tmp/safe-tool-a-breakpoints", isDirectory: true) let persistence = RecordingBreakpointPersistence() persistence.snapshots[root.standardizedFileURL] = DebugBreakpointSnapshot(breakpoints: [ - PersistedDebugBreakpoint(relativePath: "../Outside.java", line: 4), - PersistedDebugBreakpoint(relativePath: "/tmp/Absolute.java", line: 5), - PersistedDebugBreakpoint(relativePath: "src/Main.java", line: 6) + PersistedDebugBreakpoint(relativePath: "../Outside.txt", line: 4), + PersistedDebugBreakpoint(relativePath: "/tmp/Absolute.txt", line: 5), + PersistedDebugBreakpoint(relativePath: "src/Main.txt", line: 6) ]) let manager = DebugAdapterSessionManager( providers: [DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] )] ) { _, _ in nil } let feature = GenericDebugFeatureModel( @@ -3588,7 +3327,7 @@ struct DebugModuleTests { feature.openWorkspace(at: root) - #expect(feature.breakpoints.map(\.fileURL) == [root.appendingPathComponent("src/Main.java")]) + #expect(feature.breakpoints.map(\.fileURL) == [root.appendingPathComponent("src/Main.txt")]) #expect(feature.breakpoints.map(\.line) == [6]) } @@ -4617,7 +4356,7 @@ struct DebugModuleTests { let frame = DebugStackFrame( id: 70, name: "main", - sourceURL: URL(fileURLWithPath: "\(rootPath)/src/Main.java"), + sourceURL: URL(fileURLWithPath: "\(rootPath)/src/Main.txt"), line: 10, column: 1 ) @@ -4679,7 +4418,7 @@ struct DebugModuleTests { DebugStackFrame( id: 80, name: "main", - sourceURL: URL(fileURLWithPath: "/tmp/debug-step-in-place/src/Main.java"), + sourceURL: URL(fileURLWithPath: "/tmp/debug-step-in-place/src/Main.txt"), line: 11, column: 1 ) @@ -4908,7 +4647,7 @@ struct DebugModuleTests { DebugStackFrame( id: id, name: "main", - sourceURL: URL(fileURLWithPath: "/tmp/debug-step-automatic/src/Main.java"), + sourceURL: URL(fileURLWithPath: "/tmp/debug-step-automatic/src/Main.txt"), line: line, column: 1 ) @@ -5090,21 +4829,21 @@ struct DebugModuleTests { rootPath: String ) -> GenericDebugFeatureModel { let descriptor = DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] + id: "tool-a", + displayName: "Tool A", + fileExtensions: ["txt"] ) let manager = DebugAdapterSessionManager(providers: [descriptor]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) let root = URL(fileURLWithPath: rootPath, isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + let source = root.appendingPathComponent("src/Main.txt") precondition(feature.start( fileURL: source, rootURL: root, configuration: DebugLaunchConfiguration( name: "Main", request: .launch, - arguments: ["mainClass": .string("example.Main")] + arguments: ["program": .string("example.Main")] ) )) return feature @@ -5438,68 +5177,10 @@ private final class RecordingBreakpointRelocator: DebugBreakpointRelocating { } } -private struct RecordingDebugSteppingFilterResolution: Equatable { - let adapterID: String - let filters: DebugSteppingFilters? -} - -@MainActor -private final class RecordingDebugSteppingFilterResolver: DebugSteppingFilterResolving { - let defaults: DebugSteppingFilters - let normalizedOverride: DebugSteppingFilters - private(set) var requests: [RecordingDebugSteppingFilterResolution] = [] - - init(defaults: DebugSteppingFilters, normalizedOverride: DebugSteppingFilters) { - self.defaults = defaults - self.normalizedOverride = normalizedOverride - } - - func resolveDebugSteppingFilters( - adapterID: String, - filters: DebugSteppingFilters? - ) throws -> DebugSteppingFilters { - requests.append(RecordingDebugSteppingFilterResolution( - adapterID: adapterID, - filters: filters - )) - return filters == nil ? defaults : normalizedOverride - } -} - -private final class RecordingDebugSteppingFilterPersistence: - DebugSteppingFilterPersisting, - @unchecked Sendable -{ - var filtersByAdapterID: [String: DebugSteppingFilters] = [:] - - func loadSteppingFilters(adapterID: String) throws -> DebugSteppingFilters? { - filtersByAdapterID[adapterID] - } - - func saveSteppingFilters(_ filters: DebugSteppingFilters, adapterID: String) throws { - filtersByAdapterID[adapterID] = filters - } -} - -private enum DebugSteppingFilterPersistenceTestError: Error { - case unreadable -} - private enum DeferredDebugSessionError: Error { case launchFailed } -private final class FailingDebugSteppingFilterPersistence: - DebugSteppingFilterPersisting, - @unchecked Sendable -{ - func loadSteppingFilters(adapterID _: String) throws -> DebugSteppingFilters? { - throw DebugSteppingFilterPersistenceTestError.unreadable - } - - func saveSteppingFilters(_: DebugSteppingFilters, adapterID _: String) throws {} -} - private struct RecordingDebugInspectionRequest: Equatable { let operationID: String let kind: String @@ -5838,7 +5519,7 @@ private final class RecordingDebugProtocolCore: DebugProtocolCore { private(set) var startDebuggingResults: [(requestID: String, succeeded: Bool)] = [] private(set) var runInTerminalCompletions: [RecordingRunInTerminalCompletion] = [] let defaultSteppingFilters = DebugSteppingFilters( - classNameFilters: ["$JDK", "org.junit.*"], + classNameFilters: ["*.generated.*"], skipSynthetics: true, skipStaticInitializers: true, skipConstructors: false, @@ -6066,7 +5747,7 @@ private final class RecordingDebugProtocolCore: DebugProtocolCore { } func enqueueReceive( - sessionID: String = "java-session", + sessionID: String = "tool-a-session", state: String, events: [[String: Any]] ) { diff --git a/macos/Tests/LitheDebugModuleTests/DebugVariableJSONSnapshotTests.swift b/macos/Tests/LitheDebugModuleTests/DebugVariableJSONSnapshotTests.swift index 0f32efd42d..31855e6f44 100644 --- a/macos/Tests/LitheDebugModuleTests/DebugVariableJSONSnapshotTests.swift +++ b/macos/Tests/LitheDebugModuleTests/DebugVariableJSONSnapshotTests.swift @@ -118,11 +118,11 @@ struct DebugVariableJSONSnapshotTests { @Test func featureSnapshotPreservesTreeStateAndRejectsResumedFrames() async throws { let session = SnapshotSession() session.pages = [100: [variable("request", reference: 1)], 1: [variable("count", "42", "int")]] - let manager = DebugAdapterSessionManager(providers: [DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"])]) { _, _ in session } + let manager = DebugAdapterSessionManager(providers: [DebugProviderDescriptor(id: "tool-a", displayName: "Tool A", fileExtensions: ["txt"])]) { _, _ in session } let feature = GenericDebugFeatureModel(paging: LinkedCoreDebugPaging(), sessions: manager) defer { feature.reset(); session.request = nil; session.pending = nil } let root = URL(fileURLWithPath: "/snapshot-fixture") - #expect(feature.start(fileURL: root.appendingPathComponent("Main.java"), rootURL: root, + #expect(feature.start(fileURL: root.appendingPathComponent("Main.txt"), rootURL: root, configuration: DebugLaunchConfiguration(name: "Snapshot", request: .launch, arguments: [:]))) session.state = .paused session.onStateChange?(.paused) diff --git a/macos/Tests/LitheExecutionModuleTests/BuildSystemServiceTests.swift b/macos/Tests/LitheExecutionModuleTests/BuildSystemServiceTests.swift index ff477ca7cb..35d7681590 100644 --- a/macos/Tests/LitheExecutionModuleTests/BuildSystemServiceTests.swift +++ b/macos/Tests/LitheExecutionModuleTests/BuildSystemServiceTests.swift @@ -8,39 +8,6 @@ import Testing @MainActor struct BuildSystemServiceTests { - @Test - func runGenerationProjectsUseCurrentImportedModelsAndRevokePendingSnapshots() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true; planner.dynamicOptions = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static", model: - #"{"projects":[{"id":"p","path":"app","name":"App","properties":{"run.modelVersion":"1","run.provider":"quarkus.maven","java.minimumVersion":"21","maven.minimumVersion":"3.9.9","maven.wrapper":"mvnw.cmd"}}],"contentRoots":[{"projectID":"p","path":"app/checks","kind":"testSource"},{"projectID":"p","path":"app/resources","kind":"resource"}]}"#)]) - let harness = Harness(planner: planner) - defer { harness.service.stop() } - harness.service.reset(workspaceURL: Self.workspace) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - let ownership = try harness.service.runProjectOwnership() - #expect(ownership == [RunProjectOwnership(path: "app", build: .init(pluginID: "dev.example", buildSystemID: "fixture", root: "app", projectID: "p"), - contentRoots: [.init(path: "app/checks", kind: "testSource")], name: "App", minimumJavaVersion: "21")]) - let project = try #require(ownership.first?.build) - #expect(try harness.service.languageImport(workspaceURL: Self.workspace, project: project) - == harness.service.languageImport(workspaceURL: Self.workspace, root: "app")) - for wrong in [ - RunBuildProjectReference(pluginID: "dev.other", buildSystemID: project.buildSystemID, root: project.root, projectID: project.projectID), - RunBuildProjectReference(pluginID: project.pluginID, buildSystemID: "other", root: project.root, projectID: project.projectID), - RunBuildProjectReference(pluginID: project.pluginID, buildSystemID: project.buildSystemID, root: ".", projectID: project.projectID), - RunBuildProjectReference(pluginID: project.pluginID, buildSystemID: project.buildSystemID, root: project.root, projectID: "other") - ] { - #expect(throws: CancellationError.self) { try harness.service.languageImport(workspaceURL: Self.workspace, project: wrong) } - } - harness.service.setOption(Self.instanceID, optionID: "features", value: .array([.string("next")])) - #expect(throws: (any Error).self) { try harness.service.runProjectOwnership() } - #expect(throws: CancellationError.self) { try harness.service.languageImport(workspaceURL: Self.workspace, project: project) } - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(try harness.service.runProjectOwnership() == ownership) - harness.service.reset(workspaceURL: nil) - #expect(throws: (any Error).self) { try harness.service.runProjectOwnership() } - } - @Test func runGenerationUsesDeclaredTargetsWithoutLanguageImportOrToolProperties() async throws { let planner = FakeBuildPlanner() @@ -54,8 +21,7 @@ struct BuildSystemServiceTests { let harness = Harness(planner: planner, sources: [source]) defer { harness.service.stop() } harness.service.reset(workspaceURL: Self.workspace) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(try harness.service.runProjectOwnership().isEmpty) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) let runs = try harness.service.providerRunConfigurations() #expect(runs.prefix(2).map(\.reference) == [ .init(pluginID: "dev.example", buildSystemID: "fixture", root: "app", run: "custom-serve", projectID: "p", targetID: "http/opaque:1", execution: .service), @@ -78,7 +44,7 @@ struct BuildSystemServiceTests { let harness = Harness(planner: planner, sources: [fixtureSource(providerRuns: runs)]) defer { harness.service.stop() } harness.service.reset(workspaceURL: Self.workspace) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) #expect(harness.service.entries.first?.model?.targets.count == 400) #expect(throws: (any Error).self) { try harness.service.providerRunConfigurations() } } @@ -88,7 +54,6 @@ struct BuildSystemServiceTests { let planner = FakeBuildPlanner() planner.fingerprint = "o" planner.dynamicOptions = true - planner.importEnabled = true planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static", model: #"{"projects":[{"id":"p","path":"app","name":"App"},{"id":"other","path":".","name":"Other"}],"contentRoots":[{"projectID":"p","path":"app/spec","kind":"testSource"},{"projectID":"other","path":"app/spec/deeper","kind":"source"}],"optionValues":{"features":["run-only","changed"]}}"#)]) planner.providerRequest = Self.providerRequest(method: "lithe/build/execute") @@ -103,12 +68,11 @@ struct BuildSystemServiceTests { harness.service.reset(workspaceURL: Self.workspace) try #require(await harness.waitForEntries { !$0.isEmpty }) var error: Error? - var prepared: BuildLanguageImport? let task = Task { defer { finished.open() } // A deeper root published by another project must not turn this // project's test source into a main-source preparation. - do { prepared = try await harness.service.prepareLanguageRun(fileURL: Self.workspace.appendingPathComponent("app/spec/deeper/UnrelatedName.java"), + do { try await harness.service.prepareLanguageRun(fileURL: Self.workspace.appendingPathComponent("app/spec/deeper/UnrelatedName.java"), workspace: Self.workspace, purpose: "run", optionOverrides: ["features": .array([.string("run-only")])], tool: { _ in BuildProviderHints(toolExecutable: URL(fileURLWithPath: "/selected/tool"), toolEnvironment: ["JAVA_HOME": "/selected/jdk"]) }, @@ -131,18 +95,13 @@ struct BuildSystemServiceTests { try #require(await finished.waitUntilOpen()) await task.value #expect((error == nil) == (mode == "success")) - if mode == "success" { - guard case .maven(let context)? = prepared else { Issue.record("Successful preparation must return its exact import"); return } - #expect(context.profiles == ["run-only"]) - #expect(context.mavenExecutablePath == "/selected/tool") - } if ["cancel", "configuration", "workspace"].contains(mode) { #expect(error is CancellationError) } } @Test func languageRunUsesTheModelForItsTemporaryOptionsWithoutPublishingItAsTheDefaultModel() async throws { let planner = FakeBuildPlanner() - planner.fingerprint = "o"; planner.importEnabled = true; planner.dynamicOptions = true + planner.fingerprint = "o"; planner.dynamicOptions = true let baseline = #"{"projects":[{"id":"p","path":"app","name":"App"}],"contentRoots":[{"projectID":"p","path":"app/spec","kind":"source"}],"optionValues":{"features":["run-only"]}}"# planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "provider", model: baseline)]) planner.decodedModel = try JSONDecoder().decode(BuildModel.self, from: Data( @@ -156,7 +115,7 @@ struct BuildSystemServiceTests { harness.service.reset(workspaceURL: Self.workspace) try #require(await harness.waitForEntries { !$0.isEmpty }) let finished = BuildTestGate() - var result: Result? + var result: Result? let task = Task { defer { finished.open() } do { result = .success(try await harness.service.prepareLanguageRun( @@ -168,8 +127,7 @@ struct BuildSystemServiceTests { defer { task.cancel(); harness.service.stop() } try #require(await finished.waitUntilOpen()) await task.value - guard case .maven(let context)? = try #require(result).get() else { Issue.record("Expected the task import"); return } - #expect(context.profiles == ["run-only"]) + try #require(result).get() #expect(planner.taskRequests.last?.task == "prepare.test") #expect(planner.decodedModelOutputs.count == 1) #expect(planner.modelPlanHints.last?.toolExecutable?.path == "/selected/maven") @@ -212,7 +170,7 @@ struct BuildSystemServiceTests { @Test(arguments: ["purpose", "role", "ambiguous", "unknownRoot", "ambiguousRole", "ambiguousProject"]) func languagePreparationRequiresOneExplicitPurposeAndSourceRoleBinding(missing: String) async throws { let planner = FakeBuildPlanner() - planner.fingerprint = "o"; planner.importEnabled = true + planner.fingerprint = "o" let duplicateProject = missing == "ambiguousProject" ? #",{"id":"other","path":"app","name":"Other"}"# : "" let duplicateRoot = missing == "ambiguousRole" ? #",{"projectID":"p","path":"app/spec","kind":"source"}"# : "" let model = """ @@ -319,19 +277,17 @@ struct BuildSystemServiceTests { @Test func nativePreparationIdentityRejectsOptionsChangedAwayAndBackEvenWithoutModelSharing() async throws { let planner = FakeBuildPlanner() - planner.importEnabled = true planner.dynamicOptions = true planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) let harness = Harness(planner: planner) harness.optionsStore.values["fixture"] = ["features": .array([.string("first")])] harness.service.reset(workspaceURL: Self.workspace) - let initial = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) let revision = harness.service.inputRevision harness.service.setOption(Self.instanceID, optionID: "features", value: .array([.string("next")])) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) harness.service.setOption(Self.instanceID, optionID: "features", value: .array([.string("first")])) - let returned = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(returned == initial) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) #expect(harness.service.inputRevision > revision) harness.service.stop() } @@ -339,109 +295,8 @@ struct BuildSystemServiceTests { private static let workspace = URL(fileURLWithPath: "/workspace/demo") @Test - func languageImportUsesEffectiveOptionsAndRefreshesAfterSelection() async throws { + func stoppingServiceFinishesARegisteredDetectionWaiter() async throws { let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.dynamicOptions = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) - let harness = Harness(planner: planner) - defer { harness.service.stop() } - harness.optionsStore.values["fixture"] = ["features": .array([.string("first")])] - harness.service.reset(workspaceURL: Self.workspace) - let first = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(first.mavenContext?.profiles == ["first"]) - - harness.service.setOption(Self.instanceID, optionID: "features", value: .array([.string("next")])) - let next = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(next.mavenContext?.profiles == ["next"]) - #expect(harness.service.languageImport == next) - } - - @Test(arguments: [false, true]) - func runPreparationUsesItsBuildRootAndRefusesPendingOrOldWorkspaceInputs(primary: Bool) async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.dynamicOptions = true - planner.detection = BuildDetection(instances: [ - try Self.nestedInstance(id: "fixture:a", root: "a", features: ["cli"]), - try Self.nestedInstance(id: "fixture:b", root: "b", features: ["gui"]) - ]) - let harness = Harness(planner: planner) - let configuration = RunConfiguration(id: "main", name: "Main", kind: .javaMain, - modulePath: "b", mainClass: "example.Main", mavenReactorPath: "b") - let operations = MavenContextRunOperations(configuration: configuration) - let (runtime, graph) = try await makeBuildSystemTestRuntime(harness.service, runOperations: operations) - defer { graph.stop() } - harness.optionsStore.values["fixture"] = ["features": .array([.string("cli"), .string("gui")])] - harness.service.reset(workspaceURL: Self.workspace) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(harness.service.languageImport?.mavenContext?.reactorPath == "a") - await graph.run.loadProject(at: Self.workspace, files: []) - func launch() { - if primary { graph.run.run(configuration: configuration, currentFileURL: nil) } - else { graph.run.startConfiguration(configuration) } - } - launch() - #expect(operations.callCount == 1) - #expect(operations.context?.reactorPath == "b") - #expect(operations.context?.profiles == ["gui"]) - - // Invalidation is synchronous, before coalesced detection can finish. - // Both Run entry points must report failure without planning old input. - harness.service.setOption("fixture:b", optionID: "features", value: .array([])) - launch() - #expect(operations.callCount == 1) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - launch() - #expect(operations.callCount == 2) - #expect(operations.context?.profiles == []) - - harness.service.reset(workspaceURL: URL(fileURLWithPath: "/workspace/other")) - launch() - #expect(operations.callCount == 2) - harness.service.reset(workspaceURL: Self.workspace) - harness.sources = [] - harness.service.pluginsChanged() - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - launch() - #expect(operations.callCount == 3) - #expect(operations.context == nil) - await runtime.shutdownAll() - } - - @Test - func languageImportWaiterCancellationDoesNotCancelSharedDetection() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) - let gate = GatedBuildDecode() - planner.detectGate = gate - let harness = Harness(planner: planner) - defer { gate.releaseDecode(); harness.service.stop() } - harness.service.reset(workspaceURL: Self.workspace) - try #require(await gate.entered.waitUntilOpen()) - let waiterStarted = BuildTestGate() - let waiterFinished = BuildTestGate() - let cancelled = Task { @MainActor in - waiterStarted.open() - defer { waiterFinished.open() } - // No actor suspension before prepare registers its continuation. - return try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - } - defer { cancelled.cancel() } - try #require(await waiterStarted.waitUntilOpen()) - cancelled.cancel() - try #require(await waiterFinished.waitUntilOpen()) - await #expect(throws: CancellationError.self) { try await cancelled.value } - gate.releaseDecode() - let shared = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(shared.mavenContext?.reactorPath == "app") - } - - @Test - func stoppingServiceFinishesARegisteredLanguageImportWaiter() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) let gate = GatedBuildDecode() planner.detectGate = gate @@ -454,7 +309,7 @@ struct BuildSystemServiceTests { let pending = Task { @MainActor in waiterStarted.open() defer { waiterFinished.open() } - return try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) } defer { pending.cancel() } try #require(await waiterStarted.waitUntilOpen()) @@ -465,93 +320,7 @@ struct BuildSystemServiceTests { await #expect(throws: CancellationError.self) { try await pending.value } gate.releaseDecode() try #require(await gate.finished.waitUntilOpen()) - #expect(harness.service.languageImport == nil) - } - - @Test - func watchedFilesInvalidateLanguageImportBeforeDebouncedDetection() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.dynamicOptions = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) - let debounceStarted = BuildTestGate() - let releaseDebounce = BuildTestGate() - let debounceFinished = BuildTestGate() - let harness = Harness(planner: planner, waitForRedetection: { - debounceStarted.open() - defer { debounceFinished.open() } - guard await releaseDebounce.waitUntilOpen() else { throw GatedDecodeError.releaseTimedOut } - }) - defer { releaseDebounce.open(); harness.service.stop() } - harness.optionsStore.values["fixture"] = ["features": .array([.string("first")])] - harness.service.reset(workspaceURL: Self.workspace) - let first = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(first.mavenContext?.profiles == ["first"]) - - harness.service.workspaceFilesChanged([Self.workspace.appendingPathComponent("build.file")]) - #expect(harness.service.languageImport == nil) - try #require(await debounceStarted.waitUntilOpen()) - harness.optionsStore.values["fixture"] = ["features": .array([.string("next")])] - let waiterStarted = BuildTestGate() - let pending = Task { @MainActor in - waiterStarted.open() - return try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - } - defer { pending.cancel() } - try #require(await waiterStarted.waitUntilOpen()) - #expect(harness.service.languageImport == nil) - - releaseDebounce.open() - let next = try await pending.value - try #require(await debounceFinished.waitUntilOpen()) - #expect(next.mavenContext?.profiles == ["next"]) - #expect(harness.service.languageImport == next) - } - - @Test - func commandModelRecomputesLanguageImportWithItsAcceptedOptions() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.dynamicOptions = true - planner.modelOptionValues = ["features": ["cli"]] - planner.modelOutput = .stdout - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "command")]) - let runner = FakeBuildRunner() - runner.script = .init(chunks: [], result: BuildCommandResult(termination: .exited(0), standardOutput: "MODEL")) - let harness = Harness(planner: planner, runner: runner) - defer { harness.service.stop() } - harness.optionsStore.values["fixture"] = ["features": .array([.string("cli"), .string("removed")])] - harness.service.reset(workspaceURL: Self.workspace) - let initial = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(initial.mavenContext?.profiles == ["cli", "removed"]) - - harness.service.loadModel(Self.instanceID) - try #require(await harness.waitForEntries { $0.first?.modelState == .loaded }) - let loaded = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - - #expect(loaded.mavenContext?.profiles == ["cli"]) - #expect(harness.service.languageImport == loaded) - #expect(runner.requests.count == 1) - } - - @Test - func replacedWorkspaceDoesNotPublishItsPendingLanguageImport() async throws { - let planner = FakeBuildPlanner() - planner.importEnabled = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) - let gate = GatedBuildDecode() - planner.detectGate = gate - let harness = Harness(planner: planner) - defer { gate.releaseDecode(); harness.service.stop() } - var published: [URL] = [] - harness.service.onLanguageImportChanged = { published.append($0) } - harness.service.reset(workspaceURL: Self.workspace) - try #require(await gate.entered.waitUntilOpen()) - harness.service.reset(workspaceURL: nil) - gate.releaseDecode() - try #require(await gate.finished.waitUntilOpen()) - #expect(harness.service.languageImport == nil) - #expect(published.isEmpty) + #expect(harness.service.entries.isEmpty) } @Test @@ -1156,60 +925,6 @@ struct BuildSystemServiceTests { #expect(harness.service.entry("fixture:b")?.options.first?.value == .array([.string("gui")])) } - @Test - func languageImportPublishesTheSameEffectiveOptionsAsBuildPlansAndClearsDisabledPlugins() async throws { - let planner = FakeBuildPlanner() - planner.hasMavenLanguageImport = true - planner.detection = BuildDetection(instances: [try Self.instance(modelSource: "static")]) - planner.optionsResolution = try decode(BuildOptionsResolution.self, """ - {"options": [ - {"id":"profiles", "displayName":"Profiles", "kind":"multiSelect", "value":["dev"], "source":"user"}, - {"id":"settingsFile", "displayName":"Settings", "kind":"file", "value":"/fixture/settings.xml", "source":"user"}, - {"id":"localRepository", "displayName":"Repository", "kind":"directory", "value":"/fixture/repository", "source":"user"} - ], "dropped":["profiles"], "fingerprint":"first"} - """) - let harness = Harness(planner: planner) - defer { harness.service.stop() } - harness.optionsStore.values["fixture"] = [ - "profiles": .array([.string("dev"), .string("removed")]), - "settingsFile": .string("/fixture/settings.xml"), "localRepository": .string("/fixture/repository") - ] - let published = BuildTestGate() - var callbacks = 0 - harness.service.onLanguageImportChanged = { _ in callbacks += 1; published.open() } - harness.service.reset(workspaceURL: Self.workspace) - #expect(await published.waitUntilOpen()) - let context = try #require(harness.service.languageImport?.mavenContext) - #expect(context.profiles == ["dev"]) - #expect(context.settingsPath == "/fixture/settings.xml") - #expect(context.localRepositoryPath == "/fixture/repository") - harness.service.runTask(Self.instanceID, request: BuildTaskRequest(task: "build"), title: "Build") - #expect(await harness.waitForRunState { $0 == .succeeded }) - #expect(planner.languageImportInputs.last == planner.taskPlanContexts.last?.options) - - let changed = BuildTestGate() - harness.service.onLanguageImportChanged = { _ in callbacks += 1; changed.open() } - planner.optionsResolution = try decode(BuildOptionsResolution.self, """ - {"options": [{"id":"profiles", "displayName":"Profiles", "kind":"multiSelect", "value":[], "source":"user"}], - "dropped":[], "fingerprint":"second"} - """) - harness.service.setOption(Self.instanceID, optionID: "profiles", value: .array([])) - #expect(await changed.waitUntilOpen()) - #expect(harness.service.languageImport?.mavenContext?.profiles == []) - #expect(harness.service.languageImport?.mavenContext?.settingsPath == nil) - harness.sources = [] - harness.service.pluginsChanged() - let disabled = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - #expect(disabled == JavaLanguageImportConfiguration()) - #expect(harness.service.languageImport == disabled) - #expect(callbacks == 3) - harness.service.reset(workspaceURL: nil) - #expect(harness.service.languageImport == nil) - await #expect(throws: CancellationError.self) { - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) - } - } - /// Output still draining from a cancelled command must not appear in the /// run that replaced it. @Test @@ -1770,8 +1485,7 @@ struct BuildSystemServiceTests { try #require(await harness.waitForEntries { !$0.isEmpty }) let reference = BuildProviderRunReference(pluginID: "dev.example", buildSystemID: "fixture", root: "app", run: "application", projectID: "p", targetID: "t", userArguments: ["a b"]) - let configuration = RunConfiguration(id: "user:main", name: "Saved Main", kind: .process(provider: "build.provider"), - modulePath: nil, mainClass: nil, buildProvider: reference) + let configuration = RunConfiguration(id: "user:main", name: "Saved Main", kind: .process(provider: "build.provider"), buildProvider: reference) #expect(harness.service.runProviderConfiguration(configuration, workspace: URL(fileURLWithPath: "/other")) == nil) try #require(harness.service.runProviderConfiguration(configuration, workspace: Self.workspace) != nil) try #require(await harness.waitForRunState { $0 == .succeeded }) @@ -3245,7 +2959,7 @@ extension BuildSystemServiceTests { providers: providers, nativeConfigurationFiles: files) defer { harness.service.stop() } harness.service.reset(workspaceURL: Self.workspace) - _ = try await harness.service.prepareLanguageImport(workspaceURL: Self.workspace) + try await harness.service.awaitDetection(workspaceURL: Self.workspace) let snapshot = try await harness.service.readNativeConfiguration(Self.instanceID) harness.service.setOption(Self.instanceID, optionID: "release", value: .bool(true)) harness.service.setOption(Self.instanceID, optionID: "release", value: nil) @@ -3584,7 +3298,6 @@ private final class FakeBuildPlanner: BuildSystemPlanning, @unchecked Sendable { private struct State { var detection = BuildDetection(instances: []) - var importEnabled = false var modelOutput: BuildProcessPlan.Output = .outputFile var providerRequest: BuildProviderRequest? var decodedDependencyOutputs: [BuildCommandOutput] = [] @@ -3605,8 +3318,6 @@ private final class FakeBuildPlanner: BuildSystemPlanning, @unchecked Sendable { var optionsResolution: BuildOptionsResolution? var loadedOptionsResolution: BuildOptionsResolution? var dynamicOptions = false - var hasMavenLanguageImport = false - var languageImportInputs: [[String: ToolingJSONValue]] = [] var modelOptionValues: [String: [String]]? var fingerprint = "initial" var decodedModelOutputs: [BuildCommandOutput] = [] @@ -3626,10 +3337,6 @@ private final class FakeBuildPlanner: BuildSystemPlanning, @unchecked Sendable { get { access { $0.detection } } set { access { $0.detection = newValue } } } - var importEnabled: Bool { - get { access { $0.importEnabled } } - set { access { $0.importEnabled = newValue } } - } var modelOutput: BuildProcessPlan.Output { get { access { $0.modelOutput } } set { access { $0.modelOutput = newValue } } @@ -3665,11 +3372,6 @@ private final class FakeBuildPlanner: BuildSystemPlanning, @unchecked Sendable { get { access { $0.dynamicOptions } } set { access { $0.dynamicOptions = newValue } } } - var hasMavenLanguageImport: Bool { - get { access { $0.hasMavenLanguageImport } } - set { access { $0.hasMavenLanguageImport = newValue } } - } - var languageImportInputs: [[String: ToolingJSONValue]] { access { $0.languageImportInputs } } var modelOptionValues: [String: [String]]? { get { access { $0.modelOptionValues } } @@ -3745,31 +3447,6 @@ private final class FakeBuildPlanner: BuildSystemPlanning, @unchecked Sendable { return detection } - func languageImport( - _ target: BuildSystemTarget, workspaceURL: URL, root: String, - options: [String: ToolingJSONValue], executableURL: URL? - ) throws -> BuildLanguageImport? { - let profilesOptionID: String? = access { - $0.languageImportInputs.append(options) - if $0.importEnabled { return "features" } - return $0.hasMavenLanguageImport ? "profiles" : nil - } - guard let profilesOptionID else { return nil } - func text(_ id: String) -> String? { - guard case .string(let value)? = options[id] else { return nil } - return value - } - let profiles: [String] - if case .array(let values)? = options[profilesOptionID] { - profiles = values.compactMap { if case .string(let value) = $0 { value } else { nil } } - } else { profiles = [] } - return .maven(MavenLaunchContext( - reactorPath: root, profiles: profiles, settingsPath: text("settingsFile"), - localRepositoryPath: text("localRepository"), skipTests: false, - mavenExecutablePath: executableURL?.path, javaHomePath: nil - )) - } - func invocationPlan(_ target: BuildSystemTarget, root: String, settings: [String: ToolingJSONValue]) throws -> BuildInvocation { let configured: String? = if case .string(let path)? = settings["toolPath"] { path } else { nil } return BuildInvocation(executables: [.setting(id: "toolPath", path: configured), .command("fake")]) diff --git a/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift b/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift index 53cbedb730..19e30bd163 100644 --- a/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift +++ b/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift @@ -15,17 +15,14 @@ struct ExecutionModuleTests { providerRuns: [.init(id: "service", displayName: "Service", targetTags: ["service"], debugConfigurationType: "example", execution: .service)])]) let operations = ProviderChoicesRunOperations(withReference: true), gate = ProviderPreparationGate(), process = TestStreamingProcess() let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService(runtime: TestRuntime(), process: process, processFactory: { TestStreamingProcess() }, - fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, + let service = RunService(process: process, processFactory: { TestStreamingProcess() }, + fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) - service.configureBuildLanguageImportProvider { _, _ in .init(mavenContext: .init(reactorPath: ".", profiles: [], settingsPath: nil, skipTests: false, mavenExecutablePath: nil, javaHomePath: nil)) } var current = true - var imports = 0 var cancelled = false var ended: [String] = [] let observation = service.providerDebugEnded.sink { ended.append($0) } - service.configureProviderConfigurationRuns(source: { _, _ in owner }) { inputs, _, _, _, _, _, languageImport in + service.configureProviderConfigurationRuns(source: { _, _ in owner }) { inputs, _, _, _, _, _ in #expect(inputs.launchOptions.debug == .init(adapterID: "dev.adapter/remote", configurationType: "example", port: 51235)) #expect(inputs.launchOptions.arguments == ["a b", "雪"]) gate.entered.continuation.yield(()) @@ -33,16 +30,12 @@ struct ExecutionModuleTests { defer { waiter.cancel() } try await waiter.value cancelled = Task.isCancelled - try await languageImport(.maven(.init(reactorPath: ".", profiles: ["run-only"], settingsPath: nil, skipTests: false, mavenExecutablePath: "/test", javaHomePath: nil))) return try JSONDecoder().decode(BuildRunPreparation.self, from: Data(#"{"executable":{"kind":"toolchain","value":"project-maven"},"arguments":["prepared-debug"],"workingDirectory":".","environment":{}}"#.utf8)) } await service.loadProject(at: root, files: []) let task = Task { try await service.prepareProviderDebug(operations.configurations[0], debug: { type in #expect(type == "example") return .init(adapterID: "dev.adapter/remote", configurationType: type, port: 51235) - }, languageImport: { value in - guard case .maven(let context) = value else { throw CancellationError() } - #expect(context.profiles == ["run-only"]); imports += 1 }, isCurrent: { current }) } let feature = RunFeatureModel(service: service) defer { task.cancel(); gate.release.continuation.yield(()); service.reset(); observation.cancel() } @@ -56,7 +49,7 @@ struct ExecutionModuleTests { gate.release.continuation.yield(()) if outcome == "launch" { let operation = try await task.value - #expect(service.isProviderDebugActive(operation) && imports == 1) + #expect(service.isProviderDebugActive(operation)) #expect(process.startRequests.first?.arguments == ["prepared-debug"]) service.retainProviderConfigurations([]) #expect(!service.isProviderDebugActive(operation) && !process.isRunning) @@ -65,7 +58,7 @@ struct ExecutionModuleTests { } else { do { _ = try await task.value; Issue.record("Stale debug preparation launched") } catch is CancellationError { } - #expect(process.startRequests.isEmpty && !service.isRunning && imports == 0) + #expect(process.startRequests.isEmpty && !service.isRunning) #expect(cancelled == (outcome != "changed")) } } @@ -80,14 +73,12 @@ struct ExecutionModuleTests { let started = AsyncStream.makeStream(bufferingPolicy: .unbounded) let first = ProviderPreparationGate(), second = ProviderPreparationGate(), replacement = ProviderPreparationGate() var calls: [String: Int] = [:] - let service = RunService(runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { + let service = RunService(process: TestStreamingProcess(), processFactory: { let process = TestStreamingProcess(); process.onStart = { started.continuation.yield(()) }; processes.append(process); return process - }, fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, + }, fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset(); first.release.continuation.yield(()); second.release.continuation.yield(()); replacement.release.continuation.yield(()); started.continuation.finish() } - service.configureBuildLanguageImportProvider { _, _ in .init(mavenContext: .init(reactorPath: ".", profiles: [], settingsPath: nil, skipTests: false, mavenExecutablePath: nil, javaHomePath: nil)) } - service.configureProviderConfigurationRuns(source: { inputs, _ in inputs.projectPath == "second" ? secondOwner : firstOwner }) { inputs, _, _, _, current, progress, _ in + service.configureProviderConfigurationRuns(source: { inputs, _ in inputs.projectPath == "second" ? secondOwner : firstOwner }) { inputs, _, _, _, current, progress in let count = calls[inputs.projectPath, default: 0]; calls[inputs.projectPath] = count + 1 let gate = inputs.projectPath == "second" ? second : (count == 0 ? first : replacement) gate.entered.continuation.yield(()) @@ -138,13 +129,12 @@ struct ExecutionModuleTests { let root = URL(fileURLWithPath: "/workspace", isDirectory: true), process = TestStreamingProcess() let started = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) process.onStart = { started.continuation.yield(()) } - let service = RunService(runtime: TestRuntime(), process: process, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(directories: [root]), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + let service = RunService(process: process, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(directories: [root]), + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset(); gate.release.continuation.yield(()); started.continuation.finish() } - service.configureBuildLanguageImportProvider { _, _ in .init(mavenContext: .init(reactorPath: ".", profiles: [], settingsPath: nil, skipTests: false, mavenExecutablePath: nil, javaHomePath: nil)) } - service.configureProviderConfigurationRuns(source: { _, _ in firstOwner }) { inputs, _, _, _, _, _, _ in + service.configureProviderConfigurationRuns(source: { _, _ in firstOwner }) { inputs, _, _, _, _, _ in #expect(inputs.launchOptions.arguments == ["a b", "雪"]) gate.entered.continuation.yield(()) let waiter = Task { try await awaitSignal(gate.release.stream) } @@ -182,38 +172,29 @@ struct ExecutionModuleTests { operations.staleProviderModel = true let primary = TestStreamingProcess() var created = 0 - let service = RunService(runtime: TestRuntime(), process: primary, + let service = RunService(process: primary, processFactory: { created += 1; return TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset() } var pending = false - service.configureBuildProjectOwnership { + service.configureProviderRunConfigurations { if pending { throw CancellationError() } return [] } await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) - let configuration = try #require(service.configurations.first { $0.id == "Custom" }) + #expect(service.configurations.contains { $0.id == "Custom" }) #expect(service.configurationDiagnostics.contains { $0.code == "staleProviderModel" }) - service.run(configuration: configuration, currentFileURL: nil) - #expect(!service.isRunning) - service.startConfiguration(configuration) - #expect(service.moduleSessions.first?.exitCode == 1) - service.runAllServices() - #expect(created == 0) - #expect(throws: (any Error).self) { try service.validateProviderGeneration(for: configuration) } operations.staleProviderModel = false await service.refreshProviderGeneration() #expect(!service.configurationDiagnostics.contains { $0.code == "staleProviderModel" }) pending = true await service.refreshProviderGeneration() #expect(service.configurationDiagnostics.contains { $0.code == "providerModelNotReady" }) - #expect(throws: (any Error).self) { try service.validateProviderGeneration(for: configuration) } pending = false await service.refreshProviderGeneration() #expect(!service.configurationDiagnostics.contains { ["staleProviderModel", "providerModelNotReady"].contains($0.code) }) - try service.validateProviderGeneration(for: configuration) #expect(!operations.providerInspections.isEmpty) #expect(created == 0) } @@ -224,14 +205,14 @@ struct ExecutionModuleTests { let reference = BuildProviderRunReference(pluginID: "dev.example", buildSystemID: "engine", root: ".", run: "serve", projectID: "opaque/project", targetID: "opaque/target", execution: .service) operations.providerConfiguration = RunConfiguration(id: "build.provider:generated", name: "Service", kind: .process(provider: "build.provider"), - execution: .service, modulePath: nil, mainClass: nil, buildProvider: reference) - let service = RunService(runtime: TestRuntime(), process: TestStreamingProcess(), + execution: .service, buildProvider: reference) + let service = RunService(process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset() } - service.configureBuildProjectOwnership { [] } + service.configureProviderRunConfigurations { [] } var runs = [RunProviderConfiguration(projectPath: ".", name: "Service", reference: reference)] service.configureProviderRunConfigurations { runs } await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) @@ -250,12 +231,12 @@ struct ExecutionModuleTests { @Test(arguments: ["task", "workspace", "model", "reset", "new-generation"]) func generationPublicationLeaseIsRevokedBeforeAnObsoleteWorkerCanPublish(change: String) async throws { let operations = FreshnessRecordingRunConfigurationOperations() - let service = RunService(runtime: TestRuntime(), process: TestStreamingProcess(), + let service = RunService(process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) - service.configureBuildProjectOwnership { [] } + service.configureProviderRunConfigurations { [] } service.configureProviderRunConfigurations { [] } let gate = InventoryInspectionGate() defer { service.reset(); gate.release.signal(); gate.entered.continuation.finish() } @@ -284,12 +265,12 @@ struct ExecutionModuleTests { @Test(arguments: ["inputs", "workspace", "reset"]) func lateProviderInspectionCannotReplaceNewerInputWorkspaceOrReset(change: String) async throws { let operations = FreshnessRecordingRunConfigurationOperations() - let service = RunService(runtime: TestRuntime(), process: TestStreamingProcess(), + let service = RunService(process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) - service.configureBuildProjectOwnership { [] } + service.configureProviderRunConfigurations { [] } let gate = InventoryInspectionGate() defer { service.reset(); gate.release.signal(); gate.entered.continuation.finish() } await service.loadProject(at: URL(fileURLWithPath: "/old"), files: []) @@ -312,12 +293,12 @@ struct ExecutionModuleTests { @Test func providerGenerationNotificationsCoalesceBehindOneOwnedInspection() async throws { let operations = FreshnessRecordingRunConfigurationOperations() - let service = RunService(runtime: TestRuntime(), process: TestStreamingProcess(), + let service = RunService(process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, + preferences: TestRunPreferences(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) - service.configureBuildProjectOwnership { [] } + service.configureProviderRunConfigurations { [] } let gate = InventoryInspectionGate() defer { service.reset(); gate.release.signal(); gate.entered.continuation.finish() } await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) @@ -506,10 +487,8 @@ struct ExecutionModuleTests { await graph.projectDevelopment.loadProject(at: root, files: [root.appendingPathComponent("pom.xml")], snapshotID: UUID()) #expect(graph.run.hasReadyInventory(for: root)) #expect(graph.run.sourceSearchRoots == [root, root.appendingPathComponent("apps/service", isDirectory: true)]) - #expect(graph.run.mavenProfiles.map(\.id) == ["ci", "qa"]) models = [] #expect(graph.run.sourceSearchRoots == [root]) - #expect(graph.run.mavenProfiles.isEmpty) await graph.projectDevelopment.loadProject(at: URL(fileURLWithPath: "/other"), files: [], snapshotID: UUID()) #expect(graph.run.sourceSearchRoots.map(\.path) == ["/other"]) } @@ -519,11 +498,9 @@ struct ExecutionModuleTests { let process = TestStreamingProcess() let root = URL(fileURLWithPath: "/workspace", isDirectory: true) let resolver = TestExecutableResolver() - let service = RunService(runtime: TestRuntime(), process: process, processFactory: { TestStreamingProcess() }, + let service = RunService(process: process, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(directories: [root.appendingPathComponent("app", isDirectory: true)]), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: TestRunConfigurationOperations(toolchain: ProjectToolchainSelection(javaHomePath: "/fixture/jdk"), - rejectsResolutionWithoutGeneratedDocument: true), + preferences: TestRunPreferences(), runConfigurationOperations: TestRunConfigurationOperations(rejectsResolutionWithoutGeneratedDocument: true), executableResolver: resolver, languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset() } @@ -538,7 +515,6 @@ struct ExecutionModuleTests { #expect(request.arguments == ["Main", "a b"]) #expect(request.workingDirectory == "/workspace/app") #expect(service.primaryExecutionID == current) - #expect(resolver.lastOptions?.javaHomePath == "/fixture/jdk") #expect(service.lastConfiguration == nil) let received = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) let observation = service.$output.sink { if $0.contains("replacement output") { received.continuation.yield(()) } } @@ -561,10 +537,9 @@ struct ExecutionModuleTests { let process = TestStreamingProcess() process.startFailure = RunFixtureError.failed let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService(runtime: TestRuntime(), process: process, processFactory: { TestStreamingProcess() }, + let service = RunService(process: process, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(directories: invalidDirectory ? [] : [root]), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: TestRunConfigurationOperations(), executableResolver: TestExecutableResolver(), + preferences: TestRunPreferences(), runConfigurationOperations: TestRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset() } let launch = try JSONDecoder().decode(BuildRunPreparation.self, from: Data( @@ -580,11 +555,9 @@ struct ExecutionModuleTests { let process = TestStreamingProcess() let reference = BuildProviderRunReference(pluginID: "dev.example", buildSystemID: "fixture", root: ".", run: "application", projectID: "p", targetID: "t", userArguments: ["a b"]) - let configuration = RunConfiguration(id: "user:provider", name: "Main", kind: .process(provider: "build.provider"), - modulePath: nil, mainClass: nil, buildProvider: reference) - let service = RunService(runtime: TestRuntime(), process: process, processFactory: { TestStreamingProcess() }, - fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: TestRunConfigurationOperations(savedProvider: reference), executableResolver: TestExecutableResolver(), + let configuration = RunConfiguration(id: "user:provider", name: "Main", kind: .process(provider: "build.provider"), buildProvider: reference) + let service = RunService(process: process, processFactory: { TestStreamingProcess() }, + fileAccess: TestRunFileAccess(directories: [root]), preferences: TestRunPreferences(), runConfigurationOperations: TestRunConfigurationOperations(savedProvider: reference), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) defer { service.reset() } let launch = try JSONDecoder().decode(BuildRunPreparation.self, from: Data( @@ -629,202 +602,6 @@ struct ExecutionModuleTests { #expect(service.primaryExecutionID == nil) } - @Test(arguments: ["services/alpha", "services/beta"]) - func moduleRunPassesMavenContextOnlyToItsOwningReactor(reactor: String) async { - let configuration = RunConfiguration( - id: "main", name: "Main", kind: .javaMain, modulePath: ".", mainClass: "example.Main", - mavenReactorPath: reactor) - let operations = MavenContextRunOperations(configuration: configuration) - let graph = makeTestGraph(runOperations: operations) - defer { graph.run.reset() } - let context = MavenLaunchContext(reactorPath: "services/alpha", profiles: ["dev"], - settingsPath: "/fixture/settings.xml", skipTests: true, - mavenExecutablePath: nil, javaHomePath: nil) - graph.run.configureBuildLanguageImportProvider { workspace, requestedRoot in - #expect(workspace.path == "/workspace") - #expect(requestedRoot == reactor) - return .init(mavenContext: context) - } - await graph.run.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) - #expect(graph.run.defaultConfigurationID == configuration.id) - graph.run.startConfiguration(configuration) - #expect(operations.called) - #expect(operations.context == (reactor == context.reactorPath ? context : nil)) - // A failed plan remains in the existing Run output and supports a retry. - #expect(graph.run.moduleSessions.first?.exitCode == 1) - } - - @Test(arguments: ["complete", "reset", "switch", "cancel"]) - func projectLoadAwaitsToolchainProbesWithoutBlockingOrApplyingStaleResults(outcome: String) async throws { - let entered = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - let release = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - let runtime = TestRuntime() - let root = URL(fileURLWithPath: "/workspace") - let other = URL(fileURLWithPath: "/other") - runtime.loadCandidates = { target in - if target == root { - entered.continuation.yield(()) - try await awaitSignal(release.stream) - } - return [] - } - let service = RunService( - runtime: runtime, process: TestStreamingProcess(), - processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: SingleRunConfigurationOperations(configuration: .currentFile, options: RunOptions()), - executableResolver: TestExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - let snapshotID = UUID() - let loading = Task { await service.loadProject(at: root, files: [], snapshotID: snapshotID) } - defer { - loading.cancel() - entered.continuation.finish() - release.continuation.finish() - service.reset() - } - do { - try await awaitSignal(entered.stream) - } catch { - release.continuation.finish() - loading.cancel() - await loading.value - throw error - } - // This actor continues to run while the real load path awaits its port. - #expect(runtime.synchronousToolchainCalls == 0) - #expect(service.isLoadingProject) - #expect(!service.isProjectReady(for: root, snapshotID: snapshotID)) - switch outcome { - case "reset": service.reset() - case "switch": await service.loadProject(at: other, files: []) - case "cancel": loading.cancel() - default: break - } - release.continuation.yield(()) - await loading.value - switch outcome { - case "reset": #expect(service.projectLoadState == .idle && service.configurations == [.currentFile]) - case "switch": #expect(service.projectLoadState == .bound(workspace: other) && !service.isLoadingProject) - case "cancel": #expect(service.defaultConfigurationID == nil) - default: - #expect(service.defaultConfigurationID == RunConfiguration.currentFileID) - #expect(service.isProjectReady(for: root, snapshotID: snapshotID)) - } - #expect(runtime.synchronousToolchainCalls == 0) - } - - @Test - func overlappingProjectLoadsDoNotPersistTheProvisionalCurrentFileSelection() async throws { - let entered = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - let release = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - let runtime = TestRuntime() - var probes = 0 - runtime.loadCandidates = { _ in - probes += 1 - if probes == 1 { - entered.continuation.yield(()) - try await awaitSignal(release.stream) - } - return [] - } - let configuration = RunConfiguration( - id: "main", name: "Main", kind: .javaMain, modulePath: nil, mainClass: "demo.App") - let service = RunService( - runtime: runtime, process: TestStreamingProcess(), - processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: SelectionRunConfigurationOperations(configurations: [configuration]), - executableResolver: TestExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - let root = URL(fileURLWithPath: "/workspace") - let snapshot = UUID() - let loading = Task { await service.loadProject(at: root, files: [], snapshotID: snapshot) } - defer { - loading.cancel() - entered.continuation.finish() - release.continuation.finish() - service.reset() - } - do { - try await awaitSignal(entered.stream) - } catch { - release.continuation.finish() - await loading.value - throw error - } - // An entry point must not consume the inventory before its configuration - // resolves. A concurrent snapshot load must not save the initial placeholder. - #expect(!service.isProjectReady(for: root, snapshotID: snapshot)) - await service.loadProject(at: root, files: [], snapshotID: snapshot) - #expect(service.selectedConfigurationID == configuration.id) - #expect(service.isProjectReady(for: root, snapshotID: snapshot)) - release.continuation.yield(()) - await loading.value - #expect(service.selectedConfigurationID == configuration.id) - // A completed user's explicit Current File choice still survives reload. - service.selectedConfigurationID = RunConfiguration.currentFileID - await service.loadProject(at: root, files: [], snapshotID: snapshot) - #expect(service.selectedConfigurationID == RunConfiguration.currentFileID) - } - - @Test - func configuredServerPortUsesArgumentsEnvironmentResourcesAndFrameworkDefault() async throws { - let root = URL(fileURLWithPath: "/workspace/service-port", isDirectory: true) - let properties = root.appendingPathComponent("src/main/resources/application.properties") - let configuration = RunConfiguration( - id: "spring:api", - name: "API", - kind: .springBoot, - modulePath: ".", - mainClass: "example.Application" - ) - - let argumentService = makeRunService( - configuration: configuration, - options: RunOptions( - vmArguments: "-Dserver.port=18081", - programArguments: "--server.port=18082", - environment: ["SERVER_PORT": "18083"] - ), - fileAccess: TestRunFileAccess(contents: [properties: "server.port=18084"]), - serverPortParser: FixedServerPortParser(port: 18084) - ) - await argumentService.loadProject(at: root, files: [properties]) - #expect(argumentService.configuredServerPort(for: configuration) == 18082) - - let environmentService = makeRunService( - configuration: configuration, - options: RunOptions(environment: ["SERVER_PORT": "18083"]), - fileAccess: TestRunFileAccess(contents: [properties: "server.port=18084"]), - serverPortParser: FixedServerPortParser(port: 18084) - ) - await environmentService.loadProject(at: root, files: [properties]) - #expect(environmentService.configuredServerPort(for: configuration) == 18083) - - let resourceService = makeRunService( - configuration: configuration, - options: RunOptions(), - fileAccess: TestRunFileAccess(contents: [properties: "server.port=18084"]), - serverPortParser: FixedServerPortParser(port: 18084) - ) - await resourceService.loadProject(at: root, files: [properties]) - #expect(resourceService.configuredServerPort(for: configuration) == 18084) - - let defaultService = makeRunService( - configuration: configuration, - options: RunOptions(), - fileAccess: TestRunFileAccess(), - serverPortParser: FixedServerPortParser(port: nil) - ) - await defaultService.loadProject(at: root, files: []) - #expect(defaultService.configuredServerPort(for: configuration) == 8080) - } - @Test func disabledExecutionDoesNotConstructGraph() async throws { let recorder = Recorder() @@ -872,12 +649,10 @@ struct ExecutionModuleTests { func identificationBeforeProjectLoadReportsUnloadedProjectWithoutGenerating() async throws { let operations = RecordingRunConfigurationOperations() let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -892,50 +667,16 @@ struct ExecutionModuleTests { #expect(service.configurationStatus == .missing) } - @Test - func serviceUpdateUsesTheRunningTargetAndDiscardsResultsAfterStop() async throws { - let configuration = RunConfiguration( - id: "service:update", name: "Service", kind: .javaMain, - execution: .service, modulePath: nil, mainClass: "example.Main", sourcePath: "src/Main.java" - ) - let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: SelectionRunConfigurationOperations(configurations: [configuration]), - executableResolver: TestExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) - let target = JavaDebugLaunchTarget(mainClass: "example.Main", projectName: "app", - classPaths: ["/workspace/classes", "/repository/spring-boot-devtools-3.5.0.jar"]) - service.startConfiguration(configuration, javaLaunch: target) - let feature = RunFeatureModel(service: service) - let running = try #require(feature.moduleSessions.first) - #expect(feature.canUpdateService(running)) - await feature.updateService(running) { receivedTarget, source in - #expect(receivedTarget == target) - #expect(source.path == "/workspace/src/Main.java") - feature.stopModule(running) - } - #expect(feature.serviceUpdateMessage == nil) - #expect(feature.updatingServiceExecutionID == nil) - #expect(!feature.canUpdateService(try #require(feature.moduleSessions.first))) - } - @Test func selectingBetweenRunningServicesSynchronizesLogIdentityAndControls() async { - let first = RunConfiguration(id: "service:a", name: "A", kind: .javaMain, - execution: .service, modulePath: nil, mainClass: "demo.A") - let second = RunConfiguration(id: "service:b", name: "B", kind: .javaMain, - execution: .service, modulePath: nil, mainClass: "demo.B") + let first = RunConfiguration(id: "service:a", name: "A", kind: .process(provider: "fixture"), + execution: .service) + let second = RunConfiguration(id: "service:b", name: "B", kind: .process(provider: "fixture"), + execution: .service) let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), + process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: SelectionRunConfigurationOperations(configurations: [first, second]), + preferences: TestRunPreferences(), runConfigurationOperations: SelectionRunConfigurationOperations(configurations: [first, second]), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback) @@ -959,73 +700,15 @@ struct ExecutionModuleTests { #expect(!feature.isSelectedConfigurationRunning) } - /// Issue #507: editing a run document changes no project input, so the - /// service must not re-read every input on the main actor, and the - /// freshness warning the load reported must stay visible. - @Test - func documentEditsKeepFreshnessWithoutRereadingProjectInputs() async { - let operations = FreshnessRecordingRunConfigurationOperations() - let service = makeFreshnessRecordingService(operations) - defer { service.reset() } - await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) - #expect(service.configurationDiagnostics.map(\.code) == ["staleFingerprint"]) - - let created = service.createConfiguration(RunConfigurationDraft( - name: "Custom", kind: .javaMain, modulePath: ".", mainClass: "demo.Custom", scope: .project - )) - - #expect(created) - #expect(operations.fingerprintChecks == [true, false]) - #expect(service.configurationDiagnostics.map(\.code) == ["staleFingerprint"]) - } - - /// A main method added to an existing class is found by comparing JDT's - /// answer with the generated entries, once per distinct message. - @Test - func jdtFreshnessIsReportedOnceWithoutHashingInputs() async { - let operations = FreshnessRecordingRunConfigurationOperations() - operations.inputsChanged = false - let service = makeFreshnessRecordingService(operations) - defer { service.reset() } - await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) - #expect(service.configurationDiagnostics.isEmpty) - - let entrypoints = JavaEntrypoints(entries: []) - await service.reportJavaEntrypointFreshness(entrypoints) - await service.reportJavaEntrypointFreshness(entrypoints) - - #expect(operations.fingerprintChecks == [true, false, false]) - #expect(operations.comparedEntrypoints == [entrypoints, entrypoints]) - #expect(service.configurationDiagnostics.map(\.message) == [ - "Java entry points changed: 1 added, 0 removed", - ]) - } - - private func makeFreshnessRecordingService( - _ operations: FreshnessRecordingRunConfigurationOperations - ) -> RunService { - RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: operations, - executableResolver: TestExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - } - /// Once the project is bound, identification must behave exactly as before. @Test func identificationAfterProjectLoadGeneratesAndClearsTheUnloadedState() async throws { let operations = RecordingRunConfigurationOperations() let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1064,12 +747,10 @@ struct ExecutionModuleTests { func generationScansTheSnapshotInventoryAndNeverAProvisionalOne() async throws { let operations = RecordingRunConfigurationOperations() let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1082,7 +763,7 @@ struct ExecutionModuleTests { await service.loadProject(at: root, files: []) await service.generateRunConfigurations() #expect(service.generationState == .projectNotReady) - #expect(operations.generatedInventories.isEmpty, "a provisional inventory must not be scanned") + #expect(operations.generateCallCount == 0, "a provisional inventory must not be scanned") await service.loadProject( at: root, @@ -1093,8 +774,8 @@ struct ExecutionModuleTests { #expect(service.generationState == .succeeded(entryCount: 1)) #expect( - operations.generatedInventories == [[source]], - "generation must scan exactly the inventory the snapshot reported" + operations.generateCallCount == 1, + "generation must run once the snapshot reported its inventory" ) } @@ -1106,12 +787,10 @@ struct ExecutionModuleTests { func unreadableConfigurationStillAllowsRegeneration() async throws { let operations = FailingInspectionRunConfigurationOperations() let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: operations, executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1134,12 +813,10 @@ struct ExecutionModuleTests { let builtInProcess = TestStreamingProcess() let extensionSession = TestLanguageExecutionSession() let service = RunService( - runtime: TestRuntime(), process: builtInProcess, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestReadyRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1177,12 +854,10 @@ struct ExecutionModuleTests { let builtInProcess = TestStreamingProcess() let extensionSession = TestLanguageExecutionSession() let service = RunService( - runtime: TestRuntime(), process: builtInProcess, processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestGoProjectRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1224,14 +899,12 @@ struct ExecutionModuleTests { @Test func dependencyBrowserRequiresExplicitLanguageRegistration() async throws { let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(contents: [ URL(fileURLWithPath: "/workspace/go.mod"): "module example.dev/api" ]), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestGoProjectRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1280,13 +953,12 @@ struct ExecutionModuleTests { func runConfigurationsDoNotInjectDependencySources(provider: String) async { let configuration = RunConfiguration( id: "run:\(provider)", name: provider, - kind: .process(provider: provider), modulePath: ".", mainClass: nil + kind: .process(provider: provider) ) let service = makeRunService( configuration: configuration, options: RunOptions(), - fileAccess: TestRunFileAccess(), - serverPortParser: FixedServerPortParser(port: nil) + fileAccess: TestRunFileAccess() ) defer { service.reset() } await service.loadProject(at: URL(fileURLWithPath: "/workspace"), files: []) @@ -1311,7 +983,6 @@ struct ExecutionModuleTests { languageServerModuleID: .languageServerExtension("go") ) let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess( @@ -1319,7 +990,6 @@ struct ExecutionModuleTests { directories: [root.appendingPathComponent("vendor", isDirectory: true)] ), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestGoProjectRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1398,12 +1068,10 @@ struct ExecutionModuleTests { let store = TestWorkspaceDependencyStore() let firstService = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(contents: [moduleFile: "module example.dev/api"]), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestGoProjectRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1420,12 +1088,10 @@ struct ExecutionModuleTests { #expect(store.indexes.services["language:go"] != nil) let secondService = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(contents: [moduleFile: "module example.dev/api"]), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: TestGoProjectRunConfigurationOperations(), executableResolver: TestExecutableResolver(), languageProviderCatalog: .compatibilityFallback, @@ -1509,8 +1175,8 @@ struct ExecutionModuleTests { let process = TestStreamingProcess() let service = LanguageTestService(outcomeResolver: LinkedCoreTestRunOutcome(), executableResolver: TestExecutableResolver(), processFactory: { process }) defer { service.reset() } - #expect(service.run(providerID: "java", scope: .workspace, workspaceURL: root, - projectFiles: [root.appendingPathComponent("build.gradle")])) + #expect(service.run(providerID: "go", scope: .workspace, workspaceURL: root, + projectFiles: [root.appendingPathComponent("go.mod")])) let firstID = try #require(service.runID) let firstEvent = try #require(process.onStateChange) firstEvent(ProcessLifecycleEvent(operationID: firstID.uuidString, state: .running, @@ -1542,43 +1208,43 @@ struct ExecutionModuleTests { @Test(arguments: [false, true]) func closingOrClearingResultsKeepsEditorHistoryAndDiscoveredScopes(clearOnly: Bool) async throws { let root = URL(fileURLWithPath: "/workspace/results-lifecycle") - let first = root.appendingPathComponent("src/test/java/demo/FirstTest.java") - let second = root.appendingPathComponent("src/test/java/demo/SecondTest.java") - let files = [root.appendingPathComponent("pom.xml"), first, second, + let first = root.appendingPathComponent("pkg/first_test.go") + let second = root.appendingPathComponent("pkg/second_test.go") + let files = [root.appendingPathComponent("go.mod"), first, second, root.appendingPathComponent("package.json"), root.appendingPathComponent("sample.test.js"), root.appendingPathComponent("pyproject.toml"), root.appendingPathComponent("test_sample.py")] let report = try JSONDecoder().decode(BuildTestResults.self, from: Data(#"{"tests":[{"suite":"demo.FirstTest","case":"check","status":"passed"}],"summary":{"total":1,"passed":1,"failed":0,"errors":0,"skipped":0},"success":true}"#.utf8)) let service = LanguageTestService(outcomeResolver: LinkedCoreTestRunOutcome(), executableResolver: TestExecutableResolver(), processFactory: { TestStreamingProcess() }) func run(_ scope: LanguageTestScope) { - service.runUsingBackend(providerID: "java", scope: scope, workspaceURL: root, label: "Tests") { _, _ in + service.runUsingBackend(providerID: "go", scope: scope, workspaceURL: root, label: "Tests") { _, _ in LanguageTestBackendResult(exitCode: 0, reports: [report]) } } defer { service.reset() } service.discover(workspaceURL: root, files: files) let discovered = service.itemsByProviderID - for provider in ["java", "node", "python"] { + for provider in ["go", "node", "python"] { #expect(discovered[provider]?.contains { $0.kind == .workspace } == true) } run(.testCase(identifier: "demo.FirstTest#check", fileURL: first)) try await awaitTestValue(service.$state, matching: { $0 == .passed }) - let outcomes = service.testOutcomes(for: "java") + let outcomes = service.testOutcomes(for: "go") #expect(service.results?.summary.total == 1) #expect(outcomes.first?.suite == "demo.FirstTest") if clearOnly { service.clearOutput() } else { service.closeRun() } #expect(service.results == nil) - #expect(service.testOutcomes(for: "java") == outcomes, "Editor marker history must outlive the visible result") + #expect(service.testOutcomes(for: "go") == outcomes, "Editor marker history must outlive the visible result") #expect(service.itemsByProviderID == discovered) run(.file(second)) - #expect(service.hasRun(providerID: "java", scope: .file(second))) + #expect(service.hasRun(providerID: "go", scope: .file(second))) run(.workspace) - #expect(service.hasRun(providerID: "java", scope: .workspace)) + #expect(service.hasRun(providerID: "go", scope: .workspace)) } @Test(arguments: [false, true]) func closingTestRunPreservesDiscoveryAndAllowsNewRun(completed: Bool) async throws { let root = URL(fileURLWithPath: "/workspace/test-tab", isDirectory: true) - let files = [root.appendingPathComponent("build.gradle")] + let files = [root.appendingPathComponent("go.mod")] let process = TestStreamingProcess() let service = LanguageTestService( outcomeResolver: LinkedCoreTestRunOutcome(), @@ -1589,14 +1255,14 @@ struct ExecutionModuleTests { service.discover(workspaceURL: root, files: files) let discovered = service.itemsByProviderID #expect(!discovered.isEmpty) - #expect(!service.hasRun(providerID: "java", scope: .workspace)) - #expect(service.run(providerID: "java", scope: .workspace, + #expect(!service.hasRun(providerID: "go", scope: .workspace)) + #expect(service.run(providerID: "go", scope: .workspace, workspaceURL: root, projectFiles: files)) #expect(service.activePlan != nil) #expect(!service.output.isEmpty) - #expect(service.hasRun(providerID: "java", scope: .workspace)) - #expect(!service.hasRun(providerID: "java", scope: .file(files[0]))) - #expect(!service.hasRun(providerID: "go", scope: .workspace)) + #expect(service.hasRun(providerID: "go", scope: .workspace)) + #expect(!service.hasRun(providerID: "go", scope: .file(files[0]))) + #expect(!service.hasRun(providerID: "python", scope: .workspace)) if completed { process.isRunning = false process.onTermination?(0) @@ -1611,155 +1277,36 @@ struct ExecutionModuleTests { #expect(service.results == nil) #expect(service.errorMessage == nil) #expect(!service.canRerun) - #expect(!service.hasRun(providerID: "java", scope: .workspace)) + #expect(!service.hasRun(providerID: "go", scope: .workspace)) #expect(service.itemsByProviderID == discovered) // Closing a result must leave the discovered scopes runnable. - #expect(service.run(providerID: "java", scope: .workspace, + #expect(service.run(providerID: "go", scope: .workspace, workspaceURL: root, projectFiles: files)) #expect(service.activePlan != nil) #expect(service.isRunning) } - @Test - func standaloneJavaCompilesWithJavacBeforeLaunchingByClassName() async throws { - let mainProcess = TestStreamingProcess() - let stepProcesses = StepProcessRecorder() - let outputDirectory = ".lithe/run/classes/java-main-Standalone" - let configuration = RunConfiguration( - id: "java-main:Standalone", name: "Standalone", kind: .javaMain, - execution: .application, modulePath: nil, mainClass: "Standalone" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["Standalone"], - workingDirectory: ".", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-jdk"), - tool: "javac", - arguments: ["-d", outputDirectory, "Standalone.java"] - ) - ], - classpath: [outputDirectory] - ) - let service = RunService( - runtime: TestRuntime(), process: mainProcess, - processFactory: { stepProcesses.make() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: JavacAwareExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - await service.loadProject(at: root, files: []) - - let mainStarted = AsyncStream.makeStream() - mainProcess.onStart = { mainStarted.continuation.yield(()) } - - service.run(configuration: configuration, currentFileURL: nil) - - // The javac compile step runs first; the main process must wait for it. - let step = try #require(stepProcesses.processes.first) - let stepRequest = try #require(step.startRequests.first) - #expect(stepRequest.executablePath == "/test/bin/javac") - #expect(stepRequest.arguments == ["-d", outputDirectory, "Standalone.java"]) - // The application entry bounds its compile step exactly like Windows. - #expect(stepRequest.timeoutMilliseconds == 600_000) - #expect(mainProcess.startRequests.isEmpty) - - // A zero exit chains to the main process, which launches by class name - // with the compile output prepended as `-cp`. - step.onTermination?(0) - try await awaitSignal(mainStarted.stream) - let mainRequest = try #require(mainProcess.startRequests.first) - #expect(mainRequest.executablePath == "/test/bin/java") - #expect(mainRequest.arguments == ["-cp", outputDirectory, "Standalone"]) - #expect(service.isRunning) - } - - @Test - func mavenJavaMainValidatesTheProjectJDKInsteadOfTheMavenJDK() async throws { - let moduleProcess = TestStreamingProcess() - let configuration = RunConfiguration( - id: "java-main:example.Main", name: "Main", kind: .javaMain, - execution: .application, modulePath: "app", mainClass: "example.Main", - mavenReactorPath: "." - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: ".", - classpath: ["/workspace/app/target/classes"] - ) - let service = RunService( - runtime: TestRuntime(javaHome: URL(fileURLWithPath: "/valid/project-jdk")), - process: TestStreamingProcess(), - processFactory: { moduleProcess }, - fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, - plan: plan, - options: RunOptions( - javaHomePath: "/valid/project-jdk", - mavenJavaHomePath: "/invalid/maven-jdk" - ) - ), - executableResolver: TestExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - - await service.loadProject( - at: URL(fileURLWithPath: "/workspace", isDirectory: true), - files: [] - ) - service.startConfiguration(configuration, javaLaunch: JavaDebugLaunchTarget( - mainClass: "example.Main", - projectName: "app", - classPaths: ["/workspace/app/target/classes"] - )) - - #expect(moduleProcess.startRequests.first?.arguments == [ - "-cp", "/workspace/app/target/classes", "example.Main", - ]) - #expect(service.moduleSessions.first?.isRunning == true) - } - @Test func stoppingTheGraphStopsServiceSessions() async throws { let moduleProcess = TestStreamingProcess() let configuration = RunConfiguration( - id: "java-main:example.Main", name: "Main", kind: .javaMain, - execution: .application, modulePath: "app", mainClass: "example.Main", - mavenReactorPath: "." + id: "fixture:main", name: "Main", kind: .process(provider: "fixture"), + execution: .service ) - let runtime = TestRuntime(javaHome: URL(fileURLWithPath: "/valid/project-jdk")) let resolver = TestExecutableResolver() let service = RunService( - runtime: runtime, process: TestStreamingProcess(), processFactory: { moduleProcess }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( configuration: configuration, plan: SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: ".", - classpath: ["/workspace/app/target/classes"] - ), - options: RunOptions(javaHomePath: "/valid/project-jdk") + executable: .toolchain("fixture-runtime"), + arguments: ["serve"], + workingDirectory: "." + ) ), executableResolver: resolver, languageProviderCatalog: .compatibilityFallback, @@ -1781,11 +1328,7 @@ struct ExecutionModuleTests { at: URL(fileURLWithPath: "/workspace", isDirectory: true), files: [] ) - service.startConfiguration(configuration, javaLaunch: JavaDebugLaunchTarget( - mainClass: "example.Main", - projectName: "app", - classPaths: ["/workspace/app/target/classes"] - )) + service.startConfiguration(configuration) // A service session is not the "current run", yet it owns a process // that must keep the module awake and must end with the session. @@ -1801,361 +1344,11 @@ struct ExecutionModuleTests { #expect(!graph.hasActiveExecutionWork) } - @Test - func standaloneJavaMergesCompileOutputIntoUserClasspath() async throws { - let mainProcess = TestStreamingProcess() - let stepProcesses = StepProcessRecorder() - let outputDirectory = ".lithe/run/classes/java-main-Standalone" - let configuration = RunConfiguration( - id: "java-main:Standalone", name: "Standalone", kind: .javaMain, - execution: .application, modulePath: nil, mainClass: "Standalone" - ) - // The user already supplies a `-cp`; a second one would override it, so the - // compiled output must merge into that flag ahead of the user's entry. - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["-cp", "libs/foo.jar", "Standalone"], - workingDirectory: ".", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-jdk"), - tool: "javac", - arguments: ["-d", outputDirectory, "Standalone.java"] - ) - ], - classpath: [outputDirectory] - ) - let service = RunService( - runtime: TestRuntime(), process: mainProcess, - processFactory: { stepProcesses.make() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: JavacAwareExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - await service.loadProject(at: root, files: []) - - let mainStarted = AsyncStream.makeStream() - mainProcess.onStart = { mainStarted.continuation.yield(()) } - - service.run(configuration: configuration, currentFileURL: nil) - let step = try #require(stepProcesses.processes.first) - step.onTermination?(0) - try await awaitSignal(mainStarted.stream) - let mainRequest = try #require(mainProcess.startRequests.first) - #expect( - mainRequest.arguments == ["-cp", "\(outputDirectory):libs/foo.jar", "Standalone"] - ) - } - - @Test - func standaloneJavaCompileFailureAbortsBeforeLaunchingMainProcess() async throws { - let mainProcess = TestStreamingProcess() - let stepProcesses = StepProcessRecorder() - let outputDirectory = ".lithe/run/classes/java-main-Standalone" - let configuration = RunConfiguration( - id: "java-main:Standalone", name: "Standalone", kind: .javaMain, - execution: .application, modulePath: nil, mainClass: "Standalone" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["Standalone"], - workingDirectory: ".", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-jdk"), - tool: "javac", - arguments: ["-d", outputDirectory, "Standalone.java"] - ) - ], - classpath: [outputDirectory] - ) - let service = RunService( - runtime: TestRuntime(), process: mainProcess, - processFactory: { stepProcesses.make() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: JavacAwareExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - await service.loadProject(at: root, files: []) - service.run(configuration: configuration, currentFileURL: nil) - - let step = try #require(stepProcesses.processes.first) - // A non-zero compile exit aborts the run and surfaces the failure; the - // main process never starts. - step.onTermination?(1) - try await awaitTestValue(service.$lastExitCode, matching: { $0 == 1 }) - #expect(mainProcess.startRequests.isEmpty) - #expect(!service.isRunning) - #expect(service.output.contains("Pre-launch step failed (exit code 1)")) - } - - /// Issue #1133: the service entries of the Run panel go through - /// `startModuleSession`, so they must consume the same pre-launch steps the - /// application entry does. A Maven resource step also resolves and runs from - /// its reactor directory when the application cwd is overridden; only then - /// can it find the project wrapper next to the reactor POM. - @Test - func serviceSessionRunsItsPreLaunchStepFromTheReactorBeforeLaunching() async throws { - let recorder = SessionProcessRecorder() - let resourceArguments = [ - "-B", "-ntp", "-f", "/workspace/app/pom.xml", "resources:resources", - ] - let configuration = RunConfiguration( - id: "service:demo", name: "demo", kind: .javaMain, - execution: .service, modulePath: "app", mainClass: "example.Main" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: "custom-run", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-maven"), - arguments: resourceArguments, - workingDirectory: "app" - ) - ], - classpath: ["/workspace/app/target/classes"] - ) - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { recorder.make() }, - // Built the same way `resolvedWorkingDirectory` builds its result, - // so the directory check compares equal directory URLs. - fileAccess: TestRunFileAccess(directories: [ - URL(fileURLWithPath: "app", relativeTo: root).standardizedFileURL, - URL(fileURLWithPath: "custom-run", relativeTo: root).standardizedFileURL, - ]), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: ToolNamedExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - await service.loadProject(at: root, files: []) - - service.startConfiguration(configuration) - - // The resource step starts first, from the reactor directory, and the - // service process must wait for it. - let step = try #require(recorder.processes.first) - let stepRequest = try #require(step.startRequests.first) - #expect(stepRequest.executablePath == "/test/bin/project-maven") - #expect(stepRequest.arguments == resourceArguments) - let stepWorkingDirectory = try #require(stepRequest.workingDirectory) - #expect(stepWorkingDirectory.hasSuffix("/workspace/app")) - // A resource step that never finishes must fail within the same bound - // Windows applies instead of leaving the session running forever. - #expect(stepRequest.timeoutMilliseconds == 600_000) - #expect(recorder.processes.count == 1) - #expect(service.moduleSessions.first?.isRunning == true) - - step.onTermination?(0) - try await awaitSignal(recorder.started.stream) - let launcher = try #require(recorder.processes.dropFirst().first) - let launcherRequest = try #require(launcher.startRequests.first) - #expect(launcherRequest.executablePath == "/test/bin/project-jdk") - #expect( - launcherRequest.arguments == ["-cp", "/workspace/app/target/classes", "example.Main"] - ) - let launcherWorkingDirectory = try #require(launcherRequest.workingDirectory) - #expect(launcherWorkingDirectory.hasSuffix("/workspace/custom-run")) - } - - /// Issue #1133: a failed resource step must fail the service session rather - /// than start the JVM against the resources it failed to update. - @Test - func serviceSessionPreLaunchFailureLeavesTheServiceFailed() async throws { - let recorder = SessionProcessRecorder() - let configuration = RunConfiguration( - id: "service:demo", name: "demo", kind: .javaMain, - execution: .service, modulePath: "app", mainClass: "example.Main" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: "app", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-f", "/workspace/app/pom.xml", "resources:resources"] - ) - ] - ) - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { recorder.make() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: ToolNamedExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - await service.loadProject(at: root, files: []) - - service.startConfiguration(configuration) - let step = try #require(recorder.processes.first) - step.onTermination?(1) - - try await awaitTestValue(service.$moduleSessions, matching: { $0.first?.exitCode == 1 }) - #expect(service.moduleSessions.first?.isRunning == false) - #expect( - service.moduleSessions.first?.output.contains("Pre-launch step failed (exit code 1)") - == true - ) - #expect(recorder.processes.count == 1) - } - - /// Issue #1133: stopping a service while its resource step is still running - /// cancels the step, and a termination report that arrives afterwards must - /// not start the JVM for the stopped session. - @Test - func stoppingAServiceCancelsItsRunningPreLaunchStep() async throws { - let recorder = SessionProcessRecorder() - let configuration = RunConfiguration( - id: "service:demo", name: "demo", kind: .javaMain, - execution: .service, modulePath: "app", mainClass: "example.Main" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: "app", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-f", "/workspace/app/pom.xml", "resources:resources"] - ) - ] - ) - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { recorder.make() }, fileAccess: TestRunFileAccess(), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: ToolNamedExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - await service.loadProject(at: root, files: []) - - service.startConfiguration(configuration) - // Drain the step's own start signal so the later check observes only a - // service launch. - try await awaitSignal(recorder.started.stream) - let step = try #require(recorder.processes.first) - let session = try #require(service.moduleSessions.first) - - service.stopModule(session) - - #expect(!step.isRunning) - #expect(service.moduleSessions.first?.isRunning == false) - // The cancelled session released its operation, so a late termination - // report cannot start the service. The deadline makes a missing launch - // a bounded observation rather than a hang. - step.onTermination?(0) - await #expect(throws: TestObservationError.self) { - try await awaitSignal(recorder.started.stream, timeout: .milliseconds(500)) - } - #expect(recorder.processes.count == 1) - } - - /// Issue #1133 / PR review: the platform deadline must fail the session and - /// name that deadline. Windows reports the same wording, so a stuck Maven - /// resource step ends the same way on both platforms. - @Test - func servicePreLaunchDeadlineFailsTheSessionAndNamesTheDeadline() async throws { - let recorder = SessionProcessRecorder() - let configuration = RunConfiguration( - id: "service:demo", name: "demo", kind: .javaMain, - execution: .service, modulePath: "app", mainClass: "example.Main" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["example.Main"], - workingDirectory: "app", - preLaunchSteps: [ - SharedLaunchPlan.PreLaunchStep( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-f", "/workspace/app/pom.xml", "resources:resources"] - ) - ] - ) - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), - processFactory: { recorder.make() }, - // Built the same way `resolvedWorkingDirectory` builds its result, - // so the reactor directory resolves instead of falling back. - fileAccess: TestRunFileAccess(directories: [ - URL(fileURLWithPath: "app", relativeTo: root).standardizedFileURL, - ]), - preferences: TestRunPreferences(), serverPortParser: TestServerPortParser(), - runConfigurationOperations: FixedLaunchPlanRunConfigurationOperations( - configuration: configuration, plan: plan - ), - executableResolver: ToolNamedExecutableResolver(), - languageProviderCatalog: .compatibilityFallback, - languageRunProviders: .standard(catalog: .compatibilityFallback) - ) - defer { service.reset() } - await service.loadProject(at: root, files: []) - - service.startConfiguration(configuration) - let step = try #require(recorder.processes.first) - let stepRequest = try #require(step.startRequests.first) - #expect(stepRequest.timeoutMilliseconds == 600_000) - - // The platform reports its deadline and then terminates the owned - // process, exactly as `MacStreamingProcess` does on timeout. - step.onStateChange?(ProcessLifecycleEvent( - operationID: stepRequest.operationID, - state: .stopping, - exitCode: nil, - message: "Process timed out" - )) - try await awaitTestValue(service.$moduleSessions, matching: { - $0.first?.output.contains("Pre-launch step timed out after 600 seconds.") == true - }) - - step.onTermination?(15) - try await awaitTestValue(service.$moduleSessions, matching: { $0.first?.exitCode == 15 }) - #expect(service.moduleSessions.first?.isRunning == false) - #expect(recorder.processes.count == 1) - } - @Test(arguments: [LanguageTestRunState.passed, .failed(exitCode: 7), .cancelled]) func processLanguageTestsRemainIndependentFromProviderReports(expectedState: LanguageTestRunState) async throws { - let root = URL(fileURLWithPath: "/workspace/gradle-tests", isDirectory: true) - let source = root.appendingPathComponent( - "src/test/java/com/example/CalculatorTest.java" - ) - let buildFile = root.appendingPathComponent("build.gradle") + let root = URL(fileURLWithPath: "/workspace/go-tests", isDirectory: true) + let source = root.appendingPathComponent("calc/calc_test.go") + let buildFile = root.appendingPathComponent("go.mod") let process = TestStreamingProcess() let service = LanguageTestService( outcomeResolver: LinkedCoreTestRunOutcome(), @@ -2164,13 +1357,13 @@ struct ExecutionModuleTests { ) #expect(service.run( - providerID: "java", + providerID: "go", scope: .file(source), workspaceURL: root, projectFiles: [buildFile, source] )) - #expect(service.activePlan?.frameworkID == "gradle") - #expect(service.activePlan?.launchPlan.arguments.contains("--no-daemon") == true) + #expect(service.activePlan?.frameworkID == "go") + #expect(service.activePlan?.launchPlan.arguments == ["test", "./calc"]) defer { service.reset() } if expectedState == .cancelled { service.stop() } @@ -2202,16 +1395,10 @@ struct ExecutionModuleTests { private struct SelectionRunConfigurationOperations: RunConfigurationOperations { let configurations: [RunConfiguration] - func inspect(at _: URL) -> ProjectRunConfigurationInspection { + func inspect(at _: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection(status: .ready, diagnostics: []) } - func generate( - at _: URL, - files _: [URL], - modulePaths _: [String], - javaEntrypoints _: JavaEntrypoints?, - projectOwnership _: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at _: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: configurations.count) } func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2221,67 +1408,32 @@ private struct SelectionRunConfigurationOperations: RunConfigurationOperations { }, diagnostics: [], defaultConfigurationID: configurations.first?.id ) } - func launchPlan(at _: URL, configurationID: String, currentFile _: String?, classPath _: String?, debugPort _: Int?) throws -> SharedLaunchPlan { - SharedLaunchPlan(executable: .toolchain("java"), arguments: [configurationID], workingDirectory: ".") + func launchPlan(at _: URL, configurationID: String) throws -> SharedLaunchPlan { + SharedLaunchPlan(executable: .toolchain("fixture-runtime"), arguments: [configurationID], workingDirectory: ".") } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} } /// Records how the service inspects: a full check reads every project input, -/// so only project loads may request it (issue #507). +/// so only project loads may request it (issue #507). Provider staleness is +/// compared against the Provider snapshot the service hands over. private final class FreshnessRecordingRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { var inputsChanged = true var staleProviderModel = false var providerInspectionGate: InventoryInspectionGate? - private(set) var providerInspections: [[RunProjectOwnership]] = [] + private(set) var providerInspections: [[RunProviderConfiguration]] = [] + var runInspections: [[RunProviderConfiguration]] { providerInspections } var providerConfiguration: RunConfiguration? - private(set) var runInspections: [[RunProviderConfiguration]] = [] var generationGate: InventoryInspectionGate? private(set) var generationLeases: [RunConfigurationGenerationLease] = [] - func generate(at projectURL: URL, files: [URL], modulePaths: [String], javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]?, providerRuns: [RunProviderConfiguration], - models: [BuildModel], lease: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { - generationLeases.append(lease) - try lease.check() - if let gate = generationGate { - gate.entered.continuation.yield(()) - if gate.release.wait(timeout: .now() + 2) != .success { Issue.record("Generation publication gate expired") } - } - try lease.check() - return try generate(at: projectURL, files: files, modulePaths: modulePaths, javaEntrypoints: javaEntrypoints, projectOwnership: projectOwnership) - } - func inspectProviderGeneration(at projectURL: URL, projectOwnership: [RunProjectOwnership], providerRuns: [RunProviderConfiguration]) -> ProjectRunConfigurationInspection { - runInspections.append(providerRuns) - return inspectProviderGeneration(at: projectURL, projectOwnership: projectOwnership) - } - func inspectProviderGeneration(at _: URL, projectOwnership: [RunProjectOwnership]) -> ProjectRunConfigurationInspection { - providerInspections.append(projectOwnership) - let stale = staleProviderModel - if let gate = providerInspectionGate { - gate.entered.continuation.yield(()) - // The synchronous port runs on RunService's utility queue; the - // test releases it and every assertion path has cleanup/deadline. - if gate.release.wait(timeout: .now() + 2) != .success { Issue.record("Provider inspection gate expired") } - } - return ProjectRunConfigurationInspection(status: .ready, diagnostics: stale - ? [RunConfigurationDiagnostic(configurationID: nil, code: "staleProviderModel", message: "regenerate")] : []) - } private(set) var fingerprintChecks: [Bool] = [] - private(set) var comparedEntrypoints: [JavaEntrypoints] = [] private let custom = RunConfiguration( - id: "Custom", name: "Custom", kind: .javaMain, - execution: .service, modulePath: nil, mainClass: "demo.Custom" + id: "Custom", name: "Custom", kind: .process(provider: "build.provider"), + execution: .service, + buildProvider: BuildProviderRunReference(pluginID: "dev.custom", buildSystemID: "engine", root: ".", + run: "serve", projectID: "custom", targetID: "custom", execution: .service) ) - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - inspect(at: projectURL, checkFingerprint: true, javaEntrypoints: nil) - } - func inspect( - at _: URL, - checkFingerprint: Bool, - javaEntrypoints: JavaEntrypoints? - ) -> ProjectRunConfigurationInspection { + func inspect(at _: URL, checkFingerprint: Bool, providerRuns: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { fingerprintChecks.append(checkFingerprint) var diagnostics: [RunConfigurationDiagnostic] = [] if checkFingerprint && inputsChanged { @@ -2290,23 +1442,29 @@ private final class FreshnessRecordingRunConfigurationOperations: RunConfigurati message: "Project inputs changed: 0 added, 0 removed, 1 modified" )) } - if let javaEntrypoints { - comparedEntrypoints.append(javaEntrypoints) - diagnostics.append(RunConfigurationDiagnostic( - configurationID: nil, code: "staleFingerprint", - message: "Java entry points changed: 1 added, 0 removed" - )) + if let providerRuns { + providerInspections.append(providerRuns) + if let gate = providerInspectionGate { + gate.entered.continuation.yield(()) + // The synchronous port runs on RunService's utility queue; the + // test releases it and every assertion path has cleanup/deadline. + if gate.release.wait(timeout: .now() + 2) != .success { Issue.record("Provider inspection gate expired") } + } + if staleProviderModel { + diagnostics.append(RunConfigurationDiagnostic(configurationID: nil, code: "staleProviderModel", message: "regenerate")) + } } return ProjectRunConfigurationInspection(status: .ready, diagnostics: diagnostics) } - func generate( - at _: URL, - files _: [URL], - modulePaths _: [String], - javaEntrypoints _: JavaEntrypoints?, - projectOwnership _: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - RunConfigurationGenerationResult(entryCount: 1) + func generate(at _: URL, providerRuns _: [RunProviderConfiguration]?, lease: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { + generationLeases.append(lease) + try lease.check() + if let gate = generationGate { + gate.entered.continuation.yield(()) + if gate.release.wait(timeout: .now() + 2) != .success { Issue.record("Generation publication gate expired") } + } + try lease.check() + return RunConfigurationGenerationResult(entryCount: 1) } func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { RunConfigurationResolution( @@ -2317,11 +1475,9 @@ private final class FreshnessRecordingRunConfigurationOperations: RunConfigurati defaultConfigurationID: nil ) } - func launchPlan(at _: URL, configurationID: String, currentFile _: String?, classPath _: String?, debugPort _: Int?) throws -> SharedLaunchPlan { - SharedLaunchPlan(executable: .toolchain("java"), arguments: [configurationID], workingDirectory: ".") + func launchPlan(at _: URL, configurationID: String) throws -> SharedLaunchPlan { + SharedLaunchPlan(executable: .toolchain("fixture-runtime"), arguments: [configurationID], workingDirectory: ".") } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} } /// Returns a fixed launch plan (optionally carrying pre-launch steps and a @@ -2332,16 +1488,10 @@ private struct FixedLaunchPlanRunConfigurationOperations: RunConfigurationOperat let plan: SharedLaunchPlan var options = RunOptions() - func inspect(at _: URL) -> ProjectRunConfigurationInspection { + func inspect(at _: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection(status: .ready, diagnostics: []) } - func generate( - at _: URL, - files _: [URL], - modulePaths _: [String], - javaEntrypoints _: JavaEntrypoints?, - projectOwnership _: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at _: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 1) } func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2353,103 +1503,22 @@ private struct FixedLaunchPlanRunConfigurationOperations: RunConfigurationOperat defaultConfigurationID: configuration.id ) } - func launchPlan(at _: URL, configurationID _: String, currentFile _: String?, classPath _: String?, debugPort _: Int?) throws -> SharedLaunchPlan { + func launchPlan(at _: URL, configurationID _: String) throws -> SharedLaunchPlan { plan } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} -} - -/// Resolves the JDK launcher to `/test/bin/java`, so the shared `resolve(step:)` -/// default can swap the last path component to `/test/bin/javac` for a compile -/// step that names `tool: "javac"`. -@MainActor -private final class JavacAwareExecutableResolver: RunExecutableResolving { - func resolve(_ plan: SharedLaunchPlan, projectURL: URL, options: RunOptions) throws -> ResolvedRunExecutable { - ResolvedRunExecutable( - executableURL: URL(fileURLWithPath: "/test/bin/java"), - environment: [:] - ) - } - func refreshCandidates(projectURL: URL) async {} - func candidates(projectURL: URL) -> [ProjectToolchainCandidate] { [] } -} - -/// Hands out and remembers every process the pre-launch factory creates, so a -/// test can fire each step's termination and assert its start request. -private final class StepProcessRecorder: @unchecked Sendable { - private let lock = NSLock() - private var storage: [TestStreamingProcess] = [] - var processes: [TestStreamingProcess] { - lock.lock(); defer { lock.unlock() } - return storage - } - func make() -> TestStreamingProcess { - let process = TestStreamingProcess() - lock.lock(); storage.append(process); lock.unlock() - return process - } -} - -/// Hands out the processes one module session creates — the pre-launch step and -/// then the service — and yields on every start, so a test can await the exact -/// moment the JVM launches instead of sleeping. -private final class SessionProcessRecorder: @unchecked Sendable { - private let lock = NSLock() - private var storage: [TestStreamingProcess] = [] - let started = AsyncStream.makeStream(bufferingPolicy: .unbounded) - - var processes: [TestStreamingProcess] { - lock.lock(); defer { lock.unlock() } - return storage - } - - func make() -> TestStreamingProcess { - let process = TestStreamingProcess() - let continuation = started.continuation - process.onStart = { continuation.yield(()) } - lock.lock(); storage.append(process); lock.unlock() - return process - } -} - -/// Resolves a toolchain to `/test/bin/`, so a test can tell a -/// session's resource step apart from the service launcher it gates. -@MainActor -private final class ToolNamedExecutableResolver: RunExecutableResolving { - func resolve( - _ plan: SharedLaunchPlan, - projectURL: URL, - options: RunOptions - ) throws -> ResolvedRunExecutable { - let name: String - switch plan.executable { - case .toolchain(let identifier): name = identifier - case .command(let command): name = command - } - return ResolvedRunExecutable( - executableURL: URL(fileURLWithPath: "/test/bin/" + name), - environment: [:] - ) - } - func refreshCandidates(projectURL: URL) async {} - func candidates(projectURL: URL) -> [ProjectToolchainCandidate] { [] } } @MainActor private func makeRunService( configuration: RunConfiguration, options: RunOptions, - fileAccess: TestRunFileAccess, - serverPortParser: FixedServerPortParser + fileAccess: TestRunFileAccess ) -> RunService { RunService( - runtime: TestRuntime(), process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: fileAccess, preferences: TestRunPreferences(), - serverPortParser: serverPortParser, runConfigurationOperations: SingleRunConfigurationOperations( configuration: configuration, options: options @@ -2489,15 +1558,12 @@ private func makeTestGraph( runOperations: any RunConfigurationOperations = TestRunConfigurationOperations(), buildSystems: BuildSystemService? = nil ) -> ExecutionFeatureGraph { - let runtime = TestRuntime() let resolver = TestExecutableResolver() let run = RunService( - runtime: runtime, process: TestStreamingProcess(), processFactory: { TestStreamingProcess() }, fileAccess: TestRunFileAccess(), preferences: TestRunPreferences(), - serverPortParser: TestServerPortParser(), runConfigurationOperations: runOperations, executableResolver: resolver, languageProviderCatalog: .compatibilityFallback, @@ -2563,34 +1629,6 @@ private func awaitSignal(_ stream: AsyncStream, timeout: Duration = .secon if !received { throw TestObservationError.deadlineExceeded } } -@MainActor -private final class TestRuntime: RunRuntimePort { - var synchronousToolchainCalls = 0 - var loadCandidates: (@MainActor (URL?) async throws -> [ProjectToolchainCandidate])? - func loadRunConfigurationToolchainCandidates( - projectRoot: URL?, - javaHomeOverride: String?, mavenExecutableOverride: String? - ) async throws -> [ProjectToolchainCandidate] { - try await loadCandidates?(projectRoot) ?? [] - } - private let javaHome: URL? - private let mavenJavaHome: URL? - - init(javaHome: URL? = nil, mavenJavaHome: URL? = nil) { - self.javaHome = javaHome - self.mavenJavaHome = mavenJavaHome - } - - func setActiveServiceJavaHomePath(_ path: String) {} - func javaHomeURL(overridePath: String?) -> URL? { javaHome } - func mavenJavaHomeURL(overridePath: String?) -> URL? { mavenJavaHome } - func runConfigurationToolchainCandidates( - projectRoot: URL?, - javaHomeOverride: String?, - mavenExecutableOverride: String? - ) -> [ProjectToolchainCandidate] { synchronousToolchainCalls += 1; return [] } -} - private final class TestStreamingProcess: StreamingProcess, @unchecked Sendable { var isRunning = false var startFailure: (any Error)? @@ -2662,71 +1700,14 @@ private final class TestRunPreferences: RunPreferenceStore { func setString(_ value: String, forKey key: String) {} } -private struct TestServerPortParser: RunServerPortParsing { - func serverPort(content: String, fileExtension: String) -> Int? { nil } -} - -private struct FixedServerPortParser: RunServerPortParsing { - let port: Int? - func serverPort(content _: String, fileExtension _: String) -> Int? { port } -} - -final class MavenContextRunOperations: RunConfigurationOperations, @unchecked Sendable { - let configuration: RunConfiguration - private let lock = NSLock() - private var recordedContext: MavenLaunchContext? - private var didCall = false - private var recordedCallCount = 0 - var context: MavenLaunchContext? { lock.lock(); defer { lock.unlock() }; return recordedContext } - var called: Bool { lock.lock(); defer { lock.unlock() }; return didCall } - var callCount: Int { lock.lock(); defer { lock.unlock() }; return recordedCallCount } - init(configuration: RunConfiguration) { self.configuration = configuration } - func inspect(at _: URL) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { - RunConfigurationResolution(configurations: [EffectiveRunConfiguration(configuration: configuration, options: RunOptions())], - diagnostics: [], defaultConfigurationID: configuration.id) - } - func generate( - at _: URL, - files _: [URL], - modulePaths _: [String], - javaEntrypoints _: JavaEntrypoints?, - projectOwnership _: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - RunConfigurationGenerationResult(entryCount: 1) - } - func launchPlan(at _: URL, configurationID _: String, currentFile _: String?, classPath _: String?, debugPort _: Int?) throws -> SharedLaunchPlan { - throw RunConfigurationOperationFailure(message: "Expected the context-aware launch boundary") - } - func launchPlan(at _: URL, configurationID _: String, currentFile _: String?, classPath _: String?, debugPort _: Int?, - mavenContext: MavenLaunchContext?) throws -> SharedLaunchPlan { - lock.lock() - recordedContext = mavenContext - didCall = true - recordedCallCount += 1 - lock.unlock() - throw RunConfigurationOperationFailure(message: "Fixture launch failure") - } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} -} - private struct SingleRunConfigurationOperations: RunConfigurationOperations { let configuration: RunConfiguration let options: RunOptions - func inspect(at _: URL) -> ProjectRunConfigurationInspection { + func inspect(at _: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection(status: .ready, diagnostics: []) } - func generate( - at _: URL, - files _: [URL], - modulePaths _: [String], - javaEntrypoints _: JavaEntrypoints?, - projectOwnership _: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at _: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 1) } func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2736,17 +1717,9 @@ private struct SingleRunConfigurationOperations: RunConfigurationOperations { defaultConfigurationID: configuration.id ) } - func launchPlan( - at _: URL, - configurationID _: String, - currentFile _: String?, - classPath _: String?, - debugPort _: Int? - ) throws -> SharedLaunchPlan { + func launchPlan(at _: URL, configurationID _: String) throws -> SharedLaunchPlan { throw RunConfigurationOperationFailure(message: "Not required by the port resolution test") } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} } @MainActor @@ -2768,7 +1741,6 @@ private final class InventoryInspectionGate: Sendable { } private struct TestRunConfigurationOperations: RunConfigurationOperations { - var toolchain = ProjectToolchainSelection() var rejectsResolutionWithoutGeneratedDocument = false var savedProvider: BuildProviderRunReference? = nil func saveBuildProviderConfiguration(_ reference: BuildProviderRunReference, name: String, at projectURL: URL) throws -> String { @@ -2776,64 +1748,46 @@ private struct TestRunConfigurationOperations: RunConfigurationOperations { return "user:provider" } var inspectionGate: InventoryInspectionGate? = nil - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + func inspect(at projectURL: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { if let inspectionGate { inspectionGate.entered.continuation.yield(()) if inspectionGate.release.wait(timeout: .now() + 2) != .success { Issue.record("Run inspection was not released before its deadline") } } - return ProjectRunConfigurationInspection(status: .missing, diagnostics: [], - projectToolchain: toolchain == ProjectToolchainSelection() ? nil : toolchain) - } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + return ProjectRunConfigurationInspection(status: .missing, diagnostics: []) + } + func generate(at projectURL: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 0) } func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { if rejectsResolutionWithoutGeneratedDocument { throw RunFixtureError.failed } if let savedProvider { - let configuration = RunConfiguration(id: "user:provider", name: "Main", kind: .process(provider: "build.provider"), - modulePath: nil, mainClass: nil, buildProvider: savedProvider) + let configuration = RunConfiguration(id: "user:provider", name: "Main", kind: .process(provider: "build.provider"), buildProvider: savedProvider) return RunConfigurationResolution(configurations: [.init(configuration: configuration, options: RunOptions())], diagnostics: [], defaultConfigurationID: nil) } - return RunConfigurationResolution(configurations: [], diagnostics: [], defaultConfigurationID: nil, projectToolchain: toolchain) + return RunConfigurationResolution(configurations: [], diagnostics: [], defaultConfigurationID: nil) } - func launchPlan(at projectURL: URL, configurationID: String, currentFile: String?, classPath: String?, debugPort: Int?) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { throw RunConfigurationOperationFailure(message: "Unavailable in lifecycle test") } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} } /// Records the file inventory each generation attempt was given, so a test can /// prove both that a pending workspace never reaches the store and that a ready /// one is scanned with the complete inventory. private final class RecordingRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { - private(set) var generatedInventories: [[URL]] = [] - - var generateCallCount: Int { generatedInventories.count } + private(set) var generateCallCount = 0 - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + func inspect(at projectURL: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection( - status: generatedInventories.isEmpty ? .missing : .ready, + status: generateCallCount == 0 ? .missing : .ready, diagnostics: [] ) } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - generatedInventories.append(files) + func generate(at projectURL: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { + generateCallCount += 1 return RunConfigurationGenerationResult(entryCount: 1) } func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2846,52 +1800,36 @@ private final class RecordingRunConfigurationOperations: RunConfigurationOperati defaultConfigurationID: RunConfiguration.currentFileID ) } - func launchPlan(at projectURL: URL, configurationID: String, currentFile: String?, classPath: String?, debugPort: Int?) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { throw RunConfigurationOperationFailure(message: "Unavailable in identification test") } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} } /// Reports an unreadable configuration so a test can observe the failed state. private struct FailingInspectionRunConfigurationOperations: RunConfigurationOperations { - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + func inspect(at projectURL: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection( status: .invalid("configurations.json is invalid"), diagnostics: [], recoveryAction: .editConfiguration ) } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at projectURL: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 0) } func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { RunConfigurationResolution(configurations: [], diagnostics: [], defaultConfigurationID: nil) } - func launchPlan(at projectURL: URL, configurationID: String, currentFile: String?, classPath: String?, debugPort: Int?) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { throw RunConfigurationOperationFailure(message: "Unavailable in inspection test") } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} } private struct TestReadyRunConfigurationOperations: RunConfigurationOperations { - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + func inspect(at projectURL: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection(status: .ready, diagnostics: []) } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at projectURL: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 1) } func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2904,11 +1842,9 @@ private struct TestReadyRunConfigurationOperations: RunConfigurationOperations { defaultConfigurationID: RunConfiguration.currentFileID ) } - func launchPlan(at projectURL: URL, configurationID: String, currentFile: String?, classPath: String?, debugPort: Int?) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { throw RunConfigurationOperationFailure(message: "The extension must supply this launch plan") } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} } private struct TestGoProjectRunConfigurationOperations: RunConfigurationOperations { @@ -2916,21 +1852,13 @@ private struct TestGoProjectRunConfigurationOperations: RunConfigurationOperatio id: "go:api", name: "Go API", kind: .process(provider: "go.main"), - execution: .application, - modulePath: "cmd/api", - mainClass: nil + execution: .application ) - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { + func inspect(at projectURL: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { ProjectRunConfigurationInspection(status: .ready, diagnostics: []) } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { + func generate(at projectURL: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { RunConfigurationGenerationResult(entryCount: 1) } func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { @@ -2943,15 +1871,13 @@ private struct TestGoProjectRunConfigurationOperations: RunConfigurationOperatio defaultConfigurationID: configuration.id ) } - func launchPlan(at projectURL: URL, configurationID: String, currentFile: String?, classPath: String?, debugPort: Int?) throws -> SharedLaunchPlan { + func launchPlan(at projectURL: URL, configurationID: String) throws -> SharedLaunchPlan { SharedLaunchPlan( executable: .toolchain("project-go"), arguments: ["run", "./cmd/api"], workingDirectory: "." ) } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} } @MainActor @@ -3044,10 +1970,10 @@ private final class TestLanguageExecutionSession: LanguageExecutionSession { private struct ProviderChoicesRunOperations: RunConfigurationOperations { var withReference = true var configurations: [RunConfiguration] { ["first", "second"].map { id in RunConfiguration(id: id, name: id, - kind: withReference ? .process(provider: "build.provider") : .mavenFramework(.quarkus), execution: .service, modulePath: id, mainClass: nil, mavenReactorPath: withReference ? nil : ".", - buildProvider: withReference ? .init(pluginID: "dev.first", buildSystemID: "maven", root: ".", run: "service", projectID: id, targetID: "service", execution: .service) : nil) } } - func inspect(at _: URL) -> ProjectRunConfigurationInspection { .init(status: .ready, diagnostics: []) } - func generate(at _: URL, files _: [URL], modulePaths _: [String], javaEntrypoints _: JavaEntrypoints?, projectOwnership _: [RunProjectOwnership]?) throws -> RunConfigurationGenerationResult { .init(entryCount: 2) } + kind: .process(provider: "build.provider"), execution: .service, + buildProvider: .init(pluginID: "dev.first", buildSystemID: "maven", root: ".", run: "service", projectID: id, targetID: "service", execution: .service)) } } + func inspect(at _: URL, checkFingerprint _: Bool, providerRuns _: [RunProviderConfiguration]?) -> ProjectRunConfigurationInspection { .init(status: .ready, diagnostics: []) } + func generate(at _: URL, providerRuns _: [RunProviderConfiguration]?, lease _: RunConfigurationGenerationLease) throws -> RunConfigurationGenerationResult { .init(entryCount: 2) } func resolve(at _: URL, toolchainCandidates _: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { .init(configurations: configurations.map { .init(configuration: $0, options: RunOptions()) }, diagnostics: [], defaultConfigurationID: configurations.first?.id) } @@ -3056,12 +1982,10 @@ private struct ProviderChoicesRunOperations: RunConfigurationOperations { launchOptions: .init(execution: .service, arguments: ["a b", "雪"]), reference: withReference ? .init(pluginID: "dev.first", buildSystemID: "maven", root: ".", run: "service", projectID: configurationID, targetID: "service", execution: .service) : nil) } - func launchPlan(at _: URL, configurationID _: String, currentFile _: String?, classPath _: String?, debugPort _: Int?) throws -> SharedLaunchPlan { - Issue.record("Provider-owned Maven service reached the legacy Core goal planner") + func launchPlan(at _: URL, configurationID _: String) throws -> SharedLaunchPlan { + Issue.record("Provider-owned service reached the Core launch planner") throw RunFixtureError.failed } - func createConfiguration(_ draft: RunConfigurationDraft, at _: URL) throws -> String { draft.name } - func migrateLegacySettings(at _: URL, configurationIDs _: [String]) throws {} } @MainActor diff --git a/macos/Tests/LitheGitModuleTests/GitFileContextMenuPlanTests.swift b/macos/Tests/LitheGitModuleTests/GitFileContextMenuPlanTests.swift index 862c851e5a..e066365de9 100644 --- a/macos/Tests/LitheGitModuleTests/GitFileContextMenuPlanTests.swift +++ b/macos/Tests/LitheGitModuleTests/GitFileContextMenuPlanTests.swift @@ -11,7 +11,7 @@ struct GitFileContextMenuPlanTests { ) -> GitChange { GitChange( repositoryRoot: URL(fileURLWithPath: "/repo"), - path: "src/App.java", + path: "src/App.txt", originalPath: nil, indexStatus: indexStatus, workTreeStatus: workTreeStatus, diff --git a/macos/Tests/LitheGitModuleTests/GitModuleTests.swift b/macos/Tests/LitheGitModuleTests/GitModuleTests.swift index adebe63abd..6aebd83e26 100644 --- a/macos/Tests/LitheGitModuleTests/GitModuleTests.swift +++ b/macos/Tests/LitheGitModuleTests/GitModuleTests.swift @@ -993,14 +993,14 @@ struct GitModuleTests { let root = URL(fileURLWithPath: "/workspace") let change = GitChange( repositoryRoot: root, - path: "src/main/App.java", + path: "src/main/App.txt", originalPath: nil, indexStatus: "A", workTreeStatus: " " ) let projection = GitTreeStatusProjection(changes: [change]) - #expect(projection.change(relativePath: "\\src\\main\\App.java") == change) + #expect(projection.change(relativePath: "\\src\\main\\App.txt") == change) #expect(projection.kind(relativePath: "src/mai", isDirectory: true) == nil) } @@ -1147,8 +1147,8 @@ struct GitModuleTests { commit, identity: GitIdentity(name: nil, email: "ada@example.com") )) - #expect(query.matchesPaths(["src/main/java/demo/AuthController.java"])) - #expect(!query.matchesPaths(["src/main/java/demo/HomeController.java"])) + #expect(query.matchesPaths(["src/main/example/demo/AuthController.txt"])) + #expect(!query.matchesPaths(["src/main/example/demo/HomeController.txt"])) #expect(!query.matchesNonDateMetadata( commit, identity: GitIdentity(name: "Grace Hopper", email: "grace@example.com") @@ -1704,7 +1704,7 @@ struct GitModuleTests { func explicitStagingIncludesRemainingEditsWithoutChangingCheckboxSemantics(indexStatus: Character) { let feature = GitFeatureModel(service: GitService(operations: TestGitOperations())) defer { feature.reset() } - let change = GitChange(repositoryRoot: URL(fileURLWithPath: "/workspace"), path: "Main.java", + let change = GitChange(repositoryRoot: URL(fileURLWithPath: "/workspace"), path: "Main.txt", originalPath: nil, indexStatus: indexStatus, workTreeStatus: "M") #expect(feature.beginSetStaging([change], staged: true).isEmpty) #expect(feature.beginSetStaging([change], staged: true, includeWorkingTreeChanges: true) == [change]) @@ -5757,7 +5757,7 @@ struct GitModuleTests { ), GitChange( repositoryRoot: root, - path: "src/UserRepository.java", + path: "src/UserRepository.txt", originalPath: nil, indexStatus: " ", workTreeStatus: "D" @@ -5773,7 +5773,7 @@ struct GitModuleTests { let trackedComparison = GitBranchComparison(reference: reference, files: [ GitBranchComparisonFile(status: "M", path: "README.md"), GitBranchComparisonFile(status: "A", path: "qa-untracked.txt", isUntracked: true), - GitBranchComparisonFile(status: "D", path: "src/UserRepository.java") + GitBranchComparisonFile(status: "D", path: "src/UserRepository.txt") ]) let service = GitService(operations: TestGitOperations( snapshotValue: snapshot, @@ -5785,7 +5785,7 @@ struct GitModuleTests { #expect(comparison.files.map(\.path) == [ "README.md", "qa-untracked.txt", - "src/UserRepository.java" + "src/UserRepository.txt" ]) #expect(comparison.files.count == 3) #expect(comparison.files.first(where: { $0.path == "qa-untracked.txt" })?.isUntracked == true) @@ -5875,7 +5875,7 @@ struct GitModuleTests { ) ]) let payload = GitBranchComparison(reference: source, files: [ - GitBranchComparisonFile(status: "M", path: "src/Tracked.java") + GitBranchComparisonFile(status: "M", path: "src/Tracked.txt") ]) let service = GitService(operations: TestGitOperations( snapshotValue: snapshot, @@ -5884,7 +5884,7 @@ struct GitModuleTests { let comparison = await service.comparison(from: source, to: target, at: root) - #expect(comparison.files.map(\.path) == ["src/Tracked.java"]) + #expect(comparison.files.map(\.path) == ["src/Tracked.txt"]) #expect(comparison.targetReference == target) } diff --git a/macos/Tests/LitheLanguageIntelligenceModuleTests/JavaRunMarkerTests.swift b/macos/Tests/LitheLanguageIntelligenceModuleTests/JavaRunMarkerTests.swift deleted file mode 100644 index 69bea52949..0000000000 --- a/macos/Tests/LitheLanguageIntelligenceModuleTests/JavaRunMarkerTests.swift +++ /dev/null @@ -1,53 +0,0 @@ -import Foundation -import LitheCoreContracts -import Testing - -/// The caret rule behind the editor's Run context menu and keyboard shortcut. -/// It mirrors `frontend/editor/src/run-markers.ts`, which the macOS Monaco -/// host uses for the same decision. -struct JavaRunMarkerTests { - private let markers = [ - JavaRunMarker(line: 2, endLine: 2, kind: .main, label: "App.main()", mainClass: "demo.App"), - JavaRunMarker(line: 5, endLine: 14, kind: .testClass, label: "OrderTest", testClass: "demo.OrderTest"), - JavaRunMarker(line: 7, endLine: 7, kind: .testMethod, label: "OrderTest.creates", testClass: "demo.OrderTest", testMethod: "creates"), - JavaRunMarker(line: 10, endLine: 13, kind: .testClass, label: "Refunds", testClass: "demo.OrderTest$Refunds"), - ] - - @Test - func caretPicksTheInnermostTestDeclaration() { - #expect(JavaRunMarker.forLine(7, in: markers)?.label == "OrderTest.creates") - #expect(JavaRunMarker.forLine(11, in: markers)?.label == "Refunds") - #expect(JavaRunMarker.forLine(14, in: markers)?.label == "OrderTest") - } - - @Test - func caretOutsideTestsFallsBackToTheFilesMain() { - #expect(JavaRunMarker.forLine(0, in: markers)?.label == "App.main()") - #expect(JavaRunMarker.forLine(1, in: []) == nil) - } - - // Debugging re-resolves the Java Test item, whose names carry parameter - // lists (`OrderTest#creates()`); only its JDT id matches reliably. - @Test - func testMethodsRunByMavenSelectorAndDebugByJavaTestItem() { - let method = JavaRunMarker( - line: 7, endLine: 7, kind: .testMethod, label: "OrderTest.creates", - testClass: "demo.OrderTest", testMethod: "creates", testItemId: "app@demo.OrderTest#creates()" - ) - #expect(method.testIdentifier(forDebugging: false) == "demo.OrderTest#creates") - #expect(method.testIdentifier(forDebugging: true) == "app@demo.OrderTest#creates()") - let nested = JavaRunMarker( - line: 10, endLine: 13, kind: .testClass, label: "Refunds", testClass: "demo.OrderTest$Refunds" - ) - #expect(nested.testIdentifier(forDebugging: false) == "demo.OrderTest$Refunds") - #expect(nested.testIdentifier(forDebugging: true) == "demo.OrderTest$Refunds") - #expect(markers[0].testIdentifier(forDebugging: false) == nil) - } - - @Test - func coreMarkerPayloadDecodes() throws { - let data = Data(#"{"line":3,"endLine":3,"kind":"main","label":"App.main()","mainClass":"demo.App","status":"none"}"#.utf8) - let marker = try JSONDecoder().decode(JavaRunMarker.self, from: data) - #expect(marker == JavaRunMarker(line: 3, endLine: 3, kind: .main, label: "App.main()", mainClass: "demo.App")) - } -} diff --git a/macos/Tests/LitheLanguageIntelligenceModuleTests/LanguageIntelligenceModuleTests.swift b/macos/Tests/LitheLanguageIntelligenceModuleTests/LanguageIntelligenceModuleTests.swift index 03c163e24c..35551b5cc1 100644 --- a/macos/Tests/LitheLanguageIntelligenceModuleTests/LanguageIntelligenceModuleTests.swift +++ b/macos/Tests/LitheLanguageIntelligenceModuleTests/LanguageIntelligenceModuleTests.swift @@ -7,47 +7,21 @@ import Testing @MainActor struct LanguageIntelligenceModuleTests { - @Test(arguments: ["file", "method-handler", "missing"]) - func buildTestSelectorsComeFromJdtAndRetainOpaqueFullNames(selection: String) async throws { - let root = URL(fileURLWithPath: "/workspace/semantic-tests") - let source = root.appendingPathComponent("custom-source/Unexpected.java") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: source)) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - let task = Task { try await manager.javaBuildTestSelectors(fileURL: source, - identifier: selection == "file" ? nil : selection, rootURL: root) } - defer { task.cancel(); manager.stopAllLanguageServers() } - try await session.waitUntilStarted() - session.publish(.ready) - let request = try await session.waitForExecuteCommand() - #expect(request.command == "javaTestItems") - #expect(request.arguments == [.string(source.absoluteString)]) - session.completeJavaTestItems(.success(JavaTestItems(items: [ - JavaTestItem(id: "class", label: "Display class", fullName: "example.Actual$Nested", projectName: "module", kind: 0, level: 5, - children: [JavaTestItem(id: "method", label: "Display method", fullName: "example.Actual$Nested#works()", projectName: "module", - kind: 0, level: 6, jdtHandler: "method-handler")]) - ]))) - if selection == "missing" { await #expect(throws: (any Error).self) { try await task.value } } - else { #expect(try await task.value == [selection == "file" ? "example.Actual$Nested" : "example.Actual$Nested#works()"] ) } - } - @Test(arguments: [false, true]) func hostStagesAreTypedOnceAndReadyTerminationRemainLegacyOnly(cancelStartup: Bool) throws { let root = URL(fileURLWithPath: "/workspace/stages") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) + let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("main.go"))) let session = WorkspaceStateLanguageServerSession() let recorder = TypedLogRecorder() var resolutionCount = 0 let manager = LanguageToolingSessionManager(logSink: recorder, resolveLogSubject: { provider in - #expect(provider == "java") + #expect(provider == "go") resolutionCount += 1 - return LogSegment("java") - }, runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)], - workspaceFingerprintProvider: { _, _ in "stage-fingerprint" }, - workspaceStateCleaner: { _, _, _ in 2 }) + return LogSegment("go") + }, runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) defer { manager.stopAllLanguageServers() } let operation = UUID() - try manager.startLanguageServer(providerID: "java", rootURL: root, operationID: operation) + try manager.startLanguageServer(providerID: "go", rootURL: root, operationID: operation) if cancelStartup { session.publish(.initializing) } else { @@ -57,19 +31,14 @@ struct LanguageIntelligenceModuleTests { session.onLog?(.info, "Language server terminated", nil, nil) #expect(recorder.events.count == count) } - manager.stopLanguageServer(providerID: "java") + manager.stopLanguageServer(providerID: "go") let stages = recorder.events.compactMap { $0 as? LspSessionStageChanged } #expect(stages.compactMap { if case .token(let value)? = $0.fields["stage"] { return value }; return nil } == ["requested", "resolving", "registered", cancelStartup ? "cancelled" : "stopping"]) - #expect(stages.allSatisfy { $0.channel.rawValue == "lsp/java" && $0.operationID == operation.uuidString }) - let cleaned = recorder.events.compactMap { $0 as? LspCacheCleaned } - #expect(cleaned.count == 1) - if case .int(let removed)? = cleaned.first?.fields["removed"] { #expect(removed == 2) } - else { Issue.record("Cache cleanup count is missing") } - #expect(cleaned.first?.operationID == operation.uuidString) + #expect(stages.allSatisfy { $0.channel.rawValue == "lsp/go" && $0.operationID == operation.uuidString }) #expect(!recorder.events.contains { type(of: $0).id == "lsp.session.updated" || type(of: $0).id == "lsp.protocol.initialized" }) #expect(resolutionCount == 1) - let terminal = CoreLogRecord(event: "lsp.session.updated", level: "DEBUG", channel: "lsp/java", - fields: ["server": .string("java"), "state": .string("stopped")]) + let terminal = CoreLogRecord(event: "lsp.session.updated", level: "DEBUG", channel: "lsp/go", + fields: ["server": .string("go"), "state": .string("stopped")]) session.onCoreLog?(terminal) #expect(recorder.coreRecords == [terminal]) } @@ -77,7 +46,7 @@ struct LanguageIntelligenceModuleTests { @Test func subjectResolutionFailureIsCachedAndDoesNotAffectStartup() throws { let root = URL(fileURLWithPath: "/workspace/log-subject-failure") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) + let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("main.go"))) let session = WorkspaceStateLanguageServerSession() let recorder = TypedLogRecorder() var attempts = 0 @@ -86,9 +55,9 @@ struct LanguageIntelligenceModuleTests { throw WorkspaceStateSessionError.unexpectedOperation }, runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) defer { manager.stopAllLanguageServers() } - try manager.startLanguageServer(providerID: "java", rootURL: root) + try manager.startLanguageServer(providerID: "go", rootURL: root) session.onLogIssue?(true, "startup", "requestCancelled", nil, nil) - manager.stopLanguageServer(providerID: "java") + manager.stopLanguageServer(providerID: "go") #expect(attempts == 1) #expect(recorder.events.isEmpty) #expect(session.startCallCount == 1) @@ -97,15 +66,15 @@ struct LanguageIntelligenceModuleTests { @Test func coreLogCallbackPreservesFieldsWithoutLegacyBuffer() throws { let root = URL(fileURLWithPath: "/workspace/log-buffer") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) + let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("main.go"))) let session = WorkspaceStateLanguageServerSession() let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) defer { manager.stopAllLanguageServers() } var received: [CoreLogRecord] = [] manager.onLogEvent = { received.append($0) } - try manager.startLanguageServer(providerID: "java", rootURL: root) - let record = CoreLogRecord(event: "lsp.stderr.received", level: "WARN", channel: "lsp/java", op: "source-op", - fields: ["server": .string("java"), "diagnostic": .string("upstream line")]) + try manager.startLanguageServer(providerID: "go", rootURL: root) + let record = CoreLogRecord(event: "lsp.stderr.received", level: "WARN", channel: "lsp/go", op: "source-op", + fields: ["server": .string("go"), "diagnostic": .string("upstream line")]) session.onCoreLog?(record) #expect(received == [record]) for index in 0..<105 { session.onLog?(.info, "v1 message", "projectCount=\(index)", nil) } @@ -115,7 +84,7 @@ struct LanguageIntelligenceModuleTests { @Test(arguments: [false, true]) func savesFlushCurrentEditorTextAndPropagateNotificationFailures(fails: Bool) throws { let root = URL(fileURLWithPath: "/workspace/save") - let file = root.appendingPathComponent("Main.java") + let file = root.appendingPathComponent("main.go") let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: file)) let session = WorkspaceStateLanguageServerSession() let manager = LanguageToolingSessionManager(runtimes: [ @@ -125,7 +94,7 @@ struct LanguageIntelligenceModuleTests { // Saving with no active server must not start one. try manager.notifyDocumentSaved(file, text: "saved", currentText: "newer") #expect(session.startCallCount == 0) - try manager.startLanguageServer(providerID: "java", rootURL: root) + try manager.startLanguageServer(providerID: "go", rootURL: root) session.saveError = fails ? WorkspaceStateSessionError.unexpectedOperation : nil if fails { #expect(throws: WorkspaceStateSessionError.unexpectedOperation) { @@ -137,7 +106,7 @@ struct LanguageIntelligenceModuleTests { #expect(session.documentEvents == ["sync:newer", "save:saved"]) } - @Test(arguments: ["Main.java", "main.go", "main.rs"]) + @Test(arguments: ["main.py", "main.go", "main.rs"]) func sessionStartupChecksCurrentPreferenceForEachWorkspace(fileName: String) throws { let root = URL(fileURLWithPath: "/workspace/disabled-lsp", isDirectory: true) let otherRoot = URL(fileURLWithPath: "/workspace/enabled-lsp", isDirectory: true) @@ -177,299 +146,6 @@ struct LanguageIntelligenceModuleTests { #expect(session.startCallCount == 3) } - @Test - func disabledJavaBlocksMavenReloadTestDiscoveryAndDebugStartup() async throws { - let root = URL(fileURLWithPath: "/workspace/java-disabled", isDirectory: true) - let file = root.appendingPathComponent("MainTest.java") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: file)) - let session = WorkspaceStateLanguageServerSession() - var enabled = true - let manager = LanguageToolingSessionManager( - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)], - isLanguageServerEnabled: { _, _ in enabled } - ) - defer { manager.stopAllLanguageServers() } - try manager.startLanguageServer(providerID: "java", rootURL: root) - #expect(session.startCallCount == 1) - - enabled = false - manager.stopLanguageServer(providerID: "java") - // If the guard regresses, fail immediately at the fake start boundary - // instead of suspending forever waiting for a server readiness event. - session.startError = CancellationError() - let error = LanguageToolingSessionError.providerDisabled("Java") - await #expect(throws: error) { - try await manager.reloadJavaWorkspace(rootURL: root) - } - await #expect(throws: error) { - try await manager.discoverJavaTestItems(fileURL: file, rootURL: root) - } - await #expect(throws: error) { - try await manager.startJavaDebugServer(rootURL: root) - } - #expect(session.startCallCount == 1) - #expect(session.executedCommands.isEmpty) - #expect(manager.languageServerOperationIDs.isEmpty) - - enabled = true - session.startError = nil - try manager.startLanguageServer(providerID: "java", rootURL: root) - #expect(session.startCallCount == 2) - } - - @Test(arguments: [false, true]) - func mavenReloadWaitsForJavaImportAndCleansUpCancellation(cancel: Bool) async throws { - let root = URL(fileURLWithPath: "/workspace/java-reload", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - let task = Task { try await manager.reloadJavaWorkspace(rootURL: root) } - defer { task.cancel(); manager.stopLanguageServer(providerID: "java") } - try await session.waitUntilStarted() - #expect(session.executedCommands.isEmpty) - if cancel { - task.cancel() - await #expect(throws: CancellationError.self) { try await task.value } - #expect(!session.isRunning) - #expect(manager.languageServerOperationIDs["java"] == nil) - } else { - session.publish(.ready) - try await task.value - #expect(session.isRunning) - #expect(manager.languageServerStates["java"] == .ready) - } - } - - @Test - func mavenReloadUpdatesARunningJavaSessionInPlace() async throws { - // #970: restarting JDT LS reused its workspace state and skipped every - // project whose pom.xml had not changed, so missing artifacts stayed - // missing. A running session must take a forced update instead. - let root = URL(fileURLWithPath: "/workspace/java-reload-in-place", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - let context = MavenLaunchContext( - reactorPath: ".", profiles: [], settingsPath: "/maven/conf/settings.xml", - localRepositoryPath: "/repository", skipTests: false, - mavenExecutablePath: "/maven/bin/mvn", javaHomePath: nil - ) - manager.configureJavaLanguageImportProvider { _, _ in .init(mavenContext: context) } - defer { manager.stopLanguageServer(providerID: "java") } - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - session.mavenUpdateResult = .success(LanguageServerMavenConfigurationUpdate( - settingsChanged: false, projectsReloaded: true, profilesUpdating: false - )) - - try await manager.reloadJavaWorkspace(rootURL: root) - - #expect(session.startCallCount == 1) - #expect(session.stopCallCount == 0) - #expect(session.mavenUpdates.count == 1) - #expect(session.mavenUpdates.first?.context == context) - #expect(session.mavenUpdates.first?.reloadProjects == true) - } - - @Test - func mavenReloadRestartsASessionThatCannotTakeTheUpdate() async throws { - let root = URL(fileURLWithPath: "/workspace/java-reload-restart", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - manager.configureJavaLanguageImportProvider { _, _ in - .init(mavenContext: MavenLaunchContext( - reactorPath: ".", profiles: [], settingsPath: nil, skipTests: false, - mavenExecutablePath: nil, javaHomePath: nil - )) - } - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - - let task = Task { try await manager.reloadJavaWorkspace(rootURL: root) } - defer { task.cancel(); manager.stopLanguageServer(providerID: "java") } - // The failed update, stop, and restart run synchronously on the main - // actor before the reload suspends for readiness; a bounded number of - // yields lets the task reach that point. - for _ in 0..<100 where session.startCallCount < 2 { await Task.yield() } - try #require(session.startCallCount == 2) - session.publish(.ready) - try await task.value - - #expect(session.mavenUpdates.count == 1) - #expect(session.stopCallCount == 1) - #expect(session.startCallCount == 2) - } - - @Test - func pluginImportReachesJavaStartupAndMavenHotUpdateWithoutLegacyFallback() throws { - let root = URL(fileURLWithPath: "/workspace/import", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - defer { manager.stopAllLanguageServers() } - let first = MavenLaunchContext(reactorPath: ".", profiles: ["first"], settingsPath: "/settings.xml", skipTests: false, mavenExecutablePath: nil, javaHomePath: nil) - let next = MavenLaunchContext(reactorPath: ".", profiles: ["next"], settingsPath: "/settings.xml", skipTests: false, mavenExecutablePath: nil, javaHomePath: nil) - var context = first - let gradle = JavaGradleImportConfiguration(wrapperPresent: true, offline: true, userHome: "/gradle-cache") - manager.configureJavaLanguageImportProvider { _, requestedRoot in - #expect(requestedRoot == root) - return JavaLanguageImportConfiguration(mavenContext: context, javaGradle: gradle) - } - try manager.startLanguageServer(providerID: "java", rootURL: root) - #expect(session.startedMavenContext == first) - #expect(session.startedGradle == gradle) - context = next - session.mavenUpdateResult = .success(.init(settingsChanged: false, projectsReloaded: false, profilesUpdating: true)) - _ = manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) - #expect(session.mavenUpdates.last?.context == next) - #expect(session.startCallCount == 1) - } - - @Test - func removingPluginMavenImportClearsOnlySessionsThatHadMavenInputs() throws { - let root = URL(fileURLWithPath: "/workspace/removed-maven-import", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - defer { manager.stopAllLanguageServers() } - let gradle = JavaGradleImportConfiguration(wrapperPresent: true, offline: false, userHome: nil) - let maven = MavenLaunchContext( - reactorPath: "nested", profiles: ["plugin"], settingsPath: "/settings.xml", - localRepositoryPath: "/repository", skipTests: true, mavenExecutablePath: "/maven/bin/mvn", javaHomePath: "/jdk" - ) - var configuration = JavaLanguageImportConfiguration(javaGradle: gradle) - manager.configureJavaLanguageImportProvider { _, _ in configuration } - try manager.startLanguageServer(providerID: "java", rootURL: root) - #expect(session.startedMavenContext == nil) - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .noSession) - #expect(session.mavenUpdates.isEmpty) - - // A later Maven-enabled start has Core's Maven inputs. Removing its - // plugin must send an empty context, including clearing machine paths. - manager.stopLanguageServer(providerID: "java") - configuration = .init(mavenContext: maven, javaGradle: gradle) - try manager.startLanguageServer(providerID: "java", rootURL: root) - configuration = .init(javaGradle: gradle) - let update = LanguageServerMavenConfigurationUpdate(settingsChanged: true, projectsReloaded: false, profilesUpdating: true) - session.mavenUpdateResult = .success(update) - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .updated(update)) - #expect(session.mavenUpdates.last?.context == MavenLaunchContext( - reactorPath: "nested", profiles: [], settingsPath: nil, localRepositoryPath: nil, - skipTests: false, mavenExecutablePath: nil, javaHomePath: nil - )) - #expect(session.startCallCount == 2) - - // Session ownership ends at stop: reopening as Gradle cannot inherit - // the previous session's eligibility for Maven clear updates. - manager.stopLanguageServer(providerID: "java") - try manager.startLanguageServer(providerID: "java", rootURL: root) - #expect(session.startedMavenContext == nil) - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .noSession) - #expect(session.mavenUpdates.count == 1) - } - - @Test - func pendingPluginImportCannotStartJavaWithLegacyContext() throws { - let root = URL(fileURLWithPath: "/workspace/pending-import", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - defer { manager.stopAllLanguageServers() } - manager.configureJavaLanguageImportProvider { _, _ in throw CancellationError() } - #expect(throws: CancellationError.self) { try manager.startLanguageServer(providerID: "java", rootURL: root) } - #expect(session.startCallCount == 0) - } - - @Test - func failedPluginImportDoesNotPublishEmptySettingsAndCanLaterClearItsInputs() throws { - let root = URL(fileURLWithPath: "/workspace/failed-import", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - defer { manager.stopAllLanguageServers() } - var unavailable = false - var configuration = JavaLanguageImportConfiguration(mavenContext: MavenLaunchContext( - reactorPath: "nested", profiles: ["plugin"], settingsPath: "/plugin/settings.xml", - localRepositoryPath: "/plugin/repository", skipTests: false, - mavenExecutablePath: "/plugin/maven/bin/mvn", javaHomePath: nil - )) - manager.configureJavaLanguageImportProvider { _, _ in - if unavailable { throw CancellationError() } - return configuration - } - try manager.startLanguageServer(providerID: "java", rootURL: root) - unavailable = true - guard case .failed(let failure) = manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) else { - Issue.record("An unavailable current import must fail without sending replacement settings") - return - } - #expect(failure.code == "languageImportUnavailable") - #expect(session.mavenUpdates.isEmpty) - - // A failed read did not revoke the old session's ownership record. - // Once detection confirms removal, clear every old override through the same session. - unavailable = false - configuration = JavaLanguageImportConfiguration() - let update = LanguageServerMavenConfigurationUpdate(settingsChanged: true, projectsReloaded: false, profilesUpdating: false) - session.mavenUpdateResult = .success(update) - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .updated(update)) - #expect(session.mavenUpdates.count == 1) - #expect(session.mavenUpdates.first?.context == MavenLaunchContext( - reactorPath: "nested", profiles: [], settingsPath: nil, localRepositoryPath: nil, - skipTests: false, mavenExecutablePath: nil, javaHomePath: nil - )) - } - - @Test - func mavenSettingsReachOnlyARunningJavaSessionOfTheSameWorkspace() throws { - let root = URL(fileURLWithPath: "/workspace/java-settings", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - manager.configureJavaLanguageImportProvider { _, _ in - .init(mavenContext: MavenLaunchContext( - reactorPath: ".", profiles: [], settingsPath: nil, skipTests: false, - mavenExecutablePath: nil, javaHomePath: nil - )) - } - defer { manager.stopLanguageServer(providerID: "java") } - - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .noSession) - try manager.startLanguageServer(providerID: "java", rootURL: root) - let update = LanguageServerMavenConfigurationUpdate( - settingsChanged: true, projectsReloaded: false, profilesUpdating: false - ) - session.mavenUpdateResult = .success(update) - - #expect(manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) == .updated(update)) - #expect(manager.updateJavaMavenConfiguration( - rootURL: URL(fileURLWithPath: "/workspace/other", isDirectory: true), - reloadProjects: false - ) == .noSession) - #expect(session.mavenUpdates.map(\.reloadProjects) == [false]) - } - @Test func disabledModuleDoesNotConstructFactoryOrServiceGraph() async throws { let recorder = Recorder() @@ -573,6 +249,47 @@ struct LanguageIntelligenceModuleTests { #expect(factory.standardRequests.isEmpty) } + /// A backend's call to its own server (plan API-35) must reach the session + /// the manager holds. The manager stores sessions as `any + /// LanguageServerSession`, so the two methods have to be protocol + /// requirements; an extension-only method is dispatched statically to the + /// default that refuses every call, and the backend sees "not running" + /// from a server that is ready. + @Test + func pluginServerCallsReachTheSessionTheManagerHolds() async throws { + let root = URL(fileURLWithPath: "/workspace/plugin-server", isDirectory: true) + let descriptor = try #require( + LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("main.go")) + ) + let session = WorkspaceStateLanguageServerSession() + let manager = LanguageToolingSessionManager( + catalog: .compatibilityFallback, + runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] + ) + defer { manager.stopAllLanguageServers() } + try manager.startLanguageServer(providerID: "go", rootURL: root) + session.publish(.ready) + + let request = await manager.requestPluginServer( + pluginID: "tool", serverID: "go", method: "workspace/executeCommand", params: .null, timeout: nil + ) + #expect(request == .success(.string("answered"))) + let notification = await manager.notifyPluginServer( + pluginID: "tool", serverID: "go", method: "workspace/didChangeConfiguration", params: .null + ) + #expect(notification == .success(true)) + #expect(session.pluginServerRequests == [.init(pluginID: "tool", serverID: "go", method: "workspace/executeCommand")]) + #expect(session.pluginServerNotifications == [ + .init(pluginID: "tool", serverID: "go", method: "workspace/didChangeConfiguration"), + ]) + + let absent = await manager.requestPluginServer( + pluginID: "tool", serverID: "absent", method: "workspace/executeCommand", params: .null, timeout: nil + ) + #expect(absent == .failure(.languageServerUnavailable)) + #expect(session.pluginServerRequests.count == 1) + } + /// A debugger plugin installed or removed while the app runs changes only /// the catalog's debug capability. The running language server keeps going; /// any other change to the descriptor still stops it. @@ -655,9 +372,9 @@ struct LanguageIntelligenceModuleTests { } @Test - func javaWorkspaceResetUsesTheFingerprintFromTheActiveSession() throws { - let root = URL(fileURLWithPath: "/workspace/java", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") + func workspaceResetStopsTheActiveSessionBeforeResettingItsState() throws { + let root = URL(fileURLWithPath: "/workspace/go", isDirectory: true) + let source = root.appendingPathComponent("src/main.go") let descriptor = try #require( LanguageProviderCatalog.compatibilityFallback.provider(for: source) ) @@ -667,93 +384,32 @@ struct LanguageIntelligenceModuleTests { session: session ) var resetRoot: URL? - var resetFingerprint: String? + var stopCountAtReset: Int? let manager = LanguageToolingSessionManager( catalog: .compatibilityFallback, runtimes: [runtime], - workspaceFingerprintProvider: { _, _ in "active-fingerprint" }, - workspaceStateResetter: { _, rootURL, fingerprint in + workspaceStateResetter: { _, rootURL in resetRoot = rootURL - resetFingerprint = fingerprint + stopCountAtReset = session.stopCallCount } ) try manager.synchronizeLanguageServer( for: source, - text: "class Main {}", + text: "package main", rootURL: root ) - try manager.rebuildWorkspaceState(providerID: "java", rootURL: root) + try manager.rebuildWorkspaceState(providerID: "go", rootURL: root) - #expect(session.startedFingerprint == "active-fingerprint") #expect(session.stopCallCount == 1) + #expect(stopCountAtReset == 1) #expect(resetRoot == root.standardizedFileURL) - #expect(resetFingerprint == "active-fingerprint") - } - - @Test - func mavenResultsResetOnTaskStartAndRejectStoppedSessionCallbacks() throws { - let root = URL(fileURLWithPath: "/workspace/java", isDirectory: true) - let source = root.appendingPathComponent("Main.java") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: source)) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - defer { manager.stopLanguageServer(providerID: "java") } - try manager.synchronizeLanguageServer(for: source, text: "class Main {}", rootURL: root) - let failed = MavenProfileProjectResult(projectURI: URL(string: "file:///common-a")!, status: "failed") - session.onMavenProfileProject?(failed) - #expect(manager.mavenProfileProjectResults.count == 1) - session.onMavenProfileTask?("running") - #expect(manager.mavenProfileProjectResults.isEmpty) - session.onMavenProfileProject?(MavenProfileProjectResult(projectURI: failed.projectURI, status: "running")) - #expect(manager.mavenProfileProjectResults[failed.projectURI]?.status == "running") - let oldCallback = session.onMavenProfileProject - manager.stopLanguageServer(providerID: "java") - oldCallback?(failed) - #expect(manager.mavenProfileProjectResults.isEmpty) - } - - @Test - func javaSessionReceivesTheCurrentMavenContext() throws { - let root = URL(fileURLWithPath: "/workspace/java", isDirectory: true) - let source = root.appendingPathComponent("src/Main.java") - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let context = MavenLaunchContext( - reactorPath: ".", - profiles: ["dev", "enterprise"], - settingsPath: "/local/settings.xml", - skipTests: true, - mavenExecutablePath: "/local/maven/bin/mvn", - javaHomePath: "/local/jdk" - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - manager.configureJavaLanguageImportProvider { requestedDescriptor, requestedRoot in - #expect(requestedDescriptor.id == "java") - #expect(requestedRoot == root.standardizedFileURL) - return .init(mavenContext: context) - } - - try manager.startLanguageServer(providerID: "java", rootURL: root) - - #expect(session.startedMavenContext == context) } @Test func languageServerLifecycleLogsAndCallbacksRetainTheOperationID() throws { - let root = URL(fileURLWithPath: "/workspace/java", isDirectory: true) - let source = root.appendingPathComponent("Main.java") + let root = URL(fileURLWithPath: "/workspace/go", isDirectory: true) + let source = root.appendingPathComponent("main.go") let descriptor = try #require( LanguageProviderCatalog.compatibilityFallback.provider(for: source) ) @@ -768,739 +424,27 @@ struct LanguageIntelligenceModuleTests { let operationID = UUID() var callbacks: [(LanguageServerSessionState, UUID?)] = [] manager.onLanguageServerStateChange = { providerID, state, callbackOperationID in - guard providerID == "java" else { return } + guard providerID == "go" else { return } callbacks.append((state, callbackOperationID)) } try manager.startLanguageServer( - providerID: "java", + providerID: "go", rootURL: root, operationID: operationID ) session.publish(.ready) - manager.stopLanguageServer(providerID: "java") + manager.stopLanguageServer(providerID: "go") #expect(callbacks.contains { $0.0 == .ready && $0.1 == operationID }) #expect(callbacks.contains { $0.0 == .stopped && $0.1 == operationID }) - #expect(manager.languageServerOperationIDs["java"] == nil) - } - - @Test - func javaDependencySnapshotReadsResolvedJdtClasspathsWithoutBuilding() async throws { - let root = URL(fileURLWithPath: "/workspace/java-dependencies", isDirectory: true) - let module = root.appendingPathComponent("service", isDirectory: true) - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - defer { manager.stopAllLanguageServers() } - let (events, continuation) = AsyncStream.makeStream(of: Void.self, bufferingPolicy: .bufferingNewest(1)) - defer { continuation.finish() } - manager.onJavaDependencySnapshotChange = { continuation.yield(()) } - - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - #expect(session.executedCommands.isEmpty) - session.publishPreparation(.init(phase: "ready", status: "ready", blocksRun: false)) - let projects = try await session.waitForExecuteCommand() - #expect(projects.command == "java.project.getAll") - session.completeExecuteReturningValue(.success(.array([ - .string(root.absoluteString), .string(module.absoluteString), - .string("file:///unrelated/project") - ]))) - - let rootClasspath = try await session.waitForExecuteCommand(number: 2) - #expect(rootClasspath.command == "java.project.getClasspaths") - // JDT LS reads the options from JSON text only; an object leaves them - // null and the command fails inside the server. - #expect(rootClasspath.arguments == [ - .string(root.absoluteString), .string(#"{"scope":"runtime"}"#) - ]) - session.completeExecuteReturningValue(.success(.object([ - "classpaths": .array([ - .string("/external/cache/one.jar"), .string(root.appendingPathComponent("target/classes").path) - ]), - "modulepaths": .array([.string("/external/cache/two.jar")]) - ]))) - let moduleClasspath = try await session.waitForExecuteCommand(number: 3) - #expect(moduleClasspath.arguments.first == .string(module.absoluteString)) - session.completeExecuteReturningValue(.success(.object([ - "classpaths": .array([.string("/external/cache/one.jar"), .string("relative.jar")]), - "modulepaths": .array([]) - ]))) - - let published = await withTaskGroup(of: Bool.self) { group in - group.addTask { - for await _ in events { return true } - return false - } - group.addTask { - // test-stability: allow(swift-real-sleep) reason: this is the bounded failure deadline for the snapshot callback stream. - try? await Task.sleep(for: .seconds(2)) - return false - } - let result = await group.next() ?? false - group.cancelAll() - continuation.finish() - return result - } - #expect(published) - #expect(manager.dependencySnapshot(workspaceURL: root)?.dependencyRoots.map(\.path) == [ - "/external/cache/one.jar", "/external/cache/two.jar" - ]) - #expect(manager.dependencySnapshot(workspaceURL: module) == nil) - #expect(session.executedCommands.count == 3) - - let (updates, updatedContinuation) = AsyncStream.makeStream( - of: Void.self, bufferingPolicy: .bufferingNewest(1) - ) - defer { updatedContinuation.finish() } - manager.onJavaDependencySnapshotChange = { updatedContinuation.yield(()) } - try manager.notifyWorkspaceFilesChanged(providerID: "java", changes: [ - .init(fileURL: module.appendingPathComponent("pom.xml"), kind: .changed) - ]) - let refreshedProjects = try await session.waitForExecuteCommand(number: 4) - #expect(refreshedProjects.command == "java.project.getAll") - session.completeExecuteReturningValue(.success(.array([.string(module.absoluteString)]))) - let refreshedClasspath = try await session.waitForExecuteCommand(number: 5) - #expect(refreshedClasspath.command == "java.project.getClasspaths") - session.completeExecuteReturningValue(.success(.object([ - "classpaths": .array([.string("/external/cache/updated.jar")]), - "modulepaths": .array([]) - ]))) - let updated = await withTaskGroup(of: Bool.self) { group in - group.addTask { - for await _ in updates { return true } - return false - } - group.addTask { - // test-stability: allow(swift-real-sleep) reason: this bounds a missing dependency refresh callback. - try? await Task.sleep(for: .seconds(2)) - return false - } - let result = await group.next() ?? false - group.cancelAll() - updatedContinuation.finish() - return result - } - #expect(updated) - #expect(manager.dependencySnapshot(workspaceURL: root)?.dependencyRoots.map(\.path) == [ - "/external/cache/updated.jar" - ]) - #expect(session.executedCommands.count == 5) - manager.stopLanguageServer(providerID: "java") - #expect(manager.dependencySnapshot(workspaceURL: root) == nil) - } - - /// JDT reports projects and output folders at their resolved location. - /// A workspace opened through a symbolic link must still own them. - @Test - func javaDependencySnapshotMatchesProjectsBehindASymbolicLink() async throws { - let fileManager = FileManager.default - let scratch = fileManager.temporaryDirectory.appendingPathComponent( - "lithe-java-dependencies-\(UUID().uuidString)", isDirectory: true - ) - defer { try? fileManager.removeItem(at: scratch) } - let resolvedRoot = scratch.appendingPathComponent("resolved", isDirectory: true) - try fileManager.createDirectory(at: resolvedRoot, withIntermediateDirectories: true) - let root = scratch.appendingPathComponent("link", isDirectory: true) - try fileManager.createSymbolicLink(at: root, withDestinationURL: resolvedRoot) - - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - )) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - defer { manager.stopAllLanguageServers() } - let (events, continuation) = AsyncStream.makeStream(of: Void.self, bufferingPolicy: .bufferingNewest(1)) - defer { continuation.finish() } - manager.onJavaDependencySnapshotChange = { continuation.yield(()) } - - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - session.publishPreparation(.init(phase: "ready", status: "ready", blocksRun: false)) - _ = try await session.waitForExecuteCommand() - session.completeExecuteReturningValue(.success(.array([.string(resolvedRoot.absoluteString)]))) - - let classpath = try await session.waitForExecuteCommand(number: 2) - #expect(classpath.command == "java.project.getClasspaths") - #expect(classpath.arguments.first == .string(resolvedRoot.absoluteString)) - session.completeExecuteReturningValue(.success(.object([ - "classpaths": .array([ - .string("/external/cache/one.jar"), - .string(resolvedRoot.appendingPathComponent("target/classes").path) - ]), - "modulepaths": .array([]) - ]))) - - let published = await withTaskGroup(of: Bool.self) { group in - group.addTask { - for await _ in events { return true } - return false - } - group.addTask { - // test-stability: allow(swift-real-sleep) reason: this is the bounded failure deadline for the snapshot callback stream. - try? await Task.sleep(for: .seconds(2)) - return false - } - let result = await group.next() ?? false - group.cancelAll() - continuation.finish() - return result - } - #expect(published) - #expect(manager.dependencySnapshot(workspaceURL: root)?.dependencyRoots.map(\.path) == [ - "/external/cache/one.jar" - ]) - } - - @Test - func javaDebugServerWaitsForJdtlsReadyAndReturnsItsPort() async throws { - let root = URL(fileURLWithPath: "/workspace/java-debug", isDirectory: true) - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider( - for: root.appendingPathComponent("Main.java") - ) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let task = Task { try await manager.startJavaDebugServer(rootURL: root) } - defer { task.cancel() } - - try await session.waitUntilStarted() - #expect(session.executedCommands.isEmpty) - session.publish(.ready) - let command = try await session.waitForExecuteCommand() - #expect(command.command == "vscode.java.startDebugSession") - #expect(command.arguments.isEmpty) - session.completeExecuteReturningValue(.success(.integer(5005))) - - #expect(try await task.value == 5005) - } - - @Test(arguments: ["src/main/java", "src/test/java", "custom/test-sources"], [false, true]) - func javaDebugLaunchTargetUsesJdtlsProjectMetadataForTheCurrentFile(sourceRoot: String, run: Bool) async throws { - let root = URL(fileURLWithPath: "/workspace/java-debug", isDirectory: true) - let source = root.appendingPathComponent("service/\(sourceRoot)/example/Main.java") - let classPaths = sourceRoot == "src/main/java" - ? ["/workspace/custom/classes"] - : ["/workspace/custom/test-output", "/workspace/custom/classes", "/workspace/test-only.jar"] - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let prepared = JavaDebugLaunchTarget( - mainClass: "service/example.Main", projectName: "service", - modulePaths: ["/workspace/modules"], classPaths: classPaths - ) - session.javaLaunchResult = .success(.ready(prepared)) - let task = Task { - if run { - guard case .ready(let target) = try await manager.prepareJavaRunLaunchTarget(fileURL: source, rootURL: root) else { - throw CancellationError() - } - return target - } - return try await manager.resolveJavaDebugLaunchTarget(fileURL: source, rootURL: root) - } - defer { task.cancel() } - - try await session.waitUntilStarted() - session.publish(.ready) - #expect(try await task.value == prepared) - #expect(session.executedCommands.map(\.command) == ["java.prepareLaunch"]) - #expect(session.executedCommands.first?.arguments == [.string(source.path)]) - } - - @Test(arguments: ["success", "cold", "changed", "aba", "cancel", "import-success", "import-cold", "import-changed", "import-aba", "import-cancel"]) - func javaRunUsesThePreparedImportAndRejectsChangesDuringDiscovery(mode: String) async throws { - let importOnly = mode.hasPrefix("import-") - let phase = mode.replacingOccurrences(of: "import-", with: "") - let root = URL(fileURLWithPath: "/workspace/run-import") - let source = root.appendingPathComponent("app/custom/Main.java") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: source)) - let session = WorkspaceStateLanguageServerSession() - session.mavenUpdateResult = .success(.init(settingsChanged: false, projectsReloaded: false, profilesUpdating: true)) - session.deferredJavaLaunch = true - session.javaLaunchResult = .success(.ready(JavaDebugLaunchTarget(mainClass: "demo.Main", projectName: "app", classPaths: ["/current/classes"]))) - let manager = LanguageToolingSessionManager(runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)]) - let baseline = MavenLaunchContext(reactorPath: ".", profiles: ["default"], settingsPath: "/settings.xml", - skipTests: false, mavenExecutablePath: "/default/mvn", javaHomePath: nil) - let prepared = MavenLaunchContext(reactorPath: "app", profiles: ["run-only"], settingsPath: "/settings.xml", - skipTests: false, mavenExecutablePath: "/selected/mvn", javaHomePath: nil) - var current = baseline - manager.configureJavaLanguageImportProvider { _, _ in .init(mavenContext: current) } - if phase != "cold" { - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - } - let task = Task { - if importOnly { - try await manager.applyJavaRunImport(rootURL: root, languageImport: .init(mavenContext: prepared)) - return JavaLaunchPreparation.ready(JavaDebugLaunchTarget(mainClass: "demo.Main", projectName: "app", classPaths: ["/current/classes"])) - } - return try await manager.prepareJavaRunLaunchTarget(fileURL: source, rootURL: root, - languageImport: .init(mavenContext: prepared)) - } - defer { task.cancel(); session.completeExecuteReturningValue(.failure(CancellationError())); session.completeJavaEntrypoints(.failure(CancellationError())); manager.stopAllLanguageServers() } - if phase == "cold" { try await session.waitUntilStarted(); session.publish(.ready) } - _ = try await session.waitForExecuteCommand() - #expect((phase == "cold" ? session.startedMavenContext : session.mavenUpdates.last?.context) == prepared) - #expect(current == baseline) - let revision = manager.javaImportRevision - if phase == "changed" || phase == "aba" { - _ = manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) - if phase == "aba" { - current = prepared - _ = manager.updateJavaMavenConfiguration(rootURL: root, reloadProjects: false) - } - #expect(manager.javaImportRevision > revision) - } - if phase == "cancel" { task.cancel() } - #expect(session.executedCommands.first?.command == (importOnly ? "javaEntrypoints" : "java.prepareLaunch")) - if importOnly { session.completeJavaEntrypoints(.success(JavaEntrypoints(entries: []))) } - else { session.completeExecuteReturningValue(.success(.null)) } - if ["changed", "aba", "cancel"].contains(phase) { - await #expect(throws: CancellationError.self) { try await task.value } - #expect(session.executedCommands.count == 1) - return - } - guard case .ready(let target) = try await task.value else { Issue.record("Expected current launch metadata"); return } - #expect(target.classPaths == ["/current/classes"]) - #expect(session.startCallCount == 1) - // Generation/discovery restores the current Build defaults rather than - // retaining the previous Run's temporary profile as a shadow setting. - let discovery = Task { try await manager.javaEntrypoints(rootURL: root) } - defer { discovery.cancel() } - _ = try await session.waitForExecuteCommand(number: 2) - #expect(session.mavenUpdates.last?.context == baseline) - session.completeJavaEntrypoints(.success(JavaEntrypoints(entries: []))) - #expect(try await discovery.value.entries.isEmpty) - } - - @Test - func javaServiceUpdateUsesTheSameAutomaticClasspathAsLaunch() async throws { - let root = URL(fileURLWithPath: "/workspace/java-update", isDirectory: true) - let source = root.appendingPathComponent("custom/tests/MainTests.java") - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: source)) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime(descriptor: descriptor, session: session)] - ) - // An update reuses the already-running language session. - _ = try manager.startLanguageServer(providerID: "java", rootURL: root) - try await session.waitUntilStarted() - session.publish(.ready) - let target = JavaDebugLaunchTarget( - mainClass: "MainTests", projectName: "service", - modulePaths: [], classPaths: ["/workspace/custom/test-output", "/workspace/test-only.jar"] - ) - let task = Task { - try await manager.buildJavaServiceUpdate(target: target, fileURL: source, rootURL: root) - } - defer { task.cancel() } - let paths = try await session.waitForExecuteCommand() - #expect(paths.command == "vscode.java.resolveClasspath") - #expect(paths.arguments == [.string("MainTests"), .string("service")]) - session.completeExecuteReturningValue(.success(.array([ - .array([]), .array(target.classPaths.map { .string($0) }), - ]))) - let build = try await session.waitForExecuteCommand(number: 2) - #expect(build.command == "vscode.java.buildWorkspace") - session.completeExecuteReturningValue(.success(.integer(1))) - try await task.value - } - - @Test - func javaLaunchPreservesAUsableTargetAfterOneTerminalBuildFailure() async throws { - let root = URL(fileURLWithPath: "/workspace/java-build-failure", isDirectory: true) - let source = root.appendingPathComponent("service/src/main/java/example/Main.java") - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let report = JavaBuildReport( - markerScope: .launchTarget, builderFailedEarlier: true, - elapsedMilliseconds: 8, recovery: .rebuildJavaIndex - ) - let target = JavaDebugLaunchTarget( - mainClass: "service/example.Main", projectName: "service", classPaths: ["/workspace/classes"] - ) - session.javaLaunchResult = .success(.buildFailed(target: target, failure: JavaLaunchBuildFailure( - code: "javaBuildCompilationErrors", message: "The Java project has compilation errors.", report: report - ))) - let task = Task { try await manager.prepareJavaRunLaunchTarget(fileURL: source, rootURL: root) } - defer { task.cancel(); session.stop() } - try await session.waitUntilStarted() - #expect(session.executedCommands.isEmpty) - session.publish(.ready) - guard case .buildFailed(let actual, let failure) = try await task.value else { - Issue.record("expected a continuable build failure") - return - } - #expect(actual == target) - #expect(failure.report == report) - #expect(session.executedCommands.map(\.command) == ["java.prepareLaunch"]) - } - - @Test - func javaDebugLaunchTargetDoesNotBorrowAnotherFileWhenJdtlsReportsItsPath() async throws { - let root = URL(fileURLWithPath: "/workspace/java-debug", isDirectory: true) - let source = root.appendingPathComponent("service/src/main/java/example/UserService.java") - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let failure = LanguageServerRuntimeFailure( - code: "invalidServerResult", - message: "The Java language service could not identify one launch target for this source file." - ) - session.javaLaunchResult = .failure(failure) - let task = Task { try await manager.resolveJavaDebugLaunchTarget(fileURL: source, rootURL: root) } - defer { task.cancel(); session.stop() } - try await session.waitUntilStarted() - session.publish(.ready) - await #expect(throws: LanguageServerRuntimeFailure.self) { try await task.value } - #expect(session.executedCommands.map(\.command) == ["java.prepareLaunch"]) - #expect(session.executedCommands.first?.arguments == [.string(source.path)]) - } - - @Test - func javaTestDiscoveryProjectsSortedClassesAndMethodsForTheTestsTree() async throws { - let root = URL(fileURLWithPath: "/workspace/java-tests", isDirectory: true) - let source = root.appendingPathComponent( - "service/src/test/java/example/UserServiceTest.java" - ) - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let task = Task { - try await manager.discoverJavaTestItems(fileURL: source, rootURL: root) - } - defer { task.cancel() } - - try await session.waitUntilStarted() - session.publish(.ready) - let discovery = try await session.waitForExecuteCommand() - #expect(discovery.command == "javaTestItems") - #expect(discovery.arguments == [.string(source.standardizedFileURL.absoluteString)]) - session.completeJavaTestItems(.success(JavaTestItems(items: [ - JavaTestItem( - id: "service@example.UserServiceTest", - label: "UserServiceTest", - fullName: "example.UserServiceTest", - projectName: "service", - kind: 0, - level: 5, - jdtHandler: "class-handler", - sortText: "002", - children: [ - JavaTestItem( - id: "service@example.UserServiceTest#logsOut", - label: "logsOut()", - fullName: "example.UserServiceTest#logsOut()", - projectName: "service", - kind: 0, - level: 6, - jdtHandler: "logout-handler", - sortText: "002" - ), - JavaTestItem( - id: "service@example.UserServiceTest#logsIn", - label: "logsIn()", - fullName: "example.UserServiceTest#logsIn", - projectName: "service", - kind: 0, - level: 6, - jdtHandler: "login-handler", - sortText: "001" - ), - ] - ), - JavaTestItem( - id: "service@example.AccountTest", - label: "AccountTest", - fullName: "example.AccountTest", - projectName: "service", - kind: 0, - level: 5, - jdtHandler: "account-handler", - sortText: "001" - ), - ]))) - - let items = try await task.value - #expect(items.map(\.label) == [ - "AccountTest", "UserServiceTest", "logsIn()", "logsOut()", - ]) - #expect(items.map(\.depth) == [1, 1, 2, 2]) - #expect(items.map(\.kind) == [.testCase, .testCase, .testCase, .testCase]) - #expect(items.map(\.fileURL) == Array(repeating: source.standardizedFileURL, count: 4)) - #expect(items.map(\.testIdentifier) == [ - "example.AccountTest", - "example.UserServiceTest", - "example.UserServiceTest#logsIn", - "example.UserServiceTest#logsOut()", - ]) - #expect(items.map(\.reportIdentity) == [ - .init(suite: "example.AccountTest"), .init(suite: "example.UserServiceTest"), - .init(suite: "example.UserServiceTest", name: "logsIn"), - .init(suite: "example.UserServiceTest", name: "logsOut") - ]) - } - - @Test - func junitDebugTargetUsesJavaTestDiscoveryAndLaunchArguments() async throws { - let root = URL(fileURLWithPath: "/workspace/java-tests", isDirectory: true) - let source = root.appendingPathComponent( - "service/src/test/java/example/UserServiceTest.java" - ) - let descriptor = try #require( - LanguageProviderCatalog.compatibilityFallback.provider(for: source) - ) - let session = WorkspaceStateLanguageServerSession() - let manager = LanguageToolingSessionManager( - catalog: .compatibilityFallback, - runtimes: [WorkspaceStateLanguageProviderRuntime( - descriptor: descriptor, - session: session - )] - ) - let task = Task { - try await manager.resolveJavaTestDebugLaunchTarget( - fileURL: source, - rootURL: root - ) - } - defer { task.cancel() } - - try await session.waitUntilStarted() - session.publish(.ready) - let discovery = try await session.waitForExecuteCommand() - #expect(discovery.command == "javaTestItems") - #expect(discovery.arguments == [.string(source.standardizedFileURL.absoluteString)]) - session.completeJavaTestItems(.success(JavaTestItems(items: [ - JavaTestItem( - id: "service@example.UserServiceTest", - label: "UserServiceTest", - fullName: "example.UserServiceTest", - projectName: "service", - kind: 0, - level: 5, - jdtHandler: "=service/src Void)? - var onMavenProfileTask: ((String) -> Void)? - var onMavenProfileProject: ((MavenProfileProjectResult) -> Void)? var isRunning = false - var javaTestRunnerURL: URL? var onDiagnostics: ((URL, [LanguageServerDiagnostic]) -> Void)? var onCoreLog: ((CoreLogRecord) -> Void)? var onLog: ((LanguageServerLogLevel, String, String?, String?) -> Void)? @@ -2029,29 +861,10 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { var onFeaturesChange: ((LanguageServerFeatureSet) -> Void)? var serverInfo: LanguageServerInfo? var onServerInfoChange: ((LanguageServerInfo?) -> Void)? - private(set) var startedFingerprint: String? - private(set) var startedMavenContext: MavenLaunchContext? - private(set) var startedGradle: JavaGradleImportConfiguration? private(set) var stopCallCount = 0 private(set) var startCallCount = 0 var startError: Error? - var javaLaunchResult: Result = - .failure(WorkspaceStateSessionError.unexpectedOperation) - var deferredJavaLaunch = false - func prepareJavaLaunch(fileURL: URL, mainClass: String?) async throws -> JavaLaunchPreparation { - try Task.checkCancellation() - let command = LanguageServerCommand(title: "java.prepareLaunch", command: "java.prepareLaunch", - arguments: [.string(fileURL.path)] + (mainClass.map { [.string($0)] } ?? [])) - if deferredJavaLaunch { _ = try await executeReturningValue(command, fileURL: fileURL) } - else { recordExecutedCommand(command) } - try Task.checkCancellation() - return try javaLaunchResult.get() - } private(set) var executedCommands: [LanguageServerCommand] = [] - /// Maven updates handed to the running session, in order. - private(set) var mavenUpdates: [(context: MavenLaunchContext, reloadProjects: Bool)] = [] - var mavenUpdateResult: Result = - .failure(LanguageServerRuntimeFailure(code: "unsupported", message: "unsupported")) private var startWaiters: [UUID: CheckedContinuation] = [:] private var startTimeoutTasks: [UUID: Task] = [:] private var executeWaiters: [UUID: ( @@ -2060,55 +873,40 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { )] = [:] private var executeTimeoutTasks: [UUID: Task] = [:] private var executeValueCompletion: ((Result) -> Void)? - private var javaEntrypointsCompletion: ((Result) -> Void)? - private var javaTestItemsCompletion: ((Result) -> Void)? - - func start(rootURL: URL, workspaceFingerprint: String?) throws { - try start( - rootURL: rootURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: nil - ) + struct PluginServerCall: Equatable { + let pluginID: String + let serverID: String + let method: String } + private(set) var pluginServerRequests: [PluginServerCall] = [] + private(set) var pluginServerNotifications: [PluginServerCall] = [] - func start( - rootURL _: URL, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext? - ) throws { + func requestPluginServer( + pluginID: String, serverID: String, method: String, params _: ToolingJSONValue, timeout _: TimeInterval? + ) async -> Result { + pluginServerRequests.append(PluginServerCall(pluginID: pluginID, serverID: serverID, method: method)) + return .success(.string("answered")) + } + + func notifyPluginServer( + pluginID: String, serverID: String, method: String, params _: ToolingJSONValue + ) async -> Result { + pluginServerNotifications.append(PluginServerCall(pluginID: pluginID, serverID: serverID, method: method)) + return .success(true) + } + + func start(rootURL _: URL) throws { startCallCount += 1 if let startError { throw startError } - startedFingerprint = workspaceFingerprint - startedMavenContext = mavenContext isRunning = true let waiterIDs = Array(startWaiters.keys) waiterIDs.forEach { finishStartWaiter($0, result: .success(())) } } - func start( - rootURL: URL, workspaceFingerprint: String?, mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration? - ) throws { - startedGradle = javaGradle - try start(rootURL: rootURL, workspaceFingerprint: workspaceFingerprint, mavenContext: mavenContext) - } - func publish(_ state: LanguageServerSessionState) { onStateChange?(state) } - func updateMavenConfiguration( - _ context: MavenLaunchContext, - reloadProjects: Bool - ) -> Result { - mavenUpdates.append((context, reloadProjects)) - return mavenUpdateResult - } - - func publishPreparation(_ snapshot: ProjectPreparationSnapshot) { - onProjectPreparation?(snapshot) - } - func waitUntilStarted(timeout: Duration = .seconds(2)) async throws { if isRunning { return } let waiterID = UUID() @@ -2197,18 +995,6 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { completion?(result) } - func completeJavaEntrypoints(_ result: Result) { - let completion = javaEntrypointsCompletion - javaEntrypointsCompletion = nil - completion?(result) - } - - func completeJavaTestItems(_ result: Result) { - let completion = javaTestItemsCompletion - javaTestItemsCompletion = nil - completion?(result) - } - var documentEvents: [String] = [] var saveError: Error? func synchronize(fileURL _: URL, text: String, languageID _: String) throws { @@ -2294,28 +1080,6 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { throw WorkspaceStateSessionError.unexpectedOperation } - func javaEntrypoints( - completion: @escaping (Result) -> Void - ) throws { - // Recorded in the command sequence so tests observe it in request order. - javaEntrypointsCompletion = completion - recordExecutedCommand( - LanguageServerCommand(title: "javaEntrypoints", command: "javaEntrypoints", arguments: []) - ) - } - - func javaTestItems( - fileURL: URL, - completion: @escaping (Result) -> Void - ) throws { - javaTestItemsCompletion = completion - recordExecutedCommand(LanguageServerCommand( - title: "javaTestItems", - command: "javaTestItems", - arguments: [.string(fileURL.standardizedFileURL.absoluteString)] - )) - } - func executeReturningValue( _ command: LanguageServerCommand, fileURL _: URL, @@ -2358,9 +1122,6 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { let completion = executeValueCompletion executeValueCompletion = nil completion?(.failure(CancellationError())) - let testCompletion = javaTestItemsCompletion - javaTestItemsCompletion = nil - testCompletion?(.failure(CancellationError())) } private func finishStartWaiter(_ waiterID: UUID, result: Result) { @@ -2381,18 +1142,6 @@ private final class WorkspaceStateLanguageServerSession: LanguageServerSession { } } -private func javaTestLaunchRequest( - from command: LanguageServerCommand -) throws -> [String: Any] { - guard command.arguments.count == 1, - case .string(let value) = command.arguments[0], - let data = value.data(using: .utf8), - let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - throw WorkspaceStateSessionError.unexpectedOperation - } - return object -} - private enum WorkspaceStateSessionError: LocalizedError { case unexpectedOperation case timedOut diff --git a/macos/Tests/LitheTerminalModuleTests/TerminalModuleTests.swift b/macos/Tests/LitheTerminalModuleTests/TerminalModuleTests.swift index f21bddf155..6a063e07b6 100644 --- a/macos/Tests/LitheTerminalModuleTests/TerminalModuleTests.swift +++ b/macos/Tests/LitheTerminalModuleTests/TerminalModuleTests.swift @@ -141,11 +141,11 @@ struct TerminalModuleTests { let feature = TerminalFeatureModel(terminalFactory: { transport }) let launch = TerminalProcessLaunch( title: "Debug Main", - executablePath: "/opt/jdk/bin/java", - arguments: ["-cp", "/workspace/classes", "example.Main"], + executablePath: "/opt/tool-a/bin/tool-a", + arguments: ["--config", "/workspace/config", "example-target"], workingDirectory: "/workspace", environmentChanges: [ - TerminalEnvironmentChange(name: "JAVA_HOME", value: "/opt/jdk"), + TerminalEnvironmentChange(name: "TOOL_A_HOME", value: "/opt/tool-a"), TerminalEnvironmentChange(name: "REMOVE_ME", value: nil) ] ) @@ -156,7 +156,7 @@ struct TerminalModuleTests { #expect(created.session.isManagedProcess) #expect(created.session.displayTitle == "Debug Main") #expect(transport.processLaunches == [launch]) - #expect(transport.processEnvironments.first?["JAVA_HOME"] == "/opt/jdk") + #expect(transport.processEnvironments.first?["TOOL_A_HOME"] == "/opt/tool-a") #expect(transport.processEnvironments.first?["REMOVE_ME"] == nil) #expect(transport.processEnvironments.first?["TERM_PROGRAM"] == "Lithe") created.session.restart() @@ -235,8 +235,8 @@ struct TerminalModuleTests { let feature = TerminalFeatureModel(terminalFactory: { transport }) let launch = TerminalProcessLaunch( title: "Debug Main", - executablePath: "/opt/jdk/bin/java", - arguments: ["example.Main"], + executablePath: "/opt/tool-a/bin/tool-a", + arguments: ["example-target"], workingDirectory: "/workspace" ) let created = try feature.createProcessSession(launch) @@ -259,7 +259,7 @@ struct TerminalModuleTests { let created = try feature.createProcessSession( TerminalProcessLaunch( title: "Debug Main", - executablePath: "/usr/bin/java", + executablePath: "/usr/bin/tool-a", arguments: ["Main"], workingDirectory: "/tmp" ), @@ -280,7 +280,7 @@ struct TerminalModuleTests { let created = try feature.createProcessSession( TerminalProcessLaunch( title: "Debug Main", - executablePath: "/usr/bin/java", + executablePath: "/usr/bin/tool-a", arguments: ["Main"], workingDirectory: "/tmp" ), diff --git a/macos/Tests/LitheTests/AppLocalizationTests.swift b/macos/Tests/LitheTests/AppLocalizationTests.swift index c1263e22a4..c32809cb1b 100644 --- a/macos/Tests/LitheTests/AppLocalizationTests.swift +++ b/macos/Tests/LitheTests/AppLocalizationTests.swift @@ -235,17 +235,6 @@ struct AppLocalizationTests { #expect(translations["Toggle %@"] == "切换 %@") } - @Test - func simplifiedChineseResourcesCoverJavaLanguageServiceFeedback() throws { - let translations = try simplifiedChineseTranslations() - - #expect(translations["Java service is preparing"] == "Java 服务正在准备") - #expect(translations["Java service is ready"] == "Java 服务已就绪") - #expect(translations["Java service preparation timed out"] == "Java 服务准备超时") - #expect(translations["Java service failed to start"] == "Java 服务启动失败") - #expect(translations["Java service failed to start: %@"] == "Java 服务启动失败:%@") - } - @Test func simplifiedChineseResourcesCoverBreakpointManager() throws { let translations = try simplifiedChineseTranslations() diff --git a/macos/Tests/LitheTests/AppModelLanguageSessionShutdownTests.swift b/macos/Tests/LitheTests/AppModelLanguageSessionShutdownTests.swift index 4de7e77322..77a6017c3a 100644 --- a/macos/Tests/LitheTests/AppModelLanguageSessionShutdownTests.swift +++ b/macos/Tests/LitheTests/AppModelLanguageSessionShutdownTests.swift @@ -79,9 +79,8 @@ struct AppModelLanguageSessionShutdownTests { pluginMarketplace: base.pluginMarketplace, pluginCatalog: base.pluginCatalog, languageProviderCatalogSource: ShutdownTestCatalog(), workspaceLanguageServerPreferences: base.workspaceLanguageServerPreferences, - javaTestResultServerFactory: { MacJavaTestResultServer() }, workspaceOperations: base.workspaceOperations, documentLifecycleDecider: base.documentLifecycleDecider, - lineEditing: base.lineEditing, javaMavenOperations: base.javaMavenOperations, + lineEditing: base.lineEditing, markdownRenderer: base.markdownRenderer, markdownImageImporter: base.markdownImageImporter, store: base.store, fileStorage: base.fileStorage, fileOperations: base.fileOperations, binaryFileViewerRegistry: base.binaryFileViewerRegistry, projectRuntimeService: base.projectRuntimeService, diff --git a/macos/Tests/LitheTests/AppModelSettingsChangesTests.swift b/macos/Tests/LitheTests/AppModelSettingsChangesTests.swift index c64a41383a..41dc2974cc 100644 --- a/macos/Tests/LitheTests/AppModelSettingsChangesTests.swift +++ b/macos/Tests/LitheTests/AppModelSettingsChangesTests.swift @@ -61,7 +61,7 @@ struct AppModelSettingsChangesTests { func mountedLSPPageRefreshesSnapshotsWithoutNotifyingTheSettingsRoot(language: AppLanguage) async throws { let root = URL(fileURLWithPath: "/fixture/lsp-snapshot-updates") let operations = UsageSnapshotOperations(inventories: [ - ["README"], ["README", "go.mod"], ["README", "Main.java"], ["README"] + ["README"], ["README", "go.mod"], ["README", "composer.json"], ["README"] ]) let probe = SettingsChangesProbe(workspaceOperations: operations, language: language) let model = probe.model @@ -100,7 +100,7 @@ struct AppModelSettingsChangesTests { // Keep the same native host mounted while the production workspace // feature publishes create, rename and delete inventories. for expectedPlugin in [nil, OfficialPluginCatalog.goPluginID.rawValue, - OfficialPluginCatalog.javaPluginID.rawValue, nil] as [String?] { + OfficialPluginCatalog.phpPluginID.rawValue, nil] as [String?] { let result = await model.workspaceFeature.rebuild(at: root, rules: .default, isCurrent: { true }) guard case .loaded(let snapshot) = result else { Issue.record("Snapshot was not applied"); return } identities.insert(snapshot.id) diff --git a/macos/Tests/LitheTests/AppSettingsTests.swift b/macos/Tests/LitheTests/AppSettingsTests.swift index b8a3bd2b6c..d9b867f611 100644 --- a/macos/Tests/LitheTests/AppSettingsTests.swift +++ b/macos/Tests/LitheTests/AppSettingsTests.swift @@ -83,25 +83,6 @@ struct AppSettingsTests { #expect(AppSettings(store: store).gitUseCredentialHelper) } - @Test - func javaBuildFailurePolicyIsWorkspaceScopedAndCanReturnToAsk() { - let store = AppSettingsTestStore() - let workspace = URL(fileURLWithPath: "/fixture/projects/demo/../demo", isDirectory: true) - let sameWorkspace = URL(fileURLWithPath: "/fixture/projects/demo", isDirectory: true) - let otherWorkspace = URL(fileURLWithPath: "/fixture/projects/other", isDirectory: true) - let settings = AppSettings(store: store) - - #expect(settings.javaBuildFailurePolicy(for: workspace) == .ask) - settings.setJavaBuildFailurePolicy(.alwaysContinue, for: workspace) - - let reloaded = AppSettings(store: store) - #expect(reloaded.javaBuildFailurePolicy(for: sameWorkspace) == .alwaysContinue) - #expect(reloaded.javaBuildFailurePolicy(for: otherWorkspace) == .ask) - - reloaded.setJavaBuildFailurePolicy(.ask, for: sameWorkspace) - #expect(AppSettings(store: store).javaBuildFailurePolicy(for: workspace) == .ask) - } - @Test func fetchDefaultsPersistAndResetWithoutSavingAnOperationTarget() { let store = AppSettingsTestStore() @@ -156,18 +137,6 @@ struct AppSettingsTests { #expect(!AppSettings(store: store).editorSoftWrapEnabled) } - @Test - func javaKeywordNavigationFilterDefaultsToEnabledAndPersistsAcrossRelaunch() { - let store = AppSettingsTestStore() - let settings = AppSettings(store: store) - - #expect(settings.javaKeywordNavigationFilterEnabled) - - settings.javaKeywordNavigationFilterEnabled = false - - #expect(!AppSettings(store: store).javaKeywordNavigationFilterEnabled) - } - @Test func restoringDefaultsDisablesEditorSoftWrap() { let store = AppSettingsTestStore() diff --git a/macos/Tests/LitheTests/BackgroundResourceSelectionViewTests.swift b/macos/Tests/LitheTests/BackgroundResourceSelectionViewTests.swift index b52d8d573d..88129a9057 100644 --- a/macos/Tests/LitheTests/BackgroundResourceSelectionViewTests.swift +++ b/macos/Tests/LitheTests/BackgroundResourceSelectionViewTests.swift @@ -7,7 +7,7 @@ import Testing @MainActor struct BackgroundResourceSelectionViewTests { @Test func longCommandsWrapAndManyResourcesScrollWithinTheAlert() throws { - let command = "java " + String(repeating: "--add-opens=java.base/java.lang=ALL-UNNAMED ", count: 40) + let command = "tool-a " + String(repeating: "--option=value/with/a/long/path ", count: 40) let resources = (0..<12).map { resource("service-\($0)", detail: command + String(repeating: "x", count: 200)) } let view = BackgroundResourceSelectionView(resources: resources) view.layoutSubtreeIfNeeded() @@ -172,7 +172,7 @@ struct BackgroundResourceSelectionViewTests { } } - private func resource(_ id: String, name: String = "java service", detail: String = "java --add-opens=java.base/java.lang=ALL-UNNAMED --module-path=example.jar", recognizer: String? = nil) -> BackgroundResourceCandidate { + private func resource(_ id: String, name: String = "tool-a service", detail: String = "tool-a --option=value --config=example.toml", recognizer: String? = nil) -> BackgroundResourceCandidate { BackgroundResourceCandidate(id: id, name: name, detail: detail, processIDs: [20, 21], listeningPorts: [8080], startedAt: nil, recognizerID: recognizer, recognizedPolicy: nil, kind: .daemon) } diff --git a/macos/Tests/LitheTests/BuildToolProviderResolutionTests.swift b/macos/Tests/LitheTests/BuildToolProviderResolutionTests.swift index cb8cf00631..7048beed35 100644 --- a/macos/Tests/LitheTests/BuildToolProviderResolutionTests.swift +++ b/macos/Tests/LitheTests/BuildToolProviderResolutionTests.swift @@ -26,7 +26,7 @@ struct BuildToolProviderResolutionTests { "runtimePath": .string(selection == "runtime" ? root.appendingPathComponent("missing runtime").path : "") ] let planner = RustBuildSystemOperations(core: RustCoreBridge()) - let runtime = ProjectRuntimeService(runtimeLocator: ProviderRuntimeLocator(root: root), store: ProviderEmptyStore()) + let runtime = ProjectRuntimeService(runtimeLocator: ProviderRuntimeLocator(root: root)) let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) let target = BuildSystemTarget(manifest: source.manifest, buildSystemID: "fixture") let invocation = try planner.invocationPlan(target, root: ".", settings: settings) @@ -168,13 +168,7 @@ private struct ProviderStateLocator: BuildSystemStateLocating { private struct ProviderRuntimeLocator: RuntimeLocator { let root: URL func environment() -> [String: String] { ["FIXTURE_RUNTIME": root.path] } - func discover() -> RuntimeDiscoveryResult { .init(javaRuntimes: [], mavenRuntimes: []) } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } } private struct ProviderEmptyStore: KeyValueStore { diff --git a/macos/Tests/LitheTests/ConsolePresentationTests.swift b/macos/Tests/LitheTests/ConsolePresentationTests.swift index 10959b57dd..3ecf6a67df 100644 --- a/macos/Tests/LitheTests/ConsolePresentationTests.swift +++ b/macos/Tests/LitheTests/ConsolePresentationTests.swift @@ -147,7 +147,9 @@ struct ConsolePresentationTests { let text = (1...8).map { "\tat demo.Main.frame\($0)(Main.java:1)\n" }.joined() + String(repeating: "\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1)\n", count: 5) let raw = NSAttributedString(string: text) - let presentation = ConsoleFoldPresentation() + // Internal prefixes are injected by whoever owns the runtime; the host has none built in. + #expect(ConsoleStackTraceFolding.regions(in: text).allSatisfy { $0.kind == "frames" }) + let presentation = ConsoleFoldPresentation(internalPatterns: ["at java.util.concurrent.ThreadPoolExecutor"]) let folded = presentation.project(raw, dark: true, fontSize: 13) #expect(folded.string.contains("<5 folded frames>")) let outer = try #require(presentation.regions.first(where: { $0.kind == "frames" })) diff --git a/macos/Tests/LitheTests/DebugAutomaticExpressionProjectionTests.swift b/macos/Tests/LitheTests/DebugAutomaticExpressionProjectionTests.swift deleted file mode 100644 index a019fc5753..0000000000 --- a/macos/Tests/LitheTests/DebugAutomaticExpressionProjectionTests.swift +++ /dev/null @@ -1,30 +0,0 @@ -import Foundation -import Testing -@testable import Lithe - -@Suite("Debug automatic expressions") -struct DebugAutomaticExpressionProjectionTests { - @Test - func javaAutomaticDebugExpressionsKeepReceiversAndSkipMethods() { - let source = "return service.listUsers();" as NSString - - let expressions = DebugAutomaticExpressionProjection.javaExpressions( - forLine: 0, - in: source - ) - - #expect(expressions == ["service"]) - } - - @Test - func javaAutomaticDebugExpressionsAreBoundedAndSourceOrdered() { - let source = "a + b + c + d + e + f + g + h + i + j" as NSString - - let expressions = DebugAutomaticExpressionProjection.javaExpressions( - forLine: 0, - in: source - ) - - #expect(expressions == ["a", "b", "c", "d", "e", "f", "g", "h"]) - } -} diff --git a/macos/Tests/LitheTests/DebugBreakpointPersistenceTests.swift b/macos/Tests/LitheTests/DebugBreakpointPersistenceTests.swift index 9979b29325..19214e4432 100644 --- a/macos/Tests/LitheTests/DebugBreakpointPersistenceTests.swift +++ b/macos/Tests/LitheTests/DebugBreakpointPersistenceTests.swift @@ -14,7 +14,7 @@ struct DebugBreakpointPersistenceTests { let first = DebugBreakpointSnapshot( areBreakpointsMuted: true, breakpoints: [PersistedDebugBreakpoint( - relativePath: "src/Main.java", + relativePath: "src/main.txt", line: 12, enabled: false, condition: "user != null", @@ -23,7 +23,7 @@ struct DebugBreakpointPersistenceTests { )] ) let second = DebugBreakpointSnapshot( - breakpoints: [PersistedDebugBreakpoint(relativePath: "App.java", line: 4)] + breakpoints: [PersistedDebugBreakpoint(relativePath: "app.txt", line: 4)] ) try store.saveBreakpoints(first, for: firstRoot) @@ -51,44 +51,6 @@ struct DebugBreakpointPersistenceTests { try store.loadBreakpoints(for: root) } } - - @Test - func macStorePersistsSteppingFiltersByAdapter() throws { - let preferences = DebugBreakpointTestStore() - let store = MacDebugSteppingFilterStore(store: preferences) - let java = DebugSteppingFilters( - classNameFilters: ["$JDK", "org.mockito.*"], - skipSynthetics: true, - skipStaticInitializers: true, - skipConstructors: false, - hideFilteredStackFrames: true - ) - let go = DebugSteppingFilters( - classNameFilters: [], - skipSynthetics: false, - skipStaticInitializers: false, - skipConstructors: false, - hideFilteredStackFrames: false - ) - - try store.saveSteppingFilters(java, adapterID: "java") - try store.saveSteppingFilters(go, adapterID: "go") - - #expect(try store.loadSteppingFilters(adapterID: "java") == java) - #expect(try store.loadSteppingFilters(adapterID: "go") == go) - #expect(try store.loadSteppingFilters(adapterID: "python") == nil) - } - - @Test - func macStoreReportsCorruptSteppingFilterData() { - let preferences = DebugBreakpointTestStore() - preferences.set(Data("not-json".utf8), forKey: "lithe.debug.steppingFilters.java") - let store = MacDebugSteppingFilterStore(store: preferences) - - #expect(throws: MacDebugSteppingFilterStoreError.self) { - try store.loadSteppingFilters(adapterID: "java") - } - } } private final class DebugBreakpointTestStore: KeyValueStore, @unchecked Sendable { diff --git a/macos/Tests/LitheTests/DebugLaunchPreparationCoordinatorTests.swift b/macos/Tests/LitheTests/DebugLaunchPreparationCoordinatorTests.swift index dac2513c61..179d93b706 100644 --- a/macos/Tests/LitheTests/DebugLaunchPreparationCoordinatorTests.swift +++ b/macos/Tests/LitheTests/DebugLaunchPreparationCoordinatorTests.swift @@ -8,7 +8,7 @@ struct DebugLaunchPreparationCoordinatorTests { @Test("saves a dirty debug document and records its previous text") func savesDirtyDocument() async { let document = EditorDocument( - url: URL(fileURLWithPath: "/workspace/Main.java"), + url: URL(fileURLWithPath: "/workspace/example.txt"), text: "before", modificationDate: nil ) @@ -29,7 +29,7 @@ struct DebugLaunchPreparationCoordinatorTests { @Test("skips clean debug documents") func skipsCleanDocument() async { let document = EditorDocument( - url: URL(fileURLWithPath: "/workspace/Main.java"), + url: URL(fileURLWithPath: "/workspace/example.txt"), text: "source", modificationDate: nil ) @@ -45,12 +45,12 @@ struct DebugLaunchPreparationCoordinatorTests { #expect(notifications.messages.isEmpty) } - /// A launch must not proceed from a source file the compiler will not see; + /// A launch must not proceed from a source file the build will not see; /// a failed save aborts instead of debugging the stale text on disk. @Test("aborts the launch when the dirty document cannot be saved") func abortsOnFailedSave() async { let document = EditorDocument( - url: URL(fileURLWithPath: "/workspace/Main.java"), + url: URL(fileURLWithPath: "/workspace/example.txt"), text: "before", modificationDate: nil ) @@ -64,13 +64,14 @@ struct DebugLaunchPreparationCoordinatorTests { let ready = await coordinator.saveDirtyDocumentIfNeeded(document) #expect(!ready) - #expect(notifications.messages == ["Could not save Main.java"]) + #expect(notifications.messages == ["Could not save %@"]) + #expect(notifications.arguments == [["example.txt"]]) } @Test("reports a failed debug launch and reopens the debug tool window") func reportsFailedLaunch() { let configuration = DebugLaunchConfiguration( - name: "Main", + name: "example", request: .launch, arguments: [:] ) @@ -99,7 +100,7 @@ struct DebugLaunchPreparationCoordinatorTests { let started = coordinator.start( configuration: DebugLaunchConfiguration( - name: "Main", + name: "example", request: .launch, arguments: [:] ), diff --git a/macos/Tests/LitheTests/DebugModuleCoordinatorTests.swift b/macos/Tests/LitheTests/DebugModuleCoordinatorTests.swift index 8b67085a88..14f4847bd3 100644 --- a/macos/Tests/LitheTests/DebugModuleCoordinatorTests.swift +++ b/macos/Tests/LitheTests/DebugModuleCoordinatorTests.swift @@ -8,8 +8,8 @@ import Testing @MainActor struct DebugModuleCoordinatorTests { - @Test(arguments: [false, true], [false, true]) - func toolbarDebugRestartsOnlyTheSelectedTarget(paused: Bool, sameTarget: Bool) async throws { + @Test(arguments: [false, true]) + func toolbarDebugRestartsTheActiveSession(paused: Bool) async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } @@ -24,7 +24,7 @@ struct DebugModuleCoordinatorTests { } let adapter = ToolbarTargetDebugSession(paused: paused) let sessions = DebugAdapterSessionManager(providers: [ - DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"]) + DebugProviderDescriptor(id: "tool-a", displayName: "Tool A", fileExtensions: ["txt"]) ]) { _, _ in adapter } let feature = GenericDebugFeatureModel(paging: RustCoreBridge(), sessions: sessions) let graph = DebugPresentationTestGraph(feature: feature) @@ -38,22 +38,12 @@ struct DebugModuleCoordinatorTests { _ = try await runtime.activate(.debug) let capability = try #require(runtime.capability(.debugWorkspace) as? DebugModuleCapability) model.cacheModuleCapability(capability, id: .debugWorkspace, moduleID: .debug) - let source = root.appendingPathComponent("Tests.java") + let source = root.appendingPathComponent("main.txt") #expect(feature.start(fileURL: source, rootURL: root, - configuration: DebugLaunchConfiguration(name: "check()", request: .launch, arguments: [:]))) + configuration: DebugLaunchConfiguration(name: "main", request: .launch, arguments: [:]))) try #require(feature.state == (paused ? .paused : .running)) - let selected = sameTarget ? "demo.First#check()" : "demo.Second#check()" - var target = ActiveTestTarget(providerID: "java", scope: .testCase(identifier: selected, fileURL: nil)) - if sameTarget { target.resolvedName = "check()" } - model.activeTestTarget = target - model.clearNotifications() WorkbenchModuleUIComposition.builtIn.performAction(id: "workbench.debug-start-or-restart", model: model, surface: nil) - #expect(adapter.launchCount == (sameTarget ? 2 : 1)) - if !sameTarget { - // Reaching the source guard proves B entered test preparation instead of restarting A. - #expect(model.notifications.contains { $0.message == "The selected Java test has no source file" }) - #expect(model.activeTestTarget?.scope == target.scope) - } + #expect(adapter.launchCount == 2) } } diff --git a/macos/Tests/LitheTests/DebugPerformanceSamplingTests.swift b/macos/Tests/LitheTests/DebugPerformanceSamplingTests.swift index 7da6d24f37..7cece3d2d4 100644 --- a/macos/Tests/LitheTests/DebugPerformanceSamplingTests.swift +++ b/macos/Tests/LitheTests/DebugPerformanceSamplingTests.swift @@ -4,33 +4,8 @@ import Testing @testable import Lithe @MainActor -@Suite("JVM performance sampling", .serialized) +@Suite("Debug performance sampling", .serialized) struct DebugPerformanceSamplingTests { - private let header = "Timestamp S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT\n" - private let row = "12.5 10 20 1 2 30 3 40 4 500 450 100 80 1 0.1 0 0 0.1\n" - - @Test func jstatParsesChunksAndExcludesNonHeapCounters() throws { - var parser = JStatHeapParser() - #expect(try parser.append(String(header.prefix(15))).isEmpty) - #expect(try parser.append(String(header.dropFirst(15)) + String(row.prefix(9))).isEmpty) - let result = try parser.append(String(row.dropFirst(9)) + row) - #expect(result.count == 2) - #expect(result[0].uptime == 12.5) - #expect(result[0].used == 10 * 1024) - #expect(result[0].committed == 100 * 1024) - } - - @Test func jstatRejectsInvalidAndUnboundedCounters() throws { - for invalid in ["-1", "NaN", "inf", "-", "1e100", "100000"] { - var parser = JStatHeapParser() - _ = try parser.append(header) - let bad = row.replacingOccurrences(of: " 1 2 30", with: " \(invalid) 2 30") - #expect(throws: (any Error).self) { _ = try parser.append(bad) } - } - var parser = JStatHeapParser() - #expect(throws: (any Error).self) { _ = try parser.append(String(repeating: "x", count: 16_385)) } - } - @Test func collapseSwitchAndStopCancelTheirStreamsAndRejectStaleSamples() async throws { let sampler = ControlledPerformanceSampler() defer { sampler.finishAll() } @@ -38,7 +13,7 @@ struct DebugPerformanceSamplingTests { defer { feature.setVisible(false) } let first = UUID(), second = UUID() for (id, pid) in [(first, Int32(101)), (second, 102)] { - feature.register(DebugPerformanceTarget(processID: pid, javaExecutable: id == first ? nil : URL(fileURLWithPath: "/fixture/jdk/bin/java")), sessionID: id) + feature.register(DebugPerformanceTarget(processID: pid), sessionID: id) } feature.select(sessionID: first, isActive: true) feature.setVisible(true) @@ -74,7 +49,7 @@ struct DebugPerformanceSamplingTests { let feature = DebugPerformanceFeatureModel(sampler: sampler) defer { feature.setVisible(false) } let id = UUID() - feature.register(DebugPerformanceTarget(processID: 101, javaExecutable: URL(fileURLWithPath: "/fixture/jdk/bin/java")), sessionID: id) + feature.register(DebugPerformanceTarget(processID: 101), sessionID: id) feature.select(sessionID: id, isActive: true) feature.setVisible(true) #expect(await sampler.started[0].waitUntilOpen()) @@ -93,13 +68,13 @@ struct DebugPerformanceSamplingTests { #expect(!feature.isSampling) } - @Test func replacingTheJVMInTheSameDAPSessionClearsItsOldTimeline() async { + @Test func replacingTheProcessInTheSameDAPSessionClearsItsOldTimeline() async { let sampler = ControlledPerformanceSampler() defer { sampler.finishAll() } let feature = DebugPerformanceFeatureModel(sampler: sampler) defer { feature.setVisible(false) } let id = UUID() - let first = DebugPerformanceTarget(processID: 101, javaExecutable: URL(fileURLWithPath: "/fixture/jdk/bin/java")) + let first = DebugPerformanceTarget(processID: 101) feature.register(first, sessionID: id) feature.select(sessionID: id, isActive: true) feature.setVisible(true) @@ -111,7 +86,7 @@ struct DebugPerformanceSamplingTests { #expect(await received.waitUntilOpen()) feature.register(first, sessionID: id) #expect(sampler.streamCount == 1) - feature.register(DebugPerformanceTarget(processID: 102, javaExecutable: first.javaExecutable), sessionID: id) + feature.register(DebugPerformanceTarget(processID: 102), sessionID: id) #expect(feature.samples.isEmpty) #expect(await sampler.terminated[0].waitUntilOpen()) #expect(await sampler.started[1].waitUntilOpen()) @@ -128,7 +103,7 @@ struct DebugPerformanceSamplingTests { defer { sampler.finishAll() } var feature: DebugPerformanceFeatureModel? = DebugPerformanceFeatureModel(sampler: sampler) let id = UUID() - feature?.register(DebugPerformanceTarget(processID: 101, javaExecutable: URL(fileURLWithPath: "/fixture/jdk/bin/java")), sessionID: id) + feature?.register(DebugPerformanceTarget(processID: 101), sessionID: id) feature?.select(sessionID: id, isActive: true) feature?.setVisible(true) #expect(await sampler.started[0].waitUntilOpen()) @@ -138,12 +113,12 @@ struct DebugPerformanceSamplingTests { #expect(await sampler.terminated[0].waitUntilOpen()) } - @Test func anUnknownTargetShowsUnavailableWithoutPretendingToSample() { + @Test func anUnknownTargetDoesNotPretendToSample() { let feature = DebugPerformanceFeatureModel(sampler: nil) feature.select(sessionID: UUID(), isActive: true) feature.setVisible(true) #expect(!feature.isSampling) - #expect(feature.errorMessage != nil) + #expect(feature.errorMessage == nil) #expect(feature.samples.isEmpty) } diff --git a/macos/Tests/LitheTests/DebugSessionCleanupCoordinatorTests.swift b/macos/Tests/LitheTests/DebugSessionCleanupCoordinatorTests.swift index 634a6be669..cef5d2c205 100644 --- a/macos/Tests/LitheTests/DebugSessionCleanupCoordinatorTests.swift +++ b/macos/Tests/LitheTests/DebugSessionCleanupCoordinatorTests.swift @@ -4,7 +4,7 @@ import LitheDebugModule @Suite("Debug session cleanup coordinator") struct DebugSessionCleanupCoordinatorTests { - @Test("cleans Java and terminal resources after termination") + @Test("cleans terminal resources after termination") @MainActor func cleansResourcesAfterTermination() { let coordinator = DebugSessionCleanupCoordinator() @@ -14,7 +14,7 @@ struct DebugSessionCleanupCoordinatorTests { coordinator.handle(.terminated, activeSessionID: sessionID) - #expect(actions.events == ["stop-java-result-server", "stop-session-terminals"]) + #expect(actions.events == ["stop-session-terminals"]) #expect(actions.stoppedTerminalSessionIDs == [sessionID]) } @@ -29,7 +29,7 @@ struct DebugSessionCleanupCoordinatorTests { coordinator.handle(.failed, activeSessionID: nil) - #expect(actions.events == ["stop-java-result-server", "stop-terminals"]) + #expect(actions.events == ["stop-terminals"]) #expect(actions.stoppedTerminalSessionIDs == [nil]) } diff --git a/macos/Tests/LitheTests/DebugToolbarPresentationTests.swift b/macos/Tests/LitheTests/DebugToolbarPresentationTests.swift index 336be648bb..021acaca5a 100644 --- a/macos/Tests/LitheTests/DebugToolbarPresentationTests.swift +++ b/macos/Tests/LitheTests/DebugToolbarPresentationTests.swift @@ -11,10 +11,10 @@ struct DebugToolbarPresentationTests { func mainToolbarUsesPauseAndResumeOnlyForTheSelectedDebugTarget() { for state in [DebugAdapterState.idle, .initializing, .ready, .launching, .running, .paused, .terminated, .failed] { let control = DebugToolbarPresentation.mainToolbarControl(state: state, - debugTarget: "CalculatorTest.addsPositiveNumbers", selectedTarget: "CalculatorTest.addsPositiveNumbers") + debugTarget: "example-suite.case-a", selectedTarget: "example-suite.case-a") #expect(control == (state == .paused ? .resume : state == .running ? .pause : nil)) #expect(DebugToolbarPresentation.mainToolbarControl(state: state, - debugTarget: "CalculatorTest.addsPositiveNumbers", selectedTarget: "RunDemo") == nil) + debugTarget: "example-suite.case-a", selectedTarget: "other-target") == nil) } #expect(DebugToolbarPresentation.mainToolbarControl(state: .paused, debugTarget: nil, selectedTarget: nil) == nil) #expect(DebugToolbarPresentation.ideaAssetPath(for: .resume) == "expui/run/resume.svg") @@ -22,44 +22,12 @@ struct DebugToolbarPresentationTests { } @Test - func sourceNameToggleRemovesOnlyAnExactDuplicateClassSuffix() { - let source = URL(fileURLWithPath: "/demo/UserService.java") - let frame = DebugStackFrame(id: 1, name: "findUser:42, UserService", sourceURL: source, line: 42, column: 1) - #expect(DebugToolbarPresentation.stackFrameLabel(frame, showsSourceName: true) == "findUser:42") - #expect(DebugToolbarPresentation.stackFrameLabel(frame, showsSourceName: false) == frame.name) - for name in ["findUser:42, UserService$Inner", "findUser:42, OtherService", "example.UserService.findUser", ", UserService"] { - let other = DebugStackFrame(id: 2, name: name, sourceURL: source, line: 42, column: 1) - #expect(DebugToolbarPresentation.stackFrameLabel(other, showsSourceName: true) == name) - } - let unknown = DebugStackFrame(id: 3, name: frame.name, sourceURL: nil, line: 42, column: 1) - #expect(DebugToolbarPresentation.stackFrameLabel(unknown, showsSourceName: true) == frame.name) - } - - @MainActor - @Test - func qualifiedMethodsWithMultipleParametersRetainMethodHighlighting() throws { - let frame = DebugStackFrame(id: 1, name: "example.UserService.findUser(java.lang.String, int):42, UserService", - sourceURL: URL(fileURLWithPath: "/demo/UserService.java"), line: 42, column: 1) - let text = DebugToolbarPresentation.stackFrameText(frame, showsSourceName: true, isDark: true) - let range = try #require(text.range(of: "findUser")) - let palette = SyntaxHighlightingColorConfiguration.bundled.palette(formatID: "java", - base: CodeEditorPalette(isDark: true, theme: LitheTheme.activeTheme)) - #expect(text[range].foregroundColor == Color(nsColor: palette.functionCall)) - #expect(String(text.characters).hasSuffix(":42")) - } - - @MainActor - @Test(arguments: [false, true]) - func stackMethodsUseTheConfiguredJavaSyntaxColor(isDark: Bool) { - let frame = DebugStackFrame(id: 1, name: "findUser:42, UserService", - sourceURL: URL(fileURLWithPath: "/demo/UserService.java"), line: 42, column: 1) - let text = DebugToolbarPresentation.stackFrameText(frame, showsSourceName: true, isDark: isDark) - #expect(String(text.characters) == "findUser:42") - let end = text.characters.index(text.startIndex, offsetBy: "findUser".count) - let palette = SyntaxHighlightingColorConfiguration.bundled.palette(formatID: "java", - base: CodeEditorPalette(isDark: isDark, theme: LitheTheme.activeTheme)) - #expect(text[text.startIndex.. 1, "Method, punctuation and line number retain separate syntax attributes") + func stackFrameTextKeepsTheAdapterProvidedFrameName() { + let frame = DebugStackFrame(id: 1, name: "run:42, ExampleModule", + sourceURL: URL(fileURLWithPath: "/demo/example.txt"), line: 42, column: 1) + #expect(String(DebugToolbarPresentation.stackFrameText(frame).characters) == frame.name) + let unknown = DebugStackFrame(id: 2, name: frame.name, sourceURL: nil, line: 42, column: 1) + #expect(String(DebugToolbarPresentation.stackFrameText(unknown).characters) == frame.name) } @Test diff --git a/macos/Tests/LitheTests/DiagnosticsExportServiceTests.swift b/macos/Tests/LitheTests/DiagnosticsExportServiceTests.swift index 8192033e08..7af8f2e46e 100644 --- a/macos/Tests/LitheTests/DiagnosticsExportServiceTests.swift +++ b/macos/Tests/LitheTests/DiagnosticsExportServiceTests.swift @@ -161,7 +161,7 @@ struct DiagnosticsExportServiceTests { // `swift test` does not force-load the Rust Core static library by // default (see scripts/macos/test/test-macos.sh); skip gracefully rather than // asserting on the "unavailable" failure path, mirroring - // RealJavaDebugIntegrationTests's guard. + // the other Rust-backed tests' guards. guard RustCoreBridge().isAvailable else { return } let storage = InMemoryDiagnosticsFileStorage() diff --git a/macos/Tests/LitheTests/DiagnosticsWorkflowTests.swift b/macos/Tests/LitheTests/DiagnosticsWorkflowTests.swift index 5147744b7f..2052e1eb64 100644 --- a/macos/Tests/LitheTests/DiagnosticsWorkflowTests.swift +++ b/macos/Tests/LitheTests/DiagnosticsWorkflowTests.swift @@ -194,19 +194,19 @@ struct DiagnosticsWorkflowTests { let op = "render-operation-\(index / 16)" switch index % 10 { case 0: writer.emit(AppSessionStarted(operationID: op)) - case 1, 2: writer.emit(LspTraceReceived(diagnostic: "Received response", server: LogSegment("jdtls")!, operationID: op)) + case 1, 2: writer.emit(LspTraceReceived(diagnostic: "Received response", server: LogSegment("example-server")!, operationID: op)) case 3: writer.emit(LspTraceReceived(diagnostic: "Sending request", server: LogSegment("rust-analyzer")!, operationID: op)) - case 4: writer.emit(LspStderrReceived(diagnostic: "Building workspace", server: LogSegment("jdtls")!, truncated: false, operationID: op)) + case 4: writer.emit(LspStderrReceived(diagnostic: "Building workspace", server: LogSegment("example-server")!, truncated: false, operationID: op)) case 5: writer.emit(LspSessionDegradationReceived(failureCode: "unavailable", server: LogSegment("invalid-3f9a0c2e")!, stage: "index", operationID: op)) case 6: writer.emit(VcsGitCommandFinished(arguments: "fetch --prune origin", command: "fetch", duration: .milliseconds(487), exitCode: 0, source: "background", operationID: op)) - case 7: writer.emit(PluginsHostMessageLogged(diagnostic: "Using mirror central", plugin: LogSegment("maven")!, severity: "info", operationID: op)) + case 7: writer.emit(PluginsHostMessageLogged(diagnostic: "Using mirror", plugin: LogSegment("example-plugin")!, severity: "info", operationID: op)) case 8: writer.emit(PluginsHostMessageLogged(diagnostic: "Process stopped", plugin: LogSegment("lldb")!, severity: "debug", operationID: op)) default: writer.emit(AppDiagnosticsExportFailed(error: LogFailure(domain: "render", code: "unavailable"), stage: "planning", operationID: op)) } } for offset in 0..<6 { writer.emit(VcsGitCommandFinished(arguments: "fetch --prune origin", command: "fetch", duration: .milliseconds(480 + offset), exitCode: 0, source: "background", operationID: "render-selected")) } writer.emit(AppDiagnosticsExportFailed(error: NSError(domain: "render", code: 1, userInfo: [NSLocalizedDescriptionKey: "token=synthetic-render-secret"]), stage: "planning", operationID: "render-selected")) - writer.emit(LspMessageLogged(diagnostic: "Workspace initialized", server: LogSegment("jdtls")!, severity: "info", operationID: "render-selected")) + writer.emit(LspMessageLogged(diagnostic: "Workspace initialized", server: LogSegment("example-server")!, severity: "info", operationID: "render-selected")) let model = LogWindowModel(logging: writer) let loaded = TestGate(), traced = TestGate() let observation = model.$state.sink { state in @@ -216,7 +216,7 @@ struct DiagnosticsWorkflowTests { defer { observation.cancel(); model.stop() } model.refresh() try #require(await loaded.waitUntilOpen(timeout: .seconds(5)), "Catalog render fixture did not load") - #expect(Set(model.state.records.map(\.channel)).isSuperset(of: ["app", "lsp/jdtls", "lsp/rust-analyzer", "lsp/invalid-3f9a0c2e", "vcs/git", "plugins/maven/host", "plugins/lldb/host"])) + #expect(Set(model.state.records.map(\.channel)).isSuperset(of: ["app", "lsp/example-server", "lsp/rust-analyzer", "lsp/invalid-3f9a0c2e", "vcs/git", "plugins/example-plugin/host", "plugins/lldb/host"])) #expect(Set(model.state.records.map(\.level)) == ["DEBUG", "INFO", "WARN", "ERROR"]) #expect(model.displayRows.contains { $0.isRun && $0.count >= 3 }) #expect(model.state.records.contains { $0.fields.values.contains { $0.contains("") || $0.contains("‹redacted›") } }) diff --git a/macos/Tests/LitheTests/DocumentGuardedSaveTests.swift b/macos/Tests/LitheTests/DocumentGuardedSaveTests.swift index 6c8487947d..cedfcb22dd 100644 --- a/macos/Tests/LitheTests/DocumentGuardedSaveTests.swift +++ b/macos/Tests/LitheTests/DocumentGuardedSaveTests.swift @@ -188,7 +188,7 @@ struct DocumentGuardedSaveTests { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - try body(directory.appendingPathComponent("A.java"), MacWorkspaceFileOperations()) + try body(directory.appendingPathComponent("A.txt"), MacWorkspaceFileOperations()) } @Test func externalChangeWithSameSizeAndMtimeIsNotOverwritten() throws { @@ -227,7 +227,7 @@ struct DocumentGuardedSaveTests { Issue.record("Stale window must conflict"); return } #expect(try String(contentsOf: url, encoding: .utf8) == "first") - #expect(try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path) == ["A.java"]) + #expect(try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path) == ["A.txt"]) } } diff --git a/macos/Tests/LitheTests/DocumentLanguageCoordinatorTests.swift b/macos/Tests/LitheTests/DocumentLanguageCoordinatorTests.swift index 4e05eaf84f..1ff8b4b41d 100644 --- a/macos/Tests/LitheTests/DocumentLanguageCoordinatorTests.swift +++ b/macos/Tests/LitheTests/DocumentLanguageCoordinatorTests.swift @@ -93,8 +93,8 @@ struct DocumentLanguageCoordinatorTests { private func makeDocument() -> EditorDocument { EditorDocument( - url: URL(fileURLWithPath: "/in-memory/Main.java"), - text: "class Main {}", modificationDate: nil + url: URL(fileURLWithPath: "/in-memory/Main.txt"), + text: "main text", modificationDate: nil ) } } diff --git a/macos/Tests/LitheTests/EditorChromeModelTests.swift b/macos/Tests/LitheTests/EditorChromeModelTests.swift index 3e5b039f0d..2ee2cd7a2d 100644 --- a/macos/Tests/LitheTests/EditorChromeModelTests.swift +++ b/macos/Tests/LitheTests/EditorChromeModelTests.swift @@ -9,7 +9,7 @@ struct EditorChromeModelTests { func unchangedCaretAndSelectionDoNotPublish() { let chrome = EditorChromeModel() let caret = EditorCaret( - url: URL(fileURLWithPath: "/workspace/App.java"), + url: URL(fileURLWithPath: "/workspace/App.txt"), line: 3, utf16Column: 8 ) @@ -34,7 +34,7 @@ struct EditorChromeModelTests { func resetClearsCaretAndSelectionOnceEach() { let chrome = EditorChromeModel() chrome.update( - caret: EditorCaret(url: URL(fileURLWithPath: "/workspace/App.java"), line: 0, utf16Column: 0) + caret: EditorCaret(url: URL(fileURLWithPath: "/workspace/App.txt"), line: 0, utf16Column: 0) ) chrome.update(selectedText: "foo") diff --git a/macos/Tests/LitheTests/EditorClosingPreparationTests.swift b/macos/Tests/LitheTests/EditorClosingPreparationTests.swift index e00cf0d7d9..3aa49773a4 100644 --- a/macos/Tests/LitheTests/EditorClosingPreparationTests.swift +++ b/macos/Tests/LitheTests/EditorClosingPreparationTests.swift @@ -11,7 +11,7 @@ struct EditorClosingPreparationTests { @Test func holdsAllDocumentsUntilExplicitReleaseAndReleasesOnlyOnce() async throws { - let first = document("first.java"), second = document("second.java") + let first = document("first.txt"), second = document("second.txt") var held: [String] = [] var released: [String] = [] first.holdEditorForClose = { completion in @@ -28,7 +28,7 @@ struct EditorClosingPreparationTests { #expect(released.isEmpty) #expect(preparation.matches([second, first])) #expect(!preparation.matches([first])) - #expect(!preparation.matches([first, document("second.java")])) + #expect(!preparation.matches([first, document("second.txt")])) preparation.release() preparation.release() #expect(released == ["second", "first"]) @@ -36,7 +36,7 @@ struct EditorClosingPreparationTests { @Test func failedAcquisitionReleasesEarlierDocuments() async { - let first = document("first.java"), second = document("second.java") + let first = document("first.txt"), second = document("second.txt") var releases = 0 first.holdEditorForClose = { completion in completion(.success { releases += 1 }) diff --git a/macos/Tests/LitheTests/EditorDiagnosticsStoreTests.swift b/macos/Tests/LitheTests/EditorDiagnosticsStoreTests.swift index 18dc5903af..0c654fb333 100644 --- a/macos/Tests/LitheTests/EditorDiagnosticsStoreTests.swift +++ b/macos/Tests/LitheTests/EditorDiagnosticsStoreTests.swift @@ -8,7 +8,7 @@ struct EditorDiagnosticsStoreTests { @Test func unchangedDiagnosticsDoNotPublish() { let store = EditorDiagnosticsStore() - let url = URL(fileURLWithPath: "/workspace/App.java") + let url = URL(fileURLWithPath: "/workspace/App.txt") let diagnostic = EditorDiagnostic( id: "d1", fileURL: url, diff --git a/macos/Tests/LitheTests/EditorDocumentSynchronizationTests.swift b/macos/Tests/LitheTests/EditorDocumentSynchronizationTests.swift index e930a9f957..1475eff326 100644 --- a/macos/Tests/LitheTests/EditorDocumentSynchronizationTests.swift +++ b/macos/Tests/LitheTests/EditorDocumentSynchronizationTests.swift @@ -6,7 +6,7 @@ import Testing @Suite("Remote editor document synchronization") struct EditorDocumentSynchronizationTests { private func document() -> EditorDocument { - EditorDocument(url: URL(fileURLWithPath: "/in-memory/Probe.java"), text: "class Probe {}", modificationDate: nil) + EditorDocument(url: URL(fileURLWithPath: "/in-memory/Probe.txt"), text: "probe text", modificationDate: nil) } @Test func nativeDocumentActionsRemainSynchronous() { @@ -35,10 +35,10 @@ struct EditorDocumentSynchronizationTests { #expect(document.needsEditorSynchronization) #expect(throws: EditorDocument.DocumentError.self) { try document.save(using: MacWorkspaceFileOperations()) } // Explicitly deliver the last browser edit before acknowledging the flush. - document.applyLiveEditorEdit(replacedRange: NSRange(location: 6, length: 5), replacement: "中文😀") + document.applyLiveEditorEdit(replacedRange: NSRange(location: 6, length: 4), replacement: "中文😀") let acknowledge = try #require(release) acknowledge(.success(())) - #expect(observedText == "class 中文😀 {}") + #expect(observedText == "probe 中文😀") #expect(permitted) #expect(document.needsEditorSynchronization) } @@ -110,16 +110,16 @@ struct EditorDocumentSynchronizationTests { #expect(acknowledgments.count == 2) first(.success(())) first(.failure(EditorDocument.DocumentError.editorNotSynchronized)) - #expect(savedSnapshots == ["class Probe {}"]) + #expect(savedSnapshots == ["probe text"]) // Only the second drain may release the action after its final edit arrives. - document.applyLiveEditorText("class Latest {}") + document.applyLiveEditorText("latest text") let second = try #require(acknowledgments.last) second(.success(())) - #expect(savedSnapshots == ["class Probe {}", "class Latest {}"]) + #expect(savedSnapshots == ["probe text", "latest text"]) #expect(document.needsEditorSynchronization) } @Test func mixedNewlinesKeepLanguageServerEditPositionsInModelCoordinates() throws { - let document = EditorDocument(url: URL(fileURLWithPath: "/in-memory/Mixed.java"), + let document = EditorDocument(url: URL(fileURLWithPath: "/in-memory/Mixed.txt"), text: "first\rsecond\r\n😀value\n", modificationDate: nil) let source = document.text as NSString let range = source.range(of: "value") diff --git a/macos/Tests/LitheTests/EditorSettingsImportTests.swift b/macos/Tests/LitheTests/EditorSettingsImportTests.swift index 088c6f6914..f8471786c8 100644 --- a/macos/Tests/LitheTests/EditorSettingsImportTests.swift +++ b/macos/Tests/LitheTests/EditorSettingsImportTests.swift @@ -562,7 +562,7 @@ struct EditorSettingsImportTests { "editor.fontSize": 16, "editor.lineHeight": 24, "editor.fontLigatures": true, "editor.lineNumbers": "relative", "editor.minimap.enabled": false, "editor.wordWrap": "on", - "[java]": {"editor.fontSize": 99}, "secret.token": "do-not-copy", + "[plaintext]": {"editor.fontSize": 99}, "secret.token": "do-not-copy", } """#.utf8) let (values, warnings, _) = try MacEditorSettingsImportReader.parseVSCode(data, fonts: ["Fixture Mono"]) @@ -827,7 +827,7 @@ struct EditorSettingsImportTests { #expect(invalid.0["tabSize"] == nil && invalid.0["insertSpaces"] == nil && invalid.0["detectIndentation"] == nil) let files = [ "options/code.style.schemes.xml": "", - "codestyles/custom.xml": "" + "codestyles/custom.xml": "" ].mapValues { Data($0.utf8) } let idea = try MacEditorSettingsImportReader.parseIDEA(files, fonts: []) #expect(idea.0["tabSize"] == "2" && idea.0["insertSpaces"] == "false" && idea.0["detectIndentation"] == "false") @@ -938,14 +938,14 @@ struct EditorSettingsImportTests { let files = [ "options/colors.scheme.xml": "", "colors/parent.icls": "", - "colors/child.icls": "" + "colors/child.icls": "" ].mapValues { Data($0.utf8) } let values = try MacEditorSettingsImportReader.parseIDEA(files, fonts: []).0 let theme = try #require(values["customTheme"].flatMap(ImportedEditorTheme.decode)) #expect(theme.tokens["comment.line"]?.foreground == "#AA44CC") #expect(theme.tokens["comment.line"]?.fontStyle == "italic") #expect(theme.tokens["string"]?.foreground == "#00FF00") - #expect(theme.tokens["comment.documentation.java"]?.foreground == "#AA44CC") + #expect(theme.tokens["comment.documentation"]?.foreground == "#AA44CC") #expect(theme.tokens["method.declaration"]?.foreground == "#CC88FF") #expect(theme.colors["cursor"] == "#FF00FF") let store = ImportTestStore(), settings = AppSettings(store: ImportTestStore()) diff --git a/macos/Tests/LitheTests/EditorSyntaxHighlighterTests.swift b/macos/Tests/LitheTests/EditorSyntaxHighlighterTests.swift index ed00fce98f..884070c94e 100644 --- a/macos/Tests/LitheTests/EditorSyntaxHighlighterTests.swift +++ b/macos/Tests/LitheTests/EditorSyntaxHighlighterTests.swift @@ -5,64 +5,6 @@ import Testing @MainActor @Suite("Editor syntax highlighting") struct EditorSyntaxHighlighterTests { - @Test - func javaSemanticHighlightsOverrideGenericIdentifierColors() throws { - let source = "class Demo { String field; void run(String value) { call(value); } }" - let storage = NSTextStorage(string: source) - SyntaxHighlighter.apply( - to: storage, - font: .monospacedSystemFont(ofSize: 13, weight: .regular), - fileExtension: "java", - isDark: true - ) - let text = source as NSString - let fieldRange = text.range(of: "field") - let declarationRange = text.range(of: "run") - let parameterRange = text.range(of: "value") - let callRange = text.range(of: "call") - - SyntaxHighlighter.applyJavaSemanticHighlights( - [ - JavaSyntaxHighlight(range: fieldRange, role: "field"), - JavaSyntaxHighlight(range: declarationRange, role: "functionDeclaration"), - JavaSyntaxHighlight(range: parameterRange, role: "parameter"), - JavaSyntaxHighlight(range: callRange, role: "functionCall") - ], - to: storage, - isDark: true - ) - let palette = syntaxPalette(fileExtension: "java") - - #expect(try color(in: storage, at: fieldRange.location) == palette.field) - #expect(try color(in: storage, at: declarationRange.location) == palette.functionDeclaration) - #expect(try color(in: storage, at: parameterRange.location) == palette.parameter) - #expect(try color(in: storage, at: callRange.location) == palette.functionCall) - } - - @Test - func javaImportFoldingUsesCoreStructureWithoutLanguageServer() throws { - let operations = RustJavaMavenOperations(core: RustCoreBridge()) - let source = "package demo;\n\nimport java.util.List;\nimport java.util.Map;\nimport static java.util.Collections.emptyList;\n\nclass Probe {\n void run() {}\n}" - let structure = try #require(operations.structure(source: source, declarationSources: [])) - let imports = try #require(structure.foldRegions.first { $0.kind == .imports }) - #expect(imports.startLine == 2 && imports.endLine == 4) - #expect(structure.foldRegions.contains { $0.kind == .type }) - let single = try #require(operations.structure(source: "import java.util.List;\nclass Probe {}", declarationSources: [])) - #expect(!single.foldRegions.contains { $0.kind == .imports }) - } - - @Test - func javaStructurePayloadDecodesPortableUtf16Highlights() throws { - let payload = try JSONDecoder().decode( - RustCoreBridge.JavaStructurePayload.self, - from: Data(#"{"foldRegions":[],"implementationMarkers":[],"inlayHints":[],"syntaxHighlights":[{"utf16Start":7,"utf16Length":4,"role":"field"}]}"#.utf8) - ) - - #expect(payload.makeSyntaxHighlights() == [ - JavaSyntaxHighlight(range: NSRange(location: 7, length: 4), role: "field") - ]) - } - @Test func jsonPropertyKeysUseADifferentColorFromStringValues() throws { let source = #"{"name":"Lithe","nested":{"escaped\"key":"name"}}"# diff --git a/macos/Tests/LitheTests/EditorTabLayoutTests.swift b/macos/Tests/LitheTests/EditorTabLayoutTests.swift index f61af54589..16cdfaee01 100644 --- a/macos/Tests/LitheTests/EditorTabLayoutTests.swift +++ b/macos/Tests/LitheTests/EditorTabLayoutTests.swift @@ -8,49 +8,22 @@ import UniformTypeIdentifiers @Suite("Editor tab layout", .serialized) struct EditorTabLayoutTests { - @Test - func javaTabTestMarkTakesPriorityAndClearsForOrdinaryOrRenamedFiles() { - let java = URL(fileURLWithPath: "/workspace/CalculatorTest.java") - #expect(EditorDocumentIconResolver.overlayResourcePath(for: java, hasTests: true, hasMain: false) - == "expui/nodes/junitTestMark.svg") - #expect(EditorDocumentIconResolver.overlayResourcePath(for: java, hasTests: true, hasMain: true) - == "expui/nodes/junitTestMark.svg") - #expect(EditorDocumentIconResolver.overlayResourcePath(for: java, hasTests: false, hasMain: true) - == "expui/nodes/runnableMark.svg") - #expect(EditorDocumentIconResolver.overlayResourcePath(for: java, hasTests: false, hasMain: false) == nil) - #expect(EditorDocumentIconResolver.overlayResourcePath( - for: java.deletingPathExtension().appendingPathExtension("txt"), hasTests: true, hasMain: true - ) == nil) - } - @MainActor @Test - func testTabScopeUsesImportedRolesBeforeSemanticFallback() { - let root = URL(fileURLWithPath: "/workspace") - #expect(EditorDocument.isTestSourceFile(root.appendingPathComponent("checks/java/Helper.java"), importedSourceRootKind: "testSource", hasTests: false)) - #expect(EditorDocument.isTestSourceFile(root.appendingPathComponent("fixtures/input.json"), importedSourceRootKind: "testResource", hasTests: false)) - #expect(!EditorDocument.isTestSourceFile(root.appendingPathComponent("src/main/java/SomeTest.java"), importedSourceRootKind: "source", hasTests: true)) - #expect(EditorDocument.isTestSourceFile(root.appendingPathComponent("Single.java"), importedSourceRootKind: nil, hasTests: true)) + func testTabScopeUsesImportedSourceRootRoles() { + #expect(EditorDocument.isTestSourceFile(importedSourceRootKind: "testSource")) + #expect(EditorDocument.isTestSourceFile(importedSourceRootKind: "testResource")) + #expect(EditorDocument.isTestSourceFile(importedSourceRootKind: "generatedTestSource")) + #expect(!EditorDocument.isTestSourceFile(importedSourceRootKind: "source")) + #expect(!EditorDocument.isTestSourceFile(importedSourceRootKind: nil)) } @Test - func javaTabsPreferTheSemanticIconResolvedForTheProjectTree() { - let url = URL(fileURLWithPath: "/workspace/UploadService.java") + func tabsPreferTheIconResolvedForTheProjectTree() { + let url = URL(fileURLWithPath: "/workspace/notes.txt") - #expect( - EditorDocumentIconResolver.kind(for: url, resolvedKind: .javaInterface) - == .javaInterface - ) - } - - @Test - func javaTabsUseTheGenericJavaIconUntilSemanticResolutionCompletes() { - let url = URL(fileURLWithPath: "/workspace/UploadService.java") - - #expect( - EditorDocumentIconResolver.kind(for: url, resolvedKind: nil) - == .javaGeneric - ) + #expect(EditorDocumentIconResolver.kind(for: url, resolvedKind: .json) == .json) + #expect(EditorDocumentIconResolver.kind(for: url, resolvedKind: nil) == LitheIcons.kind(for: url, isDirectory: false)) } @Test diff --git a/macos/Tests/LitheTests/EditorTabOrderFeatureModelTests.swift b/macos/Tests/LitheTests/EditorTabOrderFeatureModelTests.swift index f57e52c526..8ecd00c1f8 100644 --- a/macos/Tests/LitheTests/EditorTabOrderFeatureModelTests.swift +++ b/macos/Tests/LitheTests/EditorTabOrderFeatureModelTests.swift @@ -370,9 +370,8 @@ struct EditorTabOrderFeatureModelTests { pluginMarketplace: base.pluginMarketplace, pluginCatalog: base.pluginCatalog, languageProviderCatalogSource: base.languageProviderCatalogSource, workspaceLanguageServerPreferences: base.workspaceLanguageServerPreferences, - javaTestResultServerFactory: { MacJavaTestResultServer() }, workspaceOperations: base.workspaceOperations, documentLifecycleDecider: base.documentLifecycleDecider, - lineEditing: base.lineEditing, javaMavenOperations: base.javaMavenOperations, + lineEditing: base.lineEditing, markdownRenderer: base.markdownRenderer, markdownImageImporter: base.markdownImageImporter, store: base.store, fileStorage: base.fileStorage, fileOperations: base.fileOperations, binaryFileViewerRegistry: base.binaryFileViewerRegistry, projectRuntimeService: base.projectRuntimeService, diff --git a/macos/Tests/LitheTests/Fixtures/BuildSystems/build-host-integration.plugin.json b/macos/Tests/LitheTests/Fixtures/BuildSystems/build-host-integration.plugin.json index be8d482411..09162720c4 100644 --- a/macos/Tests/LitheTests/Fixtures/BuildSystems/build-host-integration.plugin.json +++ b/macos/Tests/LitheTests/Fixtures/BuildSystems/build-host-integration.plugin.json @@ -23,7 +23,6 @@ { "id": "maven", "displayName": "Maven", - "hostIntegration": "maven", "detection": { "markers": [ "pom.xml" @@ -156,7 +155,16 @@ } ], "model": { - "source": "hostIntegration" + "source": "command", + "arguments": [ + "-q", + "lithe:model", + "-Dlithe.output=${outputFile}" + ], + "output": "outputFile", + "decoder": "litheBuildModel", + "executesProjectCode": true, + "mayUseNetwork": true }, "tasks": [ { @@ -315,7 +323,10 @@ "test" ], "results": { - "decoder": "hostIntegration" + "decoder": "junitXml", + "reports": [ + "target/surefire-reports/*.xml" + ] } }, "diagnostics": { @@ -336,7 +347,20 @@ ] }, "dependencies": { - "source": "hostIntegration" + "source": "command", + "scopes": [ + "workspace", + "project" + ], + "arguments": [ + "-q", + "lithe:dependencies", + "-Dlithe.output=${outputFile}" + ], + "output": "outputFile", + "decoder": "litheDependencies", + "executesProjectCode": true, + "mayUseNetwork": true }, "sync": { "watch": [ diff --git a/macos/Tests/LitheTests/IdeCapabilitiesTests.swift b/macos/Tests/LitheTests/IdeCapabilitiesTests.swift index 43ee3ce14c..dd53723a06 100644 --- a/macos/Tests/LitheTests/IdeCapabilitiesTests.swift +++ b/macos/Tests/LitheTests/IdeCapabilitiesTests.swift @@ -11,59 +11,7 @@ import SwiftUI @MainActor struct IdeCapabilitiesTests { @Test - func environmentUsesCanonicalSettingsWithoutActivatingLegacyProjectLoading() async throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent("agent-toolchains-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } - try Data("".utf8).write(to: settings) - try options.setOptions(["profiles": .array([.string("ci")]), "settingsFile": .string(settings.path)], - workspaceURL: fixture.root, buildSystemID: "maven") - let build = BuildSystemService(planner: RustBuildSystemOperations(core: core), - tools: CapabilityBuildToolsFixture(executable: maven), optionsStore: options, - stateLocator: MacBuildSystemStateLocator(directories: directories, fileStorage: MacFileStorage()), - runner: CapabilityBuildRunnerFixture(), providers: sessions, sources: { [source] }) - defer { build.stop() } - let actions = CapabilityActionsFixture(root: fixture.root) - let access = fixture.execution - actions.execution = ExecutionFeatureAccess(runFeature: access.runFeature, - tests: access.tests, projectDevelopment: access.projectDevelopment, buildSystems: BuildSystemsFeatureModel(service: build)) - let feature = IdeCapabilitiesFeatureModel(model: actions) - feature.allowExecute = true - feature.allowConfigure = true - feature.enable() - let result: Result - do { - build.reset(workspaceURL: fixture.root) - _ = try await build.prepareLanguageImport(workspaceURL: fixture.root) - let entry = try #require(build.entries.first) - let configured = await feature.call("lithe_build_configure", arguments: ["instanceID": entry.id, - "optionID": "skipTests", "value": true]) - #expect(configured["saved"] as? Bool == true) - #expect((configured["option"] as? [String: Any])?["value"] as? Bool == true) - #expect(try options.instanceOptions(workspaceURL: fixture.root, buildSystemID: "maven")[entry.instance.root]?["skipTests"] == .bool(true)) - #expect(try options.options(workspaceURL: fixture.root, buildSystemID: "maven")["skipTests"] == nil) - let invalid = await feature.call("lithe_build_configure", arguments: ["instanceID": entry.id, - "optionID": "skipTests", "value": "invalid"]) - #expect(invalid["error"] != nil) - #expect(try options.instanceOptions(workspaceURL: fixture.root, buildSystemID: "maven")[entry.instance.root]?["skipTests"] == .bool(true)) - let loaded = TestGate() - let modelObservation = build.$entries.sink { entries in - if entries.contains(where: { $0.id == entry.id && $0.modelState == .loaded }) { loaded.open() } - } - defer { modelObservation.cancel() } - let reload = await feature.call("lithe_build_reload", arguments: ["instanceID": entry.id]) - #expect(reload["reloadRequested"] as? Bool == true) - try #require(await loaded.waitUntilOpen(timeout: .seconds(60))) - let inspect = await feature.call("lithe_build_inspect", arguments: [:]) - let projects = try #require((inspect["instances"] as? [[String: Any]])?.first?["projects"] as? [[String: String]]) - let projectID = try #require(projects.first { $0["name"] == "core" }?["id"]) - let finished = TestGate() - let operationObservation = build.runEnded.sink { _ in finished.open() } - defer { operationObservation.cancel() } - let start = await feature.call("lithe_build_execute", arguments: ["instanceID": entry.id, - "taskID": "compile", "projectID": projectID]) - let id = try #require(start["operationID"] as? String) - try #require(await finished.waitUntilOpen(timeout: .seconds(60))) - let output = await feature.call("lithe_operation_output", arguments: ["operationID": id]) - #expect(output["state"] as? String == "completed") - #expect(output["exitCode"] as? Int32 == 0) - #expect((output["output"] as? String)?.contains("BUILD SUCCESS") == true) - #expect(FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent( - "nested/core/target/classes/demo/core/Greeter.class").path)) - let stop = await feature.call("lithe_operation_stop", arguments: ["operationID": id]) - #expect(stop["stopRequested"] as? Bool == true) - #expect(build.operation?.state == .succeeded) - result = .success(()) - } catch { result = .failure(error) } - await feature.shutdown() - build.stop() - #expect(await released.waitUntilOpen(timeout: .seconds(5))) - #expect(try MacNativeBuildProviderIntegrationTests.inventory(package) == before) - try result.get() - } - @Test func revokedAndReplacedWorkspacesCannotReachProductActions() async { let actions = CapabilityActionsFixture() @@ -319,7 +167,7 @@ struct IdeCapabilitiesTests { let inspected = await feature.call("lithe_project_inspect", arguments: [:]) #expect(inspected["name"] as? String == "Fixture") actions.currentWorkspaceIdentity = WorkspaceIdentity(url: actions.root, generation: 2) - let stale = await feature.call("lithe_environment_configure", arguments: ["javaHomePath": ""]) + let stale = await feature.call("lithe_run_list", arguments: [:]) #expect((stale["error"] as? [String: String])?["code"] == "WORKSPACE_CLOSED") #expect(actions.activationCount == 0) await feature.shutdown() @@ -332,7 +180,7 @@ struct IdeCapabilitiesTests { actions.transport.validation = ["ok": false, "error": ["code": "PERMISSION_DENIED"]] let feature = IdeCapabilitiesFeatureModel(model: actions) feature.enable() - let result = await feature.call("lithe_build_execute", arguments: ["instanceID": "maven@.", "taskID": "verify"]) + let result = await feature.call("lithe_build_execute", arguments: ["instanceID": "example@.", "taskID": "verify"]) #expect((result["error"] as? [String: String])?["code"] == "PERMISSION_DENIED") #expect(actions.activationCount == 0) await feature.shutdown() @@ -354,7 +202,7 @@ struct IdeCapabilitiesTests { let fixture = try ProviderCapabilityExecutionFixture(execution: .service) defer { fixture.remove() } let entered = TestGate(), release = TestGate(), launched = TestGate() - fixture.run.configureProviderConfigurationRuns { inputs, _, _, _, _, _, _ in + fixture.run.configureProviderConfigurationRuns { inputs, _, _, _, _, _ in #expect(inputs.reference == fixture.reference) entered.open() guard await release.waitUntilOpen(timeout: .seconds(5)) else { throw CancellationError() } @@ -511,11 +359,8 @@ private final class CapabilityActionsFixture: IdeCapabilityActions { var execution: ExecutionFeatureAccess? var startConfiguration: ((RunConfiguration) -> Void)? var currentWorkspaceIdentity: WorkspaceIdentity? - var runtime: RuntimeSettingsFeatureModel? - var runtimeFeature: RuntimeSettingsFeatureModel { - guard let runtime else { preconditionFailure("Authorization tests must not inspect runtimes") } - return runtime - } + // IdeCapabilityActions still declares this requirement; no capability reads it any more. + var runtimeFeature: RuntimeSettingsFeatureModel { preconditionFailure("Capability tests never inspect runtimes") } var ideHostTransport: (any IdeHostTransport)? { transport } init(root: URL = URL(fileURLWithPath: "/fixture/project")) { self.root = root @@ -551,11 +396,10 @@ private final class ProviderCapabilityExecutionFixture { let preferences = CapabilityPreferencesFixture() let store = MacRunConfigurationStore(core: core, storage: MacFileStorage(), preferences: preferences) configurationID = try store.saveBuildProviderConfiguration(reference, name: "Main", at: root) - let runtime = CapabilityRuntimeFixture() let resolver = CapabilityExecutableFixture() - run = RunService(runtime: runtime, process: process, processFactory: { CapabilityProcessFixture() }, + run = RunService(process: process, processFactory: { CapabilityProcessFixture() }, fileAccess: MacRunFileAccess(storage: MacFileStorage()), preferences: preferences, - serverPortParser: CapabilityPortParserFixture(), runConfigurationOperations: store, + runConfigurationOperations: store, executableResolver: resolver, languageProviderCatalog: .compatibilityFallback, languageRunProviders: .standard(catalog: .compatibilityFallback)) let runFeature = RunFeatureModel(service: run) @@ -586,17 +430,6 @@ private final class CapabilityProcessFixture: StreamingProcess, @unchecked Senda func complete(exitCode: Int32) { isRunning = false; onTermination?(exitCode) } } -@MainActor -private final class CapabilityRuntimeFixture: RunRuntimePort { - func setActiveServiceJavaHomePath(_ path: String) {} - func javaHomeURL(overridePath: String?) -> URL? { nil } - func mavenJavaHomeURL(overridePath: String?) -> URL? { nil } - func runConfigurationToolchainCandidates(projectRoot: URL?, - javaHomeOverride: String?, mavenExecutableOverride: String?) -> [ProjectToolchainCandidate] { [] } - func loadRunConfigurationToolchainCandidates(projectRoot: URL?, - javaHomeOverride: String?, mavenExecutableOverride: String?) async throws -> [ProjectToolchainCandidate] { [] } -} - @MainActor private final class CapabilityExecutableFixture: RunExecutableResolving { func resolve(_ plan: SharedLaunchPlan, projectURL: URL, options: RunOptions) throws -> ResolvedRunExecutable { @@ -614,9 +447,6 @@ private final class CapabilityPreferencesFixture: KeyValueStore, RunPreferenceSt nonisolated func setString(_ value: String, forKey key: String) {} } -private struct CapabilityPortParserFixture: RunServerPortParsing { - func serverPort(content: String, fileExtension: String) -> Int? { nil } -} private struct CapabilityBuildError: Error {} diff --git a/macos/Tests/LitheTests/JVMPerformanceIntegrationTests.swift b/macos/Tests/LitheTests/JVMPerformanceIntegrationTests.swift deleted file mode 100644 index 99963c0db2..0000000000 --- a/macos/Tests/LitheTests/JVMPerformanceIntegrationTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -import Darwin -import Foundation -import LitheCoreContracts -import Testing -@testable import Lithe - -@MainActor -@Suite("Real JVM performance integration", .serialized) -struct JVMPerformanceIntegrationTests { - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_TEST_JAVA_EXECUTABLE"] != nil)) - func realJVMReportsHeapAndCPUAndCancellationReapsTheCollector() async throws { - let java = try #require(ProcessInfo.processInfo.environment["LITHE_TEST_JAVA_EXECUTABLE"]) - let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let source = directory.appendingPathComponent("LithePerformanceProbe.java") - try """ - public class LithePerformanceProbe { - static final byte[] retained = new byte[64 * 1024 * 1024]; - static volatile long counter; - public static void main(String[] args) { - System.out.println("LITHE_READY " + ProcessHandle.current().pid()); - long end = System.nanoTime() + 20000000000L; - while (System.nanoTime() < end) { retained[(int)(counter++ % retained.length)]++; } - } - } - """.write(to: source, atomically: true, encoding: .utf8) - let process = MacStreamingProcess() - defer { process.stop() } - let readiness = JVMProbeReadiness() - process.onOutput = { readiness.receive($0) } - try process.start(ProcessRequest(executablePath: java, arguments: [source.path], timeoutMilliseconds: 25_000)) - #expect(await readiness.ready.waitUntilOpen(timeout: .seconds(15))) - let pid = try #require(readiness.processID) - let registry = ManagedProcessRegistry() - let sampler = MacDebugPerformanceSampler(processRegistry: registry) - let received = TestGate() - var samples: [DebugPerformanceSample] = [] - var failure: String? - let job = Task { @MainActor in - do { - for try await sample in sampler.samples(for: DebugPerformanceTarget(processID: pid, - javaExecutable: URL(fileURLWithPath: java))) { - samples.append(sample) - if samples.count >= 3 { received.open() } - } - } catch { failure = error.localizedDescription; received.open() } - } - defer { job.cancel() } - #expect(await received.waitUntilOpen(timeout: .seconds(10))) - #expect(failure == nil, "Collector failure: \(failure ?? "")") - #expect(samples.count >= 3) - #expect(samples.allSatisfy { $0.memoryUsedBytes > 16 * 1024 * 1024 && $0.memoryUsedBytes <= $0.memoryCapacityBytes }) - #expect(samples.compactMap(\.cpuPercent).contains { $0.isFinite && $0 > 0 && $0 <= 100 }) - let collectorPIDs = registry.processIDs(for: ManagedProcessCategory.service) - #expect(collectorPIDs.count == 1) - job.cancel() - await job.value - #expect(registry.processIDs(for: ManagedProcessCategory.service).isEmpty) - // Observe the OS process boundary: registry removal precedes the native - // process group's bounded forced termination. Never infer reaping from it. - let deadline = ContinuousClock.now.advanced(by: .seconds(3)) - while collectorPIDs.contains(where: { kill($0, 0) == 0 }), ContinuousClock.now < deadline { - await Task.yield() - } - #expect(collectorPIDs.allSatisfy { kill($0, 0) != 0 }, "jstat must exit after cancellation") - #expect(await process.stopAndWait()) - } -} - -private final class JVMProbeReadiness: @unchecked Sendable { - let ready = TestGate() - private let lock = NSLock() - private var pending = "" - private var pid: Int32? - var processID: Int32? { lock.withLock { pid } } - func receive(_ chunk: String) { - let complete = lock.withLock { () -> Bool in - pending = String((pending + chunk).suffix(1024)) - guard let line = pending.split(separator: "\n").first(where: { $0.hasPrefix("LITHE_READY ") }), - let value = Int32(line.dropFirst("LITHE_READY ".count)) else { return false } - pid = value - return true - } - if complete { ready.open() } - } -} diff --git a/macos/Tests/LitheTests/JavaLanguageServerRuntimeTests.swift b/macos/Tests/LitheTests/JavaLanguageServerRuntimeTests.swift deleted file mode 100644 index 9f2b8178dd..0000000000 --- a/macos/Tests/LitheTests/JavaLanguageServerRuntimeTests.swift +++ /dev/null @@ -1,683 +0,0 @@ -import Foundation -import LitheApplicationKernel -import LitheModuleAPI -import CryptoKit -import LitheCoreContracts -import LitheExecutionModule -import LitheLanguageIntelligenceModule -import Testing -@testable import Lithe - -@Suite("Java language server runtime") -struct JavaLanguageServerRuntimeTests { - @Test - func projectPreparationFixtureDecodesEverySharedStage() throws { - let root = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() - struct Fixture: Decodable { let snapshots: [ProjectPreparationSnapshot] } - let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: - root.appendingPathComponent("shared/fixtures/lsp/project-preparation-v1.json"))) - #expect(fixture.snapshots.map(\.phase) == ["starting", "importing", "configuring", "building", "ready", "configuring", "stopped"]) - #expect(fixture.snapshots.filter { !$0.blocksRun }.map(\.phase) == ["ready", "configuring"]) - #expect(fixture.snapshots.filter { $0.status == "failed" }.allSatisfy { !$0.blocksRun }) - } - - @Test - func mavenRuntimeFixtureDecodesStructuredTaskAndDistinctProjects() throws { - let root = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() - struct Fixture: Decodable { - let events: [RustCoreBridge.LspRuntimeEventPayload] - } - let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: - root.appendingPathComponent("shared/fixtures/lsp/maven-profile-events-v1.json"))) - #expect(fixture.events.first?.mavenProfileTask == "running") - #expect(fixture.events.last?.mavenProfileTask == "partiallySucceeded") - let results = fixture.events.compactMap(\.mavenProfileProject) - #expect(results.map(\.status) == ["running", "failed", "succeeded"]) - #expect(Set(results.map(\.projectUri)).count == 2) - } - - @Test - func coreInitializationTimeoutCodesRemainUserVisibleTimeouts() { - #expect(LanguageServerSessionFailure(code: "timed_out").isTimedOut) - #expect(LanguageServerSessionFailure(code: "initializeTimeout").isTimedOut) - #expect(LanguageServerSessionFailure(code: "serviceReadyTimeout").isTimedOut) - #expect(!LanguageServerSessionFailure(code: "serverExited").isTimedOut) - } - - @Test - func macJavaLaunchPlannerFindsReleaseFileInStandardJdkHomeLayout() throws { - let fileManager = FileManager.default - let jdkRoot = fileManager.temporaryDirectory - .appendingPathComponent("lithe-java-release-\(UUID().uuidString)", isDirectory: true) - defer { try? fileManager.removeItem(at: jdkRoot) } - let executable = jdkRoot.appendingPathComponent("Contents/Home/bin/java") - try fileManager.createDirectory( - at: executable.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try Data("JAVA_VERSION=\"21.0.2\"\n".utf8) - .write(to: jdkRoot.appendingPathComponent("Contents/Home/release")) - - let arguments = ["-cp", String(repeating: "/jars/example.jar:", count: 3000), "Main"] - let preparation = try RustCoreBridge().prepareJavaLaunch(executablePath: executable.path, arguments: arguments) - #expect(preparation.arguments.first?.hasPrefix("@") == true) - #expect(preparation.lease != nil) - try Data("JAVA_VERSION=\"1.8.0_392\"\n".utf8) - .write(to: jdkRoot.appendingPathComponent("Contents/Home/release")) - let legacy = try RustCoreBridge().prepareJavaLaunch(executablePath: executable.path, arguments: arguments) - #expect(legacy.arguments == arguments) - #expect(legacy.lease == nil) - } - - @Test - @MainActor - func mainMarkerUsesCoreToSelectThePreferredMatchingConfiguration() { - let generated = RunConfiguration( - id: "generated", name: "Generated", kind: .javaMain, - modulePath: nil, mainClass: "demo.App", sourcePath: "src/App.java" - ) - let edited = RunConfiguration( - id: "local", name: "Local", kind: .javaMain, - modulePath: nil, mainClass: "demo.App", sourcePath: "src/App.java" - ) - let operations = RustJavaMavenOperations(core: RustCoreBridge()) - let candidates = [generated, edited] - let source: (RunConfiguration) -> RunConfigurationSource = { - $0.id == "generated" ? .generated : .local - } - let selected = AppModel.javaMainConfiguration( - in: candidates, selectedID: "generated", sourcePath: "src/App.java", mainClass: "demo.App", - source: source, select: operations.selectContextConfiguration - ) - #expect(selected?.id == "generated") - let fallback = AppModel.javaMainConfiguration( - in: candidates, selectedID: "none", sourcePath: "src/App.java", mainClass: "demo.App", - source: source, select: operations.selectContextConfiguration - ) - #expect(fallback?.id == "local") - let absent = AppModel.javaMainConfiguration( - in: candidates, selectedID: "none", sourcePath: "src/Other.java", mainClass: "demo.App", - source: source, select: operations.selectContextConfiguration - ) - #expect(absent == nil) - } - - @Test - func parsesModernAndLegacyJavaVersions() { - #expect(javaRuntime("/jdk-17", "17.0.18").majorVersion == 17) - #expect(javaRuntime("/jdk-21", "21-ea").majorVersion == 21) - #expect(javaRuntime("/jdk-8", "1.8.0_442").majorVersion == 8) - #expect(javaRuntime("/jdk-unknown", "unknown").majorVersion == nil) - } - - @Test - func jdtlsCompatibilityRequiresJava21OrNewer() { - #expect(!javaRuntime("/jdk-11", "11.0.26").supportsJDTLS) - #expect(!javaRuntime("/jdk-17", "17.0.18").supportsJDTLS) - #expect(javaRuntime("/jdk-21", "21.0.10").supportsJDTLS) - #expect(javaRuntime("/jdk-25", "25.0.4").supportsJDTLS) - } - - @Test - @MainActor - func pluginJavaRuntimeIgnoresProjectRunJDK() async { - let projectRuntime = javaRuntime("/project/jdk-11", "11.0.26") - let jdtlsRuntime = javaRuntime("/language-server/jdk-21", "21.0.10") - let service = ProjectRuntimeService( - runtimeLocator: JavaLanguageServerTestRuntimeLocator(runtimes: [projectRuntime, jdtlsRuntime]), - store: JavaLanguageServerTestStore() - ) - service.setJavaLanguageServerRuntimeHome(URL(fileURLWithPath: jdtlsRuntime.homePath, isDirectory: true)) - - #expect( - service.javaHomeURL(overridePath: projectRuntime.homePath)?.path - == projectRuntime.homePath - ) - #expect(service.javaLanguageServerExecutableURL() == nil) - await service.prepareJavaLanguageServerRuntime() - #expect( - service.javaLanguageServerExecutableURL()?.path - == "/language-server/jdk-21/bin/java" - ) - } - - @Test - @MainActor - func pluginJavaRuntimeOlderThanJava21IsRejected() async { - let unsupportedRuntime = javaRuntime("/jdk-17", "17.0.18") - let service = ProjectRuntimeService( - runtimeLocator: JavaLanguageServerTestRuntimeLocator(runtimes: [unsupportedRuntime]), - store: JavaLanguageServerTestStore() - ) - service.setJavaLanguageServerRuntimeHome(URL(fileURLWithPath: unsupportedRuntime.homePath, isDirectory: true)) - - let result = await service.prepareJavaLanguageServerRuntime() - - #expect(service.javaLanguageServerExecutableURL() == nil) - guard case .failed(let message) = result else { - Issue.record("Expected the plugin runtime version check to fail") - return - } - #expect(message.contains("Java 21")) - } - - @Test - @MainActor - func withoutTheJavaPluginNoDiscoveredJDKIsUsed() async { - let discoveredRuntime = javaRuntime("/system/jdk-21", "21.0.10") - let service = ProjectRuntimeService( - runtimeLocator: JavaLanguageServerTestRuntimeLocator(runtimes: [discoveredRuntime]), - store: JavaLanguageServerTestStore() - ) - service.setJavaLanguageServerRuntimeHome(nil) - - let result = await service.prepareJavaLanguageServerRuntime() - - #expect(service.javaLanguageServerExecutableURL() == nil) - guard case .failed(let message) = result else { - Issue.record("Expected a missing Java Support plugin failure") - return - } - // The user is told which plugin provides Java, not to reinstall Lithe. - #expect(message.contains("Java Support plugin")) - } - - @Test - @MainActor - func preparationOwnerCancelsAndReleasesItsTask() { - let owner = JavaLanguageServerPreparationOwner( - workspaceURL: URL(fileURLWithPath: "/workspace", isDirectory: true), - operationID: UUID() - ) - let task = Task { @MainActor () -> Void in - do { - try await Task.sleep(nanoseconds: 60_000_000_000) - } catch { - return - } - } - owner.task = task - - owner.cancel() - - #expect(task.isCancelled) - #expect(owner.task == nil) - } - - @Test - @MainActor - func preparationCoordinatorReplacesThePreviousTask() { - let coordinator = JavaLanguageServerPreparationCoordinator() - let owner = JavaLanguageServerPreparationOwner( - workspaceURL: URL(fileURLWithPath: "/workspace", isDirectory: true), - operationID: UUID() - ) - coordinator.schedule(for: owner) {} - let previous = owner.task - coordinator.schedule(for: owner) {} - - #expect(previous?.isCancelled == true) - #expect(owner.task != nil) - coordinator.cancel(owner) - #expect(owner.task == nil) - } - - @Test - @MainActor - func workspaceStateKeepsPreparationOperationIdentity() { - let workspaceURL = URL(fileURLWithPath: "/workspace", isDirectory: true) - let operationID = UUID() - let owner = JavaLanguageServerPreparationOwner( - workspaceURL: workspaceURL, - operationID: operationID - ) - let state = JavaLanguageServerWorkspaceState.preparing(owner: owner) - - #expect(state.operationID == operationID) - #expect(state.belongs(to: workspaceURL)) - #expect(!state.belongs(to: URL(fileURLWithPath: "/other", isDirectory: true))) - } - - @Test(arguments: [false, true]) - @MainActor - func stoppedSessionClearsOnlyItsOwnPreparation(stale: Bool) { - let root = URL(fileURLWithPath: "/workspace/java-stop", isDirectory: true) - let feature = JavaFeatureModel(operations: NoProjectJavaOperations()) - let owner = feature.beginLanguageServerPreparation(workspaceURL: root, operationID: UUID()) - JavaLanguageServerPreparationCoordinator().handleSessionState( - .stopped, operationID: stale ? UUID() : owner.operationID, - javaFeature: feature, workspaceURL: root, - onReady: { Issue.record("A stopped session cannot become ready") }, - onFailure: { _ in Issue.record("An intentional stop is not a startup failure") } - ) - #expect(feature.isLanguageServerPreparing == stale) - #expect(feature.languageServerOperationID == (stale ? owner.operationID : nil)) - #expect(feature.languageServerStateBelongs(to: root) == stale) - feature.cancelLanguageServerPreparation() - } - - @Test - @MainActor - func startupRechecksImportInvalidatedDuringRuntimePreparation() async throws { - let root = URL(fileURLWithPath: "/workspace/import-during-runtime", isDirectory: true) - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let coordinator = JavaLanguageServerPreparationCoordinator() - let owner = JavaLanguageServerPreparationOwner(workspaceURL: root, operationID: UUID()) - let runtimeStarted = TestGate(), releaseRuntime = TestGate() - let importWaitStarted = TestGate(), releaseImport = TestGate() - var configuration: JavaLanguageImportConfiguration? = .init() - manager.configureJavaLanguageImportProvider { _, _ in - try #require(configuration, "The synchronous start must read the refreshed import") - } - defer { - releaseRuntime.open(); releaseImport.open() - owner.cancel(); manager.stopAllLanguageServers() - } - coordinator.prepareAndStart( - owner: owner, workspaceURL: root, - runtimePreparation: { - runtimeStarted.open() - guard await releaseRuntime.waitUntilOpen() else { return .unprepared } - return .ready(executableURL: URL(fileURLWithPath: "/jdk/bin/java")) - }, - sessionsProvider: { manager }, - languageImportPreparation: { - importWaitStarted.open() - guard await releaseImport.waitUntilOpen() else { throw CancellationError() } - }, - ownsPreparation: { true }, - onStarted: { #expect($0 == owner.operationID) }, - onFailure: { Issue.record("Startup failed: \($0)") } - ) - let task = try #require(owner.task) - try #require(await runtimeStarted.waitUntilOpen(), "Runtime preparation did not begin") - // The initial import was ready. A watched-file change invalidates it - // while JDK preparation is suspended, before the first session exists. - configuration = nil - releaseRuntime.open() - try #require(await importWaitStarted.waitUntilOpen(), "Startup skipped its final import wait") - #expect(session.starts.isEmpty) - let latest = JavaLanguageImportConfiguration(mavenContext: pluginMavenContext(profiles: ["latest"])) - configuration = latest - releaseImport.open() - await task.value - #expect(session.starts.map(\.mavenContext) == [latest.mavenContext]) - } - - @Test(arguments: [false, true]) - @MainActor - func startupImportWaitRejectsCancellationAndReopenedWorkspace(cancel: Bool) async throws { - let root = URL(fileURLWithPath: "/workspace/reopened-import", isDirectory: true) - let identity = WorkspaceIdentity(url: root, generation: 1) - var current = identity - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let coordinator = JavaLanguageServerPreparationCoordinator() - let owner = JavaLanguageServerPreparationOwner(workspaceURL: root, operationID: UUID()) - let waiting = TestGate(), release = TestGate() - defer { release.open(); owner.cancel(); manager.stopAllLanguageServers() } - coordinator.prepareAndStart( - owner: owner, workspaceURL: root, - runtimePreparation: { .ready(executableURL: URL(fileURLWithPath: "/jdk/bin/java")) }, - sessionsProvider: { manager }, - languageImportPreparation: { - waiting.open() - _ = await release.waitUntilOpen() - }, - ownsPreparation: { current == identity }, - onStarted: { _ in Issue.record("Stale preparation must not start") }, - onFailure: { _ in Issue.record("Stale preparation must not report failure") } - ) - let task = try #require(owner.task) - try #require(await waiting.waitUntilOpen(), "Final import wait did not begin") - if cancel { owner.cancel() } - else { current = WorkspaceIdentity(url: root, generation: 2) } - release.open() - await task.value - #expect(session.starts.isEmpty) - } - - @Test - @MainActor - func pluginMavenImportRestartsASessionStartedWithoutMavenInputs() async throws { - let root = URL(fileURLWithPath: "/workspace/new-plugin-maven", isDirectory: true) - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let coordinator = JavaLanguageServerPreparationCoordinator() - var configuration = JavaLanguageImportConfiguration() - manager.configureJavaLanguageImportProvider { _, _ in configuration } - defer { coordinator.cancelMavenConfigurationSynchronization(); manager.stopAllLanguageServers() } - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - #expect(session.starts.first?.mavenContext == nil) - - configuration = JavaLanguageImportConfiguration(mavenContext: pluginMavenContext(profiles: ["plugin"])) - let restarted = TestGate() - defer { restarted.open() } - session.onStart = { restarted.open() } - let recovery = coordinator.synchronizeMavenConfiguration( - sessions: manager, workspaceURL: root, - languageImportPreparation: {}, ownsWorkspace: { true } - ) - defer { recovery.cancel() } - try #require(await restarted.waitUntilOpen(), "Rejected Maven update did not restart Java") - #expect(session.stopCount == 1) - #expect(session.starts.count == 2) - #expect(session.starts.last?.mavenContext == configuration.mavenContext) - session.publish(.ready) - try await awaitImportSynchronization(recovery) - #expect(manager.languageServerStates["java"] == .ready) - - configuration = JavaLanguageImportConfiguration(mavenContext: pluginMavenContext(profiles: ["next"])) - session.mavenUpdateResult = .success(.init(settingsChanged: false, projectsReloaded: false, profilesUpdating: true)) - let update = coordinator.synchronizeMavenConfiguration( - sessions: manager, workspaceURL: root, - languageImportPreparation: {}, ownsWorkspace: { true } - ) - try await awaitImportSynchronization(update) - #expect(session.starts.count == 2) - #expect(session.updates.last?.profiles == ["next"]) - } - - @Test - @MainActor - func newerPluginImportJoinsCancelledRecoveryBeforeRestarting() async throws { - let root = URL(fileURLWithPath: "/workspace/replaced-maven-recovery", isDirectory: true) - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let coordinator = JavaLanguageServerPreparationCoordinator() - var configuration = JavaLanguageImportConfiguration() - manager.configureJavaLanguageImportProvider { _, _ in configuration } - defer { coordinator.cancelMavenConfigurationSynchronization(); manager.stopAllLanguageServers() } - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - configuration = .init(mavenContext: pluginMavenContext(profiles: ["first"])) - let firstRestart = TestGate() - session.onStart = { firstRestart.open() } - let first = coordinator.synchronizeMavenConfiguration( - sessions: manager, workspaceURL: root, - languageImportPreparation: {}, ownsWorkspace: { true } - ) - defer { first.cancel() } - try #require(await firstRestart.waitUntilOpen(), "First recovery did not reach its new session") - configuration = .init(mavenContext: pluginMavenContext(profiles: ["latest"])) - let nextRestart = TestGate() - session.onStart = { nextRestart.open() } - let next = coordinator.synchronizeMavenConfiguration( - sessions: manager, workspaceURL: root, - languageImportPreparation: {}, ownsWorkspace: { true } - ) - defer { next.cancel() } - try #require(await nextRestart.waitUntilOpen(), "Latest selection did not replace cancelled recovery") - #expect(session.starts.count == 3) - #expect(session.stopCount == 2) - #expect(session.starts.last?.mavenContext?.profiles == ["latest"]) - session.publish(.ready) - try await awaitImportSynchronization(first) - try await awaitImportSynchronization(next) - #expect(manager.languageServerStates["java"] == .ready) - #expect(session.isRunning) - } - - @Test(arguments: [false, true]) - @MainActor - func pluginImportRecoveryDoesNotStartAfterCancellationOrWorkspaceReopen(cancel: Bool) async throws { - let root = URL(fileURLWithPath: "/workspace/stale-maven-import", isDirectory: true) - let identity = WorkspaceIdentity(url: root, generation: 1) - var current = identity - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let coordinator = JavaLanguageServerPreparationCoordinator() - manager.configureJavaLanguageImportProvider { _, _ in - .init(mavenContext: pluginMavenContext(profiles: ["plugin"])) - } - try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - let waiting = TestGate(), release = TestGate() - defer { - release.open(); coordinator.cancelMavenConfigurationSynchronization() - manager.stopAllLanguageServers() - } - let task = coordinator.synchronizeMavenConfiguration( - sessions: manager, workspaceURL: root, - languageImportPreparation: { - waiting.open() - _ = await release.waitUntilOpen() - }, - ownsWorkspace: { current == identity } - ) - defer { task.cancel() } - try #require(await waiting.waitUntilOpen(), "Import preparation did not begin") - if cancel { coordinator.cancelMavenConfigurationSynchronization() } - else { current = WorkspaceIdentity(url: root, generation: 2) } - release.open() - try await awaitImportSynchronization(task) - #expect(session.starts.count == 1) - #expect(session.updates.isEmpty) - #expect(session.stopCount == 0) - } - - @MainActor - private func awaitImportSynchronization(_ task: Task) async throws { - let finished = TestGate() - let observer = Task { await task.value; finished.open() } - defer { observer.cancel(); task.cancel() } - try #require(await finished.waitUntilOpen(), "Import synchronization did not terminate") - await observer.value - } - - @Test(arguments: [false, true]) - @MainActor - func acceptedVirtualImplementationSurvivesChooserDismissal(cancelWhileLoading: Bool) async throws { - let root = URL(fileURLWithPath: "/workspace/virtual-navigation", isDirectory: true) - let session = JavaImportTestSession() - let manager = try javaImportManager(root: root, session: session) - let store = JavaLanguageServerTestStore() - let settings = AppSettings(store: store) - let container = MacServiceContainer(store: store, settings: settings, moduleLaunchMode: .safeMode) - defer { container.moduleLifecycleCoordinator.stop(); manager.stopAllLanguageServers() } - let model = AppModel(settings: settings, services: container.services) - let runtime = ModuleRuntime() - let graph = NavigationTestLanguageGraph(sessions: manager, store: store) - let module = LanguageIntelligenceModule(makeGraph: { graph }) - // The fixture activates only this module; no workspace services or real server. - try runtime.register(ModuleFactory(manifest: ModuleManifest( - id: .languageIntelligence, displayName: "Navigation test", scope: .workspace, - providedCapabilities: [.languageIntelligence]), - contributions: LanguageIntelligenceModule.moduleContributions) { module }) - var reply: ((Result) -> Void)? - session.onVirtualDocument = { reply = $0 } - try await WorkbenchTestScope.withCleanup({ - reply?(.failure(CancellationError())); reply = nil - session.onVirtualDocument = nil - await model.shutdownProjectSession() - await runtime.shutdownAll() - }) { scope in - try await scope.run("accept implementation and resolve delayed virtual source") { - _ = try await runtime.activate(.languageIntelligence) - model.cacheModuleCapability(try #require(module.exportedCapabilities()[.languageIntelligence]), - id: .languageIntelligence, moduleID: .languageIntelligence) - _ = try manager.startLanguageServer(providerID: "java", rootURL: root) - session.publish(.ready) - let uri = try #require(URL(string: "jdt://contents/library/Target.class")) - let values = [uri, try #require(URL(string: "jdt://contents/library/Other.class"))].map { - LanguageServerLocation(url: $0, range: .init(start: .init(line: 3, utf16Column: 4), - end: .init(line: 3, utf16Column: 10))) - } - model.languageNavigationCoordinator.handleResult(values, providerID: "java", kind: .implementations, - onEmpty: { Issue.record("Expected implementation targets") }, - onResults: { _ in model.presentLanguageNavigationResults(.implementations) }) - try #require(model.isImplementationChooserVisible) - let selected = try #require(model.languageNavigationCoordinator.state.locations.first) - model.navigate(to: selected) - try #require(!model.isImplementationChooserVisible) - let completion = try #require(reply, "Selection must request virtual source") - reply = nil - // The shared dropdown calls its binding after navigate has hidden it. - model.dismissImplementationChooser() - if cancelWhileLoading { model.closeLanguageNavigationResults() } - completion(.success("class Target {}")) - if cancelWhileLoading { - #expect(!model.openDocuments.contains { $0.url == uri }) - #expect(model.editorNavigationTarget == nil) - } else { - let document = try #require(model.openDocuments.first { $0.url == uri }) - #expect(document.text == "class Target {}") - #expect(document.isReadOnly) - #expect(model.editorNavigationTarget?.url == uri) - #expect(model.editorNavigationTarget?.line == 3) - } - model.presentLanguageNavigationResults(.implementations) - let cancelled = model.languageNavigationCoordinator.begin(providerID: "java", kind: .implementations) - model.dismissImplementationChooser() - #expect(!model.isImplementationChooserVisible) - #expect(!model.languageNavigationCoordinator.owns(cancelled)) - } - } - } - - @MainActor - private func javaImportManager(root: URL, session: JavaImportTestSession) throws -> LanguageToolingSessionManager { - let descriptor = try #require(LanguageProviderCatalog.compatibilityFallback.provider(for: root.appendingPathComponent("Main.java"))) - return LanguageToolingSessionManager(runtimes: [JavaImportTestRuntime(descriptor: descriptor, session: session)]) - } - - private func pluginMavenContext(profiles: [String]) -> MavenLaunchContext { - MavenLaunchContext(reactorPath: ".", profiles: profiles, settingsPath: nil, skipTests: false, - mavenExecutablePath: nil, javaHomePath: nil) - } - - private func javaRuntime(_ homePath: String, _ version: String) -> JavaRuntimeCandidate { - JavaRuntimeCandidate(homePath: homePath, version: version, vendor: "Test JDK") - } -} - -@MainActor -private final class JavaImportTestRuntime: LanguageProviderRuntime { - let descriptor: LanguageProviderDescriptor - let supportsLanguageServerSession = true - let session: JavaImportTestSession - - init(descriptor: LanguageProviderDescriptor, session: JavaImportTestSession) { - self.descriptor = descriptor - self.session = session - } - - func makeLanguageServerSession() -> (any LanguageServerSession)? { session } -} - -@MainActor -private final class JavaImportTestSession: LanguageServerSession { - var isRunning = false - var javaTestRunnerURL: URL? { nil } - var onDiagnostics: ((URL, [LanguageServerDiagnostic]) -> Void)? - var onStateChange: ((LanguageServerSessionState) -> Void)? - var onStart: (() -> Void)? - var onVirtualDocument: ((@escaping (Result) -> Void) -> Void)? - private(set) var starts: [JavaLanguageImportConfiguration] = [] - private(set) var stopCount = 0 - private(set) var updates: [MavenLaunchContext] = [] - var mavenUpdateResult: Result = - .failure(.init(code: "invalidMavenContext", message: "Session started without Maven inputs")) - - func start(rootURL: URL, workspaceFingerprint: String?) throws { - try start(rootURL: rootURL, workspaceFingerprint: workspaceFingerprint, mavenContext: nil, javaGradle: nil) - } - - func start(rootURL: URL, workspaceFingerprint: String?, mavenContext: MavenLaunchContext?, - javaGradle: JavaGradleImportConfiguration?) throws { - starts.append(.init(mavenContext: mavenContext, javaGradle: javaGradle)) - isRunning = true - onStart?() - } - - func publish(_ state: LanguageServerSessionState) { onStateChange?(state) } - - func updateMavenConfiguration(_ context: MavenLaunchContext, reloadProjects: Bool) - -> Result { - updates.append(context) - return mavenUpdateResult - } - - func stop() { isRunning = false; stopCount += 1 } - func synchronize(fileURL: URL, text: String, languageID: String) throws {} - func completions(fileURL: URL, position: LanguageServerPosition, - completion: @escaping (Result<[LanguageServerCompletionItem], Error>) -> Void) throws { completion(.success([])) } - func hover(fileURL: URL, position: LanguageServerPosition, - completion: @escaping (Result) -> Void) throws { completion(.success(nil)) } - func navigate(method: String, fileURL: URL, position: LanguageServerPosition, - completion: @escaping (Result<[LanguageServerLocation], Error>) -> Void) throws { completion(.success([])) } - func rename(fileURL: URL, position: LanguageServerPosition, newName: String, - completion: @escaping (Result) -> Void) throws { completion(.success(.init())) } - func format(fileURL: URL, - completion: @escaping (Result<[LanguageServerTextEdit], Error>) -> Void) throws { completion(.success([])) } - func codeActions(fileURL: URL, range: LanguageServerRange, diagnostics: [LanguageServerDiagnostic], - completion: @escaping (Result<[LanguageServerCodeAction], Error>) -> Void) throws { completion(.success([])) } - func resolveCompletion(_ item: LanguageServerCompletionItem, fileURL: URL, - completion: @escaping (Result) -> Void) throws { completion(.success(item)) } - func resolveCodeAction(_ action: LanguageServerCodeAction, fileURL: URL, - completion: @escaping (Result) -> Void) throws { completion(.success(action)) } - func execute(_ command: LanguageServerCommand, fileURL: URL, - completion: @escaping (Result) -> Void) throws { completion(.success(())) } - func resolveVirtualDocument(uri: String, - completion: @escaping (Result) -> Void) throws { - if let onVirtualDocument { onVirtualDocument(completion) } - else { completion(.success("")) } - } - func javaEntrypoints(completion: @escaping (Result) -> Void) throws { throw CancellationError() } -} - -private struct JavaLanguageServerTestRuntimeLocator: RuntimeLocator { - let runtimes: [JavaRuntimeCandidate] - - func environment() -> [String: String] { [:] } - - func discover() -> RuntimeDiscoveryResult { - return RuntimeDiscoveryResult(javaRuntimes: runtimes, mavenRuntimes: []) - } - - func validJavaHome(path: String) -> URL? { - runtimes.contains(where: { $0.homePath == path }) - ? URL(fileURLWithPath: path, isDirectory: true) - : nil - } - - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { - runtimes.first(where: { $0.homePath == homeURL.standardizedFileURL.path }) - } - - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} - -private struct JavaLanguageServerTestStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} - func removeObject(forKey key: String) {} -} - -@MainActor -private final class NavigationTestLanguageGraph: LanguageIntelligenceServiceGraph { - let sessions: LanguageToolingSessionManager - let tools: LanguageServerToolService - var hasActiveLanguageServers: Bool { !sessions.activeLanguageServerIDs.isEmpty } - init(sessions: LanguageToolingSessionManager, store: JavaLanguageServerTestStore) { - self.sessions = sessions - tools = LanguageServerToolService( - runtimeService: ProjectRuntimeService(runtimeLocator: JavaLanguageServerTestRuntimeLocator(runtimes: []), store: store), - commandRunner: MacProcessRunner(), settingsStore: MacLanguageToolSettingsStore(store: store)) - } - func activate(context: ModuleContext) {} - func prepareForSleep() async throws {} - func stop() async { sessions.stopAllLanguageServers() } -} diff --git a/macos/Tests/LitheTests/JavaTestDebugLaunchServiceTests.swift b/macos/Tests/LitheTests/JavaTestDebugLaunchServiceTests.swift deleted file mode 100644 index 6cf5bd35ff..0000000000 --- a/macos/Tests/LitheTests/JavaTestDebugLaunchServiceTests.swift +++ /dev/null @@ -1,366 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheExecutionModule -import Testing -@testable import Lithe - -@Suite("Java test debug launch workflow") -@MainActor -struct JavaTestDebugLaunchServiceTests { - @Test - func stoppingOrReplacingRunPreparationRevokesIdenticalSelections() { - let state = JavaTestWorkflowState(notify: { _ in }) - let first = state.beginRunPreparation() - let next = state.beginRunPreparation() - state.finishRunPreparation(first) - #expect(!state.isCurrentRunPreparation(first)) - #expect(state.isCurrentRunPreparation(next)) - state.cancelRunPreparation() - #expect(!state.isCurrentRunPreparation(next)) - } - - @Test - func cancelledDebugTestCannotPrepareAfterTheSaveFinishes() async throws { - let state = JavaTestWorkflowState(notify: { _ in }) - let coordinator = JavaTestDebugWorkflowCoordinator(notify: { _ in }) - let saving = TestGate(), release = TestGate() - var launches = 0 - coordinator.start(request: JavaTestDebugRequest(fileURL: URL(fileURLWithPath: "/workspace/Test.java"), testIdentifier: nil), state: state, - prepareDirtyDocument: { saving.open(); return await release.waitUntilOpen(timeout: .seconds(2)) }, - prepareLaunch: { launches += 1; throw CancellationError() }, startDebug: { _ in false }, errorMessage: { nil }) - let task = try #require(state.debugLaunchTask) - defer { state.cancelDebugLaunch(); release.open() } - try #require(await saving.waitUntilOpen(timeout: .seconds(2))) - state.cancelDebugLaunch() - release.open() - await task.value - #expect(launches == 0) - #expect(state.resultServer == nil) - } - - @Test - func fileSelectionResolvesTargetStartsResultsAndBuildsSharedConfiguration() async throws { - let root = URL(fileURLWithPath: "/workspace/java-tests", isDirectory: true) - let source = root.appendingPathComponent( - "src/test/java/example/UserServiceTest.java" - ) - let target = javaTestTarget(fileURL: source) - let targetResolver = TestJavaTestTargetResolver(target: target) - let resultServer = TestJavaTestResultServer(port: 43_128) - let expectedConfiguration = DebugLaunchConfiguration( - name: "UserServiceTest", - request: .launch, - arguments: ["mainClass": .string(target.mainClass)] - ) - let core = TestJavaTestLaunchCore(result: .success(expectedConfiguration)) - let service = JavaTestDebugLaunchService( - configurationResolver: DebugLaunchConfigurationResolver( - javaTestLaunchResolver: core - ), - resultServerFactory: { resultServer } - ) - - let prepared = try await service.prepare( - fileURL: source, - testIdentifier: "service@example.UserServiceTest#logsIn", - rootURL: root, - targetResolver: targetResolver - ) - - #expect(targetResolver.requests == [TestJavaTestTargetResolver.Request( - fileURL: source, - testIdentifier: "service@example.UserServiceTest#logsIn", - rootURL: root - )]) - #expect(resultServer.startCount == 1) - #expect(resultServer.stopCount == 0) - #expect(core.requests == [TestJavaTestLaunchCore.Request( - target: target, - resultPort: 43_128 - )]) - #expect(prepared.target == target) - #expect(prepared.configuration == expectedConfiguration) - - prepared.stop() - #expect(resultServer.stopCount == 1) - } - - @Test - func sharedConfigurationFailureStopsTheResultServer() async { - let source = URL(fileURLWithPath: "/workspace/UserServiceTest.java") - let resultServer = TestJavaTestResultServer(port: 43_128) - let service = JavaTestDebugLaunchService( - configurationResolver: DebugLaunchConfigurationResolver( - javaTestLaunchResolver: TestJavaTestLaunchCore( - result: .failure(TestJavaTestDebugError.configurationFailed) - ) - ), - resultServerFactory: { resultServer } - ) - - await #expect(throws: TestJavaTestDebugError.configurationFailed) { - _ = try await service.prepare( - fileURL: source, - testIdentifier: nil, - rootURL: source.deletingLastPathComponent(), - targetResolver: TestJavaTestTargetResolver( - target: javaTestTarget(fileURL: source) - ) - ) - } - #expect(resultServer.startCount == 1) - #expect(resultServer.stopCount == 1) - } - - @Test - func workspaceSelectionIsRejectedBeforeStartingAnAsyncLaunch() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-java-test-debug-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } - let store = JavaTestDebugStore() - let settings = AppSettings(store: store) - let model = AppModel( - settings: settings, - services: MacServiceContainer( - store: store, - settings: settings, - moduleLaunchMode: .safeMode - ).services - ) - model.openProjectDirectly(root) - model.clearNotifications() - - model.debugTest(providerID: "java", scope: .workspace) - - #expect(model.activeNotifications.last?.message == "Select a Java test file or test case to debug") - #expect(model.javaTestWorkflowState.debugLaunchTask == nil) - #expect(model.javaTestWorkflowState.debugLaunchOperationID == nil) - } - - @Test - func stoppingDebuggingReleasesTheJavaTestResultServer() { - let store = JavaTestDebugStore() - let settings = AppSettings(store: store) - let model = AppModel( - settings: settings, - services: MacServiceContainer( - store: store, - settings: settings, - moduleLaunchMode: .safeMode - ).services - ) - let resultServer = TestJavaTestResultServer(port: 43_128) - model.javaTestWorkflowState.resultServer = resultServer - - model.stopDebugging() - - #expect(resultServer.stopCount == 1) - #expect(model.javaTestWorkflowState.resultServer == nil) - } - - @Test - func terminalDebugStateReleasesTheJavaTestResultServer() { - let store = JavaTestDebugStore() - let settings = AppSettings(store: store) - let model = AppModel( - settings: settings, - services: MacServiceContainer( - store: store, - settings: settings, - moduleLaunchMode: .safeMode - ).services - ) - let resultServer = TestJavaTestResultServer(port: 43_128) - model.javaTestWorkflowState.resultServer = resultServer - model.isTerminalVisible = true - - model.handleDebugSessionStateChange(.running) - #expect(resultServer.stopCount == 0) - #expect(model.javaTestWorkflowState.resultServer != nil) - #expect(model.isDebugVisible) - #expect(!model.isTerminalVisible) - - model.handleDebugSessionStateChange(.terminated) - #expect(resultServer.stopCount == 1) - #expect(model.javaTestWorkflowState.resultServer == nil) - } - - @Test - func workflowCoordinatorCleansUpWhenGenericDebugStartFails() async { - let notifications = NotificationSpy() - let state = JavaTestWorkflowState(notify: notifications.notify) - let coordinator = JavaTestDebugWorkflowCoordinator(notify: notifications.notify) - let actions = WorkflowActionsSpy() - coordinator.connect(actions: actions) - let resultServer = TestJavaTestResultServer(port: 43_128) - let prepared = PreparedJavaTestDebugLaunch( - target: javaTestTarget( - fileURL: URL(fileURLWithPath: "/workspace/UserServiceTest.java") - ), - configuration: DebugLaunchConfiguration( - name: "UserServiceTest", - request: .launch, - arguments: [:] - ), - resultServer: resultServer - ) - - coordinator.start( - request: JavaTestDebugRequest( - fileURL: prepared.target.fileURL, - testIdentifier: nil - ), - state: state, - prepareDirtyDocument: { true }, - prepareLaunch: { prepared }, - startDebug: { _ in false }, - errorMessage: { "debug launch failed" } - ) - await Task.yield() - await Task.yield() - - #expect(resultServer.stopCount == 1) - #expect(state.resultServer == nil) - #expect(notifications.messages == ["debug launch failed"]) - #expect(!actions.events.contains("show-debug")) - } - - @Test - func pausedDebugStateShowsDebuggerAndActivatesApplication() { - let store = JavaTestDebugStore() - let settings = AppSettings(store: store) - let platformUI = DebugActivationPlatformUI() - let model = AppModel( - settings: settings, - services: MacServiceContainer( - store: store, - settings: settings, - moduleLaunchMode: .safeMode, - platformUI: platformUI - ).services - ) - - model.handleDebugSessionStateChange(.paused) - - #expect(model.isDebugVisible) - #expect(platformUI.activationCount == 1) - } - - private func javaTestTarget(fileURL: URL) -> JavaTestDebugLaunchTarget { - JavaTestDebugLaunchTarget( - fileURL: fileURL, - name: "UserServiceTest", - framework: .junit, - workingDirectory: fileURL.deletingLastPathComponent().path, - mainClass: "org.eclipse.jdt.internal.junit.runner.RemoteTestRunner", - projectName: "service", - classPaths: ["/workspace/classes"], - modulePaths: [], - vmArguments: [], - programArguments: ["-port", "-1"] - ) - } -} - -@MainActor -private final class DebugActivationPlatformUI: PlatformUI { - private(set) var activationCount = 0 - - func activateApplication() { - activationCount += 1 - } - - func chooseDirectory(title: String, prompt: String) -> URL? { nil } - func chooseFile(title: String, prompt: String) -> URL? { nil } - func revealInFileBrowser(_ url: URL) {} - func open(_ url: URL) {} - func copyToClipboard(_ value: String) {} - func markdownImageFromClipboard() -> MarkdownImageSource? { nil } -} - -@MainActor -private final class TestJavaTestTargetResolver: JavaTestDebugLaunchTargetResolving { - struct Request: Equatable { - let fileURL: URL - let testIdentifier: String? - let rootURL: URL - } - - private let target: JavaTestDebugLaunchTarget - private(set) var requests: [Request] = [] - - init(target: JavaTestDebugLaunchTarget) { - self.target = target - } - - func resolveJavaTestDebugLaunchTarget( - fileURL: URL, - testIdentifier: String?, - rootURL: URL - ) async throws -> JavaTestDebugLaunchTarget { - requests.append(Request( - fileURL: fileURL.standardizedFileURL, - testIdentifier: testIdentifier, - rootURL: rootURL.standardizedFileURL - )) - return target - } -} - -@MainActor -private final class TestJavaTestResultServer: JavaTestResultServing { - private let port: UInt16 - private(set) var startCount = 0 - private(set) var stopCount = 0 - - init(port: UInt16) { - self.port = port - } - - func start() async throws -> UInt16 { - startCount += 1 - return port - } - - func stop() { - stopCount += 1 - } -} - -@MainActor -private final class TestJavaTestLaunchCore: JavaTestDebugLaunchResolving, @unchecked Sendable { - struct Request: Equatable { - let target: JavaTestDebugLaunchTarget - let resultPort: UInt16 - } - - private let result: Result - private(set) var requests: [Request] = [] - - init(result: Result) { - self.result = result - } - - func resolveJavaTestDebugLaunch( - target: JavaTestDebugLaunchTarget, - resultPort: UInt16 - ) throws -> DebugLaunchConfiguration { - requests.append(Request(target: target, resultPort: resultPort)) - return try result.get() - } -} - -private enum TestJavaTestDebugError: Error, Equatable { - case configurationFailed -} - -private final class JavaTestDebugStore: KeyValueStore, @unchecked Sendable { - private var values: [String: Any] = [:] - - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } -} diff --git a/macos/Tests/LitheTests/KeyboardShortcutTests.swift b/macos/Tests/LitheTests/KeyboardShortcutTests.swift index 1146c2dd21..4c83706d73 100644 --- a/macos/Tests/LitheTests/KeyboardShortcutTests.swift +++ b/macos/Tests/LitheTests/KeyboardShortcutTests.swift @@ -8,7 +8,7 @@ struct KeyboardShortcutTests { @Test func catalogHasStableUniqueCommandsAndConflictFreeDefaults() throws { let commands = LitheCommandCatalog.commands - #expect(commands.count == 41) + #expect(commands.count == 39) let startOrContinue = try #require(LitheCommandCatalog.command(id: "debug-start-or-continue")) #expect(startOrContinue.defaultBindings.isEmpty) #expect(LitheCommandCatalog.moduleOwner(for: startOrContinue.id) == .debug) @@ -18,8 +18,6 @@ struct KeyboardShortcutTests { for preset in [KeyboardShortcutPreset.ideaClassic, .eclipse] { #expect(preset.bindings(for: findAction).isEmpty) } - // Build plugin windows own their actions; Maven is no longer a built-in command. - #expect(LitheCommandCatalog.command(id: "toggle-maven") == nil) #expect(Set(commands.map(\.id)).count == commands.count) let owners = commands.flatMap { command in @@ -119,8 +117,6 @@ struct KeyboardShortcutTests { #expect(actionIDs.contains("navigate-forward")) #expect(actionIDs.contains("go-to-definition")) #expect(actionIDs.contains("go-to-implementation")) - #expect(actionIDs.contains("rebuild-java-index")) - #expect(actionIDs.contains("spring-endpoints")) #expect(actionIDs.contains("toggle-breakpoint")) #expect(actionIDs.contains("view-breakpoints")) } diff --git a/macos/Tests/LitheTests/LSPControlCenterPresentationTests.swift b/macos/Tests/LitheTests/LSPControlCenterPresentationTests.swift index 47350e48d1..bcbe6bc2b6 100644 --- a/macos/Tests/LitheTests/LSPControlCenterPresentationTests.swift +++ b/macos/Tests/LitheTests/LSPControlCenterPresentationTests.swift @@ -92,20 +92,4 @@ struct LSPControlCenterPresentationTests { isActive: true ) == .active) } - - @Test - func mavenProfileResultsExposeApplyingAndPartialFailureStates() { - let projectA = URL(string: "file:///workspace/module-a")! - let projectB = URL(string: "file:///workspace/module-b")! - #expect(LSPControlCenterPresenter.mavenProfileState([ - MavenProfileProjectResult(projectURI: projectA, status: "running") - ]) == .applying) - #expect(LSPControlCenterPresenter.mavenProfileState([ - MavenProfileProjectResult(projectURI: projectA, status: "failed", errorDetails: "bad pom"), - MavenProfileProjectResult(projectURI: projectB, status: "succeeded") - ]) == .partiallyFailed(failed: 1, total: 2)) - #expect(LSPControlCenterPresenter.mavenProfileState([ - MavenProfileProjectResult(projectURI: projectA, status: "succeeded") - ]) == .complete) - } } diff --git a/macos/Tests/LitheTests/LSPProjectUsageTests.swift b/macos/Tests/LitheTests/LSPProjectUsageTests.swift index 41c9133064..84ce8394b9 100644 --- a/macos/Tests/LitheTests/LSPProjectUsageTests.swift +++ b/macos/Tests/LitheTests/LSPProjectUsageTests.swift @@ -9,13 +9,13 @@ import Testing struct LSPProjectUsageTests { @Test func indexedMatchingPreservesProviderAndPluginSemantics() throws { let providers = [ - provider("source", extensions: ["JAVA", "py"]), + provider("source", extensions: ["RS", "py"]), provider("named", names: ["Makefile", "文档 % #.txt", ".toolrc"]), provider("prefix", prefixes: ["Dockerfile", ".env."]), provider("missing", extensions: ["absent"]), provider("emptyExtension", extensions: [""]) ] - let files = ["中文/Foo.JAVA", "a/test.PY", "b/Makefile", "c/文档 % #.txt", "d/.toolrc", + let files = ["中文/Foo.RS", "a/test.PY", "b/Makefile", "c/文档 % #.txt", "d/.toolrc", "e/Dockerfile.prod", "f/.ENV.local", "g/README", "h/unrelated.bin"] .map { URL(fileURLWithPath: "/fixture/" + $0) } let rules = providers.map { @@ -28,11 +28,11 @@ struct LSPProjectUsageTests { } @Test func pluginProjectNamesAndSourceExtensionsShareTheSamePass() throws { - let files = ["pom.xml", "build.gradle.kts", "GO.MOD", "composer.json", "view.PHTML"] + let files = ["GO.MOD", "composer.json", "view.PHTML", "README"] .map { URL(fileURLWithPath: "/fixture/" + $0) } let summary = try #require(LSPProjectUsageScanner.scan(files: files, rules: pluginRules())) #expect(summary.pluginIDs == expectedPluginIDs(files)) - #expect(summary.pluginIDs.count == 3) + #expect(summary.pluginIDs.count == 2) } @Test func emptyAndUnmatchedInventoriesProduceACompletedEmptySummary() { @@ -43,7 +43,7 @@ struct LSPProjectUsageTests { @Test func requestIdentityUsesSnapshotAndNormalizedRulesRatherThanFileCount() { let snapshot = UUID() - let a = LSPProjectUsageRequest.Rule(target: .provider("a"), fileExtensions: ["JAVA"], fileNamePrefixes: ["Dockerfile"]) + let a = LSPProjectUsageRequest.Rule(target: .provider("a"), fileExtensions: ["RS"], fileNamePrefixes: ["Dockerfile"]) let b = LSPProjectUsageRequest.Rule(target: .plugin("b"), fileExtensions: [], fileNames: ["Makefile"]) let first = request(snapshot: snapshot, rules: [a, b]) #expect(first == request(snapshot: snapshot, rules: [b, a])) @@ -143,20 +143,20 @@ struct LSPProjectUsageTests { } defer { first.cancel(); release.open(); releaseWait.cancel(); model.reset() } #expect(await entered.waitUntilOpen()) - await model.load(newest, files: [URL(fileURLWithPath: "/fixture/pom.xml")]) + await model.load(newest, files: [URL(fileURLWithPath: "/fixture/composer.json")]) #expect(await firstFinished.waitUntilOpen()) #expect(!release.isOpen) #expect(!returned.isOpen) await first.value #expect(model.summary(for: old) == nil) - #expect(model.summary(for: newest)?.pluginIDs == [OfficialPluginCatalog.javaPluginID.rawValue]) + #expect(model.summary(for: newest)?.pluginIDs == [OfficialPluginCatalog.phpPluginID.rawValue]) #expect(await probe.maximumActive == 2) release.open() #expect(await releaseWait.value) #expect(await returned.waitUntilOpen()) await model.load(newest, files: []) #expect(model.summary(for: old) == nil) - #expect(model.summary(for: newest)?.pluginIDs == [OfficialPluginCatalog.javaPluginID.rawValue]) + #expect(model.summary(for: newest)?.pluginIDs == [OfficialPluginCatalog.phpPluginID.rawValue]) #expect(await probe.calls == 2) } @@ -179,8 +179,8 @@ struct LSPProjectUsageTests { #expect(!release.isOpen) #expect(model.state == .idle) #expect(model.summary(for: input) == nil) - await model.load(input, files: [URL(fileURLWithPath: "/fixture/pom.xml")]) - #expect(model.summary(for: input)?.pluginIDs == [OfficialPluginCatalog.javaPluginID.rawValue]) + await model.load(input, files: [URL(fileURLWithPath: "/fixture/composer.json")]) + #expect(model.summary(for: input)?.pluginIDs == [OfficialPluginCatalog.phpPluginID.rawValue]) await task.value release.open() #expect(await releaseWait.value) diff --git a/macos/Tests/LitheTests/LanguageExtensionProcessLifecycleTests.swift b/macos/Tests/LitheTests/LanguageExtensionProcessLifecycleTests.swift index e764d172ed..403eb6fbd2 100644 --- a/macos/Tests/LitheTests/LanguageExtensionProcessLifecycleTests.swift +++ b/macos/Tests/LitheTests/LanguageExtensionProcessLifecycleTests.swift @@ -155,8 +155,43 @@ struct LanguageExtensionProcessLifecycleTests { .appendingPathComponent("lithe-runtime-launch-\(UUID().uuidString)", isDirectory: true) defer { try? FileManager.default.removeItem(at: root) } let operations = DeclarativePluginTestSupport.operations - let descriptor = try operations.validate(manifest: Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot - .appendingPathComponent("shared/contracts/plugins/v1/fixtures/languages/language-host-integration.plugin.json"))) + let descriptor = try operations.validate(manifest: Data(""" + { + "schemaVersion": 2, + "id": "dev.lithe.fixture.language-packaged-runtime", + "displayName": "Packaged Runtime Language Server Fixture", + "version": "1.0.0", + "pluginAPIVersion": 2, + "vendor": { + "id": "dev.lithe", + "displayName": "Lithe", + "signatureRequirement": "publisherPackage" + }, + "permissions": ["languageServer.launch"], + "activationEvents": ["onLanguage:example"], + "languages": [ + { + "id": "example", + "displayName": "Example", + "fileExtensions": ["example"], + "projectFileNames": ["example.project"] + } + ], + "languageServers": [ + { + "languageID": "example", + "languageIdentifier": "example", + "launch": { + "kind": "runtime", + "tool": "example-runtime", + "packagedRuntime": "runtime/${arch}/bin/example-runtime", + "runtimeArguments": ["--verbose"], + "entry": "language-server/server.bin" + } + } + ] + } + """.utf8)) let packageURL = root.appendingPathComponent("package", isDirectory: true) let installed = InstalledPluginPackage( descriptor: descriptor, @@ -184,23 +219,23 @@ struct LanguageExtensionProcessLifecycleTests { ) { try runtime.register(factory) } - let moduleID = ModuleID.languageServerExtension("java") + let moduleID = ModuleID.languageServerExtension("example") try await runtime.setEnabled(true, for: moduleID) let provider = try #require( - try await runtime.activateCapability(.languageServerExtension("java")) + try await runtime.activateCapability(.languageServerExtension("example")) as? any LanguageServerExtensionProviding ) let configuration = provider.configuration // The shipped runtime is the only executable; the tool name is for // display and is never looked up on the machine. - #expect(configuration.executableNames == ["java"]) + #expect(configuration.executableNames == ["example-runtime"]) #expect(configuration.executableURL == packageURL.appendingPathComponent( - "runtime/\(MacPluginLanguageServerLaunchResolver.hostArchitecture)/bin/java" + "runtime/\(MacPluginLanguageServerLaunchResolver.hostArchitecture)/bin/example-runtime" ).standardizedFileURL) #expect(configuration.launchSource?.packageURL == packageURL) - #expect(configuration.launchSource?.languageID == "java") + #expect(configuration.launchSource?.languageID == "example") #expect(configuration.executableVersionRequirement == nil) // Activating the module must not create plugin state. #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("state").path)) diff --git a/macos/Tests/LitheTests/LanguageNavigationCoordinatorTests.swift b/macos/Tests/LitheTests/LanguageNavigationCoordinatorTests.swift index 73f83f5f55..fb962d3e37 100644 --- a/macos/Tests/LitheTests/LanguageNavigationCoordinatorTests.swift +++ b/macos/Tests/LitheTests/LanguageNavigationCoordinatorTests.swift @@ -44,7 +44,7 @@ struct LanguageNavigationCoordinatorTests { #expect(decision(linkedLibrary) == .externalReadOnly) #expect(decision(library) == .externalReadOnly) #expect(decision(credentials) == .rejected) - #expect(decision(URL(string: "jdt://contents/rt.jar/java.lang/String.class")!) == .workspace) + #expect(decision(URL(string: "virtual://contents/archive.zip/Example.txt")!) == .workspace) } /// `/outside/link.go -> /workspace/main.go` resolves inside the workspace, @@ -86,7 +86,7 @@ struct LanguageNavigationCoordinatorTests { @MainActor func projectsLocations() { let coordinator = LanguageNavigationCoordinator(notify: { _ in }) - let url = URL(fileURLWithPath: "/workspace/Source.java") + let url = URL(fileURLWithPath: "/workspace/Source.txt") let values = [ LanguageServerLocation( url: url, @@ -95,7 +95,7 @@ struct LanguageNavigationCoordinatorTests { end: LanguageServerPosition(line: 4, utf16Column: 12) ), isReadOnly: false, - displayPath: "Source.java" + displayPath: "Source.txt" ) ] @@ -105,7 +105,7 @@ struct LanguageNavigationCoordinatorTests { #expect(locations[0].url == url) #expect(locations[0].line == 4) #expect(locations[0].utf16Column == 7) - #expect(locations[0].displayPath == "Source.java") + #expect(locations[0].displayPath == "Source.txt") } @Test("does not create a result state for an empty response") @@ -116,7 +116,7 @@ struct LanguageNavigationCoordinatorTests { #expect( coordinator.resultState( from: [], - providerID: "java", + providerID: "example", kind: .definitions ) == nil ) @@ -126,10 +126,10 @@ struct LanguageNavigationCoordinatorTests { @MainActor func loadingStateOwnsOperationID() { let coordinator = LanguageNavigationCoordinator(notify: { _ in }) - let operationID = coordinator.begin(providerID: "java", kind: .references) + let operationID = coordinator.begin(providerID: "example", kind: .references) #expect(coordinator.owns(operationID)) - #expect(coordinator.state.providerID == "java") + #expect(coordinator.state.providerID == "example") #expect(coordinator.state.kind == .references) } @@ -140,8 +140,8 @@ struct LanguageNavigationCoordinatorTests { func ignoresSupersededFailure() { var messages: [String] = [] let coordinator = LanguageNavigationCoordinator(notify: { messages.append($0) }) - let stale = coordinator.begin(providerID: "java", kind: .definitions) - let current = coordinator.begin(providerID: "java", kind: .references) + let stale = coordinator.begin(providerID: "example", kind: .definitions) + let current = coordinator.begin(providerID: "example", kind: .references) coordinator.fail(stale, message: "stale failure") @@ -156,7 +156,7 @@ struct LanguageNavigationCoordinatorTests { func clearsStateOnCurrentFailure() { var messages: [String] = [] let coordinator = LanguageNavigationCoordinator(notify: { messages.append($0) }) - let operationID = coordinator.begin(providerID: "java", kind: .definitions) + let operationID = coordinator.begin(providerID: "example", kind: .definitions) coordinator.fail(operationID, message: "definition failed") @@ -168,12 +168,12 @@ struct LanguageNavigationCoordinatorTests { @MainActor func reportsEmptyResponse() { let coordinator = LanguageNavigationCoordinator(notify: { _ in }) - coordinator.begin(providerID: "java", kind: .definitions) + coordinator.begin(providerID: "example", kind: .definitions) var events: [String] = [] coordinator.handleResult( [], - providerID: "java", + providerID: "example", kind: .definitions, onEmpty: { events.append("empty") }, onResults: { _ in Issue.record("no results were returned") } @@ -227,7 +227,7 @@ struct LanguageNavigationCoordinatorTests { @MainActor func decidesImplementationFallback() { let coordinator = LanguageNavigationCoordinator(notify: { _ in }) - let url = URL(fileURLWithPath: "/workspace/Main.java") + let url = URL(fileURLWithPath: "/workspace/Main.txt") let location = LanguageServerLocation( url: url, range: LanguageServerRange( @@ -261,61 +261,6 @@ struct LanguageNavigationCoordinatorTests { } } -@Suite("Java test workflow state") -struct JavaTestWorkflowStateTests { - @Test("resolves a Java test case request") - @MainActor - func resolvesTestCase() { - let state = JavaTestWorkflowState(notify: { _ in }) - let url = URL(fileURLWithPath: "/workspace/Test.java") - - let result = state.resolveDebugRequest( - providerID: "java", - scope: .testCase(identifier: "Example.test", fileURL: url) - ) - - guard case .resolved(let request) = result else { - Issue.record("expected a resolved Java test request") - return - } - #expect(request.fileURL == url.standardizedFileURL) - #expect(request.testIdentifier == "Example.test") - } - - @Test("rejects a workspace-wide Java debug request") - @MainActor - func rejectsWorkspaceRequest() { - let state = JavaTestWorkflowState(notify: { _ in }) - - guard case .rejected(let message) = state.resolveDebugRequest( - providerID: "java", - scope: .workspace - ) else { - Issue.record("expected workspace debugging to be rejected") - return - } - #expect(message == "Select a Java test file or test case to debug") - } - - @Test("does not require a save for an absent document") - @MainActor - func absentDocumentIsReady() async { - let notifications = NotificationSpy() - let state = JavaTestWorkflowState(notify: notifications.notify) - let actions = WorkflowActionsSpy() - - let ready = await state.prepareDirtyDocument( - fileURL: URL(fileURLWithPath: "/workspace/Test.java"), - documents: [], - saving: actions - ) - - #expect(ready) - #expect(actions.events.isEmpty) - #expect(notifications.messages.isEmpty) - } -} - @Suite("Language editing coordinator") struct LanguageEditingCoordinatorTests { @Test("normalizes language-server positions") @@ -348,7 +293,7 @@ struct LanguageEditingCoordinatorTests { @MainActor func buildsCompletionWorkspaceEdit() { let coordinator = LanguageEditingCoordinator(notify: { _ in }) - let url = URL(fileURLWithPath: "/workspace/Main.java") + let url = URL(fileURLWithPath: "/workspace/Main.txt") let fallbackRange = LanguageServerRange( start: LanguageServerPosition(line: 2, utf16Column: 1), end: LanguageServerPosition(line: 2, utf16Column: 4) @@ -502,7 +447,7 @@ struct LanguageEditingCoordinatorTests { let coordinator = LanguageEditingCoordinator( notify: { _ in Issue.record("unexpected notification") } ) - let url = URL(fileURLWithPath: "/workspace/Main.java") + let url = URL(fileURLWithPath: "/workspace/Main.txt") let edit = LanguageServerTextEdit( range: LanguageServerRange( start: LanguageServerPosition(line: 0, utf16Column: 0), diff --git a/macos/Tests/LitheTests/LanguageProviderCatalogSourceTests.swift b/macos/Tests/LitheTests/LanguageProviderCatalogSourceTests.swift index c4d4cb727c..af158dd0e9 100644 --- a/macos/Tests/LitheTests/LanguageProviderCatalogSourceTests.swift +++ b/macos/Tests/LitheTests/LanguageProviderCatalogSourceTests.swift @@ -149,66 +149,6 @@ struct LanguageProviderCatalogSourceTests { #expect(provider.languageServerLaunch == nil) } - /// Java Support ships only a language server. Running, testing, and - /// debugging Java stay host features, which the package declares on its - /// `jdt` integration; without that declaration the catalog would drop - /// them and the toolbar would report Java as unsupported. - @Test - func officialJavaPackageKeepsTheHostFeaturesItsIntegrationDeclares() throws { - let supports = try #require( - try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - .pluginManifest.languageSupports - ) - #expect(supports.map(\.hostCapabilities) == [[.debug, .run, .testing]]) - #expect(supports.languageIDs(requiringExtensionFor: .run).isEmpty) - #expect(supports.languageIDs(requiringExtensionFor: .testing).isEmpty) - - let provider = try #require( - LanguageProviderCatalog.compatibilityFallback - .applying(languageSupports: supports) - .provider(for: URL(fileURLWithPath: "/tmp/Main.java")) - ) - #expect(provider.capabilities.contains(.languageServer)) - #expect(provider.capabilities.contains(.run)) - #expect(provider.capabilities.contains(.debugAdapter)) - #expect(provider.capabilities.contains(.testing)) - } - - /// The declaration is the only way back to a host feature: a package - /// that owns a language and declares nothing gets none of them, even - /// though the shared catalog lists them. - @Test - func packageWithoutHostCapabilitiesGetsNoHostFeature() throws { - let undeclared = LanguageSupportDeclaration( - id: "java", - displayName: "Java", - fileExtensions: ["java"], - languageServerModuleID: .languageServerExtension("java") - ) - let debugOnly = LanguageSupportDeclaration( - id: "java", - displayName: "Java", - fileExtensions: ["java"], - languageServerModuleID: .languageServerExtension("java"), - hostCapabilities: [.debug] - ) - let capabilities: (LanguageSupportDeclaration) throws -> LanguageToolingCapability = { - try #require( - LanguageProviderCatalog.compatibilityFallback - .applying(languageSupports: [$0]) - .provider(for: URL(fileURLWithPath: "/tmp/Main.java")) - ).capabilities - } - - let none = try capabilities(undeclared) - #expect(none.contains(.languageServer)) - #expect(none.isDisjoint(with: [.run, .debugAdapter, .testing])) - let debug = try capabilities(debugOnly) - #expect(debug.contains(.debugAdapter)) - #expect(debug.isDisjoint(with: [.run, .testing])) - #expect([undeclared].languageIDs(requiringExtensionFor: .testing) == ["java"]) - } - /// A debugger plugin names the languages it debugs. It adds the debugger /// to a language another owner serves, and leaves that owner's server, /// run, test features and display name alone. diff --git a/macos/Tests/LitheTests/LanguageServerNavigationPayloadTests.swift b/macos/Tests/LitheTests/LanguageServerNavigationPayloadTests.swift index 1644ee11a1..59abc86bfa 100644 --- a/macos/Tests/LitheTests/LanguageServerNavigationPayloadTests.swift +++ b/macos/Tests/LitheTests/LanguageServerNavigationPayloadTests.swift @@ -9,14 +9,14 @@ struct LanguageServerNavigationPayloadTests { let data = Data(""" { "locations": [{ - "uri": "jdt://contents/java.base/java/lang/String.class", + "uri": "virtual://contents/lib/core/Item.txt", "filePath": null, "range": { "start": { "line": 10, "utf16Column": 4 }, "end": { "line": 10, "utf16Column": 10 } }, "isReadOnly": true, - "displayPath": "java.base/java/lang/String.class" + "displayPath": "lib/core/Item.txt" }] } """.utf8) @@ -27,8 +27,8 @@ struct LanguageServerNavigationPayloadTests { ) let location = try #require(payload.makeModels().first) - #expect(location.url.absoluteString == "jdt://contents/java.base/java/lang/String.class") + #expect(location.url.absoluteString == "virtual://contents/lib/core/Item.txt") #expect(location.isReadOnly) - #expect(location.displayPath == "java.base/java/lang/String.class") + #expect(location.displayPath == "lib/core/Item.txt") } } diff --git a/macos/Tests/LitheTests/LanguageServerStatusTests.swift b/macos/Tests/LitheTests/LanguageServerStatusTests.swift index 664bf89797..dc28880b5a 100644 --- a/macos/Tests/LitheTests/LanguageServerStatusTests.swift +++ b/macos/Tests/LitheTests/LanguageServerStatusTests.swift @@ -33,7 +33,7 @@ struct LanguageServerStatusTests { @Test func statusProjectionPublishesOnlyWhenSessionChromeChanges() throws { let harness = Harness() defer { harness.sessions.stopAllLanguageServers() } - harness.feature.bindProjectPreparation(harness.sessions) + harness.feature.bindSessions(harness.sessions) var changes = 0 let observation = harness.feature.$serverRuntimeSnapshot.dropFirst().sink { _ in changes += 1 } defer { observation.cancel() } @@ -46,16 +46,16 @@ struct LanguageServerStatusTests { } @Test func serverNamesUseExistingExecutableMetadataAndOtherwiseThePluginID() { - let registrations = [registration("java", "jdtls"), registration("c", "clangd"), + let registrations = [registration("a", "server-a"), registration("c", "clangd"), LanguageServerRegistration(id: "legacy", pluginID: "org.example.legacy", executableNames: ["", " "])] let rows = LSPControlCenterPresenter.statusBarServers(registrations: registrations, - states: ["java": .ready, "c": .ready, "unregistered": .ready], - infos: ["java": .init(name: "Eclipse JDT Language Server", version: "1"), + states: ["a": .ready, "c": .ready, "unregistered": .ready], + infos: ["a": .init(name: "Example Language Server", version: "1"), "c": .init(name: "Apple clangd", version: "21")], disabledProviderIDs: []) - #expect(Set(rows.map(\.displayName)) == ["jdtls", "clangd", "org.example.legacy"]) + #expect(Set(rows.map(\.displayName)) == ["server-a", "clangd", "org.example.legacy"]) #expect(rows.allSatisfy { $0.id != "unregistered" }) #expect(LSPControlCenterPresenter.statusBarServers(registrations: [], - states: ["java": .ready], infos: [:], disabledProviderIDs: []).isEmpty) + states: ["a": .ready], infos: [:], disabledProviderIDs: []).isEmpty) } @Test func idleMenuKeepsLogsAndSettingsAvailableWithoutAnySessions() throws { @@ -121,7 +121,7 @@ struct LanguageServerStatusTests { harness.session.releaseStop = released defer { released.open(); harness.feature.stop(providerID: "example") } try harness.sessions.startLanguageServer(providerID: "example", rootURL: harness.workspace) - harness.feature.bindProjectPreparation(harness.sessions) + harness.feature.bindSessions(harness.sessions) harness.session.onStart = { restarted.open() } harness.feature.restart(providerID: "example") try #require(await harness.session.stopRequested.waitUntilOpen()) @@ -165,27 +165,24 @@ struct LanguageServerStatusTests { } @Test func providerResetPreservesOtherLiveServers() throws { - let harness = Harness(includesJava: true) + let harness = Harness(includesSecondProvider: true) defer { harness.sessions.stopAllLanguageServers() } - harness.feature.bindProjectPreparation(harness.sessions) + harness.feature.bindSessions(harness.sessions) try harness.sessions.startLanguageServer(providerID: "example", rootURL: harness.workspace) - try harness.sessions.startLanguageServer(providerID: "java", rootURL: harness.workspace) + try harness.sessions.startLanguageServer(providerID: "second", rootURL: harness.workspace) let before = harness.feature.serverRuntimeSnapshot - try harness.sessions.rebuildWorkspaceState(providerID: "java", rootURL: harness.workspace) - harness.feature.resetProviderState(providerID: "java") + try harness.sessions.rebuildWorkspaceState(providerID: "second", rootURL: harness.workspace) + harness.feature.resetProviderState(providerID: "second") #expect(harness.feature.serverRuntimeSnapshot.states["example"] == .ready) - #expect(harness.feature.serverRuntimeSnapshot.states["java"] == .stopped) + #expect(harness.feature.serverRuntimeSnapshot.states["second"] == .stopped) #expect(harness.feature.serverRuntimeSnapshot.states["example"] == before.states["example"]) } - @Test func stopInvalidatesPendingActivationAndCallsRegisteredPreparationOwner() { + @Test func stopInvalidatesPendingActivation() { let harness = Harness() - var cancelled = 0 - harness.feature.registerPreparationCancellation(providerID: "example") { cancelled += 1 } let old = harness.feature.activationToken(providerID: "example") let other = harness.feature.activationToken(providerID: "other") harness.feature.stop(providerID: "example") - #expect(cancelled == 1) #expect(harness.feature.activationToken(providerID: "example") != old) #expect(harness.feature.activationToken(providerID: "other") == other) harness.feature.resetWorkspaceState() @@ -232,16 +229,16 @@ private final class Harness { let sessions: LanguageToolingSessionManager let feature: LanguageToolingFeatureModel - init(includesJava: Bool = false) { + init(includesSecondProvider: Bool = false) { let descriptor = LanguageProviderDescriptor(id: "example", displayName: "Example", fileExtensions: ["example"], capabilities: .languageServer, activationPolicy: .onDemand) - let java = LanguageProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"], + let second = LanguageProviderDescriptor(id: "second", displayName: "Second", fileExtensions: ["second"], capabilities: .languageServer, activationPolicy: .onDemand) - let source = StatusTestCatalog(catalog: LanguageProviderCatalog(descriptors: includesJava ? [descriptor, java] : [descriptor])) + let source = StatusTestCatalog(catalog: LanguageProviderCatalog(descriptors: includesSecondProvider ? [descriptor, second] : [descriptor])) var runtimes: [any LanguageProviderRuntime] = [StatusTestRuntime(descriptor: descriptor, session: session)] - if includesJava { runtimes.append(StatusTestRuntime(descriptor: java, session: StatusTestSession())) } + if includesSecondProvider { runtimes.append(StatusTestRuntime(descriptor: second, session: StatusTestSession())) } let sessions = LanguageToolingSessionManager(catalog: source.catalog, - runtimes: runtimes, workspaceStateResetter: { _, _, _ in }) + runtimes: runtimes, workspaceStateResetter: { _, _ in }) self.sessions = sessions feature = LanguageToolingFeatureModel(catalogSource: source, catalogSnapshot: source.load(workspaceURL: nil), preferences: MacWorkspaceLanguageServerPreferencesStore(store: store), sessionsProvider: { sessions }) @@ -280,7 +277,6 @@ private final class StatusTestRuntime: LanguageProviderRuntime { @MainActor private final class StatusTestSession: LanguageServerSession { var isRunning = false - var javaTestRunnerURL: URL? { nil } var onDiagnostics: ((URL, [LanguageServerDiagnostic]) -> Void)? var onStateChange: ((LanguageServerSessionState) -> Void)? var startCount = 0 @@ -289,7 +285,7 @@ private final class StatusTestSession: LanguageServerSession { var stopCompletes = true let stopRequested = TestGate() var onStart: (() -> Void)? - func start(rootURL: URL, workspaceFingerprint: String?) throws { + func start(rootURL: URL) throws { isRunning = true startCount += 1 onStateChange?(.ready) @@ -317,5 +313,4 @@ private final class StatusTestSession: LanguageServerSession { func resolveCodeAction(_ action: LanguageServerCodeAction, fileURL: URL, completion: @escaping (Result) -> Void) throws { completion(.success(action)) } func execute(_ command: LanguageServerCommand, fileURL: URL, completion: @escaping (Result) -> Void) throws { completion(.success(())) } func resolveVirtualDocument(uri: String, completion: @escaping (Result) -> Void) throws { completion(.success("")) } - func javaEntrypoints(completion: @escaping (Result) -> Void) throws { throw CancellationError() } } diff --git a/macos/Tests/LitheTests/LanguageServerSyncBridgeTests.swift b/macos/Tests/LitheTests/LanguageServerSyncBridgeTests.swift index b3b3bf4c7d..e10683d4c7 100644 --- a/macos/Tests/LitheTests/LanguageServerSyncBridgeTests.swift +++ b/macos/Tests/LitheTests/LanguageServerSyncBridgeTests.swift @@ -22,7 +22,7 @@ struct LanguageServerSyncBridgeTests { } let result = core.lspSyncDocument( sessionID: "uri-bridge-test-missing-session", - fileURL: URL(fileURLWithPath: "/work/A#B?.java"), languageID: "java", text: "" + fileURL: URL(fileURLWithPath: "/work/A#B?.txt"), languageID: "plaintext", text: "" ) switch result { case .success: Issue.record("A nonexistent session must not accept a document") @@ -30,7 +30,7 @@ struct LanguageServerSyncBridgeTests { } } - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_RUN_JAVA_DEBUG_INTEGRATION"] == "1")) + @Test func incrementalPositionsReachCoreSessionLookup() throws { let core = RustCoreBridge() try #require(core.isAvailable) @@ -38,8 +38,8 @@ struct LanguageServerSyncBridgeTests { // Swift encoder and Rust decoder. Bad position keys fail before lookup. let result = core.lspSyncDocument( sessionID: "sync-bridge-test-missing-session", - fileURL: URL(fileURLWithPath: "/in-memory/Probe.java"), - languageID: "java", text: "class Probe {}", + fileURL: URL(fileURLWithPath: "/in-memory/Probe.txt"), + languageID: "plaintext", text: "probe text", changes: [.init(start: .init(line: 1, utf16Column: 4), end: .init(line: 2, utf16Column: 7), text: "😀")] ) diff --git a/macos/Tests/LitheTests/LanguageServerToolServiceTests.swift b/macos/Tests/LitheTests/LanguageServerToolServiceTests.swift index 7940179870..362ad5a5e3 100644 --- a/macos/Tests/LitheTests/LanguageServerToolServiceTests.swift +++ b/macos/Tests/LitheTests/LanguageServerToolServiceTests.swift @@ -393,7 +393,6 @@ struct LanguageServerToolServiceTests { ) -> ProjectRuntimeService { ProjectRuntimeService( runtimeLocator: LanguageServerToolTestRuntimeLocator(executablePaths: executablePaths), - store: store, toolDiscovery: LanguageServerToolTestDiscovery(candidatesByCommand: candidates) ) } @@ -403,13 +402,7 @@ private struct LanguageServerToolTestRuntimeLocator: RuntimeLocator { let executablePaths: Set func environment() -> [String: String] { ["PATH": ""] } - func discover() -> RuntimeDiscoveryResult { RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } - func validJavaHome(path _: String) -> URL? { nil } - func javaRuntime(at _: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { executablePaths.contains(url.standardizedFileURL.path) } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath _: String) -> URL? { nil } - func mavenRuntime(at _: URL) -> MavenRuntimeCandidate? { nil } } private struct LanguageServerToolTestDiscovery: RuntimeToolDiscovery { diff --git a/macos/Tests/LitheTests/LanguageTestLocalizationTests.swift b/macos/Tests/LitheTests/LanguageTestLocalizationTests.swift index 0a07fd372e..8782d4d63f 100644 --- a/macos/Tests/LitheTests/LanguageTestLocalizationTests.swift +++ b/macos/Tests/LitheTests/LanguageTestLocalizationTests.swift @@ -42,15 +42,11 @@ struct LanguageTestLocalizationTests { } @Test - func testTimeoutPreservesFrameworkAndDurationAndUnknownDiagnostics() throws { + func unknownDiagnosticsAreNotRewritten() throws { let chinese = try localization(.simplifiedChinese) let english = try localization(.english) - for framework in ["Maven", "JUnit"] { - let message = framework + " test run timed out after 120 seconds." - #expect(chinese.error(message) == framework + " 测试运行在 120 秒后超时。") - #expect(english.error(message) == message) - } - let diagnostic = "Maven: module/pom.xml 100% complete" + let diagnostic = "tool-a: module/config.toml 100% complete" #expect(chinese.error(diagnostic) == diagnostic) + #expect(english.error(diagnostic) == diagnostic) } } diff --git a/macos/Tests/LitheTests/LanguageTestPresentationTests.swift b/macos/Tests/LitheTests/LanguageTestPresentationTests.swift index 08a1560c2b..30348fc6c2 100644 --- a/macos/Tests/LitheTests/LanguageTestPresentationTests.swift +++ b/macos/Tests/LitheTests/LanguageTestPresentationTests.swift @@ -15,7 +15,7 @@ struct LanguageTestPresentationTests { BuildTestResults.TestCase(project: "a", suite: "demo.Same", name: "checks", status: .passed, durationMillis: 10), BuildTestResults.TestCase(project: "b", suite: "demo.Same", name: "checks", status: .failed, durationMillis: 20) ] - let items = LanguageTestsView.synthesizeResultItems(from: outcomes, references: [BuildTestCaseKey(outcomes[0]): a, BuildTestCaseKey(outcomes[1]): b], providerID: "java") + let items = LanguageTestsView.synthesizeResultItems(from: outcomes, references: [BuildTestCaseKey(outcomes[0]): a, BuildTestCaseKey(outcomes[1]): b], providerID: "tool-a") #expect(items.count == 4) #expect(Set(items.map(\.id)).count == 4) let first = try #require(items.first { $0.projectPath == "a" && $0.depth == 2 }) @@ -107,8 +107,7 @@ struct LanguageTestPresentationTests { #expect(LanguageTestsView.testItemIcon(status: "Failed", kind: kind, hasChildren: children) == "expui/run/testFailed.svg") } - for (path, expected) in [("/fixture/Test.java", LitheIconKind.javaGeneric), - ("/fixture/test_demo.py", .pythonSource), ("/fixture/demo.test.js", .javaScript)] { + for (path, expected) in [("/fixture/test_demo.py", LitheIconKind.pythonSource), ("/fixture/demo.test.js", .javaScript)] { #expect(LitheIcons.kind(for: URL(fileURLWithPath: path), isDirectory: false) == expected) } } @@ -171,7 +170,7 @@ struct LanguageTestPresentationTests { BuildTestResults.TestCase(suite: "demo.CalculatorTest", name: "addsPositiveNumbers()", status: .passed), BuildTestResults.TestCase(suite: "demo.CalculatorTest", name: "handlesZero()", status: .passed) ] - let items = LanguageTestsView.synthesizeResultItems(from: outcomes, providerID: "java") + let items = LanguageTestsView.synthesizeResultItems(from: outcomes, providerID: "tool-a") #expect(items.count == 3) #expect(items[0].label == "demo.CalculatorTest") #expect(items[0].depth == 1) @@ -184,24 +183,24 @@ struct LanguageTestPresentationTests { @Test func reportOnlyRowsRemainSelectableAndKeepTheirExecutableIdentifiers() throws { - let source = URL(fileURLWithPath: "/fixture/Tests.java") - let discovered = [LanguageTestItem(id: "file", providerID: "java", label: "Tests.java", + let source = URL(fileURLWithPath: "/fixture/Tests.txt") + let discovered = [LanguageTestItem(id: "file", providerID: "tool-a", label: "Tests.txt", kind: .file, fileURL: source, testIdentifier: nil, depth: 0)] let outcomes = [BuildTestResults.TestCase(suite: "demo.Tests", name: "passes()", status: .passed)] let results = BuildTestResults(tests: outcomes, summary: .init(total: 1, passed: 1, failed: 0, errors: 0, skipped: 0), success: true) - let rows = LanguageTestsView.presentedItems(discovered: discovered, results: results, resultProviderID: "java", providerID: "java") + let rows = LanguageTestsView.presentedItems(discovered: discovered, results: results, resultProviderID: "tool-a", providerID: "tool-a") #expect(rows.count == 2) for row in rows { let selected = try #require(LanguageTestsView.presentedItems(discovered: discovered, - results: results, resultProviderID: "java", providerID: "java").first { $0.id == row.id }) + results: results, resultProviderID: "tool-a", providerID: "tool-a").first { $0.id == row.id }) #expect(selected.kind == .testCase) #expect(selected.testIdentifier == (row.depth == 1 ? "demo.Tests" : "demo.Tests#passes()")) #expect(selected.fileURL == nil, "A report does not establish semantic source ownership for Debug") } - #expect(LanguageTestsView.presentedItems(discovered: discovered, results: nil, resultProviderID: "java", providerID: "java") == discovered) - let semantic = LanguageTestItem(id: "jdt-method", providerID: "java", label: "passes()", + #expect(LanguageTestsView.presentedItems(discovered: discovered, results: nil, resultProviderID: "tool-a", providerID: "tool-a") == discovered) + let semantic = LanguageTestItem(id: "semantic-method", providerID: "tool-a", label: "passes()", kind: .testCase, fileURL: source, testIdentifier: "demo.Tests#passes()", depth: 2, reportIdentity: .init(suite: "demo.Tests", name: "passes()")) - #expect(LanguageTestsView.presentedItems(discovered: [semantic], results: results, resultProviderID: "java", providerID: "java").first { $0.id == semantic.id } == semantic) + #expect(LanguageTestsView.presentedItems(discovered: [semantic], results: results, resultProviderID: "tool-a", providerID: "tool-a").first { $0.id == semantic.id } == semantic) } @Test @@ -225,7 +224,7 @@ struct LanguageTestPresentationTests { func currentResultsBelongOnlyToTheirProviderAndDisappearWhenCleared() { let outcomes = [BuildTestResults.TestCase(suite: "demo.Tests", name: "passes", status: .passed)] let results = BuildTestResults(tests: outcomes, summary: .init(total: 1, passed: 1, failed: 0, errors: 0, skipped: 0), success: true) - for provider in ["java", "node", "python"] { + for provider in ["tool-a", "node", "python"] { let discovered = [LanguageTestItem(id: "workspace-" + provider, providerID: provider, label: provider, kind: .workspace, fileURL: nil, testIdentifier: nil, depth: 0), LanguageTestItem(id: "file-" + provider, providerID: provider, label: "Unrun file", @@ -233,34 +232,26 @@ struct LanguageTestPresentationTests { LanguageTestItem(id: "unrun-" + provider, providerID: provider, label: "Unrun test", kind: .testCase, fileURL: nil, testIdentifier: "demo.Unrun#check", depth: 2)] let rows = LanguageTestsView.presentedItems(discovered: discovered, results: results, - resultProviderID: "java", providerID: provider) - #expect(provider == "java" ? rows.count == 2 : rows == discovered) + resultProviderID: "tool-a", providerID: provider) + #expect(provider == "tool-a" ? rows.count == 2 : rows == discovered) #expect(rows.allSatisfy { $0.providerID == provider }) // Clear retains the plan; Close clears both. Neither may reuse editor history. - for owner in ["java", nil] as [String?] { + for owner in ["tool-a", nil] as [String?] { #expect(LanguageTestsView.presentedItems(discovered: discovered, results: nil, resultProviderID: owner, providerID: provider) == discovered) } } } - @Test - func activeTestTargetFormatsMethodAndClassNamesCorrectly() { - #expect(ActiveTestTarget.formattedName(for: "demo.CalculatorTest#addsPositiveNumbers()") == "CalculatorTest.addsPositiveNumbers") - #expect(ActiveTestTarget.formattedName(for: "demo.CalculatorTest#intentionalFailureForPreview()") == "CalculatorTest.intentionalFailureForPreview") - #expect(ActiveTestTarget.formattedName(for: "demo.CalculatorTest") == "CalculatorTest") - } - @Test(arguments: [false, true]) - func resolvedTestNameKeepsTheFullScopeAndDebugToolbarBinding(method: Bool) { - let source = URL(fileURLWithPath: "/fixture/Tests.java") - let scope: LanguageTestScope = method ? .testCase(identifier: "demo.Tests#logsIn()", fileURL: source) : .file(source) - var target = ActiveTestTarget(providerID: "java", scope: scope) - let launchName = method ? "logsIn()" : "ActualTestClass" - target.resolvedName = launchName + func activeTestTargetKeepsTheFullScopeAndIsNamedByIt(method: Bool) { + let source = URL(fileURLWithPath: "/fixture/Tests.txt") + let scope: LanguageTestScope = method ? .testCase(identifier: "suite#case", fileURL: source) : .file(source) + let target = ActiveTestTarget(providerID: "tool-a", scope: scope) #expect(target.scope == scope) + #expect(target.name == (method ? "suite#case" : "Tests.txt")) #expect(DebugToolbarPresentation.mainToolbarControl(state: .paused, - debugTarget: launchName, selectedTarget: target.name) == .resume) + debugTarget: target.name, selectedTarget: target.name) == .resume) } private func key(_ suite: String, _ name: String? = nil) -> LanguageTestsView.ResultKey { @@ -268,7 +259,7 @@ struct LanguageTestPresentationTests { } private func testItem(_ id: String, selector: String? = nil, depth: Int) -> LanguageTestItem { - LanguageTestItem(id: id, providerID: "java", label: id, kind: .testCase, + LanguageTestItem(id: id, providerID: "tool-a", label: id, kind: .testCase, fileURL: nil, testIdentifier: selector, depth: depth) } } diff --git a/macos/Tests/LitheTests/LanguageToolEnvironmentTests.swift b/macos/Tests/LitheTests/LanguageToolEnvironmentTests.swift index ea007e2288..d3ac394ca4 100644 --- a/macos/Tests/LitheTests/LanguageToolEnvironmentTests.swift +++ b/macos/Tests/LitheTests/LanguageToolEnvironmentTests.swift @@ -95,8 +95,6 @@ struct LanguageToolEnvironmentTests { #expect(server.runtimeTools.isEmpty) #expect(server.launchRuntimeTool == "node") - let java = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - #expect(java.languageServers.first?.launchRuntimeTool == "java") let php = try DeclarativePluginTestSupport.officialDescriptor("PhpSupport") #expect(php.languageServers.allSatisfy { $0.launchRuntimeTool == nil }) } diff --git a/macos/Tests/LitheTests/LanguageWorkspaceEditServiceTests.swift b/macos/Tests/LitheTests/LanguageWorkspaceEditServiceTests.swift index ba9347c00f..bb1b6b59ad 100644 --- a/macos/Tests/LitheTests/LanguageWorkspaceEditServiceTests.swift +++ b/macos/Tests/LitheTests/LanguageWorkspaceEditServiceTests.swift @@ -7,7 +7,7 @@ import Testing struct LanguageWorkspaceEditServiceTests { @Test("rejects edits outside the workspace") func rejectsOutsideWorkspace() { - let outsideURL = URL(fileURLWithPath: "/other/Outside.java") + let outsideURL = URL(fileURLWithPath: "/other/Outside.txt") let edit = LanguageServerWorkspaceEdit(changes: [ outsideURL: [replacement(in: outsideURL)] ]) @@ -33,7 +33,7 @@ struct LanguageWorkspaceEditServiceTests { @Test("rejects edits to read-only open documents") func rejectsReadOnlyDocument() { - let url = URL(fileURLWithPath: "/workspace/ReadOnly.java") + let url = URL(fileURLWithPath: "/workspace/ReadOnly.txt") let document = EditorDocument( url: url, text: "before", @@ -62,8 +62,8 @@ struct LanguageWorkspaceEditServiceTests { @Test("rolls back files written before a later write fails") func rollsBackPartialWrite() { - let firstURL = URL(fileURLWithPath: "/workspace/First.java") - let secondURL = URL(fileURLWithPath: "/workspace/Second.java") + let firstURL = URL(fileURLWithPath: "/workspace/First.txt") + let secondURL = URL(fileURLWithPath: "/workspace/Second.txt") let edit = LanguageServerWorkspaceEdit(changes: [ firstURL: [replacement(in: firstURL)], secondURL: [replacement(in: secondURL)] diff --git a/macos/Tests/LitheTests/LazyProjectTreeInventoryTests.swift b/macos/Tests/LitheTests/LazyProjectTreeInventoryTests.swift index 0b926142bc..69a3652110 100644 --- a/macos/Tests/LitheTests/LazyProjectTreeInventoryTests.swift +++ b/macos/Tests/LitheTests/LazyProjectTreeInventoryTests.swift @@ -30,7 +30,7 @@ struct LazyProjectTreeInventoryTests { for scenario in contract.cases { let root = URL(fileURLWithPath: "/in-memory/roles/" + scenario.id) let directory = root.appendingPathComponent("archive") - let fixture = InventoryFixture(root: root, files: [directory.appendingPathComponent("Keep.java")], rows: [root.path: []]) + let fixture = InventoryFixture(root: root, files: [directory.appendingPathComponent("Keep.txt")], rows: [root.path: []]) defer { fixture.close() } await fixture.load() for step in scenario.steps { @@ -54,7 +54,7 @@ struct LazyProjectTreeInventoryTests { @Test(arguments: [false, true]) func aNewSnapshotDuringSessionRestoreDoesNotReplayTheSavedSession(fullRescan: Bool) async throws { let root = URL(fileURLWithPath: "/in-memory/snapshot-during-session-restore") - let old = root.appendingPathComponent("Old.java"), new = root.appendingPathComponent("New.java") + let old = root.appendingPathComponent("Old.txt"), new = root.appendingPathComponent("New.txt") let fixture = InventoryFixture(root: root, files: [old], rows: [root.path: []]) fixture.sessionStore.session = WorkspaceSession(openPaths: [old.path], activePath: old.path, selectedSidebar: "project") let started = TestGate(), release = TestGate() @@ -81,7 +81,7 @@ struct LazyProjectTreeInventoryTests { @Test(arguments: [false, true]) func aNewerSnapshotPublishedDuringGitRefreshCannotBeFollowedByTheOldInventory(incremental: Bool) async throws { let root = URL(fileURLWithPath: "/in-memory/snapshot-publication-order") - let old = root.appendingPathComponent("Old.java"), new = root.appendingPathComponent("New.java") + let old = root.appendingPathComponent("Old.txt"), new = root.appendingPathComponent("New.txt") let fixture = InventoryFixture(root: root, files: [old], rows: [root.path: []]) let gitStarted = TestGate(), releaseGit = TestGate() fixture.gitRefreshAction = { gitStarted.open(); _ = await releaseGit.waitUntilOpen() } @@ -109,7 +109,7 @@ struct LazyProjectTreeInventoryTests { @Test(arguments: ["configure", "snapshot", "validate"]) func anotherOwnersIndexingRefreshRetriesTheCurrentWorkspaceWithoutRetiringItAgain(phase: String) async { let root = URL(fileURLWithPath: "/in-memory/cross-owner-indexing-refresh") - let file = root.appendingPathComponent("Keep.java") + let file = root.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [root.path: []]) defer { fixture.close() } if phase == "snapshot" { @@ -163,7 +163,7 @@ struct LazyProjectTreeInventoryTests { @Test(arguments: [false, true]) func mixedRuleChangesStillDeliverOrdinaryFileUpdates(metadata: Bool) async throws { let root = URL(fileURLWithPath: "/in-memory/mixed-indexing-rules") - let keep = root.appendingPathComponent("Keep.java") + let keep = root.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: root, files: [keep], rows: [root.path: []]) defer { fixture.close() } await fixture.load() @@ -266,7 +266,7 @@ struct LazyProjectTreeInventoryTests { @Test(arguments: [false, true]) func aCompleteIndexingRescanPublishesRecoveryEvenWhenTheFileListIsUnchanged(watcherUpdate: Bool) async throws { let root = URL(fileURLWithPath: "/in-memory/indexing-complete-recovery") - let file = root.appendingPathComponent("Keep.java") + let file = root.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [root.path: []]) defer { fixture.close() } fixture.disk.setIncompleteDirectories(["unreadable"]) @@ -275,7 +275,7 @@ struct LazyProjectTreeInventoryTests { #expect(fixture.model.appliedSnapshot?.incompleteDirectories == ["unreadable"]) let files: [URL] if watcherUpdate { - let added = root.appendingPathComponent("Added.java") + let added = root.appendingPathComponent("Added.txt") files = [file, added] fixture.disk.set(files: files, rows: [root.path: []]) // Incomplete inventories use a full rescan. Wait for its applied @@ -298,7 +298,7 @@ struct LazyProjectTreeInventoryTests { @Test func initialIndexingFailureKeepsProjectIdentityForRetryAndRefreshFailureKeepsTheTree() async { - let root = URL(fileURLWithPath: "/in-memory/indexing-retry"); let file = root.appendingPathComponent("Keep.java") + let root = URL(fileURLWithPath: "/in-memory/indexing-retry"); let file = root.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [root.path: []]) defer { fixture.close() } fixture.disk.failNextConfiguration(.workspaceUnavailable) @@ -322,7 +322,7 @@ struct LazyProjectTreeInventoryTests { func normalFolderDoesNotCreateAnIncludeExceptionButCancelExclusionDoes() async { let root = URL(fileURLWithPath: "/in-memory/indexing-normal-folder") let directory = root.appendingPathComponent("src") - let fixture = InventoryFixture(root: root, files: [directory.appendingPathComponent("Keep.java")], rows: [root.path: []]) + let fixture = InventoryFixture(root: root, files: [directory.appendingPathComponent("Keep.txt")], rows: [root.path: []]) defer { fixture.close() } await fixture.load() await fixture.model.markDirectory(directory, action: .setRole(.sources)) @@ -339,7 +339,7 @@ struct LazyProjectTreeInventoryTests { func stalePolicyInstallCannotOverwriteOrFailTheNextWorkspace(staleFails: Bool, reopenSameRoot: Bool) async { let oldRoot = URL(fileURLWithPath: "/in-memory/old-indexing") let nextRoot = reopenSameRoot ? oldRoot : URL(fileURLWithPath: "/in-memory/next-indexing") - let file = nextRoot.appendingPathComponent("Keep.java") + let file = nextRoot.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: nextRoot, files: [file], rows: [nextRoot.path: []]) defer { fixture.close() } fixture.disk.blockNextConfiguration(failing: staleFails) @@ -372,7 +372,7 @@ struct LazyProjectTreeInventoryTests { @Test func visibilityRefreshCannotPublishAcrossSameRootReopen() async { let root = URL(fileURLWithPath: "/in-memory/visibility-indexing-reopen") - let file = root.appendingPathComponent("Keep.java") + let file = root.appendingPathComponent("Keep.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [root.path: []]) defer { fixture.close() } await fixture.load() @@ -420,7 +420,7 @@ struct LazyProjectTreeInventoryTests { @Test func unsupportedWorkspaceRejectsExclusionActions() async { let root = URL(fileURLWithPath: "/in-memory/unsupported-indexing") - let file = root.appendingPathComponent("src/Keep.java") + let file = root.appendingPathComponent("src/Keep.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [root.path: []]) defer { fixture.close() } fixture.disk.supportsExclusions = false @@ -437,7 +437,7 @@ struct LazyProjectTreeInventoryTests { func policyChangesDuringScanPublishOnlyTheLatestInventory(manualMark: Bool) async { let root = URL(fileURLWithPath: "/in-memory/indexing-policy-race") let directory = root.appendingPathComponent(manualMark ? "manual" : "ignored") - let file = directory.appendingPathComponent("Candidate.java") + let file = directory.appendingPathComponent("Candidate.txt") let fixture = InventoryFixture(root: root, files: [file], rows: [ root.path: [FileNode(url: directory, isDirectory: true, children: nil)], directory.path: [], ]) @@ -668,12 +668,12 @@ struct LazyProjectTreeInventoryTests { } @Test(arguments: [false, true]) - func compactPackageRelistingCannotOverwriteANewerRootFileChange(deletingB: Bool) async throws { + func compactDirectoryChainRelistingCannotOverwriteANewerRootFileChange(deletingB: Bool) async throws { let root = URL(fileURLWithPath: "/in-memory/lazy-tree-relisting") let source = root.appendingPathComponent("src") let package = source.appendingPathComponent("app") - let main = package.appendingPathComponent("Main.java") - let a = source.appendingPathComponent("A.java") + let main = package.appendingPathComponent("Main.txt") + let a = source.appendingPathComponent("A.txt") let b = root.appendingPathComponent("B.md") let compact = FileNode(url: package, isDirectory: true, children: nil, collapsedAncestorPaths: [source.path]) diff --git a/macos/Tests/LitheTests/LegacyMavenConfigurationMigrationTests.swift b/macos/Tests/LitheTests/LegacyMavenConfigurationMigrationTests.swift deleted file mode 100644 index d15623d644..0000000000 --- a/macos/Tests/LitheTests/LegacyMavenConfigurationMigrationTests.swift +++ /dev/null @@ -1,451 +0,0 @@ -import CryptoKit -import Foundation -import LitheCoreContracts -import Testing -@testable import Lithe - -@Suite("Legacy Maven configuration transfer", .serialized) -@MainActor -struct LegacyMavenConfigurationMigrationTests { - @Test - func productionCutoverOnlyTransfersTheOfficialDetectedRootsAndPreservesNewDefaults() throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: .init(selectedProfiles: ["ci"]), - local: .init(settingsPath: "/fixture/retired.xml")), workspaceURL: context.workspace, reactorPath: "a") - var document = BuildProjectOptionsDocument() - var system = BuildProjectOptionsDocument.System() - system.instanceDefaults["settingsFile"] = .string("/fixture/new-source.xml") - document.systems["maven"] = system - try context.options.saveProjectDocument(document, workspace: context.workspace, expecting: nil) - func instance(plugin: String) -> BuildSystemInstance { - BuildSystemInstance(id: "maven:a", pluginID: plugin, buildSystemID: "maven", displayName: "Maven", - root: "a", markers: ["a/pom.xml"], modelSource: .provider, optionFingerprint: "fixture", model: nil, modelError: nil) - } - #expect(!(try context.options.migrateLegacyConfiguration(workspaceURL: context.workspace, instances: []))) - #expect(!(try context.options.migrateLegacyConfiguration(workspaceURL: context.workspace, instances: [instance(plugin: "fixture.other-plugin")]))) - #expect(context.storage.fileExists(at: context.portable)) - #expect(try context.options.migrateLegacyConfiguration(workspaceURL: context.workspace, instances: [instance(plugin: "io.github.lithe-idea.maven-build")])) - #expect(!context.storage.fileExists(at: context.portable)) - #expect(!context.storage.fileExists(at: context.local("a"))) - #expect(try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven")["settingsFile"] == .string("/fixture/new-source.xml")) - #expect(try context.options.instanceOptions(workspaceURL: context.workspace, buildSystemID: "maven")["a"]?["settingsFile"] == nil) - #expect(!(try context.options.migrateLegacyConfiguration(workspaceURL: context.workspace, instances: [instance(plugin: "io.github.lithe-idea.maven-build")]))) - } - - @Test - func runtimeMavenFieldsRemainPrivateDefaultsWhileExistingRootAndTeamChoicesWin() throws { - let context = try Context() - defer { context.clean() } - let key = MacProjectRuntimeSettingsStore.preferencesKey(context.workspace) - context.preferences.set(try JSONSerialization.data(withJSONObject: [ - "mavenSettingsPath": "/fixture/old-user-settings.xml", "mavenLocalRepositoryPath": "/fixture/private-repository", - "javaHomePath": "/fixture/unrelated-jdk", "futurePreference": ["keep": true] - ]), forKey: key) - var document = BuildProjectOptionsDocument() - var maven = BuildProjectOptionsDocument.System() - maven.instanceDefaults["settingsFile"] = .string("/fixture/team-settings.xml") - document.systems["maven"] = maven - try context.options.saveProjectDocument(document, workspace: context.workspace, expecting: nil) - let sharedBytes = try context.options.projectDocument(context.workspace).bytes - try context.options.setInstanceOptions(["b": ["localRepository": .string("")]], workspaceURL: context.workspace, buildSystemID: "maven") - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["a", "b"])) - let defaults = try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven") - #expect(defaults == ["settingsFile": .string("/fixture/team-settings.xml"), "localRepository": .string("/fixture/private-repository")]) - #expect(try context.options.instanceOptions(workspaceURL: context.workspace, buildSystemID: "maven")["b"]?["localRepository"] == .string("")) - #expect(try context.options.projectDocument(context.workspace).bytes == sharedBytes) - let saved = try #require(context.preferences.data(forKey: key)) - let cleaned = try #require(JSONSerialization.jsonObject(with: saved) as? [String: Any]) - #expect(cleaned["mavenSettingsPath"] == nil && cleaned["mavenLocalRepositoryPath"] == nil) - #expect(cleaned["javaHomePath"] as? String == "/fixture/unrelated-jdk") - #expect((cleaned["futurePreference"] as? [String: Bool])?["keep"] == true) - // Defaults continue to apply when another reactor appears after cutover. - #expect(!(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["later"]))) - #expect(try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven") == defaults) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test - func runtimeFieldsWaitForAReactorAndTheirFailedPublicationCanRetry() throws { - let context = try Context() - defer { context.clean() } - let key = MacProjectRuntimeSettingsStore.preferencesKey(context.workspace) - let bytes = try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": "/fixture/settings.xml", "future": 1]) - context.preferences.set(bytes, forKey: key) - #expect(!(try context.migration().migrate(workspace: context.workspace, reactorRoots: []))) - #expect(context.preferences.data(forKey: key) == bytes) - context.preferences.refuseDefaults = true - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(context.preferences.data(forKey: key) == bytes) - #expect(!context.preferences.migrationReceipts.isEmpty) - context.preferences.refuseDefaults = false - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - #expect(try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven")["settingsFile"] == .string("/fixture/settings.xml")) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test - func failedRuntimeSourceCleanupRetainsItsReceiptAndCanRetryAfterReadback() throws { - let context = try Context() - defer { context.clean() } - let key = MacProjectRuntimeSettingsStore.preferencesKey(context.workspace) - let bytes = try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": "/fixture/settings.xml"]) - context.preferences.set(bytes, forKey: key) - context.preferences.refuseRuntimeWrites = true - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(context.preferences.data(forKey: key) == bytes) - #expect(try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven")["settingsFile"] == .string("/fixture/settings.xml")) - #expect(!context.preferences.migrationReceipts.isEmpty) - context.preferences.refuseRuntimeWrites = false - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test(arguments: [false, true]) - func emptyRuntimeFieldsDoNotCreateOverridesOrReplaceExistingDefaults(existing: Bool) throws { - let context = try Context() - defer { context.clean() } - let key = MacProjectRuntimeSettingsStore.preferencesKey(context.workspace) - if existing { - try context.options.setInstanceDefaults(["settingsFile": .string("/fixture/already-saved.xml")], workspaceURL: context.workspace, buildSystemID: "maven") - } - context.preferences.set(try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": "", "mavenLocalRepositoryPath": " ", "future": true]), forKey: key) - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - #expect(try context.options.instanceDefaults(workspaceURL: context.workspace, buildSystemID: "maven") == (existing ? ["settingsFile": .string("/fixture/already-saved.xml")] : [:])) - #expect(!context.storage.fileExists(at: context.workspace.appendingPathComponent(".lithe/build/options.json"))) - #expect(!context.storage.fileExists(at: context.workspace.appendingPathComponent(".lithe/run/local.json"))) - let saved = try #require(context.preferences.data(forKey: key)) - let fields = try #require(JSONSerialization.jsonObject(with: saved) as? [String: Bool]) - #expect(fields == ["future": true]) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test(arguments: ["wrong-type", "corrupt", "invalid-field", "source-change"]) - func invalidOrChangedRuntimeFieldsRetainTheirSource(kind: String) throws { - let context = try Context() - defer { context.clean() } - let key = MacProjectRuntimeSettingsStore.preferencesKey(context.workspace) - let original = try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": "/fixture/original.xml"]) - let changed = try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": "/fixture/external.xml"]) - switch kind { - case "wrong-type": context.preferences.set("retain me", forKey: key) - case "corrupt": context.preferences.set(Data("{broken".utf8), forKey: key) - case "invalid-field": context.preferences.set(try JSONSerialization.data(withJSONObject: ["mavenSettingsPath": 12]), forKey: key) - default: - context.preferences.set(original, forKey: key) - context.preferences.beforeWrite = { writtenKey in - if writtenKey.hasSuffix(".InstanceDefaults") { - context.preferences.beforeWrite = nil - context.preferences.set(changed, forKey: key) - } - } - } - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - if kind == "source-change" { - #expect(context.preferences.data(forKey: key) == changed) - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(context.preferences.data(forKey: key) == changed) - } else if kind == "wrong-type" { #expect(context.preferences.object(forKey: key) as? String == "retain me") } - else { #expect(context.preferences.data(forKey: key) != nil) } - } - - @Test - func transfersTeamChoicesAndReactorLocalPathsWithoutReplacingCanonicalValues() throws { - let context = try Context() - defer { context.clean() } - let portable = MavenPortableConfiguration(selectedProfiles: [], customProfiles: ["not-selected", "ci"], skipTests: true) - try context.legacy.saveMavenConfiguration(.init(portable: portable, local: .init(settingsPath: "/fixture/a.xml", localRepositoryPath: "/fixture/a-repository", mavenExecutablePath: "./mvnw", javaHomePath: "/fixture/a-jdk")), workspaceURL: context.workspace, reactorPath: "a") - try context.legacy.saveMavenConfiguration(.init(portable: portable, local: .init(settingsPath: "/fixture/b.xml", javaHomePath: "/fixture/b-jdk")), workspaceURL: context.workspace, reactorPath: "b") - try context.legacy.saveMavenConfiguration(.init(portable: portable, local: .init(settingsPath: "/fixture/absent.xml")), workspaceURL: context.workspace, reactorPath: "temporarily-absent") - var shared = BuildProjectOptionsDocument() - var maven = BuildProjectOptionsDocument.System() - maven.instanceDefaults["skipTests"] = .bool(false) - maven.savedChoices["profiles"] = ["new-custom"] - shared.systems["maven"] = maven - try context.options.saveProjectDocument(shared, workspace: context.workspace, expecting: nil) - try context.options.setInstanceOptions(["b": ["settingsFile": .string("")]], workspaceURL: context.workspace, buildSystemID: "maven") - let canonical = ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk", pathOverrides: ["b": .init()]) - try context.run.saveProjectToolchain(canonical, at: context.workspace) - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["b", "a"])) - let migrated = try context.options.projectDocument(context.workspace).document.systems["maven"] - #expect(migrated?.instanceDefaults == ["profiles": .array([]), "skipTests": .bool(false)]) - #expect(migrated?.savedChoices["profiles"] == ["ci", "new-custom", "not-selected"]) - let local = try context.options.instanceOptions(workspaceURL: context.workspace, buildSystemID: "maven") - #expect(local["a"] == ["settingsFile": .string("/fixture/a.xml"), "localRepository": .string("/fixture/a-repository")]) - #expect(local["b"] == ["settingsFile": .string("")]) - let toolchain = try #require(context.run.inspect(at: context.workspace, checkFingerprint: false, javaEntrypoints: nil).projectToolchain) - #expect(toolchain.javaHomePath == canonical.javaHomePath) - #expect(toolchain.pathOverrides["a"] == .init(mavenExecutablePath: "./mvnw", mavenJavaHomePath: "/fixture/a-jdk")) - #expect(toolchain.pathOverrides["b"] == .init()) - #expect(!context.storage.fileExists(at: context.portable)) - #expect(!context.storage.fileExists(at: context.local("a"))) - #expect(!context.storage.fileExists(at: context.local("b"))) - #expect(context.storage.fileExists(at: context.local("temporarily-absent"))) - let bytes = try context.options.projectDocument(context.workspace).bytes - #expect(!(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["a", "b"]))) - #expect(try context.options.projectDocument(context.workspace).bytes == bytes) - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["temporarily-absent"])) - #expect(try context.options.instanceOptions(workspaceURL: context.workspace, buildSystemID: "maven")["temporarily-absent"]?["settingsFile"] == .string("/fixture/absent.xml")) - #expect(!context.storage.fileExists(at: context.local("temporarily-absent"))) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test(arguments: [false, true]) - func rootReactorUsesProjectDefaultsAndPreservesAnExplicitCanonicalAutomaticChoice(existing: Bool) throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: nil, local: .init(mavenExecutablePath: "./mvnw", javaHomePath: "/fixture/legacy-jdk")), workspaceURL: context.workspace, reactorPath: ".") - if existing { try context.run.saveProjectToolchain(ProjectToolchainSelection(), at: context.workspace) } - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - let saved = try #require(context.run.inspect(at: context.workspace, checkFingerprint: false, javaEntrypoints: nil).projectToolchain) - #expect(saved.mavenExecutablePath == (existing ? "" : "./mvnw")) - #expect(saved.mavenJavaHomePath == (existing ? "" : "/fixture/legacy-jdk")) - #expect(saved.pathOverrides.isEmpty) - } - - @Test - func portableChoicesDoNotReadOrRepairAnUnrelatedInvalidRunDocument() throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: .init(selectedProfiles: ["ci"]), local: .init(settingsPath: "/fixture/settings.xml")), workspaceURL: context.workspace, reactorPath: ".") - let run = context.workspace.appendingPathComponent(".lithe/run/local.json") - try context.storage.createDirectory(at: run.deletingLastPathComponent(), withIntermediateDirectories: true) - let original = Data("{unrelated broken run configuration".utf8) - try original.write(to: run) - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - #expect(try Data(contentsOf: run) == original) - #expect(!context.storage.fileExists(at: context.portable)) - #expect(try context.options.instanceOptions(workspaceURL: context.workspace, buildSystemID: "maven")["."]?["settingsFile"] == .string("/fixture/settings.xml")) - } - - @Test - func oversizedRootInventoryRetainsSourcesBeforeAnyTargetPublication() throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: .init(selectedProfiles: ["ci"]), local: nil), workspaceURL: context.workspace, reactorPath: ".") - let original = try Data(contentsOf: context.portable) - #expect(throws: (any Error).self) { - try context.migration().migrate(workspace: context.workspace, reactorRoots: (0..<257).map { "root-\($0)" }) - } - #expect(try Data(contentsOf: context.portable) == original) - #expect(context.preferences.migrationReceipts.isEmpty) - #expect(!context.storage.fileExists(at: context.workspace.appendingPathComponent(".lithe/build/options.json"))) - } - - @Test - func partialPublicationCanRetryWithoutRemovingAnyUnverifiedSource() throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: .init(selectedProfiles: ["ci"], customProfiles: ["later"], skipTests: true), local: .init(settingsPath: "/fixture/settings.xml", mavenExecutablePath: "./mvnw")), workspaceURL: context.workspace, reactorPath: ".") - let original = try Data(contentsOf: context.portable) - let local = try Data(contentsOf: context.local(".")) - var failing = context.storage - failing.failRunPublication = true - #expect(throws: (any Error).self) { try context.migration(storage: failing).migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(try Data(contentsOf: context.portable) == original) - #expect(try Data(contentsOf: context.local(".")) == local) - #expect(!context.preferences.migrationReceipts.isEmpty) - #expect(try context.options.projectDocument(context.workspace).document.systems["maven"]?.instanceDefaults["profiles"] == .array([.string("ci")])) - #expect(try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."])) - #expect(!context.storage.fileExists(at: context.portable)) - #expect(!context.storage.fileExists(at: context.local("."))) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @Test - func anExternalSourceEditAtRemovalIsRetainedAndCannotBeErasedOnRetry() throws { - let context = try Context() - defer { context.clean() } - try context.legacy.saveMavenConfiguration(.init(portable: .init(selectedProfiles: ["old"]), local: nil), workspaceURL: context.workspace, reactorPath: ".") - let changed = try JSONEncoder().encode(MavenPortableConfiguration(selectedProfiles: ["external-after-publication"])) - let source = context.portable - var racing = context.storage - racing.beforeRemoval = { url in if url == source { try changed.write(to: url) } } - #expect(throws: (any Error).self) { try context.migration(storage: racing).migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(try Data(contentsOf: context.portable) == changed) - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(try Data(contentsOf: context.portable) == changed) - #expect(!context.preferences.migrationReceipts.isEmpty) - } - - @Test(arguments: ["unknown", "future-version", "corrupt", "outside-link"]) - func invalidOrUnownedLegacySourcesNeverCreateDestinations(kind: String) throws { - let context = try Context() - defer { context.clean() } - try context.storage.createDirectory(at: context.portable.deletingLastPathComponent(), withIntermediateDirectories: true) - var value: [String: Any] = ["version": 1, "selectedProfiles": [], "customProfiles": [], "skipTests": false] - if kind == "unknown" { value["futureOption"] = "keep me" } - if kind == "future-version" { value["version"] = 2 } - let bytes = kind == "corrupt" ? Data("{broken".utf8) : try JSONSerialization.data(withJSONObject: value) - if kind == "outside-link" { - let outside = context.root.appendingPathComponent("outside.json") - try bytes.write(to: outside) - try FileManager.default.createSymbolicLink(at: context.portable, withDestinationURL: outside) - } else { try bytes.write(to: context.portable) } - #expect(throws: (any Error).self) { try context.migration().migrate(workspace: context.workspace, reactorRoots: ["."]) } - #expect(try Data(contentsOf: context.portable) == bytes) - #expect(!context.storage.fileExists(at: context.workspace.appendingPathComponent(".lithe/build/options.json"))) - #expect(!context.storage.fileExists(at: context.workspace.appendingPathComponent(".lithe/run/local.json"))) - #expect(context.preferences.migrationReceipts.isEmpty) - } - - @MainActor - private struct Context { - let root: URL - let workspace: URL - let storage: MigrationFileStorage - let preferences = MigrationPreferences() - let options: MacBuildOptionsStore - let run: MacRunConfigurationStore - var legacy: LegacyMavenFixtureWriter { .init(storage: storage) } - var portable: URL { workspace.appendingPathComponent(".lithe/maven/config.json") } - init() throws { - root = FileManager.default.temporaryDirectory.appendingPathComponent("maven-configuration-transfer-" + UUID().uuidString).resolvingSymlinksInPath() - workspace = root.appendingPathComponent("workspace") - storage = MigrationFileStorage(root: root) - try storage.createDirectory(at: workspace, withIntermediateDirectories: true) - options = MacBuildOptionsStore(store: preferences, storage: storage) - run = MacRunConfigurationStore(core: RustCoreBridge(), storage: storage, preferences: preferences) - } - func migration(storage replacement: MigrationFileStorage? = nil) -> MacLegacyMavenConfigurationMigration { - let storage = replacement ?? storage - return MacLegacyMavenConfigurationMigration(storage: storage, preferences: preferences, - runStore: MacRunConfigurationStore(core: RustCoreBridge(), storage: storage, preferences: preferences), - options: MacBuildOptionsStore(store: preferences, storage: storage), immutableRoots: [Bundle.main.bundleURL]) - } - func local(_ path: String) -> URL { - let digest = SHA256.hash(data: Data((workspace.path + "\0" + path).utf8)).map { String(format: "%02x", $0) }.joined() - return storage.applicationSupportDirectory().appendingPathComponent("Lithe/Maven/" + digest + ".json") - } - func clean() { try? FileManager.default.removeItem(at: root) } - } -} - -private final class MigrationPreferences: KeyValueStore { - private var values: [String: Any] = [:] - var refuseDefaults = false - var refuseRuntimeWrites = false - var beforeWrite: ((String) -> Void)? - var migrationReceipts: [String] { values.keys.filter { $0.hasPrefix("BuildSystems.Migrations.Maven.") } } - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { - beforeWrite?(key) - guard !refuseDefaults || !key.hasSuffix(".InstanceDefaults") else { return } - guard !refuseRuntimeWrites || !key.hasPrefix("lithe.project-runtime-settings.") else { return } - values[key] = value - } -} - -private struct MigrationFileStorage: FileStorage { - let root: URL - var failRunPublication = false - var beforeRemoval: (@Sendable (URL) throws -> Void)? - private let native = MacFileStorage() - func homeDirectory() -> URL { root } - func cacheDirectory() -> URL { root.appendingPathComponent("cache") } - func applicationSupportDirectory() -> URL { root.appendingPathComponent("support") } - func temporaryDirectory() -> URL { root.appendingPathComponent("temporary") } - func metadata(for url: URL) -> FileMetadata? { native.metadata(for: url) } - func fileExists(at url: URL) -> Bool { native.fileExists(at: url) } - func isExecutable(at url: URL) -> Bool { native.isExecutable(at: url) } - func listDirectory(at url: URL) -> [URL] { native.listDirectory(at: url) } - func readPrefix(from url: URL, byteCount: Int) throws -> Data { try native.readPrefix(from: url, byteCount: byteCount) } - func readData(from url: URL, options: Data.ReadingOptions) throws -> Data { try native.readData(from: url, options: options) } - func writeData(_ data: Data, to url: URL, options: Data.WritingOptions) throws { try native.writeData(data, to: url, options: options) } - func replaceData(_ data: Data, at url: URL, expecting expected: Data?) throws -> Bool { - if failRunPublication && url.lastPathComponent == "local.json" { throw CocoaError(.fileWriteNoPermission) } - return try native.replaceData(data, at: url, expecting: expected) - } - func replaceDataPreservingMetadata(_ data: Data, at url: URL, expecting expected: Data?) throws -> Bool { - // The run store publishes `local.json` through this metadata-preserving - // path; the injected failure has to cover it as well as `replaceData`. - if failRunPublication && url.lastPathComponent == "local.json" { throw CocoaError(.fileWriteNoPermission) } - return try native.replaceDataPreservingMetadata(data, at: url, expecting: expected) - } - func removeData(at url: URL, expecting expected: Data) throws -> Bool { - try beforeRemoval?(url) - return try native.removeData(at: url, expecting: expected) - } - func createDirectory(at url: URL, withIntermediateDirectories: Bool) throws { try native.createDirectory(at: url, withIntermediateDirectories: withIntermediateDirectories) } - func removeItem(at url: URL) throws { try native.removeItem(at: url) } - func moveItem(at sourceURL: URL, to destinationURL: URL) throws { try native.moveItem(at: sourceURL, to: destinationURL) } - func copyItem(at sourceURL: URL, to destinationURL: URL) throws { try native.copyItem(at: sourceURL, to: destinationURL) } -} - -// Fixed saved-format fixtures survive deletion of the production legacy store. -private struct MavenPortableConfiguration: Codable, Equatable, Sendable { - static let currentVersion = 1 - - var version: Int - var selectedProfiles: [String] - var customProfiles: [String] - var skipTests: Bool - - init( - version: Int = currentVersion, - selectedProfiles: [String] = [], - customProfiles: [String] = [], - skipTests: Bool = false - ) { - self.version = version - self.selectedProfiles = selectedProfiles - self.customProfiles = customProfiles - self.skipTests = skipTests - } -} - -private struct MavenLocalConfiguration: Codable, Equatable, Sendable { - static let currentVersion = 1 - - var version: Int - var settingsPath: String? - var localRepositoryPath: String? - var mavenExecutablePath: String? - var javaHomePath: String? - - init( - version: Int = currentVersion, - settingsPath: String? = nil, - localRepositoryPath: String? = nil, - mavenExecutablePath: String? = nil, - javaHomePath: String? = nil - ) { - self.version = version - self.settingsPath = settingsPath - self.localRepositoryPath = localRepositoryPath - self.mavenExecutablePath = mavenExecutablePath - self.javaHomePath = javaHomePath - } -} - -private struct MavenStoredConfiguration: Equatable, Sendable { - let portable: MavenPortableConfiguration? - let local: MavenLocalConfiguration? - - init( - portable: MavenPortableConfiguration?, - local: MavenLocalConfiguration? - ) { - self.portable = portable - self.local = local - } -} - -private struct LegacyMavenFixtureWriter { - let storage: MigrationFileStorage - func saveMavenConfiguration(_ value: MavenStoredConfiguration, workspaceURL: URL, reactorPath: String) throws { - let portable = workspaceURL.appendingPathComponent(".lithe/maven/config.json") - let identity = MacLegacyMavenConfigurationMigration.storageIdentity(workspacePath: workspaceURL.path, reactorPath: reactorPath) - let digest = SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() - let local = storage.applicationSupportDirectory().appendingPathComponent("Lithe/Maven/" + digest + ".json") - for (url, data) in [(portable, try value.portable.map { try JSONEncoder().encode($0) }), - (local, try value.local.map { try JSONEncoder().encode($0) })] { - guard let data else { continue } - try storage.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try storage.writeData(data, to: url, options: []) - } - } -} diff --git a/macos/Tests/LitheTests/LitheCoreLogicTests.swift b/macos/Tests/LitheTests/LitheCoreLogicTests.swift index 600664eb5d..32eb75dea1 100644 --- a/macos/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/macos/Tests/LitheTests/LitheCoreLogicTests.swift @@ -20,7 +20,6 @@ struct LitheCoreLogicTests { let expectations: [(path: String, kind: LitheIconKind)] = [ ("rust/lithe-core/src/lib.rs", .rustSource), ("Cargo.toml", .toml), - ("src/main/java/App.java", .javaGeneric), ("docs/README.md", .readme), ("docs/guide.md", .markdown), (".gitignore", .gitignore), @@ -71,34 +70,6 @@ struct LitheCoreLogicTests { } } - @Test - func javaInterfaceSymbolAcceptsUnicodeIdentifiers() { - #expect( - LitheIcons.javaSymbolKind(fromSourcePrefix: "public interface 用户服务 {}") - == .javaInterface - ) - } - - @Test - func javaNavigationMarkersUseTheFourIntelliJGutterAssets() { - #expect( - LitheIcons.implementationMarkerAssetPath(isInterface: true, pointingDown: true) - == "gutter/implementedMethod.svg" - ) - #expect( - LitheIcons.implementationMarkerAssetPath(isInterface: true, pointingDown: false) - == "gutter/implementingMethod.svg" - ) - #expect( - LitheIcons.implementationMarkerAssetPath(isInterface: false, pointingDown: true) - == "gutter/overridenMethod.svg" - ) - #expect( - LitheIcons.implementationMarkerAssetPath(isInterface: false, pointingDown: false) - == "gutter/overridingMethod.svg" - ) - } - @Test @MainActor func closingAWorkspaceWindowResetsItsProjectsAndKeepsTheWelcomeWindow() async { @@ -348,8 +319,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -432,8 +402,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -476,8 +445,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -524,8 +492,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -565,8 +532,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -614,8 +580,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -662,8 +627,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -703,8 +667,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -752,8 +715,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) }, @@ -790,8 +752,7 @@ struct LitheCoreLogicTests { services: MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: .safeMode, - javaMavenOperations: NoProjectJavaOperations() + moduleLaunchMode: .safeMode ).services ) createdModels.append(model) @@ -830,7 +791,7 @@ struct LitheCoreLogicTests { modelFactory: { AppModel( settings: settings, - services: MacServiceContainer(store: store, settings: settings, javaMavenOperations: NoProjectJavaOperations()).services + services: MacServiceContainer(store: store, settings: settings).services ) }, projectWindowPresenter: { _ in } @@ -2183,8 +2144,10 @@ struct LitheCoreLogicTests { } @Test - func workspaceTreeCompactsMiddlePackagesOnlyUnderSourceRoots() throws { + func workspaceTreeDoesNotCompactPackagesWithoutSourceRoots() throws { // 目录树按 Rust core 实际发出的 JSON 形状构造,避免测试绕过解码路径。 + // 源码根只能由用户标记或插件导入的构建模型给出;没有源码根时, + // 任何目录(包括 src/main/java 这种惯用名)都不压缩、不用包图标。 func dir(_ path: String, _ children: String...) -> String { let name = (path as NSString).lastPathComponent let list = children.joined(separator: ",") @@ -2240,28 +2203,26 @@ struct LitheCoreLogicTests { } let javaRoot = try child(child(child(tree, "src"), "main"), "java") - #expect(javaRoot.iconKind == .sourceFolder) - - // com/alibaba/nacos/ai 压缩成一行,url 仍指向最深的真实目录。 - let compacted = try child(javaRoot, "com.alibaba.nacos.ai") - #expect(compacted.iconKind == .packageFolder) - #expect(compacted.url.lastPathComponent == "ai") - #expect(compacted.collapsedAncestorPaths.map { ($0 as NSString).lastPathComponent } - == ["com", "alibaba", "nacos"]) - #expect(compacted.children?.map(\.name).sorted() == ["App.java", "config"]) - #expect(try child(compacted, "config").iconKind == .packageFolder) - - // 含文件的目录不是空中间包,不压缩。 + #expect(javaRoot.iconKind == .folder) + #expect(!javaRoot.isInsideSourceRoot) + + // 没有源码根时 com/alibaba/nacos/ai 保持逐层展开,url 指向各自的真实目录。 + let com = try child(javaRoot, "com") + #expect(com.iconKind == .folder) + #expect(com.collapsedAncestorPaths.isEmpty) + let ai = try child(child(child(com, "alibaba"), "nacos"), "ai") + #expect(ai.collapsedAncestorPaths.isEmpty) + #expect(ai.children?.map(\.name).sorted() == ["App.java", "config"]) + #expect(try child(ai, "config").iconKind == .folder) + let solo = try child(javaRoot, "solo") #expect(solo.collapsedAncestorPaths.isEmpty) - #expect(try child(solo, "inner").iconKind == .packageFolder) + #expect(try child(solo, "inner").iconKind == .folder) - // 资源根用资源图标;META-INF 名字不是合法包名,保持普通文件夹。 let resources = try child(child(child(tree, "src"), "main"), "resources") - #expect(resources.iconKind == .resourceFolder) + #expect(resources.iconKind == .folder) #expect(try child(resources, "META-INF").iconKind == .folder) - // 源码根之外不压缩,也不用包图标。 let docs = try child(tree, "docs") #expect(docs.iconKind == .folder) #expect(docs.collapsedAncestorPaths.isEmpty) @@ -2392,56 +2353,6 @@ struct LitheCoreLogicTests { } } - @Test - func runConfigurationMigrationWritesToolchainsIntoServiceOverrides() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-run-migration-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } - let store = MutableKeyValueStore() - let projectKey = root.standardizedFileURL.path.replacingOccurrences(of: "/", with: "_") - store.set(try JSONEncoder().encode(JavaRunOptions( - javaHomePath: "/jdk/legacy", - workingDirectoryPath: "backend", - vmArguments: "-Xmx2g", - programArguments: "--spring.profiles.active=dev", - activeProfiles: ["dev"] - )), forKey: "lithe.java-run-options.\(projectKey).current-file") - store.set(try JSONEncoder().encode(ProjectRuntimeSettings( - javaHomePath: "/Library/Java/jdk-21", - mavenHomeSelection: .custom, - mavenHomePath: "/opt/maven", - mavenJavaHomePath: "/Library/Java/jdk-17" - )), forKey: "lithe.project-runtime.\(projectKey)") - - let adapter = MacRunConfigurationStore( - core: RustCoreBridge(), - storage: MacFileStorage(), - preferences: store, - documentMutator: RunTestDocumentMutator() - ) - try adapter.migrateLegacySettings(at: root, configurationIDs: ["current-file"]) - try adapter.saveOptions( - JavaRunOptions( - javaHomePath: "/Library/Java/jdk-22", - workingDirectoryPath: "backend app", - vmArguments: "\"-Dlabel=hello world\" -Xmx1g", - programArguments: "--dev", - activeProfiles: ["local"] - ), - configurationID: "current-file", - scope: .local, - at: root - ) - - let local = try JSONSerialization.jsonObject(with: Data(contentsOf: root.appendingPathComponent(".lithe/run/local.json"))) as? [String: Any] - let configs = local?["configurations"] as? [[String: Any]] - #expect(configs?.first?["workingDirectory"] as? String == "backend app") - #expect(configs?.first?["jvmArguments"] as? [String] == ["-Dlabel=hello world", "-Xmx1g"]) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/toolchains/local.json").path)) - #expect(store.object(forKey: "lithe.run-configuration-migrated.\(projectKey)") as? Bool == true) - #expect(store.data(forKey: "lithe.java-run-options.\(projectKey).current-file") != nil) - #expect(store.data(forKey: "lithe.java-run-options.\(projectKey).current-file") != nil) - } } private let projectWindowShutdownTestManifest = ModuleManifest( @@ -6045,7 +5956,7 @@ struct EditorDocumentTests { } @Test - func projectTreeLoaderCompactsPackagesLikeTheFullTreeConversion() throws { + func projectTreeLoaderMatchesTheFullTreeConversionWithoutSourceRoots() throws { let root = URL(fileURLWithPath: "/in-memory/lithe-tree-loader") let files = [ "pom.xml", @@ -6101,11 +6012,10 @@ struct EditorDocumentTests { #expect(unloaded(lazy).isEmpty) #expect(lazy == full) + // 没有源码根时懒加载树和整树转换都不压缩中间包。 let package = root.appendingPathComponent("src/main/java/com/acme/app") - #expect(lazy.node(exactlyAt: package)?.collapsedAncestorPaths == [ - root.appendingPathComponent("src/main/java/com").path, - root.appendingPathComponent("src/main/java/com/acme").path, - ]) + #expect(lazy.node(exactlyAt: package)?.collapsedAncestorPaths == []) + #expect(lazy.node(exactlyAt: root.appendingPathComponent("src/main/java/com")) != nil) #expect(listingCalls > 0) } diff --git a/macos/Tests/LitheTests/LitheTreeListTests.swift b/macos/Tests/LitheTests/LitheTreeListTests.swift index 8f599d3d2c..44d7101cc1 100644 --- a/macos/Tests/LitheTests/LitheTreeListTests.swift +++ b/macos/Tests/LitheTests/LitheTreeListTests.swift @@ -157,8 +157,8 @@ struct LitheTreeListTests { let directory = FileManager.default.temporaryDirectory.appendingPathComponent("Lithe.ProblemsKeyboard-\(UUID().uuidString)") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - let first = directory.appendingPathComponent("A.java"), second = directory.appendingPathComponent("B.java") - for file in [first, second] { try "class Test {}\n\n\n".write(to: file, atomically: true, encoding: .utf8) } + let first = directory.appendingPathComponent("A.txt"), second = directory.appendingPathComponent("B.txt") + for file in [first, second] { try "test\n\n\n".write(to: file, atomically: true, encoding: .utf8) } let domain = "Lithe.ProblemsKeyboard.\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: domain)) defer { defaults.removePersistentDomain(forName: domain) } @@ -249,8 +249,8 @@ struct LitheTreeListTests { selection: Binding(get: { state.selected }, set: { state.selected = $0 }), onActivate: { state.activated.append($0) - model.documentFeature.openVirtualDocument(resultRoot.appendingPathComponent($0 + ".java"), - text: "class Result {}", displayPath: nil) + model.documentFeature.openVirtualDocument(resultRoot.appendingPathComponent($0 + ".txt"), + text: "result", displayPath: nil) } ) { value in HStack { @@ -300,7 +300,7 @@ struct LitheTreeListTests { let refresh = try #require(find(host, id: "embedded-refresh")) #expect(refresh.accessibilityPerformPress?() == true) #expect(state.activated == ["b", "refresh"]) - #expect(model.activeDocument?.url == resultRoot.appendingPathComponent("b.java")) + #expect(model.activeDocument?.url == resultRoot.appendingPathComponent("b.txt")) #expect(state.selected == ["b"]) } diff --git a/macos/Tests/LitheTests/LocalHistoryIgnoreRulesTests.swift b/macos/Tests/LitheTests/LocalHistoryIgnoreRulesTests.swift index c8e7122586..e0e89d83a1 100644 --- a/macos/Tests/LitheTests/LocalHistoryIgnoreRulesTests.swift +++ b/macos/Tests/LitheTests/LocalHistoryIgnoreRulesTests.swift @@ -17,7 +17,7 @@ struct LocalHistoryIgnoreRulesTests { @Test func previewReportsInvalidRegexLinesAndTheMatchingRule() throws { - let result = try #require(preview("src/Generated/Api.java", patterns: ["*.log", ""], + let result = try #require(preview("src/Generated/Api.txt", patterns: ["*.log", ""], regexes: ["", "(unclosed", "generated/"])) #expect(Array(result.regexErrors.keys) == [1]) #expect(result.matched == .regex(index: 2)) @@ -28,17 +28,17 @@ struct LocalHistoryIgnoreRulesTests { #expect(preview("logs/run.log", patterns: ["*.log"])?.matched == .pattern("*.log")) #expect(preview("ios/Pods/A/a.h")?.matched == .pattern("**/Pods/")) #expect(preview(".git/config")?.matched == .hidden) - #expect(preview("src/Main.java")?.matched == nil) + #expect(preview("src/Main.txt")?.matched == nil) } @Test func builtInFolderRulesCanBeDeleted() { #expect(preview("ios/Pods/A/a.h", patterns: ["!**/Pods/"])?.matched == nil) - #expect(preview("gen/A.java", patterns: ["**/gen/"])?.matched == .pattern("**/gen/")) + #expect(preview("gen/A.txt", patterns: ["**/gen/"])?.matched == .pattern("**/gen/")) // Showing a hidden built-in folder still leaves it out of local history. #expect(preview(".git/config", hidden: ["!**/.git/"])?.matched == .pattern("**/.git/")) #expect(preview(".git/config", patterns: ["!**/.git/"], hidden: ["!**/.git/"])?.matched == nil) - #expect(preview("build/src/Main.java", patterns: ["!**/build/", "*.log"], + #expect(preview("build/src/Main.txt", patterns: ["!**/build/", "*.log"], hidden: ["!**/build/"])?.matched == nil) } diff --git a/macos/Tests/LitheTests/LogWindowReviewTests.swift b/macos/Tests/LitheTests/LogWindowReviewTests.swift index c514e34a84..51d02dcaa5 100644 --- a/macos/Tests/LitheTests/LogWindowReviewTests.swift +++ b/macos/Tests/LitheTests/LogWindowReviewTests.swift @@ -12,7 +12,7 @@ struct LogWindowReviewTests { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let writer = MacLogStore(defaultDirectory: root) defer { try? FileManager.default.removeItem(at: root) } - writer.emit(LspMessageLogged(diagnostic: "Java initialization", server: LogSegment("java")!, severity: "info")) + writer.emit(LspMessageLogged(diagnostic: "Example initialization", server: LogSegment("example")!, severity: "info")) writer.emit(LspMessageLogged(diagnostic: "Go initialization", server: LogSegment("go")!, severity: "info")) writer.emit(AppSessionStarted()) let feature = LanguageServerLogsModel(logging: writer) @@ -21,27 +21,27 @@ struct LogWindowReviewTests { #expect(LanguageServerLogsModel.MinimumLevel.allCases == [.info, .warning, .error]) #expect(feature.logs.query.levels == ["INFO", "WARN", "ERROR"]) - let java = try await showServer("java", channel: "lsp/java", in: feature) - #expect(feature.logs.query.channelPrefixes == ["lsp/java"]) + let example = try await showServer("example", channel: "lsp/example", in: feature) + #expect(feature.logs.query.channelPrefixes == ["lsp/example"]) feature.clear() #expect(feature.logs.state.records.isEmpty && feature.logs.state.cleared) - // Clearing Java leaves Go untouched. + // Clearing Example leaves Go untouched. _ = try await showServer("go", channel: "lsp/go", in: feature) #expect(feature.logs.query.channelPrefixes == ["lsp/go"]) #expect(!feature.logs.state.cleared) - // Back on Java the clear point still applies: only the newer row returns. + // Back on Example the clear point still applies: only the newer row returns. let returned = TestGate() let observation = feature.logs.$state.sink { state in - if !state.records.isEmpty, state.records.allSatisfy({ $0.channel == "lsp/java" }) { returned.open() } + if !state.records.isEmpty, state.records.allSatisfy({ $0.channel == "lsp/example" }) { returned.open() } } defer { observation.cancel() } - feature.select("java") - writer.emit(LspMessageLogged(diagnostic: "Java ready", server: LogSegment("java")!, severity: "info")) + feature.select("example") + writer.emit(LspMessageLogged(diagnostic: "Example ready", server: LogSegment("example")!, severity: "info")) try #require(await returned.waitUntilOpen(timeout: .logStoreQuery)) - #expect(feature.logs.query.channelPrefixes == ["lsp/java"]) - #expect(Set(feature.logs.state.records.map(LogWindowModel.recordID)).isDisjoint(with: java)) + #expect(feature.logs.query.channelPrefixes == ["lsp/example"]) + #expect(Set(feature.logs.state.records.map(LogWindowModel.recordID)).isDisjoint(with: example)) await writer.finishSession() } @@ -126,14 +126,16 @@ struct LogWindowReviewTests { try screenshot(try #require(panel.contentView), output: output, name: dark ? "final-settings-menu-dark.png" : "final-settings-menu-light.png") presenter.dismiss() } + // The reviewed session decides which language server channel is rendered. + let serverID = ProcessInfo.processInfo.environment["LITHE_REVIEW_LOG_SERVER"] ?? "example" let serverFeature = LanguageServerLogsModel(logging: writer) serverFeature.logs.changeQuery { $0.session = "all" } let serverLoaded = TestGate() let serverObservation = serverFeature.logs.$state.sink { state in - if !state.records.isEmpty, state.records.allSatisfy({ $0.channel == "lsp/java" }) { serverLoaded.open() } + if !state.records.isEmpty, state.records.allSatisfy({ $0.channel == "lsp/\(serverID)" }) { serverLoaded.open() } } defer { serverObservation.cancel(); serverFeature.stop() } - serverFeature.open(providerID: "java") + serverFeature.open(providerID: serverID) let host = NSHostingView(rootView: LanguageServerLogsView(feature: serverFeature).environmentObject(app) .environmentObject(settings).environment(\.locale, settings.language.locale).environment(\.colorScheme, .light)) let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 1400, height: 900), @@ -143,7 +145,7 @@ struct LogWindowReviewTests { try #require(await serverLoaded.waitUntilOpen(timeout: .logStoreQuery)) host.layoutSubtreeIfNeeded() await Task.yield() - try screenshot(host, output: output, name: "final-jdtls-logs.png") + try screenshot(host, output: output, name: "final-server-logs.png") await app.shutdownProjectSession() } diff --git a/macos/Tests/LitheTests/LogWindowTests.swift b/macos/Tests/LitheTests/LogWindowTests.swift index 1421272f62..9d20625d28 100644 --- a/macos/Tests/LitheTests/LogWindowTests.swift +++ b/macos/Tests/LitheTests/LogWindowTests.swift @@ -494,9 +494,9 @@ struct LogWindowTests { #expect(feature.providerID == "c++") #expect(applicationLogs.request == nil) // Opening again reuses the one tab and switches its server. - model.showLanguageServerLogs(providerID: "java") + model.showLanguageServerLogs(providerID: "example") #expect(model.editorTabItems.filter { $0 == .languageLogs }.count == 1) - #expect(feature.providerID == "java") + #expect(feature.providerID == "example") model.closeLanguageServerLogsTab() #expect(!model.editorTabItems.contains(.languageLogs)) } diff --git a/macos/Tests/LitheTests/MacBuildProviderSessionsTests.swift b/macos/Tests/LitheTests/MacBuildProviderSessionsTests.swift index 9ad5ebc0d3..4d6112e9f2 100644 --- a/macos/Tests/LitheTests/MacBuildProviderSessionsTests.swift +++ b/macos/Tests/LitheTests/MacBuildProviderSessionsTests.swift @@ -20,10 +20,10 @@ struct MacBuildProviderSessionsTests { if issues.count == 3 { observed.open() } } defer { session.stop() } - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) core.enqueueLogIssues() #expect(await observed.waitUntilOpen()) - #expect(issues.map { $0.2 } == ["mavenSettingsUnchanged", "configurationCleanupFailed", "initializeTimeout"]) + #expect(issues.map { $0.2 } == ["settingsUnchanged", "configurationCleanupFailed", "initializeTimeout"]) #expect(issues.first?.0 == true) #expect(issues.last?.0 == false) #expect(issues.last?.1 == "initialize") @@ -41,7 +41,7 @@ struct MacBuildProviderSessionsTests { releasing.open() #expect(await release.waitUntilOpen(), "Resource release was not permitted") } - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) let closing = Task { @MainActor in let result = await session.stopAndWait() finished.open() @@ -63,13 +63,13 @@ struct MacBuildProviderSessionsTests { func documentSavesReachCoreAndPropagateTransportFailure(fails: Bool) async throws { let core = ScriptedProviderCore() let session = LanguageServerRuntimeSession( - providerID: "java", executableURL: URL(fileURLWithPath: "/tools/jdtls"), + providerID: "example", executableURL: URL(fileURLWithPath: "/tools/server"), arguments: [], environment: [:], core: core) - let file = URL(fileURLWithPath: "/workspace/Main.java") + let file = URL(fileURLWithPath: "/workspace/example.txt") defer { session.stop() } try session.notifyDocumentSaved(file, text: "before startup") #expect(core.savedTexts.isEmpty) - try session.start(rootURL: file.deletingLastPathComponent(), workspaceFingerprint: nil) + try session.start(rootURL: file.deletingLastPathComponent()) core.saveFails = fails if fails { #expect(throws: (any Error).self) { try session.notifyDocumentSaved(file, text: "saved") } @@ -82,82 +82,6 @@ struct MacBuildProviderSessionsTests { try #require(await core.destroyed.waitUntilOpen()) } - @Test(arguments: [false, true], [false, true]) - func javaLaunchPreparationDecodesSharedTargetsAndCancelsItsOwnedOperation(cancel: Bool, buildFailed: Bool) async throws { - let root = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() - struct Fixture: Decodable { - struct Case: Decodable { let target: JavaDebugLaunchTarget } - let cases: [Case] - } - let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: - root.appendingPathComponent("shared/fixtures/lsp/java-launch-preparation-v1.json"))) - for item in fixture.cases { - let core = ScriptedProviderCore() - let session = LanguageServerRuntimeSession( - providerID: "java", executableURL: URL(fileURLWithPath: "/tools/jdtls"), - arguments: [], environment: [:], core: core - ) - let workspace = URL(fileURLWithPath: "/workspace/java", isDirectory: true) - try session.start(rootURL: workspace, workspaceFingerprint: nil) - let finished = TestGate() - let request = Task { @MainActor () -> Result in - defer { finished.open() } - do { return .success(try await session.prepareJavaLaunch( - fileURL: workspace.appendingPathComponent("Main.java"), mainClass: "demo.Main" - )) } catch { return .failure(error) } - } - defer { request.cancel(); session.stop() } - try #require(await core.commandStarted.waitUntilOpen()) - if cancel { - request.cancel() - try #require(await core.functionCancelled.waitUntilOpen()) - } else { - let target = try JSONDecoder().decode(ToolingJSONValue.self, from: JSONEncoder().encode(item.target)) - var result: [String: ToolingJSONValue] = [ - "kind": .string(buildFailed ? "buildFailed" : "ready"), "target": target - ] - if buildFailed { - result["failure"] = .object([ - "code": .string("javaBuildCompilationErrors"), - "message": .string("The Java project build reported compilation errors."), - "report": .object(["markerScope": .string("launchTarget"), - "builderFailedEarlier": .bool(false), "elapsedMilliseconds": .integer(25), - "recovery": .string("rebuildJavaIndex")]) - ]) - } - core.finishJavaLaunch(.object(result)) - } - try #require(await finished.waitUntilOpen(), "Java launch did not finish before its local deadline") - switch await request.value { - case .success(let preparation): - #expect(!cancel) - if buildFailed { - guard case .buildFailed(let target, let failure) = preparation else { - Issue.record("A terminal build failure must retain its evidence and launch target") - return - } - #expect(target == item.target) - #expect(failure.code == "javaBuildCompilationErrors") - #expect(failure.message == L10n.string("The Java project build reported compilation errors.")) - #expect(failure.report?.elapsedMilliseconds == 25) - #expect(failure.report?.recovery == .rebuildJavaIndex) - } else { - #expect(preparation == .ready(item.target)) - } - case .failure(let error): - #expect(cancel) - #expect(error is CancellationError) - #expect(core.cancelledOperations == ["java-launch"]) - } - #expect(session.isRunning) - #expect(core.stopCalls.isEmpty) - session.stop() - try #require(await core.destroyed.waitUntilOpen()) - } - } - @Test func preparedPluginKeepsConfigurationAndQueuedWorkspaceChanges() async throws { let core = ScriptedProviderCore() @@ -177,7 +101,7 @@ struct MacBuildProviderSessionsTests { }, core: core, pluginID: "dev.example.fixture" ) defer { resume.open(); session.stop() } - try session.start(rootURL: root, workspaceFingerprint: nil) + try session.start(rootURL: root) try #require(await preparing.waitUntilOpen()) let changes = [LanguageServerWorkspaceFileChange(fileURL: root.appendingPathComponent("new.swift"), kind: .created)] try session.notifyWorkspaceFilesChanged(changes) @@ -210,7 +134,7 @@ struct MacBuildProviderSessionsTests { }, core: core ) defer { resume.open(); lateReply.cancel(); session.stop() } - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await preparing.waitUntilOpen()) session.stop() resume.open() @@ -234,7 +158,7 @@ struct MacBuildProviderSessionsTests { var issues: [(String, String)] = [] session.onLogIssue = { _, stage, code, _, _ in issues.append((stage, code)) } defer { session.stop() } - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) #expect(await released.waitUntilOpen()) #expect(!session.isRunning) #expect(issues.contains { $0.0 == "processStart" && $0.1 == "processFailed" }) @@ -267,7 +191,7 @@ struct MacBuildProviderSessionsTests { pluginID: "dev.example.fixture", operation: .languageServerStart, at: .resolve, operationID: "lsp-start" )) - try? session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try? session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await settled.waitUntilOpen()) #expect(core.startupHandoffs.map(\.pluginId) == ["dev.example.fixture"]) @@ -297,7 +221,7 @@ struct MacBuildProviderSessionsTests { pluginID: "dev.example.fixture", operation: .languageServerStart, at: .resolve, operationID: "lsp-start" )) - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await prepared.started.waitUntilOpen()) #expect(prepared.startupHandoffs.map(\.operationId) == ["lsp-start"]) @@ -323,7 +247,7 @@ struct MacBuildProviderSessionsTests { pluginID: "dev.example.fixture", operation: .languageServerStart, at: .resolve, operationID: "lsp-start" )) - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await failed.waitUntilOpen()) #expect(operations.observations == [RecordedPluginOperations.languageServerStart( @@ -357,7 +281,7 @@ struct MacBuildProviderSessionsTests { pluginID: "dev.example.fixture", operation: .languageServerStart, at: .resolve, operationID: "lsp-start" )) - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await preparing.waitUntilOpen()) session.stop() resume.open() @@ -379,7 +303,7 @@ struct MacBuildProviderSessionsTests { let root = URL(fileURLWithPath: "/workspace") let file = root.appendingPathComponent("one.swift") let closedFile = root.appendingPathComponent("closed.swift") - try session.start(rootURL: root, workspaceFingerprint: nil) + try session.start(rootURL: root) try #require(await core.started.waitUntilOpen()) #expect(session.isRunning) try session.synchronize(fileURL: file, text: "old", languageID: "swift") @@ -412,7 +336,7 @@ struct MacBuildProviderSessionsTests { #expect(core.destroyed.isOpen, "Package bytes must outlive the late process") resourcesReleased.open() } - try session.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await core.started.waitUntilOpen()) session.stop() #expect(!session.isRunning) @@ -439,7 +363,7 @@ struct MacBuildProviderSessionsTests { resourcesReleased.open() } weak var owner = session - try session?.start(rootURL: URL(fileURLWithPath: "/workspace"), workspaceFingerprint: nil) + try session?.start(rootURL: URL(fileURLWithPath: "/workspace")) try #require(await core.started.waitUntilOpen()) session = nil #expect(owner == nil) @@ -491,7 +415,7 @@ struct MacBuildProviderSessionsTests { let result = try await fixture.sessions.prepareRun(BuildProviderRequest( method: "lithe/build/prepareRun", params: .object([:]), optionFingerprint: "", executesProjectCode: true, mayUseNetwork: true), on: fixture.target, timeout: .seconds(5)) { progress.values.append($0) } - #expect(result == .object(["executable": .object(["kind": .string("command"), "value": .string("java")]), + #expect(result == .object(["executable": .object(["kind": .string("command"), "value": .string("example-tool")]), "arguments": .array([]), "workingDirectory": .string("."), "environment": .object([:])])) #expect(progress.values == [BuildProviderProgress(percentage: 50, output: "building")]) #expect(fixture.core.startCalls.count == 1) @@ -509,7 +433,7 @@ struct MacBuildProviderSessionsTests { arguments: [], environment: [:], core: core ) let root = URL(fileURLWithPath: "/workspace/hosted-debug", isDirectory: true) - try session.start(rootURL: root, workspaceFingerprint: nil) + try session.start(rootURL: root) let finished = TestGate() let request = Task { @MainActor () -> Result in defer { finished.open() } @@ -544,31 +468,6 @@ struct MacBuildProviderSessionsTests { try #require(await core.destroyed.waitUntilOpen(), "The language session did not release its resources") } - @Test - func cancellingAwaitedJavaEntrypointsRevokesTheExactCoreOperationWithoutStoppingTheSession() async throws { - let core = ScriptedProviderCore() - let session = LanguageServerRuntimeSession(providerID: "java", executableURL: URL(fileURLWithPath: "/tools/jdtls"), - arguments: [], environment: [:], core: core) - try session.start(rootURL: URL(fileURLWithPath: "/workspace/java-profile"), workspaceFingerprint: nil) - let finished = TestGate() - let task = Task { @MainActor () -> Result in - defer { finished.open() } - do { return .success(try await session.javaEntrypoints()) } - catch { return .failure(error) } - } - defer { task.cancel(); session.stop() } - try #require(await core.commandStarted.waitUntilOpen()) - task.cancel() - try #require(await core.functionCancelled.waitUntilOpen()) - try #require(await finished.waitUntilOpen()) - if case .failure(let error) = await task.value { #expect(error is CancellationError) } - else { Issue.record("Cancelled launch discovery must not succeed") } - #expect(session.isRunning) - #expect(core.stopCalls.isEmpty) - session.stop() - try #require(await core.destroyed.waitUntilOpen()) - } - /// A second request reuses the process; stopping the plugin's providers, /// which the plugin manager does before replacing its package, ends it /// and the next request starts a new one. @@ -598,10 +497,10 @@ struct MacBuildProviderSessionsTests { let fixture = try ProviderFixture() defer { fixture.remove() } let params: ToolingJSONValue = .object([ - "buildSystemID": .string("gradle"), + "buildSystemID": .string("tool-a"), "root": .string("."), "refresh": .bool(true), - "tool": .object(["executable": .string("/opt/tools/gradle/bin/gradle")]), + "tool": .object(["executable": .string("/opt/tools/tool-a/bin/tool-a")]), ]) _ = try await fixture.load(params: params) @@ -909,7 +808,7 @@ private final class ProgressReports { var items: [PluginFunctionProgress] = [] } -/// A Gradle-like plugin whose provider is a packaged executable with a +/// A plugin whose provider is a packaged executable with a /// setting in its arguments. @MainActor private struct ProviderFixture { @@ -1123,29 +1022,10 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked var buildParams: [ToolingJSONValue] { lock.withLock { _buildParams } } var functionRequests: [FunctionCall] { lock.withLock { _functionRequests } } - func startLanguageServer( - providerID: String, executableURL: URL, arguments: [String], environment: [String: String], - rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, jdtlsLaunchResources: JDTLSLaunchResources?, cacheDirectoryURL: URL?, - workspaceFingerprint: String?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result { - startLanguageServer( - providerID: providerID, executableURL: executableURL, arguments: arguments, - environment: environment, rootURL: rootURL, workingDirectoryURL: workingDirectoryURL, - initializationOptions: initializationOptions, runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, mavenContext: nil, initializeTimeout: initializeTimeout, - requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout - ) - } - func startLanguageServer( providerID _: String, executableURL _: URL, arguments: [String], environment _: [String: String], rootURL _: URL, workingDirectoryURL _: URL, initializationOptions _: ToolingJSONValue?, - runtimeExecutableURL _: URL?, jdtlsLaunchResources _: JDTLSLaunchResources?, cacheDirectoryURL _: URL?, - workspaceFingerprint _: String?, mavenContext _: MavenLaunchContext?, initializeTimeout _: TimeInterval, - requestTimeout _: TimeInterval, shutdownTimeout _: TimeInterval + initializeTimeout _: TimeInterval, requestTimeout _: TimeInterval, shutdownTimeout _: TimeInterval ) -> Result { if failStart { return .failure(.init(code: "processFailed", message: "fixture startup failed")) } if backgroundStart { @@ -1172,10 +1052,7 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked pluginID: String, providerID: String, executableURL: URL, arguments: [String], environment: [String: String], rootURL: URL, initializationOptions: ToolingJSONValue?, workspaceConfiguration: ToolingJSONValue?, hostServices: [String], - hostIntegrationLaunch _: LanguageServerHostIntegrationLaunch?, cacheDirectoryURL _: URL?, - workspaceFingerprint _: String?, mavenContext _: MavenLaunchContext?, - javaGradle _: JavaGradleImportConfiguration?, initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, shutdownTimeout: TimeInterval + initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval ) -> Result { lock.withLock { _workspaceConfigurations.append(workspaceConfiguration) } // The host-services overload keeps the protocol's default refusal of services. @@ -1213,10 +1090,10 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked func enqueueLogIssues() { lock.withLock { events["provider-\(nextSession)", default: []] += [ - LanguageServerRuntimeEvent(type: "log", error: LanguageServerRuntimeError(code: "mavenSettingsUnchanged", stage: "mavenSettings", message: "settings warning", underlyingMessage: nil, processExitCode: nil), level: "warn", - message: "Maven settings were passed to the Java language service unchanged", detail: "private upstream detail"), + LanguageServerRuntimeEvent(type: "log", error: LanguageServerRuntimeError(code: "settingsUnchanged", stage: "settings", message: "settings warning", underlyingMessage: nil, processExitCode: nil), level: "warn", + message: "Settings were passed to the language service unchanged", detail: "private upstream detail"), LanguageServerRuntimeEvent(type: "log", error: LanguageServerRuntimeError(code: "configurationCleanupFailed", stage: "configurationCleanup", message: "cleanup warning", underlyingMessage: nil, processExitCode: nil), level: "warn", - message: "Unused Java language-server configuration areas could not be removed", detail: "private command output"), + message: "Unused language-server configuration areas could not be removed", detail: "private command output"), LanguageServerRuntimeEvent(type: "stateChanged", state: "failed", error: LanguageServerRuntimeError(code: "initializeTimeout", stage: "initialize", message: "private URL", underlyingMessage: nil, processExitCode: 17)) @@ -1329,7 +1206,7 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked result: .object(["percentage": .integer(50), "output": .string("building")]) )) } - let launch: ToolingJSONValue = .object(["executable": .object(["kind": .string("command"), "value": .string("java")]), + let launch: ToolingJSONValue = .object(["executable": .object(["kind": .string("command"), "value": .string("example-tool")]), "arguments": .array([]), "workingDirectory": .string("."), "environment": .object([:])]) let value: ToolingJSONValue = method == "lithe/build/prepareRun" ? launch : ["lithe/build/execute", "lithe/build/test"].contains(method) ? .object(["exitCode": .integer(0), "output": .string("built")]) @@ -1381,10 +1258,6 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked diagnostics _: [LanguageServerDiagnostic], completionContext: LanguageServerCompletionContext?, completionItem _: LanguageServerCompletionItem?, codeAction _: LanguageServerCodeAction?, command: LanguageServerCommand? ) -> Result { - if operation == .javaEntrypoints { - commandStarted.open() - return .success(LanguageServerRuntimeOperation(operationID: "java-entrypoints")) - } if operation == .executeCommand, command?.command == "example.startDebugSession" { commandStarted.open() return .success(LanguageServerRuntimeOperation(operationID: "debug-start")) @@ -1401,21 +1274,6 @@ private final class ScriptedProviderCore: LanguageServerRuntimeCore, @unchecked } } - func prepareJavaLaunch( - sessionID _: String, fileURL _: URL, mainClass _: String? - ) -> Result { - commandStarted.open() - return .success(LanguageServerRuntimeOperation(operationID: "java-launch")) - } - - func finishJavaLaunch(_ result: ToolingJSONValue) { - lock.withLock { - events["provider-\(nextSession)", default: []].append(LanguageServerRuntimeEvent( - type: "requestCompleted", operationID: "java-launch", result: result - )) - } - } - func cancelLanguageServerOperation(sessionID: String, operationID: String) { lock.withLock { _cancelledOperations.append(operationID) diff --git a/macos/Tests/LitheTests/MacBuildToolResolverTests.swift b/macos/Tests/LitheTests/MacBuildToolResolverTests.swift index ad99243c8e..0f8ea93a24 100644 --- a/macos/Tests/LitheTests/MacBuildToolResolverTests.swift +++ b/macos/Tests/LitheTests/MacBuildToolResolverTests.swift @@ -6,129 +6,6 @@ import Testing @Suite("Build tool resolver version output") @MainActor struct MacBuildToolResolverTests { - @Test - func definedToolchainsKeepEachRootAndSendOnlySelectedEnvironment() async throws { - let files = FileManager.default - let scratch = files.temporaryDirectory.appendingPathComponent("lithe-defined-build-tools-\(UUID().uuidString)") - defer { try? files.removeItem(at: scratch) } - let workspace = scratch.appendingPathComponent("workspace") - try files.createDirectory(at: workspace.appendingPathComponent(".lithe/toolchains"), withIntermediateDirectories: true) - let marker = scratch.appendingPathComponent("probe-ran") - var pins: [String: [String: Any]] = [:] - for root in ["a", "b"] { - let vm = scratch.appendingPathComponent("\(root) vm") - let tool = scratch.appendingPathComponent("\(root) tool") - try files.createDirectory(at: tool.appendingPathComponent("helpers"), withIntermediateDirectories: true) - for (url, output) in [(vm.appendingPathComponent("bin/vm"), "VM 21"), (tool.appendingPathComponent("bin/worker"), "Fixture 1.0")] { - try files.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data("#!/bin/sh\ntouch '\(marker.path)'\nprintf '%s\\n' '\(output)'\n".utf8).write(to: url) - try files.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path) - } - pins[root] = ["compiler": ["home": tool.path, "version": "1.0", "provider": "host:manual"], - "vm": ["home": vm.path, "version": "21", "provider": "host:manual"]] - } - let local = workspace.appendingPathComponent(".lithe/toolchains/local.json") - try JSONSerialization.data(withJSONObject: ["version": 1, "toolchains": [:], "pins": pins]).write(to: local) - let definitions: [[String: Any]] = [("compiler", "worker", "Fixture", []), - ("vm", "vm", "VM", [["name": "JAVA_HOME", "value": "${home}"]])].map { id, executable, label, exports in - ["id": id, "displayName": label, "executableLayouts": [["path": "bin/" + executable]], - "executables": [["id": "pinned", "kind": "setting", "settingID": "executable", "layer": "project"], ["id": "shell", "kind": "command", "command": executable]], - "version": ["arguments": ["--version"], "pattern": label + #" (\d+(?:\.\d+)*)"#], - "commands": [executable], "exports": exports, "pathPrepend": id == "compiler" ? ["${home}/bin", "${home}/helpers"] : ["${home}/bin"], "launch": ["${executable}", "${arguments}"]] - } - let source = ToolchainSettingsPluginSource(pluginID: "dev.lithe.fixture.build-tools", name: "Fixture", - manifest: try JSONSerialization.data(withJSONObject: ["schemaVersion": 2, "id": "dev.lithe.fixture.build-tools", - "displayName": "Fixture", "version": "1.0.0", "pluginAPIVersion": 3, - "requires": ["toolDefinitions": 1, "executableResolution": 2], - "vendor": ["id": "org.example", "displayName": "Fixture", "signatureRequirement": "publisherPackage"], - "permissions": [], "toolDefinitions": definitions]), isEnabled: true) - let defined = MacDefinedToolchainResolver() - defined.sources = { [source] } - let runtime = ProjectRuntimeService(runtimeLocator: CanonicalToolchainRuntimeLocator(), store: ToolchainPreferenceStore()) - runtime.openProject(at: workspace) - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage(), definedTools: defined) - let fixture = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("shared/contracts/plugins/v1/fixtures/build-systems/build-toolchains.plugin.json") - let text = try String(contentsOf: fixture, encoding: .utf8) - .replacingOccurrences(of: "dev.lithe.fixture.build-toolchains:vm", with: "vm") - .replacingOccurrences(of: "dev.lithe.fixture.build-toolchains:compiler", with: "compiler") - var manifest = try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) - var systems = try #require(manifest["buildSystems"] as? [[String: Any]]) - var invocationJSON = try #require(systems[0]["invocation"] as? [String: Any]) - var dependencies = try #require(invocationJSON["runtimeDependencies"] as? [[String: Any]]) - dependencies[0]["id"] = "vm" - dependencies[0]["version"] = ["arguments": ["--version"], "pattern": #"VM (\d+)"#] - invocationJSON["runtimeDependencies"] = dependencies - systems[0]["invocation"] = invocationJSON - manifest["buildSystems"] = systems - let target = BuildSystemTarget(manifest: try JSONSerialization.data(withJSONObject: manifest), buildSystemID: "cargo") - let core = RustBuildSystemOperations(core: RustCoreBridge()) - for root in ["a", "b"] { - let invocation = try core.invocationPlan(target, root: root, settings: [:]) - #expect(resolver.languageImportExecutable(invocation, workspaceURL: workspace) == nil) - #expect(!files.fileExists(atPath: marker.path)) - } - for root in ["a", "b"] { - let invocation = try core.invocationPlan(target, root: root, settings: [:]) - let tool = try await resolver.resolve(invocation, displayName: "Fixture", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - let executable = try #require(MacToolchainDiscovery.realpath(scratch.appendingPathComponent("\(root) tool/bin/worker").path)) - let home = try #require(MacToolchainDiscovery.realpath(scratch.appendingPathComponent("\(root) vm").path)) - #expect(tool.executableURL == URL(fileURLWithPath: executable)) - #expect(tool.environment["JAVA_HOME"] == home) - let helpers = try #require(MacToolchainDiscovery.realpath(scratch.appendingPathComponent("\(root) tool/helpers").path)) - #expect(tool.environment["PATH"]?.split(separator: ":").contains(Substring(helpers)) == true) - #expect(tool.providerEnvironment["JAVA_HOME"] == tool.environment["JAVA_HOME"]) - #expect(tool.environment["FIXTURE_SECRET"] == "test-only-secret") - #expect(tool.providerEnvironment["FIXTURE_SECRET"] == nil) - #expect(!tool.executesProjectCode) - } - let beforeRunChoice = try Data(contentsOf: local) - var sameDirectory = try core.invocationPlan(target, root: "a", settings: [:]) - let alternateExecutable = scratch.appendingPathComponent("b tool/bin/worker") - sameDirectory.toolSelections = ["compiler": .executable(path: alternateExecutable.path), - "vm": .installation(home: scratch.appendingPathComponent("b vm").path)] - let alternate = try await resolver.resolve(sameDirectory, displayName: "Fixture", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - #expect(alternate.executableURL == alternateExecutable) - #expect(alternate.environment["JAVA_HOME"] == MacToolchainDiscovery.realpath(scratch.appendingPathComponent("b vm").path)) - #expect(try Data(contentsOf: local) == beforeRunChoice) - pins["a"]?["compiler"] = ["home": "/fixture/missing-tool", "version": "1", "provider": "host:manual"] - try JSONSerialization.data(withJSONObject: ["version": 1, "toolchains": [:], "pins": pins]).write(to: local) - let invocation = try core.invocationPlan(target, root: "a", settings: [:]) - await #expect(throws: BuildToolResolutionError.self) { - try await resolver.resolve(invocation, displayName: "Fixture", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - } - } - - @Test - func emptySettingSkipsToWrapperAndPassiveSelectionNeverProbes() async throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let marker = root.appendingPathComponent("unexpected-probe") - let wrapper = root.appendingPathComponent("wrapper") - try Data("#!/bin/sh\ntouch '\(marker.path)'\n".utf8).write(to: wrapper) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: wrapper.path) - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) - let invocation = BuildInvocation(executables: [.setting(id: "toolPath", path: nil), .projectFile(path: "wrapper", requires: [])], - versionArguments: ["--version"], minimumVersion: "2") - #expect(resolver.languageImportExecutable(invocation, workspaceURL: root) == wrapper) - let result = try await resolver.resolve(invocation, displayName: "Fixture", workspaceURL: root) { _, _ in - Issue.record("A wrapper must not be probed") - return BuildVersionCheck(satisfied: false, version: nil) - } - #expect(result.executableURL == wrapper) - #expect(result.executesProjectCode) - #expect(!FileManager.default.fileExists(atPath: marker.path)) - let invalid = BuildInvocation(executables: [.setting(id: "toolPath", path: root.appendingPathComponent("missing").path), .projectFile(path: "wrapper", requires: [])]) - #expect(resolver.languageImportExecutable(invalid, workspaceURL: root) == nil) - } - @Test func sharedResolverUsesInjectedEnvironmentCommandAndRuntimeDiscovery() { let custom = URL(fileURLWithPath: "/tools/build") @@ -146,29 +23,6 @@ struct MacBuildToolResolverTests { #expect(resolver.resolve(.environment(variable: "BUILD_HOME", path: "build"), workspaceURL: workspace, environment: ["BUILD_HOME": "/tools"], environmentInputs: []) == .skip) } - @Test - func configuredPathWithSpacesWinsOverDiscoveryAndSuppliesItsDirectory() async throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let executable = root.appendingPathComponent("custom tools/build-tool") - try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data("#!/bin/sh\nprintf 'fixture 2.0\\n'\n".utf8).write(to: executable) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) - let invocation = BuildInvocation( - executables: [.setting(id: "toolPath", path: executable.path), .command("unavailable")], versionArguments: ["--version"], - minimumVersion: "2" - ) - let resolved = try await resolver.resolve(invocation, displayName: "Fixture", workspaceURL: root) { _, output in - BuildVersionCheck(satisfied: output.contains("fixture 2.0"), version: "2.0") - } - #expect(resolved.executableURL == executable) - #expect(resolved.environment["PATH"]?.split(separator: ":").first.map(String.init) - == executable.deletingLastPathComponent().path) - #expect(resolver.languageImportExecutable(invocation, workspaceURL: root) == executable) - } - @Test(arguments: ["missing", "non-executable", "old", "directory"]) func unusableConfiguredPathNeverFallsBackToAvailableWrapper(_ failure: String) async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) @@ -184,7 +38,7 @@ struct MacBuildToolResolverTests { let fallback = root.appendingPathComponent("wrapper") try Data("#!/bin/sh\nexit 0\n".utf8).write(to: fallback) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: fallback.path) - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) + let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root)) let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) let invocation = BuildInvocation( executables: [.setting(id: "toolPath", path: configured.path), .projectFile(path: "wrapper", requires: [])], versionArguments: ["--version"], @@ -202,7 +56,7 @@ struct MacBuildToolResolverTests { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) + let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root)) let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) let invocation = BuildInvocation(executables: [.runtime("custom")], runtimeDependencies: [ .init(id: "custom", hostManaged: false, executables: [.setting(id: "runtimePath", path: root.appendingPathComponent("missing").path), .command("sh")]) @@ -229,7 +83,7 @@ struct MacBuildToolResolverTests { } // The injected environment has no PATH entry for the helper. Only the // candidate-specific environment can make this version probe succeed. - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) + let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root)) let runner = MacProcessRunner() let resolver = MacBuildToolResolver(runtime: runtime, processRunner: runner, fileStorage: MacFileStorage()) let invocation = BuildInvocation(executables: [.runtime("custom")], runtimeDependencies: [ @@ -248,26 +102,6 @@ struct MacBuildToolResolverTests { #expect(output == "fixture 2.0\n") } - @Test - func languageImportDiscoversWrapperWithoutExecutingItOrRuntimeProbes() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let marker = root.appendingPathComponent("unexpected-execution") - let executable = root.appendingPathComponent("wrapper") - try Data("#!/bin/sh\ntouch '\(marker.path)'\n".utf8).write(to: executable) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore()) - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage()) - let invocation = BuildInvocation( - executables: [.projectFile(path: "wrapper", requires: [])], - runtimeDependencies: [.init(id: "java", hostManaged: true, minimumVersion: "8", executables: [], versionArguments: ["-version"])], - versionArguments: ["--version"], minimumVersion: "1" - ) - #expect(resolver.languageImportExecutable(invocation, workspaceURL: root) == executable.standardizedFileURL) - #expect(!FileManager.default.fileExists(atPath: marker.path)) - } - @Test func javaVersionProbeForwardsStderrToVersionCheck() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) @@ -283,9 +117,7 @@ struct MacBuildToolResolverTests { """ try Data(script.utf8).write(to: executable) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - let runtime = ProjectRuntimeService( - runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root)) let resolver = MacBuildToolResolver( runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage() ) @@ -331,9 +163,7 @@ struct MacBuildToolResolverTests { """ try Data(script.utf8).write(to: executable) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - let runtime = ProjectRuntimeService( - runtimeLocator: BuildProbeRuntimeLocator(home: root), store: BuildProbeEmptyStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: BuildProbeRuntimeLocator(home: root)) let resolver = MacBuildToolResolver( runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage() ) @@ -359,38 +189,12 @@ struct MacBuildToolResolverTests { private struct BuildProbeRuntimeLocator: RuntimeLocator { let home: URL func environment() -> [String: String] { ["FIXTURE_JDK": home.path] } - func discover() -> RuntimeDiscoveryResult { .init(javaRuntimes: [], mavenRuntimes: []) } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} - -private struct BuildProbeEmptyStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} } struct CanonicalToolchainRuntimeLocator: RuntimeLocator { func environment() -> [String: String] { ["PATH": "/usr/bin:/bin", "FIXTURE_SECRET": "test-only-secret"] } - func discover() -> RuntimeDiscoveryResult { - Issue.record("An explicit toolchain must not discover other JDKs") - return .init(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { - let url = URL(fileURLWithPath: path) - return isExecutable(at: url.appendingPathComponent("bin/java")) ? url : nil - } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { FileManager.default.isExecutableFile(atPath: url.path) } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } } private final class ToolchainPreferenceStore: KeyValueStore { diff --git a/macos/Tests/LitheTests/MacDevelopmentProfileMigrationTests.swift b/macos/Tests/LitheTests/MacDevelopmentProfileMigrationTests.swift index 952e61feb4..8a34015306 100644 --- a/macos/Tests/LitheTests/MacDevelopmentProfileMigrationTests.swift +++ b/macos/Tests/LitheTests/MacDevelopmentProfileMigrationTests.swift @@ -16,7 +16,7 @@ struct MacDevelopmentProfileMigrationTests { "SUSkippedVersion": "9", "lithe.plugins.pending-code-load": "stale-plugin" ], forName: fixture.sourceDomain) try fixture.write("Lithe/ai-secrets.json", text: "independent-secret-file") - try fixture.write("Lithe/Maven/config.json", text: "maven-settings") + try fixture.write("Lithe/Plugins/sample/config.json", text: "plugin-owned-must-not-import") try fixture.write("Lithe/PluginMarketplace/sources.json", text: "marketplace") try fixture.write("Lithe/PluginMarketplace/downloads/runtime.lock", text: "must-not-import") @@ -32,6 +32,7 @@ struct MacDevelopmentProfileMigrationTests { let target = fixture.destination.appendingPathComponent("Lithe/ai-secrets.json") #expect(try String(contentsOf: target, encoding: .utf8) == "independent-secret-file") #expect(!FileManager.default.fileExists(atPath: fixture.destination.appendingPathComponent("Lithe/PluginMarketplace/downloads").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.destination.appendingPathComponent("Lithe/Plugins").path)) fixture.defaults.set("dev-theme", forKey: "settings.theme") try Data("dev-secret".utf8).write(to: target) diff --git a/macos/Tests/LitheTests/MacJavaTestResultServerTests.swift b/macos/Tests/LitheTests/MacJavaTestResultServerTests.swift deleted file mode 100644 index ce8acbf4f5..0000000000 --- a/macos/Tests/LitheTests/MacJavaTestResultServerTests.swift +++ /dev/null @@ -1,69 +0,0 @@ -import Foundation -import Network -import Testing -@testable import Lithe - -@Suite("Java test result server") -@MainActor -struct MacJavaTestResultServerTests { - @Test - func startReturnsTheListenerPortAndStopCancelsIt() async throws { - let listener = TestJavaTestResultListener(readyPort: 43_128) - let server = MacJavaTestResultServer(listenerFactory: { listener }) - - #expect(try await server.start() == 43_128) - #expect(listener.startCount == 1) - - server.stop() - - #expect(listener.cancelCount == 1) - } - - @Test - func cancellingStartupStopsThePendingListener() async { - let started = TestGate() - let listener = TestJavaTestResultListener(onStart: started.open) - let server = MacJavaTestResultServer(listenerFactory: { listener }) - let startTask = Task { try await server.start() } - defer { - startTask.cancel() - server.stop() - } - - #expect(await started.waitUntilOpen()) - startTask.cancel() - - await #expect(throws: CancellationError.self) { - try await startTask.value - } - #expect(listener.cancelCount == 1) - } -} - -private final class TestJavaTestResultListener: MacJavaTestResultListening { - var onStateChange: ((MacJavaTestResultListenerState) -> Void)? - var onConnection: ((NWConnection) -> Void)? - private(set) var startCount = 0 - private(set) var cancelCount = 0 - - private let readyPort: UInt16? - private let onStart: (() -> Void)? - - init(readyPort: UInt16? = nil, onStart: (() -> Void)? = nil) { - self.readyPort = readyPort - self.onStart = onStart - } - - func start(queue _: DispatchQueue) { - startCount += 1 - onStart?() - if let readyPort { - onStateChange?(.ready(port: readyPort)) - } - } - - func cancel() { - cancelCount += 1 - onStateChange?(.cancelled) - } -} diff --git a/macos/Tests/LitheTests/MacJdtHostIntegrationStateTests.swift b/macos/Tests/LitheTests/MacJdtHostIntegrationStateTests.swift deleted file mode 100644 index 09f8e6fd0b..0000000000 --- a/macos/Tests/LitheTests/MacJdtHostIntegrationStateTests.swift +++ /dev/null @@ -1,161 +0,0 @@ -import Foundation -@testable import Lithe -import LitheCoreContracts -import LitheModuleAPI -import Testing - -/// What happens to the JDT LS state in the host cache when the plugin that -/// declares the `jdt` integration goes away. The state sits next to other -/// language servers' caches, outside the plugin's own state directory, so the -/// integration has to discard it itself. -@Suite("macOS JDT LS plugin state removal") -@MainActor -struct MacJdtHostIntegrationStateTests { - @Test - func removedJavaSupportTakesItsIndexesAndEquinoxAreasWithIt() async throws { - let fixture = try makeFixture() - defer { fixture.remove() } - let javaSupport = try installedJavaSupport(status: .removed) - - fixture.integration.pluginsDidLoad([], installed: [javaSupport]) - await fixture.integration.stateRemoval?.value - - #expect(!FileManager.default.fileExists(atPath: fixture.workspaceIndexURL.path)) - #expect(!FileManager.default.fileExists(atPath: fixture.equinoxAreaURL.path)) - // Other servers' caches in the same host directory are not JDT's. - #expect(FileManager.default.fileExists(atPath: fixture.unrelatedCacheURL.path)) - } - - @Test - func uninstalledJavaSupportTakesItsStateWithIt() async throws { - let fixture = try makeFixture() - defer { fixture.remove() } - - fixture.integration.pluginsDidLoad([], installed: []) - await fixture.integration.stateRemoval?.value - - #expect(!FileManager.default.fileExists(atPath: fixture.workspaceIndexURL.path)) - #expect(!FileManager.default.fileExists(atPath: fixture.equinoxAreaURL.path)) - #expect(FileManager.default.fileExists(atPath: fixture.unrelatedCacheURL.path)) - } - - @Test - func installedJavaSupportKeepsItsStateEvenWhileDisabledOrRejected() async throws { - let fixture = try makeFixture() - defer { fixture.remove() } - let javaSupport = try installedJavaSupport(status: .installed) - - // Accepted (a disabled plugin is accepted too). - fixture.integration.pluginsDidLoad([javaSupport], installed: [javaSupport]) - await fixture.integration.stateRemoval?.value - // Installed but rejected at startup: not registered, still installed. - fixture.integration.pluginsDidLoad([], installed: [javaSupport]) - await fixture.integration.stateRemoval?.value - - #expect(FileManager.default.fileExists(atPath: fixture.workspaceIndexURL.path)) - #expect(FileManager.default.fileExists(atPath: fixture.equinoxAreaURL.path)) - } - - @Test - func aFailedPluginScanNeverDeletesState() async throws { - let fixture = try makeFixture() - defer { fixture.remove() } - - fixture.integration.pluginsDidLoad([], installed: nil) - await fixture.integration.stateRemoval?.value - - #expect(fixture.integration.stateRemoval == nil) - #expect(FileManager.default.fileExists(atPath: fixture.workspaceIndexURL.path)) - #expect(FileManager.default.fileExists(atPath: fixture.equinoxAreaURL.path)) - } - - // MARK: - Fixture - - private struct Fixture { - let root: URL - let integration: MacJdtHostIntegration - /// `/jdtls/`: JDT LS's `-data` directory. - let workspaceIndexURL: URL - /// `/jdtls-configuration//configuration`: Equinox area. - let equinoxAreaURL: URL - let unrelatedCacheURL: URL - - func remove() { try? FileManager.default.removeItem(at: root) } - } - - private func makeFixture() throws -> Fixture { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-jdt-state-\(UUID().uuidString)", isDirectory: true) - let cacheURL = root.appendingPathComponent("language-servers", isDirectory: true) - let key = String(repeating: "a", count: 64) - let workspaceIndexURL = cacheURL.appendingPathComponent("jdtls/\(key)", isDirectory: true) - let equinoxAreaURL = cacheURL - .appendingPathComponent("jdtls-configuration/\(key)/configuration", isDirectory: true) - let unrelatedCacheURL = cacheURL.appendingPathComponent("other-server", isDirectory: true) - for directory in [workspaceIndexURL, equinoxAreaURL, unrelatedCacheURL] { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - try Data("state".utf8).write(to: directory.appendingPathComponent("marker")) - } - - let directories = MacPluginStateDirectories(rootURL: root.appendingPathComponent("plugin-state")) - let integration = MacJdtHostIntegration( - launchResolver: MacPluginLanguageServerLaunchResolver( - planner: DeclarativePluginTestSupport.operations, - directories: directories, - settings: InMemoryPluginSettings() - ), - runtimeService: ProjectRuntimeService( - runtimeLocator: EmptyRuntimeLocator(), - store: DiscardingKeyValueStore() - ), - workspaceState: MacJdtWorkspaceState( - cacheDirectoryURL: cacheURL, - workspaceKeyResolver: { _, _ in key } - ) - ) - return Fixture( - root: root, - integration: integration, - workspaceIndexURL: workspaceIndexURL, - equinoxAreaURL: equinoxAreaURL, - unrelatedCacheURL: unrelatedCacheURL - ) - } - - private func installedJavaSupport(status: PluginInstallationStatus) throws -> InstalledPluginPackage { - let descriptor = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - return InstalledPluginPackage( - descriptor: descriptor, - installation: PluginInstallationRecord( - pluginID: descriptor.id, - activeVersion: descriptor.pluginManifest.version, - origin: .bundled, - status: status - ), - packageURL: DeclarativePluginTestSupport.repositoryRoot - .appendingPathComponent("Plugins/mac/Official/JavaSupport") - ) - } -} - -private struct EmptyRuntimeLocator: RuntimeLocator { - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} - -private struct DiscardingKeyValueStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} - func removeObject(forKey key: String) {} -} diff --git a/macos/Tests/LitheTests/MacJdtWorkspaceStateTests.swift b/macos/Tests/LitheTests/MacJdtWorkspaceStateTests.swift deleted file mode 100644 index f861cf3c9b..0000000000 --- a/macos/Tests/LitheTests/MacJdtWorkspaceStateTests.swift +++ /dev/null @@ -1,270 +0,0 @@ -import Foundation -import Testing -@testable import Lithe - -@Suite("macOS JDT LS workspace state") -struct MacJdtWorkspaceStateTests { - @Test - func fingerprintIncludesLanguageServerVersionAndInstallationPath() throws { - let fixture = try makeFixture() - defer { fixture.remove() } - - let state = MacJdtWorkspaceState( - cacheDirectoryURL: fixture.cacheURL, - workspaceFingerprintResolver: { buildFiles, modules, identity in - #expect(buildFiles.isEmpty) - #expect(modules.isEmpty) - #expect(identity == "7.6.5|installation=\(fixture.executableURL.path)") - return "core-fingerprint" - }, - workspaceKeyResolver: { _, _ in String(repeating: "a", count: 64) } - ) - - let fingerprint = try state.fingerprint( - at: fixture.workspaceURL, - languageServerExecutableURL: fixture.executableURL - ) - - #expect(fingerprint == "core-fingerprint") - } - - @Test - func fingerprintObservesRootBuildFilesAndDirectMavenModules() throws { - let fixture = try makeFixture() - defer { fixture.remove() } - let capture = FingerprintObservationCapture() - let state = MacJdtWorkspaceState( - cacheDirectoryURL: fixture.cacheURL, - workspaceFingerprintResolver: { buildFiles, modules, version in - capture.record(buildFiles: buildFiles, modules: modules, version: version) - return "core-fingerprint" - }, - workspaceKeyResolver: { _, _ in String(repeating: "a", count: 64) } - ) - _ = try state.fingerprint( - at: fixture.workspaceURL, - languageServerExecutableURL: fixture.executableURL - ) - #expect(capture.last?.buildFiles.isEmpty == true) - - try write("a", to: fixture.workspaceURL.appendingPathComponent("pom.xml")) - _ = try state.fingerprint( - at: fixture.workspaceURL, - languageServerExecutableURL: fixture.executableURL - ) - let beforeEdit = capture.last?.buildFiles - #expect(beforeEdit?.map(\.path) == ["pom.xml"]) - // Editing a descriptor keeps the JDT LS state: JDT LS updates the - // changed projects itself instead of reimporting the workspace. - let pomURL = fixture.workspaceURL.appendingPathComponent("pom.xml") - try write("a larger project descriptor", to: pomURL) - try setModificationDate(Date(timeIntervalSince1970: 2_000_000_000), for: pomURL) - _ = try state.fingerprint( - at: fixture.workspaceURL, - languageServerExecutableURL: fixture.executableURL - ) - #expect(capture.last?.buildFiles == beforeEdit) - - for moduleName in ["zeta", "alpha"] { - let moduleURL = fixture.workspaceURL.appendingPathComponent( - moduleName, - isDirectory: true - ) - try FileManager.default.createDirectory( - at: moduleURL, - withIntermediateDirectories: true - ) - try write("", to: moduleURL.appendingPathComponent("pom.xml")) - } - let gradleOnlyURL = fixture.workspaceURL.appendingPathComponent( - "gradle-only", - isDirectory: true - ) - try FileManager.default.createDirectory( - at: gradleOnlyURL, - withIntermediateDirectories: true - ) - try write("plugins {}", to: gradleOnlyURL.appendingPathComponent("build.gradle")) - _ = try state.fingerprint( - at: fixture.workspaceURL, - languageServerExecutableURL: fixture.executableURL - ) - - #expect(Set(capture.last?.modules ?? []) == Set(["alpha", "zeta"])) - #expect(capture.last?.version == "7.6.5|installation=\(fixture.executableURL.path)") - } - - @Test - func clearIndexRemovesOnlyTheResolvedWorkspaceKey() throws { - let fixture = try makeFixture() - defer { fixture.remove() } - let currentKey = String(repeating: "a", count: 64) - let siblingKey = String(repeating: "b", count: 64) - let jdtlsCacheURL = fixture.cacheURL.appendingPathComponent("jdtls", isDirectory: true) - let currentURL = jdtlsCacheURL.appendingPathComponent(currentKey, isDirectory: true) - let siblingURL = jdtlsCacheURL.appendingPathComponent(siblingKey, isDirectory: true) - try FileManager.default.createDirectory(at: currentURL, withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: siblingURL, withIntermediateDirectories: true) - try write("current", to: currentURL.appendingPathComponent("index.bin")) - try write("sibling", to: siblingURL.appendingPathComponent("index.bin")) - let state = MacJdtWorkspaceState( - cacheDirectoryURL: fixture.cacheURL, - workspaceKeyResolver: { rootURL, fingerprint in - #expect(rootURL == fixture.workspaceURL.standardizedFileURL) - #expect(fingerprint == "current-fingerprint") - return currentKey - } - ) - - try state.clearIndex( - at: fixture.workspaceURL, - workspaceFingerprint: "current-fingerprint" - ) - - #expect(!FileManager.default.fileExists(atPath: currentURL.path)) - #expect(FileManager.default.fileExists(atPath: siblingURL.path)) - } - - @Test - func cacheCleanupRemovesOnlyCoreSelectedInactiveDirectories() throws { - let fixture = try makeFixture() - defer { fixture.remove() } - let expiredKey = String(repeating: "a", count: 64) - let recentKey = String(repeating: "b", count: 64) - let activeKey = String(repeating: "c", count: 64) - let linkedKey = String(repeating: "d", count: 64) - let now = Date(timeIntervalSince1970: 4_000_000) - let jdtlsCacheURL = fixture.cacheURL.appendingPathComponent("jdtls", isDirectory: true) - for key in [expiredKey, recentKey, activeKey] { - try FileManager.default.createDirectory( - at: jdtlsCacheURL.appendingPathComponent(key, isDirectory: true), - withIntermediateDirectories: true - ) - } - try FileManager.default.createSymbolicLink( - at: jdtlsCacheURL.appendingPathComponent(linkedKey), - withDestinationURL: jdtlsCacheURL.appendingPathComponent(recentKey, isDirectory: true) - ) - try FileManager.default.createDirectory( - at: jdtlsCacheURL.appendingPathComponent("not-a-cache-key", isDirectory: true), - withIntermediateDirectories: true - ) - try setModificationDate( - Date(timeIntervalSince1970: 1_000_000), - for: jdtlsCacheURL.appendingPathComponent(expiredKey, isDirectory: true) - ) - try setModificationDate( - Date(timeIntervalSince1970: 3_999_999), - for: jdtlsCacheURL.appendingPathComponent(recentKey, isDirectory: true) - ) - try setModificationDate( - Date(timeIntervalSince1970: 1), - for: jdtlsCacheURL.appendingPathComponent(activeKey, isDirectory: true) - ) - - let state = MacJdtWorkspaceState( - cacheDirectoryURL: fixture.cacheURL, - workspaceKeyResolver: { _, _ in activeKey }, - cacheRetentionPlanner: { nowUnixSeconds, activeWorkspaceKey, entries in - #expect(nowUnixSeconds == 4_000_000) - #expect(activeWorkspaceKey == activeKey) - #expect(Set(entries.map(\.workspaceKey)) == Set([ - expiredKey, - recentKey, - activeKey, - ])) - #expect(entries.first(where: { $0.workspaceKey == activeKey })? - .lastModifiedUnixSeconds == 4_000_000) - return RustCoreBridge.JdtCacheRetentionPayload( - retentionDays: 30, - expiredWorkspaceKeys: [expiredKey] - ) - } - ) - - let result = try state.pruneExpiredCaches( - at: fixture.workspaceURL, - workspaceFingerprint: "active-fingerprint", - now: now - ) - - #expect(result == MacJdtCacheCleanupResult( - retentionDays: 30, - removedWorkspaceKeys: [expiredKey] - )) - #expect(!FileManager.default.fileExists( - atPath: jdtlsCacheURL.appendingPathComponent(expiredKey).path - )) - for key in [recentKey, activeKey, linkedKey, "not-a-cache-key"] { - #expect(FileManager.default.fileExists( - atPath: jdtlsCacheURL.appendingPathComponent(key).path - )) - } - } - - private func makeFixture() throws -> Fixture { - let rootURL = FileManager.default.temporaryDirectory.appendingPathComponent( - "lithe-jdt-workspace-state-\(UUID().uuidString)", - isDirectory: true - ) - let workspaceURL = rootURL.appendingPathComponent("workspace", isDirectory: true) - let cacheURL = rootURL.appendingPathComponent("cache", isDirectory: true) - let jdtlsURL = rootURL.appendingPathComponent("jdtls", isDirectory: true) - let binURL = jdtlsURL.appendingPathComponent("bin", isDirectory: true) - try FileManager.default.createDirectory( - at: workspaceURL, - withIntermediateDirectories: true - ) - try FileManager.default.createDirectory(at: cacheURL, withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: binURL, withIntermediateDirectories: true) - try write(#"{"version":"7.6.5"}"#, to: jdtlsURL.appendingPathComponent("manifest.json")) - let executableURL = binURL.appendingPathComponent("jdtls") - try write("#!/bin/zsh\n", to: executableURL) - return Fixture( - rootURL: rootURL, - workspaceURL: workspaceURL, - cacheURL: cacheURL, - executableURL: executableURL - ) - } - - private func write(_ value: String, to url: URL) throws { - try Data(value.utf8).write(to: url) - } - - private func setModificationDate(_ date: Date, for url: URL) throws { - try FileManager.default.setAttributes( - [.modificationDate: date], - ofItemAtPath: url.path - ) - } -} - -private final class FingerprintObservationCapture { - struct Entry { - let buildFiles: [RustCoreBridge.JdtBuildFileObservation] - let modules: [String] - let version: String - } - - private(set) var last: Entry? - - func record( - buildFiles: [RustCoreBridge.JdtBuildFileObservation], - modules: [String], - version: String - ) { - last = Entry(buildFiles: buildFiles, modules: modules, version: version) - } -} - -private struct Fixture { - let rootURL: URL - let workspaceURL: URL - let cacheURL: URL - let executableURL: URL - - func remove() { - try? FileManager.default.removeItem(at: rootURL) - } -} diff --git a/macos/Tests/LitheTests/MacLegacyMavenRunConfigurationMigrationTests.swift b/macos/Tests/LitheTests/MacLegacyMavenRunConfigurationMigrationTests.swift deleted file mode 100644 index b6334a32fe..0000000000 --- a/macos/Tests/LitheTests/MacLegacyMavenRunConfigurationMigrationTests.swift +++ /dev/null @@ -1,476 +0,0 @@ -import Foundation -import LitheCoreContracts -import Testing -@testable import Lithe - -@Suite("Legacy Maven Run migration") -@MainActor -struct MacLegacyMavenRunConfigurationMigrationTests { - @Test(arguments: [false, true]) - func moduleChoicesRemainDataAndAnEmptyGoalListIsLeftToTheProvider(runtimeChoice: Bool) throws { - let fixture = try Fixture() - defer { fixture.remove() } - let id = "maven.module:nested/app" - try fixture.write(["version": 2, "configurations": [["id": id, "name": "Module", "provider": "maven.module", "execution": "task", "args": [], - "extensions": ["maven": ["module": "app", "mainClass": runtimeChoice ? "opaque/entry" : "", "jvmArguments": runtimeChoice ? ["-Dsaved=value"] : []]]]]], to: fixture.team) - try fixture.write(["version": 2, "configurations": []], to: fixture.local) - let reference = BuildProviderRunReference(pluginID: "io.github.lithe-idea.maven-build", buildSystemID: "maven", root: "nested", run: "module", - projectID: "p", targetID: "opaque/module", execution: .task) - let runs = [RunProviderConfiguration(projectPath: "nested/app", name: "Module", reference: reference)] - let models = [try JSONDecoder().decode(BuildModel.self, from: Data(#"{"projects":[{"id":"p","path":"nested/app","name":"app"}],"targets":[{"id":"opaque/module","projectID":"p","name":"maven.module","path":"nested/app","tags":["maven-module"]}]}"#.utf8))] - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: MigrationPreferences()) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: runs, models: models, lease: RunConfigurationGenerationLease()) - let input = try store.providerLaunchInputs(at: fixture.root, configurationID: id, providerRoot: "nested") - #expect(input.reference == reference) - #expect(input.launchOptions.arguments == []) - #expect(input.launchOptions.runtimeArguments == (runtimeChoice ? ["-Dsaved=value"] : [])) - #expect(input.launchOptions.entrypoint == (runtimeChoice ? "opaque/entry" : nil)) - } - - @Test(arguments: [false, true]) - func explicitToolsKeepEachRunAndLocalClearWithoutChangingDirectoryPins(clearLocal: Bool) throws { - let fixture = try Fixture() - defer { fixture.remove() } - var team = try fixture.read(fixture.team) - var entries = try #require(team["configurations"] as? [[String: Any]]) - var first = entries[0], firstExtensions = try #require(first["extensions"] as? [String: Any]) - firstExtensions["java"] = ["mavenExecutablePath": "/fixture/team launcher", "mavenJavaHomePath": "/fixture/team vm"] - first["extensions"] = firstExtensions - var second = first, secondExtensions = firstExtensions - second["id"] = "user:second-service" - secondExtensions["java"] = ["mavenExecutablePath": "/fixture/second launcher", "mavenJavaHomePath": "/fixture/second vm"] - second["extensions"] = secondExtensions - entries = [first, second]; team["configurations"] = entries - try fixture.write(team, to: fixture.team) - var local = try fixture.read(fixture.local) - var overrides = try #require(local["configurations"] as? [[String: Any]]) - var localExtensions = try #require(overrides[0]["extensions"] as? [String: Any]) - localExtensions["java"] = ["mavenExecutablePath": clearLocal ? "" : "/fixture/local launcher"] - overrides[0]["extensions"] = localExtensions; local["configurations"] = overrides - try fixture.write(local, to: fixture.local) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: MigrationPreferences()) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - let firstInput = try store.providerLaunchInputs(at: fixture.root, configurationID: fixture.id, providerRoot: "nested") - #expect(firstInput.tools["io.github.lithe-idea.maven-build:maven"] == (clearLocal ? nil : .executable(path: "/fixture/local launcher"))) - #expect(firstInput.tools["java"] == .installation(home: "/fixture/team vm")) - let secondInput = try store.providerLaunchInputs(at: fixture.root, configurationID: "user:second-service", providerRoot: "nested") - #expect(secondInput.tools["io.github.lithe-idea.maven-build:maven"] == .executable(path: "/fixture/second launcher")) - #expect(secondInput.tools["java"] == .installation(home: "/fixture/second vm")) - #expect(!FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent(".lithe/toolchains/local.json").path)) - let before = try fixture.bytes() - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - #expect(try fixture.bytes() == before) - } - - @Test - func preferenceOnlyExplicitToolsTransferToTheGenericRunAndRetainTheSource() throws { - let fixture = try Fixture() - defer { fixture.remove() } - try FileManager.default.removeItem(at: fixture.local) - let preferences = MigrationPreferences() - let key = "lithe.java-run-options.\(fixture.root.path.replacingOccurrences(of: "/", with: "_")).\(fixture.id)" - let source = try JSONEncoder().encode(RunOptions(mavenExecutablePath: "/fixture/preference launcher", mavenJavaHomePath: "/fixture/preference vm")) - preferences.set(source, forKey: key) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - let inputs = try store.providerLaunchInputs(at: fixture.root, configurationID: fixture.id, providerRoot: "nested") - #expect(inputs.tools == ["io.github.lithe-idea.maven-build:maven": .executable(path: "/fixture/preference launcher"), - "java": .installation(home: "/fixture/preference vm")]) - #expect(preferences.data(forKey: key) == source) - } - - @Test(arguments: ["project", "directory", "preferences", "relative", "control"]) - func unrepresentableDefaultsAndInvalidExplicitToolsKeepAllSources(kind: String) throws { - let fixture = try Fixture() - defer { fixture.remove() } - let preferences = MigrationPreferences() - var local = try fixture.read(fixture.local) - if kind == "project" { local["toolchain"] = ["maven": ["javaHomePath": "/fixture/project vm"]] } - if kind == "directory" { local["toolchain"] = ["pathOverrides": ["nested": ["mavenExecutablePath": "/fixture/project launcher"]]] } - if kind == "preferences" { - preferences.set(try JSONSerialization.data(withJSONObject: ["mavenJavaHomePath": "/fixture/inherited vm"]), - forKey: MacProjectRuntimeSettingsStore.preferencesKey(fixture.root)) - } - if kind == "relative" || kind == "control" { - var entries = try #require(local["configurations"] as? [[String: Any]]) - var ext = try #require(entries[0]["extensions"] as? [String: Any]) - ext["java"] = ["mavenExecutablePath": kind == "relative" ? "relative/launcher" : "/fixture/bad\nlauncher"] - entries[0]["extensions"] = ext; local["configurations"] = entries - } - try fixture.write(local, to: fixture.local) - let before = try fixture.bytes() - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - #expect(throws: (any Error).self) { - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - } - #expect(try fixture.bytes() == before) - } - - @Test(arguments: [false, true]) - func activePreferencesTransferOnceWithoutDroppingJavaOrReplacingLocalChoices(localMissing: Bool) throws { - let fixture = try Fixture() - defer { fixture.remove() } - let domain = "lithe.legacy-run-preferences.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: domain)) - defer { defaults.removePersistentDomain(forName: domain) } - let preferences = MacUserDefaultsStore(defaults: defaults) - let prefix = "lithe.java-run-options.\(fixture.root.path.replacingOccurrences(of: "/", with: "_"))." - let serviceBytes = try JSONEncoder().encode(RunOptions(workingDirectoryPath: fixture.root.appendingPathComponent("nested/app/work").path, - vmArguments: "'-Dvalue=one two' '\\literal'", programArguments: "'--value=two words' 雪", activeProfiles: ["release"], - mavenSkipTests: false, environment: ["FROM": "preference"])) - preferences.set(serviceBytes, forKey: prefix + fixture.id) - if localMissing { - try FileManager.default.removeItem(at: fixture.local) - try fixture.write(["version": 2, "configurations": [["id": "user:java", "name": "Unrelated Java", "provider": "java.current-file", "execution": "application"]]], to: fixture.team) - preferences.set(try JSONEncoder().encode(RunOptions(vmArguments: "-Djava=okay", programArguments: "before", environment: ["JAVA_KEEP": "value"])), forKey: prefix + "user:java") - } - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - let inputs = try store.providerLaunchInputs(at: fixture.root, configurationID: fixture.id, providerRoot: "nested") - #expect(inputs.launchOptions.runtimeArguments == ["-Dvalue=one two", "\\literal"]) - #expect(inputs.launchOptions.workingDirectory == "nested/app/work") - #expect(inputs.launchOptions.arguments == (localMissing ? ["--value=two words", "雪"] : ["--local=雪"])) - #expect(inputs.launchOptions.environment == (localMissing ? ["FROM": "preference"] : ["EXAMPLE": "local"])) - #expect(inputs.optionOverrides["profiles"] == (localMissing ? .array([.string("release")]) : nil)) - #expect(inputs.optionOverrides["skipTests"] == .bool(false)) - if localMissing { - let resolved = try store.resolve(at: fixture.root, toolchainCandidates: []) - let java = try #require(resolved.configurations.first { $0.configuration.id == "user:java" }) - #expect(java.options.vmArguments == "-Djava=okay") - #expect(java.options.environment == ["JAVA_KEEP": "value"]) - #expect((try FileManager.default.attributesOfItem(atPath: fixture.local.path)[.posixPermissions] as? NSNumber)?.intValue == 0o600) - } - let before = try fixture.bytes() - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - #expect(try fixture.bytes() == before) - #expect(preferences.data(forKey: prefix + fixture.id) == serviceBytes, "Retired source remains a rollback record; generic documents are authoritative") - } - - @Test - func preferenceOnlyCancellationRemovesOnlyOurNewFileAndEmptyDirectories() throws { - let fixture = try Fixture() - defer { fixture.remove() } - try FileManager.default.removeItem(at: fixture.root.appendingPathComponent(".lithe")) - let preferences = MigrationPreferences(), storage = MigrationFaultStorage(), lease = RunConfigurationGenerationLease() - let key = "lithe.java-run-options.\(fixture.root.path.replacingOccurrences(of: "/", with: "_")).\(fixture.id)" - let bytes = try JSONEncoder().encode(RunOptions(programArguments: "--saved")) - preferences.set(bytes, forKey: key) - let migration = MacLegacyMavenRunConfigurationMigration(storage: storage, preferences: preferences, immutableRoots: []) - let plan = try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) - #expect(plan.writes.count == 1) - storage.afterReplace = { _ in lease.invalidate() } - #expect(throws: (any Error).self) { try migration.apply(plan, workspace: fixture.root, lease: lease) } - #expect(!FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent(".lithe").path)) - #expect(preferences.data(forKey: key) == bytes) - } - - @Test - func aChangedActivePreferenceRollsBackOurFilesAndRetainsTheNewSource() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let preferences = MigrationPreferences(), storage = MigrationFaultStorage(), lease = RunConfigurationGenerationLease() - let key = "lithe.java-run-options.\(fixture.root.path.replacingOccurrences(of: "/", with: "_")).\(fixture.id)" - preferences.set(try JSONEncoder().encode(RunOptions(vmArguments: "-Dbefore=value")), forKey: key) - let migration = MacLegacyMavenRunConfigurationMigration(storage: storage, preferences: preferences, immutableRoots: []) - let plan = try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) - let original = try fixture.bytes(), external = try JSONEncoder().encode(RunOptions(vmArguments: "-Dexternal=value")) - storage.afterReplace = { index in if index == 1 { preferences.set(external, forKey: key) } } - #expect(throws: (any Error).self) { try migration.apply(plan, workspace: fixture.root, lease: lease) } - #expect(try fixture.bytes() == original) - #expect(preferences.data(forKey: key) == external) - } - - @Test(arguments: ["both-v1", "team-v1", "local-v1"]) - func retiredV1LayersKeepStableIdentitiesAndUnrelatedJavaEntries(format: String) throws { - let fixture = try Fixture() - defer { fixture.remove() } - if format != "local-v1" { - try fixture.write(["version": 1, "annotation": "v1 team", "configurations": [ - ["id": fixture.id, "name": "Saved service", "type": "quarkus.maven", "module": "app", "workingDirectory": "nested", - "mainClass": "opaque/entry:1", "jvmArguments": ["-Dvalue=one two", "雪"], "programArguments": ["--team"], "mavenProfiles": ["team"]], - ["id": "user:java", "name": "Unrelated Java", "type": "java.current-file", "workingDirectory": "."] - ]], to: fixture.team) - } - if format != "team-v1" { - try fixture.write(["version": 1, "annotation": "v1 local", "configurations": [ - ["id": fixture.id, "workingDirectory": "nested/app/work", "programArguments": ["--local=雪"], "mavenProfiles": ["local"]] - ]], to: fixture.local) - } - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: MigrationPreferences()) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - let resolved = try store.resolve(at: fixture.root, toolchainCandidates: []) - #expect(resolved.configurations.filter { $0.configuration.buildProvider != nil }.map { $0.configuration.id } == [fixture.id]) - #expect(resolved.defaultConfigurationID == fixture.id) - let inputs = try store.providerLaunchInputs(at: fixture.root, configurationID: fixture.id, providerRoot: "nested") - #expect(inputs.launchOptions.entrypoint == "opaque/entry:1") - #expect(inputs.launchOptions.arguments == ["--local=雪"]) - #expect(inputs.launchOptions.workingDirectory == "nested/app/work") - if format != "team-v1" { #expect(inputs.optionOverrides["profiles"] == .array([.string("local")])) } - if format != "local-v1" { - #expect(resolved.configurations.contains { $0.configuration.id == "user:java" && $0.configuration.kind == .currentFile }) - #expect((try fixture.read(fixture.team)["version"] as? Int) == 2) - } - let before = try fixture.bytes() - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - #expect(try fixture.bytes() == before) - } - - @Test - func generationMigratesBothLayersWithStableIDsAndNoDuplicateService() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let preferences = MigrationPreferences() - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - let manifest = try Data(contentsOf: fixture.root.appendingPathComponent(".lithe/project.json")) - try FileManager.default.setAttributes([.posixPermissions: 0o640], ofItemAtPath: fixture.team.path) - try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.local.path) - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - let resolution = try store.resolve(at: fixture.root, toolchainCandidates: []) - let service = try #require(resolution.configurations.first) - #expect(resolution.configurations.count == 1) - #expect(service.configuration.id == fixture.id) - #expect(service.configuration.buildProvider == fixture.runs[0].reference) - #expect(resolution.defaultConfigurationID == fixture.id) - #expect(!resolution.diagnostics.contains { $0.code == "orphanedOverride" }) - let inputs = try store.providerLaunchInputs(at: fixture.root, configurationID: fixture.id, providerRoot: "nested") - #expect(inputs.launchOptions.runtimeArguments == ["--runtime=one two", "", "雪"]) - #expect(inputs.launchOptions.entrypoint == "opaque/entry:1") - #expect(inputs.launchOptions.arguments == ["--local=雪"]) - #expect(inputs.launchOptions.environment == ["EXAMPLE": "local"]) - #expect(inputs.launchOptions.workingDirectory == "nested/app/work") - #expect(inputs.optionOverrides == ["skipTests": .bool(false)]) - let team = try fixture.read(fixture.team), local = try fixture.read(fixture.local) - #expect((team["annotation"] as? String) == "keep document metadata") - #expect(((team["configurations"] as? [[String: Any]])?.first?["extensions"] as? [String: Any])?["maven"] == nil) - #expect((((team["configurations"] as? [[String: Any]])?.first?["extensions"] as? [String: Any])?["annotations"] as? [String: Bool]) == ["keep": true]) - #expect((local["annotation"] as? String) == "keep local metadata") - #expect(try Data(contentsOf: fixture.root.appendingPathComponent(".lithe/project.json")) == manifest) - #expect((try FileManager.default.attributesOfItem(atPath: fixture.team.path)[.posixPermissions] as? NSNumber)?.intValue == 0o640) - #expect((try FileManager.default.attributesOfItem(atPath: fixture.local.path)[.posixPermissions] as? NSNumber)?.intValue == 0o600) - let bytes = try fixture.bytes() - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - #expect(try fixture.bytes() == bytes, "A successful cutover is idempotent without another receipt file") - #expect(!FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent(".lithe/run/generated.json").path)) - } - - @Test(arguments: ["tools", "version", "ambiguous", "preferences", "saved-preferences", "invalid-entrypoint", "changed-framework", "invalid-maven", "invalid-selector", "custom-debug"]) - func unsupportedSourcesAndFailedPreflightLeaveBothDocumentsUntouched(reason: String) throws { - let fixture = try Fixture() - defer { fixture.remove() } - let preferences = MigrationPreferences() - var team = try fixture.read(fixture.team) - var entries = try #require(team["configurations"] as? [[String: Any]]) - var entry = entries[0], extensions = try #require(entry["extensions"] as? [String: Any]) - if reason == "tools" { extensions["java"] = ["homePath": "/fixture/custom-jdk"]; entry["extensions"] = extensions } - if reason == "invalid-maven" { extensions["maven"] = "invalid legacy value"; entry["extensions"] = extensions } - if reason == "invalid-selector" { - var maven = try #require(extensions["maven"] as? [String: Any]); maven["module"] = 42 - extensions["maven"] = maven; entry["extensions"] = extensions - } - if reason == "custom-debug" { entry["debug"] = ["adapter": "dev.example.custom"] } - if reason == "saved-preferences" { - entry["id"] = "user:legacy-service" - var local = try fixture.read(fixture.local), localItems = try #require(fixture.read(fixture.local)["configurations"] as? [[String: Any]]) - localItems[0]["id"] = "user:legacy-service"; local["configurations"] = localItems - try fixture.write(local, to: fixture.local) - } - if reason == "version" { team["version"] = 1 } - if reason == "invalid-entrypoint" { - var maven = try #require(extensions["maven"] as? [String: Any]); maven["mainClass"] = String(repeating: "a", count: 4097) - extensions["maven"] = maven; entry["extensions"] = extensions - } - entries[0] = entry; team["configurations"] = entries - try fixture.write(team, to: fixture.team) - var runs = fixture.runs - if reason == "ambiguous" { - let other = BuildProviderRunReference(pluginID: "io.github.lithe-idea.maven-build", buildSystemID: "maven", root: "nested", - run: "framework", projectID: "p", targetID: "other/opaque", execution: .service) - runs.append(RunProviderConfiguration(projectPath: "nested/app", name: "Other", reference: other)) - } - if reason == "preferences" || reason == "saved-preferences" { - let key = fixture.root.path.replacingOccurrences(of: "/", with: "_") - let id = reason == "saved-preferences" ? "user:legacy-service" : fixture.id - preferences.set(Data("retired choices".utf8), forKey: "lithe.java-run-options.\(key).\(id)") - } - let before = try fixture.bytes() - let models: [BuildModel] - if reason == "changed-framework" { - models = [try JSONDecoder().decode(BuildModel.self, from: Data(#"{"projects":[{"id":"p","path":"nested/app","name":"app"}],"targets":[{"id":"opaque/service","projectID":"p","name":"micronaut.maven","path":"nested/app","tags":["maven-service"]}]}"#.utf8))] - } else { models = try fixture.models } - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - #expect(throws: (any Error).self) { - _ = try store.generate(at: fixture.root, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: fixture.projects, providerRuns: runs, models: models, lease: RunConfigurationGenerationLease()) - } - #expect(try fixture.bytes() == before) - } - - @Test(arguments: ["before", "after-first-write", "after-second-write", "second-file-conflict", "changed-source", "changed-first-during-rollback", "changed-local-after-write", "preferences-created-during-write", "marker-changed-during-write"]) - func cancellationAndConflictsUseConditionalRollbackWithoutOverwritingNewerBytes(mode: String) throws { - let fixture = try Fixture() - defer { fixture.remove() } - let lease = RunConfigurationGenerationLease(), storage = MigrationFaultStorage(), preferences = MigrationPreferences() - let migration = MacLegacyMavenRunConfigurationMigration(storage: storage, preferences: preferences, immutableRoots: []) - let plan = try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) - #expect(plan.writes.count == 2) - let original = try fixture.bytes() - let external = Data(#"{"version":2,"configurations":[],"external":"preserve"}"#.utf8) - if mode == "before" { lease.invalidate() } - if mode == "changed-source" { try external.write(to: fixture.local) } - storage.beforeReplace = { index in - if index == 2 && mode == "second-file-conflict" { try external.write(to: fixture.local) } - if index == 2 && mode == "changed-first-during-rollback" { - try external.write(to: fixture.team); try external.write(to: fixture.local) - } - } - storage.afterReplace = { index in - if (index == 1 && mode == "after-first-write") || (index == 2 && mode == "after-second-write") { lease.invalidate() } - if index == 2 && mode == "changed-local-after-write" { try external.write(to: fixture.local) } - let projectKey = fixture.root.path.replacingOccurrences(of: "/", with: "_") - if index == 1 && mode == "preferences-created-during-write" { - preferences.set(Data("new legacy choices".utf8), forKey: "lithe.java-run-options.\(projectKey).\(fixture.id)") - } - if index == 1 && mode == "marker-changed-during-write" { - preferences.set(true, forKey: "lithe.run-configuration-migrated.\(projectKey)") - } - } - #expect(throws: (any Error).self) { try migration.apply(plan, workspace: fixture.root, lease: lease) } - if mode == "changed-first-during-rollback" { - #expect(try Data(contentsOf: fixture.team) == external) - } else { #expect(try Data(contentsOf: fixture.team) == original[0]) } - let expectedLocal = ["second-file-conflict", "changed-source", "changed-first-during-rollback", "changed-local-after-write"].contains(mode) ? external : original[1] - #expect(try Data(contentsOf: fixture.local) == expectedLocal) - } - - @Test - func changingAnUnwrittenSourceRollsBackOnlyOurDestination() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let originalTeam = try fixture.read(fixture.team) - try fixture.write(originalTeam, to: fixture.local) - try fixture.write(["version": 2, "configurations": []], to: fixture.team) - let beforeLocal = try Data(contentsOf: fixture.local) - let storage = MigrationFaultStorage(), lease = RunConfigurationGenerationLease() - let migration = MacLegacyMavenRunConfigurationMigration(storage: storage, preferences: MigrationPreferences(), immutableRoots: []) - let plan = try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) - #expect(plan.writes.count == 1) - let external = Data(#"{"version":2,"configurations":[],"external":"preserve"}"#.utf8) - storage.afterReplace = { index in if index == 1 { try external.write(to: fixture.team) } } - #expect(throws: (any Error).self) { try migration.apply(plan, workspace: fixture.root, lease: lease) } - #expect(try Data(contentsOf: fixture.team) == external) - #expect(try Data(contentsOf: fixture.local) == beforeLocal) - } - - @Test - func aReadOnlyWorkspaceWithoutLegacyEntriesRemainsReadable() throws { - let fixture = try Fixture() - defer { fixture.remove() } - try fixture.write(["version": 2, "configurations": []], to: fixture.team) - try fixture.write(["version": 2, "configurations": []], to: fixture.local) - let before = try fixture.bytes() - let migration = MacLegacyMavenRunConfigurationMigration(storage: MacFileStorage(), preferences: MigrationPreferences(), immutableRoots: [fixture.root]) - let plan = try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: RunConfigurationGenerationLease()) - #expect(plan.writes.isEmpty) - #expect(try fixture.bytes() == before) - } - - @Test - func immutablePackagesAndEscapingSymlinksRejectBeforePublication() throws { - let fixture = try Fixture(), outside = try Fixture() - defer { fixture.remove(); outside.remove() } - let lease = RunConfigurationGenerationLease() - let migration = MacLegacyMavenRunConfigurationMigration(storage: MacFileStorage(), preferences: MigrationPreferences(), immutableRoots: [fixture.root]) - let before = try fixture.bytes() - #expect(throws: (any Error).self) { try migration.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) } - #expect(try fixture.bytes() == before) - try FileManager.default.removeItem(at: fixture.root.appendingPathComponent(".lithe/run")) - try FileManager.default.createSymbolicLink(at: fixture.root.appendingPathComponent(".lithe/run"), withDestinationURL: outside.root.appendingPathComponent(".lithe/run")) - let external = try outside.bytes() - let linked = MacLegacyMavenRunConfigurationMigration(storage: MacFileStorage(), preferences: MigrationPreferences(), immutableRoots: []) - #expect(throws: (any Error).self) { try linked.prepare(workspace: fixture.root, projects: fixture.projects, runs: fixture.runs, models: fixture.models, lease: lease) } - #expect(try outside.bytes() == external) - } - - private struct Fixture { - let root = FileManager.default.temporaryDirectory.appendingPathComponent("legacy-maven-run-\(UUID().uuidString)") - let id = "quarkus.maven:nested/app" - var team: URL { root.appendingPathComponent(".lithe/run/configurations.json") } - var local: URL { root.appendingPathComponent(".lithe/run/local.json") } - let projects = [RunProjectOwnership(path: "nested/app", build: .init(pluginID: "io.github.lithe-idea.maven-build", buildSystemID: "maven", root: "nested", projectID: "p"), contentRoots: [], name: "app")] - var runs: [RunProviderConfiguration] { - [.init(projectPath: "nested/app", name: "Current service", reference: .init(pluginID: "io.github.lithe-idea.maven-build", - buildSystemID: "maven", root: "nested", run: "framework", projectID: "p", targetID: "opaque/service", execution: .service))] - } - var models: [BuildModel] { - get throws { - [try JSONDecoder().decode(BuildModel.self, from: Data(#"{"projects":[{"id":"p","path":"nested/app","name":"app"}],"targets":[{"id":"opaque/service","projectID":"p","name":"quarkus.maven","path":"nested/app","tags":["maven-service"]}]}"#.utf8))] - } - } - init() throws { - do { - try FileManager.default.createDirectory(at: root.appendingPathComponent("nested/app/work"), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: team.deletingLastPathComponent(), withIntermediateDirectories: true) - try write(["version": 2, "annotation": "keep document metadata", "configurations": [["id": id, "name": "User service", "provider": "quarkus.maven", "execution": "service", "cwd": "nested", "toolchains": ["java": "project-jdk", "maven": "project-maven"], "debug": ["adapter": "jdwp"], "extensions": ["maven": ["module": "app", "jvmArguments": ["--runtime=one two", "", "雪"], "programArguments": ["--team=space value"], "mainClass": "opaque/entry:1", "profiles": ["team"], "skipTests": true], "annotations": ["keep": true]]]]], to: team) - try write(["version": 2, "annotation": "keep local metadata", "configurations": [["id": id, "cwd": "nested/app/work", "env": ["EXAMPLE": "local"], "extensions": ["maven": ["programArguments": ["--local=雪"], "profiles": [], "skipTests": false]]]]], to: local) - try write(["version": 1, "defaultRunConfiguration": id], to: root.appendingPathComponent(".lithe/project.json")) - } catch { remove(); throw error } - } - func read(_ url: URL) throws -> [String: Any] { try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) } - func write(_ document: [String: Any], to url: URL) throws { try JSONSerialization.data(withJSONObject: document, options: [.sortedKeys]).write(to: url) } - func bytes() throws -> [Data] { try [Data(contentsOf: team), Data(contentsOf: local)] } - func remove() { try? FileManager.default.removeItem(at: root) } - } -} - -/// Faults occur at explicit synchronous publication boundaries, without timing or background tasks. -private final class MigrationFaultStorage: FileStorage, @unchecked Sendable { - private let base = MacFileStorage() - private var replacements = 0 - var beforeReplace: (Int) throws -> Void = { _ in } - var afterReplace: (Int) throws -> Void = { _ in } - func replaceDataPreservingMetadata(_ data: Data, at url: URL, expecting expected: Data?) throws -> Bool { - replacements += 1; let index = replacements - try beforeReplace(index) - let result = try base.replaceDataPreservingMetadata(data, at: url, expecting: expected) - try afterReplace(index) - return result - } - func homeDirectory() -> URL { base.homeDirectory() } - func cacheDirectory() -> URL { base.cacheDirectory() } - func applicationSupportDirectory() -> URL { base.applicationSupportDirectory() } - func temporaryDirectory() -> URL { base.temporaryDirectory() } - func metadata(for url: URL) -> FileMetadata? { base.metadata(for: url) } - func fileExists(at url: URL) -> Bool { base.fileExists(at: url) } - func isExecutable(at url: URL) -> Bool { base.isExecutable(at: url) } - func listDirectory(at url: URL) -> [URL] { base.listDirectory(at: url) } - func readPrefix(from url: URL, byteCount: Int) throws -> Data { try base.readPrefix(from: url, byteCount: byteCount) } - func readData(from url: URL, options: Data.ReadingOptions) throws -> Data { try base.readData(from: url, options: options) } - func writeData(_ data: Data, to url: URL, options: Data.WritingOptions) throws { try base.writeData(data, to: url, options: options) } - func replaceData(_ data: Data, at url: URL, expecting expected: Data?) throws -> Bool { try base.replaceData(data, at: url, expecting: expected) } - func removeData(at url: URL, expecting expected: Data) throws -> Bool { try base.removeData(at: url, expecting: expected) } - func createDirectory(at url: URL, withIntermediateDirectories: Bool) throws { try base.createDirectory(at: url, withIntermediateDirectories: withIntermediateDirectories) } - func removeItem(at url: URL) throws { try base.removeItem(at: url) } - func moveItem(at sourceURL: URL, to destinationURL: URL) throws { try base.moveItem(at: sourceURL, to: destinationURL) } - func copyItem(at sourceURL: URL, to destinationURL: URL) throws { try base.copyItem(at: sourceURL, to: destinationURL) } -} - -private final class MigrationPreferences: KeyValueStore, @unchecked Sendable { - private var values: [String: Any] = [:] - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } - func keys(withPrefix prefix: String) -> [String]? { values.keys.filter { $0.hasPrefix(prefix) }.sorted() } -} diff --git a/macos/Tests/LitheTests/MacLoginShellEnvironmentTests.swift b/macos/Tests/LitheTests/MacLoginShellEnvironmentTests.swift index 661ac90545..12b2522dbd 100644 --- a/macos/Tests/LitheTests/MacLoginShellEnvironmentTests.swift +++ b/macos/Tests/LitheTests/MacLoginShellEnvironmentTests.swift @@ -62,10 +62,10 @@ struct MacLoginShellEnvironmentTests { @Test func theProcessEnvironmentWinsOverTheLoginShell() { - let shell = MacLoginShellEnvironment(overlay: ["JAVA_HOME": "/login/jdk", "MAVEN_HOME": "/login/maven"]) - let merged = shell.merged(["JAVA_HOME": "/explicit/jdk"]) - #expect(merged["JAVA_HOME"] == "/explicit/jdk") - #expect(merged["MAVEN_HOME"] == "/login/maven") + let shell = MacLoginShellEnvironment(overlay: ["TOOL_A_HOME": "/login/tool-a", "TOOL_B_HOME": "/login/tool-b"]) + let merged = shell.merged(["TOOL_A_HOME": "/explicit/tool-a"]) + #expect(merged["TOOL_A_HOME"] == "/explicit/tool-a") + #expect(merged["TOOL_B_HOME"] == "/login/tool-b") } @Test @@ -74,7 +74,7 @@ struct MacLoginShellEnvironmentTests { defer { fixture.remove() } try fixture.writeRC(""" export PATH=/fixture/first:$PATH - export JAVA_HOME=/fixture/jdk + export TOOL_A_HOME=/fixture/tool-a """) let cache = fixture.root.appendingPathComponent("cache/login-path") let shared = MacLoginShellEnvironment() @@ -88,7 +88,7 @@ struct MacLoginShellEnvironmentTests { #expect(coldRefresh == nil) #expect(applied.last?.hasPrefix("/fixture/first:") == true) #expect(try String(contentsOf: cache, encoding: .utf8).hasPrefix("/fixture/first:")) - #expect(shared.merged([:])["JAVA_HOME"] == "/fixture/jdk") + #expect(shared.merged([:])["TOOL_A_HOME"] == "/fixture/tool-a") try fixture.writeRC("export PATH=/fixture/second:$PATH") let warmShared = MacLoginShellEnvironment() @@ -101,7 +101,7 @@ struct MacLoginShellEnvironmentTests { warmRefresh() #expect(try String(contentsOf: cache, encoding: .utf8).hasPrefix("/fixture/second:")) // The refreshed overlay reflects the edited rc file, not the earlier read. - #expect(warmShared.merged([:])["JAVA_HOME"] != "/fixture/jdk") + #expect(warmShared.merged([:])["TOOL_A_HOME"] != "/fixture/tool-a") } @Test diff --git a/macos/Tests/LitheTests/MacNativeBuildProviderIntegrationTests.swift b/macos/Tests/LitheTests/MacNativeBuildProviderIntegrationTests.swift deleted file mode 100644 index 4a2745a52a..0000000000 --- a/macos/Tests/LitheTests/MacNativeBuildProviderIntegrationTests.swift +++ /dev/null @@ -1,709 +0,0 @@ -import CryptoKit -import Foundation -import LitheCoreContracts -import LitheExecutionModule -import LitheLanguageIntelligenceModule -import Testing -@testable import Lithe - -/// Explicit tool integration: the production macOS session table, linked Core, -/// real Java SDK backend and Maven reactor. No page or scripted runtime Core. -@Suite("Native macOS build Provider integration", .serialized) -@MainActor -struct MacNativeBuildProviderIntegrationTests { - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D Maven package and selected Java/Maven"), arguments: [false, true], [false, true]) - func installedDefinitionsResolveTheRealBuildAndRuntimeThroughSavedChoices(projectWrapper: Bool, consumerDefaults: Bool) async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_D_MAVEN_PACKAGE"])) - let javaPath = try #require(environment["LITHE_STAGE_C_JAVA"]) - let mavenPath = try #require(environment["LITHE_STAGE_C_MAVEN"]) - let java = try #require(MacToolchainDiscovery.realpath(javaPath)) - let maven = try #require(MacToolchainDiscovery.realpath(mavenPath)) - let javaHome = URL(fileURLWithPath: java).deletingLastPathComponent().deletingLastPathComponent().path - let mavenHome = URL(fileURLWithPath: maven).deletingLastPathComponent().deletingLastPathComponent().path - let files = FileManager.default - let workspace = files.temporaryDirectory.appendingPathComponent("lithe-native-defined-tools-\(UUID().uuidString)") - try files.createDirectory(at: workspace, withIntermediateDirectories: true) - defer { try? files.removeItem(at: workspace) } - let manifest = try Data(contentsOf: package.appendingPathComponent("plugin.json")) - let javaPackage = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("Plugins/mac/Official/JavaSupport") - let sources: [ToolchainSettingsPluginSource] = [ - .init(pluginID: "io.github.lithe-idea.maven-build", name: "Maven", manifest: manifest, isEnabled: true), - .init(pluginID: "dev.lithe.plugin.java-support", name: "Java", manifest: try Data(contentsOf: javaPackage.appendingPathComponent("plugin.json")), - isEnabled: true) - ] - let before = try Self.inventory(package), javaBefore = try Self.inventory(javaPackage) - var pins = ["java": ["home": javaHome, "version": "selected", "provider": "host:manual"]] - if projectWrapper { - // A fixture launcher delegates to the explicit real Maven without a - // download. Opening the workspace cannot execute this project code. - let wrapper = workspace.appendingPathComponent("mvnw") - let escapedMaven = maven.replacingOccurrences(of: "'", with: "'\"'\"'") - try Data("#!/bin/sh\nexec '\(escapedMaven)' \"$@\"\n".utf8).write(to: wrapper) - try files.setAttributes([.posixPermissions: 0o755], ofItemAtPath: wrapper.path) - try files.createDirectory(at: workspace.appendingPathComponent(".mvn/wrapper"), withIntermediateDirectories: true) - try Data("# fixture launcher needs no distribution\n".utf8) - .write(to: workspace.appendingPathComponent(".mvn/wrapper/maven-wrapper.properties")) - } else { - pins["io.github.lithe-idea.maven-build:maven"] = ["home": mavenHome, "version": "selected", "provider": "host:manual"] - } - if consumerDefaults { - let store = MacToolchainPreferencesStore(core: RustCoreBridge(), storage: MacFileStorage(), immutableRoots: { [package, javaPackage] }) - var baseline = try await store.load(workspace: workspace) - baseline = try await store.save(.object(["home": .string(javaHome)]), - at: .init(directory: ".", consumer: nil, tool: "java"), expecting: baseline) - baseline = try await store.save(.object(["inherit": .string("tool")]), - at: .init(directory: ".", consumer: "io.github.lithe-idea.maven-build/maven", tool: "java"), expecting: baseline) - if !projectWrapper { - _ = try await store.save(.object(["home": .string(mavenHome)]), - at: .init(directory: ".", consumer: "io.github.lithe-idea.maven-build/maven", tool: "io.github.lithe-idea.maven-build:maven"), expecting: baseline) - } - #expect(!files.fileExists(atPath: workspace.appendingPathComponent(".lithe/toolchains/local.json").path)) - } else { - try files.createDirectory(at: workspace.appendingPathComponent(".lithe/toolchains"), withIntermediateDirectories: true) - try JSONSerialization.data(withJSONObject: ["version": 1, "toolchains": [:], "pins": [".": pins]]) - .write(to: workspace.appendingPathComponent(".lithe/toolchains/local.json")) - } - let defined = MacDefinedToolchainResolver() - defined.sources = { sources } - let runtime = ProjectRuntimeService(runtimeLocator: MacRuntimeLocator(), store: NativeDefinedToolPreferences()) - runtime.openProject(at: workspace) - defer { runtime.closeProject() } - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage(), definedTools: defined) - let core = RustBuildSystemOperations(core: RustCoreBridge()) - let target = BuildSystemTarget(manifest: manifest, buildSystemID: "maven") - let invocation = try core.invocationPlan(target, root: ".", settings: [:]) - #expect(resolver.languageImportExecutable(invocation, workspaceURL: workspace) == nil) - let selected = try await resolver.resolve(invocation, displayName: "Maven", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - let expected = projectWrapper ? try #require(MacToolchainDiscovery.realpath(workspace.appendingPathComponent("mvnw").path)) : maven - #expect(selected.executableURL.path == expected) - #expect(selected.environment["JAVA_HOME"] == javaHome) - #expect(selected.executesProjectCode == projectWrapper) - if !projectWrapper { #expect(selected.version != nil) } - #expect(selected.providerEnvironment["JAVA_HOME"] == javaHome) - #expect(try Self.inventory(package) == before) - #expect(try Self.inventory(javaPackage) == javaBefore) - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D Maven package and selected Java/Maven"), - .enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_ALTERNATE_JAVA"] != nil, - "Requires an explicitly selected second compatible JDK")) - func consumerDefaultChangesReachTheRealMavenProcessWhileExplicitRunsStayFixed() async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_D_MAVEN_PACKAGE"])) - let primaryPath = try #require(environment["LITHE_STAGE_C_JAVA"]) - let alternatePath = try #require(environment["LITHE_STAGE_D_ALTERNATE_JAVA"]) - let mavenPath = try #require(environment["LITHE_STAGE_C_MAVEN"]) - let primary = try #require(MacToolchainDiscovery.realpath(primaryPath)) - let alternate = try #require(MacToolchainDiscovery.realpath(alternatePath)) - let maven = try #require(MacToolchainDiscovery.realpath(mavenPath)) - let homes = [primary, alternate].map { URL(fileURLWithPath: $0).deletingLastPathComponent().deletingLastPathComponent().path } - try #require(homes[0] != homes[1]) - let mavenHome = URL(fileURLWithPath: maven).deletingLastPathComponent().deletingLastPathComponent().path - let javaPackage = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("Plugins/mac/Official/JavaSupport") - let manifest = try Data(contentsOf: package.appendingPathComponent("plugin.json")) - let sources: [ToolchainSettingsPluginSource] = [ - .init(pluginID: "io.github.lithe-idea.maven-build", name: "Maven", manifest: manifest, isEnabled: true), - .init(pluginID: "dev.lithe.plugin.java-support", name: "Java", manifest: try Data(contentsOf: javaPackage.appendingPathComponent("plugin.json")), - isEnabled: true) - ] - let workspace = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-real-default-change-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: workspace) } - let before = try Self.inventory(package), javaBefore = try Self.inventory(javaPackage) - let store = MacToolchainPreferencesStore(core: RustCoreBridge(), storage: MacFileStorage(), immutableRoots: { [package, javaPackage] }) - var baseline = try await store.load(workspace: workspace) - baseline = try await store.save(.object(["home": .string(mavenHome)]), - at: .init(directory: ".", consumer: "io.github.lithe-idea.maven-build/maven", tool: "io.github.lithe-idea.maven-build:maven"), expecting: baseline) - _ = try await store.save(.object(["inherit": .string("tool")]), - at: .init(directory: ".", consumer: "io.github.lithe-idea.maven-build/maven", tool: "java"), expecting: baseline) - let defined = MacDefinedToolchainResolver(); defined.sources = { sources } - let runtime = ProjectRuntimeService(runtimeLocator: MacRuntimeLocator(), store: NativeDefinedToolPreferences()) - runtime.openProject(at: workspace) - defer { runtime.closeProject() } - let resolver = MacBuildToolResolver(runtime: runtime, processRunner: MacProcessRunner(), fileStorage: MacFileStorage(), definedTools: defined) - let core = RustBuildSystemOperations(core: RustCoreBridge()) - let target = BuildSystemTarget(manifest: manifest, buildSystemID: "maven") - let invocation = try core.invocationPlan(target, root: ".", settings: [:]) - for (index, home) in homes.enumerated() { - baseline = try await store.load(workspace: workspace) - _ = try await store.save(.object(["home": .string(home)]), at: .init(directory: ".", consumer: nil, tool: "java"), expecting: baseline) - let selected = try await resolver.resolve(invocation, displayName: "Maven", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - #expect(selected.environment["JAVA_HOME"] == home) - let result = try await MacBuildCommandRunner().run(.init(executableURL: selected.executableURL, arguments: ["--version"], - workingDirectory: workspace, environment: selected.environment, capturesStandardOutput: true, timeout: .seconds(5))) { _ in } - #expect(result.termination == .exited(0)) - #expect(result.standardOutput?.contains(home) == true) - if index == homes.count - 1 { - var explicit = invocation; explicit.toolSelections["java"] = .installation(home: homes[0]) - let fixed = try await resolver.resolve(explicit, displayName: "Maven", workspaceURL: workspace) { runtime, output in - try core.checkToolVersion(target, runtime: runtime, output: output) - } - #expect(fixed.environment["JAVA_HOME"] == homes[0]) - } - } - #expect(try Self.inventory(package) == before) - #expect(try Self.inventory(javaPackage) == javaBefore) - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D Maven package and selected Java/Maven")) - func runProfileUsesOneMavenModelAndSavedGenerationTracksDefaultProfileChanges() async throws { - try await verifyRunConfigurationPreparation(savedTaskOnly: false) - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D Maven package and selected Java/Maven")) - func savedProviderTaskUsesCurrentTypedInputsWithoutChangingBuildDefaults() async throws { - try await verifyRunConfigurationPreparation(savedTaskOnly: true) - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D Maven package and selected Java/Maven")) - func legacyRunTaskMigratesToTheCurrentMavenTargetWithoutLosingItsStableID() async throws { - try await verifyRunConfigurationPreparation(savedTaskOnly: true, migrateLegacy: true) - } - - private func verifyRunConfigurationPreparation(savedTaskOnly: Bool, migrateLegacy: Bool = false) async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_D_MAVEN_PACKAGE"])) - let java = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_JAVA"])) - let maven = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN"])) - let files = FileManager.default - let scratch = files.temporaryDirectory.appendingPathComponent("lithe-native-run-profile-\(UUID().uuidString)") - try files.createDirectory(at: scratch, withIntermediateDirectories: true) - defer { try? files.removeItem(at: scratch) } - let workspace = scratch.appendingPathComponent("workspace") - for path in ["nested/checks", "nested/test inputs"] { - try files.createDirectory(at: workspace.appendingPathComponent(path), withIntermediateDirectories: true) - } - try Data("class Main { public static void main(String[] args) {} }".utf8).write(to: workspace.appendingPathComponent("nested/checks/Main.java")) - try Data("selected=${selected.value}".utf8).write(to: workspace.appendingPathComponent("nested/test inputs/runtime.properties")) - try Data(""" - 4.0.0smokeapp1 - checksinactive-checks - ${selected.sources}${selected.checks}test inputs - true - run-onlycurrent-profile - inactive-sourceschecks - additional - """.utf8).write(to: workspace.appendingPathComponent("nested/pom.xml")) - let before = try Self.inventory(package) - let core = RustCoreBridge(), storage = MacFileStorage() - let planner = RustBuildSystemOperations(core: core), declarations = RustDeclarativePluginOperations(core: core) - let descriptor = try declarations.validate(manifest: Data(contentsOf: package.appendingPathComponent("plugin.json"))) - let source = BuildSystemPluginSource(pluginID: descriptor.id.rawValue, manifest: descriptor.normalizedManifest, - packageURL: package, buildSystems: descriptor.buildSystems) - let runtime = ExplicitProviderRuntime(java: java, environment: environment), released = TestGate() - let directories = MacPluginStateDirectories(rootURL: scratch.appendingPathComponent("state")) - let sessions = MacBuildProviderSessions(launchResolver: MacPluginLanguageServerLaunchResolver(planner: declarations, - directories: directories, settings: InMemoryPluginSettings()), tools: runtime, versionChecker: declarations, - runtime: runtime, core: core, processRegistry: nil, endBackendProcesses: { token, _ in - MacPluginBackendProcesses.end(token: token, gracePeriod: 0); released.open() - }) - let domain = "lithe.native-run-profile.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: domain)) - defer { defaults.removePersistentDomain(forName: domain) } - let options = MacBuildOptionsStore(store: MacUserDefaultsStore(defaults: defaults)) - let build = BuildSystemService(planner: planner, tools: ExplicitNativeConfigurationTool(maven: maven), optionsStore: options, - stateLocator: MacBuildSystemStateLocator(directories: directories, fileStorage: storage), - runner: MacBuildCommandRunner(), providers: sessions, sources: { [source] }) - let outcome: Result - do { - build.reset(workspaceURL: workspace) - let baseline = try await build.prepareLanguageImport(workspaceURL: workspace) - if migrateLegacy { - try await build.prepareLanguageTestModels(allModels: true, workspace: workspace) - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - let store = MacRunConfigurationStore(core: core, storage: storage, preferences: MacUserDefaultsStore(defaults: defaults)) - let legacyID = "user:legacy-validate" - let url = workspace.appendingPathComponent(".lithe/run/local.json") - try files.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try JSONSerialization.data(withJSONObject: ["version": 2, "configurations": [["id": legacyID, "name": "Saved validate", - "provider": "maven.module", "execution": "task", "cwd": "nested", "args": ["validate"], - "env": ["LITHE_RUN_VALUE": "雪"], "extensions": ["maven": ["module": ".", "profiles": ["run-only"]]]]]], options: [.sortedKeys]).write(to: url) - _ = try store.generate(at: workspace, files: [], modulePaths: [], javaEntrypoints: nil, - projectOwnership: build.runProjectOwnership(), providerRuns: build.providerRunConfigurations(), - models: build.entries.compactMap(\.model), lease: RunConfigurationGenerationLease()) - let resolution = try store.resolve(at: workspace, toolchainCandidates: []) - #expect(resolution.configurations.count == 1) - #expect(resolution.configurations.first?.configuration.id == legacyID) - let inputs = try store.providerLaunchInputs(at: workspace, configurationID: legacyID, providerRoot: "nested") - #expect(inputs.reference?.run == "module") - #expect(inputs.launchOptions.arguments == ["validate"]) - #expect(inputs.optionOverrides["profiles"] == .array([.string("run-only")])) - let prepared = try await build.prepareConfigurationRun(inputs: inputs, instanceRoot: "nested", workspace: workspace, - tool: BuildProviderHints(), isCurrent: { true }, progress: { _ in }) - #expect(prepared.arguments.last == "validate") - #expect(prepared.arguments.contains("-Prun-only")) - #expect(prepared.environment["LITHE_RUN_VALUE"] == "雪") - #expect(try build.languageImport(workspaceURL: workspace, root: nil) == baseline) - #expect(try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven")["nested"]?["profiles"] == nil) - } else if savedTaskOnly { - try await build.prepareLanguageTestModels(allModels: true, workspace: workspace) - let taskPreparation = try await build.prepareConfigurationRun(inputs: ProviderLaunchInputs( - buildSystemID: "maven", provider: "maven.module", projectPath: "nested", - launchOptions: BuildLaunchOptions(execution: .task, arguments: ["validate"], environment: ["LITHE_RUN_VALUE": "雪"], workingDirectory: "."), - optionOverrides: ["profiles": .array([.string("run-only")])]), instanceRoot: "nested", workspace: workspace, - tool: BuildProviderHints(toolExecutable: maven, toolEnvironment: ["JAVA_HOME": java.deletingLastPathComponent().deletingLastPathComponent().path]), - isCurrent: { true }, progress: { _ in }) - #expect(taskPreparation.executable.value == "io.github.lithe-idea.maven-build:maven") - #expect(taskPreparation.arguments.contains("validate")) - #expect(taskPreparation.arguments.contains("-Prun-only")) - #expect(taskPreparation.workingDirectory == ".") - #expect(taskPreparation.environment["LITHE_RUN_VALUE"] == "雪") - #expect(try build.languageImport(workspaceURL: workspace, root: nil) == baseline) - let store = MacRunConfigurationStore(core: core, storage: storage, preferences: MacUserDefaultsStore(defaults: defaults)) - let moduleTarget = try #require(build.entries.first?.model?.targets.first { $0.name == "maven.module" }) - let reference = BuildProviderRunReference(pluginID: source.pluginID, buildSystemID: "maven", root: "nested", - run: "module", projectID: moduleTarget.projectID, targetID: moduleTarget.id, userArguments: ["validate"], execution: .task) - let savedID = try store.saveBuildProviderConfiguration(reference, name: "Validate module", at: workspace) - try store.saveOptions(RunOptions(programArguments: "validate", providerRunOptions: BuildProviderRunOptions( - options: ["profiles": .array([.string("run-only"), .string("additional")])])), configurationID: savedID, scope: .local, at: workspace) - let savedInputs = try store.providerLaunchInputs(at: workspace, configurationID: savedID, providerRoot: "nested") - let savedPreparation = try await build.prepareConfigurationRun(inputs: savedInputs, instanceRoot: "nested", workspace: workspace, - tool: BuildProviderHints(), isCurrent: { true }, progress: { _ in }) - #expect(savedPreparation.arguments.last == "validate") - #expect(savedPreparation.arguments.contains("-Padditional,run-only")) - #expect(savedInputs.optionOverrides["profiles"] == .array([.string("run-only"), .string("additional")])) - #expect(try build.languageImport(workspaceURL: workspace, root: nil) == baseline) - #expect(try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven")["nested"]?["profiles"] == nil) - #expect(try store.resolve(at: workspace, toolchainCandidates: []).configurations.first?.configuration.execution == .task) - #expect(build.configurationRunSource(inputs: savedInputs, instanceRoot: "nested") == source) - } else { - let prepared = try await build.prepareLanguageRun(fileURL: workspace.appendingPathComponent("nested/checks/Main.java"), - workspace: workspace, purpose: "run", - optionOverrides: ["profiles": .array([.string("run-only")])], - tool: { _ in BuildProviderHints(toolExecutable: maven, - toolEnvironment: runtime.environment.filter { $0.key == "JAVA_HOME" || $0.key == "PATH" }) }, isCurrent: { true }) - guard case .maven(let context)? = prepared else { throw NativeProviderIntegrationError.unexpectedCommand } - #expect(context.profiles == ["run-only"]) - #expect(context.mavenExecutablePath == maven.path) - #expect(context.reactorPath == "nested") - #expect(try String(contentsOf: workspace.appendingPathComponent("nested/target/test-classes/runtime.properties"), encoding: .utf8) == "selected=current-profile") - #expect(build.entries.first?.model?.contentRoots.contains { $0.path == "nested/checks" && $0.kind == "source" } == true) - #expect(try build.languageImport(workspaceURL: workspace, root: nil) == baseline) - #expect(try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven")["nested"]?["profiles"] == nil) - let ownership = try build.runProjectOwnership() - #expect(ownership.first?.build?.root == "nested") - #expect(ownership.first?.contentRoots.contains { $0.path == "nested/checks" && $0.kind == "source" } == true) - let store = MacRunConfigurationStore(core: core, storage: storage, preferences: MacUserDefaultsStore(defaults: defaults)) - let runs = try build.providerRunConfigurations() - #expect(runs.contains { $0.reference.run == "module" && $0.reference.execution == .task }) - _ = try store.generate(at: workspace, files: [workspace.appendingPathComponent("nested/checks/Main.java")], modulePaths: [], - javaEntrypoints: JavaEntrypoints(entries: [JavaEntrypoint(sourcePath: "nested/checks/Main.java", mainClass: "Main")]), - projectOwnership: ownership, providerRuns: runs) - let resolvedRuns = try store.resolve(at: workspace, toolchainCandidates: []).configurations.compactMap { $0.configuration.buildProvider } - #expect(Set(resolvedRuns.map(\.targetID)) == Set(runs.map { $0.reference.targetID })) - #expect(!store.inspectProviderGeneration(at: workspace, projectOwnership: ownership, providerRuns: runs).diagnostics.contains { $0.code == "staleProviderModel" }) - let entryID = try #require(build.entries.first?.id) - func currentOwnership() async throws -> [LitheCoreContracts.RunProjectOwnership] { - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - try await build.prepareLanguageTestModels(allModels: true, workspace: workspace) - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - return try build.runProjectOwnership() - } - // These are explicit edits of Build defaults after the temporary Run - // has completed. POM bytes stay unchanged throughout A → B → A. - build.setOption(entryID, optionID: "profiles", value: .array([.string("run-only")])) - let changed = try await currentOwnership() - #expect(changed.first?.contentRoots.contains { $0.path == "nested/checks" && $0.kind == "testSource" } == true) - #expect(store.inspectProviderGeneration(at: workspace, projectOwnership: changed, providerRuns: try build.providerRunConfigurations()).diagnostics.contains { $0.code == "staleProviderModel" }) - build.setOption(entryID, optionID: "profiles", value: .array([])) - let restored = try await currentOwnership() - #expect(restored == ownership) - #expect(!store.inspectProviderGeneration(at: workspace, projectOwnership: restored, providerRuns: try build.providerRunConfigurations()).diagnostics.contains { $0.code == "staleProviderModel" }) - } - outcome = .success(()) - } catch { outcome = .failure(error) } - build.stop(); sessions.retainProviders { _ in false } - #expect(await released.waitUntilOpen(timeout: .seconds(5))) - #expect(try Self.inventory(package) == before) - try outcome.get() - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D native-configuration development package")) - func savingNativeSettingsKeepsTheOtherReactorIndependent() async throws { - try await nativeSettingsStayIndependentAcrossReactorRoots(replaceSource: false) - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D native-configuration development package")) - func replacingNativeSettingsSourceKeepsTheOtherReactorIndependent() async throws { - try await nativeSettingsStayIndependentAcrossReactorRoots(replaceSource: true) - } - - private func nativeSettingsStayIndependentAcrossReactorRoots(replaceSource: Bool) async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_D_MAVEN_PACKAGE"])) - let java = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_JAVA"])) - let maven = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN"])) - let files = FileManager.default - let scratch = files.temporaryDirectory.appendingPathComponent("lithe-native-reactor-settings-\(UUID().uuidString)") - try files.createDirectory(at: scratch, withIntermediateDirectories: true) - defer { try? files.removeItem(at: scratch) } - let workspace = scratch.appendingPathComponent("workspace") - for root in ["a", "b"] { - let directory = workspace.appendingPathComponent(root) - try files.createDirectory(at: directory, withIntermediateDirectories: true) - try Data("".utf8).write(to: directory.appendingPathComponent("pom.xml")) - } - let a = scratch.appendingPathComponent("a settings.xml") - let b = scratch.appendingPathComponent("b settings.xml") - let replacement = scratch.appendingPathComponent("replacement.xml") - for (url, name) in [(a, "a"), (b, "b"), (replacement, "replacement")] { - try Data("\(scratch.appendingPathComponent(name + "-repository").path)".utf8).write(to: url) - } - // Each reactor has an independent pin. Maven receives its canonical - // selection as environment rather than inferring the backend's java.home. - let javaHome = java.resolvingSymlinksInPath().deletingLastPathComponent().deletingLastPathComponent() - var pins: [String: [String: [String: String]]] = [:] - let mavenPath = try #require(MacToolchainDiscovery.realpath(maven.path)) - let mavenHome = URL(fileURLWithPath: mavenPath).deletingLastPathComponent().deletingLastPathComponent().path - for root in ["a", "b"] { - let alias = scratch.appendingPathComponent("runtime-\(root)") - try files.createSymbolicLink(at: alias, withDestinationURL: javaHome) - pins[root] = ["java": ["home": alias.path, "version": "selected", "provider": "host:manual"], - "io.github.lithe-idea.maven-build:maven": ["home": mavenHome, "version": "selected", "provider": "host:manual"]] - } - try files.createDirectory(at: workspace.appendingPathComponent(".lithe/toolchains"), withIntermediateDirectories: true) - try JSONSerialization.data(withJSONObject: ["version": 1, "toolchains": [:], "pins": pins]) - .write(to: workspace.appendingPathComponent(".lithe/toolchains/local.json")) - let bSettings = "\(scratch.appendingPathComponent("b-repository").path)${env.JAVA_HOME}" - try Data(bSettings.utf8).write(to: b) - let before = try Self.inventory(package) - let core = RustCoreBridge() - let planner = RustBuildSystemOperations(core: core) - let declarations = RustDeclarativePluginOperations(core: core) - let descriptor = try declarations.validate(manifest: Data(contentsOf: package.appendingPathComponent("plugin.json"))) - let source = BuildSystemPluginSource(pluginID: descriptor.id.rawValue, manifest: descriptor.normalizedManifest, - packageURL: package, buildSystems: descriptor.buildSystems) - let runtime = ExplicitProviderRuntime(java: java, environment: environment) - let released = TestGate() - let directories = MacPluginStateDirectories(rootURL: scratch.appendingPathComponent("state")) - let sessions = MacBuildProviderSessions( - launchResolver: MacPluginLanguageServerLaunchResolver(planner: declarations, directories: directories, - settings: InMemoryPluginSettings()), tools: runtime, versionChecker: declarations, - runtime: runtime, core: core, processRegistry: nil, endBackendProcesses: { token, _ in - MacPluginBackendProcesses.end(token: token, gracePeriod: 0); released.open() - }) - let domain = "lithe.native-reactor-settings.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: domain)) - defer { defaults.removePersistentDomain(forName: domain) } - let options = MacBuildOptionsStore(store: MacUserDefaultsStore(defaults: defaults)) - try options.setInstanceOptions(["a": ["settingsFile": .string(a.path)], "b": ["settingsFile": .string(b.path)]], - workspaceURL: workspace, buildSystemID: "maven") - let storage = MacFileStorage() - let defined = MacDefinedToolchainResolver() - let javaManifest = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("Plugins/mac/Official/JavaSupport/plugin.json")) - let toolSources: [ToolchainSettingsPluginSource] = [ - .init(pluginID: descriptor.id.rawValue, name: "Maven", manifest: descriptor.normalizedManifest, isEnabled: true), - .init(pluginID: "dev.lithe.plugin.java-support", name: "Java", manifest: javaManifest, isEnabled: true) - ] - defined.sources = { toolSources } - let projectRuntime = ProjectRuntimeService(runtimeLocator: CanonicalToolchainRuntimeLocator(), store: NativeDefinedToolPreferences()) - projectRuntime.openProject(at: workspace) - defer { projectRuntime.closeProject() } - let build = BuildSystemService(planner: planner, - tools: MacBuildToolResolver(runtime: projectRuntime, processRunner: MacProcessRunner(), fileStorage: storage, definedTools: defined), optionsStore: options, - stateLocator: MacBuildSystemStateLocator(directories: directories, fileStorage: storage), - runner: MacBuildCommandRunner(), providers: sessions, - nativeConfigurationFiles: MacBuildNativeConfigurationStore(storage: storage, planner: planner, - immutableRoots: [package, Bundle.main.bundleURL]), sources: { [source] }) - let outcome: Result - do { - build.reset(workspaceURL: workspace) - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - #expect(build.entries.map(\.id) == ["maven:a", "maven:b"]) - // Saving a source and selecting another source are independent - // workflows. Each keeps both reactors live but owns one mutation, - // without reading an unchanged fixture through Maven twice. - if replaceSource { - let originalA = try Data(contentsOf: a) - _ = try build.configureOption("maven:a", optionID: "settingsFile", value: .string(replacement.path)) - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - let changedA = try await build.readNativeConfiguration("maven:a") - #expect(changedA.sources.first { $0.id == "user" }?.uri == replacement.absoluteString) - #expect(try Data(contentsOf: a) == originalA) - } else { - let firstA = try await build.readNativeConfiguration("maven:a") - let userA = try #require(firstA.sources.first { $0.id == "user" }) - #expect(userA.uri == a.absoluteString) - let savedPath = scratch.appendingPathComponent("saved-a-repository").path - // The production save already reads back from the provider. - let changedA = try await build.saveNativeConfiguration("maven:a", snapshot: firstA, - edits: BuildNativeConfigurationEdits(sourceID: userA.id, revision: userA.revision, - values: ["localRepository": .string(savedPath)])) - #expect(changedA.sources.first { $0.id == "user" }?.fields.first { $0.id == "localRepository" }?.effectiveValue == .string(savedPath)) - } - let unchangedB = try await build.readNativeConfiguration("maven:b") - let userB = try #require(unchangedB.sources.first { $0.id == "user" }) - #expect(userB.uri == b.absoluteString) - #expect(userB.fields.first { $0.id == "localRepository" }?.effectiveValue - == .string(scratch.appendingPathComponent("b-repository").path)) - #expect(userB.fields.first { $0.id == "activeProfiles" }?.effectiveValue - == .array([.string(try #require(MacToolchainDiscovery.realpath(javaHome.path)))])) - #expect(try String(contentsOf: b, encoding: .utf8) == bSettings) - #expect(try options.instanceOptions(workspaceURL: workspace, buildSystemID: "maven")["b"]?["settingsFile"] == .string(b.path)) - #expect(!files.fileExists(atPath: workspace.appendingPathComponent("a/target").path)) - #expect(!files.fileExists(atPath: workspace.appendingPathComponent("b/target").path)) - for path in ["a-repository", "b-repository", "saved-a-repository", "replacement-repository"] { - #expect(!files.fileExists(atPath: scratch.appendingPathComponent(path).path)) - } - outcome = .success(()) - } catch { outcome = .failure(error) } - build.stop(); sessions.retainProviders { _ in false } - #expect(await released.waitUntilOpen(timeout: .seconds(5))) - #expect(try Self.inventory(package) == before) - try outcome.get() - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_D_MAVEN_PACKAGE"] != nil, - "Requires the stage D native-configuration development package")) - func nativeSettingsUseProductionStorageReadBackAndRejectExternalChanges() async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_D_MAVEN_PACKAGE"])) - let java = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_JAVA"])) - let maven = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN"])) - let files = FileManager.default - let scratch = files.temporaryDirectory.appendingPathComponent("lithe-native-settings-workflow-\(UUID().uuidString)") - try files.createDirectory(at: scratch, withIntermediateDirectories: true) - defer { try? files.removeItem(at: scratch) } - let workspace = scratch.appendingPathComponent("workspace") - try files.createDirectory(at: workspace.appendingPathComponent(".mvn"), withIntermediateDirectories: true) - try Data("".utf8).write(to: workspace.appendingPathComponent("pom.xml")) - let user = scratch.appendingPathComponent("user settings.xml") - let global = scratch.appendingPathComponent("global.xml") - let inheritedRepository = scratch.appendingPathComponent("inherited-repository").path - let selectedRepository = scratch.appendingPathComponent("saved-repository").path - let original = "test-secret-preservedci" - try Data(original.utf8).write(to: user) - try Data("\(inheritedRepository)".utf8).write(to: global) - try Data("--global-settings=\(global.path)\n".utf8).write(to: workspace.appendingPathComponent(".mvn/maven.config")) - let before = try Self.inventory(package) - let core = RustCoreBridge() - let planner = RustBuildSystemOperations(core: core) - let declarations = RustDeclarativePluginOperations(core: core) - let descriptor = try declarations.validate(manifest: Data(contentsOf: package.appendingPathComponent("plugin.json"))) - let source = BuildSystemPluginSource(pluginID: descriptor.id.rawValue, manifest: descriptor.normalizedManifest, - packageURL: package, buildSystems: descriptor.buildSystems) - let selectedRuntime = ExplicitProviderRuntime(java: java, environment: environment) - let released = TestGate() - let directories = MacPluginStateDirectories(rootURL: scratch.appendingPathComponent("state")) - let sessions = MacBuildProviderSessions( - launchResolver: MacPluginLanguageServerLaunchResolver(planner: declarations, directories: directories, - settings: InMemoryPluginSettings()), tools: selectedRuntime, versionChecker: declarations, - runtime: selectedRuntime, core: core, processRegistry: nil, endBackendProcesses: { token, _ in - MacPluginBackendProcesses.end(token: token, gracePeriod: 0); released.open() - }) - let preferenceDomain = "lithe.native-settings.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: preferenceDomain)) - defer { defaults.removePersistentDomain(forName: preferenceDomain) } - let options = MacBuildOptionsStore(store: MacUserDefaultsStore(defaults: defaults)) - try options.setOptions(["settingsFile": .string(user.path)], workspaceURL: workspace, buildSystemID: "maven") - let storage = MacFileStorage() - func service() -> BuildSystemService { - BuildSystemService(planner: planner, tools: ExplicitNativeConfigurationTool(maven: maven), optionsStore: options, - stateLocator: MacBuildSystemStateLocator(directories: directories, fileStorage: storage), - runner: MacBuildCommandRunner(), providers: sessions, - nativeConfigurationFiles: MacBuildNativeConfigurationStore(storage: storage, planner: planner, - immutableRoots: [package, Bundle.main.bundleURL]), sources: { [source] }) - } - let build = service() - var reopened: BuildSystemService? - let outcome: Result - do { - build.reset(workspaceURL: workspace) - _ = try await build.prepareLanguageImport(workspaceURL: workspace) - let entry = try #require(build.entries.first) - let first = try await build.readNativeConfiguration(entry.id) - let userSource = try #require(first.sources.first { $0.id == "user" }) - let repository = try #require(userSource.fields.first { $0.id == "localRepository" }) - #expect(repository.value == .null) - #expect(repository.effectiveValue == .string(inheritedRepository)) - #expect(try String(contentsOf: user, encoding: .utf8) == original) - var draft = BuildNativeConfigurationDraft(source: userSource) - #expect(!draft.isDirty) - draft.setOverride(true, fieldID: repository.id) - draft.setValue(.string(selectedRepository), fieldID: repository.id) - let saved = try await build.saveNativeConfiguration(entry.id, snapshot: first, edits: draft.edits) - #expect(saved.sources.first { $0.id == "user" }?.fields.first { $0.id == "localRepository" }?.effectiveValue == .string(selectedRepository)) - let savedText = try String(contentsOf: user, encoding: .utf8) - #expect(savedText.contains("")) - #expect(savedText.contains("test-secret-preserved")) - #expect(!String(decoding: try JSONEncoder().encode(saved), as: UTF8.self).contains("test-secret-preserved")) - let current = try #require(saved.sources.first { $0.id == "user" }) - let external = savedText + "\n" - try Data(external.utf8).write(to: user) - await #expect(throws: (any Error).self) { - try await build.saveNativeConfiguration(entry.id, snapshot: saved, edits: BuildNativeConfigurationEdits( - sourceID: current.id, revision: current.revision, values: ["localRepository": .string("/obsolete")])) - } - #expect(try String(contentsOf: user, encoding: .utf8) == external) - build.stop() - let next = service(); reopened = next - next.reset(workspaceURL: workspace) - _ = try await next.prepareLanguageImport(workspaceURL: workspace) - let nextEntry = try #require(next.entries.first) - let fresh = try await next.readNativeConfiguration(nextEntry.id) - #expect(fresh.sources.first { $0.id == "user" }?.fields.first { $0.id == "localRepository" }?.value == .string(selectedRepository)) - #expect(!files.fileExists(atPath: workspace.appendingPathComponent("target").path)) - #expect(!files.fileExists(atPath: inheritedRepository)) - #expect(!files.fileExists(atPath: selectedRepository)) - outcome = .success(()) - } catch { outcome = .failure(error) } - build.stop(); reopened?.stop(); sessions.retainProviders { _ in false } - #expect(await released.waitUntilOpen(timeout: .seconds(5))) - #expect(try Self.inventory(package) == before) - try outcome.get() - } - - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_STAGE_C_MAVEN_PACKAGE"] != nil, - "Requires an explicit development Maven package and tool paths")) - func realMavenProviderBuildsAndTestsWithoutAPluginPage() async throws { - let environment = ProcessInfo.processInfo.environment - let package = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN_PACKAGE"])) - let fixture = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN_FIXTURE"])) - let java = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_JAVA"])) - let maven = URL(fileURLWithPath: try #require(environment["LITHE_STAGE_C_MAVEN"])) - try #require(RustCoreBridge().isAvailable) - let files = FileManager.default - let scratch = files.temporaryDirectory.appendingPathComponent("lithe-native-provider-\(UUID().uuidString)") - try files.createDirectory(at: scratch, withIntermediateDirectories: true) - defer { try? files.removeItem(at: scratch) } - let workspace = scratch.appendingPathComponent("workspace") - try files.createDirectory(at: workspace, withIntermediateDirectories: true) - try files.copyItem(at: fixture, to: workspace.appendingPathComponent("nested")) - let before = try Self.inventory(package) - let core = RustCoreBridge() - let operations = RustBuildSystemOperations(core: core) - let declarations = RustDeclarativePluginOperations(core: core) - let descriptor = try declarations.validate(manifest: Data(contentsOf: package.appendingPathComponent("plugin.json"))) - let target = BuildSystemTarget(manifest: descriptor.normalizedManifest, buildSystemID: "maven") - let provider = BuildProviderTarget(pluginID: descriptor.id.rawValue, manifest: descriptor.normalizedManifest, - packageURL: package, buildSystemID: "maven", workspaceURL: workspace) - let released = TestGate() - let selectedTools = ExplicitProviderRuntime(java: java, environment: environment) - let sessions = MacBuildProviderSessions( - launchResolver: MacPluginLanguageServerLaunchResolver(planner: declarations, - directories: MacPluginStateDirectories(rootURL: scratch.appendingPathComponent("state")), settings: InMemoryPluginSettings()), - tools: selectedTools, versionChecker: declarations, runtime: selectedTools, core: core, processRegistry: nil, - endBackendProcesses: { token, _ in - MacPluginBackendProcesses.end(token: token, gracePeriod: 0) - released.open() - }) - let context = BuildPlanContext(root: "nested", options: ["profiles": .array([.string("ci")])], - pluginDirectory: package, workspaceStateDirectory: scratch.appendingPathComponent("workspace-state")) - let outcome: Result - do { - let plan = try operations.modelPlan(target, context: context, outputFile: nil, - providerHints: BuildProviderHints(toolExecutable: maven)) - guard case .provider(let request) = plan else { throw NativeProviderIntegrationError.unexpectedCommand } - let raw = try await sessions.send(request, to: provider, timeout: .seconds(20)) - let model = try operations.decodeModel(target, workspaceURL: workspace, root: context.root, - output: .providerResult(raw), options: context.options) - #expect(Set(model.projects.map(\.name)) == ["reactor", "core", "app"]) - #expect(try #require(sessions.processID(for: provider)) > 0) - let project = try #require(model.projects.first { $0.name == "core" }) - let taskPlan = try operations.taskPlan(target, context: context, - request: BuildTaskRequest(task: "compile", project: BuildSelection(project: project))) - guard case .provider(let build) = taskPlan else { throw NativeProviderIntegrationError.unexpectedCommand } - let progress = NativeProviderProgress() - let built = try await sessions.execute(Self.withTool(build, maven: maven), on: provider, timeout: .seconds(20)) { - progress.output += $0.output ?? "" - } - #expect(built.exitCode == 0) - #expect(built.output == progress.output) - #expect(files.fileExists(atPath: workspace.appendingPathComponent("nested/core/target/classes/demo/core/Greeter.class").path)) - let testPlan = try operations.testPlan(target, context: context, - request: BuildTestRequest(project: BuildSelection(project: project), selectorKind: "java.test.fullName", selectors: ["demo.core.GreeterTest#greetsByName()"])) - guard case .provider(let test) = testPlan.execution else { throw NativeProviderIntegrationError.unexpectedCommand } - let tested = try await sessions.execute(Self.withTool(test, maven: maven), on: provider, timeout: .seconds(20)) { _ in } - #expect(tested.exitCode == 0) - let results = try operations.decodeTestResults(target, request: BuildTestResultsRequest(workspaceURL: workspace, - root: context.root, project: project.path, projects: model.projects.map(\.path), output: tested.output, - notBefore: nil, suite: "demo.core.GreeterTest", result: tested.testResults)) - #expect(results.summary.total == 1) - #expect(results.summary.failed == 0) - #expect(results.tests.first?.name == "greetsByName") - #expect(try await sessions.pluginFunctions(of: provider).isEmpty) - outcome = .success(()) - } catch { outcome = .failure(error) } - // Shutdown is observed through the production session's release callback, - // including after failed assertions/requests; the scratch workspace outlives it. - sessions.retainProviders { _ in false } - #expect(await released.waitUntilOpen(timeout: .seconds(5))) - #expect(try Self.inventory(package) == before) - try outcome.get() - } - - private static func withTool(_ request: BuildProviderRequest, maven: URL) -> BuildProviderRequest { - guard case .object(var params) = request.params else { return request } - params["tool"] = .object(["executable": .string(maven.path)]) - return BuildProviderRequest(method: request.method, params: .object(params), optionFingerprint: request.optionFingerprint, - executesProjectCode: request.executesProjectCode, mayUseNetwork: request.mayUseNetwork) - } - - static func inventory(_ root: URL) throws -> [String: String] { - let files = FileManager.default - let paths = try files.subpathsOfDirectory(atPath: root.path).sorted() - return try Dictionary(uniqueKeysWithValues: paths.map { relative in - let path = root.appendingPathComponent(relative) - let attributes = try files.attributesOfItem(atPath: path.path) - let type = attributes[.type] as? FileAttributeType - let digest = type == .typeRegular ? SHA256.hash(data: try Data(contentsOf: path)).map { String(format: "%02x", $0) }.joined() : "directory" - return (relative, "\(attributes[.posixPermissions] ?? ""):\(digest)") - }) - } -} - -private enum NativeProviderIntegrationError: Error { case unexpectedCommand } -@MainActor -private final class ExplicitNativeConfigurationTool: BuildToolResolving { - let maven: URL - init(maven: URL) { self.maven = maven } - func resolve(_ invocation: BuildInvocation, displayName: String, workspaceURL: URL, - checkVersion: @escaping @Sendable (String?, String) throws -> BuildVersionCheck) async throws -> ResolvedBuildTool { - ResolvedBuildTool(executableURL: maven, environment: [:], executesProjectCode: false, version: nil) - } -} -@MainActor private final class NativeProviderProgress { var output = "" } - -/// Explicit test-selected executable paths. All process/RPC execution is real; -/// this port avoids reading or modifying the user's runtime preferences. -@MainActor -final class ExplicitProviderRuntime: BuildToolResolving, LanguageToolRuntimePort { - let java: URL - let environment: [String: String] - init(java: URL, environment: [String: String]) { - self.java = java - var values = environment - values["JAVA_HOME"] = java.deletingLastPathComponent().deletingLastPathComponent().path - self.environment = values - } - func resolve(_ invocation: BuildInvocation, displayName: String, workspaceURL: URL, - checkVersion: @escaping @Sendable (String?, String) throws -> BuildVersionCheck) async throws -> ResolvedBuildTool { - ResolvedBuildTool(executableURL: java, environment: environment, executesProjectCode: false, version: nil) - } - func executableOnPath(_ name: String) -> URL? { name == "java" ? java : nil } - func executableURL(at path: String) -> URL? { path == java.path ? java : nil } - func executableCandidates(_ command: String) -> [RuntimeToolCandidate] { [] } - func languageToolProcessEnvironment(runtimeTools: [String]) -> [String: String] { environment } - func missingLanguageToolMessage(_ name: String) -> String { name } -} - -/// This integration never reads or writes the user's saved runtime preferences. -private struct NativeDefinedToolPreferences: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} -} diff --git a/macos/Tests/LitheTests/MacNativeProviderDebugIntegrationTests.swift b/macos/Tests/LitheTests/MacNativeProviderDebugIntegrationTests.swift index 5032bd3615..6b15c9ba97 100644 --- a/macos/Tests/LitheTests/MacNativeProviderDebugIntegrationTests.swift +++ b/macos/Tests/LitheTests/MacNativeProviderDebugIntegrationTests.swift @@ -1,3 +1,4 @@ +import CryptoKit import Foundation import LitheCoreContracts import LitheDebugModule @@ -42,7 +43,7 @@ struct MacNativeProviderDebugIntegrationTests { "targetBindings": ["program": "target.path", "cwd": "target.workingDirectory", "args": "target.arguments", "env": "target.environment"]]] manifest["debugAdapters"] = adapters try JSONSerialization.data(withJSONObject: manifest, options: [.sortedKeys]).write(to: manifestFile) - let before = try MacNativeBuildProviderIntegrationTests.inventory(copiedSDK) + let before = try NativeDebugInventory.inventory(copiedSDK) let workspace = scratch.appendingPathComponent("workspace") let app = workspace.appendingPathComponent("nested/app") try files.createDirectory(at: app, withIntermediateDirectories: true) @@ -158,13 +159,29 @@ struct MacNativeProviderDebugIntegrationTests { sessions.retainProviders { _ in false } #expect(await released.waitUntilOpen(timeout: .seconds(5))) #expect(manager.activeSessionIDs.isEmpty) - #expect(try MacNativeBuildProviderIntegrationTests.inventory(copiedSDK) == before) + #expect(try NativeDebugInventory.inventory(copiedSDK) == before) try outcome.get() } } private enum NativeDebugIntegrationError: Error { case unexpectedPlan } +private enum NativeDebugInventory { + /// Permission and content digest of every file under `root`, so the test + /// can prove the SDK copy is byte-identical after the build/debug cycle. + static func inventory(_ root: URL) throws -> [String: String] { + let files = FileManager.default + let paths = try files.subpathsOfDirectory(atPath: root.path).sorted() + return try Dictionary(uniqueKeysWithValues: paths.map { relative in + let path = root.appendingPathComponent(relative) + let attributes = try files.attributesOfItem(atPath: path.path) + let type = attributes[.type] as? FileAttributeType + let digest = type == .typeRegular ? SHA256.hash(data: try Data(contentsOf: path)).map { String(format: "%02x", $0) }.joined() : "directory" + return (relative, "\(attributes[.posixPermissions] ?? ""):\(digest)") + }) + } +} + @MainActor private final class NativeDebugTrace { let ready = TestGate(), stopped = TestGate(), terminated = TestGate() diff --git a/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift b/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift index 2956bd245a..65f626c5a7 100644 --- a/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift +++ b/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift @@ -711,8 +711,7 @@ private final class ScriptedBackendCore: LanguageServerRuntimeCore, @unchecked S func startLanguageServer( providerID _: String, executableURL _: URL, arguments _: [String], environment _: [String: String], rootURL _: URL, workingDirectoryURL _: URL, initializationOptions _: ToolingJSONValue?, - runtimeExecutableURL _: URL?, jdtlsLaunchResources _: JDTLSLaunchResources?, cacheDirectoryURL _: URL?, - workspaceFingerprint _: String?, initializeTimeout _: TimeInterval, requestTimeout _: TimeInterval, + initializeTimeout _: TimeInterval, requestTimeout _: TimeInterval, shutdownTimeout _: TimeInterval ) -> Result { .failure(LanguageServerRuntimeFailure(code: "unexpected", message: "A backend is plugin-owned.")) diff --git a/macos/Tests/LitheTests/MacRuntimeDiscoveryTests.swift b/macos/Tests/LitheTests/MacRuntimeDiscoveryTests.swift deleted file mode 100644 index a5086666c4..0000000000 --- a/macos/Tests/LitheTests/MacRuntimeDiscoveryTests.swift +++ /dev/null @@ -1,191 +0,0 @@ -import Foundation -import Testing -@testable import Lithe - -@Suite("macOS runtime discovery") -struct MacRuntimeDiscoveryTests { - @Test - func resolvesJavaHomeFromPathSymlinkWithoutLaunchingIt() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let home = root.appendingPathComponent("custom-jdk", isDirectory: true) - try createExecutableJava(at: home) - let bin = root.appendingPathComponent("path-bin", isDirectory: true) - try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: bin.appendingPathComponent("java"), withDestinationURL: home.appendingPathComponent("bin/java")) - let environment = ["PATH": bin.path] - #expect(MacRuntimeDiscovery.javaHomeOnPath(environment: environment)?.resolvingSymlinksInPath().path == home.resolvingSymlinksInPath().path) - } - - @Test - func discoversSDKMANJavaCandidatesFromDefaultDirectory() throws { - let testRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-sdkman-runtime-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: testRoot) } - let javaRoot = testRoot.appendingPathComponent(".sdkman/candidates/java", isDirectory: true) - let javaHome = javaRoot.appendingPathComponent("25.0.1-zulu", isDirectory: true) - try createExecutableJava(at: javaHome) - try FileManager.default.createSymbolicLink( - at: javaRoot.appendingPathComponent("current"), - withDestinationURL: javaHome - ) - - let homes = MacRuntimeDiscovery.discoverJavaHomes( - environment: [:], - homeDirectory: testRoot.path, - javaHomePaths: [], - directoryEntries: try directoryEntries(in: javaRoot) - ) - - #expect(homes.count == 1) - #expect(homes.first?.resolvingSymlinksInPath() == javaHome.resolvingSymlinksInPath()) - } - - @Test - func honorsCustomSDKMANDirectoryAndIgnoresInvalidCandidates() throws { - let testRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-sdkman-custom-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: testRoot) } - let sdkmanRoot = testRoot.appendingPathComponent("sdkman", isDirectory: true) - let javaRoot = sdkmanRoot.appendingPathComponent("candidates/java", isDirectory: true) - let javaHome = javaRoot.appendingPathComponent("21.0.8-tem", isDirectory: true) - try createExecutableJava(at: javaHome) - try FileManager.default.createDirectory( - at: javaRoot.appendingPathComponent("incomplete"), - withIntermediateDirectories: true - ) - - let homes = MacRuntimeDiscovery.discoverJavaHomes( - environment: ["SDKMAN_DIR": sdkmanRoot.path], - homeDirectory: testRoot.appendingPathComponent("home").path, - javaHomePaths: [], - directoryEntries: try directoryEntries(in: javaRoot) - ) - - #expect(homes == [javaHome.standardizedFileURL]) - } - - @Test - func discoversMvndWithoutProbingAndPreservesMavenPriority() { - func discover(_ environment: [String: String], files: Set) -> [String] { - MacRuntimeDiscovery.discoverMavenExecutables( - environment: environment, isExecutable: { files.contains($0.path) } - ).map(\.path) - } - let daemon = "/fixture/daemon/bin/mvnd" - let pathDaemon = "/fixture/path/mvnd" - let maven = "/fixture/maven/bin/mvn" - #expect(discover(["MVND_HOME": "/fixture/daemon"], files: [daemon]) == [daemon]) - #expect(discover(["PATH": "/fixture/path"], files: [pathDaemon]) == [pathDaemon]) - #expect(discover(["MVND_HOME": "/missing", "PATH": "/fixture/path"], files: [pathDaemon]) == [pathDaemon]) - #expect(discover( - ["MAVEN_HOME": "/fixture/maven", "MVND_HOME": "/fixture/daemon", "PATH": "/fixture/path"], - files: [daemon, pathDaemon, maven] - ) == [maven, daemon, pathDaemon]) - #expect(discover( - ["PATH": "/fixture/path:/fixture/maven/bin:/fixture/path"], files: [pathDaemon, maven] - ) == [maven, pathDaemon]) - #expect(discover(["M2_HOME": "/fixture/maven"], files: [maven]) == [maven]) - #expect(discover(["MVND_HOME": "/missing"], files: []) == []) - #expect(discover([:], files: ["/opt/homebrew/bin/mvnd"]) == ["/opt/homebrew/bin/mvnd"]) - #expect(discover([:], files: ["/usr/local/bin/mvn", "/opt/homebrew/bin/mvnd"]) - == ["/usr/local/bin/mvn", "/opt/homebrew/bin/mvnd"]) - } - - @Test - func explicitDaemonHomeNeverFallsBackToEmbeddedMaven() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let embedded = root.appendingPathComponent("mvn/bin/mvn") - try FileManager.default.createDirectory(at: embedded.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data().write(to: embedded) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: embedded.path) - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: root.path) == nil) - let bin = root.appendingPathComponent("bin") - try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) - // Traversable directories named like launchers are not executable files. - try FileManager.default.createDirectory(at: bin.appendingPathComponent("mvnd"), withIntermediateDirectories: true) - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: root.path) == nil) - } - - @Test - func mavenVersionsMatchSharedContract() throws { - struct Fixture: Decodable { - struct Case: Decodable { let output: String; let version: String? } - let cases: [Case] - } - let root = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() - let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: - root.appendingPathComponent("shared/fixtures/execution/maven-runtime-versions.json"))) - for example in fixture.cases { - #expect(MacRuntimeDiscovery.mavenVersion(in: example.output) == example.version) - } - } - - @Test - func discoversVersionManagerAndIDEAJavaInstalls() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-version-managers-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - let home = root.appendingPathComponent("home", isDirectory: true) - // mise keeps a macOS JDK as its bundle; asdf and IDEA flatten it. - let mise = home.appendingPathComponent(".local/share/mise/installs/java/21.0.2/Contents/Home") - let asdf = root.appendingPathComponent("asdf/installs/java/temurin-17.0.10+7") - let idea = home.appendingPathComponent(".jdks/corretto-1.8.0_402") - for javaHome in [mise, asdf, idea] { try createExecutableJava(at: javaHome) } - - let homes = MacRuntimeDiscovery.discoverJavaHomes( - environment: ["ASDF_DATA_DIR": root.appendingPathComponent("asdf").path], - homeDirectory: home.path, - javaHomePaths: [], - directoryEntries: { (try? FileManager.default.contentsOfDirectory(atPath: $0)) ?? [] } - ).map { $0.resolvingSymlinksInPath().path } - - for javaHome in [mise, asdf, idea] { - #expect(homes.contains(javaHome.resolvingSymlinksInPath().path)) - } - } - - @Test - func discoversVersionManagerMavenAndSkipsShims() { - let home = "/fixture/home" - let mise = "\(home)/.local/share/mise/installs/maven/3.9.6/bin/mvn" - let sdkman = "\(home)/.sdkman/candidates/maven/3.8.8/bin/mvn" - let shim = "\(home)/.local/share/mise/shims/mvn" - let entries: [String: [String]] = [ - "\(home)/.local/share/mise/installs/maven": ["3.9.6"], - "\(home)/.sdkman/candidates/maven": ["3.8.8"] - ] - let found = MacRuntimeDiscovery.discoverMavenExecutables( - environment: ["PATH": "\(home)/.local/share/mise/shims"], - homeDirectory: home, - directoryEntries: { entries[$0] ?? [] }, - isExecutable: { [mise, sdkman, shim].contains($0.path) } - ).map(\.path) - - #expect(found == [sdkman, mise]) - } - - private func createExecutableJava(at home: URL) throws { - let executable = home.appendingPathComponent("bin/java") - try FileManager.default.createDirectory( - at: executable.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - #expect(FileManager.default.createFile(atPath: executable.path, contents: Data())) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: executable.path - ) - } - - private func directoryEntries(in fixtureRoot: URL) throws -> (String) -> [String] { - let fixturePath = fixtureRoot.standardizedFileURL.path - let entries = try FileManager.default.contentsOfDirectory(atPath: fixturePath) - // Discovery also asks for system and Homebrew directories. Only expose - // this fixture so installed JDKs cannot affect either test's assertions. - return { path in path == fixturePath ? entries : [] } - } -} diff --git a/macos/Tests/LitheTests/MacRuntimeProbeCacheTests.swift b/macos/Tests/LitheTests/MacRuntimeProbeCacheTests.swift index e6b530de93..f1c118929b 100644 --- a/macos/Tests/LitheTests/MacRuntimeProbeCacheTests.swift +++ b/macos/Tests/LitheTests/MacRuntimeProbeCacheTests.swift @@ -8,7 +8,7 @@ struct MacRuntimeProbeCacheTests { func reusesSuccessfulResultsAndRetriesFailures() async { await onWorker { let cache = MacRuntimeProbeCache() - let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/java", identity: "one") + let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/tool-a", identity: "one") var calls = 0 let failed = cache.value(for: key) { calls += 1; return nil } let success = cache.value(for: key) { calls += 1; return "21" } @@ -23,7 +23,7 @@ struct MacRuntimeProbeCacheTests { func invalidationDiscardsCompletedAndInFlightResults() async { await onWorker { let cache = MacRuntimeProbeCache() - let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/java", identity: "one") + let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/tool-a", identity: "one") var calls = 0 #expect(cache.value(for: key) { calls += 1 @@ -37,83 +37,10 @@ struct MacRuntimeProbeCacheTests { } } - @Test - func canonicalAliasesReuseProbeAndUpdatedReleaseReprobes() async throws { - try await onThrowingWorker { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let home = root.appendingPathComponent("jdk") - let java = home.appendingPathComponent("bin/java") - let log = home.appendingPathComponent("probes") - let release = home.appendingPathComponent("release") - try FileManager.default.createDirectory(at: java.deletingLastPathComponent(), withIntermediateDirectories: true) - // All paths belong to the disposable fixture. The script records real - // process invocations without relying on an installed developer tool. - try Data("#!/bin/sh\necho probe >> \"$(dirname \"$0\")/../probes\"\necho 'openjdk version \"21.0.1\"' >&2\n".utf8).write(to: java) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: java.path) - try Data("first".utf8).write(to: release) - let alias = root.appendingPathComponent("alias") - try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: home) - #expect(MacRuntimeDiscovery.probeJavaHome(home)?.version == "21.0.1") - #expect(MacRuntimeDiscovery.probeJavaHome(alias)?.homePath == alias.path) - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 1) - try Data("updated release identity".utf8).write(to: release) - #expect(MacRuntimeDiscovery.probeJavaHome(home)?.version == "21.0.1") - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 2) - } - } - - @Test - func mvndProbeUsesEmbeddedMavenAndInvalidatesItsLibraries() async throws { - try await onThrowingWorker { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let home = root.appendingPathComponent("daemon") - let executable = home.appendingPathComponent("bin/mvnd") - let library = home.appendingPathComponent("mvn/lib/maven-core-fixture.jar") - let log = home.appendingPathComponent("probes") - try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: library.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data("first".utf8).write(to: library) - try Data("#!/bin/sh\necho probe >> \"$(dirname \"$0\")/../probes\"\necho 'Apache Maven Daemon (mvnd) 1.0.6'\necho 'Apache Maven 3.9.11 (fixture)'\n".utf8).write(to: executable) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - #expect(MacRuntimeDiscovery.probeMaven(executable)?.version == "3.9.11") - #expect(MacRuntimeDiscovery.probeMaven(executable)?.version == "3.9.11") - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 1) - try Data("changed Maven library".utf8).write(to: library) - #expect(MacRuntimeDiscovery.probeMaven(executable)?.version == "3.9.11") - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 2) - } - } - - @Test - func mavenWrapperReusesVersionUntilDistributionChanges() async throws { - try await onThrowingWorker { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: root) } - let executable = root.appendingPathComponent("mvnw") - let properties = root.appendingPathComponent(".mvn/wrapper/maven-wrapper.properties") - let log = root.appendingPathComponent("probes") - try FileManager.default.createDirectory(at: properties.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data("#!/bin/sh\necho probe >> \"$(dirname \"$0\")/probes\"\necho 'Apache Maven 3.9.9'\n".utf8).write(to: executable) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - try Data("distributionUrl=fixture-one".utf8).write(to: properties) - let alias = root.appendingPathComponent("alias/mvnw") - try FileManager.default.createDirectory(at: alias.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: executable) - #expect(MacRuntimeDiscovery.probeMaven(executable)?.version == "3.9.9") - #expect(MacRuntimeDiscovery.probeMaven(alias)?.executablePath == alias.path) - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 1) - try Data("distributionUrl=fixture-updated".utf8).write(to: properties) - #expect(MacRuntimeDiscovery.probeMaven(executable)?.version == "3.9.9") - #expect(try String(contentsOf: log, encoding: .utf8).split(separator: "\n").count == 2) - } - } - @Test func simultaneousRequestsShareOneProbe() async throws { let cache = MacRuntimeProbeCache() - let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/java", identity: "one") + let key = MacRuntimeProbeCache.Key(executablePath: "/fixture/tool-a", identity: "one") let gate = ProbeGate() let (started, start) = AsyncStream.makeStream() defer { gate.release(); start.finish() } @@ -164,17 +91,6 @@ struct MacRuntimeProbeCacheTests { } } } - - private func onThrowingWorker(_ work: @escaping @Sendable () throws -> Value) async throws -> Value { - // A native synchronous probe must run on a dispatch worker, never on the - // cooperative executor used by Swift Testing. - let result: Result = await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: Result { try work() }) - } - } - return try result.get() - } } private final class ProbeGate: @unchecked Sendable { diff --git a/macos/Tests/LitheTests/MacToolchainDiscoveryTests.swift b/macos/Tests/LitheTests/MacToolchainDiscoveryTests.swift index 2a2984bc3e..0736fbf1ea 100644 --- a/macos/Tests/LitheTests/MacToolchainDiscoveryTests.swift +++ b/macos/Tests/LitheTests/MacToolchainDiscoveryTests.swift @@ -592,7 +592,7 @@ struct MacToolchainDiscoveryTests { let plan = MacToolchainDiscovery.callCore("toolchains.discoveryPlan", ["registry": ["plugins": plugins], "platform": "macos"])?["plan"] let tools = try #require((plan as? [String: Any])?["tools"] as? [[String: Any]]) - #expect(tools.compactMap { $0["tool"] as? String }.sorted() == ["java", "maven", "node", "python"]) + #expect(tools.compactMap { $0["tool"] as? String }.sorted() == ["node", "python", "tool-a", "tool-b"]) #expect(tools.allSatisfy { !($0["scans"] as? [Any] ?? []).isEmpty }) } #endif diff --git a/macos/Tests/LitheTests/MavenRuntimeTests.swift b/macos/Tests/LitheTests/MavenRuntimeTests.swift deleted file mode 100644 index f23836f142..0000000000 --- a/macos/Tests/LitheTests/MavenRuntimeTests.swift +++ /dev/null @@ -1,536 +0,0 @@ -import Foundation -import LitheCoreContracts -import Testing -@testable import Lithe - -@Suite("Maven and runtime integration") -struct MavenRuntimeTests { - @Test - @MainActor - func automaticJavaUsesProjectMinimumAndPreservesExplicitSelections() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } - // Before the Run list is identified, Core reads the minimum from the project's declaration. - let pom = root.appendingPathComponent("pom.xml") - let old = JavaRuntimeCandidate(homePath: "/jdk/env", version: "1.8.0_402", vendor: "fixture") - let current = JavaRuntimeCandidate(homePath: "/jdk/current", version: "21.0.4", vendor: "fixture") - let locator = ChoiceRuntimeLocator(environmentValues: ["JAVA_HOME": old.homePath], validJavaHomes: [old.homePath, current.homePath], runtimeCandidates: [old, current]) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - service.openProject(at: root) - func require(_ version: String) throws { - try Data("\(version)".utf8).write(to: pom) - } - try require("17") - let choice = service.chooseJavaHome(overridePath: nil) { [old, current] } - #expect(choice?.url?.path == current.homePath) - #expect(service.javaHomeURL()?.path == current.homePath) - #expect(service.mavenJavaHomeURL()?.path == current.homePath) - #expect(locator.discoverCalls == 1) - #expect(service.chooseMavenJavaHome(overridePath: nil) { [old, current] }?.url == choice?.url) - #expect(service.chooseJavaHome(overridePath: old.homePath) { [old, current] }?.url?.path == old.homePath) - #expect(service.chooseJavaHome(overridePath: "/missing") { [old, current] } == .invalid("/missing")) - try require("25") - if case .warning(let url, _, let message)? = service.chooseJavaHome(overridePath: nil, detected: { [old, current] }) { - #expect(url.path == old.homePath) - #expect(message.contains("25")) - } else { Issue.record("Expected an actionable fallback warning") } - try FileManager.default.removeItem(at: pom) - #expect(service.chooseJavaHome(overridePath: nil) { [current, old] }?.url?.path == old.homePath) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe").path)) - // Project switching cannot retain the previous workspace's requirement. - service.closeProject() - #expect(service.chooseJavaHome(overridePath: nil) { [current, old] }?.url?.path == old.homePath) - #expect(locator.discoverCalls == 1) - } - - @Test - func mavenLifecyclePhasesMatchTheSharedPlatformContract() throws { - let fixture = try Self.platformContractFixture() - #expect(MavenLifecyclePhase.allCases.map(\.rawValue) == fixture.lifecyclePhases) - } - - @Test - func macMavenStorageIdentityMatchesTheSharedPlatformContract() throws { - let fixture = try Self.platformContractFixture() - let macCases = fixture.storageIdentityCases.filter { $0.platform == "macos" } - #expect(macCases.count == 1) - for item in macCases { - #expect(MacLegacyMavenConfigurationMigration.storageIdentity( - workspacePath: item.workspacePath, - reactorPath: item.reactorPath - ) == item.expectedIdentity) - } - } - - @Test - @MainActor - func projectRelativeJavaOverridesResolveAgainstProjectRoot() { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-project-relative-runtime", isDirectory: true) - .standardizedFileURL - let javaHome = root.appendingPathComponent("toolchains/jdk", isDirectory: true).standardizedFileURL - let mavenJavaHome = root.appendingPathComponent("toolchains/maven-jdk", isDirectory: true).standardizedFileURL - let service = ProjectRuntimeService( - runtimeLocator: ProjectRelativeRuntimeLocator(validJavaHomes: [javaHome.path, mavenJavaHome.path]), - store: EmptyKeyValueStore() - ) - service.openProject(at: root) - - #expect(service.javaHomeURL(overridePath: "toolchains/jdk") == javaHome) - #expect(service.mavenJavaHomeURL(overridePath: "toolchains/maven-jdk") == mavenJavaHome) - } - - @Test - @MainActor - func javaChoiceNamesTheLaunchedJDKAndItsSource() { - // Settings shows this chain's answer in place of "automatic", so each - // step must report where the JDK came from, and a pending discovery must - // not be replaced by a synchronous probe. - let locator = ChoiceRuntimeLocator( - environmentValues: ["JAVA_HOME": "/jdk/env"], - validJavaHomes: ["/jdk/env", "/jdk/detected", "/jdk/project"] - ) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - service.openProject(at: URL(fileURLWithPath: "/workspace", isDirectory: true)) - - #expect(describe(service.chooseJavaHome(overridePath: nil) { nil }) == "found /jdk/env javaHomeEnvironment") - #expect(service.javaHomeURL()?.path == "/jdk/env") - #expect(locator.discoverCalls == 0) - #expect(describe(service.chooseJavaHome(overridePath: "/missing") { nil }) == "invalid /missing") - #expect(describe(service.chooseJavaHome(overridePath: "/jdk/detected") { nil }) == "found /jdk/detected configured") - - var settings = service.settings - settings.javaHomePath = "/jdk/project" - service.updateSettings(settings) - #expect(describe(service.chooseJavaHome(overridePath: nil) { nil }) == "found /jdk/project projectSetting") - #expect(service.javaHomeURL()?.path == "/jdk/project") - #expect(locator.discoverCalls == 0) - } - - @Test - @MainActor - func automaticJavaChoiceWaitsForDiscoveryInsteadOfProbing() { - let locator = ChoiceRuntimeLocator(environmentValues: [:], validJavaHomes: ["/jdk/detected"]) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - service.openProject(at: URL(fileURLWithPath: "/workspace", isDirectory: true)) - let detected = JavaRuntimeCandidate(homePath: "/jdk/detected", version: "21.0.4", vendor: "Temurin") - - #expect(service.chooseJavaHome(overridePath: nil) { nil } == nil) - #expect(describe(service.chooseJavaHome(overridePath: nil) { [detected] }) == "found /jdk/detected detected") - #expect(describe(service.chooseJavaHome(overridePath: nil) { [] }) == "notFound") - #expect(locator.discoverCalls == 0) - } - - @Test - @MainActor - func viewsShowingAutomaticRuntimesStartDiscoveryOnce() async { - // The Run configuration editor can be opened without visiting the project - // page, which used to be the only place that started discovery. - let locator = ChoiceRuntimeLocator(environmentValues: [:], validJavaHomes: []) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - await service.ensureRuntimesDiscovered() - #expect(locator.discoverCalls == 0) - - service.openProject(at: URL(fileURLWithPath: "/workspace", isDirectory: true)) - #expect(!service.hasDiscoveredRuntimes) - await service.ensureRuntimesDiscovered() - #expect(service.hasDiscoveredRuntimes) - await service.ensureRuntimesDiscovered() - // One discovery in total: the environment report must reuse its result - // instead of probing every JDK again on the main actor. - #expect(locator.discoverCalls == 1) - #expect(service.javaHomeURL() == nil) - #expect(service.mavenJavaHomeURL() == nil) - #expect(locator.discoverCalls == 1) - service.closeProject() - service.openProject(at: URL(fileURLWithPath: "/another-fixture-workspace", isDirectory: true)) - #expect(service.javaHomeURL() == nil) - #expect(service.mavenJavaHomeURL() == nil) - #expect(locator.discoverCalls == 2) - } - - @Test - @MainActor - func mavenJavaChoiceReportsAFallbackInsteadOfHidingIt() { - let locator = ChoiceRuntimeLocator( - environmentValues: ["JAVA_HOME": "/jdk/env"], - validJavaHomes: ["/jdk/env", "/jdk/maven"] - ) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - service.openProject(at: URL(fileURLWithPath: "/workspace", isDirectory: true)) - - #expect(describe(service.chooseMavenJavaHome(overridePath: nil) { [] }) == "found /jdk/env projectJDK") - - var settings = service.settings - settings.mavenJavaHomePath = "/missing-maven-jdk" - service.updateSettings(settings) - // Launches keep falling back to the project JDK; Settings now says so. - #expect(describe(service.chooseMavenJavaHome(overridePath: nil) { [] }) - == "fallback /missing-maven-jdk -> found /jdk/env javaHomeEnvironment") - #expect(service.mavenJavaHomeURL()?.path == "/jdk/env") - - settings.mavenJavaHomePath = "/jdk/maven" - service.updateSettings(settings) - #expect(describe(service.chooseMavenJavaHome(overridePath: nil) { [] }) == "found /jdk/maven projectSetting") - // A usable Maven JDK never walks the project chain, which may probe every JDK. - #expect(locator.discoverCalls == 0) - } - - @Test - @MainActor - func mavenChoiceNamesWrapperSystemAndInvalidSelections() { - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let wrapper = root.appendingPathComponent("mvnw") - let system = URL(fileURLWithPath: "/usr/local/bin/mvn") - let withWrapper = ProjectRuntimeService( - runtimeLocator: ChoiceRuntimeLocator(executables: [wrapper.path], systemMaven: system), - store: EmptyKeyValueStore() - ) - #expect(describe(withWrapper.chooseMavenExecutable(at: root)) == "found /workspace/mvnw mavenWrapper") - #expect(describe(withWrapper.chooseMavenExecutable(at: root, overridePath: "/missing")) == "invalid /missing") - - let systemOnly = ProjectRuntimeService( - runtimeLocator: ChoiceRuntimeLocator(systemMaven: system), - store: EmptyKeyValueStore() - ) - #expect(describe(systemOnly.chooseMavenExecutable(at: root)) == "found /usr/local/bin/mvn systemMaven") - let none = ProjectRuntimeService(runtimeLocator: ChoiceRuntimeLocator(), store: EmptyKeyValueStore()) - #expect(describe(none.chooseMavenExecutable(at: root)) == "notFound") - } - - @Test - @MainActor - func runtimeSelectionsReadCurrentCanonicalDefaults() throws { - let store = InMemoryProjectRuntimeSettingsStore() - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let service = ProjectRuntimeService( - runtimeLocator: MavenOverrideRuntimeLocator(resolutions: [:]), settingsStore: store - ) - service.openProject(at: root) - let original = try store.load(at: root, migrateLegacy: false) - var current = original.settings - current.javaHomePath = "/fixture/run-jdk" - current.mavenHomeSelection = .wrapper - _ = try store.save(current, at: root, expecting: original) - service.reloadSettings() - #expect(service.settings.javaHomePath == "/fixture/run-jdk") - #expect(service.settings.mavenHomeSelection == .wrapper) - let saved = try store.load(at: root, migrateLegacy: false) - _ = try store.save(ProjectRuntimeSettings(), at: root, expecting: saved) - service.reloadSettings() - #expect(service.settings.projectToolchainSelection() == ProjectToolchainSelection()) - store.failure = CocoaError(.fileReadCorruptFile) - #expect(service.javaHomeURL() == nil) - #expect(service.settingsError != nil) - } - - @Test - @MainActor - func mavenOverrideUsesRuntimeLocatorForHomeExecutableAndInvalidPaths() { - let root = URL(fileURLWithPath: "/workspace", isDirectory: true) - let home = root.appendingPathComponent("toolchains/maven", isDirectory: true) - let homeExecutable = home.appendingPathComponent("bin/mvn") - let directExecutable = root.appendingPathComponent("toolchains/custom-mvn") - let locator = MavenOverrideRuntimeLocator(resolutions: [ - home.standardizedFileURL.path: homeExecutable, - directExecutable.standardizedFileURL.path: directExecutable - ]) - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - - #expect(service.mavenExecutable(at: root, overridePath: "toolchains/maven") == homeExecutable) - #expect(service.mavenExecutable(at: root, overridePath: directExecutable.path) == directExecutable) - #expect(service.mavenExecutable(at: root, overridePath: "toolchains/missing") == nil) - } - - @Test(arguments: ["mvn", "mvnd"]) - @MainActor - func macRuntimeDiscoveryDistinguishesMavenHomeFromExecutable(launcher: String) throws { - let testRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-maven-runtime-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: testRoot) } - let home = testRoot.appendingPathComponent("apache-maven", isDirectory: true) - let homeExecutable = home.appendingPathComponent("bin/\(launcher)") - let directExecutable = testRoot.appendingPathComponent("custom-mvn") - let invalidHome = testRoot.appendingPathComponent("invalid-maven", isDirectory: true) - try FileManager.default.createDirectory( - at: homeExecutable.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try FileManager.default.createDirectory(at: invalidHome, withIntermediateDirectories: true) - #expect(FileManager.default.createFile(atPath: homeExecutable.path, contents: Data())) - #expect(FileManager.default.createFile(atPath: directExecutable.path, contents: Data())) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: homeExecutable.path - ) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: directExecutable.path - ) - - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: home.path) == homeExecutable) - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: directExecutable.path) == directExecutable) - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: invalidHome.path) == nil) - - // Exercise the real adapter through the service: POSIX execute permission - // on a directory means traversal, not that it can be launched as Maven. - let locator = MacRuntimeLocator() - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - #expect(!locator.isExecutable(at: home)) - #expect(locator.isExecutable(at: homeExecutable)) - #expect(service.mavenExecutable(at: testRoot, overridePath: home.path) == homeExecutable) - #expect(service.mavenExecutable(at: testRoot, overridePath: "apache-maven") == homeExecutable) - #expect(service.mavenExecutable(at: testRoot, overridePath: directExecutable.path) == directExecutable) - #expect(service.mavenExecutable(at: testRoot, overridePath: invalidHome.path) == nil) - - if launcher == "mvnd" { - let ordinaryMaven = home.appendingPathComponent("bin/mvn") - try Data().write(to: ordinaryMaven) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ordinaryMaven.path) - #expect(MacRuntimeDiscovery.mavenExecutable(forHomePath: home.path) == homeExecutable) - try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: ordinaryMaven.path) - } - let binLink = testRoot.appendingPathComponent("bin-alias", isDirectory: true) - try FileManager.default.createSymbolicLink(at: binLink, withDestinationURL: home.appendingPathComponent("bin")) - #expect(service.mavenExecutable(at: testRoot, overridePath: binLink.path) == binLink.appendingPathComponent(launcher)) - let homeLink = testRoot.appendingPathComponent("maven-link", isDirectory: true) - let executableLink = testRoot.appendingPathComponent("mvn-link") - try FileManager.default.createSymbolicLink(at: homeLink, withDestinationURL: home) - try FileManager.default.createSymbolicLink(at: executableLink, withDestinationURL: homeExecutable) - #expect(!locator.isExecutable(at: homeLink)) - #expect(service.mavenExecutable(at: testRoot, overridePath: homeLink.path) == homeLink.appendingPathComponent("bin/\(launcher)")) - #expect(service.mavenExecutable(at: testRoot, overridePath: home.appendingPathComponent("bin").path) == homeExecutable) - #expect(service.mavenExecutable(at: testRoot, overridePath: executableLink.path) == executableLink) - - try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: homeExecutable.path) - #expect(!locator.isExecutable(at: homeExecutable)) - #expect(service.mavenExecutable(at: testRoot, overridePath: home.path) == nil) - #expect(service.mavenExecutable(at: testRoot, overridePath: homeExecutable.path) == nil) - } - - @Test - @MainActor - func canceledRuntimeDiscoveryClearsDiscoveringState() async throws { - let locator = BlockingRuntimeLocator() - defer { locator.release() } - let service = ProjectRuntimeService(runtimeLocator: locator, store: EmptyKeyValueStore()) - let task = Task { @MainActor in - await service.refreshAvailableRuntimes() - } - - #expect(await locator.waitUntilStarted()) - #expect(service.isDiscovering) - - task.cancel() - locator.release() - await task.value - - #expect(!service.isDiscovering) - } - - private static func platformContractFixture() throws -> MavenPlatformContractFixture { - let repositoryRoot = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent() - .deletingLastPathComponent() - .deletingLastPathComponent() - .deletingLastPathComponent() - let url = repositoryRoot.appendingPathComponent( - "shared/fixtures/maven/platform-contract-v1.json" - ) - return try JSONDecoder().decode( - MavenPlatformContractFixture.self, - from: Data(contentsOf: url) - ) - } - - -} - -private struct MavenPlatformContractFixture: Decodable { - struct StorageIdentityCase: Decodable { - let platform: String - let workspacePath: String - let reactorPath: String - let expectedIdentity: String - } - - let lifecyclePhases: [String] - let storageIdentityCases: [StorageIdentityCase] -} - -private struct MavenTestFileStorage: FileStorage { - let root: URL - - func homeDirectory() -> URL { root.appendingPathComponent("home", isDirectory: true) } - func cacheDirectory() -> URL { root.appendingPathComponent("cache", isDirectory: true) } - func applicationSupportDirectory() -> URL { - root.appendingPathComponent("application-support", isDirectory: true) - } - func temporaryDirectory() -> URL { root.appendingPathComponent("temporary", isDirectory: true) } - func metadata(for url: URL) -> FileMetadata? { - guard let values = try? url.resourceValues(forKeys: [ - .fileSizeKey, .contentModificationDateKey, .isRegularFileKey, .isDirectoryKey - ]) else { return nil } - return FileMetadata( - byteCount: values.fileSize, - modificationDate: values.contentModificationDate, - isRegularFile: values.isRegularFile == true, - isDirectory: values.isDirectory == true - ) - } - func fileExists(at url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) } - func isExecutable(at url: URL) -> Bool { FileManager.default.isExecutableFile(atPath: url.path) } - func listDirectory(at url: URL) -> [URL] { - (try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)) ?? [] - } - func readPrefix(from url: URL, byteCount: Int) throws -> Data { - Data(try Data(contentsOf: url).prefix(byteCount)) - } - func readData(from url: URL, options: Data.ReadingOptions) throws -> Data { - try Data(contentsOf: url, options: options) - } - func writeData(_ data: Data, to url: URL, options: Data.WritingOptions) throws { - try data.write(to: url, options: options) - } - func createDirectory(at url: URL, withIntermediateDirectories: Bool) throws { - try FileManager.default.createDirectory( - at: url, - withIntermediateDirectories: withIntermediateDirectories - ) - } - func removeItem(at url: URL) throws { try FileManager.default.removeItem(at: url) } - func moveItem(at sourceURL: URL, to destinationURL: URL) throws { - try FileManager.default.moveItem(at: sourceURL, to: destinationURL) - } - func copyItem(at sourceURL: URL, to destinationURL: URL) throws { - try FileManager.default.copyItem(at: sourceURL, to: destinationURL) - } -} - -private struct ProjectRelativeRuntimeLocator: RuntimeLocator { - let validJavaHomes: Set - - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { - validJavaHomes.contains(path) ? URL(fileURLWithPath: path, isDirectory: true) : nil - } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } - func javaLanguageServerExecutable() -> URL? { nil } -} - -private struct MavenOverrideRuntimeLocator: RuntimeLocator { - let resolutions: [String: URL] - - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { - resolutions[url.standardizedFileURL.path]?.standardizedFileURL == url.standardizedFileURL - } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { - resolutions[URL(fileURLWithPath: path).standardizedFileURL.path] - } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } - func systemJDBExecutable() -> URL? { nil } -} - -private final class BlockingRuntimeLocator: RuntimeLocator, @unchecked Sendable { - private let started = TestGate() - private let releaseGate = TestGate() - - func release() { - releaseGate.open() - } - - func waitUntilStarted() async -> Bool { - await started.waitUntilOpen() - } - - func environment() -> [String: String] { [:] } - - func discover() -> RuntimeDiscoveryResult { - started.open() - _ = releaseGate.waitSynchronously() - return RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } - func javaLanguageServerExecutable() -> URL? { nil } -} - -private struct EmptyKeyValueStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} - func removeObject(forKey key: String) {} -} - -/// Flattens a runtime choice for readable expectations. -private func describe(_ choice: RuntimeChoice?) -> String { - switch choice { - case nil: "detecting" - case .found(let url, let source)?: "found \(url.path) \(source)" - case .invalid(let path)?: "invalid \(path)" - case .fallback(let path, let replacement)?: "fallback \(path) -> \(describe(replacement))" - case .warning(let url, _, let message)?: "warning \(url.path) \(message)" - case .unavailable(let message)?: "unavailable \(message)" - case .notFound?: "notFound" - } -} - -/// Runtime locator with fixed answers that counts synchronous discoveries. -private final class ChoiceRuntimeLocator: RuntimeLocator, @unchecked Sendable { - private let environmentValues: [String: String] - private let validJavaHomes: Set - private let executables: Set - private let systemMaven: URL? - private let runtimeCandidates: [JavaRuntimeCandidate] - private(set) var discoverCalls = 0 - - init( - environmentValues: [String: String] = [:], - validJavaHomes: Set = [], - executables: Set = [], - systemMaven: URL? = nil, - runtimeCandidates: [JavaRuntimeCandidate] = [] - ) { - self.environmentValues = environmentValues - self.validJavaHomes = validJavaHomes - self.executables = executables - self.systemMaven = systemMaven - self.runtimeCandidates = runtimeCandidates - } - - func environment() -> [String: String] { environmentValues } - func discover() -> RuntimeDiscoveryResult { - discoverCalls += 1 - return RuntimeDiscoveryResult(javaRuntimes: runtimeCandidates, mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { - validJavaHomes.contains(path) ? URL(fileURLWithPath: path, isDirectory: true) : nil - } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { executables.contains(url.standardizedFileURL.path) } - func systemMavenExecutable() -> URL? { systemMaven } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} diff --git a/macos/Tests/LitheTests/MonacoDocumentContextTests.swift b/macos/Tests/LitheTests/MonacoDocumentContextTests.swift index 209c94613c..d520e6dab6 100644 --- a/macos/Tests/LitheTests/MonacoDocumentContextTests.swift +++ b/macos/Tests/LitheTests/MonacoDocumentContextTests.swift @@ -9,8 +9,8 @@ struct MonacoDocumentContextTests { @Test(arguments: ["rename", "rename-back", "close", "reopen", "workspace", "edit"]) func lateResponseCannotUseChangedDocument(change: String) { - let url = root.appendingPathComponent("Probe.java") - let document = EditorDocument(url: url, text: "class Probe {}", modificationDate: nil) + let url = root.appendingPathComponent("Probe.txt") + let document = EditorDocument(url: url, text: "probe", modificationDate: nil) let context = MonacoDocumentContext(document: document, revision: 7, workspaceURL: root) var documents = [document] var workspaceURL = root @@ -22,13 +22,13 @@ struct MonacoDocumentContextTests { #expect(accept()) switch change { case "rename", "rename-back": - document.relocate(to: root.appendingPathComponent("Other.java")) + document.relocate(to: root.appendingPathComponent("Other.txt")) if change == "rename-back" { document.relocate(to: url) } case "close": documents.removeAll() case "reopen": documents = [EditorDocument(url: url, text: document.text, modificationDate: nil)] case "workspace": workspaceURL = root.appendingPathComponent("other-workspace") case "edit": - document.applyLiveEditorText("class Edited {}") + document.applyLiveEditorText("edited") revision += 1 default: Issue.record("Unknown change") } @@ -36,19 +36,19 @@ struct MonacoDocumentContextTests { } @Test func commandMayFollowItsOwnWorkspaceEditButNotAMoveOrClose() { - let document = EditorDocument(url: root.appendingPathComponent("Probe.java"), - text: "class Probe {}", modificationDate: nil) + let document = EditorDocument(url: root.appendingPathComponent("Probe.txt"), + text: "probe", modificationDate: nil) let context = MonacoDocumentContext(document: document, revision: 0, workspaceURL: root) - document.applyLiveEditorText("class Fixed {}") + document.applyLiveEditorText("fixed") #expect(context.matchesIdentity(document: document, documents: [document], workspaceURL: root)) #expect(!context.matches(document: document, revision: 1, documents: [document], workspaceURL: root)) #expect(!context.matchesIdentity(document: document, documents: [], workspaceURL: root)) - document.relocate(to: root.appendingPathComponent("Fixed.java")) + document.relocate(to: root.appendingPathComponent("Fixed.txt")) #expect(!context.matchesIdentity(document: document, documents: [document], workspaceURL: root)) } @Test func sameLocationRefreshDoesNotInvalidateRequests() { - let document = EditorDocument(url: root.appendingPathComponent("Probe.java"), text: "", modificationDate: nil) + let document = EditorDocument(url: root.appendingPathComponent("Probe.txt"), text: "", modificationDate: nil) let context = MonacoDocumentContext(document: document, revision: 0, workspaceURL: root) document.relocate(to: document.url) #expect(context.matches(document: document, revision: 0, documents: [document], workspaceURL: root)) @@ -56,8 +56,8 @@ struct MonacoDocumentContextTests { @Test(arguments: ["edit", "rename-back", "close"]) func workspaceResultRejectsChangedTargetWithoutAMonacoView(change: String) { - let source = EditorDocument(url: root.appendingPathComponent("Source.java"), text: "source", modificationDate: nil) - let target = EditorDocument(url: root.appendingPathComponent("Target.java"), text: "target", modificationDate: nil) + let source = EditorDocument(url: root.appendingPathComponent("Source.txt"), text: "source", modificationDate: nil) + let target = EditorDocument(url: root.appendingPathComponent("Target.txt"), text: "target", modificationDate: nil) var documents = [source, target] let context = MonacoWorkspaceContext(documents: documents, workspaceURL: root) #expect(context.matches(documents: documents, workspaceURL: root)) @@ -65,7 +65,7 @@ struct MonacoDocumentContextTests { case "edit": target.applyLiveEditorText("new target input") case "rename-back": let url = target.url - target.relocate(to: root.appendingPathComponent("Moved.java")) + target.relocate(to: root.appendingPathComponent("Moved.txt")) target.relocate(to: url) case "close": documents.removeLast() default: Issue.record("Unknown target change") diff --git a/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift b/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift index 61dbd3ed06..2f5def8ff9 100644 --- a/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift +++ b/macos/Tests/LitheTests/MonacoWorkbenchSessionLifetimeTests.swift @@ -69,7 +69,7 @@ struct MonacoWorkbenchSessionLifetimeTests { @Test func readOnlyPreviewRejectsRunActionsAtTheNativeBoundary() { let main = MonacoWorkbenchSession.forModel(UUID()) let preview = MonacoWorkbenchSession.forModel(UUID(), documentID: UUID(), previewID: UUID()) - for message in ["javaRunMarkerAction", "pluginEditorAction", "pluginEditorProviderCommand", "format", "rename", + for message in ["pluginEditorAction", "pluginEditorProviderCommand", "format", "rename", "executeCodeAction", "setBlameVisibility"] { #expect(main.allowsMessage(message)) #expect(!preview.allowsMessage(message)) @@ -80,8 +80,8 @@ struct MonacoWorkbenchSessionLifetimeTests { @Test func independentPreviewKeepsMainDocumentAndSynchronizationOwner() throws { let project = UUID(), previewID = UUID() - let document = EditorDocument(url: URL(fileURLWithPath: "/fixture/Problems.java"), - text: "class Problems {}", modificationDate: nil) + let document = EditorDocument(url: URL(fileURLWithPath: "/fixture/Problems.txt"), + text: "problems", modificationDate: nil) let main = MonacoWorkbenchSession.forModel(project, documentID: document.id) main.register(document) let owner = try #require(document.editorSynchronizationOwnerID) diff --git a/macos/Tests/LitheTests/MybatisFeatureModelTests.swift b/macos/Tests/LitheTests/MybatisFeatureModelTests.swift deleted file mode 100644 index 3514ad47d7..0000000000 --- a/macos/Tests/LitheTests/MybatisFeatureModelTests.swift +++ /dev/null @@ -1,222 +0,0 @@ -import Foundation -import Testing -@testable import Lithe - -@Suite("MyBatis feature model") -@MainActor -struct MybatisFeatureModelTests { - @Test - func mapperMethodNavigationJumpsToTheXmlStatement() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("src/main/java/demo/UserMapper.java") - let xmlURL = root.appendingPathComponent("src/main/resources/mapper/UserMapper.xml") - let feature = MybatisFeatureModel(operations: MybatisTestOperations(result: index( - javaURL: javaURL, - xmlURL: xmlURL - ))) - await feature.load(workspaceURL: root, files: [javaURL, xmlURL]) - - let location = try #require( - feature.navigationLocations(for: javaURL, line: 8, utf16Column: 9).first - ) - #expect(location.url == xmlURL) - #expect(location.range.start.line == 4) - #expect(location.range.start.utf16Column == 16) - #expect(feature.handles(javaURL)) - #expect(feature.handles(xmlURL)) - } - - @Test - func mapperReturnTypeAndParameterKeepLanguageServerNavigation() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("UserMapper.java") - let xmlURL = root.appendingPathComponent("UserMapper.xml") - let feature = MybatisFeatureModel(operations: MybatisTestOperations(result: index( - javaURL: javaURL, - xmlURL: xmlURL, - javaLine: 9, - javaColumn: 10, - javaEndColumn: 14, - xmlLine: 5, - xmlColumn: 17, - xmlEndColumn: 21 - ))) - await feature.load(workspaceURL: root, files: [javaURL, xmlURL]) - - #expect(feature.navigationLocations(for: javaURL, line: 8, utf16Column: 4).isEmpty) - #expect(feature.navigationLocations(for: javaURL, line: 8, utf16Column: 16).isEmpty) - #expect(feature.navigationLocations(for: javaURL, line: 11, utf16Column: 9).isEmpty) - let location = try #require( - feature.navigationLocations(for: javaURL, line: 8, utf16Column: 9).first - ) - #expect(location.url == xmlURL) - } - - @Test - func xmlStatementNavigationJumpsToTheMapperMethod() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("UserMapper.java") - let xmlURL = root.appendingPathComponent("UserMapper.xml") - let feature = MybatisFeatureModel(operations: MybatisTestOperations(result: index( - javaURL: javaURL, - xmlURL: xmlURL - ))) - await feature.load(workspaceURL: root, files: [javaURL, xmlURL]) - - let location = try #require( - feature.navigationLocations(for: xmlURL, line: 4, utf16Column: 16).first - ) - #expect(location.url == javaURL) - #expect(location.range.start.line == 8) - #expect(location.range.start.utf16Column == 9) - #expect(feature.navigationLocations(for: xmlURL, line: 4, utf16Column: 4).isEmpty) - } - - @Test - func loadDropsUnrelatedProjectFilesBeforeIndexing() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("UserMapper.java") - let xmlURL = root.appendingPathComponent("UserMapper.xml") - let sqlURL = root.appendingPathComponent("dump.sql") - let pomURL = root.appendingPathComponent("pom.xml") - let operations = MybatisTestOperations(result: index(javaURL: javaURL, xmlURL: xmlURL)) - let feature = MybatisFeatureModel(operations: operations) - await feature.load(workspaceURL: root, files: [sqlURL, pomURL, javaURL, xmlURL]) - - #expect(operations.requestedFiles == [[javaURL, xmlURL]]) - } - - /// Opening a workspace must not wait for mapper indexing. - @Test - func scheduleLoadDefersIndexingAndPublishesTheResult() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("UserMapper.java") - let xmlURL = root.appendingPathComponent("UserMapper.xml") - let operations = MybatisTestOperations(result: index(javaURL: javaURL, xmlURL: xmlURL)) - let feature = MybatisFeatureModel(operations: operations) - defer { feature.reset() } - - feature.scheduleLoad(workspaceURL: root, files: [javaURL, xmlURL]) - - #expect(feature.statements.isEmpty) - #expect(operations.requestedFiles.isEmpty) - - let published = await awaitChange(on: feature) { - !feature.isIndexing && !feature.statements.isEmpty - } - #expect(published, "the scheduled index never published a result") - #expect(feature.statements.map(\.statementID) == ["selectById"]) - #expect(operations.requestedFiles == [[javaURL, xmlURL]]) - } - - @Test - func unpairedAndTemporarilyMissingMapperEditsRemainEligible() async throws { - let root = URL(fileURLWithPath: "/workspace") - let javaURL = root.appendingPathComponent("src/main/java/demo/UserMapper.java") - let xmlURL = root.appendingPathComponent("src/main/resources/mapper/UserMapper.xml") - let feature = MybatisFeatureModel(operations: MybatisTestOperations(result: index( - javaURL: javaURL, - xmlURL: xmlURL - ))) - await feature.load(workspaceURL: root, files: [javaURL, xmlURL]) - - #expect(feature.editChangesIndex(javaURL)) - #expect(feature.editChangesIndex(root.appendingPathComponent("src/main/resources/mapper/OrderMapper.xml"))) - #expect(feature.editChangesIndex(root.appendingPathComponent("src/main/java/demo/NewMapper.java"))) - feature.reset() - #expect(feature.statements.isEmpty) - #expect(feature.editChangesIndex(javaURL)) - #expect(!feature.editChangesIndex(root.appendingPathComponent("README.md"))) - } - - /// A newer schedule supersedes the pending one so a burst of reloads cannot - /// publish a stale index. - @Test - func scheduleLoadReplacesAPendingSchedule() async throws { - let root = URL(fileURLWithPath: "/workspace") - let staleURL = root.appendingPathComponent("StaleMapper.java") - let freshURL = root.appendingPathComponent("FreshMapper.java") - let xmlURL = root.appendingPathComponent("UserMapper.xml") - let operations = MybatisTestOperations { files in - files.first.map { index(javaURL: $0, xmlURL: xmlURL) } ?? .empty - } - let feature = MybatisFeatureModel(operations: operations) - defer { feature.reset() } - - feature.scheduleLoad(workspaceURL: root, files: [staleURL]) - feature.scheduleLoad(workspaceURL: root, files: [freshURL]) - - let published = await awaitChange(on: feature) { - !feature.isIndexing && !feature.statements.isEmpty - } - #expect(published, "the replacement schedule never published a result") - #expect(operations.requestedFiles == [[freshURL]]) - #expect(feature.statements.map(\.javaURL) == [freshURL]) - } -} - -private func index( - javaURL: URL, - xmlURL: URL, - javaLine: Int = 9, - javaColumn: Int = 10, - javaEndColumn: Int = 20, - xmlLine: Int = 5, - xmlColumn: Int = 17, - xmlEndColumn: Int = 27 -) -> MybatisIndexResult { - MybatisIndexResult( - statements: [MybatisStatement( - id: javaURL.lastPathComponent, - namespace: "demo.UserMapper", - statementID: "selectById", - kind: "select", - javaURL: javaURL, - javaLine: javaLine, - javaColumn: javaColumn, - javaEndLine: javaLine, - javaEndColumn: javaEndColumn, - xmlURL: xmlURL, - xmlLine: xmlLine, - xmlColumn: xmlColumn, - xmlEndColumn: xmlEndColumn - )] - ) -} - -private final class MybatisTestOperations: JavaMavenOperations, @unchecked Sendable { - private let makeResult: @Sendable ([URL]) -> MybatisIndexResult - private let lock = NSLock() - private var requested: [[URL]] = [] - - var requestedFiles: [[URL]] { - lock.lock() - defer { lock.unlock() } - return requested - } - - init(result: MybatisIndexResult) { - makeResult = { _ in result } - } - - init(resultForFiles: @escaping @Sendable ([URL]) -> MybatisIndexResult) { - makeResult = resultForFiles - } - - func mybatisIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String] - ) -> MybatisIndexResult? { - lock.lock() - requested.append(files) - lock.unlock() - return makeResult(files) - } - - func codeVision(at rootURL: URL, targetPath: String, paths: [String]) -> [JavaCodeVisionValue] { [] } - func className(source: String, simpleName: String) -> String? { nil } - func sourceDefinition(source: String, declarationName: String, memberName: String?) -> (line: Int, utf16Column: Int)? { nil } - func serverPort(content: String, fileExtension: String) -> Int? { nil } - func structure(source: String, declarationSources: [String]) -> JavaStructureResult? { nil } -} diff --git a/macos/Tests/LitheTests/NavigationHistoryFeatureModelTests.swift b/macos/Tests/LitheTests/NavigationHistoryFeatureModelTests.swift index 92f434e684..de6eb71859 100644 --- a/macos/Tests/LitheTests/NavigationHistoryFeatureModelTests.swift +++ b/macos/Tests/LitheTests/NavigationHistoryFeatureModelTests.swift @@ -8,9 +8,9 @@ struct NavigationHistoryFeatureModelTests { @Test func backAndForwardPreserveLiveCaretLocations() throws { let model = NavigationHistoryFeatureModel(logSink: nil) - let first = location("First.java", line: 4, column: 2) - let second = location("Second.java", line: 9, column: 7) - let movedSecond = location("Second.java", line: 14, column: 3) + let first = location("First.txt", line: 4, column: 2) + let second = location("Second.txt", line: 9, column: 7) + let movedSecond = location("Second.txt", line: 14, column: 3) model.recordJump(from: first, to: second) @@ -23,9 +23,9 @@ struct NavigationHistoryFeatureModelTests { @Test func newJumpClearsForwardHistory() { let model = NavigationHistoryFeatureModel(logSink: nil) - let first = location("First.java", line: 1) - let second = location("Second.java", line: 2) - let third = location("Third.java", line: 3) + let first = location("First.txt", line: 1) + let second = location("Second.txt", line: 2) + let third = location("Third.txt", line: 3) model.recordJump(from: first, to: second) #expect(model.navigateBack(from: second) == first) @@ -38,28 +38,28 @@ struct NavigationHistoryFeatureModelTests { @Test func historyIsDeduplicatedAndBoundedByCore() { let model = NavigationHistoryFeatureModel(logSink: nil) - let destination = location("Target.java", line: 0) - let repeated = location("First.java", line: 1) + let destination = location("Target.txt", line: 0) + let repeated = location("First.txt", line: 1) model.recordJump(from: repeated, to: destination) model.recordJump(from: repeated, to: destination) #expect(model.backLocations == [repeated]) for line in 0...100 { - model.recordJump(from: location("Many.java", line: line + 2), to: destination) + model.recordJump(from: location("Many.txt", line: line + 2), to: destination) } // Core keeps the newest 100 entries (shared/fixtures/editor/navigation-history-v1.json). #expect(model.backLocations.count == 100) - #expect(model.backLocations.first == location("Many.java", line: 3)) - #expect(model.backLocations.last == location("Many.java", line: 102)) + #expect(model.backLocations.first == location("Many.txt", line: 3)) + #expect(model.backLocations.last == location("Many.txt", line: 102)) } @Test func backSkipsTheEntryAtTheLiveLocation() { let model = NavigationHistoryFeatureModel(logSink: nil) - let first = location("First.java", line: 1) - let second = location("Second.java", line: 2) - let third = location("Third.java", line: 3) + let first = location("First.txt", line: 1) + let second = location("Second.txt", line: 2) + let third = location("Third.txt", line: 3) model.recordJump(from: first, to: second) model.recordJump(from: second, to: third) @@ -71,12 +71,12 @@ struct NavigationHistoryFeatureModelTests { @Test func virtualAndReadOnlyContextSurvivesTheCoreRoundTrip() throws { let model = NavigationHistoryFeatureModel(logSink: nil) - let url = try #require(URL(string: "jdt://contents/java.base/java/lang/String.class?=a%20b")) + let url = try #require(URL(string: "example-plugin://contents/library/docs/readme.txt?=a%20b")) let virtual = EditorNavigationLocation( url: url, line: 8, utf16Column: 4, isReadOnly: true, - displayPath: "java.base/java/lang/String.class", virtualProviderID: "java" + displayPath: "library/docs/readme.txt", virtualProviderID: "example-plugin" ) - model.recordJump(from: virtual, to: location("Other.java", line: 1)) + model.recordJump(from: virtual, to: location("Other.txt", line: 1)) #expect(model.navigateBack(from: nil) == virtual) } @@ -84,8 +84,8 @@ struct NavigationHistoryFeatureModelTests { @Test func resetClearsBothDirections() { let model = NavigationHistoryFeatureModel(logSink: nil) - let first = location("First.java", line: 1) - let second = location("Second.java", line: 2) + let first = location("First.txt", line: 1) + let second = location("Second.txt", line: 2) model.recordJump(from: first, to: second) _ = model.navigateBack(from: second) @@ -98,8 +98,8 @@ struct NavigationHistoryFeatureModelTests { @Test func failedNavigationCanRestoreBothStacks() { let model = NavigationHistoryFeatureModel(logSink: nil) - let first = location("First.java", line: 1) - let second = location("Second.java", line: 2) + let first = location("First.txt", line: 1) + let second = location("Second.txt", line: 2) model.recordJump(from: first, to: second) let snapshot = model.snapshot() @@ -112,18 +112,18 @@ struct NavigationHistoryFeatureModelTests { @Test func virtualLocationsKeepTheirOwningProvider() throws { - let url = try #require(URL(string: "jdt://contents/java.base/java/lang/String.class")) + let url = try #require(URL(string: "example-plugin://contents/library/docs/readme.txt")) let location = EditorNavigationLocation( url: url, line: 8, utf16Column: 4, isReadOnly: true, - displayPath: "java.base/java/lang/String.class", - virtualProviderID: "java" + displayPath: "library/docs/readme.txt", + virtualProviderID: "example-plugin" ) #expect(location.url == url) - #expect(location.virtualProviderID == "java") + #expect(location.virtualProviderID == "example-plugin") #expect(location.isReadOnly) } diff --git a/macos/Tests/LitheTests/PluginBackendLaunchTests.swift b/macos/Tests/LitheTests/PluginBackendLaunchTests.swift index 6e18dba9bd..8206d5a708 100644 --- a/macos/Tests/LitheTests/PluginBackendLaunchTests.swift +++ b/macos/Tests/LitheTests/PluginBackendLaunchTests.swift @@ -214,6 +214,67 @@ struct PluginBackendLaunchTests { fixture.contexts.close(owner: window) } + @Test + func theQuestionCarriesTheRequiredToolsTheHostFound() async throws { + let fixture = try Fixture.make(requiresTools: ["coursier", "jvm"]) + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.packagedAnswer() } + let definedTools = ScriptedDefinedTools(installations: [ + "coursier": ResolvedDefinedToolchain( + executable: URL(fileURLWithPath: "/opt/cs/bin/cs"), environment: [:], projectCode: false, + version: "2.1.0", home: "/opt/cs" + ), + // Chosen by executable: no installation root, no version. + "jvm": ResolvedDefinedToolchain( + executable: URL(fileURLWithPath: "/usr/bin/java"), environment: [:], projectCode: false, version: nil + ) + ]) + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools(), definedTools: definedTools) + + let prepared = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + + let call = try #require(backends.calls.first) + guard case .object(let params) = call.params else { Issue.record("params are not an object"); return } + #expect(params["tools"] == .object([ + "coursier": .object([ + "executable": .string("/opt/cs/bin/cs"), "home": .string("/opt/cs"), "version": .string("2.1.0") + ]), + "jvm": .object(["executable": .string("/usr/bin/java")]) + ])) + // Resolved as installations the way the launch template consumers are, + // never running project code, in manifest order. + #expect(definedTools.calls.map(\.tool) == ["coursier", "jvm"]) + #expect(definedTools.calls.allSatisfy { $0.use == .installation && !$0.projectCodeAllowed }) + await prepared.release() + fixture.contexts.close(owner: window) + } + + @Test + func aRequiredToolThatIsMissingOrInsideTheProjectIsLeftOut() async throws { + let fixture = try Fixture.make(requiresTools: ["coursier", "jvm"]) + defer { fixture.remove() } + let window = NSObject() + fixture.contexts.open(owner: window, rootURL: fixture.workspaceURL, remote: nil) + let backends = ScriptedBackends { _ in Fixture.packagedAnswer() } + let definedTools = ScriptedDefinedTools(installations: [ + "jvm": ResolvedDefinedToolchain( + executable: fixture.workspaceURL.appendingPathComponent("java"), environment: [:], projectCode: true, version: "21" + ) + ]) + let preparer = fixture.preparer(backends: backends, tools: ScriptedTools(), definedTools: definedTools) + + let prepared = try await preparer.prepare(fixture.source, workspaceURL: fixture.workspaceURL) + + let call = try #require(backends.calls.first) + guard case .object(let params) = call.params else { Issue.record("params are not an object"); return } + // Nothing found: the key is absent rather than an empty object, as before. + #expect(params["tools"] == nil) + await prepared.release() + fixture.contexts.close(owner: window) + } + @Test func aToolInsideTheProjectIsRefusedAndTheScratchGoes() async throws { let fixture = try Fixture.make() @@ -367,7 +428,8 @@ private struct Fixture { static func make( manifest: String = "language-server-backend-launch.plugin.json", languageID: String = "scala", - executable: Bool = true + executable: Bool = true, + requiresTools: [String]? = nil ) throws -> Fixture { let root = FileManager.default.temporaryDirectory .appendingPathComponent("lithe-backend-launch-\(UUID().uuidString)", isDirectory: true) @@ -378,9 +440,18 @@ private struct Fixture { try FileManager.default.setAttributes([.posixPermissions: executable ? 0o755 : 0o644], ofItemAtPath: launcher.path) let operations = DeclarativePluginTestSupport.operations - let manifestData = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot + var manifestData = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot .appendingPathComponent("shared/contracts/plugins/v1/fixtures/languages") .appendingPathComponent(manifest)) + if let requiresTools { + // `requiresTools` exists from `serverProcess` 4; the fixture stays at 3 otherwise. + var object = try #require(try JSONSerialization.jsonObject(with: manifestData) as? [String: Any]) + var requires = try #require(object["requires"] as? [String: Any]) + requires["serverProcess"] = 4 + object["requires"] = requires + object["requiresTools"] = requiresTools + manifestData = try JSONSerialization.data(withJSONObject: object) + } let descriptor = try operations.validate(manifest: manifestData) let directories = MacPluginStateDirectories( rootURL: root.appendingPathComponent("state", isDirectory: true), @@ -416,9 +487,11 @@ private struct Fixture { (try? FileManager.default.contentsOfDirectory(atPath: directories.temporaryRootURL.path)) ?? [] } - func preparer(backends: ScriptedBackends, tools: ScriptedTools) -> MacPluginBackendLaunchPreparer { + func preparer( + backends: ScriptedBackends, tools: ScriptedTools, definedTools: ScriptedDefinedTools = ScriptedDefinedTools() + ) -> MacPluginBackendLaunchPreparer { MacPluginBackendLaunchPreparer( - backends: backends, contexts: contexts, resolver: resolver, tools: tools, + backends: backends, contexts: contexts, resolver: resolver, tools: tools, definedTools: definedTools, runtime: NoToolRuntime(), core: RustCoreBridge() ) } @@ -519,6 +592,31 @@ private final class ScriptedTools: BuildToolResolving { } } +/// The user's tool installations, by tool ID; a tool without an entry is missing. +@MainActor +private final class ScriptedDefinedTools: DefinedToolchainResolving { + private let installations: [String: ResolvedDefinedToolchain] + private(set) var calls: [(tool: String, use: DefinedToolchainUse, projectCodeAllowed: Bool)] = [] + + init(installations: [String: ResolvedDefinedToolchain] = [:]) { + self.installations = installations + } + + func resolve(tool: String, directory _: String, workspace _: URL, environment _: [String: String], + minimumVersion _: String?, projectCodeAllowed: Bool, + fixed _: FixedToolchainSelection?, use: DefinedToolchainUse, consumerID _: String?) async throws -> ResolvedDefinedToolchain? { + calls.append((tool, use, projectCodeAllowed)) + return installations[tool] + } + + func resolve(tool: String, directory: String, workspace: URL, environment: [String: String], + minimumVersion: String?, projectCodeAllowed: Bool) async throws -> ResolvedDefinedToolchain? { + try await resolve(tool: tool, directory: directory, workspace: workspace, environment: environment, + minimumVersion: minimumVersion, projectCodeAllowed: projectCodeAllowed, + fixed: nil, use: .executable, consumerID: nil) + } +} + @MainActor private final class NoToolRuntime: LanguageToolRuntimePort { func executableOnPath(_: String) -> URL? { nil } diff --git a/macos/Tests/LitheTests/PluginBuildOptionPersistenceTests.swift b/macos/Tests/LitheTests/PluginBuildOptionPersistenceTests.swift index d4c6c674c0..ba5fc688d6 100644 --- a/macos/Tests/LitheTests/PluginBuildOptionPersistenceTests.swift +++ b/macos/Tests/LitheTests/PluginBuildOptionPersistenceTests.swift @@ -44,7 +44,7 @@ struct PluginBuildOptionPersistenceTests { let runner = OptionCommandRecorder() let service = Self.service(source: source, workspace: workspace, store: store, runner: runner) defer { service.stop() } - _ = try await Self.refreshed(service) { service.reset(workspaceURL: workspace) } + try await Self.refreshed(service, workspace: workspace) { service.reset(workspaceURL: workspace) } #expect(service.entry("cargo:a")?.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/private.xml")) #expect(service.entry("cargo:b")?.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/team-b.xml")) #expect(Array(try await Self.run("cargo:a", service: service, runner: runner).suffix(2)) == ["--config", "/fixture/private.xml"]) @@ -52,7 +52,7 @@ struct PluginBuildOptionPersistenceTests { #expect(try service.configureOption("cargo:a", optionID: "settingsFile", value: nil).value == .string("/fixture/private.xml")) #expect(backing.instanceData.isEmpty) try store.setInstanceDefaults(["settingsFile": .string("/fixture/team.xml")], workspaceURL: workspace, buildSystemID: "cargo") - _ = try await Self.refreshed(service) { service.detect() } + try await Self.refreshed(service, workspace: workspace) { service.detect() } #expect(service.entry("cargo:a")?.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/team.xml")) #expect(try store.projectDocument(workspace).bytes == bytes) } @@ -75,13 +75,13 @@ struct PluginBuildOptionPersistenceTests { let runner = OptionCommandRecorder() let service = Self.service(source: source, workspace: workspace, store: store, runner: runner) defer { service.stop() } - _ = try await Self.refreshed(service) { service.reset(workspaceURL: workspace) } + try await Self.refreshed(service, workspace: workspace) { service.reset(workspaceURL: workspace) } #expect(service.entries.allSatisfy { $0.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/shared.xml") }) #expect(try store.projectDocument(workspace).bytes == original) #expect(backing.instanceData.isEmpty) #expect(service.entry("cargo:a")?.options.first { $0.id == "features" }?.choices.contains { $0.value == "custom-unselected" } == true) #expect(service.entry("cargo:a")?.options.first { $0.id == "features" }?.value == .array([.string("base")])) - _ = try await Self.refreshed(service) { + try await Self.refreshed(service, workspace: workspace) { service.setInstanceOption("cargo:a", optionID: "settingsFile", value: .string("/fixture/local-a.xml")) } #expect(service.entry("cargo:b")?.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/shared.xml")) @@ -97,7 +97,7 @@ struct PluginBuildOptionPersistenceTests { changed.systems["cargo"]?.instanceDefaults["settingsFile"] = .string("/fixture/new-shared.xml") try store.saveProjectDocument(changed, workspace: workspace, expecting: original) #expect(throws: (any Error).self) { try store.saveProjectDocument(shared, workspace: workspace, expecting: original) } - _ = try await Self.refreshed(service) { service.detect() } + try await Self.refreshed(service, workspace: workspace) { service.detect() } #expect(service.entries.allSatisfy { $0.options.first { $0.id == "settingsFile" }?.value == .string("/fixture/new-shared.xml") }) #expect(try await Self.run("cargo:a", service: service, runner: runner) == ["build", "--message-format=short", "--features", "base", "--offline", "--config", "/fixture/new-shared.xml"]) } @@ -126,7 +126,7 @@ struct PluginBuildOptionPersistenceTests { let service = Self.service(source: source, workspace: workspace, store: store, runner: OptionCommandRecorder()) defer { service.stop() } service.reset(workspaceURL: workspace) - await #expect(throws: (any Error).self) { try await service.prepareLanguageImport(workspaceURL: workspace) } + await #expect(throws: (any Error).self) { try await service.awaitDetection(workspaceURL: workspace) } #expect(service.entries.isEmpty) #expect(!service.issues.isEmpty) #expect(try Data(contentsOf: url) == broken) @@ -148,7 +148,7 @@ struct PluginBuildOptionPersistenceTests { let service = Self.service(source: source, workspace: workspace, store: store, runner: OptionCommandRecorder()) defer { service.stop() } service.reset(workspaceURL: workspace) - await #expect(throws: (any Error).self) { try await service.prepareLanguageImport(workspaceURL: workspace) } + await #expect(throws: (any Error).self) { try await service.awaitDetection(workspaceURL: workspace) } #expect(service.entries.isEmpty) #expect(!service.issues.isEmpty) #expect(backing.object(forKey: key) as? String == "retain the malformed preference") @@ -170,7 +170,7 @@ struct PluginBuildOptionPersistenceTests { defer { service.stop() } service.reset(workspaceURL: workspace) do { - _ = try await service.prepareLanguageImport(workspaceURL: workspace) + try await service.awaitDetection(workspaceURL: workspace) Issue.record("A failed migration must block publishing an unrelated default configuration") } catch { #expect(!service.issues.isEmpty) @@ -179,16 +179,14 @@ struct PluginBuildOptionPersistenceTests { #expect(try store.options(workspaceURL: workspace, buildSystemID: "cargo") == previous) #expect(try store.emptyMultiSelectOptions(workspaceURL: workspace, buildSystemID: "cargo") == ["a": ["features"], "temporarily-absent": ["features"]]) backing.refuseInstanceWrites = false - let imported = try await Self.refreshed(service) { service.detect() } - #expect(imported.mavenContext?.profiles == []) - #expect(imported.mavenContext?.settingsPath == "/fixture/shared.xml") + try await Self.refreshed(service, workspace: workspace) { service.detect() } #expect(try store.options(workspaceURL: workspace, buildSystemID: "cargo") == ["offline": .bool(true)]) #expect(try store.emptyMultiSelectOptions(workspaceURL: workspace, buildSystemID: "cargo").isEmpty) #expect(try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["a"]?["features"] == .array([])) #expect(try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["temporarily-absent"]?["features"] == .array([])) #expect(try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["b"]?["features"] == .array([.string("gui")])) #expect(try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["b"]?["settingsFile"] == .string("/fixture/explicit b.xml")) - _ = try await Self.refreshed(service) { service.detect() } + try await Self.refreshed(service, workspace: workspace) { service.detect() } #expect(try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["a"]?["features"] == .array([])) } @@ -206,14 +204,12 @@ struct PluginBuildOptionPersistenceTests { let runner = OptionCommandRecorder() let service = Self.service(source: source, workspace: workspace, store: store, runner: runner) defer { service.stop() } - let imported = try await Self.refreshed(service) { service.reset(workspaceURL: workspace) } - #expect(imported.mavenContext?.profiles == []) - #expect(imported.mavenContext?.settingsPath == "/fixture/a settings.xml") + try await Self.refreshed(service, workspace: workspace) { service.reset(workspaceURL: workspace) } #expect(service.entry("cargo:a")?.options.first { $0.id == "features" }?.scope == .instance) #expect(try await Self.run("cargo:a", service: service, runner: runner) == ["build", "--message-format=short", "--config", "/fixture/a settings.xml"]) #expect(try await Self.run("cargo:b", service: service, runner: runner) == ["build", "--message-format=short", "--features", "gui", "--config", "/fixture/b.xml", "--cache", "/fixture/cache b"]) let originalA = try store.instanceOptions(workspaceURL: workspace, buildSystemID: "cargo")["a"] - _ = try await Self.refreshed(service) { + try await Self.refreshed(service, workspace: workspace) { service.setInstanceOption("cargo:b", optionID: "features", value: .array([])) service.setInstanceOption("cargo:b", optionID: "settingsFile", value: .string("/fixture/changed b.xml")) } @@ -226,12 +222,12 @@ struct PluginBuildOptionPersistenceTests { let reopenedStore = MacBuildOptionsStore(store: backing) let reopened = Self.service(source: source, workspace: workspace, store: reopenedStore, runner: runner) defer { reopened.stop() } - _ = try await Self.refreshed(reopened) { reopened.reset(workspaceURL: workspace) } + try await Self.refreshed(reopened, workspace: workspace) { reopened.reset(workspaceURL: workspace) } #expect(reopened.entry("cargo:a")?.options.first { $0.id == "features" }?.value == .array([])) #expect(reopened.entry("cargo:a")?.options.first { $0.id == "label" }?.source == "user") #expect(reopened.entry("cargo:a")?.options.first { $0.id == "release" }?.source == "user") #expect(reopened.entry("cargo:b")?.options.first { $0.id == "features" }?.value == .array([])) - _ = try await Self.refreshed(reopened) { + try await Self.refreshed(reopened, workspace: workspace) { reopened.setInstanceOption("cargo:a", optionID: "features", value: nil) reopened.setOption("cargo:a", optionID: "settingsFile", value: nil) reopened.setOption("cargo:a", optionID: "offline", value: .bool(true)) @@ -252,7 +248,7 @@ struct PluginBuildOptionPersistenceTests { let store = MacBuildOptionsStore(store: OptionPreferenceStore()) let service = Self.service(source: source, workspace: workspace, store: store, runner: OptionCommandRecorder()) defer { service.stop() } - _ = try await Self.refreshed(service) { service.reset(workspaceURL: workspace) } + try await Self.refreshed(service, workspace: workspace) { service.reset(workspaceURL: workspace) } #expect(throws: (any Error).self) { try service.configureOption("cargo:a", optionID: "features", value: .bool(true)) } #expect(throws: (any Error).self) { try service.configureOption("cargo:a", optionID: "features", value: .array([.string("absent")])) } #expect(throws: (any Error).self) { try service.configureOption("cargo:a", optionID: "missing", value: .string("v")) } @@ -282,7 +278,7 @@ struct PluginBuildOptionPersistenceTests { let runner = OptionCommandRecorder() let service = Self.service(source: source, workspace: workspace, store: store, runner: runner) defer { service.stop() } - _ = try await Self.refreshed(service) { service.reset(workspaceURL: workspace) } + try await Self.refreshed(service, workspace: workspace) { service.reset(workspaceURL: workspace) } let a = try #require(service.entry("cargo:a")) let b = try #require(service.entry("cargo:b")) #expect(a.options.first { $0.id == "features" }?.value == .array([.string("cli")])) @@ -297,10 +293,9 @@ struct PluginBuildOptionPersistenceTests { #expect(fallback.options.first { $0.id == "features" }?.source == "default") #expect(fallback.options.first { $0.id == "features" }?.value == .array([.string("base")])) let previousFingerprint = a.sync?.fingerprint - let cleared = try await Self.refreshed(service) { + try await Self.refreshed(service, workspace: workspace) { service.setInstanceOption("cargo:a", optionID: "features", value: .array([])) } - #expect(cleared.mavenContext?.profiles == []) #expect(try store.options(workspaceURL: workspace, buildSystemID: "cargo")["features"] == .array([.string("gui")])) #expect(try store.emptyMultiSelectOptions(workspaceURL: workspace, buildSystemID: "cargo") == ["a": ["features"]]) #expect(service.entry("cargo:a")?.options.first { $0.id == "features" }?.source == "user") @@ -310,7 +305,7 @@ struct PluginBuildOptionPersistenceTests { #expect(try await Self.run("cargo:b", service: service, runner: runner) == ["build", "--message-format=short", "--features", "gui"]) // A sibling selecting a value also accepted by A must not undo A's clear. - _ = try await Self.refreshed(service) { + try await Self.refreshed(service, workspace: workspace) { service.setInstanceOption("cargo:b", optionID: "features", value: .array([.string("base")])) } #expect(try await Self.run("cargo:a", service: service, runner: runner) == ["build", "--message-format=short"]) @@ -320,25 +315,23 @@ struct PluginBuildOptionPersistenceTests { let reopenedStore = MacBuildOptionsStore(store: backing) let reopened = Self.service(source: source, workspace: workspace, store: reopenedStore, runner: runner) defer { reopened.stop() } - let imported = try await Self.refreshed(reopened) { reopened.reset(workspaceURL: workspace) } - #expect(imported.mavenContext?.profiles == []) + try await Self.refreshed(reopened, workspace: workspace) { reopened.reset(workspaceURL: workspace) } #expect(try await Self.run("cargo:a", service: reopened, runner: runner) == ["build", "--message-format=short"]) #expect(try await Self.run("cargo:b", service: reopened, runner: runner) == ["build", "--message-format=short", "--features", "base"]) - _ = try await Self.refreshed(reopened) { + try await Self.refreshed(reopened, workspace: workspace) { reopened.setInstanceOption("cargo:a", optionID: "features", value: .array([.string("cli")])) } #expect(try reopenedStore.emptyMultiSelectOptions(workspaceURL: workspace, buildSystemID: "cargo").isEmpty) #expect(try await Self.run("cargo:a", service: reopened, runner: runner) == ["build", "--message-format=short", "--features", "base,cli"]) - _ = try await Self.refreshed(reopened) { + try await Self.refreshed(reopened, workspace: workspace) { reopened.setInstanceOption("cargo:a", optionID: "features", value: .array([])) } - let reset = try await Self.refreshed(reopened) { + try await Self.refreshed(reopened, workspace: workspace) { reopened.setInstanceOption("cargo:a", optionID: "features", value: nil) } #expect(try reopenedStore.options(workspaceURL: workspace, buildSystemID: "cargo")["features"] == nil) #expect(try reopenedStore.emptyMultiSelectOptions(workspaceURL: workspace, buildSystemID: "cargo").isEmpty) - #expect(reset.mavenContext?.profiles == ["base"]) #expect(try await Self.run("cargo:a", service: reopened, runner: runner) == ["build", "--message-format=short", "--features", "base"]) } @@ -363,14 +356,10 @@ struct PluginBuildOptionPersistenceTests { } private static func refreshed( - _ service: BuildSystemService, action: () -> Void - ) async throws -> JavaLanguageImportConfiguration { - let published = TestGate() - service.onLanguageImportChanged = { _ in published.open() } - defer { service.onLanguageImportChanged = nil } + _ service: BuildSystemService, workspace: URL, action: () -> Void + ) async throws { action() - try #require(await published.waitUntilOpen(timeout: .seconds(5)), "Detection/import did not finish") - return try #require(service.languageImport) + try await service.awaitDetection(workspaceURL: workspace) } private static func run( @@ -412,10 +401,6 @@ struct PluginBuildOptionPersistenceTests { options[index]["default"] = ["base"] options[index]["allowCustom"] = allowCustom systems[0]["options"] = options - systems[0]["languageImport"] = ["kind": "maven", "options": ["profiles": "features"]] - if instanceScoped { - systems[0]["languageImport"] = ["kind": "maven", "options": ["profiles": "features", "settingsFile": "settingsFile"]] - } manifest["buildSystems"] = systems let descriptor = try DeclarativePluginTestSupport.operations.validate(manifest: JSONSerialization.data(withJSONObject: manifest)) return BuildSystemPluginSource( diff --git a/macos/Tests/LitheTests/PluginBundledPublisherTrustTests.swift b/macos/Tests/LitheTests/PluginBundledPublisherTrustTests.swift deleted file mode 100644 index af9c5070e9..0000000000 --- a/macos/Tests/LitheTests/PluginBundledPublisherTrustTests.swift +++ /dev/null @@ -1,378 +0,0 @@ -import CryptoKit -import Foundation -@testable import Lithe -import LitheCoreContracts -import LitheApplicationKernel -import LitheModuleAPI -import LithePluginPackageSigning -import Testing - -/// Runs production validation, signature verification and package storage. -/// No fixture process executes, and all files belong to this test's root. -@MainActor -struct PluginBundledPublisherTrustTests { - @Test(arguments: [true, false], ["direct", "marketplace", "disk"]) - func installingOverBundledCopyPreservesDefaultOrDisabledChoice(enabled: Bool, source: String) async throws { - let fixture = try Fixture() - defer { fixture.remove() } - let preferences = MigrationPreferences() - let configuration = MacModuleConfigurationStore(store: preferences) - let store = fixture.store() - let initial = try store.scanInstalledPlugins().packages - let moduleID = try #require(initial.first?.manifest.modules.first?.manifest.id) - if !enabled { configuration.setEnabledState(false, for: moduleID) } - let settings = InMemoryPluginSettings([OfficialPluginCatalog.javaPluginID.rawValue: ["saved": .string("retained")]]) - let manager = fixture.manager(store: store, configuration: configuration, packages: initial, settings: settings) - let original = try fixture.digest(of: fixture.bundled) - try fixture.sign(fixture.download) - - // All production entry points now share live-activation routing. Each - // must still migrate the sealed copy's choice only after validation. - let digest = try fixture.digest(of: fixture.download) - switch source { - case "marketplace": - try manager.installMarketplacePackage(at: fixture.download, origin: .marketplace, - provenance: PluginMarketplaceProvenance(sourceID: "official", sourceName: "Official", - repository: "https://github.com/example/java-support", archiveSHA256: String(repeating: "0", count: 64), - contentDigest: digest, approvedPrograms: [])) - case "disk": - // Signed disk imports retain publisher trust. The community-only - // installDiskPackage entry point must never accept this official ID. - let transport = PluginMarketplaceTestSupport.LocalFileTransport(files: [:]) - let service = MacPluginMarketplaceService( - evaluator: PluginMarketplaceTestSupport.evaluator, - packageStore: store, - downloader: MacPluginPackageDownloader(transport: transport, temporaryDirectory: fixture.root.appendingPathComponent("tmp")), - transport: transport, - applicationSupportDirectory: fixture.root.appendingPathComponent("support"), - cacheDirectory: fixture.root.appendingPathComponent("cache"), - bundledOfficialIndexURL: nil, - diskImporter: MacPluginDiskPackageImporter(temporaryDirectory: fixture.root.appendingPathComponent("tmp")), - allowsLocalDevelopmentPackages: false - ) - let marketplace = PluginMarketplaceFeatureModel(service: service, pluginManager: manager) - await marketplace.installFromDisk(at: fixture.download) - #expect(marketplace.diskInstallError == nil) - #expect(marketplace.pendingConfirmation == nil) - default: - try manager.installPackage(at: fixture.download) - } - - #expect(configuration.enabledState(for: moduleID) == enabled) - #expect(manager.snapshots.first?.isEnabled == enabled) - #expect(manager.snapshots.first?.requiresRestart == true) - #expect(settings.values(forPlugin: OfficialPluginCatalog.javaPluginID.rawValue)["saved"] == .string("retained")) - try store.prepareForLaunch() - let restarted = try store.scanInstalledPlugins() - #expect(restarted.packages.count == 1) - #expect(restarted.packages.first?.installation.origin == .marketplace) - #expect(restarted.packages.first?.installation.status == .installed) - #expect(try fixture.digest(of: fixture.bundled) == original) - } - - @Test - func migrationDoesNotEnableModulesThePreviousPackageDidNotOwn() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let store = fixture.store() - try store.setBundledPluginRemoved(OfficialPluginCatalog.javaPluginID, removed: true) - let configuration = MacModuleConfigurationStore(store: MigrationPreferences()) - let manager = fixture.manager(store: store, configuration: configuration, packages: try store.scanInstalledPlugins().packages) - var object = fixture.manifest - var languages = try #require(object["languages"] as? [[String: Any]]) - languages.append(["id": "future", "displayName": "Future", "fileExtensions": ["future"]]) - object["languages"] = languages - object["activationEvents"] = ["onLanguage:fixture", "onLanguage:future"] - var servers = try #require(object["languageServers"] as? [[String: Any]]) - var added = try #require(servers.first) - added["languageID"] = "future" - servers.append(added) - object["languageServers"] = servers - try JSONSerialization.data(withJSONObject: object).write(to: fixture.download.appendingPathComponent("plugin.json")) - try fixture.sign(fixture.download) - - try manager.installPackage(at: fixture.download) - - #expect(configuration.enabledState(for: .languageServerExtension("fixture")) == true) - #expect(configuration.enabledState(for: .languageServerExtension("future")) == nil) - } - - @Test - func directUpgradeWithoutBundledCopyKeepsDisabledPreferenceAndRemovedState() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let store = fixture.store(includeBundled: false) - try store.setBundledPluginRemoved(OfficialPluginCatalog.javaPluginID, removed: true) - try store.prepareForLaunch() - #expect(try store.scanInstalledPlugins().packages.isEmpty) - let configuration = MacModuleConfigurationStore(store: MigrationPreferences()) - let moduleID = try #require(DeclarativePluginTestSupport.operations.validate( - manifest: Data(contentsOf: fixture.download.appendingPathComponent("plugin.json")) - ).pluginManifest.modules.first?.manifest.id) - configuration.setEnabledState(false, for: moduleID) - let manager = fixture.manager(store: store, configuration: configuration, packages: []) - try fixture.sign(fixture.download) - try manager.installPackage(at: fixture.download) - // An explicit disk install is allowed, but does not turn a disabled - // module back on or let the old removal marker delete its state. - let state = fixture.stateDirectories.pluginDirectory(pluginID: OfficialPluginCatalog.javaPluginID.rawValue) - try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) - let saved = state.appendingPathComponent("saved.json") - try Data("user state".utf8).write(to: saved) - try store.prepareForLaunch() - #expect(configuration.enabledState(for: moduleID) == false) - #expect(try Data(contentsOf: saved) == Data("user state".utf8)) - #expect(try store.scanInstalledPlugins().packages.count == 1) - } - - @Test - func uninstallingInstalledUpdateDoesNotResurrectBundledJava() async throws { - let fixture = try Fixture() - defer { fixture.remove() } - let store = fixture.store() - try fixture.sign(fixture.download) - _ = try store.installPackage(from: fixture.download) - let configuration = MacModuleConfigurationStore(store: MigrationPreferences()) - let manager = fixture.manager(store: store, configuration: configuration, packages: try store.scanInstalledPlugins().packages) - try await manager.uninstall(OfficialPluginCatalog.javaPluginID) - try store.prepareForLaunch() - let packages = try store.scanInstalledPlugins().packages - #expect(packages.count == 1) - #expect(packages.first?.installation.origin == .bundled) - #expect(packages.first?.installation.status == .removed) - let restarted = fixture.manager(store: store, configuration: configuration, packages: packages) - #expect(restarted.snapshots.first?.installationStatus == .removed) - for file in ["Main.java", "pom.xml"] { - #expect(JavaPluginTransition.shouldSuggest(files: [fixture.root.appendingPathComponent(file)], - plugins: restarted.snapshots)) - } - } - - @Test - func failedInstallPreservesBundledEnablementAndImmutableResources() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let configuration = MacModuleConfigurationStore(store: MigrationPreferences()) - let store = fixture.store() - let packages = try store.scanInstalledPlugins().packages - let manager = fixture.manager(store: store, configuration: configuration, packages: packages) - let moduleID = try #require(packages.first?.manifest.modules.first?.manifest.id) - let before = try fixture.digest(of: fixture.bundled) - #expect(throws: (any Error).self) { try manager.installPackage(at: fixture.download) } - #expect(configuration.enabledState(for: moduleID) == nil) - #expect(manager.snapshots.first?.isEnabled == true) - #expect(manager.snapshots.first?.requiresRestart == false) - #expect(try fixture.digest(of: fixture.bundled) == before) - } - - @Test - func missingJavaIsSuggestedOnlyWhenNeededAndNoPackageExists() { - for name in ["Main.java", "pom.xml", "build.gradle", "build.gradle.kts"] { - let files = [URL(fileURLWithPath: "/fixture/\(name)")] - #expect(JavaPluginTransition.shouldSuggest(files: files, plugins: [])) - } - #expect(!JavaPluginTransition.shouldSuggest(files: [URL(fileURLWithPath: "/fixture/README.md")], plugins: [])) - } - - @Test(arguments: [PluginInstallationStatus.installed, .updateStaged, .uninstallPending, .removed], [false, true]) - func installationStateControlsTheJavaSuggestion(status: PluginInstallationStatus, enabled: Bool) throws { - let manifest = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport").pluginManifest - var snapshot = PluginManagementSnapshot(manifest: manifest, origin: .bundled, installationStatus: status, - isEnabled: enabled, isRequired: false, isRunning: false, isQuarantined: false, - isSuppressedBySafeMode: false, requiresRestart: status != .installed, canRollback: false, - statusMessage: "fixture", marketplace: nil) - for name in ["Main.java", "pom.xml", "build.gradle", "build.gradle.kts"] { - #expect(JavaPluginTransition.shouldSuggest(files: [URL(fileURLWithPath: "/fixture/\(name)")], - plugins: [snapshot]) == (status == .removed)) - } - #expect(!JavaPluginTransition.shouldSuggest(files: [URL(fileURLWithPath: "/fixture/README.md")], plugins: [snapshot])) - // A removed sealed copy can still be registered until this session - // restarts; only the next launch should offer to restore it. - snapshot.hasChangesPendingRestart = true - #expect(!JavaPluginTransition.shouldSuggest(files: [URL(fileURLWithPath: "/fixture/Main.java")], plugins: [snapshot])) - } - @Test - func hostSealedCopyAndSignedInstalledUpdateUseOnePluginIdentity() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let before = try fixture.digest(of: fixture.bundled) - let initial = try fixture.store().scanInstalledPlugins() - #expect(initial.issues.isEmpty) - #expect(initial.packages.map(\.installation.origin) == [.bundled]) - - try fixture.sign(fixture.download) - let installed = try fixture.store().installPackage(from: fixture.download) - let restarted = try fixture.store().scanInstalledPlugins() - #expect(restarted.issues.isEmpty) - #expect(restarted.packages.count == 1) - #expect(restarted.packages.first?.packageURL.resolvingSymlinksInPath() == installed.packageURL.resolvingSymlinksInPath()) - #expect(restarted.packages.first?.installation.origin == .marketplace) - #expect(try fixture.digest(of: fixture.bundled) == before) - #expect(try fixture.digest(of: installed.packageURL) == fixture.digest(of: fixture.download)) - } - - @Test - func unsignedOutsideCopyCannotClaimTheBundledTrustException() throws { - let fixture = try Fixture() - defer { fixture.remove() } - for origin: PluginInstallationOrigin in [.marketplace, .bundled, .localDevelopment] { - #expect(throws: (any Error).self) { - _ = try fixture.store().verifyCandidatePackage( - at: fixture.download, origin: origin, marketplace: nil - ) - } - } - #expect(try fixture.store().scanInstalledPlugins().packages.first?.installation.origin == .bundled) - } - - @Test - func presentInvalidSignatureIsRejectedEvenInsideTheHostSeal() throws { - let fixture = try Fixture() - defer { fixture.remove() } - try fixture.sign(fixture.bundled) - try Data("tampered".utf8).write(to: fixture.bundled.appendingPathComponent("server.jar")) - let scan = try fixture.store().scanInstalledPlugins() - #expect(scan.packages.isEmpty) - #expect(scan.issues.count == 1) - } - - @Test - func installedRuntimeTamperingCannotFallBackToHostSeal() throws { - let fixture = try Fixture() - defer { fixture.remove() } - try fixture.sign(fixture.download) - let installed = try fixture.store().installPackage(from: fixture.download) - try Data("tampered".utf8).write(to: installed.packageURL.appendingPathComponent("runtime/arm64/bin/java")) - let scan = try fixture.store().scanInstalledPlugins() - #expect(scan.issues.count == 1) - // The damaged update is isolated; the immutable bundled source remains. - #expect(scan.packages.map(\.installation.origin) == [.bundled]) - } - - @Test - func officialPackageCannotChangeItsPinnedBundledTrust() throws { - let fixture = try Fixture() - defer { fixture.remove() } - var manifest = fixture.manifest - var vendor = try #require(manifest["vendor"] as? [String: Any]) - vendor.removeValue(forKey: "bundledSignatureRequirement") - manifest["vendor"] = vendor - var requires = try #require(manifest["requires"] as? [String: Int]) - requires.removeValue(forKey: "packageTrust") - manifest["requires"] = requires - try JSONSerialization.data(withJSONObject: manifest).write(to: fixture.download.appendingPathComponent("plugin.json")) - try fixture.sign(fixture.download) - #expect(throws: PluginPackageStoreError.officialSignatureRequirementMismatch(OfficialPluginCatalog.javaPluginID)) { - _ = try fixture.store().installPackage(from: fixture.download) - } - } - - @Test - func signedPackageMissingTheHostArchitectureRuntimeIsRejected() throws { - let fixture = try Fixture() - defer { fixture.remove() } - let arch = MacPluginLanguageServerLaunchResolver.hostArchitecture - try FileManager.default.removeItem(at: fixture.download.appendingPathComponent("runtime/\(arch)/bin/java")) - try fixture.sign(fixture.download) - #expect(throws: (any Error).self) { - _ = try fixture.store().installPackage(from: fixture.download) - } - #expect(try fixture.store().scanInstalledPlugins().packages.map(\.installation.origin) == [.bundled]) - } - - private struct Fixture { - let root: URL - let host: URL - let bundled: URL - let download: URL - let manifest: [String: Any] - let privateKey: Curve25519.Signing.PrivateKey - - init() throws { - root = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-publisher-bundled-\(UUID().uuidString)") - host = root.appendingPathComponent("Lithe.app") - bundled = host.appendingPathComponent("Contents/Resources/OfficialPlugins/dev.lithe.plugin.java-support") - download = root.appendingPathComponent("download/dev.lithe.plugin.java-support") - privateKey = try Curve25519.Signing.PrivateKey(rawRepresentation: Data(repeating: 9, count: 32)) - let url = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("shared/contracts/plugins/v1/fixtures/package-trust/publisher-bundled.plugin.json") - var object = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) - object["id"] = OfficialPluginCatalog.javaPluginID.rawValue - manifest = object - do { - for package in [bundled, download] { - try DeclarativePluginTestSupport.writePackage(at: package, manifest: manifest) - for arch in ["arm64", "x86_64"] { - let java = package.appendingPathComponent("runtime/\(arch)/bin/java") - try FileManager.default.createDirectory(at: java.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data("fixture runtime".utf8).write(to: java) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: java.path) - } - try Data("fixture server".utf8).write(to: package.appendingPathComponent("server.jar")) - } - } catch { - try? FileManager.default.removeItem(at: root) - throw error - } - } - - var stateDirectories: MacPluginStateDirectories { MacPluginStateDirectories(rootURL: root.appendingPathComponent("state")) } - - func store(includeBundled: Bool = true) -> MacPluginPackageStore { - MacPluginPackageStore( - rootURL: root.appendingPathComponent("installed"), - bundledRootURL: includeBundled ? bundled.deletingLastPathComponent() : nil, - stateDirectories: stateDirectories, - validator: DeclarativePluginTestSupport.operations, - verifier: MacOfficialPluginSignatureVerifier( - trustedPublisherKeys: [PluginPackageSignature.keyID: privateKey.publicKey], - allowsLocalDevelopmentPackages: false, - hostBundleURL: host - ) - ) - } - - @MainActor - func manager( - store: MacPluginPackageStore, - configuration: MacModuleConfigurationStore, - packages: [InstalledPluginPackage], - settings: any PluginSettingsStoring = InMemoryPluginSettings() - ) -> MacPluginManager { - MacPluginManager( - packageStore: store, - moduleRuntime: ModuleRuntime(configurationStore: configuration, recoveryStore: configuration), - configurationStore: configuration, - settings: settings, - launchMode: .normal, - startup: MacPluginStartupResult(installedPlugins: packages, registeredPlugins: [], issues: []), - allowsLocalDevelopmentPackages: false - ) - } - - func sign(_ package: URL) throws { - let descriptor = try DeclarativePluginTestSupport.operations.validate(manifest: Data(contentsOf: package.appendingPathComponent("plugin.json"))) - let document = try PluginPackageSignature.makeDocument( - packageAt: package, - pluginID: descriptor.id.rawValue, - pluginVersion: descriptor.pluginManifest.version.description, - privateKey: privateKey - ) - try PluginPackageSignature.write(document, to: package) - } - - func digest(of package: URL) throws -> String { - try PluginPackageSignature.contentDigest(packageAt: package, fileManager: FileManager.default) - } - - func remove() { try? FileManager.default.removeItem(at: root) } - } -} - -private final class MigrationPreferences: KeyValueStore, @unchecked Sendable { - private var values: [String: Any] = [:] - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } -} diff --git a/macos/Tests/LitheTests/PluginDebugAdapterTests.swift b/macos/Tests/LitheTests/PluginDebugAdapterTests.swift index e149ffb08c..ba999275af 100644 --- a/macos/Tests/LitheTests/PluginDebugAdapterTests.swift +++ b/macos/Tests/LitheTests/PluginDebugAdapterTests.swift @@ -15,17 +15,29 @@ struct PluginDebugAdapterTests { @Test(arguments: ["unchanged", "disabled", "replaced", "generation"]) func providerConnectionUsesTheOwningRegistryEntryAndRevokesStaleBindings(change: String) throws { - let fixture = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("Plugins/mac/Official/JavaSupport/plugin.json") - let descriptor = try DeclarativePluginTestSupport.operations.validate(manifest: Data(contentsOf: fixture)) + // The contract fixture's `example` adapter, declared as an attach-only adapter for a connection target. + let fixture = DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/debug-adapters/debug-adapter.plugin.json") + var manifest = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: fixture)) as? [String: Any]) + var adapters = try #require(manifest["debugAdapters"] as? [[String: Any]]) + let adapterIndex = try #require(adapters.firstIndex { $0["id"] as? String == "example" }) + adapters[adapterIndex]["requests"] = ["attach"] + adapters[adapterIndex]["selectors"] = [["targetKinds": ["connection"], "languageIDs": ["example"]]] + adapters[adapterIndex]["configurations"] = [ + "attach": ["targetBindings": ["connection": ["host": "hostName", "port": "port"]]] + ] + manifest["debugAdapters"] = adapters + let descriptor = try DeclarativePluginTestSupport.operations.validate( + manifest: JSONSerialization.data(withJSONObject: manifest)) let package = InstalledPluginPackage(descriptor: descriptor, installation: PluginInstallationRecord( pluginID: descriptor.id, activeVersion: descriptor.pluginManifest.version, origin: .marketplace, status: .installed), - packageURL: URL(fileURLWithPath: "/fixture/java-support")) - let entry = try #require(PluginDebugAdapterEntry.qualifiedIndex(of: [package]).values.first) + packageURL: URL(fileURLWithPath: "/fixture/example-plugin")) + let entry = try #require(PluginDebugAdapterEntry.qualifiedIndex(of: [package]).values.first { $0.adapter.id == "example" }) var entries = [entry.providerID: entry] var generation = 7 let resolver = MacBuildConnectionDebugResolver(planner: DeclarativePluginTestSupport.operations, entries: { entries }, generation: { generation }) - let prepared = try resolver.prepare(configurationType: "java", preferredAdapterID: nil, port: 51235) + let prepared = try resolver.prepare(configurationType: "example", preferredAdapterID: nil, port: 51235) #expect(prepared.options.adapterID == entry.providerID) #expect(prepared.options.target.kind == "connection") #expect(prepared.configuration.adapterProviderID == entry.providerID) @@ -40,9 +52,9 @@ struct PluginDebugAdapterTests { entries[entry.providerID] = PluginDebugAdapterEntry(plugin: replacement, adapter: entry.adapter) } #expect(prepared.isCurrent() == (change == "unchanged")) - // Explicit old language IDs and a missing alias never select built-in adapters. + // An unqualified adapter ID and a missing alias never select an adapter. #expect(throws: DebugLaunchConfigurationResolutionError.providerDebugUnavailable) { - try resolver.prepare(configurationType: "java", preferredAdapterID: "java", port: 51235) + try resolver.prepare(configurationType: "example", preferredAdapterID: "example", port: 51235) } #expect(throws: DebugLaunchConfigurationResolutionError.providerDebugUnavailable) { try resolver.prepare(configurationType: "missing", preferredAdapterID: nil, port: 51235) @@ -50,9 +62,9 @@ struct PluginDebugAdapterTests { entries["another/adapter"] = entry if change == "unchanged" { #expect(throws: DebugLaunchConfigurationResolutionError.providerDebugUnavailable) { - try resolver.prepare(configurationType: "java", preferredAdapterID: nil, port: 51235) + try resolver.prepare(configurationType: "example", preferredAdapterID: nil, port: 51235) } - #expect(try resolver.prepare(configurationType: "java", preferredAdapterID: entry.providerID, port: 51235).isCurrent()) + #expect(try resolver.prepare(configurationType: "example", preferredAdapterID: entry.providerID, port: 51235).isCurrent()) } } @@ -427,8 +439,7 @@ struct PluginDebugAdapterTests { } ) let configuration = try resolver.resolve( - provider: provider, documentURL: document, workspaceURL: root, - configurations: [], selectedConfiguration: nil, javaTarget: nil, options: { _ in RunOptions() } + provider: provider, documentURL: document, workspaceURL: root ) #expect(asked == ["zig"]) #expect(configuration.name == "main.zig") @@ -436,8 +447,7 @@ struct PluginDebugAdapterTests { let without = DebugLaunchConfigurationResolver() #expect(throws: DebugLaunchConfigurationResolutionError.self) { try without.resolve( - provider: provider, documentURL: document, workspaceURL: root, - configurations: [], selectedConfiguration: nil, javaTarget: nil, options: { _ in RunOptions() } + provider: provider, documentURL: document, workspaceURL: root ) } } diff --git a/macos/Tests/LitheTests/PluginDetailLayoutTests.swift b/macos/Tests/LitheTests/PluginDetailLayoutTests.swift index 245d8d297e..ab5e39ac8d 100644 --- a/macos/Tests/LitheTests/PluginDetailLayoutTests.swift +++ b/macos/Tests/LitheTests/PluginDetailLayoutTests.swift @@ -11,9 +11,32 @@ import Testing struct PluginDetailLayoutTests { @Test(arguments: [false, true]) func settingsStayBesideTheDividerWhenTheWindowShrinks(dark: Bool) throws { - let descriptor = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") + // A language-server plugin form with one number field and one choice, + // the shape most plugin settings pages take. + var manifest = DeclarativePluginTestSupport.manifestObject(version: PluginVersion(major: 1, minor: 0, patch: 0)) + manifest["pluginAPIVersion"] = 3 + manifest["requires"] = ["languages": 1, "languageServers": 1, "serverProcess": 1, "settings": 2] + manifest["settings"] = [ + [ + "id": "heapMaxMB", "type": "integer", "title": "Maximum memory", + "description": "Upper bound of the language server's heap. Raise it for large projects.", + "default": 2048, "minimum": 2048, "maximum": 16384, "unit": "MB", + "page": ["languageID": "fixture"], "section": "Language server" + ], + [ + "id": "logLevel", "type": "enum", "title": "Language server log level", + "description": "How much the language server writes to its own log.", + "default": "WARNING", + "options": [ + ["value": "ALL", "title": "All messages"], ["value": "INFO", "title": "Information"], + ["value": "WARNING", "title": "Warnings"], ["value": "SEVERE", "title": "Errors only"] + ], + "page": ["languageID": "fixture"], "section": "Language server" + ] + ] + let descriptor = try DeclarativePluginTestSupport.descriptor(manifest) var plugin = PluginManagementSnapshot( - manifest: descriptor.pluginManifest, origin: .bundled, installationStatus: .installed, + manifest: descriptor.pluginManifest, origin: .community, installationStatus: .installed, isEnabled: true, isRequired: false, isRunning: false, isQuarantined: false, isSuppressedBySafeMode: false, requiresRestart: false, canRollback: false, statusMessage: "Enabled", marketplace: nil diff --git a/macos/Tests/LitheTests/PluginEditorActionLaunchTests.swift b/macos/Tests/LitheTests/PluginEditorActionLaunchTests.swift new file mode 100644 index 0000000000..4e639c99c2 --- /dev/null +++ b/macos/Tests/LitheTests/PluginEditorActionLaunchTests.swift @@ -0,0 +1,151 @@ +import Foundation +import LitheCoreContracts +import LitheModuleAPI +import Testing +@testable import Lithe + +/// Toolbar Run/Debug for plugin-owned languages picks one of the plugin's +/// editor actions; these tests pin the choice and the routing guard. +@Suite("Plugin editor action launch") +@MainActor +struct PluginEditorActionLaunchTests { + private let registration = PluginEditorActionRegistration( + lease: UUID(), pluginID: "io.example.lang", sessionID: "s1", + context: PluginWorkspaceContextReference(contextID: "w1", generation: 1), + id: "actions", functionID: "lang.collect", fileExtensions: ["lang"], fileNames: [] + ) + + private func action(_ id: String, line: Int, column: Int = 1, icon: String, + alternatives: [(id: String, icon: String)] = []) throws -> PluginEditorActionItem { + let alternatives = alternatives.map { + """ + {"id":"\($0.id)","title":"\($0.id)","icon":"\($0.icon)","invoke":{"functionID":"lang.\($0.id)","params":{"alt":"\($0.id)"}}} + """ + }.joined(separator: ",") + let json = """ + {"id":"\(id)","range":{"start":{"line":\(line),"column":\(column)},"end":{"line":\(line),"column":\(column + 1)}}, + "title":"\(id)","icon":"\(icon)","invoke":{"functionID":"lang.\(id)","params":{"main":"\(id)"}}, + "alternatives":[\(alternatives)]} + """ + let decoded = try JSONDecoder().decode(PluginEditorAction.self, from: Data(json.utf8)) + return PluginEditorActionItem(registration: registration, action: decoded) + } + + @Test("Run picks the first run-icon action by document position") + func runPicksFirstRunActionByPosition() throws { + let items = [ + try action("later", line: 20, icon: "run"), + try action("test", line: 3, icon: "test"), + try action("sameLine", line: 5, column: 9, icon: "run-all"), + try action("first", line: 5, column: 2, icon: "run"), + ] + let choice = try #require(PluginEditorActionLaunchSelection.choose(items, intent: .run)) + #expect(choice.item.action.id == "first") + #expect(choice.invocation.functionID == "lang.first") + #expect(choice.alternativeID == nil) + } + + @Test("Debug prefers the run action's debug alternative") + func debugPrefersAlternativeOfRunAction() throws { + let items = [ + try action("debugOnly", line: 9, icon: "debug"), + try action("main", line: 4, icon: "run", alternatives: [(id: "dbg", icon: "debug"), (id: "cov", icon: "test")]), + ] + let choice = try #require(PluginEditorActionLaunchSelection.choose(items, intent: .debug)) + #expect(choice.item.action.id == "main") + #expect(choice.alternativeID == "dbg") + #expect(choice.invocation.functionID == "lang.dbg") + #expect(choice.invocation.params == .object(["alt": .string("dbg")])) + } + + @Test("Debug falls back to an action whose own icon is debug") + func debugFallsBackToDebugIconAction() throws { + let items = [ + try action("main", line: 2, icon: "run", alternatives: [(id: "cov", icon: "test")]), + try action("attach", line: 8, icon: "debug"), + ] + let choice = try #require(PluginEditorActionLaunchSelection.choose(items, intent: .debug)) + #expect(choice.item.action.id == "attach") + #expect(choice.alternativeID == nil) + } + + @Test("No matching icon yields no choice") + func noMatchingIconYieldsNil() throws { + let items = [try action("test", line: 1, icon: "test"), try action("nav", line: 2, icon: "navigate-super")] + #expect(PluginEditorActionLaunchSelection.choose(items, intent: .run) == nil) + #expect(PluginEditorActionLaunchSelection.choose(items, intent: .debug) == nil) + #expect(PluginEditorActionLaunchSelection.choose([], intent: .run) == nil) + } + + private func support( + execution: Bool = false, debug: Bool = false, testing: Bool = false, + hostCapabilities: Set = [] + ) -> LanguageSupportDeclaration { + LanguageSupportDeclaration( + id: "lang", displayName: "Lang", fileExtensions: ["lang"], projectFileNames: [], + languageServerModuleID: .languageServerExtension("lang"), + executionModuleID: execution ? .languageExecutionExtension("lang") : nil, + testingModuleID: testing ? .languageExecutionExtension("lang") : nil, + debugModuleID: debug ? .debugAdaptersExtension("io.example.lang") : nil, + hostCapabilities: hostCapabilities + ) + } + + private let currentFile = RunConfiguration(id: RunConfiguration.currentFileID, name: "Current File", kind: .currentFile) + private let fileURL = URL(fileURLWithPath: "/workspace/Main.lang") + + @Test("Routing applies only to current-file configurations with a module-less language") + func routingRequiresCurrentFileAndMissingModule() { + let coordinator = makeRunWorkflowCoordinator() + let plain = support() + let routed = coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in plain }, hostLaunchesFiles: { _ in true }) + #expect(routed?.id == "lang") + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in plain }, hostLaunchesFiles: { _ in true })?.id == "lang") + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: nil, languageSupportForFile: { _ in plain }, hostLaunchesFiles: { _ in true }) == nil) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in nil }, hostLaunchesFiles: { _ in true }) == nil) + + let named = RunConfiguration(id: "named", name: "Named", kind: .process(provider: "fixture.main")) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: named, currentFileURL: fileURL, languageSupportForFile: { _ in plain }, hostLaunchesFiles: { _ in true }) == nil) + } + + @Test("Languages with their own module or host capability keep the module path") + func routingSkipsLanguagesWithModulesOrHostCapabilities() { + let coordinator = makeRunWorkflowCoordinator() + let withExecution = support(execution: true) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withExecution }, hostLaunchesFiles: { _ in true }) == nil) + // Debug is still routed when only the execution module exists. + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withExecution }, hostLaunchesFiles: { _ in true })?.id == "lang") + + let withDebugger = support(debug: true) + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withDebugger }, hostLaunchesFiles: { _ in true }) == nil) + // An adapter that only attaches leaves the Debug button nothing to launch. + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withDebugger }, hostLaunchesFiles: { _ in false })?.id == "lang") + let named = RunConfiguration(id: "named", name: "Named", kind: .process(provider: "fixture.main")) + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: named, currentFileURL: fileURL, languageSupportForFile: { _ in withDebugger }, hostLaunchesFiles: { _ in false }) == nil) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withDebugger }, hostLaunchesFiles: { _ in true })?.id == "lang") + + let hostRun = support(hostCapabilities: [.run]) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in hostRun }, hostLaunchesFiles: { _ in true }) == nil) + #expect(coordinator.languageSupportRoutingToEditorActions(.debug, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in hostRun }, hostLaunchesFiles: { _ in true })?.id == "lang") + + let withTesting = support(testing: true) + #expect(coordinator.languageSupportRoutingToEditorActions(.testing, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in withTesting }, hostLaunchesFiles: { _ in true }) == nil) + } + + @Test("Debug-only and editor-only declarations are never routed") + func routingSkipsDebugOnlyAndEditorOnly() { + let coordinator = makeRunWorkflowCoordinator() + let debugOnly = LanguageSupportDeclaration( + id: "lang", displayName: "Lang", fileExtensions: ["lang"], + debugModuleID: .debugAdaptersExtension("io.example.debugger") + ) + #expect(debugOnly.isDebugOnly) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in debugOnly }, hostLaunchesFiles: { _ in true }) == nil) + let editorOnly = LanguageSupportDeclaration( + id: "lang", displayName: "Lang", fileExtensions: ["lang"], + editorModuleID: .grammarsExtension("io.example.grammar") + ) + #expect(editorOnly.isEditorOnly) + #expect(coordinator.languageSupportRoutingToEditorActions(.run, for: currentFile, currentFileURL: fileURL, languageSupportForFile: { _ in editorOnly }, hostLaunchesFiles: { _ in true }) == nil) + } +} diff --git a/macos/Tests/LitheTests/PluginInstallationGuidancePresentationTests.swift b/macos/Tests/LitheTests/PluginInstallationGuidancePresentationTests.swift deleted file mode 100644 index 57b0784c87..0000000000 --- a/macos/Tests/LitheTests/PluginInstallationGuidancePresentationTests.swift +++ /dev/null @@ -1,131 +0,0 @@ -import AppKit -import Foundation -import SwiftUI -import Testing -import LitheCoreContracts -import LitheModuleAPI -@testable import Lithe - -@MainActor -@Suite("Java installation guidance presentation", .serialized) -struct PluginInstallationGuidancePresentationTests { - @Test(arguments: [false, true]) - func missingJavaNotificationOffersAnExplicitMarketplaceAction(dark: Bool) async throws { - let language = InterfaceLanguage.locale.identifier - InterfaceLanguage.select("en") - defer { InterfaceLanguage.select(language) } - let feature = WorkbenchNotificationFeatureModel() - feature.setApplicationActive(false) - defer { feature.clear() } - var searches: [String] = [] - feature.show("Java Support is installed separately. Install it from the Marketplace, or use Install from Disk for an offline package. Your Java settings are kept.", - arguments: [], action: WorkbenchNotification.Action(id: "plugins.marketplace.open", title: "Open Marketplace") { searches.append("Java Support") }) - let notification = try #require(feature.activeNotifications.first) - let view = WorkbenchNotificationBanner(message: notification.message, occurrenceCount: 1, - actionTitle: notification.action?.title, performAction: { feature.perform(notification.id) }, - dismiss: { feature.dismiss(notification.id) }) - .padding(20).frame(width: 400, height: 260, alignment: .top) - .background(LitheTheme.editor) - try await withHost(AnyView(view), size: NSSize(width: 400, height: 260), dark: dark) { host in - let expand = try #require(await button("Expand notification", in: host)) - try #require(expand.accessibilityPerformPress?() == true) - try #require(await button("Collapse notification", in: host) != nil) - let action = try #require(await button("Open Marketplace", in: host)) - try capture(host, name: "java-missing-notification-" + (dark ? "dark" : "light")) - #expect(searches.isEmpty) - #expect(action.accessibilityPerformPress?() == true) - #expect(searches == ["Java Support"]) - #expect(feature.activeNotifications.isEmpty) - } - } - - @Test(arguments: [false, true]) - func newProjectOffersJavaMavenAndSpringTemplatesWhenJavaIsMissing(dark: Bool) async throws { - let language = InterfaceLanguage.locale.identifier - InterfaceLanguage.select("en") - defer { InterfaceLanguage.select(language) } - let suite = "java-template-presentation-" + UUID().uuidString - let defaults = try #require(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let planner = RustProjectGeneratorOperations(core: RustCoreBridge()) - let service = ProjectGenerationService(planner: planner, - platform: MacProjectGenerationPlatform(environment: { $0 }, executable: { _ in nil }, runner: GuidanceCommandRunner()), - initializeGitRepository: { _ in nil }, recordJavaHome: { _, _ in }) - var searches: [String] = [] - let feature = NewProjectFeatureModel(environment: NewProjectEnvironment( - sources: { [] }, iconResources: [:], javaRuntimes: { [] }, service: service, - setPluginEnabled: { _ in Issue.record("A marketplace action must not enable a plugin") }, - openMarketplace: { searches.append($0) }, openProject: { _ in Issue.record("No project should be created") }, - store: MacUserDefaultsStore(defaults: defaults))) - defer { feature.cancelCreation() } - feature.location = "/fixture/projects" - feature.reloadCatalog() - #expect(feature.isJavaSupportMissing) - try await withHost(AnyView(NewProjectView(feature: feature).defaultAppStorage(defaults)), - size: NSSize(width: 880, height: 660), dark: dark) { host in - let action = try #require(await button("Install Java Support for Java, Maven and Spring templates…", in: host)) - try capture(host, name: "java-new-project-" + (dark ? "dark" : "light")) - #expect(searches.isEmpty) - #expect(action.accessibilityPerformPress?() == true) - #expect(searches == ["Java Support"]) - #expect(!feature.isCreating) - } - } - - private func withHost(_ view: AnyView, size: NSSize, dark: Bool, - body: (NSView) async throws -> Void) async throws { - let application = NSApplication.shared - let attribute = NSAccessibility.Attribute(rawValue: "AXEnhancedUserInterface") - let previous = (application.accessibilityAttributeValue(attribute) as? Bool) ?? false - application.accessibilitySetValue(true, forAttribute: attribute) - defer { application.accessibilitySetValue(previous, forAttribute: attribute) } - MacBundledFontRegistry.registerFonts() - let host = NSHostingView(rootView: view.environment(\.locale, Locale(identifier: "en")) - .environment(\.colorScheme, dark ? .dark : .light)) - let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), - styleMask: [.borderless], backing: .buffered, defer: false) - window.isReleasedWhenClosed = false - window.appearance = NSAppearance(named: dark ? .darkAqua : .aqua) - window.contentView = host - window.orderFront(nil) - defer { window.contentView = nil; window.close() } - try await body(host) - } - - private func buttons(in value: Any) -> [AnyObject] { - let item = value as AnyObject - return (item.accessibilityRole?() == .button ? [item] : []) - + (item.accessibilityChildren?() ?? []).flatMap { buttons(in: $0) } - } - - private func button(_ title: String, in host: NSView) async -> AnyObject? { - let clock = ContinuousClock(), deadline = clock.now.advanced(by: .seconds(2)) - repeat { - host.layoutSubtreeIfNeeded() - if let result = buttons(in: host).first(where: { ($0.accessibilityLabel?() ?? $0.accessibilityTitle?()) == title }) { - return result - } - await Task.yield() - } while clock.now < deadline - return nil - } - - private func capture(_ host: NSView, name: String) throws { - host.layoutSubtreeIfNeeded() - let bitmap = try nativeSRGBCapture(host) - #expect(bitmap.pixelsWide == Int(host.bounds.width * 2)) - #expect(bitmap.pixelsHigh == Int(host.bounds.height * 2)) - if let directory = ProcessInfo.processInfo.environment["LITHE_JAVA_GUIDANCE_CAPTURE_DIR"] { - try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true) - try #require(bitmap.representation(using: .png, properties: [:])).write(to: - URL(fileURLWithPath: directory).appendingPathComponent(name + ".png")) - } - } -} - -private struct GuidanceCommandRunner: BuildCommandRunning { - func run(_ request: BuildCommandRequest, onOutput: @escaping @Sendable (String) -> Void) async throws -> BuildCommandResult { - Issue.record("Installation guidance must not execute a tool") - throw CancellationError() - } -} diff --git a/macos/Tests/LitheTests/PluginLanguageServerLaunchResolverTests.swift b/macos/Tests/LitheTests/PluginLanguageServerLaunchResolverTests.swift index cce31743de..5817756449 100644 --- a/macos/Tests/LitheTests/PluginLanguageServerLaunchResolverTests.swift +++ b/macos/Tests/LitheTests/PluginLanguageServerLaunchResolverTests.swift @@ -10,17 +10,18 @@ import Testing struct PluginLanguageServerLaunchResolverTests { @Test func apiLevelTwoDescriptorStartsTheRuntimeAndExpandsTemplates() throws { - let descriptor = try DeclarativePluginTestSupport.operations.validate(manifest: javaFixtureManifest()) + let descriptor = try DeclarativePluginTestSupport.operations.validate( + manifest: fixtureManifest("node-runtime.plugin.json") + ) let server = try #require(descriptor.languageServers.first) #expect(server.launch == .runtime( - tool: "java", - entryRelativePath: "language-server/plugins/org.eclipse.equinox.launcher.jar", - packagedRuntime: "runtime/${arch}/bin/java" + tool: "node", + entryRelativePath: "language-server/lib/server.js", + packagedRuntime: nil )) - #expect(server.hostIntegrationID == "jdt") // The runtime is the process the host discovers and starts. - #expect(server.executableNames == ["java"]) + #expect(server.executableNames == ["node"]) #expect(server.expandsLaunchTemplates) #expect(server.packagedRelativePath == nil) } @@ -132,56 +133,6 @@ struct PluginLanguageServerLaunchResolverTests { await writer.finishSession() } - /// The Java plugin's JDT LS files reach the shared JDT launch only through - /// what the plugin declares; nothing is looked up in the app or on the Mac. - @Test - func theJdtIntegrationReceivesExactlyTheDeclaredPackageFiles() throws { - let root = temporaryRoot() - defer { try? FileManager.default.removeItem(at: root) } - let fixture = try makeFixture(root: root) - let package = fixture.source.packageURL - let architecture = MacPluginLanguageServerLaunchResolver.hostArchitecture - - let integration = try #require(try fixture.resolver.hostIntegration(for: fixture.source)) - let resources = try MacJdtLaunchResources().resources(from: integration, javaRuntimes: []) - - #expect(integration.id == MacJdtHostIntegration.integrationID) - #expect(resources.launcherJarURL == package.appendingPathComponent( - "language-server/plugins/org.eclipse.equinox.launcher.jar" - )) - // The packaged directory itself: Rust Core makes the writable copy. - #expect(resources.configurationDirectoryURL.path - == package.appendingPathComponent("language-server/configuration/\(architecture)").path) - #expect(resources.lombokAgentURL == package.appendingPathComponent("language-server/lombok/lombok.jar")) - // Declared directory order first, then file name; non-JAR files are ignored. - #expect(resources.javaExtensionBundleURLs.map(\.lastPathComponent) == [ - "com.microsoft.java.debug.plugin.jar", "a-extension.jar", "b-extension.jar" - ]) - #expect(resources.javaTestRunnerURL == package.appendingPathComponent( - "language-server/java-test/runner/runner.jar" - )) - // Locating the files must not create plugin state. - #expect(!FileManager.default.fileExists(atPath: fixture.directories.rootURL.path)) - } - - @Test - func theGenericLaunchOfTheJavaPluginStartsItsEntryWithoutStateDirectories() throws { - let root = temporaryRoot() - defer { try? FileManager.default.removeItem(at: root) } - let fixture = try makeFixture(root: root) - - let resolved = try fixture.resolver.resolve(fixture.source, workspaceRootURL: fixture.workspaceURL) - - #expect(resolved.arguments == [ - "-Dfile.encoding=UTF-8", - "-jar", - fixture.source.packageURL.appendingPathComponent( - "language-server/plugins/org.eclipse.equinox.launcher.jar" - ).path - ]) - #expect(!FileManager.default.fileExists(atPath: fixture.directories.rootURL.path)) - } - /// What the user stored for a setting reaches the server command line, and /// a boolean setting stays a boolean in the initialization options. @Test @@ -242,12 +193,12 @@ struct PluginLanguageServerLaunchResolverTests { let directories = MacPluginStateDirectories(rootURL: temporaryRoot()) let first = directories.workspaceStateDirectory( pluginID: "dev.example.plugin", - languageID: "java", + languageID: "fixture", workspaceRootURL: URL(fileURLWithPath: "/projects/one") ) let second = directories.workspaceStateDirectory( pluginID: "dev.example.plugin", - languageID: "java", + languageID: "fixture", workspaceRootURL: URL(fileURLWithPath: "/projects/two") ) @@ -261,11 +212,11 @@ struct PluginLanguageServerLaunchResolverTests { defer { try? FileManager.default.removeItem(at: root) } let fixture = try makeFixture(root: root) try FileManager.default.removeItem( - at: fixture.source.packageURL.appendingPathComponent("language-server/lombok/lombok.jar") + at: fixture.source.packageURL.appendingPathComponent("language-server/lib/server.js") ) #expect(throws: MacPluginLanguageServerLaunchResolver.ResolutionError.missingPackagePath( - "language-server/lombok/lombok.jar" + "language-server/lib/server.js" )) { try fixture.resolver.resolve(fixture.source, workspaceRootURL: fixture.workspaceURL) } @@ -279,23 +230,23 @@ struct PluginLanguageServerLaunchResolverTests { let root = temporaryRoot() defer { try? FileManager.default.removeItem(at: root) } let fixture = try makeFixture(root: root) - let lombok = fixture.source.packageURL.appendingPathComponent("language-server/lombok/lombok.jar") - let outside = root.appendingPathComponent("outside.jar") + let entry = fixture.source.packageURL.appendingPathComponent("language-server/lib/server.js") + let outside = root.appendingPathComponent("outside.js") try Data("outside".utf8).write(to: outside) - try FileManager.default.removeItem(at: lombok) - try FileManager.default.createSymbolicLink(at: lombok, withDestinationURL: outside) + try FileManager.default.removeItem(at: entry) + try FileManager.default.createSymbolicLink(at: entry, withDestinationURL: outside) #expect(throws: MacPluginLanguageServerLaunchResolver.ResolutionError.packagePathOutsidePackage( - "language-server/lombok/lombok.jar" + "language-server/lib/server.js" )) { try fixture.resolver.resolve(fixture.source, workspaceRootURL: fixture.workspaceURL) } } - /// The plugin ships its own runtime, so the host is told where it is - /// inside the package instead of looking for `java` on the machine. + /// A runtime the plugin does not ship is discovered on the machine, so the + /// probe carries its version requirement and no location inside the package. @Test - func theRuntimeShippedByThePluginIsPinnedInsideItsPackage() throws { + func aDiscoveredRuntimeIsProbedForItsVersionWithoutAPackagedLocation() throws { let root = temporaryRoot() defer { try? FileManager.default.removeItem(at: root) } let fixture = try makeFixture(root: root) @@ -303,34 +254,33 @@ struct PluginLanguageServerLaunchResolverTests { let probe = try fixture.resolver.executableProbe(for: fixture.source) #expect(probe.validationArguments.isEmpty) - #expect(probe.versionRequirement == nil) - #expect(probe.packagedRuntimeURL == fixture.source.packageURL.appendingPathComponent( - "runtime/\(MacPluginLanguageServerLaunchResolver.hostArchitecture)/bin/java" - ).standardizedFileURL) + #expect(probe.versionRequirement?.tool == "node") + #expect(probe.versionRequirement?.minimumVersion == "18.17") + #expect(probe.packagedRuntimeURL == nil) // Expanding the probe needs no workspace and must not create state. #expect(!FileManager.default.fileExists(atPath: fixture.directories.rootURL.path)) } - /// A JDK older than the plugin requires must not be offered, even when it - /// is first on PATH; the first runtime that qualifies is used. + /// A runtime older than the plugin requires must not be offered, even when + /// it is first on PATH; the first runtime that qualifies is used. @MainActor @Test func runtimeCandidatesBelowTheMinimumVersionAreNotUsed() async { - let old = URL(fileURLWithPath: "/jdks/17/bin/java") - let stub = URL(fileURLWithPath: "/usr/bin/java") - let current = URL(fileURLWithPath: "/jdks/21/bin/java") + let old = URL(fileURLWithPath: "/runtimes/16/bin/node") + let stub = URL(fileURLWithPath: "/usr/bin/node") + let current = URL(fileURLWithPath: "/runtimes/20/bin/node") let runner = VersionProbeRunner(outputs: [ - old.path: (0, "openjdk 17.0.11 2024-04-16"), - stub.path: (1, "Unable to locate a Java Runtime."), - current.path: (0, "openjdk 21.0.12 2026-07-15 LTS") + old.path: (0, "v16.20.2"), + stub.path: (1, "node: command not found"), + current.path: (0, "v20.11.0") ]) let service = LanguageServerToolService( - runtimeService: FixedLanguageToolRuntime(candidates: ["java": [old, stub, current]]), + runtimeService: FixedLanguageToolRuntime(candidates: ["node": [old, stub, current]]), commandRunner: runner, settingsStore: MemoryLanguageToolSettings(), versionChecker: DeclarativePluginTestSupport.operations ) - let descriptor = javaRuntimeDescriptor() + let descriptor = discoveredRuntimeDescriptor() // Nothing is offered before the probe ran. #expect(service.candidates(for: descriptor).isEmpty) @@ -347,19 +297,19 @@ struct PluginLanguageServerLaunchResolverTests { @MainActor @Test func aCustomRuntimeBelowTheMinimumVersionIsRejectedWithTheReason() async { - let old = URL(fileURLWithPath: "/jdks/17/bin/java") + let old = URL(fileURLWithPath: "/runtimes/16/bin/node") let service = LanguageServerToolService( runtimeService: FixedLanguageToolRuntime(candidates: [:]), - commandRunner: VersionProbeRunner(outputs: [old.path: (0, "openjdk 17.0.11 2024-04-16")]), + commandRunner: VersionProbeRunner(outputs: [old.path: (0, "v16.20.2")]), settingsStore: MemoryLanguageToolSettings(), versionChecker: DeclarativePluginTestSupport.operations ) await #expect(throws: LanguageServerToolConfigurationError.executableValidationFailed( path: old.path, - message: "java 17.0.11 is older than the required 21." + message: "node 16.20.2 is older than the required 18.17." )) { - try await service.setCustomExecutablePath(old.path, for: javaRuntimeDescriptor()) + try await service.setCustomExecutablePath(old.path, for: discoveredRuntimeDescriptor()) } } @@ -418,7 +368,7 @@ struct PluginLanguageServerLaunchResolverTests { session.onStateChange = { states.append($0) } #expect(throws: LanguageServerSessionStartError.self) { - try session.start(rootURL: URL(fileURLWithPath: "/projects/one"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/projects/one")) } #expect(!session.isRunning) guard case .failed(let failure)? = states.last else { @@ -458,7 +408,7 @@ struct PluginLanguageServerLaunchResolverTests { )) #expect(throws: LanguageServerSessionStartError.self) { - try session.start(rootURL: URL(fileURLWithPath: "/projects/one"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/projects/one")) } session.stop() @@ -492,7 +442,7 @@ struct PluginLanguageServerLaunchResolverTests { #expect(await session.stopAndWait()) #expect(throws: LanguageServerSessionStartError.self) { - try session.start(rootURL: URL(fileURLWithPath: "/projects/one"), workspaceFingerprint: nil) + try session.start(rootURL: URL(fileURLWithPath: "/projects/one")) } #expect(operations.observations.isEmpty) @@ -568,38 +518,26 @@ struct PluginLanguageServerLaunchResolverTests { let workspaceURL: URL } - /// Files each fixture manifest points at. A trailing `/` marks a directory. - private func declaredFiles(_ manifest: String) -> [String] { + /// Files the fixture manifest points at. A trailing `/` marks a directory. + private func declaredFiles() -> [String] { let architecture = MacPluginLanguageServerLaunchResolver.hostArchitecture - return manifest == "node-runtime.plugin.json" - ? [ - "language-server/lib/server.js", - "language-server/lib/preload.js", - "language-server/stubs/\(architecture)/" - ] - : [ - "language-server/lombok/lombok.jar", - "language-server/plugins/org.eclipse.equinox.launcher.jar", - "language-server/configuration/\(architecture)/config.ini", - "language-server/java-debug/com.microsoft.java.debug.plugin.jar", - "language-server/java-debug/LICENSE.txt", - "language-server/java-test/extensions/b-extension.jar", - "language-server/java-test/extensions/a-extension.jar", - "language-server/java-test/runner/runner.jar", - "runtime/\(architecture)/bin/java" - ] + return [ + "language-server/lib/server.js", + "language-server/lib/preload.js", + "language-server/stubs/\(architecture)/" + ] } private func makeFixture( root: URL, - manifest: String = "language-host-integration.plugin.json", - languageID: String = "java", + manifest: String = "node-runtime.plugin.json", + languageID: String = "fixture", settings: any PluginSettingsStoring = InMemoryPluginSettings() ) throws -> Fixture { let operations = DeclarativePluginTestSupport.operations let descriptor = try operations.validate(manifest: fixtureManifest(manifest)) let packageURL = root.appendingPathComponent("package", isDirectory: true) - for relativePath in declaredFiles(manifest) { + for relativePath in declaredFiles() { let url = packageURL.appendingPathComponent(relativePath) if relativePath.hasSuffix("/") { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) @@ -629,28 +567,24 @@ struct PluginLanguageServerLaunchResolverTests { ) } - private func javaRuntimeDescriptor() -> LanguageProviderDescriptor { + private func discoveredRuntimeDescriptor() -> LanguageProviderDescriptor { LanguageProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"], + id: "fixture", + displayName: "Fixture", + fileExtensions: ["fixture"], capabilities: .languageServer, activationPolicy: .onDemand, languageServerLaunch: LanguageServerLaunchDescriptor( - executableNames: ["java"], + executableNames: ["node"], executableVersionRequirement: LanguageServerExecutableVersionRequirement( - tool: "java", - minimumVersion: "21", + tool: "node", + minimumVersion: "18.17", probeArguments: ["--version"] ) ) ) } - private func javaFixtureManifest() throws -> Data { - try fixtureManifest("language-host-integration.plugin.json") - } - private func fixtureManifest(_ name: String) throws -> Data { try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot .appendingPathComponent("shared/contracts/plugins/v1/fixtures/languages") diff --git a/macos/Tests/LitheTests/PluginLiveActivationTests.swift b/macos/Tests/LitheTests/PluginLiveActivationTests.swift index a64eb2e524..7a05d2b6a8 100644 --- a/macos/Tests/LitheTests/PluginLiveActivationTests.swift +++ b/macos/Tests/LitheTests/PluginLiveActivationTests.swift @@ -47,7 +47,7 @@ struct PluginLiveActivationTests { manifest["activationEvents"] = ["onDebug:lldb", "onLanguage:rust"] manifest["languageServers"] = [[ "languageID": "rust", - "launch": ["kind": "systemCommand", "commands": ["example-language-server"]] + "launch": ["kind": "systemCommand", "commands": ["exampleuage-server"]] ]] let descriptor = try DeclarativePluginTestSupport.descriptor(manifest) #expect(!descriptor.debugAdapters.isEmpty) @@ -106,18 +106,18 @@ struct PluginLiveActivationTests { let first = try fixture.package(Self.debugManifest(id: "dev.example.first")) let second = try fixture.package(Self.debugManifest(id: "dev.example.second")) let attach = try fixture.package(Self.debugManifest(id: "dev.example.attach", - languageIDs: ["java"], requests: ["attach"], targetKinds: ["process"])) + languageIDs: ["example"], requests: ["attach"], targetKinds: ["process"])) let packages = [second, attach, first] let qualified = PluginDebugAdapterEntry.qualifiedIndex(of: packages) #expect(Set(qualified.keys) == ["dev.example.first/lldb", "dev.example.second/lldb", "dev.example.attach/lldb"]) let automatic = PluginDebugAdapterEntry.index(of: packages) #expect(automatic["rust"]?.plugin.descriptor.id == first.descriptor.id) - #expect(automatic["java"] == nil) - let languages = [DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"])] + #expect(automatic["example"] == nil) + let languages = [DebugProviderDescriptor(id: "example", displayName: "Example", fileExtensions: ["example"])] let descriptor = try #require(qualified["dev.example.attach/lldb"]?.provider(languages: languages)) #expect(descriptor.requests == [.attach]) #expect(!descriptor.selectsByFile) - #expect(descriptor.matches(URL(fileURLWithPath: "/workspace/Main.java"))) + #expect(descriptor.matches(URL(fileURLWithPath: "/workspace/main.example"))) } @Test @@ -206,11 +206,11 @@ struct PluginLiveActivationTests { } @Test - func theFirstPluginInIDOrderDebugsALanguageAndJavaKeepsTheHostAdapter() throws { + func theFirstPluginInIDOrderDebugsALanguage() throws { let fixture = try LiveFixture() defer { fixture.cleanUp() } let later = try fixture.package(Self.debugManifest( - id: "dev.example.zeta", adapterID: "zeta", languageIDs: ["rust", "java"] + id: "dev.example.zeta", adapterID: "zeta", languageIDs: ["rust", "example"] )) let earlier = try fixture.package(Self.debugManifest( id: "dev.example.alpha", adapterID: "alpha", languageIDs: ["rust", "zig"] @@ -221,7 +221,7 @@ struct PluginLiveActivationTests { let adapters = fixture.registry.snapshot.debugAdapters #expect(adapters["rust"]?.adapter.id == "alpha") #expect(adapters["zig"]?.adapter.id == "alpha") - #expect(adapters["java"] == nil) + #expect(adapters["example"]?.adapter.id == "zeta") } /// The Debug button launches the open file, so an adapter that only diff --git a/macos/Tests/LitheTests/PluginLocalDevelopmentTests.swift b/macos/Tests/LitheTests/PluginLocalDevelopmentTests.swift index fa6d178859..fcab8ea363 100644 --- a/macos/Tests/LitheTests/PluginLocalDevelopmentTests.swift +++ b/macos/Tests/LitheTests/PluginLocalDevelopmentTests.swift @@ -326,7 +326,6 @@ struct NodeLanguageToolEnvironmentTests { let node = URL(fileURLWithPath: "/fixture-tools/node") let service = ProjectRuntimeService( runtimeLocator: NodeEnvironmentTestRuntimeLocator(environment: ["PATH": "/usr/bin:/bin"]), - store: PluginLocalDevelopmentKeyValueStore(), toolDiscovery: FixedNodeToolDiscovery(node: node) ) @@ -350,12 +349,10 @@ struct NodeLanguageToolEnvironmentTests { ) let withGlobalNode = ProjectRuntimeService( runtimeLocator: NodeEnvironmentTestRuntimeLocator(environment: ["PATH": "/usr/bin:/bin"]), - store: PluginLocalDevelopmentKeyValueStore(), toolDiscovery: FixedNodeToolDiscovery(candidates: [projectNode, homebrewNode]) ) let projectNodeOnly = ProjectRuntimeService( runtimeLocator: NodeEnvironmentTestRuntimeLocator(environment: ["PATH": "/usr/bin:/bin"]), - store: PluginLocalDevelopmentKeyValueStore(), toolDiscovery: FixedNodeToolDiscovery(candidates: [projectNode]) ) @@ -389,7 +386,6 @@ struct NodeLanguageToolEnvironmentTests { ) let service = ProjectRuntimeService( runtimeLocator: NodeEnvironmentTestRuntimeLocator(environment: ["PATH": "/usr/bin:/bin"]), - store: PluginLocalDevelopmentKeyValueStore(), toolDiscovery: FixedNodeToolDiscovery(candidates: [go]) ) @@ -411,7 +407,6 @@ struct NodeLanguageToolEnvironmentTests { ) let service = ProjectRuntimeService( runtimeLocator: NodeEnvironmentTestRuntimeLocator(environment: ["PATH": "/usr/bin:/bin"]), - store: PluginLocalDevelopmentKeyValueStore(), toolDiscovery: FixedNodeToolDiscovery(candidates: [projectGo]) ) @@ -533,13 +528,7 @@ private struct NodeEnvironmentTestRuntimeLocator: RuntimeLocator { } func environment() -> [String: String] { environmentValues } - func discover() -> RuntimeDiscoveryResult { RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } } private struct FixedNodeToolDiscovery: RuntimeToolDiscovery { diff --git a/macos/Tests/LitheTests/PluginManagementPresentationTests.swift b/macos/Tests/LitheTests/PluginManagementPresentationTests.swift index c97ba3b54a..394010ca8c 100644 --- a/macos/Tests/LitheTests/PluginManagementPresentationTests.swift +++ b/macos/Tests/LitheTests/PluginManagementPresentationTests.swift @@ -74,31 +74,6 @@ struct PluginManagementPresentationTests { ]) } - /// Java's run and test support is still Lithe's own JDT integration, so the - /// Features tab says so. Debug is declared by the plugin's own - /// `debugAdapters` entry, so it is listed as plugin-provided instead. - @Test - func javaFeaturesIncludeHostIntegratedCapabilities() throws { - let java = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - - let capabilities = PluginCapability.capabilities(of: java.pluginManifest, descriptor: java) - let kinds = Set(capabilities.map(\.kind)) - - #expect(kinds.isSuperset(of: [.language, .languageServer, .run, .test, .debug])) - let server = try #require(capabilities.first { $0.kind == .languageServer && $0.subject == "java" }) - if case .runtimeServer(let tool, let packagedRuntime) = server.detail { - #expect(tool == "java") - #expect(packagedRuntime) - } else { - Issue.record("Expected the Java server to run on the packaged runtime, got \(server.detail)") - } - for capability in capabilities where [.run, .test].contains(capability.kind) { - #expect(capability.detail == .hostIntegration) - } - let debug = try #require(capabilities.first { $0.kind == .debug && $0.subject == "java" }) - #expect(debug.detail == .none) - } - @Test func installedListFiltersByCapabilityStateAndQuery() throws { let descriptor = try DeclarativePluginTestSupport.descriptor( diff --git a/macos/Tests/LitheTests/PluginManagerTests.swift b/macos/Tests/LitheTests/PluginManagerTests.swift index d3ad290752..5a4f60ba01 100644 --- a/macos/Tests/LitheTests/PluginManagerTests.swift +++ b/macos/Tests/LitheTests/PluginManagerTests.swift @@ -32,18 +32,22 @@ struct PluginManagerTests { } @Test func serverRegistrationUsesDeclaredCommandsOrExistingServerMetadataWithoutInventingNames() throws { - let java = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - let server = try #require(java.languageServers.first) + // A backend names its executable only when the server starts, so the + // registration reuses the catalog's descriptive metadata for its language. + let backend = try DeclarativePluginTestSupport.operations.validate(manifest: Data(contentsOf: + DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent( + "shared/contracts/plugins/v1/fixtures/languages/language-server-backend-launch.plugin.json"))) + let server = try #require(backend.languageServers.first) let catalog = RustLanguageProviderCatalogSource(core: RustCoreBridge()).load().catalog - let entry = MacPluginManager.languageServerRegistration(server, pluginID: java.id.rawValue, catalog: catalog) - #expect(entry.executableNames == ["jdtls"]) - #expect(entry.pluginID == java.id.rawValue) - let unnamed = MacPluginManager.languageServerRegistration(server, pluginID: java.id.rawValue, + let entry = MacPluginManager.languageServerRegistration(server, pluginID: backend.id.rawValue, catalog: catalog) + #expect(entry.executableNames == ["metals"]) + #expect(entry.pluginID == backend.id.rawValue) + let unnamed = MacPluginManager.languageServerRegistration(server, pluginID: backend.id.rawValue, catalog: LanguageProviderCatalog(descriptors: [])) #expect(unnamed.executableNames.isEmpty) let row = try #require(LSPControlCenterPresenter.statusBarServers(registrations: [unnamed], states: [:], infos: [:], disabledProviderIDs: []).first) - #expect(row.displayName == java.id.rawValue) + #expect(row.displayName == backend.id.rawValue) let installed = try installedPlugin() let direct = try #require(installed.descriptor.languageServers.first) @@ -84,15 +88,15 @@ struct PluginManagerTests { }) #expect(markdown.languageServerModuleID == nil) #expect(yaml.languageServerModuleID == .languageServerExtension("yaml")) - // Java Support also proves that a plugin may own the Java language + // The retired official plugins prove that a plugin may own a language // alongside every built-in and bundled catalog without a collision. - let officialLanguagePlugins = try ["GoSupport", "JavaSupport", "PhpSupport"].map { + let officialLanguagePlugins = try ["GoSupport", "PhpSupport"].map { try DeclarativePluginTestSupport.officialDescriptor($0).pluginManifest } #expect(Set(officialLanguagePlugins.map(\.id)) == Set(OfficialPluginCatalog.entries.map(\.id))) // Go and PHP moved to Lithe Store: installed copies keep their pinned // publisher signature, but the host no longer suggests them. - #expect(OfficialPluginCatalog.publishedEntries.map(\.id) == [OfficialPluginCatalog.javaPluginID]) + #expect(OfficialPluginCatalog.publishedEntries.isEmpty) #expect(OfficialPluginCatalog.entry(for: OfficialPluginCatalog.goPluginID)?.communityReplacementID == PluginID("io.github.lithe-idea.go-support")) #expect(OfficialPluginCatalog.entry(for: OfficialPluginCatalog.phpPluginID)?.communityReplacementID diff --git a/macos/Tests/LitheTests/PluginMarketplaceFeatureModelTests.swift b/macos/Tests/LitheTests/PluginMarketplaceFeatureModelTests.swift index 5b94bf1317..78c50d22e1 100644 --- a/macos/Tests/LitheTests/PluginMarketplaceFeatureModelTests.swift +++ b/macos/Tests/LitheTests/PluginMarketplaceFeatureModelTests.swift @@ -19,36 +19,6 @@ struct PluginMarketplaceFeatureModelTests { isEnabled: true ) - @Test - func bundledJavaCanMoveToTheOfficialDownloadAtTheSameVersion() async throws { - let id = OfficialPluginCatalog.javaPluginID - let (feature, service, manager) = try makeModel(staleOfficialIDs: [id.rawValue]) - var object = try #require(JSONSerialization.jsonObject(with: - DeclarativePluginTestSupport.officialDescriptor("JavaSupport").normalizedManifest - ) as? [String: Any]) - object["version"] = "1.0.0" - let manifest = try DeclarativePluginTestSupport.descriptor(object).pluginManifest - func snapshot(_ status: PluginInstallationStatus) -> PluginManagementSnapshot { - PluginManagementSnapshot( - manifest: manifest, origin: .bundled, installationStatus: status, - isEnabled: false, isRequired: false, isRunning: false, isQuarantined: false, - isSuppressedBySafeMode: false, requiresRestart: false, canRollback: false, statusMessage: "Disabled", marketplace: nil - ) - } - manager.snapshots = [snapshot(.installed)] - let listing = try #require(feature.listings.first { $0.pluginID == id }) - let offer = try #require(feature.offer(for: listing)) - #expect(feature.installedSourceID(for: id) == PluginMarketplaceSource.officialID) - #expect(feature.installState(for: offer) == .updateAvailable(installed: "1.0.0", available: "1.0.0")) - #expect(feature.availableUpdate(for: id)?.entry.id == id.rawValue) - service.origin = .marketplace - await feature.install(offer) - #expect(manager.installed.count == 1) - #expect(feature.pendingConfirmation == nil) - manager.snapshots = [snapshot(.removed)] - #expect(feature.installState(for: offer) == .installable) - } - /// Rows and the detail pane ask for one URL at the same time; they share /// one request, and a rejected icon is not requested again per row. @Test @@ -125,7 +95,7 @@ struct PluginMarketplaceFeatureModelTests { @Test func pluginsWithoutIconsShowIDEAStyleInitials() { #expect(PluginMarketplacePresentation.avatarText(for: "Go Support") == "GS") - #expect(PluginMarketplacePresentation.avatarText(for: "maven-build") == "MB") + #expect(PluginMarketplacePresentation.avatarText(for: "tool-build") == "TB") #expect(PluginMarketplacePresentation.avatarText(for: "Lua") == "LU") #expect(PluginMarketplacePresentation.avatarText(for: "R") == "R") #expect(PluginMarketplacePresentation.avatarText(for: "数据库工具") == "数") diff --git a/macos/Tests/LitheTests/PluginPackageStoreTests.swift b/macos/Tests/LitheTests/PluginPackageStoreTests.swift index 322658c265..f1586f49ed 100644 --- a/macos/Tests/LitheTests/PluginPackageStoreTests.swift +++ b/macos/Tests/LitheTests/PluginPackageStoreTests.swift @@ -836,7 +836,7 @@ struct PluginPackageStoreTests { ) } - /// The Gradle provider fixture, with its provider launch replaced when + /// The build-provider contract fixture, with its provider launch replaced when /// `launch` is given. A packaged launch gets an executable script. private func makeProviderPackage(root: URL, launch: [String: Any]?) throws -> URL { let fixtureURL = DeclarativePluginTestSupport.repositoryRoot diff --git a/macos/Tests/LitheTests/PluginRunHostServiceTests.swift b/macos/Tests/LitheTests/PluginRunHostServiceTests.swift index ff90021b40..56add5939a 100644 --- a/macos/Tests/LitheTests/PluginRunHostServiceTests.swift +++ b/macos/Tests/LitheTests/PluginRunHostServiceTests.swift @@ -31,7 +31,10 @@ struct PluginRunHostServiceTests { #expect(launch.environment["B"] == "b") // The user's layers pick the installation; project code is allowed as for any Run. #expect(fixture.tools.resolutions == [ - RunTools.Resolution(tool: "go", directory: "sub", workspace: PluginHostFixture.workspaceURL.path, projectCodeAllowed: true), + // Resolved as an installation: Core expands the launch template, so a template + // with runtime arguments must not be refused the way a direct launch refuses it. + RunTools.Resolution(tool: "go", directory: "sub", workspace: PluginHostFixture.workspaceURL.path, + projectCodeAllowed: true, use: .installation), ]) #expect(fixture.decoder.workspaceRoots == [PluginHostFixture.workspaceURL]) } @@ -464,6 +467,7 @@ private final class RunTools: DefinedToolchainResolving, DefinedToolLaunching { let directory: String let workspace: String let projectCodeAllowed: Bool + var use: DefinedToolchainUse = .executable } static let installation = ResolvedDefinedToolchain( @@ -477,7 +481,15 @@ private final class RunTools: DefinedToolchainResolving, DefinedToolLaunching { func resolve(tool: String, directory: String, workspace: URL, environment _: [String: String], minimumVersion _: String?, projectCodeAllowed: Bool) async throws -> ResolvedDefinedToolchain? { - resolutions.append(Resolution(tool: tool, directory: directory, workspace: workspace.path, projectCodeAllowed: projectCodeAllowed)) + try await resolve(tool: tool, directory: directory, workspace: workspace, environment: [:], minimumVersion: nil, + projectCodeAllowed: projectCodeAllowed, fixed: nil, use: .executable, consumerID: nil) + } + + func resolve(tool: String, directory: String, workspace: URL, environment _: [String: String], + minimumVersion _: String?, projectCodeAllowed: Bool, fixed _: FixedToolchainSelection?, + use: DefinedToolchainUse, consumerID _: String?) async throws -> ResolvedDefinedToolchain? { + resolutions.append(Resolution(tool: tool, directory: directory, workspace: workspace.path, + projectCodeAllowed: projectCodeAllowed, use: use)) if let resolveFailure { throw resolveFailure } return selection } diff --git a/macos/Tests/LitheTests/PluginServerProcessToolReferenceTests.swift b/macos/Tests/LitheTests/PluginServerProcessToolReferenceTests.swift new file mode 100644 index 0000000000..f8feaca5e6 --- /dev/null +++ b/macos/Tests/LitheTests/PluginServerProcessToolReferenceTests.swift @@ -0,0 +1,181 @@ +import Foundation +import Testing +@testable import Lithe +import LitheCoreContracts +import LitheModuleAPI + +/// `requires.serverProcess` 4: a server process that names a tool definition. +/// Rust Core plans the launch, the host resolves the tool through its four +/// layers or runs the runtime the plugin ships, and the definition's `launch` +/// template alone places every argument. +@Suite("Plugin server process tool reference") +struct PluginServerProcessToolReferenceTests { + private static let fixtureURL = DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/run/tool-reference-launch.plugin.json") + private static let pluginDirectory = URL(fileURLWithPath: "/plugins/tool-reference") + + @Test func theHostAdvertisesToolReferenceServerProcesses() { + #expect(PluginManifest.hostCapabilities["serverProcess"]?.contains(4) == true) + } + + @Test func aToolLaunchPlanDecodesWithoutAnExecutableOrPackageEntry() throws { + let descriptor = try DeclarativePluginTestSupport.operations.validate(manifest: Data(contentsOf: Self.fixtureURL)) + let plan = try DeclarativePluginTestSupport.operations.languageServerLaunchPlan( + manifest: descriptor.normalizedManifest, + languageID: "script", + request: DeclarativeLanguageServerLaunchRequest( + pluginDirectory: Self.pluginDirectory, + stateDirectory: URL(fileURLWithPath: "/state"), + workspaceStateDirectory: URL(fileURLWithPath: "/state/workspace"), + architecture: MacPluginLanguageServerLaunchResolver.hostArchitecture + ) + ) + + let launch = try #require(plan.toolLaunch) + #expect(launch.tool == "interpreter") + #expect(launch.entry == Self.pluginDirectory.path + "/language-server/server.script") + #expect(launch.runtimeArguments == ["-X", "utf8"]) + #expect(launch.minimumVersion == "3.9") + #expect(launch.packagedRuntime == nil) + // The plan's own arguments fill `${arguments}` only; the entry and + // runtime arguments stay out of them. + #expect(plan.arguments == ["--stdio"]) + #expect(plan.executable == nil) + #expect(plan.entryPath == nil) + #expect(plan.runtimeRequirements.contains { + $0.tool == "interpreter" && $0.resolvesThroughDefinition + }) + } + + @MainActor @Test func anUnresolvedToolIsReportedAsToolUnresolved() async throws { + let workspace = try Self.temporaryWorkspace() + defer { try? FileManager.default.removeItem(at: workspace) } + let resolver = MacDefinedToolchainResolver() + resolver.sources = { [] } + + do { + _ = try await resolver.command( + for: Self.process(packagedRuntimeURL: nil), arguments: ["--stdio"], workspace: workspace, + environment: [:], projectCodeAllowed: false + ) + Issue.record("A tool no layer resolves must not start.") + } catch let rejection as DeclarativePluginRejection { + #expect(rejection.code == "plugin.host.toolUnresolved") + #expect(rejection.message.contains("interpreter")) + } + } + + @MainActor @Test func anUnresolvedRequirementStopsEvenAPackagedRuntime() async throws { + let workspace = try Self.temporaryWorkspace() + defer { try? FileManager.default.removeItem(at: workspace) } + let resolver = MacDefinedToolchainResolver() + let source = try Self.source(template: nil) + resolver.sources = { [source] } + let process = Self.process( + packagedRuntimeURL: Self.pluginDirectory.appendingPathComponent("runtime/bin/interpreter"), + requirements: [.init(tool: "formatter", minimumVersion: nil, resolvesThroughDefinition: true)] + ) + + do { + _ = try await resolver.command( + for: process, arguments: ["--stdio"], workspace: workspace, environment: [:], projectCodeAllowed: false + ) + Issue.record("A requirement no layer resolves must not start.") + } catch let rejection as DeclarativePluginRejection { + #expect(rejection.code == "plugin.host.toolUnresolved") + #expect(rejection.message.contains("formatter")) + } + } + + /// The packaged runtime runs as the tool without any lookup, and the + /// template decides where the entry, runtime arguments and plan arguments + /// go. The host adds nothing of its own. + @MainActor @Test(arguments: [ + ( + nil as [String]?, + ["-X", "utf8", "/plugins/tool-reference/language-server/server.script", "--stdio"] + ), + ( + ["${executable}", "${arguments}", "${runtimeArguments}", "${entry}"], + ["--stdio", "-X", "utf8", "/plugins/tool-reference/language-server/server.script"] + ) + ]) + func aPackagedRuntimeStartsDirectlyWithTheTemplateOrder(template: [String]?, expected: [String]) async throws { + let workspace = try Self.temporaryWorkspace() + defer { try? FileManager.default.removeItem(at: workspace) } + let resolver = MacDefinedToolchainResolver() + let source = try Self.source(template: template) + resolver.sources = { [source] } + let runtime = Self.pluginDirectory.appendingPathComponent("runtime/bin/interpreter") + + let command = try await resolver.command( + for: Self.process(packagedRuntimeURL: runtime), arguments: ["--stdio"], workspace: workspace, + environment: ["FIXTURE_SETTING": "kept"], projectCodeAllowed: false + ) + + #expect(command.executableURL.path == runtime.path) + #expect(command.arguments == expected) + #expect(command.environment["FIXTURE_SETTING"] == "kept") + } + + @MainActor @Test func aTemplateThatCannotPlaceTheEntryRefusesTheLaunch() async throws { + let workspace = try Self.temporaryWorkspace() + defer { try? FileManager.default.removeItem(at: workspace) } + let resolver = MacDefinedToolchainResolver() + let source = try Self.source(template: ["${executable}", "${arguments}"]) + resolver.sources = { [source] } + + do { + _ = try await resolver.command( + for: Self.process(packagedRuntimeURL: Self.pluginDirectory.appendingPathComponent("runtime/bin/interpreter")), + arguments: ["--stdio"], workspace: workspace, environment: [:], projectCodeAllowed: false + ) + Issue.record("A template without `${entry}` must not drop the entry.") + } catch let rejection as DeclarativePluginRejection { + #expect(rejection.code != "plugin.host.toolUnresolved") + } + } + + // MARK: - Fixtures + + private static func process( + packagedRuntimeURL: URL?, + requirements: [DeclarativeLanguageServerLaunchPlan.RuntimeRequirement] = [] + ) -> DefinedToolProcessLaunch { + DefinedToolProcessLaunch( + launch: .init( + tool: "interpreter", + entry: pluginDirectory.path + "/language-server/server.script", + runtimeArguments: ["-X", "utf8"], + minimumVersion: "3.9", + packagedRuntime: packagedRuntimeURL.map { _ in "runtime/bin/interpreter" } + ), + packagedRuntimeURL: packagedRuntimeURL, + requirements: requirements + ) + } + + /// The contract fixture as an installed plugin, with its definition's + /// `launch` template replaced when one is given. + private static func source(template: [String]?) throws -> ToolchainSettingsPluginSource { + var manifest = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as? [String: Any] + ) + if let template { + var definitions = try #require(manifest["toolDefinitions"] as? [[String: Any]]) + definitions[0]["launch"] = template + manifest["toolDefinitions"] = definitions + } + return ToolchainSettingsPluginSource( + pluginID: "dev.lithe.fixture.tool-reference-launch", name: "Tool reference", + manifest: try JSONSerialization.data(withJSONObject: manifest), isEnabled: true + ) + } + + private static func temporaryWorkspace() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-tool-reference-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } +} diff --git a/macos/Tests/LitheTests/PluginSettingsTests.swift b/macos/Tests/LitheTests/PluginSettingsTests.swift index ba42b8ac52..aba2b29a3f 100644 --- a/macos/Tests/LitheTests/PluginSettingsTests.swift +++ b/macos/Tests/LitheTests/PluginSettingsTests.swift @@ -100,56 +100,6 @@ struct PluginSettingsTests { #expect(settings.values(forPlugin: pluginID.rawValue)["telemetry"] == nil) } - @Test - func theJavaPluginOffersMaximumMemoryAndLogLevelWithTheCurrentBehaviorAsDefault() throws { - let descriptor = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - - #expect(descriptor.settings.map(\.id) == ["heapMaxMB", "logLevel"]) - let heap = try #require(descriptor.settings.first { $0.id == "heapMaxMB" }) - // The language server starts with a 2 GB heap and logs warnings and - // errors only. A smaller heap makes JDT LS import Maven modules in its - // constrained-memory mode, which fails the whole Java service for modules - // that share coordinates, so the plugin does not offer one. - #expect(heap.defaultValue == .integer(2048)) - #expect(heap.kind == .integer(minimum: 2048, maximum: 16384, unit: "MB")) - let level = try #require(descriptor.settings.first { $0.id == "logLevel" }) - #expect(level.defaultValue == .string("WARNING")) - #expect(level.accepts(.string("SEVERE")) && !level.accepts(.string("OFF"))) - } - - /// The Java plugin's choices end up on the JVM command line. - @Test - func theJavaPluginPassesItsSettingsToTheJvm() throws { - let descriptor = try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - let source = DeclarativeLanguageServerLaunchSource( - pluginID: descriptor.id.rawValue, - languageID: "java", - manifest: descriptor.normalizedManifest, - packageURL: URL(fileURLWithPath: "/plugins/java") - ) - let settings = InMemoryPluginSettings([ - descriptor.id.rawValue: ["heapMaxMB": .integer(3072), "logLevel": .string("WARNING")] - ]) - let request = DeclarativeLanguageServerLaunchRequest( - pluginDirectory: source.packageURL, - stateDirectory: URL(fileURLWithPath: "/state"), - workspaceStateDirectory: URL(fileURLWithPath: "/state/workspace"), - architecture: MacPluginLanguageServerLaunchResolver.hostArchitecture, - settings: settings.values(forPlugin: descriptor.id.rawValue), - logDirectory: URL(fileURLWithPath: "/logs") - ) - - let plan = try DeclarativePluginTestSupport.operations.languageServerLaunchPlan( - manifest: source.manifest, - languageID: "java", - request: request - ) - - #expect(plan.arguments.prefix(2) == ["-Xmx3072m", "-Dlog.level=WARNING"]) - // JDT LS keeps its own log in Lithe's log directory, never in plugin state. - #expect(plan.arguments.contains("-Dosgi.logfile=/logs/jdt.log")) - } - // MARK: Settings v2: layers, pages, and buttons @Test @@ -247,9 +197,9 @@ struct PluginSettingsTests { defaultValue: .string("") ) #expect(path.accepts(.string("/opt/tool"))) - #expect(path.accepts(.string("C:\\tools\\jdk"))) + #expect(path.accepts(.string("C:\\tools\\kit"))) #expect(path.accepts(.string("d:/tools"))) - #expect(!path.accepts(.string("tools/jdk"))) + #expect(!path.accepts(.string("tools/kit"))) #expect(!path.accepts(.string("1:/tools"))) } diff --git a/macos/Tests/LitheTests/PluginWebBridgeTests.swift b/macos/Tests/LitheTests/PluginWebBridgeTests.swift index 3d77b3becb..12bef066af 100644 --- a/macos/Tests/LitheTests/PluginWebBridgeTests.swift +++ b/macos/Tests/LitheTests/PluginWebBridgeTests.swift @@ -638,7 +638,7 @@ struct PluginWebBridgeTests { let pages = PluginWebPages(windows: [harness.window]) let manager = ProjectSessionManager(settings: settings, modelFactory: { let container = MacServiceContainer( - store: store, settings: settings, javaMavenOperations: NoProjectJavaOperations(), + store: store, settings: settings, pluginWebPageLifecycle: PluginWebPageLifecycle() ) containers.append(container) @@ -743,9 +743,8 @@ struct PluginWebBridgeTests { languageProviderCatalogSnapshot: base.languageProviderCatalogSnapshot, debugLaunchConfigurationResolver: base.debugLaunchConfigurationResolver, debugPortAvailabilityChecker: base.debugPortAvailabilityChecker, - javaTestResultServerFactory: { MacJavaTestResultServer() }, workspaceOperations: base.workspaceOperations, documentLifecycleDecider: base.documentLifecycleDecider, - lineEditing: base.lineEditing, javaMavenOperations: base.javaMavenOperations, + lineEditing: base.lineEditing, markdownRenderer: base.markdownRenderer, markdownImageImporter: base.markdownImageImporter, store: base.store, fileStorage: base.fileStorage, fileOperations: base.fileOperations, agentEditRestorer: base.agentEditRestorer, binaryFileViewerRegistry: base.binaryFileViewerRegistry, diff --git a/macos/Tests/LitheTests/ProblemsPanelPresentationTests.swift b/macos/Tests/LitheTests/ProblemsPanelPresentationTests.swift index 8d1c733a04..fde3d809bb 100644 --- a/macos/Tests/LitheTests/ProblemsPanelPresentationTests.swift +++ b/macos/Tests/LitheTests/ProblemsPanelPresentationTests.swift @@ -26,8 +26,8 @@ struct ProblemsPanelPresentationTests { let settings = AppSettings(store: store) let model = AppModel(settings: settings, services: MacServiceContainer(store: store, settings: settings, moduleLaunchMode: .safeMode).services) - let url = try #require(URL(string: "lithe-fixture://workspace/Main.java")) - model.documentFeature.openVirtualDocument(url, text: "class Main {}", displayPath: nil) + let url = try #require(URL(string: "lithe-fixture://workspace/Main.txt")) + model.documentFeature.openVirtualDocument(url, text: "main", displayPath: nil) let document = try #require(model.activeDocument) #expect(ProblemsPanelScope.currentFileURL(in: model) == url) model.showAgentChatsInEditor() @@ -41,8 +41,8 @@ struct ProblemsPanelPresentationTests { @Test func fileScopeFollowsSelectedURLAndKeepsWorkspaceDiagnostics() { - let first = URL(fileURLWithPath: "/workspace/one/Main.java") - let second = URL(fileURLWithPath: "/workspace/two/Main.java") + let first = URL(fileURLWithPath: "/workspace/one/Main.txt") + let second = URL(fileURLWithPath: "/workspace/two/Main.txt") let store = EditorDiagnosticsStore() let problem = EditorDiagnostic(id: "second", fileURL: second, line: 5, utf16Column: 2, endLine: 5, endUTF16Column: 3, severity: .warning, message: "Example warning", @@ -51,7 +51,7 @@ struct ProblemsPanelPresentationTests { #expect(ProblemsPanelScope.file.diagnostics(in: store.diagnosticsByURL, currentFileURL: first).isEmpty) #expect(ProblemsPanelScope.file.diagnostics(in: store.diagnosticsByURL, - currentFileURL: second.deletingLastPathComponent().appendingPathComponent("./Main.java")) == [problem]) + currentFileURL: second.deletingLastPathComponent().appendingPathComponent("./Main.txt")) == [problem]) // No selected text editor must not fall back to the first file with diagnostics. #expect(ProblemsPanelScope.file.diagnostics(in: store.diagnosticsByURL, currentFileURL: nil).isEmpty) #expect(ProblemsPanelScope.projectErrors.diagnostics(in: store.diagnosticsByURL, currentFileURL: nil) == [problem]) @@ -63,11 +63,11 @@ struct ProblemsPanelPresentationTests { @Test func problemsQueryUsesSharedFileAndSeverityOrder() { let root = URL(fileURLWithPath: "/workspace/problems") - let ten = root.appendingPathComponent("src/File10.java") - let two = root.appendingPathComponent("src/File2.java") + let ten = root.appendingPathComponent("src/File10.txt") + let two = root.appendingPathComponent("src/File2.txt") func problem(_ id: String, _ url: URL, _ line: Int, _ severity: DiagnosticSeverity) -> EditorDiagnostic { EditorDiagnostic(id: id, fileURL: url, line: line, utf16Column: 0, endLine: line, endUTF16Column: 1, - severity: severity, message: id, source: "java", code: nil, tags: [], relatedInformation: []) + severity: severity, message: id, source: "test", code: nil, tags: [], relatedInformation: []) } let diagnostics = [ problem("ten-warning", ten, 1, .warning), @@ -75,7 +75,7 @@ struct ProblemsPanelPresentationTests { problem("two-error", two, 9, .error), problem("two-hint", two, 0, .hint), ] - let paths = [ten: "src/File10.java", two: "src/File2.java"] + let paths = [ten: "src/File10.txt", two: "src/File2.txt"] let all = ProblemsQuery.run(diagnostics: diagnostics, severities: Set(DiagnosticSeverity.allCases), displayPaths: paths, logSink: nil) @@ -115,14 +115,14 @@ struct ProblemsPanelPresentationTests { .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources") let bundle = try #require(Bundle(url: resources)) let english = try #require(Bundle(url: resources.appendingPathComponent("en.lproj"))) - let file = URL(fileURLWithPath: "/workspace/Main.java") + let file = URL(fileURLWithPath: "/workspace/Main.txt") let chinese = language == "zh-Hans" let cases: [(LocalizedStringKey, String)] = [ (ProblemsPanelScope.projectErrors.title, chinese ? "项目错误" : "Project Errors"), (ProblemsPanelScope.file.emptyTitle(currentFileURL: nil), chinese ? "在编辑器中打开文件以查看问题" : "Open file in editor to see problems"), (ProblemsPanelScope.file.emptyTitle(currentFileURL: file), - chinese ? "Main.java 中没有问题" : "No problems in Main.java"), + chinese ? "Main.txt 中没有问题" : "No problems in Main.txt"), ("Problems could be filtered out", chinese ? "问题可能已被筛选隐藏" : "Problems could be filtered out"), ("Could not load file preview", chinese ? "无法加载文件预览" : "Could not load file preview") ] @@ -154,7 +154,7 @@ struct ProblemsPanelPresentationTests { if ownsFont { CTFontManagerUnregisterFontsForURL(fontURL as CFURL, .process, nil) } } #expect(LitheTheme.uiNSFont(size: 13).fontName == "Inter-Regular") - let content = ProblemsEmptyState(title: "No problems in Main.java", details: nil) + let content = ProblemsEmptyState(title: "No problems in Main.txt", details: nil) .frame(width: width, height: 300) .environment(\.colorScheme, scheme) let renderer = ImageRenderer(content: content) diff --git a/macos/Tests/LitheTests/ProcessLifecycleFixtureTests.swift b/macos/Tests/LitheTests/ProcessLifecycleFixtureTests.swift index 7d5acf1002..49d5b5a75a 100644 --- a/macos/Tests/LitheTests/ProcessLifecycleFixtureTests.swift +++ b/macos/Tests/LitheTests/ProcessLifecycleFixtureTests.swift @@ -142,7 +142,7 @@ struct ProcessExitCoordinatorTests { resources: BackgroundResourceAnswer(terminate: ["service:20:2"], remember: false) ) let coordinator = ProcessExitCoordinator(core: RustProcessLifecycleDecider(core: RustCoreBridge()), presenter: presenter) - let busy = terminal(programs: [TerminalRunningProgram(processID: 10, commandLine: "mvn spring-boot:run")]) + let busy = terminal(programs: [TerminalRunningProgram(processID: 10, commandLine: "tool-a serve")]) let idle = terminal(programs: []) let (outcome, _) = await coordinator.confirmQuit( @@ -171,13 +171,13 @@ struct ProcessExitCoordinatorTests { let (outcome, _) = await coordinator.confirmQuit( settings: ProcessTerminationSettings(), - runServices: [service("run:api"), service("maven:install")], + runServices: [service("run:api"), service("tool-a:install")], terminals: [busy], agentTasks: [], resources: [] ) - #expect(presenter.asked == ["runServices:quit:run:api,maven:install", "terminal:\(busy.sessionID)"]) + #expect(presenter.asked == ["runServices:quit:run:api,tool-a:install", "terminal:\(busy.sessionID)"]) guard case .proceed = outcome else { Issue.record("Expected to proceed, got \(outcome)") return diff --git a/macos/Tests/LitheTests/ProcessTreePerformanceTests.swift b/macos/Tests/LitheTests/ProcessTreePerformanceTests.swift index 5f8796c9b2..296e9d2dc5 100644 --- a/macos/Tests/LitheTests/ProcessTreePerformanceTests.swift +++ b/macos/Tests/LitheTests/ProcessTreePerformanceTests.swift @@ -14,7 +14,7 @@ struct ProcessTreePerformanceTests { if event.state == .running { recorder.root = event.processID } } process.onOutput = { recorder.receive($0) } - // The shell owns a CPU-bound worker, like a build launcher owns a test JVM. + // The shell owns a CPU-bound worker, like a build launcher owns a test worker. try process.start(ProcessRequest(executablePath: "/bin/sh", arguments: ["-c", "/usr/bin/yes > /dev/null & echo $!; wait"], timeoutMilliseconds: 8000)) #expect(await recorder.ready.waitUntilOpen()) @@ -28,7 +28,7 @@ struct ProcessTreePerformanceTests { var error: String? let job = Task { @MainActor in do { - for try await sample in MacDebugPerformanceSampler(processRegistry: nil) + for try await sample in MacDebugPerformanceSampler() .samples(for: DebugPerformanceTarget(processID: root)) { samples.append(sample) if samples.count == 3 { received.open() } diff --git a/macos/Tests/LitheTests/ProjectGenerationTests.swift b/macos/Tests/LitheTests/ProjectGenerationTests.swift index f1e2ebe9da..7eaa2fe52e 100644 --- a/macos/Tests/LitheTests/ProjectGenerationTests.swift +++ b/macos/Tests/LitheTests/ProjectGenerationTests.swift @@ -8,7 +8,6 @@ import Testing @Suite("New project generation") @MainActor struct ProjectGenerationTests { - private static let javaSupportDirectory = "JavaSupport" /// The published projectGenerators 2 fixture: `python-app` asks for a /// `python` tool of at least 3.11, `node-app` for an optional `node` tool. private static let toolFieldPluginID = PluginID("dev.lithe.fixture.project-generator-tool-field") @@ -21,169 +20,9 @@ struct ProjectGenerationTests { private static let python312 = ProjectToolInstallation( home: "/opt/python-3.12", executable: "/opt/python-3.12/bin/python3", version: "3.12.4" ) - /// Generator-only copy of Java Support's entries, so window tests can - /// keep the template plugin and the language provider apart the way a - /// community template plugin would be. - private static let templatesPluginID = PluginID("dev.lithe.test.java-templates") - private static let jdk = JavaRuntimeCandidate(homePath: "/opt/jdk-21", version: "21.0.4", vendor: "Temurin") - - // MARK: Plugin declaration - - @Test - func javaSupportDeclaresGeneratorsAndItsOwnModule() throws { - let descriptor = try DeclarativePluginDescriptor( - normalizedManifest: DeclarativePluginTestSupport.officialDescriptor(Self.javaSupportDirectory).normalizedManifest, - enabledByDefault: true - ) - #expect(descriptor.projectGenerators.map(\.id) == ["java", "maven-archetype", "spring-boot"]) - let module = try #require(descriptor.pluginManifest.modules.first { - $0.manifest.id == .projectGeneratorsExtension(descriptor.id.rawValue) - }) - // The window runs without a workspace, and a bundled package is on - // from the first launch. - #expect(module.manifest.scope == .application) - #expect(module.manifest.defaultState == .enabled) - let capabilities = PluginCapability.capabilities(of: descriptor.pluginManifest, descriptor: descriptor) - #expect(capabilities.filter { $0.kind == .projectGenerator }.map(\.title) == ["Java", "Maven Archetype", "Spring Boot"]) - } - - /// Startup refuses a plugin that declares a module the host does not - /// register, so every Java Support module, the project-generators one - /// included, needs a factory. - @Test - func everyJavaSupportModuleIsRegisteredAtStartup() throws { - let directory = Self.javaSupportDirectory - let descriptor = try DeclarativePluginTestSupport.officialDescriptor(directory) - let installed = InstalledPluginPackage( - descriptor: descriptor, - installation: PluginInstallationRecord( - pluginID: descriptor.id, - activeVersion: descriptor.pluginManifest.version, - origin: .localDevelopment - ), - packageURL: DeclarativePluginTestSupport.officialPackageURL(directory) - ) - let registered = Set(MacServiceContainer.declarativePluginFactories( - [installed], - executionHost: MacLanguageExecutionHost(processRegistry: ManagedProcessRegistry()), - planner: DeclarativePluginTestSupport.operations - ).map(\.manifest.id)) - #expect(registered.contains(.projectGeneratorsExtension(descriptor.id.rawValue))) - #expect(Set(descriptor.pluginManifest.modules.map(\.manifest.id)).isSubset(of: registered)) - } - - // MARK: Rust Core - - @Test - func catalogListsProvidersOfEachRequirement() throws { - let split = try Self.splitJavaSupport() - let catalog = try Self.planner.catalog([ - split.templates, - split.language.with(enabled: false), - ]) - #expect(catalog.generators.map(\.generator.id) == ["java", "maven-archetype", "spring-boot"]) - let java = try #require(catalog.generators.first) - #expect(java.generator.section == .project) - #expect(java.requirements.first?.subject == .language("java")) - #expect(java.requirements.first?.providers == [ - ProjectRequirementProvider(pluginID: "dev.lithe.plugin.java-support", pluginName: "Java Support", enabled: false) - ]) - // No installed plugin declares the Maven build system. - #expect(java.requirements.dropFirst().allSatisfy { $0.providers.isEmpty }) - } - - @Test - func bundledJavaSupportProvidesTheLanguageItsTemplatesNeed() throws { - let catalog = try Self.planner.catalog([try Self.source(Self.javaSupportDirectory, enabled: true)]) - let java = try #require(catalog.generators.first) - #expect(java.pluginEnabled) - #expect(java.requirements.first?.providers == [ - ProjectRequirementProvider(pluginID: "dev.lithe.plugin.java-support", pluginName: "Java Support", enabled: true) - ]) - } - - @Test - func formDerivesDefaultsAndHidesFieldsOfOtherBuildSystems() throws { - let target = try Self.target("spring-boot") - var input = ProjectGeneratorFormInput(projectName: "Order-Service") - input.runtimes["jdk"] = ProjectRuntimeSelection(home: Self.jdk.homePath, version: Self.jdk.version) - let form = try Self.planner.form(target, input: input) - #expect(form.field("artifactId")?.value == .string("Order-Service")) - #expect(form.field("packageName")?.value == .string("com.example.orderservice")) - #expect(form.valid) - - let java = try Self.planner.form( - try Self.target("java"), - input: ProjectGeneratorFormInput(projectName: "demo", values: ["buildSystem": .string("none")]) - ) - #expect(java.field("groupId")?.visible == false) - #expect(java.field("jdk")?.problem == .required) - } // MARK: Creating projects - @Test - func createsAMavenProjectFromTemplates() async throws { - let directory = try TemporaryDirectory() - defer { directory.remove() } - let recorder = JavaHomeRecorder() - let service = Self.service(recorder: recorder) - var input = ProjectGeneratorFormInput(projectName: "demo") - input.runtimes["jdk"] = ProjectRuntimeSelection(home: Self.jdk.homePath, version: Self.jdk.version) - - let project = try await service.create( - try Self.target("java"), input: input, in: directory.url, createGitRepository: false - ) - - let root = directory.url.appendingPathComponent("demo") - #expect(project.url.path == root.path) - let pom = try String(contentsOf: root.appendingPathComponent("pom.xml"), encoding: .utf8) - #expect(pom.contains("21")) - #expect(FileManager.default.fileExists(atPath: root.appendingPathComponent(".gitignore").path)) - #expect(project.openFiles.map(\.path) == [root.appendingPathComponent("src/main/java/org/example/Main.java").path]) - #expect(await recorder.records == [Record(root: root.path, home: Self.jdk.homePath)]) - #expect(try Self.stagingEntries(in: directory.url).isEmpty) - } - - @Test - func collectsTheDirectoryAScaffoldingToolCreated() async throws { - let directory = try TemporaryDirectory() - defer { directory.remove() } - let runner = ScaffoldingRunner(creates: "demo/pom.xml") - let service = Self.service(runner: runner) - var input = ProjectGeneratorFormInput(projectName: "demo") - input.runtimes["jdk"] = ProjectRuntimeSelection(home: Self.jdk.homePath, version: Self.jdk.version) - - _ = try await service.create( - try Self.target("maven-archetype"), input: input, in: directory.url, createGitRepository: false - ) - - let request = try #require(runner.requests.first) - #expect(request.executableURL.path == "/usr/local/bin/mvn") - #expect(request.environment["JAVA_HOME"] == Self.jdk.homePath) - #expect(request.environment["PATH"]?.hasPrefix(Self.jdk.homePath + "/bin:") == true) - #expect(request.arguments.contains("-DartifactId=demo")) - let root = directory.url.appendingPathComponent("demo") - #expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("pom.xml").path)) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("demo").path)) - } - - @Test - func aFailedStepLeavesNothingBehind() async throws { - let directory = try TemporaryDirectory() - defer { directory.remove() } - let service = Self.service(runner: ScaffoldingRunner(creates: "demo/pom.xml", exitStatus: 1)) - var input = ProjectGeneratorFormInput(projectName: "demo") - input.runtimes["jdk"] = ProjectRuntimeSelection(home: Self.jdk.homePath, version: Self.jdk.version) - - await #expect(throws: ProjectGenerationError.self) { - try await service.create( - try Self.target("maven-archetype"), input: input, in: directory.url, createGitRepository: false - ) - } - #expect(try FileManager.default.contentsOfDirectory(atPath: directory.url.path).isEmpty) - } - @Test func refusesAnExistingDestination() async throws { let directory = try TemporaryDirectory() @@ -199,32 +38,6 @@ struct ProjectGenerationTests { #expect(try Self.stagingEntries(in: directory.url).isEmpty) } - @Test - func extractsADownloadedArchive() async throws { - let directory = try TemporaryDirectory() - defer { directory.remove() } - let archive = DeclarativePluginTestSupport.repositoryRoot - .appendingPathComponent("macos/Tests/LitheTests/Fixtures/ProjectGeneration/starter.zip") - let platform = DownloadStubPlatform(base: Self.platform(), archive: archive) - let service = ProjectGenerationService( - planner: Self.planner, platform: platform, - initializeGitRepository: { _ in nil }, recordJavaHome: { _, _ in } - ) - var input = ProjectGeneratorFormInput(projectName: "demo") - input.runtimes["jdk"] = ProjectRuntimeSelection(home: Self.jdk.homePath, version: Self.jdk.version) - - let project = try await service.create( - try Self.target("spring-boot"), input: input, in: directory.url, createGitRepository: false - ) - - #expect(platform.requestedURL?.host == "start.spring.io") - let mvnw = project.url.appendingPathComponent("mvnw").path - #expect(FileManager.default.isExecutableFile(atPath: mvnw)) - #expect(project.openFiles.map(\.path) == [project.url.appendingPathComponent("pom.xml").path]) - // The downloaded copy is removed after extraction. - #expect(!FileManager.default.fileExists(atPath: platform.downloadedCopy?.path ?? "/nonexistent")) - } - // MARK: Downloading archives /// An oversized body is cut off while it streams, whether or not the @@ -261,77 +74,6 @@ struct ProjectGenerationTests { } } - // MARK: Window state - - @Test - func missingJavaTemplatesOfferAnInstallationEntry() throws { - let missing = NewProjectFeatureModel(environment: try Self.environment(plugins: PluginStates(enabled: []), sources: [])) - missing.reloadCatalog() - #expect(missing.isJavaSupportMissing) - let installed = NewProjectFeatureModel(environment: try Self.environment( - plugins: PluginStates(enabled: []), sources: [try Self.source(Self.javaSupportDirectory, enabled: false)] - )) - installed.reloadCatalog() - #expect(!installed.isJavaSupportMissing) - } - - @Test - func offersToEnableDisabledProvidersAndFindsMissingOnes() async throws { - let plugins = PluginStates(enabled: [Self.templatesPluginID]) - let feature = NewProjectFeatureModel(environment: try Self.environment(plugins: plugins)) - await feature.load() - #expect(feature.selectedEntry?.generator.id == "java") - #expect(feature.requirementNotices.map(\.action) == [ - .enable(PluginID("dev.lithe.plugin.java-support"), name: "Java Support"), - .findInMarketplace("maven"), - ]) - // A requirement never blocks creation. - #expect(feature.canCreate) - - await feature.enablePlugin(PluginID("dev.lithe.plugin.java-support")) - #expect(feature.requirementNotices.map(\.action) == [.findInMarketplace("maven")]) - } - - @Test - func aDisabledTemplatePluginMustBeEnabledBeforeCreating() async throws { - let feature = NewProjectFeatureModel(environment: try Self.environment(plugins: PluginStates(enabled: []))) - await feature.load() - #expect(feature.selectedEntry?.pluginEnabled == false) - #expect(!feature.canCreate) - - await feature.enablePlugin(Self.templatesPluginID) - #expect(feature.selectedEntry?.pluginEnabled == true) - #expect(feature.canCreate) - } - - @Test - func aDisabledJavaSupportIsOfferedOnceForItsOwnTemplates() async throws { - let javaSupport = try Self.source(Self.javaSupportDirectory, enabled: true) - let environment = try Self.environment(plugins: PluginStates(enabled: []), sources: [javaSupport]) - let feature = NewProjectFeatureModel(environment: environment) - await feature.load() - #expect(feature.selectedEntry?.pluginEnabled == false) - // The Java requirement is Java Support itself, so only the Maven - // build system is left to find. - #expect(feature.requirementNotices.map(\.action) == [.findInMarketplace("maven")]) - } - - @Test - func derivedFieldsFollowTheProjectNameUntilEdited() async throws { - let plugins = PluginStates(enabled: [Self.templatesPluginID]) - let feature = NewProjectFeatureModel(environment: try Self.environment(plugins: plugins)) - await feature.load() - let spring = try #require(feature.entries.first { $0.generator.id == "spring-boot" }) - feature.selection = .generator(spring.id) - let artifact = try #require(spring.generator.fields.first { $0.id == "artifactId" }) - - feature.projectName = "billing" - #expect(feature.value(of: artifact) == .string("billing")) - feature.setValue(.string("billing-api"), for: artifact) - feature.projectName = "payments" - #expect(feature.value(of: artifact) == .string("billing-api")) - } - // MARK: Tool fields: Rust Core @Test @@ -530,7 +272,8 @@ struct ProjectGenerationTests { let plugins = PluginStates(enabled: [Self.toolFieldPluginID]) let feature = NewProjectFeatureModel(environment: try Self.environment( plugins: plugins, - sources: [try Self.toolFieldSource(tool: "java", enabled: true), try Self.toolDefinitionSource()] + sources: [try Self.toolFieldSource(tool: "java", enabled: true), try Self.toolDefinitionSource()], + toolInstallations: { _ in [:] } )) await feature.load() let field = try #require(feature.selectedEntry?.generator.fields.first { $0.id == "python" }) @@ -642,63 +385,6 @@ struct ProjectGenerationTests { RustProjectGeneratorOperations(core: RustCoreBridge()) } - private static func source(_ directory: String, enabled: Bool) throws -> ProjectGeneratorPluginSource { - let descriptor = try DeclarativePluginTestSupport.officialDescriptor(directory) - return ProjectGeneratorPluginSource( - pluginID: descriptor.id, - manifest: descriptor.normalizedManifest, - packageURL: DeclarativePluginTestSupport.officialPackageURL(directory), - isEnabled: enabled - ) - } - - /// Java Support split into a language-only plugin with its real ID and a - /// generator-only plugin, both enabled. - private static func splitJavaSupport() throws -> (language: ProjectGeneratorPluginSource, templates: ProjectGeneratorPluginSource) { - let javaSupport = try source(javaSupportDirectory, enabled: true) - guard let manifest = try JSONSerialization.jsonObject(with: javaSupport.manifest) as? [String: Any], - var languageRequires = manifest["requires"] as? [String: Any] else { - throw CocoaError(.coderReadCorrupt) - } - var language = manifest - language["projectGenerators"] = nil - // The language half keeps the debug adapter it declares, so it keeps - // the debug permissions that adapter needs. - language["permissions"] = ["languageServer.launch", "debug.launch", "debug.attach"] - languageRequires["projectGenerators"] = nil - language["requires"] = languageRequires - var templates = manifest - // The template half requires only projectGenerators, so every other - // capability contribution leaves with its requirement. - for key in ["languages", "languageServers", "settings", "debugAdapters", "toolDefinitions"] { templates[key] = nil } - templates["id"] = templatesPluginID.rawValue - templates["displayName"] = "Java Templates" - templates["permissions"] = ["project.generate"] - templates["requires"] = ["projectGenerators": 1] - // This separate template fixture is not the host-pinned bundled Java - // package, so it does not inherit that package's origin trust. - var templateVendor = manifest["vendor"] as? [String: Any] ?? [:] - templateVendor["bundledSignatureRequirement"] = nil - templates["vendor"] = templateVendor - templates["activationEvents"] = [String]() - func plugin(_ object: [String: Any], id: PluginID) throws -> ProjectGeneratorPluginSource { - ProjectGeneratorPluginSource( - pluginID: id, - manifest: try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), - packageURL: javaSupport.packageURL, - isEnabled: true - ) - } - return (try plugin(language, id: javaSupport.pluginID), try plugin(templates, id: templatesPluginID)) - } - - private static func target(_ generatorID: String) throws -> ProjectGeneratorTarget { - let source = try source(javaSupportDirectory, enabled: true) - return ProjectGeneratorTarget( - pluginID: source.pluginID, generatorID: generatorID, manifest: source.manifest, packageURL: source.packageURL - ) - } - private static func downloadPlatform(maximumBytes: Int64) -> MacProjectGenerationPlatform { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [GeneratorServerURLProtocol.self] @@ -723,18 +409,44 @@ struct ProjectGenerationTests { private static func service( runner: any BuildCommandRunning = ScaffoldingRunner(creates: nil), - recorder: JavaHomeRecorder = JavaHomeRecorder(), saveToolPin: @escaping @Sendable (URL, ProjectGenerationPlan.ToolPin) async throws -> Void = { _, _ in } ) -> ProjectGenerationService { ProjectGenerationService( planner: planner, platform: platform(runner: runner), initializeGitRepository: { _ in nil }, - recordJavaHome: { root, home in await recorder.record(root: root, home: home) }, saveToolPin: saveToolPin ) } + /// The window's environment over the given plugin sources; `plugins` + /// decides which of them count as enabled on each reload. + private static func environment( + plugins: PluginStates, + sources: [ProjectGeneratorPluginSource], + toolInstallations: @escaping @MainActor ([String]) async throws -> [String: [ProjectToolInstallation]] = { _ in [:] }, + pluginChanges: AnyPublisher = Empty().eraseToAnyPublisher() + ) throws -> NewProjectEnvironment { + NewProjectEnvironment( + sources: { + sources.map { + ProjectGeneratorPluginSource( + pluginID: $0.pluginID, manifest: $0.manifest, packageURL: $0.packageURL, + isEnabled: plugins.enabled.contains($0.pluginID) + ) + } + }, + iconResources: [:], + service: service(), + setPluginEnabled: { _ = plugins.enabled.insert($0) }, + openMarketplace: { _ in }, + openProject: { _ in }, + store: InMemoryStore(), + toolInstallations: toolInstallations, + pluginChanges: pluginChanges + ) + } + // MARK: Tool field fixtures /// The project-generator fixtures. The tool-field manifest's @@ -804,35 +516,6 @@ struct ProjectGenerationTests { } } - private static func environment( - plugins: PluginStates, - sources: [ProjectGeneratorPluginSource]? = nil, - toolInstallations: @escaping @MainActor ([String]) async throws -> [String: [ProjectToolInstallation]] = { _ in [:] }, - pluginChanges: AnyPublisher = Empty().eraseToAnyPublisher() - ) throws -> NewProjectEnvironment { - let split = try splitJavaSupport() - let installed = sources ?? [split.templates, split.language] - return NewProjectEnvironment( - sources: { - installed.map { - ProjectGeneratorPluginSource( - pluginID: $0.pluginID, manifest: $0.manifest, packageURL: $0.packageURL, - isEnabled: plugins.enabled.contains($0.pluginID) - ) - } - }, - iconResources: [:], - javaRuntimes: { [jdk] }, - service: service(), - setPluginEnabled: { _ = plugins.enabled.insert($0) }, - openMarketplace: { _ in }, - openProject: { _ in }, - store: InMemoryStore(), - toolInstallations: toolInstallations, - pluginChanges: pluginChanges - ) - } - private static func stagingEntries(in directory: URL) throws -> [String] { try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.contains(".lithe-creating-") } } @@ -887,19 +570,6 @@ private extension ProjectGeneratorPluginSource { } } -private struct Record: Equatable, Sendable { - let root: String - let home: String -} - -private actor JavaHomeRecorder { - private(set) var records: [Record] = [] - - func record(root: URL, home: String) { - records.append(Record(root: root.path, home: home)) - } -} - private struct SavedToolPin: Equatable, Sendable { let root: String let pin: ProjectGenerationPlan.ToolPin diff --git a/macos/Tests/LitheTests/ProjectRuntimeLoadingTests.swift b/macos/Tests/LitheTests/ProjectRuntimeLoadingTests.swift index d91e2ca233..6236d046fc 100644 --- a/macos/Tests/LitheTests/ProjectRuntimeLoadingTests.swift +++ b/macos/Tests/LitheTests/ProjectRuntimeLoadingTests.swift @@ -6,13 +6,13 @@ import Testing @MainActor struct ProjectRuntimeLoadingTests { @Test(arguments: ["complete", "switch", "cancel"]) - func versionProbesLeaveMainActorAvailableAndDiscardStaleDiscovery(outcome: String) async { + func hostProbeLeavesMainActorAvailableAndDiscardsStaleDiscovery(outcome: String) async { let (started, start) = AsyncStream.makeStream() let locator = LoadingRuntimeLocator(started: start) - let service = ProjectRuntimeService(runtimeLocator: locator, store: LoadingEmptyStore()) + let service = ProjectRuntimeService(runtimeLocator: locator) let root = URL(fileURLWithPath: "/fixture/workspace") service.openProject(at: root) - let load = Task { try await service.loadRunConfigurationToolchainCandidates( projectRoot: root) } + let load = Task { await service.ensureRuntimesDiscovered() } defer { locator.release(); start.finish(); load.cancel(); service.closeProject() } let received = await withTaskGroup(of: Bool.self) { group in group.addTask { for await _ in started { return true }; return false } @@ -27,24 +27,20 @@ struct ProjectRuntimeLoadingTests { } guard received else { locator.release() - _ = await load.result + await load.value Issue.record("Discovery did not reach its bounded worker gate") return } - // This code executes on MainActor while synchronous discovery is held. + // This code executes on MainActor while the synchronous host probe is held. if outcome == "switch" { service.openProject(at: URL(fileURLWithPath: "/fixture/other")) } if outcome == "cancel" { load.cancel() } locator.release() - switch await load.result { - case .success(let candidates): - #expect(outcome == "complete") - #expect(candidates.map(\.id) == ["project-jdk", "project-maven"]) - #expect(candidates.map(\.version) == ["21.0.1", "3.9.9"]) - case .failure(let error): - #expect(outcome != "complete") - #expect(error is CancellationError) - #expect(service.chooseJavaHome(overridePath: nil, detected: { nil }) == nil) - } + await load.value + #expect(locator.firstProbeSawCancellation == (outcome == "cancel")) + // A completed probe is remembered; a discarded one runs again on the next request. + let probes = locator.probeCount + await service.ensureRuntimesDiscovered() + #expect(locator.probeCount == (outcome == "complete" ? probes : probes + 1)) #expect(!locator.probedOnMainThread) } @@ -54,60 +50,49 @@ struct ProjectRuntimeLoadingTests { defer { start.finish() } let locator = LoadingRuntimeLocator(started: start) locator.release() - let service = ProjectRuntimeService(runtimeLocator: locator, store: LoadingEmptyStore()) + let service = ProjectRuntimeService(runtimeLocator: locator) defer { service.closeProject() } service.openProject(at: URL(fileURLWithPath: "/fixture/workspace")) await service.ensureRuntimesDiscovered() await service.ensureRuntimesDiscovered() #expect(locator.invalidations == 0) + #expect(locator.probeCount == 1) await service.refreshAvailableRuntimes() #expect(locator.invalidations == 1) + #expect(locator.probeCount == 2) #expect(!locator.probedOnMainThread) } } -private struct LoadingEmptyStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} -} - private final class LoadingRuntimeLocator: RuntimeLocator, @unchecked Sendable { private let gate = NSCondition() private let started: AsyncStream.Continuation private var released = false private var mainThread = false private var invalidationCount = 0 - private let java = JavaRuntimeCandidate(homePath: "/fixture/jdk", version: "21.0.1", vendor: "fixture") + private var probes = 0 + private var cancellationAtFirstProbeEnd: Bool? init(started: AsyncStream.Continuation) { self.started = started } var probedOnMainThread: Bool { gate.lock(); defer { gate.unlock() }; return mainThread } var invalidations: Int { gate.lock(); defer { gate.unlock() }; return invalidationCount } + var probeCount: Int { gate.lock(); defer { gate.unlock() }; return probes } + var firstProbeSawCancellation: Bool { gate.lock(); defer { gate.unlock() }; return cancellationAtFirstProbeEnd ?? false } func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { RuntimeDiscoveryResult(javaRuntimes: discoverJavaRuntimes(), mavenRuntimes: []) } - func discoverJavaRuntimes() -> [JavaRuntimeCandidate] { + func probeHost(isCancelled: @Sendable () -> Bool) { gate.lock() defer { gate.unlock() } mainThread = mainThread || Thread.isMainThread + probes += 1 + let isFirst = probes == 1 started.yield(()) let deadline = Date().addingTimeInterval(2) while !released { // Bounded native gate: production-owned dispatch worker exercises a synchronous locator with a bounded native gate. - guard gate.wait(until: deadline) else { return [] } + guard gate.wait(until: deadline) else { break } } - return [java] + if isFirst { cancellationAtFirstProbeEnd = isCancelled() } } func invalidateProbeCache() { gate.lock(); defer { gate.unlock() }; invalidationCount += 1 } func release() { gate.lock(); released = true; gate.broadcast(); gate.unlock() } - private func recordProbe() { gate.lock(); defer { gate.unlock() }; mainThread = mainThread || Thread.isMainThread } - func validJavaHome(path: String) -> URL? { path == java.homePath ? URL(fileURLWithPath: path) : nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { recordProbe(); return java } func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { URL(fileURLWithPath: "/fixture/maven/bin/mvn") } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { - recordProbe() - return MavenRuntimeCandidate(homePath: "/fixture/maven", executablePath: executableURL.path, version: "3.9.9") - } } diff --git a/macos/Tests/LitheTests/ProjectRuntimePersistenceTests.swift b/macos/Tests/LitheTests/ProjectRuntimePersistenceTests.swift deleted file mode 100644 index fe05a0c313..0000000000 --- a/macos/Tests/LitheTests/ProjectRuntimePersistenceTests.swift +++ /dev/null @@ -1,233 +0,0 @@ -import Foundation -import LitheCoreContracts -import Testing -@testable import Lithe - -@Suite("Project runtime canonical persistence", .serialized) -@MainActor -struct ProjectRuntimePersistenceTests { - @Test(arguments: [false, true]) - func migratesSubprojectPathsIntoExistingCanonicalDefaultsWithoutReplacingSavedChoices(existingPaths: Bool) throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - var legacy = ProjectRuntimeSettings(javaHomePath: "/fixture/old-project-jdk") - legacy.setOverride(path: "services/a", javaHomePath: "/fixture/a-jdk", mavenExecutablePath: "/fixture/a-mvn") - legacy.setOverride(path: "services/b", mavenExecutablePath: "./mvnw", mavenJavaHomePath: "/fixture/b-maven-jdk") - preferences.set(try JSONEncoder().encode(legacy), forKey: key) - let local = root.appendingPathComponent(".lithe/run/local.json") - try FileManager.default.createDirectory(at: local.deletingLastPathComponent(), withIntermediateDirectories: true) - var toolchain: [String: Any] = ["java": ["homePath": "/fixture/saved-project-jdk"]] - if existingPaths { toolchain["pathOverrides"] = ["services/a": ["javaHomePath": "/fixture/saved-a-jdk"]] } - try JSONSerialization.data(withJSONObject: ["version": 2, "toolchain": toolchain, "configurations": []]).write(to: local) - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - let migrated = try store.load(at: root, migrateLegacy: true) - #expect(migrated.settings.javaHomePath == "/fixture/saved-project-jdk") - #expect(migrated.settings.exactOverride(for: "services/a")?.javaHomePath == (existingPaths ? "/fixture/saved-a-jdk" : "/fixture/a-jdk")) - #expect(migrated.settings.exactOverride(for: "services/b")?.mavenExecutablePath == (existingPaths ? nil : "./mvnw")) - let preferenceData = try #require(preferences.data(forKey: key)) - let cleaned = try #require(JSONSerialization.jsonObject(with: preferenceData) as? [String: Any]) - #expect(cleaned["moduleOverrides"] == nil) - let bytes = try Data(contentsOf: local) - let reopened = try store.load(at: root, migrateLegacy: false) - #expect(reopened.settings == migrated.settings) - #expect(try Data(contentsOf: local) == bytes) - var edited = reopened.settings - edited.setOverride(path: "services/a", javaHomePath: "/fixture/edited-a-jdk") - let saved = try store.save(edited, at: root, expecting: reopened) - #expect(saved.settings.exactOverride(for: "services/a")?.javaHomePath == "/fixture/edited-a-jdk") - #expect(try store.load(at: root, migrateLegacy: false).settings == saved.settings) - #expect(saved.settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/a/module").javaHomePath == "/fixture/edited-a-jdk") - #expect(saved.settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/another").javaHomePath == "/fixture/saved-project-jdk") - } - - @Test(arguments: ["outside", "duplicate", "unknown"]) - func invalidSubprojectPathRetainsLegacyDataAndDoesNotCreateCanonicalDocument(kind: String) throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - let path = kind == "outside" ? "../escape" : "services/a" - var overrides: [[String: Any]] = [["path": path, "javaHomePath": "/fixture/jdk"]] - if kind == "duplicate" { overrides.append(["path": path, "javaHomePath": "/fixture/another-jdk"]) } - if kind == "unknown" { overrides[0]["futureField"] = "preserve-this-value" } - let original = try JSONSerialization.data(withJSONObject: ["moduleOverrides": overrides]) - preferences.set(original, forKey: key) - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - #expect(throws: (any Error).self) { try store.load(at: root, migrateLegacy: true) } - #expect(preferences.data(forKey: key) == original) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/local.json").path)) - } - - @Test(arguments: [false, true]) - func migratesLegacyOnlyAfterReadingTheCanonicalSelection(existingCanonical: Bool) throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let core = RustCoreBridge() - try #require(core.isAvailable) - let store = MacProjectRuntimeSettingsStore(core: core, storage: MacFileStorage(), preferences: preferences) - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - let legacy = ProjectRuntimeSettings(javaHomePath: "/fixture/old-jdk", mavenHomeSelection: .wrapper, - mavenJavaHomePath: "/fixture/old-maven-jdk") - var document = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(legacy)) as? [String: Any]) - document["futurePreference"] = true - document["mavenSettingsPath"] = "/fixture/settings.xml" - let original = try JSONSerialization.data(withJSONObject: document) - preferences.set(original, forKey: key) - let expected = existingCanonical ? ProjectToolchainSelection() : legacy.projectToolchainSelection() - if existingCanonical { - // Explicit automatic is a saved choice and wins over old overrides. - try MacRunConfigurationStore(core: core, storage: MacFileStorage(), preferences: preferences) - .saveProjectToolchain(expected, at: root) - } - let readOnly = try store.load(at: root, migrateLegacy: false) - #expect(preferences.data(forKey: key) == original) - #expect(readOnly.settings.projectToolchainSelection() == ProjectToolchainSelection()) - let migrated = try store.load(at: root, migrateLegacy: true) - #expect(migrated.settings.projectToolchainSelection() == expected) - let savedPreferences = try #require(preferences.data(forKey: key)) - let cleaned = try #require(JSONSerialization.jsonObject(with: savedPreferences) as? [String: Any]) - for field in ["javaHomePath", "mavenHomePath", "mavenHomeSelection", "mavenJavaHomePath"] { - #expect(cleaned[field] == nil) - } - #expect(cleaned["futurePreference"] as? Bool == true) - #expect(cleaned["mavenSettingsPath"] as? String == "/fixture/settings.xml") - let local = root.appendingPathComponent(".lithe/run/local.json") - let bytes = try Data(contentsOf: local) - _ = try store.load(at: root, migrateLegacy: true) - #expect(try Data(contentsOf: local) == bytes) - #expect(preferences.data(forKey: key) == savedPreferences) - let ignore = try String(contentsOf: root.appendingPathComponent(".lithe/.gitignore"), encoding: .utf8) - #expect(ignore.contains("run/local.json")) - } - - @Test - func invalidCanonicalDocumentPreservesBothSourcesAndBlocksRuntimeSelection() throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - let legacy = try JSONEncoder().encode(ProjectRuntimeSettings(javaHomePath: "/fixture/old-jdk")) - preferences.set(legacy, forKey: key) - let local = root.appendingPathComponent(".lithe/run/local.json") - try FileManager.default.createDirectory(at: local.deletingLastPathComponent(), withIntermediateDirectories: true) - let invalid = Data("{broken".utf8) - try invalid.write(to: local) - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - #expect(throws: (any Error).self) { try store.load(at: root, migrateLegacy: true) } - let service = ProjectRuntimeService(runtimeLocator: ProjectRuntimeSettingsTestLocator(), settingsStore: store) - service.openProject(at: root) - #expect(service.javaHomeURL() == nil) - #expect(service.mavenExecutable(at: root) == nil) - #expect(service.settingsError != nil) - #expect(preferences.data(forKey: key) == legacy) - #expect(try Data(contentsOf: local) == invalid) - } - - @Test(arguments: [false, true]) - func nonDataRuntimePreferenceCannotBecomeAutomaticOrBeRemovedByMigration(migrate: Bool) throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - preferences.set("retain the malformed preference", forKey: key) - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - #expect(throws: (any Error).self) { try store.load(at: root, migrateLegacy: migrate) } - let service = ProjectRuntimeService(runtimeLocator: ProjectRuntimeSettingsTestLocator(), settingsStore: store) - service.openProject(at: root) - #expect(service.javaHomeURL() == nil) - #expect(service.mavenExecutable(at: root) == nil) - #expect(service.settingsError != nil) - #expect(preferences.object(forKey: key) as? String == "retain the malformed preference") - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/local.json").path)) - } - - @Test - func draftCancelSaveReadBackAndExternalEditUseTheSameSource() throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - let service = ProjectRuntimeService(runtimeLocator: ProjectRuntimeSettingsTestLocator(), settingsStore: store) - let feature = RuntimeSettingsFeatureModel(service: service) - service.openProject(at: root) - prepare(feature, root: root) - let local = root.appendingPathComponent(".lithe/run/local.json") - #expect(!FileManager.default.fileExists(atPath: local.path)) - feature.updateSettings { $0.javaHomePath = "/fixture/draft-jdk" } - #expect(!FileManager.default.fileExists(atPath: local.path)) - #expect(service.settings.javaHomePath.isEmpty) - feature.cancelChanges() - #expect(!feature.hasChanges) - #expect(feature.saveSettings()) - feature.finishSaving() - #expect(!FileManager.default.fileExists(atPath: local.path)) - feature.updateSettings { $0.javaHomePath = "/fixture/saved-jdk" } - #expect(feature.saveSettings()) - #expect(feature.isSaving) - feature.updateSettings { $0.javaHomePath = "/fixture/blocked-edit" } - #expect(feature.settings.javaHomePath == "/fixture/saved-jdk") - #expect(!feature.saveSettings()) - feature.finishSaving() - #expect(service.javaHomeURL()?.path == "/fixture/saved-jdk") - #expect(!feature.hasChanges) - let baseline = try store.load(at: root, migrateLegacy: false) - var external = baseline.settings - external.javaHomePath = "/fixture/external-jdk" - _ = try store.save(external, at: root, expecting: baseline) - feature.updateSettings { $0.javaHomePath = "/fixture/kept-draft" } - // A launch refreshes its source while a settings draft is open. It must - // not replace that draft's baseline and make a stale save appear valid. - #expect(service.javaHomeURL()?.path == "/fixture/external-jdk") - #expect(!feature.saveSettings()) - #expect(feature.settings.javaHomePath == "/fixture/kept-draft") - #expect(feature.settingsError != nil) - #expect(try store.load(at: root, migrateLegacy: false).settings.javaHomePath == "/fixture/external-jdk") - feature.cancelChanges() - #expect(feature.settings.javaHomePath == "/fixture/external-jdk") - #expect(!feature.hasChanges) - let other = try workspace() - defer { try? FileManager.default.removeItem(at: other) } - let otherSnapshot = try store.load(at: other, migrateLegacy: false) - #expect(throws: (any Error).self) { try store.save(otherSnapshot.settings, at: root, expecting: otherSnapshot) } - service.closeProject() - service.openProject(at: root) - #expect(service.javaHomeURL()?.path == "/fixture/external-jdk") - } - - @Test - func failedMigrationRetainsLegacyPreferences() throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let preferences = RuntimeMigrationPreferences() - let key = MacProjectRuntimeSettingsStore.preferencesKey(root) - let original = try JSONEncoder().encode(ProjectRuntimeSettings(javaHomePath: "/fixture/jdk")) - preferences.set(original, forKey: key) - var storage = MacFileStorage() - storage.unsupportedExchangeForTesting = true - let store = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: storage, preferences: preferences) - #expect(throws: (any Error).self) { try store.load(at: root, migrateLegacy: true) } - #expect(preferences.data(forKey: key) == original) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/local.json").path)) - } - - private func workspace() throws -> URL { - let root = FileManager.default.temporaryDirectory.appendingPathComponent("runtime-canonical-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - return root - } - private func prepare(_ feature: RuntimeSettingsFeatureModel, root: URL) { - feature.prepare(workspaceName: "fixture", workspaceURL: root, files: []) - } -} - -private final class RuntimeMigrationPreferences: KeyValueStore { - private var values: [String: Any] = [:] - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } -} diff --git a/macos/Tests/LitheTests/ProjectRuntimeSettingsTests.swift b/macos/Tests/LitheTests/ProjectRuntimeSettingsTests.swift deleted file mode 100644 index ede08cdce0..0000000000 --- a/macos/Tests/LitheTests/ProjectRuntimeSettingsTests.swift +++ /dev/null @@ -1,276 +0,0 @@ -import Foundation -import LitheModuleAPI -import LitheCoreContracts -import Testing -@testable import Lithe - -@Suite("Project runtime settings") -struct ProjectRuntimeSettingsTests { - @Test - func overlayPrefersRunConfigurationThenSubprojectThenProjectJDK() { - var settings = ProjectRuntimeSettings(javaHomePath: "/jdk-21") - settings.setOverride(path: "services/alpha", javaHomePath: "/jdk-17") - - #expect( - settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/beta").javaHomePath - == "/jdk-21" - ) - #expect( - settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/alpha").javaHomePath - == "/jdk-17" - ) - #expect( - settings.overlay( - onto: RunOptions(), - workspaceRelativePath: "services/alpha/module-a" - ).javaHomePath == "/jdk-17" - ) - #expect( - settings.overlay( - onto: RunOptions(javaHomePath: "/jdk-8"), - workspaceRelativePath: "services/alpha" - ).javaHomePath == "/jdk-8" - ) - #expect( - settings.overlay( - onto: RunOptions(javaHomePath: "/jdk-21"), - workspaceRelativePath: "services/alpha" - ).javaHomePath == "/jdk-17" - ) - } - - @Test - func emptySubprojectOverrideInheritsProjectMavenHome() { - var settings = ProjectRuntimeSettings( - mavenHomeSelection: .custom, - mavenHomePath: "/opt/maven" - ) - settings.setOverride(path: "services/alpha", javaHomePath: "/jdk-17") - - let options = settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/alpha") - #expect(options.javaHomePath == "/jdk-17") - #expect(options.mavenExecutablePath == "/opt/maven") - } - - @Test - func nestedSubprojectOverrideKeepsParentOverride() { - var settings = ProjectRuntimeSettings(javaHomePath: "/jdk-21") - settings.setOverride(path: "services/alpha", javaHomePath: "/jdk-17") - settings.setOverride(path: "services/alpha/api", javaHomePath: "/jdk-11") - - #expect(settings.exactOverride(for: "services/alpha")?.javaHomePath == "/jdk-17") - #expect(settings.exactOverride(for: "services/alpha/api")?.javaHomePath == "/jdk-11") - #expect( - settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/alpha").javaHomePath - == "/jdk-17" - ) - #expect( - settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/alpha/api").javaHomePath - == "/jdk-11" - ) - #expect( - settings.overlay( - onto: RunOptions(), - workspaceRelativePath: "services/alpha/api/impl" - ).javaHomePath == "/jdk-11" - ) - - settings.setOverride(path: "services/alpha/api", javaHomePath: "") - #expect(settings.exactOverride(for: "services/alpha/api") == nil) - #expect(settings.exactOverride(for: "services/alpha")?.javaHomePath == "/jdk-17") - #expect( - settings.overlay(onto: RunOptions(), workspaceRelativePath: "services/alpha/api").javaHomePath - == "/jdk-17" - ) - } - - @Test - func inventoryUsesProviderHierarchyAndDeclarationsInsteadOfGuessingFromFileNames() { - let root = URL(fileURLWithPath: "/workspace/fixture") - let files = ["engine.marker", "ghost/engine.marker", "pom.xml", "package.json"].map { root.appendingPathComponent($0) } - let language = LanguageSupportDeclaration(id: "java", displayName: "Java", projectFileNames: ["engine.marker"]) - let model = BuildModel(projects: [ - .init(id: "root", path: ".", name: "Root"), - .init(id: "library", path: "active/library", name: "Engine library", parentID: "root"), - .init(id: "nested", path: "active/library/nested", name: "Engine child", parentID: "library") - ]) - let sources: [ProjectRuntimeInventory.BuildSource] = [.init(id: "generic:root", root: ".", displayName: "Generic", usesJava: true, model: model)] - let rows = ProjectRuntimeInventory.subprojects(workspaceName: "fixture", workspaceURL: root, files: files, - buildSources: sources, languageSupports: [language]) - #expect(rows.map(\.id) == ["project", "path:active/library", "path:active/library/nested"]) - #expect(rows.last?.parentID == "path:active/library") - #expect(rows.last?.title == "Engine child") - #expect(rows.allSatisfy { $0.usesJava }) - #expect(ProjectRuntimeInventory.subprojects(workspaceName: "fixture", workspaceURL: root, files: files, - buildSources: [], languageSupports: []).map(\.id) == ["project"]) - let passive = ProjectRuntimeInventory.subprojects(workspaceName: "fixture", workspaceURL: root, files: files, - buildSources: [], languageSupports: [language]) - #expect(passive.map(\.id) == ["project", "path:ghost"]) - #expect(passive.last?.kind == .other) - } - - @Test - func overlappingSourcesShareOneDirectoryAndDoNotExposeOutsideFiles() { - let root = URL(fileURLWithPath: "/workspace/fixture") - let model = BuildModel(projects: [.init(id: "library", path: "services/library", name: "Library")]) - let rows = ProjectRuntimeInventory.subprojects(workspaceName: "fixture", workspaceURL: root, - files: [URL(fileURLWithPath: "/outside/engine.marker")], - buildSources: [ - .init(id: "first", root: "services/library", displayName: "First", usesJava: false, model: model), - .init(id: "second", root: "services/library", displayName: "Second", usesJava: true, model: nil), - .init(id: "outside", root: "../outside", displayName: "Outside", usesJava: false, model: nil) - ], languageSupports: [.init(id: "java", displayName: "Java", projectFileNames: ["engine.marker"])]) - #expect(rows.map(\.id) == ["project", "path:services/library"]) - #expect(rows.last?.usesJava == true) - } - - @Test - func inventoryListsIndependentBackendsAndFrontendRoots() { - let root = URL(fileURLWithPath: "/workspace/shop", isDirectory: true) - let alpha = BuildModel(projects: [ - .init(id: "alpha", path: "services/alpha", name: "alpha"), - .init(id: "api", path: "services/alpha/api", name: "alpha-api", parentID: "alpha") - ]) - let files = [ - root.appendingPathComponent("services/alpha/pom.xml"), - root.appendingPathComponent("services/alpha/api/pom.xml"), - root.appendingPathComponent("services/beta/pom.xml"), - root.appendingPathComponent("frontend/package.json") - ] - - let subprojects = ProjectRuntimeInventory.subprojects( - workspaceName: "shop", - workspaceURL: root, - files: files, - buildSources: [.init(id: "sample:alpha", root: "services/alpha", displayName: "Build root", usesJava: true, model: alpha)], - languageSupports: [ - LanguageSupportDeclaration(id: "java", displayName: "Java", projectFileNames: ["pom.xml"]), - LanguageSupportDeclaration(id: "frontend", displayName: "Frontend", projectFileNames: ["package.json"]) - ] - ) - - #expect(subprojects.map(\.id) == [ - "project", - "path:services/alpha", - "path:services/alpha/api", - "path:frontend", - "path:services/beta" - ]) - #expect(subprojects.first { $0.id == "path:services/beta" }?.usesJava == true) - #expect(subprojects.first { $0.id == "path:frontend" }?.usesJava == false) - #expect( - ProjectRuntimeInventory.workspaceRelativePath( - modulePath: ".", - workingDirectory: "services/beta" - ) == "services/beta" - ) - } - - @Test - func settingsCategoryPlacesBuildPagesBetweenKeymapAndTerminal() { - // The build group (toolchain pages, project environment, run configurations) - // stays contiguous in declaration order, so search results list the pages in - // the same order as the sidebar and run configurations still follow the - // project environment they inherit. - let cases = SettingsCategory.allCases - guard let keymap = cases.firstIndex(of: .keymap), - let terminal = cases.firstIndex(of: .terminal) else { - Issue.record("Keymap and Terminal must both be settings pages") - return - } - #expect(Array(cases[(keymap + 1)..? - var discoveredJavaRuntimes: [JavaRuntimeCandidate] = [] - - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: discoveredJavaRuntimes, mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { - if let validJavaHomes { - return validJavaHomes.contains(path) ? URL(fileURLWithPath: path, isDirectory: true) : nil - } - return URL(fileURLWithPath: path, isDirectory: true) - } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { - JavaRuntimeCandidate(homePath: homeURL.path, version: "21", vendor: "Test") - } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} diff --git a/macos/Tests/LitheTests/ProjectRuntimeTestSupport.swift b/macos/Tests/LitheTests/ProjectRuntimeTestSupport.swift index 58a93b826d..3f0867f8eb 100644 --- a/macos/Tests/LitheTests/ProjectRuntimeTestSupport.swift +++ b/macos/Tests/LitheTests/ProjectRuntimeTestSupport.swift @@ -2,34 +2,13 @@ import Foundation import LitheCoreContracts @testable import Lithe -/// Runtime selection unit tests use an explicit, isolated source. Persistence -/// and migration are exercised separately against Core and temporary files. -@MainActor -final class InMemoryProjectRuntimeSettingsStore: ProjectRuntimeSettingsStoring { - var values: [URL: ProjectRuntimeSettingsSnapshot] = [:] - var failure: (any Error)? - private var revision = 0 - func load(at workspace: URL, migrateLegacy: Bool) throws -> ProjectRuntimeSettingsSnapshot { - if let failure { throw failure } - return values[workspace] ?? ProjectRuntimeSettingsSnapshot(workspaceURL: workspace, settings: ProjectRuntimeSettings(), revision: "missing") - } - func save(_ settings: ProjectRuntimeSettings, at workspace: URL, - expecting snapshot: ProjectRuntimeSettingsSnapshot) throws -> ProjectRuntimeSettingsSnapshot { - let current = try load(at: workspace, migrateLegacy: false) - guard snapshot.workspaceURL == workspace, current.revision == snapshot.revision else { throw ProjectRuntimeSettingsStoreError.conflict } - revision += 1 - let saved = ProjectRuntimeSettingsSnapshot(workspaceURL: workspace, settings: settings, revision: String(revision), hasSavedToolchain: true) - values[workspace] = saved - return saved - } -} - +/// Tool lookup tests use an explicit, isolated locator. The runtime service +/// keeps no persisted settings, so the store argument only keeps older call +/// sites that still pass an isolated defaults store compiling. @MainActor extension ProjectRuntimeService { convenience init(runtimeLocator: any RuntimeLocator, store _: any KeyValueStore, - toolDiscovery: (any RuntimeToolDiscovery)? = nil, - javaSelector: any JavaRuntimeSelecting = RustCoreBridge()) { - self.init(runtimeLocator: runtimeLocator, settingsStore: InMemoryProjectRuntimeSettingsStore(), - toolDiscovery: toolDiscovery, javaSelector: javaSelector) + toolDiscovery: (any RuntimeToolDiscovery)? = nil) { + self.init(runtimeLocator: runtimeLocator, toolDiscovery: toolDiscovery) } } diff --git a/macos/Tests/LitheTests/ProjectTreeLoaderTests.swift b/macos/Tests/LitheTests/ProjectTreeLoaderTests.swift index 6dce7bee9b..56d0038c5e 100644 --- a/macos/Tests/LitheTests/ProjectTreeLoaderTests.swift +++ b/macos/Tests/LitheTests/ProjectTreeLoaderTests.swift @@ -121,12 +121,12 @@ struct ProjectTreeLoaderTests { } @Test - func expandingCompactedPackageReusesItsListing() throws { + func expandingCompactedDirectoryChainReusesItsListing() throws { let root = URL(fileURLWithPath: "/in-memory/lookahead") - let source = root.appendingPathComponent("src/main/java") + let source = root.appendingPathComponent("sources") let com = source.appendingPathComponent("com") let package = com.appendingPathComponent("example") - let file = package.appendingPathComponent("Main.java") + let file = package.appendingPathComponent("Main.txt") let cache = ProjectDirectoryListingCache() let generation = cache.prepare(at: root, rules: .default) let disk: [String: [ProjectDirectoryEntry]] = [ @@ -142,7 +142,7 @@ struct ProjectTreeLoaderTests { }) } - let first = try #require(loader.childRows(of: [FileNode(url: source, isDirectory: true, children: nil)])) + let first = try #require(loader.childRows(of: [FileNode(url: source, isDirectory: true, children: nil, isInsideSourceRoot: true)])) let rows = try #require(first[source.path]) #expect(rows.count == 1) #expect(rows.first?.url == package) @@ -192,10 +192,10 @@ struct ProjectTreeLoaderTests { @Test func failedCompactionListingDoesNotPublishPartialRows() { - let source = URL(fileURLWithPath: "/in-memory/lookahead/src/main/java") + let source = URL(fileURLWithPath: "/in-memory/lookahead/sources") let loader = ProjectTreeLoader { directories in directories == [source] ? [source.path: [.init(url: source.appendingPathComponent("com"), isDirectory: true)]] : nil } - #expect(loader.childRows(of: [FileNode(url: source, isDirectory: true, children: nil)]) == nil) + #expect(loader.childRows(of: [FileNode(url: source, isDirectory: true, children: nil, isInsideSourceRoot: true)]) == nil) } } diff --git a/macos/Tests/LitheTests/ProjectTreeSelectionTests.swift b/macos/Tests/LitheTests/ProjectTreeSelectionTests.swift index f209438570..48bbd2562b 100644 --- a/macos/Tests/LitheTests/ProjectTreeSelectionTests.swift +++ b/macos/Tests/LitheTests/ProjectTreeSelectionTests.swift @@ -171,7 +171,7 @@ struct ProjectTreeSelectionTests { collapsedAncestorPaths: collapsed) } let root = node("/p", [ - node("/p/src", [node("/p/src/com/acme", [node("/p/src/com/acme/App.java")], + node("/p/src", [node("/p/src/com/acme", [node("/p/src/com/acme/App.txt")], collapsed: ["/p/src/com"])]), node("/p/README.md") ]) @@ -192,7 +192,7 @@ struct ProjectTreeSelectionTests { press(.right) #expect(expanded.isSuperset(of: ["/p/src/com/acme", "/p/src/com"])) press(.down) - #expect(selection.focusedPath == "/p/src/com/acme/App.java") + #expect(selection.focusedPath == "/p/src/com/acme/App.txt") press(.left) #expect(selection.focusedPath == "/p/src/com/acme") press(.left) @@ -511,7 +511,7 @@ struct ProjectTreeSelectionTests { let root = node("/p", [ node("/p/dest", [node("/p/dest/a.txt")]), node("/p/dest copy", [node("/p/dest copy/a.txt"), node("/p/dest copy/b.txt")]), - node("/p/src", [node("/p/src/com/acme", [node("/p/src/com/acme/App.java")], collapsed: ["/p/src/com"])]), + node("/p/src", [node("/p/src/com/acme", [node("/p/src/com/acme/App.txt")], collapsed: ["/p/src/com"])]), node("/p/alpha.txt"), node("/p/gamma.txt") ]) let topLevel: Set = ["/p/dest", "/p/dest copy", "/p/src", "/p/alpha.txt", "/p/gamma.txt"] @@ -532,11 +532,11 @@ struct ProjectTreeSelectionTests { #expect(selectAll(focusing: "/p/dest/a.txt") == ["/p/dest/a.txt"]) // Compacted packages use their displayed parent. #expect(selectAll(focusing: "/p/src/com/acme") == ["/p/src/com/acme"]) - #expect(selectAll(focusing: "/p/src/com/acme/App.java") == ["/p/src/com/acme/App.java"]) + #expect(selectAll(focusing: "/p/src/com/acme/App.txt") == ["/p/src/com/acme/App.txt"]) // Folder selection highlights only the folder, independent of descendants. #expect(selectAll(focusing: "/p/dest copy") == topLevel) #expect(!selection.covers("/p/dest copy/a.txt")) - #expect(!selection.covers("/p/src/com/acme/App.java")) + #expect(!selection.covers("/p/src/com/acme/App.txt")) #expect(!selection.paths.contains("/p/dest copy/a.txt")) // Right-clicking an unselected descendant targets only that row. selection.selectForContextMenu("/p/dest copy/a.txt") @@ -589,7 +589,7 @@ struct ProjectTreeSelectionTests { @Test func flattenedRowsKeepDisplayedDepthAndCollapsedDirectoriesAtomic() { - let leaf = FileNode(url: URL(fileURLWithPath: "/p/src/com/acme/Main.java"), isDirectory: false, children: nil) + let leaf = FileNode(url: URL(fileURLWithPath: "/p/src/com/acme/Main.txt"), isDirectory: false, children: nil) let package = FileNode(url: URL(fileURLWithPath: "/p/src/com/acme"), isDirectory: true, children: [leaf]) let root = FileNode(url: URL(fileURLWithPath: "/p"), isDirectory: true, children: [package]) let collapsed = ProjectTreeSelection.visibleRows(in: root, expandedPaths: ["/p"]) diff --git a/macos/Tests/LitheTests/ProviderWorkflowPresentationTests.swift b/macos/Tests/LitheTests/ProviderWorkflowPresentationTests.swift index 3e22d96407..3ffe8a68ac 100644 --- a/macos/Tests/LitheTests/ProviderWorkflowPresentationTests.swift +++ b/macos/Tests/LitheTests/ProviderWorkflowPresentationTests.swift @@ -45,7 +45,7 @@ struct ProviderWorkflowPresentationTests { let feature = BuildSystemsFeatureModel(service: service) try await WorkbenchTestScope.withCleanup({ await model.shutdownProjectSession() }) { _ in feature.reset(workspaceURL: root) - _ = try await service.prepareLanguageImport(workspaceURL: root) + try await service.awaitDetection(workspaceURL: root) let entryID = try #require(feature.entries.first?.id) let loaded = TestGate() let loadedObservation = service.$entries.sink { if $0.first?.modelState == .loaded { loaded.open() } } diff --git a/macos/Tests/LitheTests/RealJavaDebugIntegrationTests.swift b/macos/Tests/LitheTests/RealJavaDebugIntegrationTests.swift deleted file mode 100644 index 3485d07d6f..0000000000 --- a/macos/Tests/LitheTests/RealJavaDebugIntegrationTests.swift +++ /dev/null @@ -1,884 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheDebugModule -import LitheLanguageIntelligenceModule -import LitheModuleAPI -import LitheTerminalModule -import Testing -@testable import Lithe - -@Suite("Real Java Debug integration", .serialized) -@MainActor -struct RealJavaDebugIntegrationTests { - @Test - func springRequestHitsBreakpointInspectsStepsAndResumes() async throws { - let environment = ProcessInfo.processInfo.environment - guard environment["LITHE_RUN_JAVA_DEBUG_INTEGRATION"] == "1" else { return } - - let repositoryRoot = Self.repositoryRoot - let fileManager = FileManager.default - // The same package the application ships: JDT LS, its extensions and - // the JDK are located only through the plugin's own declaration. - let javaSupport = try RealJavaSupportPackage(environment: environment) - let javaURL = javaSupport.javaURL - - let rootURL = fileManager.temporaryDirectory.appendingPathComponent( - "lithe-real-java-debug-\(UUID().uuidString)", - isDirectory: true - ) - let cacheURL = fileManager.temporaryDirectory.appendingPathComponent( - "\(rootURL.lastPathComponent)-jdtls-cache", - isDirectory: true - ) - let fixtureURL = repositoryRoot.appendingPathComponent( - "shared/fixtures/projects/lithe-spring-boot-git-graph", - isDirectory: true - ) - try fileManager.copyItem(at: fixtureURL, to: rootURL) - let mainURL = rootURL.appendingPathComponent( - "src/main/java/com/example/demo/DemoApplication.java" - ) - let serviceURL = rootURL.appendingPathComponent( - "src/main/java/com/example/demo/user/UserService.java" - ) - let serviceSource = try String(contentsOf: serviceURL, encoding: .utf8) - let serviceBreakpointLine = try #require(Self.line( - containing: "return repository.findAll();", - in: serviceSource - )) - let serviceConstructorLine = try #require(Self.line( - containing: "this.repository = repository;", - in: serviceSource - )) - let controllerSource = try String(contentsOf: rootURL.appendingPathComponent( - "src/main/java/com/example/demo/user/UserController.java" - ), encoding: .utf8) - let controllerURL = rootURL.appendingPathComponent( - "src/main/java/com/example/demo/user/UserController.java" - ) - let controllerBreakpointLine = try #require(Self.line( - containing: "return service.listUsers();", - in: controllerSource - )) - - let core = RustCoreBridge() - #expect(core.isAvailable) - guard core.isAvailable else { return } - let resources = javaSupport.resources - - let descriptor = try #require(LanguageProviderCatalog.standard.provider(for: mainURL)) - let launch = try #require(descriptor.languageServerLaunch) - let languageSession = LanguageServerRuntimeSession( - providerID: descriptor.id, - executableURL: javaURL, - arguments: launch.arguments, - environment: environment, - initializationOptions: launch.initializationOptions, - launchResolver: { try javaSupport.resolveLaunch(workspaceRootURL: $0) }, - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch( - runtimeExecutableURL: javaURL, - coreLaunch: .jdt(resources) - ), - cacheDirectoryURL: cacheURL, - initializeTimeout: 120, - requestTimeout: 120, - shutdownTimeout: 5, - core: core - ) - let languageRuntime = RealJavaDebugLanguageRuntime( - descriptor: descriptor, - session: languageSession - ) - let languageManager = LanguageToolingSessionManager( - catalog: LanguageProviderCatalog(descriptors: [descriptor]), - runtimes: [languageRuntime], - builtinCore: core - ) - let protocolTrace = RealJavaDebugProtocolTrace() - let debugManager = DebugAdapterSessionManager( - providers: [DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] - )] - ) { _, _ in - CoreDebugAdapterProtocolSession( - adapterID: "java", - transport: RealJavaDebugRecordingTransport( - wrapping: MacHostedPortDebugAdapterTransport( - portResolver: { rootURL in - try await languageManager.startJavaDebugServer(rootURL: rootURL) - }, - core: core - ), - trace: protocolTrace - ), - core: core, - deadlineScheduler: MacDebugOperationDeadlineScheduler() - ) - } - let feature = GenericDebugFeatureModel(paging: RustCoreBridge(), sessions: debugManager) - let debugTerminals = RealJavaDebugTerminalOwner(workspaceURL: rootURL) - feature.onRunInTerminalRequest = debugTerminals.handle - let portAllocator = MacJavaTestResultServer() - let springPort = try await portAllocator.start() - portAllocator.stop() - var requestTask: Task<(Data, URLResponse), Error>? - defer { - requestTask?.cancel() - feature.stop() - debugTerminals.stop() - languageManager.stopAll() - try? fileManager.removeItem(at: rootURL) - try? fileManager.removeItem(at: cacheURL) - } - - let mainSource = try String(contentsOf: mainURL, encoding: .utf8) - try languageManager.synchronizeLanguageServer( - for: mainURL, - text: mainSource, - rootURL: rootURL - ) - let target: JavaDebugLaunchTarget - do { - target = try await languageManager.resolveJavaDebugLaunchTarget( - fileURL: mainURL, - rootURL: rootURL - ) - } catch { - throw RealJavaDebugIntegrationError.languageToolingFailed( - message: String(describing: error), - logs: String(describing: languageManager.languageServerStates) - ) - } - // The dependency projection asks the same server for each project's - // runtime classpath. The temporary workspace sits behind `/var`, so - // this also covers projects JDT reports at their resolved location. - #expect(await Self.waitUntil(timeout: .seconds(60)) { - languageManager.dependencySnapshot(workspaceURL: rootURL)? - .dependencyRoots.contains { $0.lastPathComponent.hasPrefix("spring-boot-") } == true - }, "JDT LS did not report the project's runtime dependencies.") - // Start at the controller call so the real integration test exercises - // both Java step-into and step-out, not only a step-over at a leaf line. - feature.toggleBreakpoint(fileURL: controllerURL, line: controllerBreakpointLine) - feature.toggleBreakpoint(fileURL: serviceURL, line: serviceBreakpointLine) - feature.toggleBreakpoint(fileURL: serviceURL, line: serviceConstructorLine) - // Verify the Java adapter receives and honors the condition field, - // rather than only exercising an unconditional source breakpoint. - feature.updateBreakpoint( - fileURL: controllerURL, - line: controllerBreakpointLine, - enabled: true, - condition: "true", - hitCondition: "1", - logMessage: nil - ) - // A logpoint must emit a Debug Console message without stopping the - // application. Keep it on the constructor so it is exercised during - // Spring Boot startup before the HTTP request breakpoint. - feature.updateBreakpoint( - fileURL: serviceURL, - line: serviceConstructorLine, - enabled: true, - condition: nil, - hitCondition: nil, - logMessage: "entered UserService constructor" - ) - var arguments: [String: ToolingJSONValue] = [ - "mainClass": .string(target.mainClass), - "cwd": .string(rootURL.path), - "console": .string("integratedTerminal"), - "args": .string("--server.port=\(springPort)") - ] - if let projectName = target.projectName { - arguments["projectName"] = .string(projectName) - } - if !target.modulePaths.isEmpty { - arguments["modulePaths"] = .array(target.modulePaths.map(ToolingJSONValue.string)) - } - if !target.classPaths.isEmpty { - arguments["classPaths"] = .array(target.classPaths.map(ToolingJSONValue.string)) - } - #expect(feature.start( - fileURL: mainURL, - rootURL: rootURL, - configuration: DebugLaunchConfiguration( - name: "Spring Debug Integration", - request: .launch, - arguments: arguments - ) - )) - - #expect(await Self.waitUntil(timeout: .seconds(120)) { - feature.state == .running - }, "Java Debug Server did not reach the running state. Output:\n\(feature.output)") - #expect(await Self.waitUntil(timeout: .seconds(120)) { - feature.breakpoints.count == 3 && feature.breakpoints.allSatisfy(\.verified) - }, "The Java breakpoints were not verified. Output:\n\(feature.output)") - #expect( - protocolTrace.entries.contains { $0.contains("\"condition\":\"true\"") }, - "The Java condition breakpoint was not sent to the adapter." - ) - #expect( - protocolTrace.entries.contains { $0.contains("\"hitCondition\":\"1\"") }, - "The Java hit-count breakpoint was not sent to the adapter." - ) - #expect( - protocolTrace.entries.contains { - $0.contains("\"logMessage\":\"entered UserService constructor\"") - }, - "The Java logpoint was not sent to the adapter." - ) - guard await Self.waitForSpringServer(port: springPort, timeout: .seconds(120)) else { - throw RealJavaDebugIntegrationError.springServerDidNotStart( - "expectedPort=\(springPort)\n" + Self.debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - #expect( - feature.output.contains("entered UserService constructor"), - "The Java logpoint did not produce a Debug Console message." - ) - - var request = URLRequest( - url: URL(string: "http://127.0.0.1:\(springPort)/api/users")! - ) - request.timeoutInterval = 60 - requestTask = Task { try await URLSession.shared.data(for: request) } - guard await Self.waitUntil(timeout: .seconds(60), condition: { - feature.state == .paused - }) else { - throw RealJavaDebugIntegrationError.debuggerDidNotPause( - Self.debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - guard await Self.waitUntil(timeout: .seconds(30), condition: { - feature.selectedFrame?.sourceURL?.standardizedFileURL - == controllerURL.standardizedFileURL - && feature.selectedFrame?.line == controllerBreakpointLine - }) else { - throw RealJavaDebugIntegrationError.stoppedFrameUnavailable( - Self.debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - #expect(await Self.waitUntil(timeout: .seconds(30)) { - !feature.variables.isEmpty - }, "No variables were loaded for the stopped Java frame.") - // Exercise the same frame-scoped evaluation path used by the Debug - // console and inline inspection, not only the variables request. - let outputBeforeEvaluation = feature.output - feature.evaluate("service") - #expect(await Self.waitUntil(timeout: .seconds(30)) { - feature.output.count > outputBeforeEvaluation.count - && feature.output.contains("service =") - }, "The stopped Java frame did not evaluate the service expression.") - - feature.execute(.stepIn) - #expect(await Self.waitUntil(timeout: .seconds(30)) { - feature.state == .paused - && feature.selectedFrame?.sourceURL?.standardizedFileURL - == serviceURL.standardizedFileURL - && feature.selectedFrame?.line == serviceBreakpointLine - }, "Step into did not enter UserService.listUsers().\n\(Self.debugSnapshot(feature, protocolTrace: protocolTrace))") - - feature.execute(.stepOut) - #expect(await Self.waitUntil(timeout: .seconds(30)) { - feature.state == .paused - && feature.selectedFrame?.sourceURL?.standardizedFileURL - == controllerURL.standardizedFileURL - && feature.selectedFrame?.line == controllerBreakpointLine - }, "Step out did not return to UserController.list().\n\(Self.debugSnapshot(feature, protocolTrace: protocolTrace))") - - let frameBeforeStepOver = try #require(feature.selectedFrame) - feature.execute(.next) - #expect(await Self.waitUntil(timeout: .seconds(30)) { - feature.state == .paused && feature.selectedFrame?.id != frameBeforeStepOver.id - }, "Step over did not reach the next Java source position.\n\(Self.debugSnapshot(feature, protocolTrace: protocolTrace))") - feature.execute(.continueExecution) - guard await Self.waitUntil(timeout: .seconds(10), condition: { - feature.state == .running || feature.state == .terminated - }) else { - throw RealJavaDebugIntegrationError.debuggerDidNotResume( - "Continue did not leave the paused state.\n" + Self.debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - - let response: (Data, URLResponse) - do { - response = try await Self.value(of: try #require(requestTask), timeout: .seconds(60)) - } catch { - throw RealJavaDebugIntegrationError.debuggerDidNotResume( - "(error)\n" + Self.debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - let httpResponse = try #require(response.1 as? HTTPURLResponse) - #expect(httpResponse.statusCode == 200) - let body = String(decoding: response.0, as: UTF8.self) - #expect(body.contains("Ada Lovelace")) - #expect(body.contains("Grace Hopper")) - } - - @Test - func junitMethodHitsBreakpointAndResumes() async throws { - try await Self.runJavaTestDebug(.junit) - } - - @Test - func testngMethodHitsBreakpointAndResumes() async throws { - try await Self.runJavaTestDebug(.testng) - } - - private static func runJavaTestDebug(_ scenario: RealJavaTestDebugScenario) async throws { - let environment = ProcessInfo.processInfo.environment - guard environment["LITHE_RUN_JAVA_TEST_DEBUG_INTEGRATION"] == "1" else { return } - - let repositoryRoot = Self.repositoryRoot - let fileManager = FileManager.default - // The same package the application ships: JDT LS, its extensions and - // the JDK are located only through the plugin's own declaration. - let javaSupport = try RealJavaSupportPackage(environment: environment) - let javaURL = javaSupport.javaURL - - let rootURL = fileManager.temporaryDirectory.appendingPathComponent( - "lithe-real-java-test-debug-\(scenario.rawValue)-\(UUID().uuidString)", - isDirectory: true - ) - let cacheURL = fileManager.temporaryDirectory.appendingPathComponent( - "\(rootURL.lastPathComponent)-jdtls-cache", - isDirectory: true - ) - let fixtureURL = repositoryRoot.appendingPathComponent( - "shared/fixtures/projects/lithe-spring-boot-git-graph", - isDirectory: true - ) - try fileManager.copyItem(at: fixtureURL, to: rootURL) - defer { - try? fileManager.removeItem(at: rootURL) - try? fileManager.removeItem(at: cacheURL) - } - try scenario.prepareProject(at: rootURL, fileManager: fileManager) - let testURL = rootURL.appendingPathComponent( - "src/test/java/com/example/demo/user/UserServiceTest.java" - ) - let testSource = try String(contentsOf: testURL, encoding: .utf8) - let breakpointLine = try #require(line( - containing: scenario.breakpointNeedle, - in: testSource - )) - - let braceLine = try #require(testSource.components(separatedBy: .newlines) - .firstIndex { $0.trimmingCharacters(in: .whitespaces) == "}" }).advanced(by: 1) - #expect(DebugBreakpointLocationValidator.canSetSourceBreakpoint(source: testSource, line: braceLine)) - - let core = RustCoreBridge() - #expect(core.isAvailable) - guard core.isAvailable else { return } - let resources = javaSupport.resources - - let descriptor = try #require(LanguageProviderCatalog.standard.provider(for: testURL)) - let launch = try #require(descriptor.languageServerLaunch) - let languageSession = LanguageServerRuntimeSession( - providerID: descriptor.id, - executableURL: javaURL, - arguments: launch.arguments, - environment: environment, - initializationOptions: launch.initializationOptions, - launchResolver: { try javaSupport.resolveLaunch(workspaceRootURL: $0) }, - hostIntegrationLaunch: LanguageServerHostIntegrationLaunch( - runtimeExecutableURL: javaURL, - coreLaunch: .jdt(resources) - ), - cacheDirectoryURL: cacheURL, - initializeTimeout: 120, - requestTimeout: 120, - shutdownTimeout: 5, - core: core - ) - let languageRuntime = RealJavaDebugLanguageRuntime( - descriptor: descriptor, - session: languageSession - ) - let languageManager = LanguageToolingSessionManager( - catalog: LanguageProviderCatalog(descriptors: [descriptor]), - runtimes: [languageRuntime], - builtinCore: core - ) - let protocolTrace = RealJavaDebugProtocolTrace() - let debugManager = DebugAdapterSessionManager( - providers: [DebugProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"] - )] - ) { _, _ in - CoreDebugAdapterProtocolSession( - adapterID: "java", - transport: RealJavaDebugRecordingTransport( - wrapping: MacHostedPortDebugAdapterTransport( - portResolver: { rootURL in - try await languageManager.startJavaDebugServer(rootURL: rootURL) - }, - core: core - ), - trace: protocolTrace - ), - core: core, - deadlineScheduler: MacDebugOperationDeadlineScheduler() - ) - } - let feature = GenericDebugFeatureModel(paging: RustCoreBridge(), sessions: debugManager) - let debugTerminals = RealJavaDebugTerminalOwner(workspaceURL: rootURL) - feature.onRunInTerminalRequest = debugTerminals.handle - let launchService = JavaTestDebugLaunchService( - configurationResolver: DebugLaunchConfigurationResolver( - javaTestLaunchResolver: core - ), - resultServerFactory: { MacJavaTestResultServer() } - ) - defer { - feature.stop() - debugTerminals.stop() - languageManager.stopAll() - } - - let prepared: PreparedJavaTestDebugLaunch - do { - prepared = try await launchService.prepare( - fileURL: testURL, - testIdentifier: scenario.testIdentifier, - rootURL: rootURL, - targetResolver: languageManager - ) - } catch { - throw RealJavaDebugIntegrationError.languageToolingFailed( - message: String(describing: error), - logs: String(describing: languageManager.languageServerStates) - ) - } - defer { prepared.stop() } - - #expect(prepared.target.framework == scenario.framework) - feature.toggleBreakpoint(fileURL: testURL, line: breakpointLine) - feature.toggleBreakpoint(fileURL: testURL, line: braceLine) - #expect(feature.start( - fileURL: testURL, - rootURL: rootURL, - configuration: prepared.configuration - )) - - guard await waitUntil(timeout: .seconds(120), condition: { - feature.state == .paused - }) else { - throw RealJavaDebugIntegrationError.debuggerDidNotPause( - debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - #expect( - feature.breakpoints.first(where: { $0.line == breakpointLine })?.verified == true, - "The Java test breakpoint was not verified.\n\(debugSnapshot(feature, protocolTrace: protocolTrace))" - ) - guard await waitUntil(timeout: .seconds(30), condition: { - feature.selectedFrame?.sourceURL?.standardizedFileURL - == testURL.standardizedFileURL - && feature.selectedFrame?.line == breakpointLine - }) else { - throw RealJavaDebugIntegrationError.stoppedFrameUnavailable( - debugSnapshot(feature, protocolTrace: protocolTrace) - ) - } - #expect(await waitUntil(timeout: .seconds(30)) { - feature.variables.contains { $0.name == scenario.expectedVariable } - }, "The stopped Java test frame did not expose \(scenario.expectedVariable).") - - let brace = try #require(feature.breakpoints.first(where: { $0.line == braceLine })) - // Placement remains saved whether the adapter can bind this brace or not. - #expect(feature.breakpoints.count == 2) - feature.removeBreakpoint(brace) - feature.execute(.continueExecution) - #expect(await waitUntil(timeout: .seconds(60)) { - feature.state == .terminated - }, "Java test Debug did not terminate.\n\(debugSnapshot(feature, protocolTrace: protocolTrace))") - } - - private static var repositoryRoot: URL { - URL(fileURLWithPath: #filePath) - .deletingLastPathComponent() - .deletingLastPathComponent() - .deletingLastPathComponent() - .deletingLastPathComponent() - } - - private static func line(containing needle: String, in source: String) -> Int? { - source.split(separator: "\n", omittingEmptySubsequences: false) - .firstIndex { $0.contains(needle) } - .map { $0 + 1 } - } - - private static func debugSnapshot( - _ feature: GenericDebugFeatureModel, - protocolTrace: RealJavaDebugProtocolTrace - ) -> String { - let breakpointSummary = feature.breakpoints.map { - "\($0.title) enabled=\($0.enabled) verified=\($0.verified) message=\($0.message ?? "nil")" - }.joined(separator: "\n") - let threadSummary = feature.threads.map { "\($0.id):\($0.name)" }.joined(separator: ", ") - let recentTrace = protocolTrace.entries.suffix(40).joined(separator: "\n") - return """ - state=\(feature.state) - stoppedReason=\(feature.stoppedReason ?? "nil") - selectedThreadID=\(feature.selectedThreadID.map(String.init) ?? "nil") - selectedFrame=\(feature.selectedFrame.map { "\($0.name) @ \($0.line)" } ?? "nil") - threads=\(threadSummary) - breakpoints: - \(breakpointSummary) - output: - \(feature.output) - Recent DAP trace: - \(recentTrace) - """ - } - - private static func waitForSpringServer( - port: UInt16, - timeout: Duration - ) async -> Bool { - let clock = ContinuousClock() - let deadline = clock.now.advanced(by: timeout) - let url = URL(string: "http://127.0.0.1:\(port)/")! - while clock.now < deadline { - var request = URLRequest(url: url) - request.timeoutInterval = 2 - do { - _ = try await URLSession.shared.data(for: request) - return true - } catch { - // Spring Boot may still be starting while the debuggee is - // already attached and accepting debugger requests. - } - // test-stability: allow(swift-real-sleep) reason: The external Spring process exposes readiness only through its loopback listener. - try? await Task.sleep(for: .milliseconds(100)) - } - return false - } - - private static func waitUntil( - timeout: Duration, - condition: @escaping @MainActor () -> Bool - ) async -> Bool { - let clock = ContinuousClock() - let deadline = clock.now.advanced(by: timeout) - while clock.now < deadline { - if condition() { return true } - // test-stability: allow(swift-real-sleep) reason: External JDT LS and JVM state arrives only through production process callbacks. - try? await Task.sleep(for: .milliseconds(25)) - } - return condition() - } - - private static func value( - of task: Task, - timeout: Duration - ) async throws -> T { - try await withThrowingTaskGroup(of: T.self) { group in - group.addTask { try await task.value } - group.addTask { - // test-stability: allow(swift-real-sleep) reason: The real HTTP request needs a local deadline independent of the test runner. - try await Task.sleep(for: timeout) - throw RealJavaDebugIntegrationError.timedOut - } - defer { group.cancelAll() } - return try await group.next()! - } - } -} - -private enum RealJavaTestDebugScenario: String { - case junit - case testng - - var framework: JavaTestDebugFramework { - switch self { - case .junit: .junit - case .testng: .testng - } - } - - var testIdentifier: String { - switch self { - case .junit: "com.example.demo.user.UserServiceTest#addsNumbers()" - case .testng: "com.example.demo.user.UserServiceTest#multipliesNumbers()" - } - } - - var breakpointNeedle: String { - switch self { - case .junit: "int total = left + right;" - case .testng: "int product = left * right;" - } - } - - var expectedVariable: String { - switch self { - case .junit: "left" - case .testng: "left" - } - } - - func prepareProject(at rootURL: URL, fileManager: FileManager) throws { - let testDirectory = rootURL.appendingPathComponent( - "src/test/java/com/example/demo/user", - isDirectory: true - ) - try fileManager.createDirectory( - at: testDirectory, - withIntermediateDirectories: true - ) - let sourceURL = testDirectory.appendingPathComponent("UserServiceTest.java") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - guard self == .testng else { return } - - let pomURL = rootURL.appendingPathComponent("pom.xml") - var pom = try String(contentsOf: pomURL, encoding: .utf8) - guard let insertion = pom.range(of: "") else { - throw RealJavaDebugIntegrationError.invalidFixture("Missing Maven dependencies section") - } - pom.insert(contentsOf: testNGDependency, at: insertion.lowerBound) - try pom.write(to: pomURL, atomically: true, encoding: .utf8) - } - - private var source: String { - switch self { - case .junit: - """ - package com.example.demo.user; - - import static org.junit.jupiter.api.Assertions.assertEquals; - - import org.junit.jupiter.api.Test; - - class UserServiceTest { - @Test void addsNumbers() { - int left = 20; - int right = 22; - int total = left + right; - assertEquals(42, total); - } - } - """ - case .testng: - """ - package com.example.demo.user; - - import org.testng.Assert; - import org.testng.annotations.Test; - - public class UserServiceTest { - @Test - public void multipliesNumbers() { - int left = 6; - int right = 7; - int product = left * right; - Assert.assertEquals(product, 42); - } - } - """ - } - } - - private var testNGDependency: String { - """ - - org.testng - testng - 7.10.2 - test - - """ - } -} - -@MainActor -private final class RealJavaDebugTerminalOwner { - private let workspaceURL: URL - private let feature = TerminalFeatureModel( - terminalFactory: { MacTerminalTransport() } - ) - - init(workspaceURL: URL) { - self.workspaceURL = workspaceURL.standardizedFileURL - } - - func handle( - _ request: DebugRunInTerminalRequest, - completion: @escaping DebugRunInTerminalCompletion - ) { - do { - guard request.kind == .integrated else { - throw RealJavaDebugTerminalError.externalTerminalUnsupported - } - guard !request.argsCanBeInterpretedByShell else { - throw RealJavaDebugTerminalError.shellInterpretationUnsupported - } - guard let executablePath = request.args.first, !executablePath.isEmpty else { - throw RealJavaDebugTerminalError.missingExecutable - } - let workingDirectory = request.cwd.isEmpty ? workspaceURL.path : request.cwd - guard workingDirectory.hasPrefix("/") else { - throw RealJavaDebugTerminalError.invalidWorkingDirectory - } - let launch = TerminalProcessLaunch( - title: request.title, - executablePath: executablePath, - arguments: Array(request.args.dropFirst()), - workingDirectory: workingDirectory, - environmentChanges: request.environment.map { - TerminalEnvironmentChange(name: $0.name, value: $0.value) - } - ) - let created = try feature.createProcessSession(launch) - completion(.success(DebugRunInTerminalResponse(processID: Int(created.processID)))) - } catch { - completion(.failure(error)) - } - } - - func stop() { - feature.stopAllSessions() - } -} - -private enum RealJavaDebugTerminalError: Error { - case externalTerminalUnsupported - case shellInterpretationUnsupported - case missingExecutable - case invalidWorkingDirectory -} - -@MainActor -private final class RealJavaDebugProtocolTrace { - private(set) var entries: [String] = [] - - func record(direction: String, data: Data) { - entries.append("\(direction) \(Self.payload(in: data))") - } - - private static func payload(in data: Data) -> String { - guard let text = String(data: data, encoding: .utf8), - let separator = text.range(of: "\r\n\r\n") else { - return String(decoding: data, as: UTF8.self) - } - return String(text[separator.upperBound...]) - } -} - -@MainActor -private final class RealJavaDebugRecordingTransport: DebugAdapterTransport { - private let wrapped: any DebugAdapterTransport - private let trace: RealJavaDebugProtocolTrace - - var isRunning: Bool { wrapped.isRunning } - var onData: ((Data) -> Void)? - var onErrorOutput: ((Data) -> Void)? - var onTermination: ((Int) -> Void)? - - init( - wrapping wrapped: any DebugAdapterTransport, - trace: RealJavaDebugProtocolTrace - ) { - self.wrapped = wrapped - self.trace = trace - wrapped.onData = { [weak self] data in - self?.trace.record(direction: "<-", data: data) - self?.onData?(data) - } - wrapped.onErrorOutput = { [weak self] data in self?.onErrorOutput?(data) } - wrapped.onTermination = { [weak self] code in self?.onTermination?(code) } - } - - func start(rootURL: URL) throws { - try wrapped.start(rootURL: rootURL) - } - - func send(_ data: Data) throws { - trace.record(direction: "->", data: data) - try wrapped.send(data) - } - - func stop() { - wrapped.stop() - } -} - -@MainActor -private final class RealJavaDebugLanguageRuntime: LanguageProviderRuntime { - let descriptor: LanguageProviderDescriptor - let supportsLanguageServerSession = true - private let session: any LanguageServerSession - - init(descriptor: LanguageProviderDescriptor, session: any LanguageServerSession) { - self.descriptor = descriptor - self.session = session - } - - func makeLanguageServerSession() -> (any LanguageServerSession)? { session } -} - -private enum RealJavaDebugIntegrationError: Error { - case timedOut - case languageToolingFailed(message: String, logs: String) - case springServerDidNotStart(String) - case debuggerDidNotPause(String) - case debuggerDidNotResume(String) - case stoppedFrameUnavailable(String) - case invalidFixture(String) -} - -/// The assembled Java Support plugin package, resolved the way the application -/// resolves it: Rust Core expands the declaration, and the `jdt` integration -/// receives only the files the plugin names. -@MainActor -private struct RealJavaSupportPackage { - let javaURL: URL - let resources: JDTLSLaunchResources - private let source: DeclarativeLanguageServerLaunchSource - private let resolver: MacPluginLanguageServerLaunchResolver - private let stateRootURL: URL - - /// Build the package first with - /// `scripts/plugins/build-official-plugins.sh --bundled-only --triple ` - /// and pass the directory it prints, plus the plugin ID, as - /// `LITHE_JAVA_SUPPORT_PACKAGE`. The default is the debug output of a - /// local build. - init(environment: [String: String]) throws { - let packageURL = URL( - fileURLWithPath: environment["LITHE_JAVA_SUPPORT_PACKAGE"] - ?? DeclarativePluginTestSupport.repositoryRoot - .appendingPathComponent(".build/out/Products/Debug/OfficialPlugins") - .appendingPathComponent(OfficialPluginCatalog.javaPluginID.rawValue).path, - isDirectory: true - ).standardizedFileURL - let operations = DeclarativePluginTestSupport.operations - let descriptor = try operations.validate( - manifest: Data(contentsOf: packageURL.appendingPathComponent("plugin.json")) - ) - source = DeclarativeLanguageServerLaunchSource( - pluginID: descriptor.id.rawValue, - languageID: "java", - manifest: descriptor.normalizedManifest, - packageURL: packageURL - ) - stateRootURL = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-real-java-plugin-state-\(UUID().uuidString)", isDirectory: true) - resolver = MacPluginLanguageServerLaunchResolver( - planner: operations, - directories: MacPluginStateDirectories(rootURL: stateRootURL), - settings: InMemoryPluginSettings() - ) - javaURL = try #require(try resolver.executableProbe(for: source).packagedRuntimeURL) - let integration = try #require(try resolver.hostIntegration(for: source)) - resources = try MacJdtLaunchResources().resources(from: integration, javaRuntimes: []) - } - - func resolveLaunch(workspaceRootURL: URL) throws -> ResolvedLanguageServerLaunch { - try resolver.resolve(source, workspaceRootURL: workspaceRootURL) - } -} diff --git a/macos/Tests/LitheTests/RealPhpIntegrationTests.swift b/macos/Tests/LitheTests/RealPhpIntegrationTests.swift index 13c46ed236..2c05a5ae3d 100644 --- a/macos/Tests/LitheTests/RealPhpIntegrationTests.swift +++ b/macos/Tests/LitheTests/RealPhpIntegrationTests.swift @@ -99,7 +99,6 @@ struct RealPhpIntegrationTests { arguments: launch.arguments, environment: environment, initializationOptions: .object(["storagePath": .string(cacheURL.path)]), - cacheDirectoryURL: cacheURL, initializeTimeout: 60, requestTimeout: 60, shutdownTimeout: 5, diff --git a/macos/Tests/LitheTests/RemoteDirectoryObservationTests.swift b/macos/Tests/LitheTests/RemoteDirectoryObservationTests.swift index 52e31a2896..9111306d7a 100644 --- a/macos/Tests/LitheTests/RemoteDirectoryObservationTests.swift +++ b/macos/Tests/LitheTests/RemoteDirectoryObservationTests.swift @@ -62,8 +62,8 @@ struct RemoteDirectoryObservationTests { #expect(host.requests == ["one:/host/project"]) host.emit(.started) #expect(batches.values.last?.requiresFullRescan == true) - host.emit(.changed(paths: ["/host/project/src/A.java", "/host/project-neighbor/a"], overflow: false)) - #expect(batches.values.last?.workspacePaths == [root.appendingPathComponent("src/A.java").path]) + host.emit(.changed(paths: ["/host/project/src/A.txt", "/host/project-neighbor/a"], overflow: false)) + #expect(batches.values.last?.workspacePaths == [root.appendingPathComponent("src/A.txt").path]) host.emit(.changed(paths: [], overflow: true)) #expect(batches.values.last?.requiresFullRescan == true) host.emit(.invalidated(rootRemoved: true)) @@ -84,8 +84,8 @@ struct RemoteDirectoryObservationTests { let host = WatchFixture() let files = RemoteRoutingFileOperations(local: MacWorkspaceFileOperations(), registry: registry, transport: host) let changes = WatchDocuments() - let a = root.appendingPathComponent("src/A.java") - let b = root.appendingPathComponent("B.java") + let a = root.appendingPathComponent("src/A.txt") + let b = root.appendingPathComponent("B.txt") let observation = files.observeDocuments(at: [a, b], onChange: changes.append) defer { observation.cancel(); host.finish() } #expect(await watchEventually { host.active == 1 }) diff --git a/macos/Tests/LitheTests/RemoteRuntimeDiscoveryTests.swift b/macos/Tests/LitheTests/RemoteRuntimeDiscoveryTests.swift index 1b2052f258..a9b42b450e 100644 --- a/macos/Tests/LitheTests/RemoteRuntimeDiscoveryTests.swift +++ b/macos/Tests/LitheTests/RemoteRuntimeDiscoveryTests.swift @@ -11,40 +11,36 @@ struct RemoteRuntimeDiscoveryTests { ) @Test - func discoversHostToolsAndNormalizesOnlyAgainstRemoteHome() throws { + func discoversHostToolsAndNormalizesOnlyAgainstRemoteHome() { let host = FixtureRuntimeHost() let locator = MacRemoteRuntimeLocator(binding: Self.binding, host: host) - let result = locator.discover() - #expect(result.javaRuntimes.map(\.homePath) == ["/host/jdk"]) - #expect(result.mavenRuntimes.map(\.version) == ["3.9.9"]) + locator.probeHost(isCancelled: { false }) #expect(locator.discoveryFailure == nil) - #expect(locator.normalizedPath("~/jdk", relativeTo: Self.binding.root) == "/host/home/jdk") - #expect(locator.normalizedPath("tools/java", relativeTo: Self.binding.root) == "/host/project/tools/java") - #expect(locator.normalizedPath(Self.binding.root.path + "/gradlew", relativeTo: nil) == "/host/project/gradlew") - #expect(locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/node"))) + #expect(locator.environment()["HOME"] == "/host/home") + #expect(locator.normalizedPath("~/tools", relativeTo: Self.binding.root) == "/host/home/tools") + #expect(locator.normalizedPath("tools/tool-b", relativeTo: Self.binding.root) == "/host/project/tools/tool-b") + #expect(locator.normalizedPath(Self.binding.root.path + "/run.sh", relativeTo: nil) == "/host/project/run.sh") + #expect(locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/tool-a"))) + #expect(locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/tool-b"))) #expect(!locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/not-executable"))) #expect(!locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/not-executable-link"))) - #expect(locator.validJavaHome(path: "/host/jdk")?.path == "/host/jdk") - #expect(locator.validJavaHome(path: "/fixture/local-jdk") == nil) + #expect(locator.candidates(for: "tool-b", projectURL: Self.binding.root, environment: ["PATH": "/host/bin"]) + .map(\.executableURL.path) == ["/host/bin/tool-b"]) let calls = host.callCount - let selection = try #require(locator.selectJavaRuntime( - candidates: [AutomaticJavaCandidate(id: "old", version: "17", priority: 0), - AutomaticJavaCandidate(id: "current", version: "21", priority: 1)], fallbackID: "old" - )).get() - #expect(selection.id == "current") + #expect(locator.candidates(for: "tool-a", projectURL: nil, environment: ["PATH": "/host/bin"]).count == 1) #expect(host.callCount == calls) } @Test func failedAndCancelledDiscoveryCannotPublishPartialOrLocalTools() { - let host = FixtureRuntimeHost(failsVersion: true) + let host = FixtureRuntimeHost(failsEnvironment: true) let locator = MacRemoteRuntimeLocator(binding: Self.binding, host: host) - #expect(locator.discover().javaRuntimes.isEmpty) + locator.probeHost(isCancelled: { false }) #expect(locator.discoveryFailure != nil) #expect(locator.environment().isEmpty) - #expect(locator.candidates(for: "node", projectURL: Self.binding.root, environment: ["PATH": "/host/bin"]).isEmpty) + #expect(locator.candidates(for: "tool-b", projectURL: Self.binding.root, environment: ["PATH": "/host/bin"]).isEmpty) let calls = host.callCount - #expect(locator.discover(isCancelled: { true }).javaRuntimes.isEmpty) + locator.probeHost(isCancelled: { true }) #expect(host.callCount == calls) } @@ -52,33 +48,33 @@ struct RemoteRuntimeDiscoveryTests { func invalidatedProbeCannotOverwriteANewerSnapshot() { let host = FixtureRuntimeHost() let locator = MacRemoteRuntimeLocator(binding: Self.binding, host: host) - host.beforeVersion = { locator.invalidateProbeCache() } - #expect(locator.discover().javaRuntimes.isEmpty) + host.beforeEnvironment = { locator.invalidateProbeCache() } + locator.probeHost(isCancelled: { false }) #expect(locator.environment().isEmpty) - host.beforeVersion = nil - #expect(locator.discover().javaRuntimes.count == 1) + #expect(!locator.isExecutable(at: URL(fileURLWithPath: "/host/bin/tool-b"))) + host.beforeEnvironment = nil + locator.probeHost(isCancelled: { false }) + #expect(locator.environment()["HOME"] == "/host/home") } @Test @MainActor - func projectSwitchUsesHostWorkersAndNewProjectAlwaysUsesLocalDiscovery() async { + func projectSwitchUsesHostWorkersAndLocalProjectsKeepLocalDiscovery() async { let host = FixtureRuntimeHost() let remote = MacRemoteRuntimeLocator(binding: Self.binding, host: host) let local = FixtureLocalRuntimeLocator() - let service = ProjectRuntimeService(runtimeLocator: local, settingsStore: InMemoryProjectRuntimeSettingsStore(), + let service = ProjectRuntimeService(runtimeLocator: local, workspaceRuntime: { $0 == Self.binding.root ? (remote, remote) : nil }) defer { service.closeProject() } service.openProject(at: Self.binding.root) await service.ensureRuntimesDiscovered() - #expect(service.javaRuntimes.map(\.homePath) == ["/host/jdk"]) - #expect(service.javaHomeURL()?.path == "/host/jdk") + #expect(service.executableCandidates("tool-b").map(\.executableURL.path) == ["/host/bin/tool-b"]) + #expect(service.processEnvironment()["HOME"] == "/host/home") #expect(!host.probedOnMainThread) let hostCalls = host.callCount - let newProject = await service.discoverJavaRuntimesForNewProject() - #expect(newProject.map(\.homePath) == ["/fixture/local-jdk"]) - #expect(host.callCount == hostCalls) service.openProject(at: URL(fileURLWithPath: "/fixture/local-project")) await service.ensureRuntimesDiscovered() - #expect(service.javaHomeURL()?.path == "/fixture/local-jdk") + #expect(service.executableCandidates("tool-b").map(\.executableURL.path) == ["/fixture/local-bin/tool-b"]) + #expect(service.processEnvironment()["HOME"] == nil) #expect(host.callCount == hostCalls) } } @@ -87,14 +83,14 @@ private final class FixtureRuntimeHost: RemoteRuntimeProbing, @unchecked Sendabl private let lock = NSLock() private var calls = 0 private var onMain = false - private var versionHook: (@Sendable () -> Void)? - let failsVersion: Bool - init(failsVersion: Bool = false) { self.failsVersion = failsVersion } + private var environmentHook: (@Sendable () -> Void)? + let failsEnvironment: Bool + init(failsEnvironment: Bool = false) { self.failsEnvironment = failsEnvironment } var callCount: Int { lock.withLock { calls } } var probedOnMainThread: Bool { lock.withLock { onMain } } - var beforeVersion: (@Sendable () -> Void)? { - get { lock.withLock { versionHook } } - set { lock.withLock { versionHook = newValue } } + var beforeEnvironment: (@Sendable () -> Void)? { + get { lock.withLock { environmentHook } } + set { lock.withLock { environmentHook = newValue } } } private func record(_ session: String) { #expect(session == "fixture-host") @@ -102,60 +98,27 @@ private final class FixtureRuntimeHost: RemoteRuntimeProbing, @unchecked Sendabl } func runtimeEnvironment(session: String) throws -> [String: String] { record(session) - return ["HOME": "/host/home", "JAVA_HOME": "/host/jdk", "PATH": "/host/bin"] - } - func runtimeRequirements(_ root: String, session: String) throws -> ToolingJSONValue { - record(session) - #expect(root == "/host/project") - return .object(["version": .integer(1), "toolchains": .object([ - "project-jdk": .object(["type": .string("java"), "minimumVersion": .string("21")]) - ])]) + beforeEnvironment?() + if failsEnvironment { throw RemoteProbeFailure(code: "connection_closed", message: "fixture disconnected") } + return ["HOME": "/host/home", "PATH": "/host/bin"] } func runtimeDirectory(_ path: String, session: String) throws -> [RemoteDirectoryEntry] { record(session) guard path == "/host/bin" else { return [] } return [ - RemoteDirectoryEntry(name: "java", metadata: .init(kind: "symlink", symlinkTargetKind: "file", symlinkTargetMode: 0o755)), - RemoteDirectoryEntry(name: "mvn", metadata: .init(kind: "file", mode: 0o755)), - RemoteDirectoryEntry(name: "node", metadata: .init(kind: "file", mode: 0o755)), + RemoteDirectoryEntry(name: "tool-a", metadata: .init(kind: "symlink", symlinkTargetKind: "file", symlinkTargetMode: 0o755)), + RemoteDirectoryEntry(name: "tool-b", metadata: .init(kind: "file", mode: 0o755)), RemoteDirectoryEntry(name: "not-executable", metadata: .init(kind: "file", mode: 0o644)), RemoteDirectoryEntry(name: "not-executable-link", metadata: .init(kind: "symlink", symlinkTargetKind: "file", symlinkTargetMode: 0o644)) ] } - func runtimeRealPath(_ path: String, session: String) throws -> String { - record(session) - return path == "/host/bin/java" ? "/host/jdk/bin/java" : path - } func runtimeExecutable(_ path: String, session: String) throws -> Bool { record(session) - return ["/host/jdk/bin/java", "/host/project/gradlew"].contains(path) - } - func runtimeVersion(_ executable: String, session: String) throws -> String { - record(session) - beforeVersion?() - if failsVersion { throw RemoteProbeFailure(code: "connection_closed", message: "fixture disconnected") } - return executable.hasSuffix("/java") ? "openjdk version \"21.0.1\"\nOpenJDK Runtime Environment" : "Apache Maven 3.9.9" + return false } } -private struct FixtureRuntimeStore: KeyValueStore { - func data(forKey key: String) -> Data? { nil } - func object(forKey key: String) -> Any? { nil } - func string(forKey key: String) -> String? { nil } - func stringArray(forKey key: String) -> [String]? { nil } - func set(_ value: Any?, forKey key: String) {} -} - private struct FixtureLocalRuntimeLocator: RuntimeLocator { - private let home = URL(fileURLWithPath: "/fixture/local-jdk") - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [JavaRuntimeCandidate(homePath: home.path, version: "21", vendor: "fixture")], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { path == home.path ? home : nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { discover().javaRuntimes.first } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } + func environment() -> [String: String] { ["PATH": "/fixture/local-bin"] } + func isExecutable(at url: URL) -> Bool { url.path == "/fixture/local-bin/tool-b" } } diff --git a/macos/Tests/LitheTests/RemoteTerminalTransportTests.swift b/macos/Tests/LitheTests/RemoteTerminalTransportTests.swift index 36412e0281..087b1260c3 100644 --- a/macos/Tests/LitheTests/RemoteTerminalTransportTests.swift +++ b/macos/Tests/LitheTests/RemoteTerminalTransportTests.swift @@ -20,8 +20,8 @@ struct RemoteTerminalTransportTests { let host = FixtureTerminalHost() let (transport, renderer) = terminal(host) defer { transport.stop(); host.finish() } - let launch = TerminalProcessLaunch(title: "Run", executablePath: "/host/jdk/bin/java", - arguments: ["-cp", "/host/project/classes with spaces", "Main"], + let launch = TerminalProcessLaunch(title: "Run", executablePath: "/host/tools/bin/tool-a", + arguments: ["--input", "/host/project/dir with spaces", "main"], workingDirectory: root.appendingPathComponent("module").path) let pid = try await transport.startProcessAsync(launch, environment: ["TERM": "xterm-256color"]) #expect(pid == 321) @@ -29,7 +29,7 @@ struct RemoteTerminalTransportTests { #expect(renderer.view.hasRemoteProcess) #expect(host.requests.first?.session == "host-one") #expect(host.requests.first?.request.cwd == "/host/project/module") - #expect(host.requests.first?.request.argv == ["/host/jdk/bin/java", "-cp", "/host/project/classes with spaces", "Main"]) + #expect(host.requests.first?.request.argv == ["/host/tools/bin/tool-a", "--input", "/host/project/dir with spaces", "main"]) try transport.send(Data("input\n".utf8)) #expect(await terminalEventually { !host.writes.isEmpty }) #expect(host.writes.first == Data("input\n".utf8)) diff --git a/macos/Tests/LitheTests/RunBrowserStateTests.swift b/macos/Tests/LitheTests/RunBrowserStateTests.swift index e4735833f0..8e5c5e814d 100644 --- a/macos/Tests/LitheTests/RunBrowserStateTests.swift +++ b/macos/Tests/LitheTests/RunBrowserStateTests.swift @@ -3,14 +3,14 @@ import Testing @Suite("Services browser selection and layout") struct RunBrowserStateTests { - private let node = RunConfiguration(id: "npm:web", name: "web", kind: .process(provider: "npm.script"), execution: .service, modulePath: nil, mainClass: nil) - private let rust = RunConfiguration(id: "cargo:worker", name: "worker", kind: .process(provider: "cargo.run"), modulePath: nil, mainClass: nil) - private let java = RunConfiguration(id: "java:api", name: "api", kind: .javaMain, modulePath: nil, mainClass: "demo.Api") - private let spring = RunConfiguration(id: "spring:api", name: "api", kind: .springBoot, modulePath: nil, mainClass: "demo.Api") + private let node = RunConfiguration(id: "npm:web", name: "web", kind: .process(provider: "npm.script"), execution: .service) + private let rust = RunConfiguration(id: "cargo:worker", name: "worker", kind: .process(provider: "cargo.run")) + private let java = RunConfiguration(id: "java:api", name: "api", kind: .process(provider: "fixture.main")) + private let spring = RunConfiguration(id: "spring:api", name: "api", kind: .process(provider: "fixture.service"), execution: .service) @Test func groupsApplicationFamiliesAcrossExecutionCategories() { let groups = RunBrowserState.groups(for: [spring, rust, .currentFile, node, java]) - #expect(groups.map(\.title) == ["Java", "Node", "Rust"]) + #expect(groups.map(\.title) == ["Fixture", "Node", "Rust"]) #expect(groups[0].configurations.map(\.id) == [java.id, spring.id]) #expect(groups[1].configurations == [node]) #expect(groups[2].configurations == [rust]) @@ -18,7 +18,7 @@ struct RunBrowserStateTests { } @Test func unknownProvidersRemainVisible() { - let unknown = RunConfiguration(id: "custom:run", name: "run", kind: .process(provider: "custom.launch"), modulePath: nil, mainClass: nil) + let unknown = RunConfiguration(id: "custom:run", name: "run", kind: .process(provider: "custom.launch")) let groups = RunBrowserState.groups(for: [unknown, node]) #expect(groups.map(\.title) == ["Custom", "Node"]) #expect(groups[0].configurations == [unknown]) diff --git a/macos/Tests/LitheTests/RunConfigurationIntegrationTests.swift b/macos/Tests/LitheTests/RunConfigurationIntegrationTests.swift index 08617f309e..18f1d62f7e 100644 --- a/macos/Tests/LitheTests/RunConfigurationIntegrationTests.swift +++ b/macos/Tests/LitheTests/RunConfigurationIntegrationTests.swift @@ -88,72 +88,6 @@ struct RunConfigurationIntegrationTests { #expect(reopened.providerRunOptions?.tools.values.allSatisfy { $0 == nil } == true) } - @Test - func nativeGenerationUsesProviderOwnershipThroughTheRealBridgeWithoutReadingPomsForJavaMembership() throws { - let root = FileManager.default.temporaryDirectory.appendingPathComponent("provider-generation-\(UUID().uuidString)") - defer { try? FileManager.default.removeItem(at: root) } - let data = try Data(contentsOf: DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("shared/fixtures/run-configuration/provider-project-ownership.json")) - let fixture = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) - let files = try #require(fixture["files"] as? [String: String]) - for (path, contents) in files { - let file = root.appendingPathComponent(path) - try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try Data(contents.utf8).write(to: file) - } - let decoder = JSONDecoder() - let ownershipObject = try #require(fixture["projectOwnership"]) - let ownershipData = try JSONSerialization.data(withJSONObject: ownershipObject) - let ownership = try decoder.decode([LitheCoreContracts.RunProjectOwnership].self, from: ownershipData) - let runsData = try JSONSerialization.data(withJSONObject: try #require(fixture["providerRuns"])) - let runs = try decoder.decode([RunProviderConfiguration].self, from: runsData) - let entryObject = try #require(fixture["javaEntrypoints"]) - let entryData = try JSONSerialization.data(withJSONObject: entryObject) - let entries = try decoder.decode(JavaEntrypoints.self, from: entryData) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: RunTestKeyValueStore()) - _ = try store.generate(at: root, files: files.keys.map { root.appendingPathComponent($0) }, modulePaths: ["wrong-legacy-path"], - javaEntrypoints: entries, projectOwnership: ownership, providerRuns: runs) - let inspected = try RustCoreBridge().inspectRunConfiguration(at: root, checkFingerprint: false, projectOwnership: ownership, providerRuns: runs).get() - let generated = try #require(inspected.generated) - let generatedData = try JSONEncoder().encode(generated) - let document = try #require(JSONSerialization.jsonObject(with: generatedData) as? [String: Any]) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/generated.json").path)) - let configurations = try #require(document["configurations"] as? [[String: Any]]) - let expected = try #require(fixture["expected"] as? [String: Any]) - for item in try #require(expected["configurations"] as? [[String: String]]) { - let actual = try #require(configurations.first { $0["id"] as? String == item["id"] }) - #expect(actual["cwd"] as? String == item["cwd"]) - let extensions = try #require(actual["extensions"] as? [String: [String: Any]]) - #expect(extensions["java"]?["module"] as? String == item["module"]) - #expect(extensions["maven"] == nil) - #expect(extensions["java"]?["sourceSet"] as? String == item["sourceSet"]) - } - for item in try #require(expected["services"] as? [[String: Any]]) { - let id = try #require(item["id"] as? String) - let actual = try #require(configurations.first { $0["id"] as? String == id }) - #expect(actual["provider"] as? String == "build.provider") - #expect(actual["execution"] as? String == "service") - let extensions = try #require(actual["extensions"] as? [String: Any]) - #expect(extensions["maven"] == nil) - } - let metadata = try #require(document["generator"] as? [String: Any]) - #expect((metadata["providerFingerprint"] as? String)?.hasPrefix("sha256:") == true) - #expect((metadata["providerRunFingerprint"] as? String)?.hasPrefix("sha256:") == true) - #expect(!store.inspectProviderGeneration(at: root, projectOwnership: ownership, providerRuns: runs.reversed()).diagnostics.contains { $0.code == "staleProviderModel" }) - #expect(store.inspectProviderGeneration(at: root, projectOwnership: ownership, providerRuns: []).diagnostics.contains { $0.code == "staleProviderModel" }) - #expect(!store.inspectProviderGeneration(at: root, projectOwnership: ownership).diagnostics.contains { $0.code == "staleProviderModel" }) - #expect(!store.inspectProviderGeneration(at: root, projectOwnership: ownership.reversed()).diagnostics.contains { $0.code == "staleProviderModel" }) - #expect(store.inspectProviderGeneration(at: root, projectOwnership: []).diagnostics.contains { $0.code == "staleProviderModel" }) - #expect(!store.inspectProviderGeneration(at: root, projectOwnership: ownership).diagnostics.contains { $0.code == "staleProviderModel" }) - let savedRequirements = try #require(inspected.toolchainRequirements) - let requirementsData = try JSONEncoder().encode(savedRequirements) - let requirements = try #require(JSONSerialization.jsonObject(with: requirementsData) as? [String: Any]) - let tools = try #require(requirements["toolchains"] as? [String: [String: Any]]) - #expect(tools["project-jdk"]?["minimumVersion"] as? String == expected["minimumJavaVersion"] as? String) - #expect(tools["project-maven"]?["minimumVersion"] as? String == expected["minimumMavenVersion"] as? String) - #expect(tools["project-maven"]?["wrapper"] == nil) - - } - @Test(arguments: [BuildExecution.application, .service, .task]) func savedBuildProviderReferenceWorksWithoutGeneratedConfiguration(execution: BuildExecution) throws { let core = RustCoreBridge() @@ -185,7 +119,7 @@ struct RunConfigurationIntegrationTests { #expect(entry["args"] == nil) let ignore = try String(contentsOf: root.appendingPathComponent(".lithe/.gitignore"), encoding: .utf8) #expect(ignore.contains("run/local.json")) - _ = try store.generate(at: root, files: [], modulePaths: [], javaEntrypoints: nil) + _ = try store.generate(at: root, providerRuns: nil) #expect(!store.inspect(at: root).requiresGeneration) } @@ -234,73 +168,6 @@ struct RunConfigurationIntegrationTests { #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/generated.json").path)) } - @Test - func readySavedTasksStillRequestDetectionUntilGenerationSucceeds() async { - let fixture = makeFixture(status: .ready) - fixture.operations.requiresGeneration = true - await fixture.service.loadProject(at: fixture.root, files: [], snapshotID: UUID()) - #expect(fixture.service.configurationStatus == .ready) - #expect(fixture.service.requiresConfigurationGeneration) - await fixture.service.generateRunConfigurations(automatic: true) - #expect(fixture.operations.generateCalls == 1) - #expect(!fixture.service.requiresConfigurationGeneration) - } - - @Test - func projectEnvironmentSavesWithoutGeneratedConfigurationsAndPreservesOverrides() throws { - // The unit lane does not link Rust Core; the Rust test with the same - // shared fixture covers the Core half there. - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-project-environment-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root.appendingPathComponent(".lithe/run"), - withIntermediateDirectories: true) - let localURL = root.appendingPathComponent(".lithe/run/local.json") - let original = #"{"version":2,"configurations":[{"id":"user:service","extensions":{"java":{"homePath":"/fixture/service-jdk"}}}]}"# - try Data(original.utf8).write(to: localURL) - let store = MacRunConfigurationStore(core: core, storage: MacFileStorage(), - preferences: RunTestKeyValueStore()) - // A layer that never saved defaults reports none, not automatic ones. - #expect(store.inspect(at: root).projectToolchain == nil) - try store.saveProjectToolchain(ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk"), at: root) - #expect(store.inspect(at: root).projectToolchain == ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk")) - let saved = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: localURL)) as? [String: Any]) - let configurations = try #require(saved["configurations"] as? [[String: Any]]) - let extensions = try #require(configurations.first?["extensions"] as? [String: Any]) - let java = try #require(extensions["java"] as? [String: String]) - #expect(java["homePath"] == "/fixture/service-jdk") - let toolchain = try #require(saved["toolchain"] as? [String: [String: String]]) - #expect(toolchain["java"]?["homePath"] == "/fixture/project-jdk") - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/generated.json").path)) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/configurations.json").path)) - let ignoreURL = root.appendingPathComponent(".lithe/.gitignore") - let requiredIgnore = "/run/local.json\n/run/classes/\n**/*.tmp\n" - #expect(try String(contentsOf: ignoreURL, encoding: .utf8) == requiredIgnore) - let existingIgnore = "# user rule\ncache/\n!run/local.json" - try Data(existingIgnore.utf8).write(to: ignoreURL) - try store.saveProjectToolchain(ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk"), at: root) - let expectedIgnore = existingIgnore + "\n" + requiredIgnore - #expect(try String(contentsOf: ignoreURL, encoding: .utf8) == expectedIgnore) - try store.saveProjectToolchain(ProjectToolchainSelection(), at: root) - #expect(try String(contentsOf: ignoreURL, encoding: .utf8) == expectedIgnore) - - // Rules written by generation already protect local paths; saving must - // not dirty the committed ignore file with equivalent anchored copies. - let generatedIgnore = "run/local.json\nrun/classes/\n**/*.tmp\n" - try Data(generatedIgnore.utf8).write(to: ignoreURL) - try store.saveProjectToolchain(ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk"), at: root) - #expect(try String(contentsOf: ignoreURL, encoding: .utf8) == generatedIgnore) - - // A user rule after Lithe's rules must not make every save append them again. - let userExtendedIgnore = expectedIgnore + "build/\n" - try Data(userExtendedIgnore.utf8).write(to: ignoreURL) - try store.saveProjectToolchain(ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk"), at: root) - try store.saveProjectToolchain(ProjectToolchainSelection(), at: root) - #expect(try String(contentsOf: ignoreURL, encoding: .utf8) == userExtendedIgnore) - } - @Test func projectDefaultsPersistOnlyAfterTheWorkspaceDocumentsWereRead() { // Settings persists the project toolchain when it closes. Loading, failed or @@ -315,17 +182,6 @@ struct RunConfigurationIntegrationTests { #expect(!ProjectLoadState.bound(workspace: other).hasLoadedDocuments(for: workspace)) } - @Test - func missingConfigurationsStillBindTheWorkspaceDocuments() async { - let fixture = makeFixture(status: .missing) - let saved = ProjectToolchainSelection(javaHomePath: "/fixture/project-jdk") - fixture.operations.inspectionToolchain = saved - await fixture.service.loadProject(at: fixture.root, files: []) - #expect(fixture.service.projectLoadState.hasLoadedDocuments(for: fixture.root)) - // Settings mirror these defaults before any configuration is generated. - #expect(fixture.service.savedProjectToolchain == saved) - } - @Test func localRunIgnoreRulesRespectOrderOfUserNegations() { let all = ["/run/local.json", "/run/classes/", "**/*.tmp"] @@ -342,54 +198,6 @@ struct RunConfigurationIntegrationTests { ).isEmpty) } - @Test - func generationRefusesUnsupportedVersionsEvenWithoutTheConfirmationEntry() async { - let fixture = makeFixture(status: .invalid("Unsupported configuration version")) - fixture.operations.inspectionRecoveryAction = .upgradeApplication - await fixture.service.loadProject(at: fixture.root, files: [], snapshotID: UUID()) - let feature = RunFeatureModel(service: fixture.service) - feature.requestRunConfigurationGeneration() - #expect(!feature.isGenerationConfirmationPresented) - await fixture.service.generateRunConfigurations() - #expect(fixture.operations.generateCalls == 0) - #expect(fixture.service.recoveryAction == .upgradeApplication) - guard case .failed = fixture.service.generationState else { - Issue.record("Direct generation must report an unsupported version without writing") - return - } - } - - @Test - func projectPreparationDoesNotBlockStandaloneOrMavenGoalLaunchers() { - func configuration(_ kind: RunConfigurationKind, reactor: String? = nil, source: String? = nil) -> RunConfiguration { - RunConfiguration(id: "sample", name: "Sample", kind: kind, modulePath: nil, - mainClass: "sample.Main", sourcePath: source, mavenReactorPath: reactor) - } - #expect(!configuration(.javaMain).usesJavaProjectPreparation) - #expect(!configuration(.currentFile, reactor: ".").usesJavaProjectPreparation) - #expect(!configuration(.mavenModule, reactor: ".").usesJavaProjectPreparation) - #expect(configuration(.javaMain, reactor: ".").usesJavaProjectPreparation) - #expect(!configuration(.springBoot, reactor: ".").usesJavaProjectPreparation) - #expect(configuration(.springBoot, reactor: ".", source: "src/Main.java").usesJavaProjectPreparation) - #expect(!configuration(.springBoot, reactor: ".").usesProviderConnectionDebug) - #expect(!configuration(.mavenFramework(.quarkus), reactor: ".").usesProviderConnectionDebug) - let service = RunConfiguration(id: "imported:service", name: "Service", kind: .process(provider: "build.provider"), - modulePath: nil, mainClass: nil, buildProvider: .init(pluginID: "dev.example.engine", buildSystemID: "engine", root: ".", - run: "serve", projectID: "project", targetID: "target", execution: .service)) - #expect(service.usesProviderConnectionDebug) - #expect(!RunConfigurationKind.mavenModule.capabilities.contains(.jdwpDebug)) - } - - @Test - func portConflictTitleIncludesTheActualPortAndConfigurations() { - let conflict = RunPortConflict( - port: 18080, - configurationNames: ["api", "worker"] - ) - - #expect(conflict.title == "Port 18080 is used by api, worker") - } - @Test func sourceBreakpointPlacementRetainsBraceAndAnnotatedDeclarationLines() { let source = """ @@ -416,37 +224,6 @@ struct RunConfigurationIntegrationTests { #expect(!DebugBreakpointLocationValidator.canSetSourceBreakpoint(source: "", line: 2)) } - @Test - func providerCapabilitiesKeepProcessEditorsLanguageNeutral() { - let process = RunConfigurationKind.process(provider: "python.script").capabilities - #expect(process.contains(.workingDirectory)) - #expect(process.contains(.arguments)) - #expect(process.contains(.environment)) - #expect(!process.contains(.javaRuntime)) - #expect(!process.contains(.javaVMArguments)) - #expect(!process.contains(.mavenProfiles)) - - let maven = RunConfigurationKind.springBoot.capabilities - #expect(maven.contains(.javaRuntime)) - #expect(maven.contains(.javaVMArguments)) - #expect(maven.contains(.mavenProfiles)) - #expect(maven.contains(.jdwpDebug)) - - let current = RunConfiguration.currentFile - let pythonCapabilities = current.effectiveCapabilities( - for: URL(fileURLWithPath: "/tmp/scripts/main.py") - ) - #expect(pythonCapabilities == .process) - let unknownCapabilities = current.effectiveCapabilities( - for: URL(fileURLWithPath: "/tmp/scripts/main.rb") - ) - #expect(unknownCapabilities == .process) - let javaCapabilities = current.effectiveCapabilities( - for: URL(fileURLWithPath: "/tmp/Main.java") - ) - #expect(javaCapabilities.contains(.javaRuntime)) - } - @Test func currentFileRunProvidersBuildPlansWithoutJavaAssumptions() throws { let registry = LanguageRunProviderRegistry.standard() @@ -507,7 +284,8 @@ struct RunConfigurationIntegrationTests { #expect(go?.activationPolicy == .onDemand) #expect(go?.capabilities.contains(.languageServer) == true) #expect(go?.capabilities.contains(.debugAdapter) == true) - #expect(catalog.provider(for: URL(fileURLWithPath: "/tmp/Main.java"))?.capabilities.contains(.debugAdapter) == true) + // Java run/debug/test come from the Java plugin; the built-in row is editor-only. + #expect(catalog.provider(for: URL(fileURLWithPath: "/tmp/Main.java"))?.capabilities.contains(.debugAdapter) == false) if !RustCoreBridge().isAvailable { #expect(catalog.provider(for: URL(fileURLWithPath: "/tmp/Package.swift")) == nil) #expect(catalog.provider(for: URL(fileURLWithPath: "/tmp/Dockerfile")) == nil) @@ -682,270 +460,6 @@ struct RunConfigurationIntegrationTests { #expect(runtime.debugAdapters.count == 1) } - @Test - func javaGenericDebugConfigurationUsesLanguageNeutralDapArguments() throws { - let provider = try #require(LanguageProviderCatalog.standard.provider( - for: URL(fileURLWithPath: "/tmp/java-project/src/main/java/com/acme/Main.java") - )) - let resolver = DebugLaunchConfigurationResolver() - let root = URL(fileURLWithPath: "/tmp/java-project", isDirectory: true) - let configuration = try resolver.resolve( - provider: provider, - documentURL: root.appendingPathComponent("src/main/java/com/acme/Main.java"), - workspaceURL: root, - configurations: [], - selectedConfiguration: nil, - javaTarget: JavaDebugLaunchTarget( - mainClass: "service/com.acme.Main", - projectName: "service", - modulePaths: ["/tmp/java-project/modules"], - classPaths: ["/tmp/java-project/classes"] - ), - options: { _ in RunOptions() } - ) - - #expect(configuration.request == .launch) - #expect(configuration.arguments["mainClass"] == .string("service/com.acme.Main")) - #expect(configuration.arguments["projectName"] == .string("service")) - #expect(configuration.arguments["modulePaths"] == .array([ - .string("/tmp/java-project/modules"), - ])) - #expect(configuration.arguments["classPaths"] == .array([ - .string("/tmp/java-project/classes"), - ])) - #expect(configuration.arguments["cwd"] == .string(root.path)) - } - - @Test - func javaDebugRunsOnTheJDKRunSelectsForTheSameConfiguration() throws { - let document = URL(fileURLWithPath: "/tmp/java-project/src/main/java/com/acme/Main.java") - let provider = try #require(LanguageProviderCatalog.standard.provider(for: document)) - let root = URL(fileURLWithPath: "/tmp/java-project", isDirectory: true) - let target = JavaDebugLaunchTarget( - mainClass: "com.acme.Main", - projectName: "service", - modulePaths: [], - classPaths: [] - ) - var requested: [DebugJavaRuntime] = [] - let resolver = DebugLaunchConfigurationResolver( - javaExecutablePath: { runtime in - requested.append(runtime) - return "/selected/bin/java" - } - ) - func javaExec(_ selected: RunConfiguration?, _ options: RunOptions) throws -> ToolingJSONValue? { - try resolver.resolve( - provider: provider, - documentURL: document, - workspaceURL: root, - configurations: [], - selectedConfiguration: selected, - javaTarget: target, - options: { _ in options } - ).arguments["javaExec"] - } - let javaMain = RunConfiguration( - id: "java-main:service", - name: "Service", - kind: .javaMain, - execution: .application, - modulePath: "service", - mainClass: "com.acme.Main" - ) - let mavenModule = RunConfiguration( - id: "module:service", - name: "service", - kind: .mavenModule, - execution: .service, - modulePath: "service", - mainClass: nil - ) - - #expect(try javaExec(nil, RunOptions()) == .string("/selected/bin/java")) - #expect(try javaExec(javaMain, RunOptions(javaHomePath: "/jdks/17")) == .string("/selected/bin/java")) - #expect(try javaExec(mavenModule, RunOptions(javaHomePath: "/jdks/17")) == .string("/selected/bin/java")) - #expect(try javaExec( - mavenModule, - RunOptions(javaHomePath: "/jdks/17", mavenJavaHomePath: "/jdks/21") - ) == .string("/selected/bin/java")) - - #expect(requested == [ - .java(homeOverride: nil), - .java(homeOverride: "/jdks/17"), - .maven(homeOverride: "/jdks/17"), - .maven(homeOverride: "/jdks/21"), - ]) - } - - @Test - func javaDebugFailsLikeRunWhenItsJDKIsUnusable() throws { - let document = URL(fileURLWithPath: "/tmp/java-project/src/main/java/com/acme/Main.java") - let provider = try #require(LanguageProviderCatalog.standard.provider(for: document)) - let resolver = DebugLaunchConfigurationResolver( - javaExecutablePath: { _ in nil } - ) - - #expect(throws: DebugLaunchConfigurationResolutionError.javaRuntimeUnavailable) { - try resolver.resolve( - provider: provider, - documentURL: document, - workspaceURL: URL(fileURLWithPath: "/tmp/java-project", isDirectory: true), - configurations: [], - selectedConfiguration: nil, - javaTarget: JavaDebugLaunchTarget( - mainClass: "com.acme.Main", - projectName: nil, - modulePaths: [], - classPaths: [] - ), - options: { _ in RunOptions() } - ) - } - } - - @Test - func debugJavaRuntimeFollowsTheRunSelectionChain() { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - runtime.openProject(at: URL(fileURLWithPath: "/tmp/lithe-runtime-toolchains", isDirectory: true)) - - #expect( - runtime.javaExecutableURL(forDebugging: .java(homeOverride: "/local/JDK 21")) - == runtime.javaExecutableURL(overridePath: "/local/JDK 21") - ) - #expect( - runtime.javaExecutableURL(forDebugging: .maven(homeOverride: "/local/Maven JDK"))?.path - == runtime.environment(for: .maven, javaHomeOverride: "/local/Maven JDK")["JAVA_HOME"] - .map { $0 + "/bin/java" } - ) - #expect( - runtime.javaExecutableURL(forDebugging: .java(homeOverride: nil)) - == runtime.javaExecutableURL() - ) - } - - @Test - func javaDebugReusesTheSelectedRunConfigurationOptions() throws { - let provider = try #require(LanguageProviderCatalog.standard.provider( - for: URL(fileURLWithPath: "/tmp/java-project/src/main/java/com/acme/Main.java") - )) - let root = URL(fileURLWithPath: "/tmp/java-project", isDirectory: true) - let selected = RunConfiguration( - id: "java-main:service", - name: "Service", - kind: .javaMain, - execution: .application, - modulePath: "service", - mainClass: "com.acme.ConfiguredMain" - ) - let options = RunOptions( - workingDirectoryPath: "service", - vmArguments: "-Xmx1g -Dprofile=dev", - programArguments: "--port 8080", - environment: ["APP_ENV": "dev"] - ) - let resolver = DebugLaunchConfigurationResolver() - let configuration = try resolver.resolve( - provider: provider, - documentURL: root.appendingPathComponent("src/main/java/com/acme/Main.java"), - workspaceURL: root, - configurations: [selected], - selectedConfiguration: selected, - javaTarget: JavaDebugLaunchTarget( - mainClass: "com.acme.ResolvedByJdtls", - projectName: nil, - modulePaths: [], - classPaths: [] - ), - options: { _ in options } - ) - - #expect(configuration.name == "Service") - #expect(configuration.arguments["mainClass"] == .string("com.acme.ConfiguredMain")) - #expect(configuration.arguments["cwd"] == .string(root.appendingPathComponent("service").path)) - #expect(configuration.arguments["vmArgs"] == .string("-Xmx1g -Dprofile=dev")) - #expect(configuration.arguments["args"] == .string("--port 8080")) - #expect(configuration.arguments["env"] == .object(["APP_ENV": .string("dev")])) - } - - @Test - func selectedSpringBootConfigurationResolvesItsMainSourceWithoutAnOpenJavaEditor() throws { - let root = URL(fileURLWithPath: "/workspace/demo", isDirectory: true) - let readme = root.appendingPathComponent("README.md") - let application = root.appendingPathComponent( - "src/main/java/com/example/demo/DemoApplication.java" - ) - let controller = root.appendingPathComponent( - "src/main/java/com/example/demo/user/UserController.java" - ) - let configuration = RunConfiguration( - id: "spring-boot:demo", - name: "DemoApplication", - kind: .springBoot, - execution: .service, - modulePath: nil, - mainClass: "com.example.demo.DemoApplication" - ) - - let source = DebugLaunchSourceResolver().resolve( - configuration: configuration, - activeDocumentURL: readme, - projectFiles: [controller, application, readme], - workspaceURL: root - ) - - #expect(source == application) - } - - @Test - func selectedJavaConfigurationUsesItsModuleToDisambiguateDuplicateMainClasses() throws { - let root = URL(fileURLWithPath: "/workspace/multi-module", isDirectory: true) - let first = root.appendingPathComponent("first/src/main/java/com/acme/Main.java") - let second = root.appendingPathComponent("second/src/main/java/com/acme/Main.java") - let configuration = RunConfiguration( - id: "java-main:second", - name: "Second Main", - kind: .javaMain, - execution: .application, - modulePath: "second", - mainClass: "com.acme.Main" - ) - - let source = DebugLaunchSourceResolver().resolve( - configuration: configuration, - activeDocumentURL: first, - projectFiles: [first, second], - workspaceURL: root - ) - - #expect(source == second) - } - - @Test - func providerJavaDebugSourceUsesTheGenericInstanceRootWithoutCrossingIntoAnotherProject() { - let root = URL(fileURLWithPath: "/workspace/providers", isDirectory: true) - let wrong = root.appendingPathComponent("app/src/main/java/com/acme/Main.java") - let current = root.appendingPathComponent("nested/engine/app/src/main/java/com/acme/Main.java") - let configuration = RunConfiguration(id: "java-main:engine", name: "Engine Main", kind: .javaMain, - modulePath: "app", mainClass: "com.acme.Main", mavenReactorPath: "obsolete-owner", - buildProject: .init(pluginID: "dev.example.engine", buildSystemID: "engine", root: "nested/engine", projectID: "opaque-project")) - let resolver = DebugLaunchSourceResolver() - #expect(resolver.resolve(configuration: configuration, activeDocumentURL: wrong, - projectFiles: [wrong, current], workspaceURL: root) == current) - // The current module has no source in the second snapshot. A matching - // class in another instance is not a replacement launch target. - #expect(resolver.resolve(configuration: configuration, activeDocumentURL: wrong, - projectFiles: [wrong], workspaceURL: root) == nil) - let workspaceOwner = RunConfiguration(id: "java-main:root", name: "Root Main", kind: .javaMain, - modulePath: "app", mainClass: "com.acme.Main", mavenReactorPath: "obsolete-owner", - buildProject: .init(pluginID: "dev.example.other", buildSystemID: "other", root: ".", projectID: "other-project")) - #expect(resolver.resolve(configuration: workspaceOwner, activeDocumentURL: current, - projectFiles: [wrong, current], workspaceURL: root) == wrong) - } - @Test func currentFileDebugStillUsesTheActiveEditorDocument() throws { let root = URL(fileURLWithPath: "/workspace/current-file", isDirectory: true) @@ -962,144 +476,6 @@ struct RunConfigurationIntegrationTests { #expect(source == current) } - @Test - func debugFallsBackFromNonLaunchableCurrentJavaFileToSpringBootConfiguration() { - let current = RunConfiguration( - id: "current-file", - name: "Current File", - kind: .currentFile, - execution: .application, - modulePath: nil, - mainClass: nil - ) - let springBoot = RunConfiguration( - id: "spring-boot:demo", - name: "DemoApplication", - kind: .springBoot, - execution: .service, - modulePath: nil, - mainClass: "com.example.demo.DemoApplication" - ) - - let selected = DebugLaunchSourceResolver().configurationForDebug( - selected: current, - activeDocumentIsLaunchable: false, - configurations: [current, springBoot] - ) - - #expect(selected.id == springBoot.id) - } - - @Test - func debugFallsBackWhenJdtCannotConfirmTheCurrentFile() { - let current = RunConfiguration( - id: "current-file", - name: "Current File", - kind: .currentFile, - execution: .application, - modulePath: nil, - mainClass: nil - ) - let springBoot = RunConfiguration( - id: "spring-boot:demo", - name: "DemoApplication", - kind: .springBoot, - execution: .service, - modulePath: nil, - mainClass: "com.example.demo.DemoApplication" - ) - - let selected = DebugLaunchSourceResolver().configurationForDebug( - selected: current, - activeDocumentIsLaunchable: false, - configurations: [current, springBoot] - ) - - #expect(selected.id == springBoot.id) - } - - @Test - func debugKeepsCurrentJavaFileWhenJdtListsItAsLaunchable() { - let current = RunConfiguration( - id: "current-file", - name: "Current File", - kind: .currentFile, - execution: .application, - modulePath: nil, - mainClass: nil - ) - let springBoot = RunConfiguration( - id: "spring-boot:demo", - name: "DemoApplication", - kind: .springBoot, - execution: .service, - modulePath: nil, - mainClass: "com.example.demo.DemoApplication" - ) - - let selected = DebugLaunchSourceResolver().configurationForDebug( - selected: current, - activeDocumentIsLaunchable: true, - configurations: [current, springBoot] - ) - - #expect(selected.id == current.id) - } - - @Test - func javaTestDebugLaunchUsesTheSharedRustConfiguration() throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let target = JavaTestDebugLaunchTarget( - fileURL: URL(fileURLWithPath: "/workspace/UserServiceTest.java"), - name: "UserServiceTest", - framework: .testng, - workingDirectory: "/workspace", - mainClass: "com.microsoft.java.test.runner.Launcher", - projectName: "service", - classPaths: ["/workspace/classes"], - modulePaths: [], - vmArguments: [], - programArguments: [], - testNGRunnerPath: "/lithe/java-test-runner.jar", - testNGTestNames: ["example.UserServiceTest#logsIn"] - ) - let resolver = DebugLaunchConfigurationResolver( - javaTestLaunchResolver: core - ) - - let configuration = try resolver.resolveJavaTest(target: target, resultPort: 43_128) - - #expect(configuration.name == "UserServiceTest") - #expect(configuration.request == .launch) - #expect( - configuration.arguments["mainClass"] - == .string("com.microsoft.java.test.runner.Launcher") - ) - #expect(configuration.arguments["classPaths"] == .array([ - .string("/workspace/classes"), - .string("/lithe/java-test-runner.jar"), - ])) - #expect( - configuration.arguments["args"] - == .string("43128 testng example.UserServiceTest#logsIn") - ) - #expect(configuration.arguments["javaExec"] == nil) - - var requested: [DebugJavaRuntime] = [] - let aligned = try DebugLaunchConfigurationResolver( - javaTestLaunchResolver: core, - javaExecutablePath: { runtime in - requested.append(runtime) - return "/maven-jdk/bin/java" - } - ).resolveJavaTest(target: target, resultPort: 43_128) - - #expect(requested == [.maven(homeOverride: nil)]) - #expect(aligned.arguments["javaExec"] == .string("/maven-jdk/bin/java")) - #expect(aligned.arguments["args"] == configuration.arguments["args"]) - } - @Test func sourceBreakpointRelocationUsesTheSharedRustCore() throws { let core = RustCoreBridge() @@ -1127,26 +503,6 @@ struct RunConfigurationIntegrationTests { )]) } - @Test - func javaAttachUsesTheSharedDAPSessionWithValidatedEndpointArguments() throws { - let resolver = DebugLaunchConfigurationResolver() - - let configuration = try resolver.resolveJavaAttach(host: " localhost ", port: 5005) - - #expect(configuration.name == "localhost:5005") - #expect(configuration.request == .attach) - #expect(configuration.arguments == [ - "hostName": .string("localhost"), - "port": .integer(5005) - ]) - #expect(throws: DebugLaunchConfigurationResolutionError.invalidJavaAttachHost) { - try resolver.resolveJavaAttach(host: " ", port: 5005) - } - #expect(throws: DebugLaunchConfigurationResolutionError.invalidJavaAttachPort) { - try resolver.resolveJavaAttach(host: "localhost", port: 65_536) - } - } - @Test func macToolDiscoveryReportsProjectHomebrewAndXcodeSources() { let root = URL(fileURLWithPath: "/tmp/mac-tool-project", isDirectory: true) @@ -1179,8 +535,6 @@ struct RunConfigurationIntegrationTests { environment: [:] ) #expect(xcrunCandidates.first?.source == .xcode) - #expect(discovery.guidance(for: "java-debug-adapter", projectURL: root, environment: [:]) - .recovery.contains("bundled Java language and Debug Adapter resources")) } @Test @@ -1201,26 +555,26 @@ struct RunConfigurationIntegrationTests { } @Test - func javaDAPBreakpointsCanBeStoredBeforeTheAdapterStarts() throws { - let source = URL(fileURLWithPath: "/tmp/Main.java") + func dapBreakpointsCanBeStoredBeforeTheAdapterStarts() throws { + let source = URL(fileURLWithPath: "/tmp/main.go") let manager = DebugAdapterSessionManager( providers: LanguageProviderCatalog.standard.debugProviders ) { _, _ in nil } try manager.setBreakpoints([DebugSourceBreakpoint(line: 1)], in: source) - #expect(manager.provider(for: source)?.id == "java") + #expect(manager.provider(for: source)?.id == "go") #expect(manager.activeAdapterIDs.isEmpty) } @Test - func restoredJavaBreakpointInAnotherSourceIsSentWhenDebugStarts() throws { - let root = URL(fileURLWithPath: "/tmp/restored-java-debug", isDirectory: true) - let launchSource = root.appendingPathComponent("src/main/java/demo/DemoApplication.java") - let breakpointSource = root.appendingPathComponent("src/main/java/demo/UserController.java") + func restoredBreakpointInAnotherSourceIsSentWhenDebugStarts() throws { + let root = URL(fileURLWithPath: "/tmp/restored-go-debug", isDirectory: true) + let launchSource = root.appendingPathComponent("cmd/app/main.go") + let breakpointSource = root.appendingPathComponent("internal/user/controller.go") let persistence = RestoredBreakpointPersistence(snapshot: DebugBreakpointSnapshot( breakpoints: [PersistedDebugBreakpoint( - relativePath: "src/main/java/demo/UserController.java", + relativePath: "internal/user/controller.go", line: 23 )] )) @@ -1244,7 +598,7 @@ struct RunConfigurationIntegrationTests { fileURL: launchSource, rootURL: root, configuration: DebugLaunchConfiguration( - name: "DemoApplication", + name: "app", request: .launch, arguments: [:] ) @@ -1271,7 +625,7 @@ struct RunConfigurationIntegrationTests { let registry = LanguageTestProviderRegistry.standard() for (providerID, source) in [ - ("java", files[0]), ("go", files[1]), ("python", files[2]), + ("go", files[1]), ("python", files[2]), ("node", files[3]), ("rust", files[4]) ] { let provider = try #require(registry.provider(for: source)) @@ -1295,53 +649,6 @@ struct RunConfigurationIntegrationTests { #expect(pythonPlan.launchPlan.toolchainID == "project-python") #expect(pythonPlan.launchPlan.arguments == ["-m", "pytest", "tests/test_api.py::test_health"]) - let javaProvider = try #require(registry.provider(id: "java")) - #expect(throws: LanguageTestPlanError.unsupportedProvider(javaProvider.descriptor.displayName)) { - try javaProvider.testPlan(scope: .file(files[0]), workspaceURL: root) - } - - let gradleMethodPlan = try javaProvider.testPlan( - scope: .testCase( - identifier: "example.UserServiceTest#logsIn()", - fileURL: files[0] - ), - context: LanguageTestContext( - workspaceURL: root, - projectFiles: [root.appendingPathComponent("build.gradle.kts"), files[0]] - ) - ) - #expect(gradleMethodPlan.launchPlan.arguments == [ - "test", "--no-daemon", "--tests", "example.UserServiceTest.logsIn", - ]) - - #expect(throws: LanguageTestPlanError.unsupportedProvider(javaProvider.descriptor.displayName)) { - try javaProvider.testPlan( - scope: .testCase( - identifier: "example.UserServiceTest#logsIn()", - fileURL: files[0] - ), - context: LanguageTestContext( - workspaceURL: root, - projectFiles: [root.appendingPathComponent("pom.xml"), files[0]] - ) - ) - } - - let gradlePlan = try javaProvider.testPlan( - scope: .workspace, - context: LanguageTestContext( - workspaceURL: root, - projectFiles: [root.appendingPathComponent("build.gradle.kts")] - ) - ) - #expect(gradlePlan.frameworkID == "gradle") - #expect(gradlePlan.launchPlan.arguments == ["test", "--no-daemon"]) - if case .toolchain(let executable) = gradlePlan.launchPlan.executable { - #expect(executable == "project-gradle") - } else { - Issue.record("Expected Gradle projects to use the registered Gradle toolchain") - } - let nodeProvider = try #require(registry.provider(id: "node")) let nodePlan = try nodeProvider.testPlan(scope: .workspace, workspaceURL: root) if case .command(let executable) = nodePlan.launchPlan.executable { @@ -1367,67 +674,6 @@ struct RunConfigurationIntegrationTests { #expect(rustPlan.launchPlan.arguments == ["test", "--test", "parser"]) } - @Test - func testDiscoveryDoesNotInventAFrameworkForAPlainWorkspace() throws { - let root = URL(fileURLWithPath: "/tmp/plain-polyglot", isDirectory: true) - let javaFile = root.appendingPathComponent("src/test/java/PlainTest.java") - let nodeFile = root.appendingPathComponent("src/app.spec.ts") - let registry = LanguageTestProviderRegistry.standard() - let javaProvider = try #require(registry.provider(id: "java")) - let nodeProvider = try #require(registry.provider(id: "node")) - - // Every Java source is only inventory for JDT semantic discovery; - // a plain workspace still cannot acquire a Maven command plan. - #expect(javaProvider.discoverTests(context: LanguageTestContext( - workspaceURL: root, projectFiles: [javaFile] - )).last?.fileURL == javaFile) - #expect(nodeProvider.discoverTests(context: LanguageTestContext( - workspaceURL: root, - projectFiles: [nodeFile] - )).isEmpty) - #expect(throws: LanguageTestPlanError.unsupportedProvider("Java")) { - _ = try javaProvider.testPlan( - scope: .file(javaFile), - context: LanguageTestContext( - workspaceURL: root, - projectFiles: [javaFile] - ) - ) - } - - let mavenItems = javaProvider.discoverTests(context: LanguageTestContext( - workspaceURL: root, - projectFiles: [ - javaFile, - root.appendingPathComponent("pom.xml") - ] - )) - #expect(mavenItems.count == 2) - #expect(mavenItems.last?.fileURL == javaFile.standardizedFileURL) - } - - @Test - func javaDiscoveryOffersNonConventionalSourceNamesToJDT() throws { - let root = URL(fileURLWithPath: "/tmp/java-semantic-tests", isDirectory: true) - let inheritedSuite = root.appendingPathComponent("src/checks/InheritedSuite.java") - let helper = root.appendingPathComponent("src/main/java/Helper.java") - let provider = try #require(LanguageTestProviderRegistry.standard().provider(id: "java")) - - let items = provider.discoverTests(context: LanguageTestContext( - workspaceURL: root, - projectFiles: [ - inheritedSuite, - helper, - root.appendingPathComponent("pom.xml"), - ] - )) - - #expect(items.compactMap(\.fileURL) == [ - inheritedSuite.standardizedFileURL, - helper.standardizedFileURL, - ]) - } - @Test func testProvidersRejectFilesOutsideTheWorkspace() throws { let provider = try #require(LanguageTestProviderRegistry.standard().provider(id: "python")) @@ -1605,26 +851,9 @@ struct RunConfigurationIntegrationTests { #expect(diagnostics[0] == EditorDiagnostic(languageServerDiagnostic: lsp, fileURL: fileURL)) } - @Test - func runOptionsDecodeLegacyJavaPreferencesIntoGenericFields() throws { - let data = Data( - #"{"javaHomePath":"/jdk","workingDirectoryPath":"backend","vmArguments":"-Xmx1g","programArguments":"--port 8080","activeProfiles":["dev"]}"#.utf8 - ) - let options = try JSONDecoder().decode(RunOptions.self, from: data) - - #expect(options.javaHomePath == "/jdk") - #expect(options.workingDirectoryPath == "backend") - #expect(options.vmArguments == "-Xmx1g") - #expect(options.arguments == "--port 8080") - #expect(options.activeProfiles == ["dev"]) - } - @Test func executableResolverRejectsUnknownToolchainsInsteadOfUsingMaven() throws { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let resolver = RunExecutableResolver(runtimeService: runtime) let plan = SharedLaunchPlan( executable: .toolchain("project-unknown"), @@ -1641,39 +870,9 @@ struct RunConfigurationIntegrationTests { } } - @Test - func mavenToolchainResolvesTheWrapperFromTheLaunchWorkingDirectory() throws { - let workspaceRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-nested-maven-wrapper", isDirectory: true) - let mavenRoot = URL( - fileURLWithPath: workspaceRoot.path + "/projects/demo", - isDirectory: true - ) - let runtime = ProjectRuntimeService( - runtimeLocator: NestedMavenWrapperRuntimeLocator(wrapperRoot: mavenRoot), - store: RunTestKeyValueStore() - ) - let resolver = RunExecutableResolver(runtimeService: runtime) - let resolved = try resolver.resolve( - SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["verify"], - workingDirectory: "projects/demo" - ), - projectURL: workspaceRoot, - options: RunOptions() - ) - - #expect(resolved.executableURL == mavenRoot.appendingPathComponent("mvnw")) - #expect(!resolved.executableURL.absoluteString.contains("%2F")) - } - @Test func commandResolverLayersGenericEnvironmentWithoutJavaInjection() throws { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let resolver = RunExecutableResolver(runtimeService: runtime) let plan = SharedLaunchPlan( executable: .command("python3"), @@ -1696,10 +895,7 @@ struct RunConfigurationIntegrationTests { @Test func registeredGoToolchainResolvesWithoutMavenFallback() throws { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let resolver = RunExecutableResolver(runtimeService: runtime) let resolved = try resolver.resolve( SharedLaunchPlan( @@ -1716,33 +912,9 @@ struct RunConfigurationIntegrationTests { #expect(resolved.environment["JAVA_HOME"] == nil) } - @Test - func registeredGradleToolchainPrefersTheProjectWrapper() throws { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let resolver = RunExecutableResolver(runtimeService: runtime) - let resolved = try resolver.resolve( - SharedLaunchPlan( - executable: .toolchain("project-gradle"), - arguments: ["test"], - workingDirectory: "." - ), - projectURL: URL(fileURLWithPath: "/tmp/gradle-project"), - options: RunOptions() - ) - - #expect(resolved.executableURL.path == "/tmp/gradle-project/gradlew") - #expect(resolved.environment["JAVA_HOME"] == nil) - } - @Test func genericToolchainVersionsAreProbedOffTheResolutionPathAndCachedPerAlias() async throws { - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtime = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let runner = ToolchainVersionProcessRunner() let resolver = RunExecutableResolver( runtimeService: runtime, @@ -1777,10 +949,7 @@ struct RunConfigurationIntegrationTests { arguments: [] ) ) - let runtimeService = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtimeService = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let process = RecordingRawProcessSession() let core = TestLanguageServerRuntimeCore(providerID: "go") let runtime = StdioLanguageProviderRuntime( @@ -1849,122 +1018,19 @@ struct RunConfigurationIntegrationTests { } @Test - func languageToolingRejectsUnavailableRequiredRuntime() { + func languageServerFailureClearsActiveSessionState() async throws { let descriptor = LanguageProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"], - capabilities: [.languageServer], - activationPolicy: .onDemand, - languageIdentifier: "java", - languageServerLaunch: LanguageServerLaunchDescriptor(executableNames: ["jdtls"]) - ) - let runtimeService = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let message = "JDTLS requires JDK 17 or newer." - let runtime = StdioLanguageProviderRuntime( - descriptor: descriptor, - runtimeService: runtimeService, - languageServerLaunch: descriptor.languageServerLaunch, - languageServerCore: TestLanguageServerRuntimeCore(providerID: "java"), - languageServerExecutableResolver: { _ in URL(fileURLWithPath: "/usr/bin/jdtls") }, - hostIntegrationResolver: { _ in .unavailable(message) } - ) - - #expect(runtime.makeLanguageServerSession() == nil) - #expect(runtime.unavailableToolingMessage == message) - } - - @Test - func languageToolingForwardsStructuredJdtlsLaunchResources() throws { - let descriptor = LanguageProviderDescriptor( - id: "java", - displayName: "Java", - fileExtensions: ["java"], - capabilities: [.languageServer], - activationPolicy: .onDemand, - languageIdentifier: "java", - languageServerLaunch: LanguageServerLaunchDescriptor(executableNames: ["jdtls"]) - ) - let runtimeService = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let core = TestLanguageServerRuntimeCore(providerID: "java") - let resources = JDTLSLaunchResources( - launcherJarURL: URL(fileURLWithPath: "/jdtls/plugins/equinox.jar"), - configurationDirectoryURL: URL(fileURLWithPath: "/jdtls/config_mac"), - lombokAgentURL: URL(fileURLWithPath: "/jdtls/lombok/lombok.jar"), - javaDebugBundleURL: URL( - fileURLWithPath: "/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar" - ), - javaExtensionBundleURLs: [ - URL( - fileURLWithPath: - "/jdtls/java-test/extensions/com.microsoft.java.test.plugin-0.42.0.jar" - ) - ], - javaTestRunnerURL: URL( - fileURLWithPath: - "/jdtls/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar" - ) - ) - let runtime = StdioLanguageProviderRuntime( - descriptor: descriptor, - runtimeService: runtimeService, - languageServerLaunch: descriptor.languageServerLaunch, - languageServerCore: core, - languageServerExecutableResolver: { _ in URL(fileURLWithPath: "/jdtls/bin/jdtls") }, - hostIntegrationResolver: { _ in - .available(LanguageServerHostIntegrationLaunch( - runtimeExecutableURL: URL(fileURLWithPath: "/jdk/bin/java"), - coreLaunch: .jdt(resources) - )) - } - ) - let session = try #require(runtime.makeLanguageServerSession()) - let mavenContext = MavenLaunchContext( - reactorPath: ".", - profiles: ["dev", "enterprise"], - settingsPath: "/local/settings.xml", - skipTests: true, - mavenExecutablePath: "/local/maven/bin/mvn", - javaHomePath: "/local/jdk" - ) - - try session.start( - rootURL: URL(fileURLWithPath: "/workspace", isDirectory: true), - workspaceFingerprint: "workspace-fingerprint", - mavenContext: mavenContext - ) - - let start = try #require(core.startCalls.last) - #expect(start.runtimeExecutableURL?.path == "/jdk/bin/java") - #expect(start.jdtlsLaunchResources == resources) - #expect(start.workspaceFingerprint == "workspace-fingerprint") - #expect(start.mavenContext == mavenContext) - session.stop() - } - - @Test - func languageServerFailureClearsActiveSessionState() async throws { - let descriptor = LanguageProviderDescriptor( - id: "swift", - displayName: "Swift", - fileExtensions: ["swift"], - capabilities: [.languageServer, .formatting], + id: "swift", + displayName: "Swift", + fileExtensions: ["swift"], + capabilities: [.languageServer, .formatting], activationPolicy: .onDemand, languageIdentifier: "swift", languageServerLaunch: LanguageServerLaunchDescriptor( executableNames: ["sourcekit-lsp"] ) ) - let runtimeService = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtimeService = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let core = TestLanguageServerRuntimeCore() let source = URL(fileURLWithPath: "/tmp/swift-project/App.swift") let runtime = StdioLanguageProviderRuntime( @@ -2423,10 +1489,7 @@ struct RunConfigurationIntegrationTests { initializationOptions: .object(["indexing": .bool(true)]) ) ) - let runtimeService = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) + let runtimeService = ProjectRuntimeService(runtimeLocator: RunTestRuntimeLocator()) let process = RecordingRawProcessSession() let core = TestLanguageServerRuntimeCore(providerID: "swift") let root = URL(fileURLWithPath: "/tmp/swift-project", isDirectory: true) @@ -2748,30 +1811,6 @@ struct RunConfigurationIntegrationTests { #expect(harness.core.startCalls.count == 4) } - @Test - func pluginSessionPreservesHostIntegrationLaunchResources() throws { - let core = TestLanguageServerRuntimeCore(providerID: "java") - let resources = JDTLSLaunchResources( - launcherJarURL: URL(fileURLWithPath: "/test-plugin/equinox.jar"), - configurationDirectoryURL: URL(fileURLWithPath: "/test-plugin/configuration/arm64"), - lombokAgentURL: URL(fileURLWithPath: "/test-plugin/lombok.jar") - ) - let java = URL(fileURLWithPath: "/test-plugin/runtime/bin/java") - let cache = URL(fileURLWithPath: "/test-cache/language-servers") - let session = StdioLanguageServerSession( - providerID: "java", executableURL: java, arguments: ["-jar", resources.launcherJarURL.path], - environment: [:], hostIntegrationLaunch: .init(runtimeExecutableURL: java, coreLaunch: .jdt(resources)), - cacheDirectoryURL: cache, core: core, pluginID: "test.java-support" - ) - defer { session.stop() } - try session.start(rootURL: URL(fileURLWithPath: "/test-workspace"), workspaceFingerprint: "workspace-v1") - let launch = try #require(core.startCalls.first) - #expect(launch.runtimeExecutableURL == java) - #expect(launch.jdtlsLaunchResources == resources) - #expect(launch.cacheDirectoryURL == cache) - #expect(launch.workspaceFingerprint == "workspace-v1") - } - @Test func virtualDocumentContentProjectsFromRustEvents() async throws { let core = TestLanguageServerRuntimeCore(providerID: "java") @@ -2782,10 +1821,7 @@ struct RunConfigurationIntegrationTests { environment: [:], core: core ) - try session.start( - rootURL: URL(fileURLWithPath: "/test-workspace", isDirectory: true), - workspaceFingerprint: nil - ) + try session.start(rootURL: URL(fileURLWithPath: "/test-workspace", isDirectory: true)) core.enqueueReady(capabilities: ["executeCommand"]) #expect(await Self.waitForMainActorCondition { session.features.contains(.executeCommand) @@ -2850,10 +1886,10 @@ struct RunConfigurationIntegrationTests { defer { manager.stopAll() } let feature = GenericDebugFeatureModel(paging: RustCoreBridge(), sessions: manager) let root = URL(fileURLWithPath: "/workspace") - let source = root.appendingPathComponent("Example.java") + let source = root.appendingPathComponent("example.go") feature.toggleBreakpoint(fileURL: source, line: 3) #expect(feature.start(fileURL: source, rootURL: root, - configuration: DebugLaunchConfiguration(name: "Example", request: .launch, arguments: [:]))) + configuration: DebugLaunchConfiguration(name: "example", request: .launch, arguments: [:]))) adapter.onEvent?(.breakpoint(DebugBreakpoint(id: 41, verified: true, message: nil, sourceURL: source, line: 5, column: nil, requestedLine: 3))) let point = try #require(feature.breakpoints.first) @@ -2866,1545 +1902,179 @@ struct RunConfigurationIntegrationTests { } @Test - func reloadingRunConfigurationsDoesNotStopAnUnrelatedProcessSession() async { - let configuration = RunConfiguration( - id: "python:api", - name: "API", - kind: .process(provider: "python.script"), - modulePath: nil, - mainClass: nil - ) - let plan = SharedLaunchPlan( - executable: .command("python3"), - arguments: ["app.py"], - workingDirectory: "." - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: RunOptions())], - plans: [configuration.id: plan] - ) - - await fixture.service.loadProject(at: fixture.root, files: []) - fixture.service.run(configuration: configuration, currentFileURL: nil) - #expect(fixture.process.isRunning) - let stopCountAfterStart = fixture.process.stopCount - await fixture.service.loadProject(at: fixture.root, files: []) - #expect(fixture.process.isRunning) - #expect(fixture.process.stopCount == stopCountAfterStart) - } - - @Test - func missingConfigurationLeavesRunUnavailableWithoutScanningLegacySettings() async { - let fixture = makeFixture(status: .missing) - - await fixture.service.loadProject( - at: fixture.root, - files: [], - snapshotID: UUID() + func generationSucceedsWithoutWritingTheWorkspace() throws { + let core = RustCoreBridge() + guard core.isAvailable else { return } + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-generation-read-only-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root.appendingPathComponent("src"), withIntermediateDirectories: true) + let source = root.appendingPathComponent("src/App.java") + try Data("class App { public static void main(String[] args) {} }".utf8).write(to: source) + let storage = CountingFileStorage(root: root) + storage.shouldFailWrites = true + let store = MacRunConfigurationStore( + core: core, + storage: storage, + preferences: RunTestKeyValueStore() ) - #expect(fixture.service.configurationStatus == .missing) - #expect(fixture.service.configurations.isEmpty) - #expect(fixture.operations.resolveCalls == 0) - #expect(fixture.operations.migrationCalls == 0) - #expect(fixture.process.requests.isEmpty) + let result = try store.generate(at: root, providerRuns: nil) + #expect(result.entryCount == 0) + #expect(storage.writeCount == 0) + #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe").path)) + #expect(store.inspect(at: root).status == .ready) } @Test - func readyConfigurationUsesSharedLaunchPlanForProcessRequest() async throws { - let configuration = JavaRunConfiguration( - id: "spring:com.example.App", - name: "App", - kind: .springBoot, - modulePath: "backend", - mainClass: "com.example.App" - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-pl", "backend", "-am", "-P", "dev", "spring-boot:run"], - workingDirectory: "backend" - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: JavaRunOptions())], - plans: [configuration.id: plan] + func unchangedLocalOptionsDoNotRewriteTheConfigurationFile() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-unchanged-write-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let storage = CountingFileStorage(root: root) + let store = MacRunConfigurationStore( + core: RustCoreBridge(), + storage: storage, + preferences: RunTestKeyValueStore(), + documentMutator: RunTestDocumentMutator() ) - - await fixture.service.loadProject( - at: fixture.root, - files: [], - snapshotID: UUID() + let options = RunOptions( + workingDirectoryPath: "backend app", + programArguments: "--dev" ) - fixture.service.run(configuration: configuration, currentFileURL: nil) - - let request = try #require(fixture.process.requests.last) - #expect(request.executablePath == "/toolchains/maven/bin/mvn") - #expect(request.arguments == plan.arguments) - #expect(request.workingDirectory == fixture.root.appendingPathComponent("backend").path) - #expect(request.environment?["JAVA_HOME"] == "/toolchains/jdk") - #expect(fixture.operations.launchPlanIDs == [configuration.id]) - } - @Test - func runAllSpringBootServicesUsesPreparedJavaTargetAndProjectJDK() async throws { - let configuration = JavaRunConfiguration( - id: "spring-boot.maven:ruoyi-admin", - name: "ruoyi-admin", - kind: .springBoot, - modulePath: "ruoyi-admin", - mainClass: "com.ruoyi.RuoYiApplication" - ) - let target = JavaDebugLaunchTarget( - mainClass: "com.ruoyi.RuoYiApplication", - projectName: "ruoyi-admin", - modulePaths: [], - classPaths: ["/workspace/RuoYi/ruoyi-admin/target/classes"] - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-jdk"), - arguments: ["com.ruoyi.RuoYiApplication"], - workingDirectory: ".", - classpath: target.classPaths - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: JavaRunOptions())], - plans: [configuration.id: plan] + try store.saveOptions( + options, + configurationID: "spring:com.example.App", + scope: .local, + at: root ) - - await fixture.service.loadProject( - at: fixture.root, - files: [], - snapshotID: UUID() + let writesAfterFirstSave = storage.writeCount + try store.saveOptions( + options, + configurationID: "spring:com.example.App", + scope: .local, + at: root ) - fixture.service.runAllServices(javaLaunches: [configuration.id: target]) - let request = try #require(fixture.processFactory.processes.last?.requests.last) - #expect(request.executablePath == "/toolchains/jdk/bin/java") - #expect(request.arguments == [ - "-cp", "/workspace/RuoYi/ruoyi-admin/target/classes", - "com.ruoyi.RuoYiApplication", - ]) - #expect(fixture.operations.javaLaunchTargets == [target]) + #expect(writesAfterFirstSave == 1) + #expect(storage.writeCount == writesAfterFirstSave) } @Test - func toolchainBackedGoPlanUsesTheRegisteredProviderInRunService() async throws { - let configuration = RunConfiguration( - id: "go:api", - name: "Go API", - kind: .process(provider: "go.main"), - modulePath: nil, - mainClass: nil - ) - let plan = SharedLaunchPlan( - executable: .toolchain("project-go"), - arguments: ["run", "./cmd/api"], - workingDirectory: ".", - environment: ["APP_ENV": "test"] - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: RunOptions())], - plans: [configuration.id: plan] + func failedAtomicWritePreservesExistingLocalConfiguration() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("lithe-failed-write-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let storage = CountingFileStorage(root: root) + let localURL = root.appendingPathComponent(".lithe/run/local.json") + let original = Data(#"{"version":1,"configurations":[]}"#.utf8) + storage.seed(original, at: localURL) + storage.shouldFailWrites = true + let store = MacRunConfigurationStore( + core: RustCoreBridge(), + storage: storage, + preferences: RunTestKeyValueStore(), + documentMutator: RunTestDocumentMutator() ) - await fixture.service.loadProject(at: fixture.root, files: []) - fixture.service.run(configuration: configuration, currentFileURL: nil) - - let request = try #require(fixture.process.requests.last) - #expect(request.executablePath == "/usr/bin/go") - #expect(request.arguments == ["run", "./cmd/api"]) - #expect(request.environment?["APP_ENV"] == "test") - #expect(request.environment?["JAVA_HOME"] == nil) - #expect(fixture.operations.lastToolchainCandidates.contains { - $0.id == "project-go" && $0.type == "go" - }) + #expect(throws: (any Error).self) { + try store.saveOptions( + RunOptions(programArguments: "-Xmx2g"), + configurationID: "current-file", + scope: .local, + at: root + ) + } + #expect(try storage.readData(from: localURL, options: []) == original) } @Test - func currentFilePythonRunUsesTheLanguageProviderInsteadOfJavaCore() async throws { - let current = RunConfiguration.currentFile - let fixture = makeFixture( - status: .ready, - effective: [] - ) - let source = fixture.root.appendingPathComponent("scripts/main.py") - - await fixture.service.loadProject( - at: fixture.root, - files: [source] - ) - #expect(fixture.service.configurations == [current]) - fixture.service.run(configuration: current, currentFileURL: source) - - let request = try #require(fixture.process.requests.last) - #expect(request.executablePath == "/usr/bin/python3") - #expect(request.arguments == ["scripts/main.py"]) - #expect(request.environment?["JAVA_HOME"] == nil) - #expect(fixture.operations.launchPlanIDs.isEmpty) + func inspectionErrorsMapToSafeRecoveryActionsAndFiles() { + #expect(MacRunConfigurationStore.recoveryAction(for: "not_supported") == .upgradeApplication) + #expect(MacRunConfigurationStore.recoveryAction(for: "parse_failed") == .editConfiguration) + #expect(MacRunConfigurationStore.recoveryAction(for: "permission_denied") == .fixPermissions) + #expect(MacRunConfigurationStore.recoveryPath( + in: "Configuration JSON is invalid: .lithe/run/local.json: line 1" + ) == ".lithe/run/local.json") + #expect(MacRunConfigurationStore.recoveryPath( + in: "Configuration JSON is invalid: .lithe/toolchains/local.json: line 1" + ) == nil) } @Test - func runAllServicesUsesOneSharedLaunchPlanPerService() async throws { - let first = JavaRunConfiguration( - id: "module:backend", - name: "backend", - kind: .mavenModule, - execution: .service, - modulePath: "backend", - mainClass: nil - ) - let second = JavaRunConfiguration( - id: "module:worker", - name: "worker", - kind: .mavenModule, - execution: .service, - modulePath: "worker", - mainClass: nil - ) - let firstPlan = SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-pl", "backend", "-am", "spring-boot:run"], - workingDirectory: "." - ) - let secondPlan = SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-pl", "worker", "-am", "-P", "local", "spring-boot:run"], - workingDirectory: "worker" - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration(configuration: first, options: JavaRunOptions()), - EffectiveRunConfiguration(configuration: second, options: JavaRunOptions()) - ], - plans: [first.id: firstPlan, second.id: secondPlan] - ) + func appOwnedFileEventSuppressionIsOneShotAndExpires() { + let first = URL(fileURLWithPath: "/tmp/lithe-self-write-one.json") + let second = URL(fileURLWithPath: "/tmp/lithe-self-write-two.json") + let now = Date(timeIntervalSince1970: 1_000) - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.service.runAllServices() - - #expect(fixture.operations.launchPlanIDs == [first.id, second.id]) - #expect(fixture.processFactory.processes.count == 2) - let requests = try fixture.processFactory.processes.map { try #require($0.requests.last) } - #expect(requests.map(\.arguments) == [firstPlan.arguments, secondPlan.arguments]) - #expect(requests.map(\.workingDirectory) == [ - fixture.root.path, - fixture.root.appendingPathComponent("worker").path - ]) - } + MacFileWriteEventSuppression.markWritten(first, now: now) + #expect(MacFileWriteEventSuppression.consume(first, now: now.addingTimeInterval(1))) + #expect(!MacFileWriteEventSuppression.consume(first, now: now.addingTimeInterval(1))) - /// The concurrent-session path was written for Maven and hard-required a - /// `project-maven` toolchain. A full-stack project has to bring up its Java - /// service and its Node service side by side, each resolved its own way. - @Test - func runAllServicesStartsMavenAndProcessServicesTogether() async throws { - let backend = JavaRunConfiguration( - id: "module:backend", - name: "backend", - kind: .mavenModule, - execution: .service, - modulePath: "backend", - mainClass: nil - ) - let frontend = JavaRunConfiguration( - id: "npm.script:frontend-web/dev", - name: "dev", - kind: .process(provider: "npm.script"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let backendPlan = SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["-B", "-ntp", "-pl", "backend", "-am", "spring-boot:run"], - workingDirectory: "." - ) - let frontendPlan = SharedLaunchPlan( - executable: .command("pnpm"), - arguments: ["run", "dev"], - workingDirectory: "frontend-web", - environment: ["PORT": "5173"] - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration(configuration: backend, options: JavaRunOptions()), - EffectiveRunConfiguration(configuration: frontend, options: JavaRunOptions()) - ], - plans: [backend.id: backendPlan, frontend.id: frontendPlan] - ) + MacFileWriteEventSuppression.markWritten(second, now: now) + #expect(!MacFileWriteEventSuppression.consume(second, now: now.addingTimeInterval(3))) + } - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.service.runAllServices() - - #expect(fixture.processFactory.processes.count == 2) - #expect(fixture.service.moduleSessions.map(\.id) == [backend.id, frontend.id]) - #expect(fixture.service.moduleSessions.allSatisfy { $0.isRunning }) - - let requests = try fixture.processFactory.processes.map { try #require($0.requests.last) } - #expect(requests[0].executablePath == "/toolchains/maven/bin/mvn") - #expect(requests[1].executablePath == "/usr/bin/pnpm") - #expect(requests[1].arguments == ["run", "dev"]) - #expect(requests[1].workingDirectory == fixture.root.appendingPathComponent("frontend-web").path) - // A process plan carries its own environment and must not inherit Maven's. - #expect(requests[1].environment?["PORT"] == "5173") - #expect(requests[1].environment?["JAVA_HOME"] == nil) + private static func framedJSON(_ data: Data?) -> [String: Any]? { + guard let data, + let separator = data.range(of: Data("\r\n\r\n".utf8)) else { return nil } + let body = data.subdata(in: separator.upperBound.. LanguageServerReliabilityHarness { + let descriptor = LanguageProviderDescriptor( + id: "swift", + displayName: "Swift", + fileExtensions: ["swift"], + capabilities: [.languageServer, .formatting], + activationPolicy: .onDemand, + languageIdentifier: "swift" ) - let backendPlan = SharedLaunchPlan( - executable: .toolchain("project-maven"), - arguments: ["spring-boot:run"], - workingDirectory: "." + let root = URL(fileURLWithPath: "/tmp/lithe-lsp-reliability", isDirectory: true) + let source = root.appendingPathComponent("App.swift") + let core = TestLanguageServerRuntimeCore(providerID: "swift") + let session = StdioLanguageServerSession( + providerID: "swift", + executableURL: URL(fileURLWithPath: "/usr/bin/sourcekit-lsp"), + arguments: [], + environment: [:], + initializeTimeout: TimeInterval(initializeTimeoutNanoseconds) / 1_000_000_000, + requestTimeout: TimeInterval(requestTimeoutNanoseconds) / 1_000_000_000, + core: core ) - let diagnostic = RunConfigurationDiagnostic( - configurationID: frontend.id, - code: "missingToolchain", - message: "No local node toolchain is selected" + let runtime = TestLanguageServerRuntime(descriptor: descriptor, session: session) + let manager = LanguageToolingSessionManager( + catalog: LanguageProviderCatalog(descriptors: [descriptor]), + runtimes: [runtime], policyCore: policyCore ) - let fixture = makeFixture( - status: .ready, - effective: [backend, frontend].map { - EffectiveRunConfiguration(configuration: $0, options: RunOptions()) - }, - plans: [backend.id: backendPlan], - diagnostics: [diagnostic] + return LanguageServerReliabilityHarness( + root: root, + source: source, + core: core, + session: session, + manager: manager ) + } - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.service.runAllServices() + private static func debugRequest(named command: String, in frames: [Data]) -> [String: Any]? { + frames.lazy + .compactMap(framedJSON) + .first { message in + message["type"] as? String == "request" && message["command"] as? String == command + } + } - #expect(fixture.operations.launchPlanIDs == [backend.id]) - #expect(fixture.processFactory.processes.count == 1) - let backendSession = try #require( - fixture.service.moduleSessions.first(where: { $0.id == backend.id }) - ) - let frontendSession = try #require( - fixture.service.moduleSessions.first(where: { $0.id == frontend.id }) - ) - #expect(backendSession.isRunning) - #expect(!frontendSession.isRunning) - #expect(frontendSession.exitCode == 1) - #expect(frontendSession.output.contains("No local node toolchain")) - } - - @Test - func serviceAddressUsesExplicitArgumentsAndEnvironmentPorts() async throws { - let argumentService = JavaRunConfiguration( - id: "npm.script:web/dev", - name: "dev", - kind: .process(provider: "npm.script"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let environmentService = JavaRunConfiguration( - id: "python.uvicorn:api", - name: "api", - kind: .process(provider: "python.uvicorn"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration( - configuration: argumentService, - options: RunOptions(programArguments: "--host 0.0.0.0 --port 5173") - ), - EffectiveRunConfiguration( - configuration: environmentService, - options: RunOptions(environment: ["PORT": "8000"]) - ) - ] - ) - - await fixture.service.loadProject(at: fixture.root, files: []) - - #expect(fixture.service.serviceURL(for: argumentService)?.absoluteString == "http://127.0.0.1:5173") - #expect(fixture.service.serviceURL(for: environmentService)?.absoluteString == "http://127.0.0.1:8000") - } - - @Test - func serviceAddressRejectsUnknownInvalidAndNonServicePorts() async throws { - let unknown = JavaRunConfiguration( - id: "npm.script:web/dev", - name: "dev", - kind: .process(provider: "npm.script"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let invalid = JavaRunConfiguration( - id: "python.uvicorn:api", - name: "api", - kind: .process(provider: "python.uvicorn"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let application = JavaRunConfiguration( - id: "go.main:cli", - name: "cli", - kind: .process(provider: "go.main"), - execution: .application, - modulePath: nil, - mainClass: nil - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration(configuration: unknown, options: RunOptions()), - EffectiveRunConfiguration( - configuration: invalid, - options: RunOptions(programArguments: "--port 70000") - ), - EffectiveRunConfiguration( - configuration: application, - options: RunOptions(environment: ["PORT": "4321"]) - ) - ] - ) - - await fixture.service.loadProject(at: fixture.root, files: []) - - #expect(fixture.service.serviceURL(for: unknown) == nil) - #expect(fixture.service.serviceURL(for: invalid) == nil) - #expect(fixture.service.serviceURL(for: application) == nil) - } - - @Test - func runAllServicesExcludesApplicationsAndTasks() async throws { - let service = JavaRunConfiguration( - id: "npm.script:web/dev", - name: "dev", - kind: .process(provider: "npm.script"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let application = JavaRunConfiguration( - id: "go.command:cmd/migrate/migrate", - name: "migrate", - kind: .process(provider: "go.command"), - execution: .application, - modulePath: nil, - mainClass: nil - ) - let task = JavaRunConfiguration( - id: "npm.script:web/build", - name: "build", - kind: .process(provider: "npm.script"), - execution: .task, - modulePath: nil, - mainClass: nil - ) - let servicePlan = SharedLaunchPlan( - executable: .command("npm"), - arguments: ["run", "dev"], - workingDirectory: "web" - ) - let fixture = makeFixture( - status: .ready, - effective: [service, application, task].map { - EffectiveRunConfiguration(configuration: $0, options: JavaRunOptions()) - }, - plans: [service.id: servicePlan] - ) - - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.service.runAllServices() - - #expect(fixture.operations.launchPlanIDs == [service.id]) - #expect(fixture.service.moduleSessions.map(\.id) == [service.id]) - #expect(fixture.processFactory.processes.count == 1) - } - - /// Services start individually, not only as an all-at-once batch. - @Test - func startingASingleProcessServiceCreatesItsOwnSession() async throws { - let frontend = JavaRunConfiguration( - id: "npm.script:frontend-web/dev", - name: "dev", - kind: .process(provider: "npm.script"), - execution: .service, - modulePath: nil, - mainClass: nil - ) - let plan = SharedLaunchPlan( - executable: .command("pnpm"), - arguments: ["run", "dev"], - workingDirectory: "frontend-web" - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: frontend, options: JavaRunOptions())], - plans: [frontend.id: plan] - ) - - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.service.startConfiguration(frontend) - - let session = try #require(fixture.service.moduleSessions.first) - #expect(session.configurationID == frontend.id) - #expect(session.isRunning) - #expect(fixture.processFactory.processes.count == 1) } - - @Test - func projectRuntimeResolvesServiceLevelToolchainOverrides() throws { - let root = URL(fileURLWithPath: "/tmp/lithe-runtime-toolchains", isDirectory: true) - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - runtime.openProject(at: root) - - #expect(runtime.javaExecutableURL(overridePath: "/local/JDK 21")?.path == "/local/JDK 21/bin/java") - #expect(runtime.mavenExecutable(at: root, overridePath: "/local/Maven 3.9/bin/mvn")?.path == "/local/Maven 3.9/bin/mvn") - #expect(runtime.environment(for: .maven, javaHomeOverride: "/local/Maven JDK")["JAVA_HOME"] == "/local/Maven JDK") - } - - @Test - func projectRuntimePublishesAReadyJavaEnvironmentReport() async throws { - let root = URL(fileURLWithPath: "/tmp/lithe-java-health", isDirectory: true) - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - runtime.openProject(at: root) - await runtime.refreshAvailableRuntimes() - - let report = try #require(runtime.javaEnvironmentReport) - #expect(report.status == .ready) - #expect(report.javaHomePath == "/toolchains/jdk") - #expect(!report.status.blocksJavaRun) - } - - @Test - func projectRuntimeStronglyReportsMissingJDK() async throws { - let root = URL(fileURLWithPath: "/tmp/lithe-java-health-missing", isDirectory: true) - let runtime = ProjectRuntimeService( - runtimeLocator: MissingJavaRuntimeLocator(), - store: RunTestKeyValueStore() - ) - runtime.openProject(at: root) - await runtime.refreshAvailableRuntimes() - - let report = try #require(runtime.javaEnvironmentReport) - #expect(report.status == .jdkMissing) - #expect(report.status.blocksJavaRun) - #expect(report.recovery.contains("JAVA_HOME")) - } - - @Test - func generationPublishesNoEntryResultAndKeepsCurrentFileAvailable() async { - let current = JavaRunConfiguration.currentFile - let fixture = makeFixture( - status: .missing, - effective: [EffectiveRunConfiguration(configuration: current, options: JavaRunOptions())], - generationEntryCount: 0 - ) - - await fixture.service.loadProject( - at: fixture.root, - files: [], - snapshotID: UUID() - ) - await fixture.service.generateRunConfigurations() - - #expect(fixture.service.configurationStatus == .ready) - #expect(!fixture.service.isLoadingProject) - #expect(fixture.service.generationState == .noEntries) - #expect(fixture.service.configurations == [current]) - } - - @Test - func projectOptionsAreWrittenToTeamFileWithoutLocalJDKPath() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-project-options-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory( - at: root.appendingPathComponent(".lithe/run"), - withIntermediateDirectories: true - ) - let store = MacRunConfigurationStore( - core: RustCoreBridge(), - storage: MacFileStorage(), - preferences: RunTestKeyValueStore(), - documentMutator: RunTestDocumentMutator() - ) - - try store.saveOptions( - JavaRunOptions( - javaHomePath: "/Library/Java/private-jdk", - workingDirectoryPath: root.appendingPathComponent("backend app").path, - vmArguments: "-Xmx2g", - programArguments: "--dev", - activeProfiles: ["dev"] - ), - configurationID: "spring:com.example.App", - scope: .project, - at: root - ) - - let data = try Data(contentsOf: root.appendingPathComponent(".lithe/run/configurations.json")) - let text = String(decoding: data, as: UTF8.self) - #expect(text.contains("backend app")) - #expect(!text.contains("private-jdk")) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/toolchains/local.json").path)) - #expect(throws: (any Error).self) { - try store.saveOptions( - JavaRunOptions(workingDirectoryPath: "../outside"), - configurationID: "spring:com.example.App", - scope: .project, - at: root - ) - } - } - - @Test - func creatingProjectConfigurationWritesTypedTeamEntry() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-create-project-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory( - at: root.appendingPathComponent("backend/src/main/java/com/example"), - withIntermediateDirectories: true - ) - try Data("package com.example; class App { public static void main(String[] args) {} }".utf8) - .write(to: root.appendingPathComponent("backend/src/main/java/com/example/App.java")) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: RunTestKeyValueStore(), documentMutator: RunTestDocumentMutator()) - - let id = try store.createConfiguration( - RunConfigurationDraft(name: "Backend Dev", kind: .springBoot, modulePath: "backend", mainClass: "com.example.App", scope: .project), - at: root - ) - #expect(id == "user:backend-dev") - let data = try Data(contentsOf: root.appendingPathComponent(".lithe/run/configurations.json")) - let document = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) - let configurations = try #require(document["configurations"] as? [[String: Any]]) - #expect(configurations.first?["type"] as? String == "spring-boot.maven") - #expect(configurations.first?["module"] as? String == "backend") - #expect(configurations.first?["mainClass"] as? String == "com.example.App") - } - - @Test - func linkedRustCoreMutatesDocumentsThroughTheProductionAdapter() throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-linked-mutation-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory( - at: root.appendingPathComponent("src/main/java/com/example"), - withIntermediateDirectories: true - ) - try Data("package com.example; class App { public static void main(String[] args) {} }".utf8) - .write(to: root.appendingPathComponent("src/main/java/com/example/App.java")) - let store = MacRunConfigurationStore( - core: core, - storage: MacFileStorage(), - preferences: RunTestKeyValueStore() - ) - // Core identifies Current File in memory; the workspace holds only user documents. - _ = try store.generate( - at: root, - files: [root.appendingPathComponent("src/main/java/com/example/App.java")], - modulePaths: [], - javaEntrypoints: nil - ) - - try store.saveOptions( - JavaRunOptions(vmArguments: "\"-Dlabel=hello world\" -Xmx2g"), - configurationID: "current-file", - scope: .project, - at: root - ) - let id = try store.createConfiguration( - RunConfigurationDraft( - name: "Backend Dev", - kind: .springBoot, - modulePath: ".", - mainClass: "com.example.App", - scope: .project - ), - at: root - ) - - #expect(id == "user:backend-dev") - let data = try Data(contentsOf: root.appendingPathComponent(".lithe/run/configurations.json")) - let document = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) - let configurations = try #require(document["configurations"] as? [[String: Any]]) - #expect(configurations.count == 2) - let mavenExtension = try #require( - configurations.first?["extensions"] as? [String: Any] - ) - let mavenOptions = try #require(mavenExtension["maven"] as? [String: Any]) - #expect(mavenOptions["jvmArguments"] as? [String] == ["-Dlabel=hello world", "-Xmx2g"]) - } - - private func generateConfirmedSpringService(at root: URL, store: MacRunConfigurationStore) throws { - // A plugin declaration alone no longer establishes an application. Model - // the confirmed JDT entry so these tests exercise persistence, not detection failure. - let sourcePath = "src/main/java/demo/App.java" - let source = root.appendingPathComponent(sourcePath) - try FileManager.default.createDirectory(at: source.deletingLastPathComponent(), - withIntermediateDirectories: true) - try Data("package demo; @SpringBootApplication public class App { public static void main(String[] args) {} }".utf8) - .write(to: source) - _ = try store.generate(at: root, files: [source], modulePaths: [], javaEntrypoints: JavaEntrypoints( - entries: [JavaEntrypoint(sourcePath: sourcePath, mainClass: "demo.App", projectName: "demo")] - )) - let resolved = try store.resolve(at: root, toolchainCandidates: []) - _ = try #require(resolved.configurations.first { $0.configuration.id == "spring-boot.maven:demo" }) - } - - @Test - func serviceToolchainOverridesRoundTripThroughRustConfigurationDocuments() throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-service-toolchains-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - try Data(#"demoorg.springframework.bootspring-boot-maven-plugin"#.utf8) - .write(to: root.appendingPathComponent("pom.xml")) - let store = MacRunConfigurationStore( - core: core, - storage: MacFileStorage(), - preferences: RunTestKeyValueStore() - ) - // Core identifies the project in memory; the workspace holds only user documents. - try generateConfirmedSpringService(at: root, store: store) - try store.saveOptions( - RunOptions( - javaHomePath: "/test/jdk-21", - mavenSkipTests: false, - mavenExecutablePath: "/test/maven/bin/mvn", - mavenJavaHomePath: "/test/maven-jdk" - ), - configurationID: "spring-boot.maven:demo", - scope: .local, - at: root - ) - - let resolved = try store.resolve(at: root, toolchainCandidates: []) - let options = try #require(resolved.configurations.first { $0.configuration.id == "spring-boot.maven:demo" }?.options) - #expect(options.javaHomePath == "/test/jdk-21") - #expect(options.mavenExecutablePath == "/test/maven/bin/mvn") - #expect(options.mavenJavaHomePath == "/test/maven-jdk") - #expect(options.mavenSkipTests == false) - } - - @Test - func projectToolchainSelectionsPersistAsProjectRelativePaths() throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-project-toolchains-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - for path in [".lithe/run", "toolchains/jdk", "toolchains/maven/bin", "toolchains/maven-jdk"] { - try FileManager.default.createDirectory( - at: root.appendingPathComponent(path, isDirectory: true), - withIntermediateDirectories: true - ) - } - try Data("#!/bin/sh\n".utf8) - .write(to: root.appendingPathComponent("toolchains/maven/bin/mvn")) - try Data(#"demoorg.springframework.bootspring-boot-maven-plugin"#.utf8) - .write(to: root.appendingPathComponent("pom.xml")) - let store = MacRunConfigurationStore( - core: core, - storage: MacFileStorage(), - preferences: RunTestKeyValueStore() - ) - // Core identifies the project in memory; the workspace holds only user documents. - try generateConfirmedSpringService(at: root, store: store) - - try store.saveOptions( - RunOptions( - javaHomePath: root.appendingPathComponent("toolchains/jdk").path, - mavenExecutablePath: root.appendingPathComponent("toolchains/maven/bin/mvn").path, - mavenJavaHomePath: root.appendingPathComponent("toolchains/maven-jdk").path - ), - configurationID: "spring-boot.maven:demo", - scope: .project, - at: root - ) - - let resolved = try store.resolve(at: root, toolchainCandidates: []) - let options = try #require(resolved.configurations.first { $0.configuration.id == "spring-boot.maven:demo" }?.options) - #expect(options.javaHomePath == "toolchains/jdk") - #expect(options.mavenExecutablePath == "toolchains/maven/bin/mvn") - #expect(options.mavenJavaHomePath == "toolchains/maven-jdk") - } - - @Test - func goRuntimeToolchainFlowsFromSharedJSONIntoProcessRequest() async throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-go-runtime-toolchain-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory( - at: root.appendingPathComponent(".lithe/run"), - withIntermediateDirectories: true - ) - // A saved team configuration; Core's detected layer is identified below. - try Data(#"{"version":2,"configurations":[{"id":"user:go-api","name":"Go API","provider":"go.main","execution":"application","args":["run","./cmd/api"],"cwd":".","env":{"APP_ENV":"test"},"toolchains":{"runtime":"project-go"}}]}"#.utf8) - .write(to: root.appendingPathComponent(".lithe/run/configurations.json")) - - let preferences = RunTestKeyValueStore() - let store = MacRunConfigurationStore( - core: core, - storage: MacFileStorage(), - preferences: preferences - ) - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: preferences - ) - let process = RecordingStreamingProcess() - let service = RunService( - runtimeService: runtime, - process: process, - processFactory: { RecordingStreamingProcess() }, - fileStorage: MacFileStorage(), - preferences: preferences, - javaMavenOperations: RunTestJavaMavenOperations(), - runConfigurationOperations: store - ) - - _ = try store.generate(at: root, files: [], modulePaths: [], javaEntrypoints: nil) - await service.loadProject(at: root, files: []) - let configuration = try #require(service.configurations.first { $0.id == "user:go-api" }) - - service.run(configuration: configuration, currentFileURL: nil) - - let request = try #require(process.requests.last) - #expect(request.executablePath == "/usr/bin/go") - #expect(request.arguments == ["run", "./cmd/api"]) - #expect(request.workingDirectory == root.path) - #expect(request.environment?["APP_ENV"] == "test") - #expect(request.environment?["JAVA_HOME"] == nil) - } - - @Test - func generationSucceedsWithoutWritingTheWorkspace() throws { - let core = RustCoreBridge() - guard core.isAvailable else { return } - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-generation-read-only-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root.appendingPathComponent("src"), withIntermediateDirectories: true) - let source = root.appendingPathComponent("src/App.java") - try Data("class App { public static void main(String[] args) {} }".utf8).write(to: source) - let storage = CountingFileStorage(root: root) - storage.shouldFailWrites = true - let store = MacRunConfigurationStore( - core: core, - storage: storage, - preferences: RunTestKeyValueStore() - ) - - let result = try store.generate(at: root, files: [source], modulePaths: [], javaEntrypoints: nil) - #expect(result.entryCount == 0) - #expect(storage.writeCount == 0) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe").path)) - #expect(store.inspect(at: root).status == .ready) - } - - @Test - func creatingLocalConfigurationWritesLocalEntryAndDisambiguatesName() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-create-local-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: RunTestKeyValueStore(), documentMutator: RunTestDocumentMutator()) - let draft = RunConfigurationDraft(name: "Backend Dev", kind: .mavenModule, modulePath: ".", mainClass: "", scope: .local) - _ = try store.createConfiguration(draft, at: root) - let second = try store.createConfiguration(draft, at: root) - #expect(second == "user:backend-dev-2") - #expect(FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/local.json").path)) - #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(".lithe/run/configurations.json").path)) - } - - @Test - func creatingSpringBootConfigurationRequiresMainClassAndRejectsOutsideModule() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-create-validation-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: RunTestKeyValueStore(), documentMutator: RunTestDocumentMutator()) - #expect(throws: (any Error).self) { - try store.createConfiguration( - RunConfigurationDraft(name: "Broken", kind: .springBoot, modulePath: ".", mainClass: "", scope: .project), - at: root - ) - } - #expect(throws: (any Error).self) { - try store.createConfiguration( - RunConfigurationDraft(name: "Outside", kind: .mavenModule, modulePath: "../other", mainClass: "", scope: .project), - at: root - ) - } - } - - @Test - func configurationWriteRejectsLitheSymlinkOutsideProject() throws { - let base = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-symlink-write-\(UUID().uuidString)", isDirectory: true) - let root = base.appendingPathComponent("project", isDirectory: true) - let outside = base.appendingPathComponent("outside", isDirectory: true) - defer { try? FileManager.default.removeItem(at: base) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink( - at: root.appendingPathComponent(".lithe"), - withDestinationURL: outside - ) - let store = MacRunConfigurationStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: RunTestKeyValueStore(), documentMutator: RunTestDocumentMutator()) - - #expect(throws: (any Error).self) { - try store.createConfiguration( - RunConfigurationDraft(name: "Outside", kind: .mavenModule, modulePath: ".", mainClass: "", scope: .project), - at: root - ) - } - #expect(!FileManager.default.fileExists(atPath: outside.appendingPathComponent("run/configurations.json").path)) - } - - @Test - func unchangedLocalOptionsDoNotRewriteTheConfigurationFile() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-unchanged-write-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let storage = CountingFileStorage(root: root) - let store = MacRunConfigurationStore( - core: RustCoreBridge(), - storage: storage, - preferences: RunTestKeyValueStore(), - documentMutator: RunTestDocumentMutator() - ) - let options = JavaRunOptions( - workingDirectoryPath: "backend app", - vmArguments: "-Xmx2g", - programArguments: "--dev", - activeProfiles: ["dev"] - ) - - try store.saveOptions( - options, - configurationID: "spring:com.example.App", - scope: .local, - at: root - ) - let writesAfterFirstSave = storage.writeCount - try store.saveOptions( - options, - configurationID: "spring:com.example.App", - scope: .local, - at: root - ) - - #expect(writesAfterFirstSave == 1) - #expect(storage.writeCount == writesAfterFirstSave) - } - - @Test - func failedAtomicWritePreservesExistingLocalConfiguration() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-failed-write-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let storage = CountingFileStorage(root: root) - let localURL = root.appendingPathComponent(".lithe/run/local.json") - let original = Data(#"{"version":1,"configurations":[]}"#.utf8) - storage.seed(original, at: localURL) - storage.shouldFailWrites = true - let store = MacRunConfigurationStore( - core: RustCoreBridge(), - storage: storage, - preferences: RunTestKeyValueStore(), - documentMutator: RunTestDocumentMutator() - ) - - #expect(throws: (any Error).self) { - try store.saveOptions( - JavaRunOptions(vmArguments: "-Xmx2g"), - configurationID: "current-file", - scope: .local, - at: root - ) - } - #expect(try storage.readData(from: localURL, options: []) == original) - } - - @Test - func teamDefaultAndEffectiveSourceAreApplied() async throws { - let first = JavaRunConfiguration.currentFile - let second = JavaRunConfiguration( - id: "spring:com.example.App", - name: "App", - kind: .springBoot, - modulePath: nil, - mainClass: "com.example.App" - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration(configuration: first, options: JavaRunOptions()), - EffectiveRunConfiguration( - configuration: second, - options: JavaRunOptions(vmArguments: "-Xmx2g"), - source: .project - ) - ], - defaultConfigurationID: second.id - ) - - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - - #expect(fixture.service.selectedConfigurationID == second.id) - #expect(fixture.service.source(for: second) == .project) - #expect(fixture.operations.migrationCalls == 0) - } - - @Test - func duplicateEffectiveConfigurationIDsDoNotCrashServiceProjection() async throws { - let configuration = JavaRunConfiguration( - id: "java-main:com.example.App", - name: "App", - kind: .javaMain, - modulePath: nil, - mainClass: "com.example.App" - ) - let fixture = makeFixture( - status: .ready, - effective: [ - EffectiveRunConfiguration( - configuration: configuration, - options: JavaRunOptions(vmArguments: "-Xmx1g"), - source: .project - ), - EffectiveRunConfiguration( - configuration: configuration, - options: JavaRunOptions(vmArguments: "-Xmx2g"), - source: .local - ) - ] - ) - - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - - let projected = try #require( - fixture.service.configurations.first { $0.id == configuration.id } - ) - #expect(fixture.service.configurations.count { $0.id == configuration.id } == 1) - #expect(fixture.service.options(for: projected).vmArguments == "-Xmx1g") - #expect(fixture.service.source(for: projected) == .project) - } - - @Test - func createdConfigurationIsResolvedAndSelected() async { - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: .currentFile, options: JavaRunOptions())] - ) - await fixture.service.loadProject(at: fixture.root, files: []) - - let created = fixture.service.createConfiguration( - RunConfigurationDraft( - name: "Backend Dev", - kind: .mavenModule, - modulePath: "backend", - mainClass: "", - scope: .project - ) - ) - - #expect(created) - #expect(fixture.service.selectedConfigurationID == "user:backend-dev") - #expect(fixture.service.selectedConfiguration?.name == "Backend Dev") - #expect(fixture.operations.createdDrafts.count == 1) - } - - @Test - func recentConfigurationSelectionIsRestoredFromLocalPreferences() async { - let preferences = RunTestKeyValueStore() - let current = EffectiveRunConfiguration(configuration: .currentFile, options: JavaRunOptions()) - let backend = JavaRunConfiguration( - id: "module:backend", - name: "backend", - kind: .mavenModule, - modulePath: "backend", - mainClass: nil - ) - let first = makeFixture( - status: .ready, - effective: [current, EffectiveRunConfiguration(configuration: backend, options: JavaRunOptions())], - preferences: preferences - ) - await first.service.loadProject(at: first.root, files: []) - first.service.select(backend) - - let reopened = makeFixture( - status: .ready, - effective: [current, EffectiveRunConfiguration(configuration: backend, options: JavaRunOptions())], - preferences: preferences - ) - await reopened.service.loadProject(at: reopened.root, files: []) - - #expect(reopened.service.selectedConfigurationID == backend.id) - } - - @Test - func staleProjectLoadCannotReplaceTheNewProjectState() async { - let oldRoot = URL(fileURLWithPath: "/tmp/lithe-old-project", isDirectory: true) - let newRoot = URL(fileURLWithPath: "/tmp/lithe-new-project", isDirectory: true) - let operations = BlockingInspectionOperations(blockedProjectURL: oldRoot) - defer { operations.releaseBlockedInspection() } - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let service = JavaRunService( - runtimeService: runtime, - process: RecordingStreamingProcess(), - processFactory: { RecordingStreamingProcess() }, - fileStorage: RunTestFileStorage(), - preferences: RunTestKeyValueStore(), - javaMavenOperations: RunTestJavaMavenOperations(), - runConfigurationOperations: operations - ) - - let oldLoad = Task { - await service.loadProject(at: oldRoot, files: []) - } - #expect(await operations.waitUntilBlocked()) - await service.loadProject(at: newRoot, files: []) - operations.releaseBlockedInspection() - await oldLoad.value - - #expect(service.configurationStatus == .missing) - #expect(service.configurations.isEmpty) - #expect(!service.isLoadingProject) - } - - @Test - func projectReloadDuringGenerationDoesNotLeaveRunServiceLoading() async { - let root = URL(fileURLWithPath: "/tmp/lithe-generation-reload", isDirectory: true) - let operations = BlockingGenerationOperations() - defer { operations.releaseGeneration() } - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let service = JavaRunService( - runtimeService: runtime, - process: RecordingStreamingProcess(), - processFactory: { RecordingStreamingProcess() }, - fileStorage: RunTestFileStorage(), - preferences: RunTestKeyValueStore(), - javaMavenOperations: RunTestJavaMavenOperations(), - runConfigurationOperations: operations - ) - - let snapshotID = UUID() - await service.loadProject(at: root, files: [], snapshotID: snapshotID) - let generation = Task { await service.generateRunConfigurations() } - #expect(await operations.waitUntilBlocked()) - await service.loadProject(at: root, files: [], snapshotID: snapshotID) - operations.releaseGeneration() - await generation.value - - #expect(!service.isLoadingProject) - } - - @Test - func inspectionErrorsMapToSafeRecoveryActionsAndFiles() { - #expect(MacRunConfigurationStore.recoveryAction(for: "not_supported") == .upgradeApplication) - #expect(MacRunConfigurationStore.recoveryAction(for: "parse_failed") == .editConfiguration) - #expect(MacRunConfigurationStore.recoveryAction(for: "permission_denied") == .fixPermissions) - #expect(MacRunConfigurationStore.recoveryPath( - in: "Configuration JSON is invalid: .lithe/run/local.json: line 1" - ) == ".lithe/run/local.json") - #expect(MacRunConfigurationStore.recoveryPath( - in: "Configuration JSON is invalid: .lithe/toolchains/local.json: line 1" - ) == nil) - } - - @Test - func projectEditorSaveForwardsSelectedToolchainPaths() async { - let configuration = JavaRunConfiguration( - id: "spring", - name: "Spring", - kind: .springBoot, - modulePath: ".", - mainClass: nil - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration( - configuration: configuration, - options: RunOptions(), - source: .generated - )] - ) - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - let options = RunOptions( - javaHomePath: "toolchains/jdk", - mavenExecutablePath: "toolchains/maven/bin/mvn", - mavenJavaHomePath: "toolchains/maven-jdk" - ) - - #expect(fixture.service.saveEditorChanges( - options, - for: configuration, - scope: .project - )) - #expect(fixture.operations.savedOptions == [options]) - #expect(fixture.operations.savedScopes == [.project]) - } - - @Test - func editorChangesUseOneRunConfigurationOperation() async { - let configuration = JavaRunConfiguration( - id: "spring", - name: "Spring", - kind: .springBoot, - modulePath: ".", - mainClass: nil - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration( - configuration: configuration, - options: RunOptions(), - source: .generated - )] - ) - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - let options = RunOptions(programArguments: "--dev") - - - #expect(fixture.service.saveEditorChanges( - options, - for: configuration, - scope: .local - )) - #expect(fixture.operations.editorSaveCalls == 1) - #expect(fixture.operations.savedOptions == [options]) - #expect(fixture.operations.savedScopes == [.local]) - #expect(fixture.operations.savedToolchains == [ProjectToolchainSelection()]) - } - - @Test - func editorSaveKeepsTheEffectiveProjectDefaults() async { - // Never manufacture project defaults from a separate form. External - // updates made after loading must be read again before an editor save. - let configuration = JavaRunConfiguration( - id: "spring", - name: "Spring", - kind: .springBoot, - modulePath: ".", - mainClass: nil - ) - let unsaved = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: RunOptions(), source: .generated)] - ) - await unsaved.service.loadProject(at: unsaved.root, files: []) - #expect(unsaved.service.savedProjectToolchain == nil) - #expect(unsaved.service.saveEditorChanges(RunOptions(), for: configuration, scope: .local)) - #expect(unsaved.operations.savedToolchains == [ProjectToolchainSelection()]) - #expect(unsaved.service.savedProjectToolchain == ProjectToolchainSelection()) - - // Current on-disk defaults win over this service's loaded snapshot. - let saved = ProjectToolchainSelection(javaHomePath: "/fixture/saved-jdk", mavenExecutablePath: "mvnw") - let stored = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration(configuration: configuration, options: RunOptions(), source: .generated)] - ) - await stored.service.loadProject(at: stored.root, files: []) - // A different editor saves after this service loaded its documents. - stored.operations.inspectionToolchain = saved - #expect(stored.service.saveEditorChanges(RunOptions(), for: configuration, scope: .local)) - #expect(stored.operations.savedToolchains == [saved]) - } - - @Test - func editorSaveReportsReloadFailureWithoutApplyingTheDraft() async { - let configuration = JavaRunConfiguration( - id: "spring", - name: "Spring", - kind: .springBoot, - modulePath: ".", - mainClass: nil - ) - let original = RunOptions(programArguments: "--old") - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration( - configuration: configuration, - options: original, - source: .generated - )] - ) - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - fixture.operations.resolveFailureMessage = "Injected reload failure." - - #expect(!fixture.service.saveEditorChanges( - RunOptions(programArguments: "--new"), - for: configuration, - scope: .local - )) - #expect(fixture.service.options(for: configuration) == original) - #expect(fixture.service.configurationSaveError?.contains( - "Changes were saved, but Lithe could not reload them" - ) == true) - } - - @Test(arguments: [false, true]) - func resettingOptionsUsesTheCombinedEditorSave(provider: Bool) async { - let configuration = JavaRunConfiguration( - id: "spring", - name: "Spring", - kind: provider ? .process(provider: "build.provider") : .springBoot, - execution: .service, - modulePath: ".", - mainClass: nil, - buildProvider: provider ? BuildProviderRunReference(pluginID: "dev.example", buildSystemID: "engine", root: ".", - run: "serve", projectID: "p", targetID: "t", execution: .service) : nil - ) - let fixture = makeFixture( - status: .ready, - effective: [EffectiveRunConfiguration( - configuration: configuration, - options: RunOptions(programArguments: "--dev", providerRunOptions: provider ? BuildProviderRunOptions(tools: ["dev.example:compiler": .executable(path: "/fixture/compiler")]) : nil), - source: .local - )] - ) - await fixture.service.loadProject( - at: fixture.root, - files: [] - ) - - fixture.service.resetOptions(for: configuration) - - #expect(fixture.operations.editorSaveCalls == 1) - #expect(fixture.operations.savedOptions == [RunOptions(providerRunOptions: provider ? BuildProviderRunOptions(tools: ["dev.example:compiler": nil]) : nil)]) - #expect(fixture.operations.savedScopes == [.local]) - } - - @Test - func projectEditorSaveRestoresLocalDocumentWhenTeamWriteFails() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-editor-transaction-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - let run = root.appendingPathComponent(".lithe/run") - try FileManager.default.createDirectory(at: run, withIntermediateDirectories: true) - try Data(#"demoorg.springframework.bootspring-boot-maven-plugin"#.utf8) - .write(to: root.appendingPathComponent("pom.xml")) - let oldLocal = Data(#"{"version":2,"configurations":[]}"#.utf8) - let oldProject = Data(#"{"version":2,"configurations":[]}"#.utf8) - let localURL = run.appendingPathComponent("local.json") - let projectURL = run.appendingPathComponent("configurations.json") - try oldLocal.write(to: localURL) - try oldProject.write(to: projectURL) - let storage = CountingFileStorage(root: root) - storage.seed(oldLocal, at: localURL) - storage.seed(oldProject, at: projectURL) - storage.failOnWriteNumber = 2 - let store = MacRunConfigurationStore( - core: RustCoreBridge(), - storage: storage, - preferences: RunTestKeyValueStore() - ) - try generateConfirmedSpringService(at: root, store: store) - - do { - try store.saveEditorChanges( - RunOptions(), - toolchain: ProjectToolchainSelection(javaHomePath: "/opt/jdk-21"), - configurationID: "spring-boot.maven:demo", - scope: .project, - at: root - ) - Issue.record("Expected the project document write to fail") - } catch let failure as RunConfigurationEditorSaveFailure { - #expect(failure.stage == .write) - } - #expect(storage.writeCount > 0) - #expect(try storage.readData(from: localURL, options: []) == oldLocal) - #expect(try storage.readData(from: projectURL, options: []) == oldProject) - } - - @Test - func appOwnedFileEventSuppressionIsOneShotAndExpires() { - let first = URL(fileURLWithPath: "/tmp/lithe-self-write-one.json") - let second = URL(fileURLWithPath: "/tmp/lithe-self-write-two.json") - let now = Date(timeIntervalSince1970: 1_000) - - MacFileWriteEventSuppression.markWritten(first, now: now) - #expect(MacFileWriteEventSuppression.consume(first, now: now.addingTimeInterval(1))) - #expect(!MacFileWriteEventSuppression.consume(first, now: now.addingTimeInterval(1))) - - MacFileWriteEventSuppression.markWritten(second, now: now) - #expect(!MacFileWriteEventSuppression.consume(second, now: now.addingTimeInterval(3))) - } - - private func makeFixture( - status: ProjectRunConfigurationStatus, - effective: [EffectiveRunConfiguration] = [], - plans: [String: SharedLaunchPlan] = [:], - generationEntryCount: Int? = nil, - defaultConfigurationID: String? = nil, - diagnostics: [RunConfigurationDiagnostic] = [], - preferences: RunTestKeyValueStore = RunTestKeyValueStore() - ) -> RunServiceFixture { - let root = URL(fileURLWithPath: "/tmp/lithe-run-service", isDirectory: true) - let operations = RecordingRunConfigurationOperations( - status: status, - effective: effective, - plans: plans, - generationEntryCount: generationEntryCount, - defaultConfigurationID: defaultConfigurationID, - diagnostics: diagnostics - ) - let process = RecordingStreamingProcess() - let processFactory = RecordingProcessFactory() - let runtime = ProjectRuntimeService( - runtimeLocator: RunTestRuntimeLocator(), - store: RunTestKeyValueStore() - ) - let service = JavaRunService( - runtimeService: runtime, - process: process, - processFactory: { processFactory.make() }, - fileStorage: RunTestFileStorage(), - preferences: preferences, - javaMavenOperations: RunTestJavaMavenOperations(), - runConfigurationOperations: operations - ) - return RunServiceFixture( - root: root, - service: service, - operations: operations, - process: process, - processFactory: processFactory - ) - } - - private static func framedJSON(_ data: Data?) -> [String: Any]? { - guard let data, - let separator = data.range(of: Data("\r\n\r\n".utf8)) else { return nil } - let body = data.subdata(in: separator.upperBound.. LanguageServerReliabilityHarness { - let descriptor = LanguageProviderDescriptor( - id: "swift", - displayName: "Swift", - fileExtensions: ["swift"], - capabilities: [.languageServer, .formatting], - activationPolicy: .onDemand, - languageIdentifier: "swift" - ) - let root = URL(fileURLWithPath: "/tmp/lithe-lsp-reliability", isDirectory: true) - let source = root.appendingPathComponent("App.swift") - let core = TestLanguageServerRuntimeCore(providerID: "swift") - let session = StdioLanguageServerSession( - providerID: "swift", - executableURL: URL(fileURLWithPath: "/usr/bin/sourcekit-lsp"), - arguments: [], - environment: [:], - initializeTimeout: TimeInterval(initializeTimeoutNanoseconds) / 1_000_000_000, - requestTimeout: TimeInterval(requestTimeoutNanoseconds) / 1_000_000_000, - core: core - ) - let runtime = TestLanguageServerRuntime(descriptor: descriptor, session: session) - let manager = LanguageToolingSessionManager( - catalog: LanguageProviderCatalog(descriptors: [descriptor]), - runtimes: [runtime], policyCore: policyCore - ) - return LanguageServerReliabilityHarness( - root: root, - source: source, - core: core, - session: session, - manager: manager - ) - } - - private static func debugRequest(named command: String, in frames: [Data]) -> [String: Any]? { - frames.lazy - .compactMap(framedJSON) - .first { message in - message["type"] as? String == "request" && message["command"] as? String == command - } - } - - private static func drainMainActorTasks() async { - await Task.yield() - await Task.yield() + private static func drainMainActorTasks() async { + await Task.yield() + await Task.yield() } private static func waitForMainActorCondition( @@ -4429,267 +2099,6 @@ private struct LanguageServerReliabilityHarness { let manager: LanguageToolingSessionManager } -@MainActor -private struct RunServiceFixture { - let root: URL - let service: JavaRunService - let operations: RecordingRunConfigurationOperations - let process: RecordingStreamingProcess - let processFactory: RecordingProcessFactory -} - -private final class RecordingRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { - var requiresGeneration = false - var inspectionRecoveryAction: RunConfigurationRecoveryAction = .none - var inspectionToolchain: ProjectToolchainSelection? - private(set) var generateCalls = 0 - let status: ProjectRunConfigurationStatus - private var effective: [EffectiveRunConfiguration] - let plans: [String: SharedLaunchPlan] - let generationEntryCount: Int? - let defaultConfigurationID: String? - let diagnostics: [RunConfigurationDiagnostic] - private(set) var resolveCalls = 0 - private(set) var migrationCalls = 0 - private(set) var launchPlanIDs: [String] = [] - private(set) var javaLaunchTargets: [JavaDebugLaunchTarget?] = [] - private(set) var debugPorts: [Int?] = [] - private(set) var createdDrafts: [RunConfigurationDraft] = [] - private(set) var lastToolchainCandidates: [ProjectToolchainCandidate] = [] - private(set) var savedOptions: [RunOptions] = [] - private(set) var savedScopes: [RunConfigurationSaveScope] = [] - private(set) var savedToolchains: [ProjectToolchainSelection] = [] - private(set) var editorSaveCalls = 0 - var resolveFailureMessage: String? - - init( - status: ProjectRunConfigurationStatus, - effective: [EffectiveRunConfiguration], - plans: [String: SharedLaunchPlan], - generationEntryCount: Int? = nil, - defaultConfigurationID: String? = nil, - diagnostics: [RunConfigurationDiagnostic] = [] - ) { - self.status = status - self.effective = effective - self.plans = plans - self.generationEntryCount = generationEntryCount - self.defaultConfigurationID = defaultConfigurationID - self.diagnostics = diagnostics - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection( - status: status, - diagnostics: [], - recoveryAction: inspectionRecoveryAction, - projectToolchain: inspectionToolchain, - requiresGeneration: requiresGeneration - ) - } - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - generateCalls += 1 - return RunConfigurationGenerationResult(entryCount: generationEntryCount ?? effective.count) - } - func resolve( - at projectURL: URL, - toolchainCandidates: [ProjectToolchainCandidate] - ) throws -> RunConfigurationResolution { - resolveCalls += 1 - lastToolchainCandidates = toolchainCandidates - if let resolveFailureMessage { - throw RunConfigurationOperationFailure(message: resolveFailureMessage) - } - return RunConfigurationResolution( - configurations: effective, - diagnostics: diagnostics, - defaultConfigurationID: defaultConfigurationID - ) - } - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - launchPlanIDs.append(configurationID) - debugPorts.append(debugPort) - guard let plan = plans[configurationID] else { - throw RunConfigurationOperationFailure(message: "Missing test launch plan") - } - return plan - } - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - javaLaunch: JavaDebugLaunchTarget?, - debugPort: Int?, - mavenContext: MavenLaunchContext? - ) throws -> SharedLaunchPlan { - javaLaunchTargets.append(javaLaunch) - return try launchPlan( - at: projectURL, - configurationID: configurationID, - currentFile: currentFile, - classPath: classPath, - debugPort: debugPort - ) - } - func saveEditorChanges( - _ options: RunOptions, - toolchain: ProjectToolchainSelection, - configurationID: String, - scope: RunConfigurationSaveScope, - at projectURL: URL - ) throws { - editorSaveCalls += 1 - savedOptions.append(options) - savedScopes.append(scope) - savedToolchains.append(toolchain) - } - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { - createdDrafts.append(draft) - let slug = draft.name.lowercased().replacingOccurrences(of: " ", with: "-") - let id = "user:\(slug)" - let configuration = JavaRunConfiguration( - id: id, - name: draft.name, - kind: draft.kind, - modulePath: draft.modulePath, - mainClass: draft.mainClass.isEmpty ? nil : draft.mainClass - ) - effective.append(EffectiveRunConfiguration( - configuration: configuration, - options: JavaRunOptions(), - source: draft.scope == .local ? .local : .project - )) - return id - } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws { - migrationCalls += 1 - } -} - -private final class BlockingInspectionOperations: RunConfigurationOperations, @unchecked Sendable { - private let blockedProjectPath: String - private let didBlock = TestGate() - private let release = TestGate() - - init(blockedProjectURL: URL) { - blockedProjectPath = blockedProjectURL.standardizedFileURL.path - } - - func waitUntilBlocked() async -> Bool { - await didBlock.waitUntilOpen() - } - - func releaseBlockedInspection() { - release.open() - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - if projectURL.standardizedFileURL.path == blockedProjectPath { - didBlock.open() - _ = release.waitSynchronously() - return ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - return ProjectRunConfigurationInspection(status: .missing, diagnostics: []) - } - - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - RunConfigurationGenerationResult(entryCount: 0) - } - - func resolve( - at projectURL: URL, - toolchainCandidates: [ProjectToolchainCandidate] - ) throws -> RunConfigurationResolution { - RunConfigurationResolution(configurations: [], diagnostics: [], defaultConfigurationID: nil) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - throw RunConfigurationOperationFailure(message: "No launch plan") - } - - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { - throw RunConfigurationOperationFailure(message: "Creation is unavailable in this test double") - } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} -} - -private final class BlockingGenerationOperations: RunConfigurationOperations, @unchecked Sendable { - private let didBlock = TestGate() - private let release = TestGate() - - func waitUntilBlocked() async -> Bool { - await didBlock.waitUntilOpen() - } - - func releaseGeneration() { - release.open() - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection(status: .missing, diagnostics: []) - } - - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - didBlock.open() - _ = release.waitSynchronously() - return RunConfigurationGenerationResult(entryCount: 0) - } - - func resolve( - at projectURL: URL, - toolchainCandidates: [ProjectToolchainCandidate] - ) throws -> RunConfigurationResolution { - RunConfigurationResolution(configurations: [], diagnostics: [], defaultConfigurationID: nil) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - throw RunConfigurationOperationFailure(message: "No launch plan") - } - - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { - throw RunConfigurationOperationFailure(message: "Creation is unavailable in this test double") - } - - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} -} - private final class RecordingStreamingProcess: StreamingProcess, @unchecked Sendable { var isRunning = false var onOutput: (@Sendable (String) -> Void)? @@ -4735,11 +2144,6 @@ private final class TestLanguageServerRuntimeCore: LanguageServerRuntimeCore, @u let rootURL: URL let workingDirectoryURL: URL let initializationOptions: ToolingJSONValue? - let runtimeExecutableURL: URL? - let jdtlsLaunchResources: JDTLSLaunchResources? - let cacheDirectoryURL: URL? - let workspaceFingerprint: String? - let mavenContext: MavenLaunchContext? let initializeTimeout: TimeInterval let requestTimeout: TimeInterval let shutdownTimeout: TimeInterval @@ -4796,40 +2200,7 @@ private final class TestLanguageServerRuntimeCore: LanguageServerRuntimeCore, @u self.sessionID = sessionID ?? "test-\(providerID)-session" } - func startLanguageServer( - providerID: String, - executableURL: URL, - arguments: [String], - environment: [String: String], - rootURL: URL, - workingDirectoryURL: URL, - initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - initializeTimeout: TimeInterval, - requestTimeout: TimeInterval, - shutdownTimeout: TimeInterval - ) -> Result { - startLanguageServer( - providerID: providerID, - executableURL: executableURL, - arguments: arguments, - environment: environment, - rootURL: rootURL, - workingDirectoryURL: workingDirectoryURL, - initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: nil, - initializeTimeout: initializeTimeout, - requestTimeout: requestTimeout, - shutdownTimeout: shutdownTimeout - ) - } + func requiresBackgroundLanguageServerStart(rootURL _: URL) -> Bool { false } func startLanguageServer( providerID: String, @@ -4839,11 +2210,6 @@ private final class TestLanguageServerRuntimeCore: LanguageServerRuntimeCore, @u rootURL: URL, workingDirectoryURL: URL, initializationOptions: ToolingJSONValue?, - runtimeExecutableURL: URL?, - jdtlsLaunchResources: JDTLSLaunchResources?, - cacheDirectoryURL: URL?, - workspaceFingerprint: String?, - mavenContext: MavenLaunchContext?, initializeTimeout: TimeInterval, requestTimeout: TimeInterval, shutdownTimeout: TimeInterval @@ -4856,11 +2222,6 @@ private final class TestLanguageServerRuntimeCore: LanguageServerRuntimeCore, @u rootURL: rootURL, workingDirectoryURL: workingDirectoryURL, initializationOptions: initializationOptions, - runtimeExecutableURL: runtimeExecutableURL, - jdtlsLaunchResources: jdtlsLaunchResources, - cacheDirectoryURL: cacheDirectoryURL, - workspaceFingerprint: workspaceFingerprint, - mavenContext: mavenContext, initializeTimeout: initializeTimeout, requestTimeout: requestTimeout, shutdownTimeout: shutdownTimeout @@ -5160,70 +2521,12 @@ private final class ToolchainVersionProcessRunner: ProcessRunner, @unchecked Sen private struct RunTestRuntimeLocator: RuntimeLocator { func environment() -> [String: String] { ["PATH": "/usr/bin"] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult( - javaRuntimes: [JavaRuntimeCandidate(homePath: "/toolchains/jdk", version: "21", vendor: "Test")], - mavenRuntimes: [] - ) - } - func validJavaHome(path: String) -> URL? { URL(fileURLWithPath: path, isDirectory: true) } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { - JavaRuntimeCandidate(homePath: homeURL.path, version: "21", vendor: "Test") - } - func isExecutable(at url: URL) -> Bool { url.lastPathComponent != "mvnw" } - func systemMavenExecutable() -> URL? { URL(fileURLWithPath: "/toolchains/maven/bin/mvn") } - func mavenExecutable(forHomePath path: String) -> URL? { - let url = URL(fileURLWithPath: path) - return url.lastPathComponent == "mvn" ? url : url.appendingPathComponent("bin/mvn") - } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { - MavenRuntimeCandidate( - homePath: executableURL.deletingLastPathComponent().deletingLastPathComponent().path, - executablePath: executableURL.path, - version: "3.9.9" - ) - } -} - -private struct NestedMavenWrapperRuntimeLocator: RuntimeLocator { - let wrapperRoot: URL - - func environment() -> [String: String] { [:] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { - url.standardizedFileURL == wrapperRoot.appendingPathComponent("mvnw").standardizedFileURL - } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } -} - -private struct MissingJavaRuntimeLocator: RuntimeLocator { - func environment() -> [String: String] { ["PATH": "/usr/bin"] } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } - func isExecutable(at url: URL) -> Bool { false } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } + func isExecutable(at url: URL) -> Bool { true } } private struct XcrunOnlyRuntimeLocator: RuntimeLocator { func environment() -> [String: String] { ["PATH": "/usr/bin"] } - func discover() -> RuntimeDiscoveryResult { RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { url.path == "/usr/bin/xcrun" } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } } @MainActor @@ -5502,11 +2805,27 @@ private final class CountingFileStorage: FileStorage, @unchecked Sendable { } final class RunTestDocumentMutator: RunConfigurationDocumentMutating, @unchecked Sendable { + private func documentURL(_ root: URL, scope: RunConfigurationSaveScope) -> URL { + root.appendingPathComponent(scope == .local ? ".lithe/run/local.json" : ".lithe/run/configurations.json") + } + + private func readDocument(_ url: URL) -> [String: Any] { + guard let data = try? Data(contentsOf: url), + let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return ["version": 1, "configurations": []] + } + return value + } + + private func encode(_ value: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys]) + } + func updateOptionsDocument( at projectURL: URL, configurationID: String, scope: RunConfigurationSaveScope, - options: JavaRunOptions + options: RunOptions ) throws -> RunConfigurationDocumentMutation { let url = documentURL(projectURL, scope: scope) var document = readDocument(url) @@ -5521,9 +2840,7 @@ final class RunTestDocumentMutator: RunConfigurationDocumentMutating, @unchecked let value: [String: Any] = [ "id": configurationID, "workingDirectory": workingDirectory, - "jvmArguments": split(options.vmArguments), - "programArguments": split(options.programArguments), - "mavenProfiles": options.activeProfiles.sorted() + "programArguments": split(options.programArguments) ] if let index = configurations.firstIndex(where: { $0["id"] as? String == configurationID }) { configurations[index].merge(value) { _, new in new } @@ -5535,58 +2852,6 @@ final class RunTestDocumentMutator: RunConfigurationDocumentMutating, @unchecked return RunConfigurationDocumentMutation(configurationID: nil, document: try encode(document)) } - func createConfigurationDocument( - at projectURL: URL, - draft: RunConfigurationDraft - ) throws -> RunConfigurationDocumentMutation { - let name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines) - guard !name.isEmpty, - draft.kind == .mavenModule || !draft.mainClass.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - !draft.modulePath.split(separator: "/").contains("..") else { - throw RunConfigurationOperationFailure(message: "Invalid configuration draft") - } - let url = documentURL(projectURL, scope: draft.scope) - var document = readDocument(url) - var configurations = document["configurations"] as? [[String: Any]] ?? [] - let base = "user:" + name.lowercased().replacingOccurrences(of: " ", with: "-") - let ids = Set(configurations.compactMap { $0["id"] as? String }) - var id = base - var suffix = 2 - while ids.contains(id) { id = "\(base)-\(suffix)"; suffix += 1 } - var value: [String: Any] = [ - "id": id, - "name": name, - "type": draft.kind == .springBoot ? "spring-boot.maven" : "maven.module", - "module": draft.modulePath.isEmpty ? "." : draft.modulePath, - "toolchains": ["java": "project-jdk", "maven": "project-maven"], - "workingDirectory": ".", - "jvmArguments": [], - "programArguments": [], - "mavenProfiles": [] - ] - if draft.kind == .springBoot { value["mainClass"] = draft.mainClass } - configurations.append(value) - document["version"] = 1 - document["configurations"] = configurations - return RunConfigurationDocumentMutation(configurationID: id, document: try encode(document)) - } - - private func documentURL(_ root: URL, scope: RunConfigurationSaveScope) -> URL { - root.appendingPathComponent(scope == .local ? ".lithe/run/local.json" : ".lithe/run/configurations.json") - } - - private func readDocument(_ url: URL) -> [String: Any] { - guard let data = try? Data(contentsOf: url), - let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { - return ["version": 1, "configurations": []] - } - return value - } - - private func encode(_ value: [String: Any]) throws -> Data { - try JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys]) - } - private func split(_ input: String) -> [String] { var result: [String] = [] var current = "" @@ -5614,14 +2879,6 @@ private final class RunTestKeyValueStore: KeyValueStore, @unchecked Sendable { func set(_ value: Any?, forKey key: String) { values[key] = value } } -private struct RunTestJavaMavenOperations: JavaMavenOperations { - func codeVision(at rootURL: URL, targetPath: String, paths: [String]) -> [JavaCodeVisionValue] { [] } - func className(source: String, simpleName: String) -> String? { nil } - func sourceDefinition(source: String, declarationName: String, memberName: String?) -> (line: Int, utf16Column: Int)? { nil } - func serverPort(content: String, fileExtension: String) -> Int? { nil } - func structure(source: String, declarationSources: [String]) -> JavaStructureResult? { nil } -} - @Suite("Core payload decoding") struct CorePayloadDecodingTests { /// Same root cause, quieter symptom: `hunkId` decoded as nil left every diff --git a/macos/Tests/LitheTests/RunConsolePresentationTests.swift b/macos/Tests/LitheTests/RunConsolePresentationTests.swift index d75f9b10c2..a357d98500 100644 --- a/macos/Tests/LitheTests/RunConsolePresentationTests.swift +++ b/macos/Tests/LitheTests/RunConsolePresentationTests.swift @@ -43,10 +43,10 @@ struct RunConsolePresentationTests { } @Test(arguments: [false, true]) - func stackTraceLinksKeepNavigationAndConsoleLinkAppearance(dark: Bool) throws { - let result = OutputTextView.renderOutput("at demo.Main.run(Main.java:42)", + func sourceLocationLinksKeepNavigationAndConsoleLinkAppearance(dark: Bool) throws { + let result = OutputTextView.renderOutput("app/main.go:42:7: undefined: run", searchRoots: [URL(fileURLWithPath: "/project")], - fileExists: { $0.path == "/project/src/main/java/demo/Main.java" }, + fileExists: { $0.path == "/project/app/main.go" }, isDark: dark, theme: .lithe, fontSize: 13, usesIDEAConsoleStyle: true) var links = 0 result.enumerateAttribute(.link, in: NSRange(location: 0, length: result.length)) { value, range, _ in diff --git a/macos/Tests/LitheTests/RunEntryPointTests.swift b/macos/Tests/LitheTests/RunEntryPointTests.swift deleted file mode 100644 index 6c1106bc66..0000000000 --- a/macos/Tests/LitheTests/RunEntryPointTests.swift +++ /dev/null @@ -1,1504 +0,0 @@ -import AppKit -import Foundation -import SwiftUI -import LitheCoreContracts -import Testing -@testable import Lithe - -// Each test here opens a real workspace and builds a full service container, and -// several of them coordinate on gates. Run in parallel they contend hard enough -// to stretch their own durations by two orders of magnitude and to push other -// suites past their deadlines, so this suite takes one test at a time. -@Suite("Run entry points", .serialized) -@MainActor -struct RunEntryPointTests { - @Test(arguments: [false, true]) - func javaPreparationSavesDirtyDependenciesAndStopsOnSaveFailure(saveFails: Bool) async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let model = makeAppModel(workspaceOperations: SequencedWorkspaceOperations.neverScans()) - defer { model.closeProject() } - model.settings.autoSave = false - model.openProjectDirectly(workspace.root) - let identity = try #require(model.currentWorkspaceIdentity) - await model.documentFeature.openFileAsync( - workspace.sourceURL, isReadOnly: false, displayPath: nil, activateWhenReady: true - ) - let main = try #require(model.activeDocument) - main.text += "\n// edited main" - let dependencyURL = workspace.root.appendingPathComponent("Dependency.java") - try "class Dependency {}".write(to: dependencyURL, atomically: true, encoding: .utf8) - await model.documentFeature.openFileAsync( - dependencyURL, isReadOnly: false, displayPath: nil, activateWhenReady: true - ) - let dependency = try #require(model.activeDocument) - dependency.text += "\n// edited dependency" - if saveFails { - try FileManager.default.removeItem(at: dependencyURL) - try FileManager.default.createDirectory(at: dependencyURL, withIntermediateDirectories: false) - } - // A removed module ends preparation after saving, before any language - // server starts. A failed save must stop even before source resolution. - let configuration = RunConfiguration( - id: "fixture-java", name: "Missing", kind: .javaMain, - modulePath: "removed-module", mainClass: "demo.Missing", mavenReactorPath: "." - ) - do { - _ = try await model.prepareJavaRunLaunch(for: configuration, identity: identity) - Issue.record("A removed module must not produce a Java target") - } catch { - let sourceFailure = error as? RunConfigurationOperationFailure - let failure = try #require(sourceFailure) - #expect(failure.message == (saveFails - ? "Java launch stopped because modified files could not be saved." - : "The Java source for Missing could not be resolved.")) - } - if saveFails { - #expect(dependency.isDirty) - } else { - #expect(!main.isDirty && !dependency.isDirty) - #expect(try String(contentsOf: workspace.sourceURL, encoding: .utf8) == main.text) - #expect(try String(contentsOf: dependencyURL, encoding: .utf8) == dependency.text) - } - await model.shutdownProjectSession() - } - - @Test(arguments: [AppLanguage.english, .simplifiedChinese], [false, true]) - func javaBuildDecisionButtonsStayInsideTheDialog(language: AppLanguage, offersRecovery: Bool) async throws { - let model = makeAppModel(workspaceOperations: SequencedWorkspaceOperations.neverScans()) - defer { model.closeProject() } - model.settings.language = language - let request = PendingJavaLaunchDecision( - id: UUID(), workspaceURL: URL(fileURLWithPath: "/fixture/workspace"), - failure: JavaLaunchBuildFailure(code: "javaBuildFailed", message: "Build failed", report: JavaBuildReport( - markerScope: .launchTarget, builderFailedEarlier: true, elapsedMilliseconds: 100, - recovery: offersRecovery ? .rebuildJavaIndex : .none))) - let host = NSHostingView(rootView: JavaLaunchDecisionDialog(request: request) - .environmentObject(model).environmentObject(model.settings) - .environment(\.locale, language.locale)) - host.layoutSubtreeIfNeeded() - let window = NSWindow(contentRect: NSRect(origin: .zero, size: host.fittingSize), - styleMask: [.titled], backing: .buffered, defer: false) - window.isReleasedWhenClosed = false - window.contentView = host - window.orderBack(nil) - defer { window.contentView = nil; window.close() } - var identifiers = ["java-build-run-anyway", "java-build-always-continue", "java-build-open-logs", "java-build-cancel"] - if offersRecovery { identifiers.insert("java-build-rebuild-index", at: 2) } - var frames: [NSRect] = [] - for identifier in identifiers { - let frame = try await AgentNativeControlTestSupport.frame(of: identifier, in: host) - // Check actual product controls, including the long English label and optional recovery action. - #expect(frame.minX >= 19.5 && frame.maxX <= host.bounds.width - 19.5, "\(identifier) overflows horizontally") - #expect(frame.minY >= 19.5 && frame.maxY <= host.bounds.height - 19.5, "\(identifier) overflows vertically") - #expect(abs(frame.height - 28) < 0.5) - #expect(frame.width >= 71.5) - #expect(!frames.contains { $0.intersects(frame) }, "Actions must not overlap") - frames.append(frame) - } - if language == .english && offersRecovery { - #expect(abs(frames[0].midY - frames[1].midY) >= 33.5, "The recovery row must wrap instead of clipping") - } - } - - @Test - func debugSelectedTestValidatesItsSourceInsteadOfLaunchingTheUnderlyingMain() throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let model = makeAppModel(workspaceOperations: SequencedWorkspaceOperations.neverScans()) - defer { model.closeProject() } - model.openProjectDirectly(workspace.root) - model.activeTestTarget = ActiveTestTarget(providerID: "java", scope: .testCase(identifier: "demo.ExampleTest#check()", fileURL: nil)) - model.startDebugging() - #expect(model.notifications.contains { $0.message == "The selected Java test has no source file" }) - #expect(model.genericDebugFeatureIfActive?.isSessionActive != true) - } - - @Test(arguments: [false, true]) - func toolbarRerunsTheNewScopeAfterLeavingASingleTest(fileScope: Bool) async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let model = makeAppModel(workspaceOperations: SequencedWorkspaceOperations.neverScans()) - defer { model.closeProject() } - model.openProjectDirectly(workspace.root) - // An unregistered provider rejects execution without launching external tools. - let provider = "scope-regression" - model.runTest(providerID: provider, scope: .testCase(identifier: "demo.ExampleTest#check()", fileURL: workspace.sourceURL)) - let scope: LanguageTestScope = fileScope ? .file(workspace.sourceURL) : .workspace - model.runTest(providerID: provider, scope: scope) - WorkbenchModuleUIComposition.builtIn.performAction(id: "workbench.run-start-or-restart", model: model, surface: nil) - #expect(model.activeTestTarget?.scope == scope) - #expect(model.activeTestTarget?.name == (fileScope ? workspace.sourceURL.lastPathComponent : String(localized: "Workspace"))) - let execution = try #require(await model.activateExecutionModule()) - #expect(await awaitChange(on: execution.tests) { execution.tests.errorMessage != nil }) - model.startDebugging() - #expect(model.activeTestTarget?.scope == scope, "Debug must receive the same scope instead of the stale single test") - #expect(model.genericDebugFeatureIfActive?.isSessionActive != true) - await model.shutdownProjectSession() - } - - @Test - func provisionalSnapshotStaysUnavailableAcrossRefreshesUntilReleased() throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let snapshot = workspace.snapshot - let operations = SequencedWorkspaceOperations.neverScans() - for _ in 0..<3 { - #expect(operations.snapshot(at: workspace.root, visibilityRules: .default) == nil) - } - operations.publish(snapshot) - for _ in 0..<3 { - #expect(operations.snapshot(at: workspace.root, visibilityRules: .default)?.id == snapshot.id) - } - } - - @Test - func javaBuildDecisionResumesTheSamePreparedTargetAndPersistsWorkspaceChoice() async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let model = makeAppModel(workspaceOperations: SequencedWorkspaceOperations(snapshots: [workspace.snapshot])) - defer { model.closeProject() } - model.openProjectDirectly(workspace.root) - let identity = try #require(model.currentWorkspaceIdentity) - let target = JavaDebugLaunchTarget( - mainClass: "demo.App", - projectName: "demo", - classPaths: ["/fixture/classes"] - ) - let failure = JavaLaunchBuildFailure( - code: "javaBuildFailed", - message: "The Java builder failed.", - report: JavaBuildReport( - markerScope: .launchTarget, - builderFailedEarlier: false, - elapsedMilliseconds: 5_012, - recovery: .rebuildJavaIndex - ) - ) - - let decisionTask = Task { - try await model.resolveJavaLaunchPreparation( - .buildFailed(target: target, failure: failure), - identity: identity - ) - } - let presented = await awaitChange(on: model) { - model.pendingJavaLaunchDecision?.failure == failure - } - #expect(presented) - model.completeJavaLaunchDecision(.alwaysContinue) - - #expect(try await decisionTask.value == target) - #expect(model.settings.javaBuildFailurePolicy(for: workspace.root) == .alwaysContinue) - - let automatic = try await model.resolveJavaLaunchPreparation( - .buildFailed(target: target, failure: failure), - identity: identity - ) - #expect(automatic == target) - #expect(model.pendingJavaLaunchDecision == nil) - } - - /// Run activates the execution module on demand, so it can reach a run - /// feature before the workspace snapshot has been applied. Binding the - /// workspace there is not enough: generation scans the file inventory the - /// run service holds, so identifying a provisional inventory would publish - /// a Run list that omits entry points the workspace contains. - /// - /// The snapshot is held until after Run is pressed, then released with a - /// real Java entry point, so the test observes both halves of the contract. - @Test - func runBeforeTheSnapshotDefersGenerationUntilTheInventoryIsComplete() async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let operations = SequencedWorkspaceOperations.neverScans() - let model = makeAppModel(workspaceOperations: operations) - defer { model.closeProject() } - - model.openProjectDirectly(workspace.root) - model.runSelectedConfiguration() - - // The entry point binds the workspace so existing configuration is - // readable, but the pending snapshot must keep generation out. - let bound = await awaitLoadDrivenChange(on: model) { - model.runFeatureIfActive?.projectLoadState == .bound(workspace: workspace.root.standardizedFileURL) - } - #expect(bound, "the Run entry point never bound the workspace") - #expect(model.runFeatureIfActive?.isProjectReady(for: workspace.root, snapshotID: model.workspaceSnapshotID) == false) - - let runFeature = try #require(model.runFeatureIfActive) - await runFeature.generateRunConfigurations() - #expect(runFeature.generationState == .projectNotReady) - #expect(runFeature.configurationStatus != .ready, "a partial inventory must not be identified") - - try await publishFirstCompleteSnapshot(workspace.snapshot, using: operations, in: model) - - let ready = await awaitLoadDrivenChange(on: model) { - model.runFeatureIfActive?.isProjectReady( - for: workspace.root, - snapshotID: model.workspaceSnapshotID - ) == true - } - #expect(ready, "the applied snapshot never made the run project ready") - // Which paths generation then scans is asserted against the run - // configuration store in ExecutionModuleTests, because the Swift test - // binary does not link the Rust Core that performs the scan. - } - - /// Launching from a provisional inventory resolves toolchains without the - /// Maven project, so Run has to defer rather than proceed on a bound-only - /// workspace. The deferred action is remembered and resumed by the load the - /// snapshot drives, which is what lets the user press Run once. - @Test - func runDefersAndResumesWhenTheSnapshotArrivesLater() async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let operations = SequencedWorkspaceOperations.neverScans() - let model = makeAppModel(workspaceOperations: operations) - defer { model.closeProject() } - - model.openProjectDirectly(workspace.root) - model.runSelectedConfiguration() - - let deferred = await awaitLoadDrivenChange(on: model) { model.pendingRunAction?.kind == .run } - #expect(deferred, "Run must be deferred while the inventory is provisional") - - try await publishFirstCompleteSnapshot(workspace.snapshot, using: operations, in: model) - - let ready = await awaitLoadDrivenChange(on: model) { - model.runFeatureIfActive?.isProjectReady( - for: workspace.root, - snapshotID: model.workspaceSnapshotID - ) == true - } - #expect(ready, "the applied snapshot never made the run project ready") - let resumed = await awaitLoadDrivenChange(on: model) { model.pendingRunAction == nil } - #expect(resumed, "the deferred Run was never resumed") - } - - /// A workspace that already has a configuration reports `configurationStatus - /// == .ready` as soon as it is bound, which used to be enough to launch. With - /// a provisional inventory the Maven project is absent, so toolchains resolve - /// without it. Readiness has to be checked before the configuration status. - @Test(arguments: [0, 4]) - func runWithExistingConfigurationLaunchesOnlyAfterTheSnapshotArrives(earlyRefreshes: Int) async throws { - let workspace = try JavaWorkspaceFixture() - defer { workspace.remove() } - let workspaceOperations = SequencedWorkspaceOperations.neverScans() - let runConfigurations = ReadyRunConfigurationOperations() - let model = makeAppModel( - workspaceOperations: workspaceOperations, - runConfigurationOperations: runConfigurations - ) - defer { model.closeProject() } - - model.openProjectDirectly(workspace.root) - for _ in 0.. AppModel { - let store = RunEntryPointTestStore() - let settings = AppSettings(store: store) - let services = MacServiceContainer( - store: store, - settings: settings, - workspaceOperations: workspaceOperations, - javaMavenOperations: NoProjectJavaOperations(), - runConfigurationOperations: runConfigurationOperations, - gitWatchContextProvider: gitWatchContextProvider, - // These tests assert load ordering, never toolchain selection. The - // real resolver inspects installed JDKs through processes, which - // makes every test here depend on the machine and serialize behind - // that discovery. - runExecutableResolver: StubRunExecutableResolver() - ).services - return AppModel(settings: settings, services: services) - } -} - -/// Awaits a state this suite reaches only after a full snapshot-driven load — -/// watch configuration, project load, toolchain resolution, and the deferred -/// resume that follows. That pipeline is far longer than a single publication, -/// so these waits carry the same deadline as the file's cross-load gates -/// instead of the shared default a failing test would otherwise hit first. -@MainActor -private func awaitLoadDrivenChange( - on model: AppModel, - until isSatisfied: @escaping @MainActor @Sendable () -> Bool -) async -> Bool { - await awaitChange(on: model, timeout: .seconds(30), until: isSatisfied) -} - -/// Releases the first complete inventory only after the opening scan has -/// reported its provisional result. Publishing while the workspace is idle -/// ensures any subsequent scan sees the released inventory, even if a watcher -/// starts before the caller's explicit refresh. Gated service loads keep their -/// refresh in a caller-owned task instead of awaiting it here. -@MainActor -private func publishFirstCompleteSnapshot( - _ snapshot: WorkspaceSnapshot, - using operations: SequencedWorkspaceOperations, - in model: AppModel, - refresh: Bool = true -) async throws { - let deadline = DispatchTime.now() + .seconds(30) - let openingScanFinished: @MainActor @Sendable () -> Bool = { - model.workspaceLoadErrorMessage != nil - && !model.workspaceFeature.isLoadingWorkspace - && !model.workspaceFeature.isRefreshingWorkspace - } - // A queued refresh can begin before an observation's continuation resumes. - // Recheck on this actor, retaining one deadline across those state changes. - while !openingScanFinished() { - let now = DispatchTime.now() - try #require(now < deadline, "the provisional opening scan did not finish") - let remaining = DispatchTimeInterval.nanoseconds(Int(deadline.uptimeNanoseconds - now.uptimeNanoseconds)) - try #require(await awaitChange( - on: model.workspaceFeature, timeout: remaining, until: openingScanFinished - )) - } - operations.publish(snapshot) - guard refresh else { return } - await model.workspaceFeature.refreshCurrent() - try #require(await awaitChange(on: model.workspaceFeature, timeout: .seconds(30)) { - model.workspaceSnapshotID == snapshot.id - }, "the released inventory must be applied before checking deferred Run") -} - -/// A real workspace on disk holding one Java entry point, so generation runs -/// through the shared Core instead of a stubbed result. -@MainActor -private struct JavaWorkspaceFixture { - let root: URL - let sourceURL: URL - - init() throws { - root = FileManager.default.temporaryDirectory - .appendingPathComponent("lithe-run-entry-\(UUID().uuidString)") - sourceURL = root.appendingPathComponent("src/main/java/demo/App.java") - try FileManager.default.createDirectory( - at: sourceURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try """ - package demo; - public class App { - public static void main(String[] args) {} - } - """.write(to: sourceURL, atomically: true, encoding: .utf8) - } - - var snapshot: WorkspaceSnapshot { - WorkspaceSnapshot( - root: FileNode(url: root, isDirectory: true, children: []), - files: [sourceURL] - ) - } - - func remove() { - try? FileManager.default.removeItem(at: root) - } -} - -/// Answers toolchain questions without inspecting the machine. -/// -/// Launching is out of scope for this suite, so resolution never has to succeed; -/// the protocol's default candidate and refresh behavior is what keeps real JDK -/// discovery out of these tests. -private final class StubRunExecutableResolver: RunExecutableResolving { - func resolve( - _ plan: SharedLaunchPlan, - projectURL: URL, - options: RunOptions - ) throws -> ResolvedRunExecutable { - throw RunConfigurationOperationFailure(message: "Launching is out of scope for this test") - } -} - -/// Supplies scans in call order, or holds a snapshot until explicitly released. -/// Ordered scans report the folder as unreadable once they run out. -/// -/// Reporting "no snapshot" is how these tests reach the pre-snapshot entry path. -/// Suspending the scan instead would model a scan in flight, but the workspace -/// feature scans from a detached task, so a held scan occupies a thread of the -/// cooperative pool for the whole test and starves every other suite running in -/// parallel. The tests coordinate on the run service's inspection and on the -/// watch-configuration fetch instead, both of which suspend without a thread. -private final class SequencedWorkspaceOperations: WorkspaceOperations, @unchecked Sendable { - private let lock = NSLock() - private let snapshots: [WorkspaceSnapshot?] - private var scanCount = 0 - private var publishedSnapshot: WorkspaceSnapshot? - - init(snapshots: [WorkspaceSnapshot?]) { - self.snapshots = snapshots - } - - /// No scan succeeds until the test explicitly publishes its inventory. - static func neverScans() -> SequencedWorkspaceOperations { - SequencedWorkspaceOperations(snapshots: []) - } - - /// File-system callbacks may rescan while Run is loading configuration. - /// Keep every scan provisional until the test reaches its release point. - func publish(_ snapshot: WorkspaceSnapshot) { - lock.lock() - defer { lock.unlock() } - publishedSnapshot = snapshot - } - - func snapshot(at rootURL: URL, visibilityRules: FileVisibilityRules) -> WorkspaceSnapshot? { - lock.lock() - defer { lock.unlock() } - if let publishedSnapshot { return publishedSnapshot } - let ordinal = scanCount - scanCount += 1 - guard ordinal < snapshots.count else { return nil } - return snapshots[ordinal] - } - - func readFile(at rootURL: URL, relativePath: String) -> String? { - try? String(contentsOf: rootURL.appendingPathComponent(relativePath), encoding: .utf8) - } - - func writeFile(_ text: String, at rootURL: URL, relativePath: String) -> Bool { - (try? text.write( - to: rootURL.appendingPathComponent(relativePath), - atomically: true, - encoding: .utf8 - )) != nil - } -} - -/// Reports a workspace that already carries a configuration, which the Swift test -/// binary cannot obtain from the real store because it does not link the Rust -/// Core. Records launch-plan requests so a test can prove no launch was built. -private final class ReadyRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { - private let lock = NSLock() - private var launchPlanCalls = 0 - private var currentFileTexts: [String] = [] - - var launchedCurrentFileTexts: [String] { - lock.lock() - defer { lock.unlock() } - return currentFileTexts - } - private let launchPlanRequests: [TestGate] - - init(capacity: Int = 8) { - launchPlanRequests = (0.. Bool { - await launchPlanRequests[ordinal - 1].waitUntilOpen(timeout: .seconds(30)) - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - RunConfigurationGenerationResult(entryCount: 1) - } - - /// A configuration that does not depend on the active editor file, so a - /// resumed Run reaches the launch plan instead of stopping at "no open file". - static let entryPoint = RunConfiguration( - id: "java-main:demo.App", - name: "App", - kind: .javaMain, - execution: .application, - modulePath: nil, - mainClass: "demo.App" - ) - - /// A service configuration so `runAllServiceConfigurations` has something to - /// launch after a deferred resume. This fixture tests inventory deferral; - /// Maven preparation has its own model, Provider and lifecycle integration tests. - static let serviceEntryPoint = RunConfiguration( - id: "fixture-service:demo.App", - name: "App Service", - kind: .process(provider: "fixture.service"), - execution: .service, - modulePath: nil, - mainClass: "demo.App" - ) - - static let serviceEntryPointB = RunConfiguration( - id: "fixture-service:demo.OtherApp", - name: "Other Service", - kind: .process(provider: "fixture.service"), - execution: .service, - modulePath: nil, - mainClass: "demo.OtherApp" - ) - - func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { - RunConfigurationResolution( - configurations: [ - EffectiveRunConfiguration( - configuration: Self.entryPoint, - options: RunOptions() - ), - EffectiveRunConfiguration( - configuration: Self.serviceEntryPoint, - options: RunOptions() - ), - EffectiveRunConfiguration( - configuration: Self.serviceEntryPointB, - options: RunOptions() - ), - ], - diagnostics: [], - defaultConfigurationID: Self.entryPoint.id - ) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - lock.lock() - if let currentFile { - currentFileTexts.append((try? String(contentsOf: projectURL.appendingPathComponent(currentFile), encoding: .utf8)) ?? "") - } - launchPlanCalls += 1 - let ordinal = launchPlanCalls - lock.unlock() - launchPlanRequests[ordinal - 1].open() - throw RunConfigurationOperationFailure(message: "Launching is out of scope for this test") - } - - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} -} - -/// Reports a workspace that already carries a configuration, and lets a test -/// release each `inspect` individually so it can decide what happens while a -/// specific project load is suspended. -private final class InspectionGatedRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { - private let entered: [TestGate] - private let releases: [TestGate] - private let launchPlanRequests: [TestGate] - private let lock = NSLock() - private var inspectCalls = 0 - private var launchPlanCalls = 0 - private var resolveCalls = 0 - - init(capacity: Int = 8) { - entered = (0.. Bool { - await launchPlanRequests[ordinal - 1].waitUntilOpen(timeout: .seconds(30)) - } - - var resolveCallCount: Int { - lock.lock() - defer { lock.unlock() } - return resolveCalls - } - - /// Waits for the `ordinal`-th inspection (1-based) to reach its gate. - func inspectionEntered(_ ordinal: Int) async -> Bool { - await entered[ordinal - 1].waitUntilOpen(timeout: .seconds(5)) - } - - func release(_ ordinal: Int) { - releases[ordinal - 1].open() - } - - func releaseAll() { - releases.forEach { $0.open() } - } - - // Generation identity checks have their own tests; this fake gates only - // workspace inventory inspections, never unrelated model validation. - func inspectProviderGeneration(at _: URL, projectOwnership _: [RunProjectOwnership]) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - lock.lock() - inspectCalls += 1 - let ordinal = inspectCalls - lock.unlock() - // Runs on the run service's utility queue, never the cooperative - // executor. The race test holds the first gate across a full - // snapshot-driven load, so the deadline must cover that window. - entered[ordinal - 1].open() - _ = releases[ordinal - 1].waitSynchronously(timeout: 30) - return ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - RunConfigurationGenerationResult(entryCount: 1) - } - - func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { - lock.lock() - resolveCalls += 1 - lock.unlock() - return RunConfigurationResolution( - configurations: [EffectiveRunConfiguration( - configuration: ReadyRunConfigurationOperations.entryPoint, - options: RunOptions() - )], - diagnostics: [], - defaultConfigurationID: ReadyRunConfigurationOperations.entryPoint.id - ) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - lock.lock() - launchPlanCalls += 1 - let ordinal = launchPlanCalls - lock.unlock() - launchPlanRequests[ordinal - 1].open() - throw RunConfigurationOperationFailure(message: "Launching is out of scope for this test") - } - - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} -} - -/// Holds `updateWatchConfiguration`'s git-context fetch so a test can publish a -/// newer snapshot without letting `onSnapshotLoaded` consume it yet. -private final class GatedGitWatchContextProvider: GitWatchContextProviding, @unchecked Sendable { - private let entered: [TestGate] - private let releases: [TestGate] - private let queue = DispatchQueue(label: "lithe.tests.gated-git-watch-context") - private var calls = 0 - - init(capacity: Int = 8) { - entered = (0.. Bool { - await entered[ordinal - 1].waitUntilOpen(timeout: .seconds(5)) - } - - func release(_ ordinal: Int) { - releases[ordinal - 1].open() - } - - func releaseAll() { - releases.forEach { $0.open() } - } - - func watchContext(for workspace: URL) async -> GitWatchContext? { - let ordinal: Int = await withCheckedContinuation { continuation in - queue.async { - self.calls += 1 - continuation.resume(returning: self.calls) - } - } - entered[ordinal - 1].open() - _ = await releases[ordinal - 1].waitUntilOpen(timeout: .seconds(30)) - return nil - } -} - -/// Like `InspectionGatedRunConfigurationOperations`, but also records every -/// generate inventory so a superseded-snapshot test can prove generation never -/// scanned the stale file list. -private final class InventoryRecordingGatedRunConfigurationOperations: RunConfigurationOperations, @unchecked Sendable { - private let entered: [TestGate] - private let releases: [TestGate] - private let lock = NSLock() - private var inspectCalls = 0 - private var launchPlanCalls = 0 - private var inventories: [[URL]] = [] - - init(capacity: Int = 8) { - entered = (0.. Bool { - await entered[ordinal - 1].waitUntilOpen(timeout: .seconds(5)) - } - - func release(_ ordinal: Int) { - releases[ordinal - 1].open() - } - - func releaseAll() { - releases.forEach { $0.open() } - } - - // Generation identity checks have their own tests; this fake gates only - // workspace inventory inspections, never unrelated model validation. - func inspectProviderGeneration(at _: URL, projectOwnership _: [RunProjectOwnership]) -> ProjectRunConfigurationInspection { - ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - - func inspect(at projectURL: URL) -> ProjectRunConfigurationInspection { - lock.lock() - inspectCalls += 1 - let ordinal = inspectCalls - lock.unlock() - entered[ordinal - 1].open() - _ = releases[ordinal - 1].waitSynchronously(timeout: 30) - return ProjectRunConfigurationInspection(status: .ready, diagnostics: []) - } - - func generate( - at projectURL: URL, - files: [URL], - modulePaths: [String], - javaEntrypoints: JavaEntrypoints?, - projectOwnership: [RunProjectOwnership]? = nil - ) throws -> RunConfigurationGenerationResult { - lock.lock() - inventories.append(files) - lock.unlock() - return RunConfigurationGenerationResult(entryCount: files.count) - } - - func resolve(at projectURL: URL, toolchainCandidates: [ProjectToolchainCandidate]) throws -> RunConfigurationResolution { - RunConfigurationResolution( - configurations: [EffectiveRunConfiguration( - configuration: ReadyRunConfigurationOperations.entryPoint, - options: RunOptions() - )], - diagnostics: [], - defaultConfigurationID: ReadyRunConfigurationOperations.entryPoint.id - ) - } - - func launchPlan( - at projectURL: URL, - configurationID: String, - currentFile: String?, - classPath: String?, - debugPort: Int? - ) throws -> SharedLaunchPlan { - lock.lock() - launchPlanCalls += 1 - lock.unlock() - throw RunConfigurationOperationFailure(message: "Launching is out of scope for this test") - } - - func createConfiguration(_ draft: RunConfigurationDraft, at projectURL: URL) throws -> String { draft.name } - func migrateLegacySettings(at projectURL: URL, configurationIDs: [String]) throws {} -} - -private final class RunEntryPointTestStore: KeyValueStore, @unchecked Sendable { - private var values: [String: Any] = [:] - - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } -} - -@MainActor -private func waitForRunEntryCompletion(_ task: Task) async -> Bool { - let completed = TestGate() - let observer = Task { - await task.value - completed.open() - } - defer { observer.cancel() } - return await completed.waitUntilOpen(timeout: .seconds(5)) -} diff --git a/macos/Tests/LitheTests/RunLaunchEnvironmentTests.swift b/macos/Tests/LitheTests/RunLaunchEnvironmentTests.swift index 8447f7f137..1720a72e7a 100644 --- a/macos/Tests/LitheTests/RunLaunchEnvironmentTests.swift +++ b/macos/Tests/LitheTests/RunLaunchEnvironmentTests.swift @@ -25,19 +25,20 @@ struct RunLaunchEnvironmentTests { } @Test - func sharedCoreLaunchEnvironmentRetainsSelectionAndExplicitOverrides() throws { + func sharedCoreLaunchEnvironmentKeepsInheritedValuesAndAppliesExplicitOverrides() throws { let core = RustCoreBridge() - let selected = try core.resolveLaunchEnvironment( - toolchain: "project-maven", selectedHome: "/fixture/jdk21", - inherited: ["JAVA_HOME": "/fixture/jdk8", "PATH": "/fixture/bin"], overrides: [:] + let inherited = try core.resolveLaunchEnvironment( + toolchain: "project-go", + inherited: ["TOOL_HOME": "/fixture/tool", "PATH": "/fixture/bin"], overrides: [:] ) - #expect(selected["JAVA_HOME"] == "/fixture/jdk21") - #expect(selected["PATH"] == "/fixture/bin") + #expect(inherited["TOOL_HOME"] == "/fixture/tool") + #expect(inherited["PATH"] == "/fixture/bin") let overridden = try core.resolveLaunchEnvironment( - toolchain: "project-maven", selectedHome: "/fixture/jdk21", - inherited: selected, overrides: ["JAVA_HOME": "/fixture/explicit"] + toolchain: "project-go", + inherited: inherited, overrides: ["TOOL_HOME": "/fixture/explicit"] ) - #expect(overridden["JAVA_HOME"] == "/fixture/explicit") + #expect(overridden["TOOL_HOME"] == "/fixture/explicit") + #expect(overridden["PATH"] == "/fixture/bin") } @Test @@ -199,7 +200,7 @@ struct RunLaunchEnvironmentTests { @Test @MainActor func definedToolLaunchReturnsAnOperationValueWithoutAmbientLaunchPermission() async throws { let runtime = ProjectRuntimeService(runtimeLocator: RunLaunchPathRuntimeLocator( - environmentValues: ["PATH": "/fixture/bin"], executablePath: "/unused"), store: RunLaunchPathStore()) + environmentValues: ["PATH": "/fixture/bin"], executablePath: "/unused")) let defined = DefinedRunToolFixture() let resolver = RunExecutableResolver(runtimeService: runtime, environmentResolver: RustCoreBridge(), definedTools: defined) let plan = SharedLaunchPlan(executable: .toolchain("compiler"), arguments: [], workingDirectory: "apps/example") @@ -248,15 +249,7 @@ private struct RunLaunchPathRuntimeLocator: RuntimeLocator { func environment() -> [String: String] { environmentValues } func defaultExecutableSearchPath() -> String? { "/fixture-system/bin" } - func discover() -> RuntimeDiscoveryResult { - RuntimeDiscoveryResult(javaRuntimes: [], mavenRuntimes: []) - } - func validJavaHome(path: String) -> URL? { nil } - func javaRuntime(at homeURL: URL) -> JavaRuntimeCandidate? { nil } func isExecutable(at url: URL) -> Bool { url.standardizedFileURL.path == executablePath } - func systemMavenExecutable() -> URL? { nil } - func mavenExecutable(forHomePath path: String) -> URL? { nil } - func mavenRuntime(at executableURL: URL) -> MavenRuntimeCandidate? { nil } } @MainActor diff --git a/macos/Tests/LitheTests/RunWorkflowCoordinatorTests.swift b/macos/Tests/LitheTests/RunWorkflowCoordinatorTests.swift index f395d105ea..69ee98ff3f 100644 --- a/macos/Tests/LitheTests/RunWorkflowCoordinatorTests.swift +++ b/macos/Tests/LitheTests/RunWorkflowCoordinatorTests.swift @@ -77,9 +77,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: RunConfiguration.currentFileID, name: "Current File", - kind: .currentFile, - modulePath: nil, - mainClass: nil + kind: .currentFile ) let selected = coordinator.languageSupport( @@ -99,9 +97,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: "java-main", name: "Main", - kind: .javaMain, - modulePath: nil, - mainClass: "Main" + kind: .process(provider: "fixture.main") ) let selected = coordinator.languageSupport( @@ -128,9 +124,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: "java-main", name: "Main", - kind: .javaMain, - modulePath: nil, - mainClass: "Main" + kind: .process(provider: "fixture.main") ) coordinator.performDeferredAction(.startConfiguration(configuration)) @@ -209,9 +203,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: RunConfiguration.currentFileID, name: "Current File", - kind: .currentFile, - modulePath: nil, - mainClass: nil + kind: .currentFile ) let document = EditorDocument( url: URL(fileURLWithPath: "/workspace/Main.go"), @@ -243,9 +235,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: RunConfiguration.currentFileID, name: "Current File", - kind: .currentFile, - modulePath: nil, - mainClass: nil + kind: .currentFile ) let document = EditorDocument( url: URL(fileURLWithPath: "/workspace/Main.go"), @@ -261,7 +251,8 @@ struct RunWorkflowCoordinatorTests { ) #expect(!ready) - #expect(notifications.messages == ["Could not save Main.go"]) + #expect(notifications.messages == ["Could not save %@"]) + #expect(notifications.arguments == [["Main.go"]]) } @Test("does not save a clean non-current-file configuration") @@ -272,9 +263,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: "java-main", name: "Main", - kind: .javaMain, - modulePath: nil, - mainClass: "Main" + kind: .process(provider: "fixture.main") ) let ready = await coordinator.saveDirtyCurrentFileIfNeeded( @@ -293,9 +282,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: "java-main", name: "Main", - kind: .javaMain, - modulePath: nil, - mainClass: "Main" + kind: .process(provider: "fixture.main") ) guard case .ready(let selected) = makeRunWorkflowCoordinator().configurationReadiness( @@ -326,9 +313,7 @@ struct RunWorkflowCoordinatorTests { let configuration = RunConfiguration( id: RunConfiguration.currentFileID, name: "Current File", - kind: .currentFile, - modulePath: nil, - mainClass: nil + kind: .currentFile ) let result = makeRunWorkflowCoordinator().resolveDebugSource( @@ -359,46 +344,6 @@ struct RunWorkflowCoordinatorTests { #expect(fileName == "Main.rb") } - /// Java Support ships a language server and leaves running to the host - /// through its `jdt` integration. Asking for its execution module would - /// refuse every Java run with "does not provide project execution". - @Test("does not ask a package for an execution module when the host runs its language") - func hostRunCapabilityNeedsNoExecutionExtension() throws { - let java = try #require( - try DeclarativePluginTestSupport.officialDescriptor("JavaSupport") - .pluginManifest.languageSupports?.first - ) - let coordinator = makeRunWorkflowCoordinator() - let javaMain = RunConfiguration( - id: "java-main", - name: "Main", - kind: .javaMain, - modulePath: nil, - mainClass: "Main" - ) - let currentFile = RunConfiguration( - id: RunConfiguration.currentFileID, - name: "Current File", - kind: .currentFile, - modulePath: nil, - mainClass: nil - ) - let supports = ["java": java, "go": makeSupport(id: "go")] - let required: (RunConfiguration, URL?) -> String? = { configuration, fileURL in - coordinator.languageSupportRequiringRunExtension( - for: configuration, - currentFileURL: fileURL, - languageSupportForFile: { supports[$0.pathExtension] }, - languageSupportForProvider: { supports[$0] } - )?.id - } - - #expect(required(javaMain, nil) == nil) - #expect(required(currentFile, URL(fileURLWithPath: "/workspace/Main.java")) == nil) - // A package that provides run itself is still activated. - #expect(required(currentFile, URL(fileURLWithPath: "/workspace/main.go")) == "go") - } - private func makeSupport(id: String) -> LanguageSupportDeclaration { LanguageSupportDeclaration( id: id, diff --git a/macos/Tests/LitheTests/RustBuildSystemOperationsTests.swift b/macos/Tests/LitheTests/RustBuildSystemOperationsTests.swift index 2fee949d45..d4b58a881c 100644 --- a/macos/Tests/LitheTests/RustBuildSystemOperationsTests.swift +++ b/macos/Tests/LitheTests/RustBuildSystemOperationsTests.swift @@ -58,11 +58,6 @@ struct RustBuildSystemOperationsTests { #expect(cargo.dependencyScopes.isEmpty) #expect(descriptor.pluginManifest.modules.map(\.manifest.id) .contains(.buildSystemsExtension(descriptor.id.rawValue))) - - let maven = try #require(Self.descriptor("build-systems/build-host-integration").buildSystems.first) - #expect(maven.modelSource == .hostIntegration) - // A host-integration dependency source declares no scopes of its own. - #expect(maven.dependencyScopes == [.workspace, .project]) } @Test @@ -448,49 +443,6 @@ struct RustBuildSystemOperationsTests { #expect(changed.fingerprint != first.fingerprint) } - @Test - func languageImportMapsPluginOptionIDsWithoutBuildSystemNameAssumptions() throws { - let workspace = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - try FileManager.default.createDirectory( - at: workspace.appendingPathComponent("gradle/wrapper"), withIntermediateDirectories: true - ) - defer { try? FileManager.default.removeItem(at: workspace) } - try Data("distributionUrl=fixture".utf8).write( - to: workspace.appendingPathComponent("gradle/wrapper/gradle-wrapper.properties") - ) - for kind in ["maven", "gradle"] { - var manifest = try #require(JSONSerialization.jsonObject(with: Self.fixtureData("build-systems/build-host-integration")) as? [String: Any]) - var systems = try #require(manifest["buildSystems"] as? [[String: Any]]) - systems[0]["languageImport"] = kind == "maven" - ? ["kind": kind, "options": ["profiles": "profiles", "settingsFile": "settingsFile", "localRepository": "localRepository"]] - : ["kind": kind, "options": ["offline": "offline", "gradleUserHome": "localRepository"]] - manifest["buildSystems"] = systems - let target = BuildSystemTarget(manifest: try JSONSerialization.data(withJSONObject: manifest), buildSystemID: "maven") - let value = try operations.languageImport( - target, workspaceURL: workspace, root: ".", - options: ["profiles": .array([.string("dev")]), "settingsFile": .string("/settings.xml"), - "localRepository": .string("/cache"), "offline": .bool(true)], - executableURL: URL(fileURLWithPath: "/tool/bin/mvn") - ) - switch value { - case .maven(let context): - #expect(kind == "maven") - #expect(context.profiles == ["dev"]) - #expect(context.settingsPath == "/settings.xml") - #expect(context.localRepositoryPath == "/cache") - #expect(context.mavenExecutablePath == "/tool/bin/mvn") - #expect(!context.skipTests) - case .gradle(let context): - #expect(kind == "gradle") - #expect(context == JavaGradleImportConfiguration(wrapperPresent: true, offline: true, userHome: "/cache")) - case nil: Issue.record("Expected the declared language import") - } - } - #expect(try operations.languageImport( - Self.target("build-systems/build-static-file", "cargo"), workspaceURL: workspace, root: ".", options: [:], executableURL: nil - ) == nil) - } - @Test func modelInputsCrossTheRealCoreBridgeWithoutPrivatePlans() throws { let producer = try Self.source("build-systems/build-model-producer") diff --git a/macos/Tests/LitheTests/RustLanguageServerLaunchTests.swift b/macos/Tests/LitheTests/RustLanguageServerLaunchTests.swift index 8a83d52004..fc135ddb16 100644 --- a/macos/Tests/LitheTests/RustLanguageServerLaunchTests.swift +++ b/macos/Tests/LitheTests/RustLanguageServerLaunchTests.swift @@ -38,7 +38,7 @@ struct RustLanguageServerLaunchTests { } let ready = TestGate() session.onStateChange = { state in if case .ready = state { ready.open() } } - try session.start(rootURL: root, workspaceFingerprint: nil) + try session.start(rootURL: root) try #require(await ready.waitUntilOpen(timeout: .seconds(5))) let manifestURL = DeclarativePluginTestSupport.repositoryRoot .appendingPathComponent("shared/contracts/plugins/v1/fixtures/keymap-import/keymap-import-provider.plugin.json") @@ -76,7 +76,7 @@ struct RustLanguageServerLaunchTests { defer { session.stop() } let ready = TestGate() session.onStateChange = { state in if case .ready = state { ready.open() } } - try session.start(rootURL: root, workspaceFingerprint: nil) + try session.start(rootURL: root) try #require(await ready.waitUntilOpen(timeout: .seconds(5))) #expect(session.keymapImportProviders == ["fixture"]) let response = try await session.keymapImportRequest(providerID: "fixture", snapshotID: "snapshot-1", timeout: 2) @@ -135,49 +135,33 @@ struct RustLanguageServerLaunchTests { #expect(params == ["providerID": "fixture", "snapshotID": "snapshot-1"]) } - @Test(arguments: [false, true]) - func startupMapsIdentityConfigurationServicesAndJdtContextThroughCore(useJdt: Bool) async throws { + @Test + func startupMapsIdentityConfigurationAndServicesThroughCore() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("plugin-core-launch-#\(UUID().uuidString)", isDirectory: true) - let installed = root.appendingPathComponent("installed") - let configuration = installed.appendingPathComponent("config_arm64") - let cache = root.appendingPathComponent("cache") - try FileManager.default.createDirectory(at: configuration, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } - let configText = "osgi.bundles.defaultStartLevel=4\n" - try configText.write(to: configuration.appendingPathComponent("config.ini"), atomically: true, encoding: .utf8) let executable = root.appendingPathComponent("runtime.py") try Self.server.write(to: executable, atomically: true, encoding: .utf8) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) - let launcher = installed.appendingPathComponent("plugins/equinox.jar") - let lombok = installed.appendingPathComponent("lombok.jar") - let extensionJar = installed.appendingPathComponent("extension.jar") let core = RustCoreBridge() let plugin = "dev.lithe.fixture.launch" let started = try core.startPluginLanguageServer( - pluginID: plugin, providerID: useJdt ? "java" : "test-plugin", - executableURL: useJdt ? root.appendingPathComponent("must-not-be-launched") : executable, - arguments: useJdt ? ["-jar", launcher.path] : [], environment: [:], rootURL: root, + pluginID: plugin, providerID: "test-plugin", + executableURL: executable, + arguments: [], environment: [:], rootURL: root, initializationOptions: .object(["fixtureOption": .string("preserved")]), workspaceConfiguration: .object(["fixture": .object(["value": .string("configured")])]), hostServices: ["credentials"], - hostIntegrationLaunch: useJdt ? .init(runtimeExecutableURL: executable, coreLaunch: .jdt(.init( - launcherJarURL: launcher, configurationDirectoryURL: configuration, lombokAgentURL: lombok, - javaExtensionBundleURLs: [extensionJar]))) : nil, - cacheDirectoryURL: cache, workspaceFingerprint: "workspace-v1", mavenContext: nil, javaGradle: nil, initializeTimeout: 5, requestTimeout: 5, shutdownTimeout: 0.1 ).get() defer { core.stopLanguageServer(sessionID: started.sessionID); core.destroyLanguageServer(sessionID: started.sessionID) } - var ready = false, hostRequest = false, fingerprintObserved = false + var ready = false, hostRequest = false let deadline = ContinuousClock.now.advanced(by: .seconds(5)) // Core exposes a poll boundary; observe real process replies under a // monotonic deadline rather than guessing when the backend has started. while ContinuousClock.now < deadline { for event in core.pollLanguageServerEvents(sessionID: started.sessionID) { if event.type == "stateChanged", event.state == "ready" { ready = true } - if event.message == "Java language service process started", let detail = event.detail?.data(using: .utf8), - let fields = try? JSONSerialization.jsonObject(with: detail) as? [String: Any] { - fingerprintObserved = fields["workspaceFingerprintPresent"] as? Bool == true - } if event.type == "hostRequest" { guard case .object(let value)? = event.result else { Issue.record("Host request was not an object") @@ -198,25 +182,13 @@ struct RustLanguageServerLaunchTests { await Task.yield() } try #require(ready && hostRequest, "Backend did not reach ready and receive the granted service") - let arguments = try #require(read("argv", root) as? [String]) - if useJdt { - #expect(fingerprintObserved) - #expect(arguments.contains("-javaagent:" + lombok.path)) - #expect(arguments.contains(launcher.path)) - let configIndex = try #require(arguments.firstIndex(of: "-configuration")) - let writable = URL(fileURLWithPath: arguments[configIndex + 1]) - #expect(writable.path.hasPrefix(cache.path + "/jdtls-configuration/")) - #expect(try String(contentsOf: writable.appendingPathComponent("config.ini"), encoding: .utf8) == configText) - let dataIndex = try #require(arguments.firstIndex(of: "-data")) - #expect(arguments[dataIndex + 1].hasPrefix(cache.path + "/jdtls/")) - } let initialize = try #require(read("initialize", root) as? [String: Any]) let params = try #require(initialize["params"] as? [String: Any]) #expect(params["rootUri"] as? String == root.standardizedFileURL.absoluteString) struct URI: Encodable { let path: String; let platform = "posix" } struct SyncRequest: Encodable { let sessionId: String; let uri: URI; let languageId = "fixture"; let text = "example" } struct SyncResponse: Decodable { let uri: String; let documentVersion: Int } - let document = root.appendingPathComponent("A#B.java") + let document = root.appendingPathComponent("A#B.fixture") let synchronized: SyncResponse = try core.executeResult(command: "lsp.syncDocument", payload: SyncRequest(sessionId: started.sessionID, uri: URI(path: document.path))).get() #expect(synchronized.uri == document.absoluteString) @@ -233,15 +205,9 @@ struct RustLanguageServerLaunchTests { #expect(openDocument["uri"] as? String == document.absoluteString) let options = try #require(params["initializationOptions"] as? [String: Any]) #expect(options["fixtureOption"] as? String == "preserved") - if useJdt { #expect((options["bundles"] as? [String])?.contains(extensionJar.path) == true) } let configured = try #require(read("configuration", root) as? [String: Any]) - if useJdt { - // JDT owns workspace/configuration sections; an unrelated section - // returns null. Generic plugins read the forwarded plugin config. - #expect((configured["result"] as? [Any])?.first is NSNull) - } else { - #expect(((configured["result"] as? [[String: String]])?.first)?["value"] == "configured") - } + // Plugins read the forwarded plugin configuration. + #expect(((configured["result"] as? [[String: String]])?.first)?["value"] == "configured") let credential = try #require(read("credential", root) as? [String: Any]) #expect((credential["result"] as? [String: String])?["value"] == "fixture-only") // A function call with the exact plugin owner must be accepted, while @@ -252,8 +218,6 @@ struct RustLanguageServerLaunchTests { functionID: "snapshot.refresh", params: .object([:]), timeout: 1) { Issue.record("Core accepted another plugin's function request") } - #expect(try String(contentsOf: configuration.appendingPathComponent("config.ini"), encoding: .utf8) == configText) - #expect(try FileManager.default.contentsOfDirectory(atPath: configuration.path) == ["config.ini"]) } @Test(arguments: [LanguageServerLogRole.languageServer, .vcs, .build, .toolchain, .backend]) @@ -322,9 +286,7 @@ struct RustLanguageServerLaunchTests { arguments: [], environment: [:], initializeTimeout: 5, shutdownTimeout: 0.1, core: bridge) let manager = LanguageToolingSessionManager(catalog: .init(descriptors: [descriptor]), logSink: recorder, resolveLogSubject: { try bridge.resolveEngineLogSubject(providerID: $0) }, - runtimes: [LogChannelRuntime(descriptor: descriptor, session: session)], - workspaceFingerprintProvider: { _, _ in "channel-fingerprint" }, - workspaceStateCleaner: { _, _, _ in 0 }) + runtimes: [LogChannelRuntime(descriptor: descriptor, session: session)]) defer { manager.stopAllLanguageServers() } manager.onLogEvent = { recorder.emit($0) } let ready = TestGate() @@ -340,7 +302,6 @@ struct RustLanguageServerLaunchTests { #expect(recorder.coreRecords.contains { $0.event == "lsp.session.updated" && $0.channel == channel }) #expect(recorder.coreRecords.contains { $0.event == "lsp.protocol.initialized" && $0.channel == channel }) #expect(recorder.events.compactMap { $0 as? LspSessionStageChanged }.count == 3) - #expect(recorder.events.contains { $0 is LspCacheCleaned }) #expect(recorder.events.contains { $0 is LspSessionDegradationReceived }) #expect(recorder.events.contains { $0 is LspSessionIssueFailed }) #expect(recorder.events.allSatisfy { $0.channel.rawValue == channel }) @@ -363,7 +324,7 @@ struct RustLanguageServerLaunchTests { } // macOS developer tools already provide Python; this explicit integration - // fixture speaks framed JSON-RPC and accepts the JVM argv without a JDK. + // fixture speaks framed JSON-RPC and accepts any argv. private static let keymapSourceServer = #""" #!/usr/bin/python3 import json, sys diff --git a/macos/Tests/LitheTests/SearchEverywhereBehaviorTests.swift b/macos/Tests/LitheTests/SearchEverywhereBehaviorTests.swift index 7f6bef317e..a7dc74a4ab 100644 --- a/macos/Tests/LitheTests/SearchEverywhereBehaviorTests.swift +++ b/macos/Tests/LitheTests/SearchEverywhereBehaviorTests.swift @@ -188,11 +188,11 @@ struct SearchEverywhereBehaviorTests { } @Test - func rustPortDeliversNamesBeforeSymbolsAndCancelsAnObservedRequest() async throws { + func rustPortDeliversFileNamesWithoutHostSymbolsAndCancelsAnObservedRequest() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } - try "class Name { void NameMethod() {} }".write(to: root.appendingPathComponent("Name.java"), + try "Name NameMethod".write(to: root.appendingPathComponent("Name.txt"), atomically: true, encoding: .utf8) let operations = RustWorkspaceOperations(core: RustCoreBridge()) let batches = OSAllocatedUnfairLock(initialState: [SearchEverywhereResults]()) @@ -200,10 +200,10 @@ struct SearchEverywhereBehaviorTests { visibilityRules: .init(hiddenDirectoryNames: [], hiddenFilePatterns: []), includeGeneratedFileNames: true, kinds: [.file, .type, .symbol], onResults: { batch in batches.withLock { $0.append(batch) } })) let snapshots = batches.withLock { $0 } - #expect(snapshots.first?.fileMatches.first?.url.lastPathComponent == "Name.java") - #expect(snapshots.first?.classMatches.isEmpty == true) - #expect(snapshots.contains { !$0.classMatches.isEmpty }) - #expect(final.classMatches.first?.symbolName == "Name") + #expect(snapshots.first?.fileMatches.first?.url.lastPathComponent == "Name.txt") + // Core indexes file names and contents only; type and symbol results come from language servers. + #expect(snapshots.allSatisfy { $0.classMatches.isEmpty && $0.symbolMatches.isEmpty }) + #expect(final.classMatches.isEmpty && final.symbolMatches.isEmpty) let started = TestGate(), resume = TestGate() defer { resume.open() } let cancelled = Task { diff --git a/macos/Tests/LitheTests/SettingsSearchVocabularyTests.swift b/macos/Tests/LitheTests/SettingsSearchVocabularyTests.swift index f9b3b37bcb..ed5783894c 100644 --- a/macos/Tests/LitheTests/SettingsSearchVocabularyTests.swift +++ b/macos/Tests/LitheTests/SettingsSearchVocabularyTests.swift @@ -15,7 +15,7 @@ struct SettingsSearchVocabularyTests { let translations = try simplifiedChineseTranslations() for query in ["Project Indexing", "index", "ignore", "exclude", "索引", "忽略", "排除", "根据 Git 忽略规则自动排除目录"] { #expect(SettingsSearchVocabulary.matches(query: query, category: .git, localize: { translations[$0] ?? $0 })) - #expect(!SettingsSearchVocabulary.matches(query: query, category: .project, localize: { translations[$0] ?? $0 })) + #expect(!SettingsSearchVocabulary.matches(query: query, category: .run, localize: { translations[$0] ?? $0 })) } } diff --git a/macos/Tests/LitheTests/SettingsSidebarLayoutTests.swift b/macos/Tests/LitheTests/SettingsSidebarLayoutTests.swift index 5d6dc903dd..726cbc7421 100644 --- a/macos/Tests/LitheTests/SettingsSidebarLayoutTests.swift +++ b/macos/Tests/LitheTests/SettingsSidebarLayoutTests.swift @@ -34,7 +34,7 @@ struct SettingsSidebarLayoutTests { @Test func pagesLiveInTheGroupsDescribedByTheOwnershipRules() { #expect(SettingsGroup.appearance.categories == [.general, .updates, .network, .editor, .keymap, .processTermination]) #expect(SettingsGroup.versionControl.categories == [.git]) - #expect(SettingsGroup.build.categories == [.toolchainEnvironment, .toolchainSources, .project, .run]) + #expect(SettingsGroup.build.categories == [.toolchainEnvironment, .toolchainSources, .run]) #expect(SettingsGroup.languages.categories == [.lsp]) #expect(SettingsGroup.tools.categories == [.terminal]) #expect(SettingsGroup.ai.categories == [.providers, .agents, .instructions, .skills, .hooks, .mcp, .ai]) diff --git a/macos/Tests/LitheTests/SettingsWindowRestorationTests.swift b/macos/Tests/LitheTests/SettingsWindowRestorationTests.swift index 51955d9fd6..900b911197 100644 --- a/macos/Tests/LitheTests/SettingsWindowRestorationTests.swift +++ b/macos/Tests/LitheTests/SettingsWindowRestorationTests.swift @@ -7,6 +7,21 @@ import Testing @MainActor @Suite(.serialized) struct SettingsWindowRestorationTests { + @Test + func settingsCategoryPlacesBuildPagesBetweenKeymapAndTerminal() { + // The build group (toolchain pages, run configurations) stays contiguous in + // declaration order, so search results list the pages in the same order as + // the sidebar and run configurations still follow the toolchain pages. + let cases = SettingsCategory.allCases + guard let keymap = cases.firstIndex(of: .keymap), + let terminal = cases.firstIndex(of: .terminal) else { + Issue.record("Keymap and Terminal must both be settings pages") + return + } + #expect(Array(cases[(keymap + 1).. SpringIndexResult { - SpringIndexResult( - properties: [], - values: [], - propertyReferences: [], - diagnostics: [], - beans: [SpringBean( - id: url.lastPathComponent, - name: "service", - typeName: "Service", - url: url, - line: 3, - column: 7, - kind: "component" - )], - injections: [], - endpoints: [] - ) -} - -private final class SpringTestOperations: JavaMavenOperations, @unchecked Sendable { - private let makeResult: @Sendable ([URL]) -> SpringIndexResult - private let lock = NSLock() - private var requested: [[URL]] = [] - - /// Every set of files handed to the index, in call order. An empty value - /// proves the double was never reached. - var requestedFiles: [[URL]] { - lock.lock() - defer { lock.unlock() } - return requested - } - - init(result: SpringIndexResult) { - makeResult = { _ in result } - } - - init(resultForFiles: @escaping @Sendable ([URL]) -> SpringIndexResult) { - makeResult = resultForFiles - } - - func springIndex( - at rootURL: URL, - files: [URL], - textOverrides: [URL: String], - refreshDependencyMetadata: Bool - ) -> SpringIndexResult? { - lock.lock() - requested.append(files) - lock.unlock() - return makeResult(files) - } - func codeVision(at rootURL: URL, targetPath: String, paths: [String]) -> [JavaCodeVisionValue] { [] } - func className(source: String, simpleName: String) -> String? { nil } - func sourceDefinition(source: String, declarationName: String, memberName: String?) -> (line: Int, utf16Column: Int)? { nil } - func serverPort(content: String, fileExtension: String) -> Int? { nil } - func structure(source: String, declarationSources: [String]) -> JavaStructureResult? { nil } -} diff --git a/macos/Tests/LitheTests/Support/NoProjectJavaOperations.swift b/macos/Tests/LitheTests/Support/NoProjectJavaOperations.swift deleted file mode 100644 index b14a856df2..0000000000 --- a/macos/Tests/LitheTests/Support/NoProjectJavaOperations.swift +++ /dev/null @@ -1,13 +0,0 @@ -import Foundation -@testable import Lithe - -/// Window and run-lifecycle tests do not inspect Java indexes or installed Maven -/// artifacts. Keep their unrelated background work independent of the host, -/// including when the test executable links the real Rust Core. -struct NoProjectJavaOperations: JavaMavenOperations { - func codeVision(at rootURL: URL, targetPath: String, paths: [String]) -> [JavaCodeVisionValue] { [] } - func className(source: String, simpleName: String) -> String? { nil } - func sourceDefinition(source: String, declarationName: String, memberName: String?) -> (line: Int, utf16Column: Int)? { nil } - func serverPort(content: String, fileExtension: String) -> Int? { nil } - func structure(source: String, declarationSources: [String]) -> JavaStructureResult? { nil } -} diff --git a/macos/Tests/LitheTests/TerminalPlacementFeatureModelTests.swift b/macos/Tests/LitheTests/TerminalPlacementFeatureModelTests.swift index 08a43bc534..103d863505 100644 --- a/macos/Tests/LitheTests/TerminalPlacementFeatureModelTests.swift +++ b/macos/Tests/LitheTests/TerminalPlacementFeatureModelTests.swift @@ -35,7 +35,7 @@ struct TerminalPlacementFeatureModelTests { try runtime.register(ModuleFactory(manifest: manifest) { InputTestDependency(manifest: manifest) }) } let sessions = DebugAdapterSessionManager(providers: [ - DebugProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"]) + DebugProviderDescriptor(id: "example", displayName: "Example", fileExtensions: ["txt"]) ]) { _, _ in InputTestDebugSession() } let feature = GenericDebugFeatureModel(paging: RustCoreBridge(), sessions: sessions) let graph = InputTestDebugGraph(feature: feature) @@ -57,7 +57,7 @@ struct TerminalPlacementFeatureModelTests { model.cacheModuleCapability(try #require(capability), id: .debugWorkspace, moduleID: .debug) model.cacheModuleCapability(TerminalModuleCapability(feature: terminals), id: .terminalWorkspace, moduleID: .terminal) let root = URL(fileURLWithPath: "/workspace/debug-input") - let source = root.appendingPathComponent("Main.java") + let source = root.appendingPathComponent("Main.txt") let a = try sessions.activateNew(for: source, rootURL: root).id let b = try sessions.activateNew(for: source, rootURL: root).id let aTerminal = terminals.createSession(in: root, shellPath: "/bin/zsh") @@ -106,7 +106,7 @@ struct TerminalPlacementFeatureModelTests { session.update(ownerID: owner, document: document, secondaryDocument: nil, preview: nil, markdownScrollPosition: nil, model: model, fontSize: 14, fontFamily: "monospace", theme: .init(colorTheme: .lithe, isDark: true, revealsWorkbenchBackground: false), - wrap: false, minimap: false, javaKeywordNavigationFilter: true, markers: [], secondaryMarkers: []) + wrap: false, minimap: false, markers: [], secondaryMarkers: []) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 300), styleMask: [.borderless], backing: .buffered, defer: false) window.isReleasedWhenClosed = false diff --git a/macos/Tests/LitheTests/TestJFRIntegrationTests.swift b/macos/Tests/LitheTests/TestJFRIntegrationTests.swift deleted file mode 100644 index b3c46e422e..0000000000 --- a/macos/Tests/LitheTests/TestJFRIntegrationTests.swift +++ /dev/null @@ -1,218 +0,0 @@ -import Foundation -import LitheCoreContracts -import LitheExecutionModule -import Testing -@testable import Lithe - -@MainActor -@Suite("Real test JVM profiling", .serialized) -struct TestJFRIntegrationTests { - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_TEST_JAVA_EXECUTABLE"] != nil)) - func ownedWorkerReportsRealHeapAndProducesJFRAnalysis() async throws { - let java = URL(fileURLWithPath: try #require(ProcessInfo.processInfo.environment["LITHE_TEST_JAVA_EXECUTABLE"])) - let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let source = directory.appendingPathComponent("ConsoleLauncher.java") - try """ - package org.junit.platform.console; - public class ConsoleLauncher { - static volatile Object sink; - static final byte[] retained = new byte[16 * 1024 * 1024]; - public static void main(String[] args) { - System.out.println("READY"); - long end = System.nanoTime() + 25000000000L; - long count = 0; - while (System.nanoTime() < end) { - sink = new byte[128 * 1024]; - retained[(int)(count++ % retained.length)]++; - } - } - } - """.write(to: source, atomically: true, encoding: .utf8) - let compile = await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: MacProcessRunner().run(ProcessRequest( - executablePath: java.deletingLastPathComponent().appendingPathComponent("javac").path, - arguments: ["-d", directory.path, source.path], timeoutMilliseconds: 8000))) - } - } - #expect(compile.succeeded, "\(compile.output)") - let process = MacStreamingProcess() - defer { process.stop() } - let probe = JFRWorkerProbe() - process.onOutput = { probe.receive($0) } - process.onStateChange = { if $0.state == .running { probe.processID = $0.processID } } - try process.start(ProcessRequest(executablePath: java.path, - arguments: ["-Xmx128m", "-cp", directory.path, "org.junit.platform.console.ConsoleLauncher"], timeoutMilliseconds: 30_000)) - let provider = MacTestJVMPerformance(processRegistry: nil) - var recording: TestJVMRecording? - var collector: Task? - do { - #expect(await probe.ready.waitUntilOpen(timeout: .seconds(5))) - let root = try #require(probe.processID) - var worker: TestJVMProcess? - let discovered = TestGate() - let discovery = Task { @MainActor in - for try await workers in provider.processes(rootProcessID: root) { - if let first = workers.first { worker = first; discovered.open(); break } - } - } - defer { discovery.cancel() } - #expect(await discovered.waitUntilOpen()) - let target = try #require(worker) - #expect(target.processID == root) - let value = try await provider.startRecording(target) - recording = value - let received = TestGate() - var samples: [DebugPerformanceSample] = [] - var failure: String? - collector = Task { @MainActor in - do { - for try await sample in MacDebugPerformanceSampler(processRegistry: nil).samples(for: target.target) { - samples.append(sample) - if samples.count >= 3 { received.open() } - } - } catch { failure = error.localizedDescription; received.open() } - } - #expect(await received.waitUntilOpen(timeout: .seconds(6))) - #expect(failure == nil) - #expect(samples.count >= 3) - #expect(samples.allSatisfy { $0.memoryUsedBytes > 8 * 1024 * 1024 }) - collector?.cancel(); await collector?.value - try await provider.stopRecording(value) - let report = try await provider.report(value) - #expect(report.contains("JDK Flight Recorder")) - #expect(report.contains("ExecutionSample")) - #expect(report.contains("ConsoleLauncher")) - #expect(report.contains("allocation-by-site")) - #expect(!report.contains("Unknown command")) - await provider.discard(value) - #expect(!FileManager.default.fileExists(atPath: value.fileURL.deletingLastPathComponent().path)) - #expect(await process.stopAndWait()) - } catch { - collector?.cancel(); await collector?.value - if let recording { await provider.discard(recording) } - _ = await process.stopAndWait() - throw error - } - } - @Test(.enabled(if: ProcessInfo.processInfo.environment["LITHE_TEST_GRADLE_EXECUTABLE"] != nil)) - func gradleTestWorkerIsOwnedEvenWithAnExistingDaemon() async throws { - let environment = ProcessInfo.processInfo.environment - let gradle = try #require(environment["LITHE_TEST_GRADLE_EXECUTABLE"]) - let java = try #require(environment["LITHE_TEST_JAVA_EXECUTABLE"]) - let junit = try #require(environment["LITHE_TEST_JUNIT_JAR"]) - let hamcrest = try #require(environment["LITHE_TEST_HAMCREST_JAR"]) - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-gradle-\(UUID().uuidString)") - let source = directory.appendingPathComponent("src/test/java/OwnedWorkerTest.java") - try FileManager.default.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try FileManager.default.copyItem(atPath: junit, toPath: directory.appendingPathComponent("junit.jar").path) - try FileManager.default.copyItem(atPath: hamcrest, toPath: directory.appendingPathComponent("hamcrest.jar").path) - let build = directory.appendingPathComponent("build.gradle") - try """ - plugins { id 'java' } - dependencies { testImplementation files('junit.jar', 'hamcrest.jar') } - tasks.withType(JavaCompile).configureEach { options.fork = true } - test { useJUnit(); testLogging.showStandardStreams = true } - tasks.register('probeDaemon') { doLast { println('DAEMON:' + ProcessHandle.current().pid()) } } - """.write(to: build, atomically: true, encoding: .utf8) - try """ - import org.junit.Test; - import java.nio.file.*; - public class OwnedWorkerTest { - @Test public void holdsWorker() throws Exception { - System.out.println("READY"); - long deadline = System.nanoTime() + 30000000000L; - while (!Files.exists(Paths.get("release")) && System.nanoTime() < deadline) { Thread.onSpinWait(); } - } - } - """.write(to: source, atomically: true, encoding: .utf8) - let mainSource = directory.appendingPathComponent("src/main/java/ForkedCompile.java") - try FileManager.default.createDirectory(at: mainSource.deletingLastPathComponent(), withIntermediateDirectories: true) - try "public class ForkedCompile {}".write(to: mainSource, atomically: true, encoding: .utf8) - let home = directory.appendingPathComponent("gradle-home").path - let options = ["--offline", "--console=plain", "--gradle-user-home", home] - let processEnvironment = ["JAVA_HOME": URL(fileURLWithPath: java).deletingLastPathComponent().deletingLastPathComponent().path] - func runGradle(_ arguments: [String]) async -> ProcessResult { - await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: MacProcessRunner().run(ProcessRequest( - executablePath: gradle, arguments: options + arguments, workingDirectory: directory.path, - environment: processEnvironment, timeoutMilliseconds: 60_000))) - } - } - } - let process = MacStreamingProcess() - defer { process.stop() } - do { - let warmup = await runGradle(["--daemon", "probeDaemon"]) - try #require(warmup.succeeded, "\(warmup.output)") - let daemonPID = try #require(warmup.output.split(separator: "\n") - .first(where: { $0.hasPrefix("DAEMON:") }).flatMap { Int32($0.dropFirst(7)) }) - #expect(MacProcessMemorySampler().cpuSnapshot(for: daemonPID) != nil) - let descriptor = LanguageProviderDescriptor(id: "java", displayName: "Java", fileExtensions: ["java"], - capabilities: [.testing], activationPolicy: .onDemand) - let plan = try StandardLanguageTestProvider(descriptor: descriptor).testPlan(scope: .workspace, - context: LanguageTestContext(workspaceURL: directory, projectFiles: [build, source])) - let probe = JFRWorkerProbe() - process.onOutput = { probe.receive($0) } - process.onStateChange = { if $0.state == .running { probe.processID = $0.processID } } - try process.start(ProcessRequest(executablePath: gradle, arguments: options + plan.launchPlan.arguments, - workingDirectory: directory.path, environment: processEnvironment, timeoutMilliseconds: 60_000)) - #expect(await probe.ready.waitUntilOpen(timeout: .seconds(40))) - let root = try #require(probe.processID) - let discovered = TestGate() - var target: TestJVMProcess? - let discovery = Task { @MainActor in - for try await workers in MacTestJVMPerformance(processRegistry: nil).processes(rootProcessID: root) { - if let worker = workers.first { target = worker; discovered.open(); break } - } - } - defer { discovery.cancel() } - #expect(await discovered.waitUntilOpen(timeout: .seconds(5))) - let worker = try #require(target) - let listing = await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: MacProcessRunner().run(ProcessRequest( - executablePath: URL(fileURLWithPath: java).deletingLastPathComponent().appendingPathComponent("jps").path, - arguments: ["-lm"], timeoutMilliseconds: 10_000))) - } - } - try #require(listing.succeeded, "\(listing.output)") - let owned = MacProcessMemorySampler().descendantProcessIDs(of: [root]) - let compilerWorkers = listing.output.split(separator: "\n").filter { $0.contains("Gradle Worker Daemon ") } - .compactMap { Int32($0.split(separator: " ").first ?? "") }.filter { owned.contains($0) } - #expect(!compilerWorkers.isEmpty, "Forked compilation must coexist with the test executor: \(listing.output)") - #expect(!compilerWorkers.contains(worker.processID)) - #expect(worker.processID != daemonPID) - #expect(MacProcessMemorySampler().descendantProcessIDs(of: [root]).contains(worker.processID)) - #expect(MacProcessMemorySampler().cpuSnapshot(for: daemonPID) != nil, - "The pre-existing daemon must be left running and untouched") - try Data().write(to: directory.appendingPathComponent("release")) - #expect(await process.stopAndWait()) - let stopped = await runGradle(["--stop"]) - #expect(stopped.succeeded, "\(stopped.output)") - } catch { - _ = await process.stopAndWait() - _ = await runGradle(["--stop"]) - throw error - } - } - -} - -private final class JFRWorkerProbe: @unchecked Sendable { - let ready = TestGate() - private let lock = NSLock() - private var pid: Int32? - private var text = "" - var processID: Int32? { - get { lock.withLock { pid } } - set { lock.withLock { pid = newValue } } - } - func receive(_ chunk: String) { - if lock.withLock({ text = String((text + chunk).suffix(128)); return text.contains("READY\n") }) { ready.open() } - } -} diff --git a/macos/Tests/LitheTests/TestJVMPerformanceFeatureTests.swift b/macos/Tests/LitheTests/TestJVMPerformanceFeatureTests.swift deleted file mode 100644 index 36eae94e3f..0000000000 --- a/macos/Tests/LitheTests/TestJVMPerformanceFeatureTests.swift +++ /dev/null @@ -1,254 +0,0 @@ -import Combine -import Foundation -import Testing -@testable import Lithe - -@MainActor -@Suite("Test JVM performance lifecycle", .serialized) -struct TestJVMPerformanceFeatureTests { - @Test func workerExitStopsRecordingAndSelectsTheNextWorkerWithoutMixingRuns() async throws { - let provider = ControlledTestJVMPerformance() - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - feature.setVisible(true) - let run = UUID() - feature.update(runID: run, processID: 10, isRunning: true, isJava: true) - #expect(await provider.started.waitUntilOpen()) - let first = provider.worker(11), second = provider.worker(12) - let selected = TestGate() - let selection = feature.$selectedProcess.sink { if $0 == first { selected.open() } } - defer { selection.cancel() } - provider.yield([first]) - #expect(await selected.waitUntilOpen()) - #expect(feature.canStartRecording) - let recording = TestGate() - let subscription = feature.$isRecording.sink { if $0 { recording.open() } } - defer { subscription.cancel() } - feature.startRecording() - #expect(await recording.waitUntilOpen()) - feature.setVisible(false) - #expect(!provider.terminated.isOpen, "An explicit recording keeps discovery alive while hidden") - provider.yield([second]) - #expect(await provider.stopping.waitUntilOpen()) - #expect(!feature.canStartRecording) - let stopped = TestGate() - let stopSubscription = feature.$isBusy.sink { if !$0 { stopped.open() } } - defer { stopSubscription.cancel() } - provider.allowStop.open() - #expect(await stopped.waitUntilOpen()) - #expect(!feature.isRecording) - #expect(feature.selectedProcess == second) - #expect(await provider.terminated.waitUntilOpen()) - feature.showResults() - let reported = TestGate() - let reportSubscription = feature.$report.sink { if $0 != nil { reported.open() } } - defer { reportSubscription.cancel() } - #expect(await reported.waitUntilOpen()) - #expect(feature.report == "JFR fixture report") - feature.update(runID: UUID(), processID: 20, isRunning: true, isJava: true) - #expect(feature.recording == nil) - #expect(feature.report == nil) - #expect(feature.selectedProcess == nil) - #expect(await provider.discarded.waitUntilOpen()) - } - - @Test func closingTheRunDisposesARecordingThatFinishesStartingLate() async throws { - let provider = ControlledTestJVMPerformance(delayedStart: true) - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - feature.setVisible(true) - feature.update(runID: UUID(), processID: 10, isRunning: true, isJava: true) - #expect(await provider.started.waitUntilOpen()) - let selected = TestGate() - let selection = feature.$selectedProcess.sink { if $0 != nil { selected.open() } } - defer { selection.cancel() } - provider.yield([provider.worker(11)]) - #expect(await selected.waitUntilOpen()) - feature.startRecording() - #expect(await provider.starting.waitUntilOpen()) - feature.update(runID: nil, processID: nil, isRunning: false, isJava: true) - // The provider deliberately returns a created resource after cancellation. - provider.allowStart.open() - #expect(await provider.discarded.waitUntilOpen()) - #expect(feature.recording == nil) - #expect(!feature.isRecording) - #expect(!feature.isBusy) - } - - @Test func anExitedWorkerKeepsTheLastChartTargetUntilTheRunIsClosed() async throws { - let provider = ControlledTestJVMPerformance() - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - feature.setVisible(true) - let id = UUID() - feature.update(runID: id, processID: 10, isRunning: true, isJava: true) - #expect(await provider.started.waitUntilOpen()) - let first = provider.worker(11) - let selected = TestGate() - let selection = feature.$selectedProcess.sink { if $0 == first { selected.open() } } - defer { selection.cancel() } - provider.yield([first]) - #expect(await selected.waitUntilOpen()) - let exited = TestGate() - let exitSubscription = feature.$processes.sink { if $0.isEmpty { exited.open() } } - defer { exitSubscription.cancel() } - provider.yield([]) - #expect(await exited.waitUntilOpen()) - #expect(feature.selectedProcess == first) - #expect(!feature.isProcessRunning) - #expect(!feature.canStartRecording) - feature.update(runID: id, processID: nil, isRunning: false, isJava: true) - #expect(feature.selectedProcess == first) - feature.update(runID: nil, processID: nil, isRunning: false, isJava: true) - #expect(feature.selectedProcess == nil) - } - - @Test func failedStopKeepsRecordingRetryable() async throws { - let provider = ControlledTestJVMPerformance(failFirstStop: true) - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - try await selectWorker(feature, provider) - let recording = TestGate() - let subscription = feature.$isRecording.sink { if $0 { recording.open() } } - defer { subscription.cancel() } - feature.startRecording() - #expect(await recording.waitUntilOpen()) - provider.allowStop.open() - let failed = TestGate() - let failureSubscription = feature.$errorMessage.sink { if $0 != nil { failed.open() } } - defer { failureSubscription.cancel() } - feature.stopRecording() - #expect(await failed.waitUntilOpen()) - #expect(feature.isRecording) - #expect(!feature.isBusy) - #expect(!feature.canStartRecording) - feature.showResults() - #expect(!provider.reporting.isOpen) - let stopped = TestGate() - let stoppedSubscription = feature.$isRecording.sink { if !$0 { stopped.open() } } - defer { stoppedSubscription.cancel() } - feature.stopRecording() - #expect(await stopped.waitUntilOpen()) - #expect(!feature.isRecording) - #expect(feature.errorMessage == nil) - #expect(feature.canStartRecording) - } - - @Test(arguments: [false, true]) - func hidingDuringReportStopsDiscoveryAfterSuccessOrFailure(fails: Bool) async throws { - let provider = ControlledTestJVMPerformance(delayedReport: true, failReport: fails) - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - try await selectWorker(feature, provider) - let recording = TestGate() - let subscription = feature.$isRecording.sink { if $0 { recording.open() } } - defer { subscription.cancel() } - feature.startRecording() - #expect(await recording.waitUntilOpen()) - provider.allowStop.open() - feature.stopRecording() - let stopped = TestGate() - let stoppedSubscription = feature.$isBusy.sink { if !$0 { stopped.open() } } - defer { stoppedSubscription.cancel() } - #expect(await stopped.waitUntilOpen()) - feature.showResults() - #expect(await provider.reporting.waitUntilOpen()) - feature.setVisible(false) - #expect(!provider.terminated.isOpen) - provider.allowReport.open() - #expect(await provider.terminated.waitUntilOpen()) - #expect(!feature.isBusy) - #expect(!feature.isRecording) - #expect(fails ? feature.errorMessage != nil : feature.report == "JFR fixture report") - } - - @Test func failedStartReconcilesHiddenDiscovery() async throws { - let provider = ControlledTestJVMPerformance(delayedStart: true, failStart: true) - let feature = TestJVMPerformanceFeatureModel(sampler: nil, provider: provider) - defer { feature.update(runID: nil, processID: nil, isRunning: false, isJava: true); provider.finish() } - try await selectWorker(feature, provider) - feature.startRecording() - #expect(await provider.starting.waitUntilOpen()) - feature.setVisible(false) - #expect(!provider.terminated.isOpen) - provider.allowStart.open() - #expect(await provider.terminated.waitUntilOpen()) - #expect(!feature.isBusy) - #expect(!feature.isRecording) - #expect(feature.errorMessage != nil) - } - - private func selectWorker(_ feature: TestJVMPerformanceFeatureModel, _ provider: ControlledTestJVMPerformance) async throws { - feature.setVisible(true) - feature.update(runID: UUID(), processID: 10, isRunning: true, isJava: true) - #expect(await provider.started.waitUntilOpen()) - let selected = TestGate() - let subscription = feature.$selectedProcess.sink { if $0 != nil { selected.open() } } - defer { subscription.cancel() } - provider.yield([provider.worker(11)]) - #expect(await selected.waitUntilOpen()) - } - - @Test func upstreamWorkerMarkersExcludeBuildLaunchers() { - for arguments in [["java", "-jar", "/tmp/module/target/surefire/surefirebooter-1.jar"], - ["java", "com.intellij.rt.junit.JUnitStarter"], - ["java", "worker.org.gradle.process.internal.worker.GradleWorkerMain", "Gradle Test Executor 1"], - ["java", "worker.org.gradle.process.internal.worker.GradleWorkerMain", "'Gradle Test Executor 2'"], - ["java", "org.junit.platform.console.ConsoleLauncher"]] { - #expect(MacTestJVMPerformance.isTestWorker(arguments: arguments)) - } - #expect(!MacTestJVMPerformance.isTestWorker(arguments: ["java", "org.codehaus.plexus.classworlds.launcher.Launcher"])) - #expect(!MacTestJVMPerformance.isTestWorker(arguments: ["java", "org.gradle.launcher.daemon.bootstrap.GradleDaemon"])) - #expect(!MacTestJVMPerformance.isTestWorker(arguments: ["java", "demo.Main"])) - for name in [nil, "Gradle Worker Daemon 1", "Gradle Test Executor ", "Gradle Test Executor other"] as [String?] { - let arguments = ["java", "worker.org.gradle.process.internal.worker.GradleWorkerMain"] + (name.map { [$0] } ?? []) - #expect(!MacTestJVMPerformance.isTestWorker(arguments: arguments)) - } - #expect(MacTestJVMPerformance.quoted("/tmp/a b/\"x\".jfr") == "\"/tmp/a b/\\\"x\\\".jfr\"") - } -} - -private final class ControlledTestJVMPerformance: TestJVMPerformanceProviding, @unchecked Sendable { - let starting = TestGate(), allowStart = TestGate() - private let delayedStart: Bool, failStart: Bool, delayedReport: Bool, failReport: Bool, failFirstStop: Bool - private let lock = NSLock() - private var stopAttempts = 0 - let reporting = TestGate(), allowReport = TestGate() - init(delayedStart: Bool = false, failStart: Bool = false, delayedReport: Bool = false, - failReport: Bool = false, failFirstStop: Bool = false) { - self.delayedStart = delayedStart; self.failStart = failStart - self.delayedReport = delayedReport; self.failReport = failReport; self.failFirstStop = failFirstStop - } - let started = TestGate(), terminated = TestGate(), stopping = TestGate(), allowStop = TestGate(), discarded = TestGate() - private let pair = AsyncThrowingStream<[TestJVMProcess], Error>.makeStream() - func worker(_ pid: Int32) -> TestJVMProcess { - TestJVMProcess(processID: pid, javaExecutable: URL(fileURLWithPath: "/fixture/bin/java"), - startedSeconds: UInt64(pid), startedMicroseconds: 0) - } - func processes(rootProcessID: Int32) -> AsyncThrowingStream<[TestJVMProcess], Error> { - pair.continuation.onTermination = { [terminated] _ in terminated.open() } - started.open() - return pair.stream - } - func startRecording(_ process: TestJVMProcess) async throws -> TestJVMRecording { - starting.open() - if delayedStart { _ = await allowStart.waitUntilOpen() } - if failStart { throw DebugPerformanceError.unavailable("fixture start failed") } - return TestJVMRecording(id: UUID(), process: process, fileURL: URL(fileURLWithPath: "/fixture/recording.jfr"), startedAt: Date()) - } - func stopRecording(_ recording: TestJVMRecording) async throws { - stopping.open() - guard await allowStop.waitUntilOpen() else { throw CancellationError() } - let attempt = lock.withLock { stopAttempts += 1; return stopAttempts } - if failFirstStop && attempt == 1 { throw DebugPerformanceError.unavailable("fixture stop failed") } - } - func report(_ recording: TestJVMRecording) async throws -> String { - reporting.open() - if delayedReport { _ = await allowReport.waitUntilOpen() } - if failReport { throw DebugPerformanceError.unavailable("fixture report failed") } - return "JFR fixture report" - } - func discard(_ recording: TestJVMRecording) async { discarded.open() } - func yield(_ workers: [TestJVMProcess]) { pair.continuation.yield(workers) } - func finish() { allowStart.open(); allowStop.open(); allowReport.open(); pair.continuation.finish() } -} diff --git a/macos/Tests/LitheTests/ToolWindowDockingTests.swift b/macos/Tests/LitheTests/ToolWindowDockingTests.swift index 3317df78d1..b380c23f6e 100644 --- a/macos/Tests/LitheTests/ToolWindowDockingTests.swift +++ b/macos/Tests/LitheTests/ToolWindowDockingTests.swift @@ -264,7 +264,7 @@ struct ToolWindowDockingTests { model.move(.terminal, to: position, before: .project) model.setVisibility(.terminal, isVisible: true) model.setGroupFraction(0.7, for: .right) - model.saveLayout(.init(sidebarWidth: 310, topPaneHeight: 280, mavenPaneWidth: 390), for: workspace) + model.saveLayout(.init(sidebarWidth: 310, topPaneHeight: 280, rightPaneWidth: 390), for: workspace) let restored = WorkbenchFeatureModel(layoutStore: persistence) let layout = restored.loadLayout(for: workspace) #expect(restored.tools(in: position) == [.terminal, .project]) @@ -272,7 +272,7 @@ struct ToolWindowDockingTests { #expect(!restored.isVisible(.project)) #expect(restored.groupFractions["right"] == 0.7) #expect(layout.sidebarWidth == 310) - #expect(layout.mavenPaneWidth == 390) + #expect(layout.rightPaneWidth == 390) _ = restored.loadLayout(for: URL(fileURLWithPath: "/fixture/docking/other")) #expect(restored.state(for: .project).position.anchor == .left) #expect(restored.isVisible(.project)) diff --git a/macos/Tests/LitheTests/ToolchainPreferencesTests.swift b/macos/Tests/LitheTests/ToolchainPreferencesTests.swift index cb1a228346..a433eb2a67 100644 --- a/macos/Tests/LitheTests/ToolchainPreferencesTests.swift +++ b/macos/Tests/LitheTests/ToolchainPreferencesTests.swift @@ -77,7 +77,7 @@ struct ToolchainPreferencesTests { let local = root.appendingPathComponent(".lithe/run/local.json") try FileManager.default.createDirectory(at: local.deletingLastPathComponent(), withIntermediateDirectories: true) let original: [String: Any] = ["version": 2, "configurations": [], "future": ["keep": true], - "toolchain": ["java": ["homePath": "/fixture/legacy-jdk"], "future": "keep"]] + "toolchain": ["legacy-tool": ["homePath": "/fixture/legacy-sdk"], "future": "keep"]] try JSONSerialization.data(withJSONObject: original).write(to: local) try FileManager.default.setAttributes([.posixPermissions: 0o640], ofItemAtPath: local.path) let store = store() @@ -202,24 +202,6 @@ struct ToolchainPreferencesTests { #expect(model.error != nil && model.draft?.path == "/fixture/retained-draft") } - @Test - func preferencesOnlyDocumentDoesNotSuppressLegacyDefaultMigration() async throws { - let root = try workspace() - defer { try? FileManager.default.removeItem(at: root) } - let store = store() - let initial = try await store.load(workspace: root) - let saved = try await store.save(.object(["home": .string("/fixture/generic-sdk")]), at: address, expecting: initial) - let preferences = PreferenceMigrationValues() - preferences.set(try JSONEncoder().encode(ProjectRuntimeSettings(javaHomePath: "/fixture/old-jdk")), - forKey: MacProjectRuntimeSettingsStore.preferencesKey(root)) - let runtime = MacProjectRuntimeSettingsStore(core: RustCoreBridge(), storage: MacFileStorage(), preferences: preferences) - let migrated = try runtime.load(at: root, migrateLegacy: true) - #expect(migrated.settings.javaHomePath == "/fixture/old-jdk") - let after = try await store.load(workspace: root) - #expect(after.document == saved.document) - #expect(try store.inspect(address, snapshot: after).fixed == .installation(home: "/fixture/generic-sdk")) - } - @Test(arguments: ["immutable", "parent-alias", "file-alias", "invalid"]) func invalidOrReadOnlyTargetsRemainUnchanged(kind: String) async throws { let root = try workspace(), outside = try workspace() @@ -331,12 +313,3 @@ private struct PreferenceSettingsSnapshotLoader: ToolchainSettingsLoading { let snapshot: ToolchainSettingsSnapshot func load(workspace: URL?) async throws -> ToolchainSettingsSnapshot { snapshot } } - -private final class PreferenceMigrationValues: KeyValueStore { - private var values: [String: Any] = [:] - func data(forKey key: String) -> Data? { values[key] as? Data } - func object(forKey key: String) -> Any? { values[key] } - func string(forKey key: String) -> String? { values[key] as? String } - func stringArray(forKey key: String) -> [String]? { values[key] as? [String] } - func set(_ value: Any?, forKey key: String) { values[key] = value } -} diff --git a/macos/Tests/LitheTests/UserActionTraceTests.swift b/macos/Tests/LitheTests/UserActionTraceTests.swift index 0da642d59d..1f08cd2055 100644 --- a/macos/Tests/LitheTests/UserActionTraceTests.swift +++ b/macos/Tests/LitheTests/UserActionTraceTests.swift @@ -55,7 +55,7 @@ struct UserActionTraceTests { @Test func actionIDsAreCatalogTokensNeverTitles() { - #expect(UserActionTrace.normalizedID("plugin:dev.lithe.maven/run-goal") == "plugin:dev.lithe.maven/run-goal") + #expect(UserActionTrace.normalizedID("plugin:example-plugin/run-action") == "plugin:example-plugin/run-action") #expect(UserActionTrace.normalizedID("vcs.git.branch.checkout") == "vcs.git.branch.checkout") #expect(UserActionTrace.normalizedID("Commit 提交") == "invalid") #expect(UserActionTrace.normalizedID("") == "invalid") diff --git a/macos/Tests/LitheTests/VcsProviderHostTests.swift b/macos/Tests/LitheTests/VcsProviderHostTests.swift index 44da844622..80c65c3397 100644 --- a/macos/Tests/LitheTests/VcsProviderHostTests.swift +++ b/macos/Tests/LitheTests/VcsProviderHostTests.swift @@ -311,7 +311,7 @@ struct VcsProviderHostTests { // Metadata the provider did not declare never refreshes; a working // file does. Both arrive before the delay, so one refresh covers them. fixture.metadataWatchers.deliver([fixture.url(".svn/tmp/x")]) - fixture.changed("module/File.java") + fixture.changed("module/File.txt") #expect(await fixture.settled { fixture.providers.statusCount(root: module) == 2 }) #expect(fixture.providers.statusCount(root: workspace) == 1) @@ -320,7 +320,7 @@ struct VcsProviderHostTests { #expect(await fixture.feature.cleanup("module")) #expect(await fixture.settled { fixture.providers.statusCount(root: module) == 3 }) fixture.metadataWatchers.deliver([fixture.url(".svn/wc.db")]) - fixture.changed("module/Other.java") + fixture.changed("module/Other.txt") #expect(await fixture.settled { fixture.providers.statusCount(root: module) == 4 }) #expect(fixture.providers.statusCount(root: workspace) == 1) @@ -384,13 +384,13 @@ struct VcsProviderHostTests { // A created entry and the directory holding it are looked up unless // they are a known root; a changed file is not looked up at all. let lookedUp = fixture.files.gate(afterLookups: 3) - fixture.changed("plugins/Plugin.java") - fixture.created("README.md", "src/Main.java") + fixture.changed("plugins/Plugin.txt") + fixture.created("README.md", "src/Main.txt") #expect(await lookedUp.waitUntilOpen(timeout: .seconds(5))) #expect(Set(fixture.files.lookups) - == Set(["README.md/.svn", "src/Main.java/.svn", "src/.svn"].map { fixture.url($0).path })) + == Set(["README.md/.svn", "src/Main.txt/.svn", "src/.svn"].map { fixture.url($0).path })) - fixture.created("plugins/Plugin.java") + fixture.created("plugins/Plugin.txt") #expect(await fixture.settled { fixture.planner.detectCount == 2 }) #expect(!fixture.files.lookups.contains(fixture.url(".svn").path)) } @@ -598,11 +598,11 @@ struct VcsProviderHostTests { @Test func commitCarriesBothHalvesOfAMoveOnce() { let paths = VcsProviderToolWindowView.commitPaths([ - VcsChange(path: "src/New.java", oldPath: "src/Old.java", status: .renamed), - VcsChange(path: "src/Old.java", status: .deleted), + VcsChange(path: "src/New.txt", oldPath: "src/Old.txt", status: .renamed), + VcsChange(path: "src/Old.txt", status: .deleted), VcsChange(path: "README", status: .modified) ]) - #expect(paths == ["src/New.java", "src/Old.java", "README"]) + #expect(paths == ["src/New.txt", "src/Old.txt", "README"]) } @Test diff --git a/macos/Tests/LitheTests/WorkbenchContributionHostTests.swift b/macos/Tests/LitheTests/WorkbenchContributionHostTests.swift index 70dce74209..4f2de4a02e 100644 --- a/macos/Tests/LitheTests/WorkbenchContributionHostTests.swift +++ b/macos/Tests/LitheTests/WorkbenchContributionHostTests.swift @@ -319,7 +319,7 @@ struct WorkbenchContributionHostTests { #expect((expected == .leftSidebar ? workbench.activeLeftToolWindow : (expected == .rightSidebar ? workbench.activeRightToolWindow : workbench.activeToolWindow)) == window) } - @Test(arguments: ["toggle-terminal", "toggle-problems", "toggle-git-log", "toggle-run", "toggle-tests", "toggle-debug", "spring-endpoints"]) + @Test(arguments: ["toggle-terminal", "toggle-problems", "toggle-git-log", "toggle-run", "toggle-tests", "toggle-debug"]) func nativeWindowCommandsReuseRegisteredActionsAndCheckedState(id: String) async throws { let suite = "lithe-native-window-command-" + UUID().uuidString let defaults = try #require(UserDefaults(suiteName: suite)) @@ -1012,19 +1012,6 @@ struct WorkbenchContributionHostTests { } } - @Test func rebuildJavaIndexIsEnabledOnlyWithAWorkspace() throws { - let suite = "lithe-rebuild-index-" + UUID().uuidString - let defaults = try #require(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let store = MacUserDefaultsStore(defaults: defaults), settings = AppSettings(store: store) - let container = MacServiceContainer(store: store, settings: settings) - defer { container.moduleLifecycleCoordinator.stop() } - let model = AppModel(settings: settings, services: container.services) - #expect(!model.canPerformShortcutCommand(id: "rebuild-java-index")) - model.workspaceSessionCoordinator.beginWorkspace(at: URL(fileURLWithPath: "/fixture/rebuild-index")) - #expect(model.canPerformShortcutCommand(id: "rebuild-java-index")) - } - @Test func activationWaitsForGatedSleepWithoutReactivatingTheSleepingInstance() async throws { let runtime = ModuleRuntime() let owner = ModuleID("org.example.sleep-race") @@ -1129,7 +1116,7 @@ struct WorkbenchContributionHostTests { let position = DockPosition(anchor: .right, group: .primary) let window = WorkbenchFeatureModel.ToolWindow( rawValue: DeclarativeBuildSystem.toolWindowID(pluginID: "org.example.make", buildSystemID: "make")) - // A build system's window docks on the right like the Maven window it replaces. + // A build system's window docks on the right beside the Agent pane. #expect(workbench.tools(in: position) == [.agent, window]) workbench.moveContribution(window.rawValue, earlier: true) #expect(workbench.tools(in: position) == [window, .agent]) diff --git a/macos/Tests/LitheTests/WorkbenchFeatureModelTests.swift b/macos/Tests/LitheTests/WorkbenchFeatureModelTests.swift index aecfda5d36..444b9e0579 100644 --- a/macos/Tests/LitheTests/WorkbenchFeatureModelTests.swift +++ b/macos/Tests/LitheTests/WorkbenchFeatureModelTests.swift @@ -25,10 +25,10 @@ struct WorkbenchFeatureModelTests { // Settings links may request the category that was requested before, // after the user navigated elsewhere inside the open window. let model = WorkbenchFeatureModel() - model.presentSettings(category: .project) + model.presentSettings(category: .run) let first = model.settingsCategoryRequest - model.presentSettings(category: .project) - #expect(model.requestedSettingsCategory == .project) + model.presentSettings(category: .run) + #expect(model.requestedSettingsCategory == .run) #expect(model.settingsCategoryRequest == first + 1) #expect(model.isSettingsPresented) } diff --git a/macos/Tests/LitheTests/WorkbenchHoverTooltipTests.swift b/macos/Tests/LitheTests/WorkbenchHoverTooltipTests.swift index ece7dabbc8..a062b880e7 100644 --- a/macos/Tests/LitheTests/WorkbenchHoverTooltipTests.swift +++ b/macos/Tests/LitheTests/WorkbenchHoverTooltipTests.swift @@ -76,7 +76,7 @@ struct WorkbenchHoverTooltipTests { @Test func longTextWrapsWithinANarrowViewport() async throws { - let text = "运行选中的 Maven 生命周期阶段" + let text = "运行选中的 Build 生命周期阶段" let wide = try renderedBounds(text: text) let narrow = try renderedBounds(text: text, viewport: CGSize(width: 130, height: 120)) #expect(narrow.height > wide.height) @@ -99,7 +99,7 @@ struct WorkbenchHoverTooltipTests { let leftSource = CGRect(x: 4, y: 20, width: 30, height: 30) let rightSource = CGRect(x: 326, y: 20, width: 30, height: 30) let left = try renderedBounds(text: "项目", source: leftSource, placement: .trailing) - let right = try renderedBounds(text: "Maven", source: rightSource, placement: .leading) + let right = try renderedBounds(text: "Build", source: rightSource, placement: .leading) #expect(left.minX >= leftSource.maxX + 4) #expect(right.maxX <= rightSource.minX - 4) } diff --git a/macos/Tests/LitheTests/WorkbenchNotificationTests.swift b/macos/Tests/LitheTests/WorkbenchNotificationTests.swift index 030cd88ba1..3df9b6f78f 100644 --- a/macos/Tests/LitheTests/WorkbenchNotificationTests.swift +++ b/macos/Tests/LitheTests/WorkbenchNotificationTests.swift @@ -12,7 +12,7 @@ struct WorkbenchNotificationTests { let feature = WorkbenchNotificationFeatureModel() feature.setApplicationActive(false) defer { feature.clear() } - let key = "Java service failed to start: %@" + let key = "Could not connect to the Debug Adapter: %@" feature.show(key, arguments: ["connection refused"]) feature.show(key, arguments: ["other failure"]) feature.show(key, arguments: ["connection refused"]) @@ -24,8 +24,8 @@ struct WorkbenchNotificationTests { let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources") let bundle = try #require(Bundle(url: resources)) - for (language, expected) in [("zh-Hans", "Java 服务启动失败:connection refused(2)"), - ("en", "Java service failed to start: connection refused (2)")] { + for (language, expected) in [("zh-Hans", "无法连接调试适配器:connection refused(2)"), + ("en", "Could not connect to the Debug Adapter: connection refused (2)")] { #expect(WorkbenchNotificationPresentation.message(notification.message, arguments: notification.arguments, occurrenceCount: notification.occurrenceCount, locale: Locale(identifier: language), bundle: bundle) == expected) } @@ -69,19 +69,6 @@ struct WorkbenchNotificationTests { #expect(!DatabasePluginTransition.shouldSuggest(store: store, installedPluginIDs: none)) } - @Test func mavenRuntimeErrorUsesApplicationLanguage() throws { - let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources") - let bundle = try #require(Bundle(url: resources)) - let key = "Java runtime is not ready. Retry Maven reload." - for (language, expected) in [(AppLanguage.simplifiedChinese, "Java 运行时尚未就绪,请重试 Maven 重新加载。"), - (.english, key)] { - let error = NSError(domain: "MavenReload", code: 1, - userInfo: [NSLocalizedDescriptionKey: language.localizedString(key, bundle: bundle)]) - #expect(error.localizedDescription == expected) - } - } - @Test func notificationTimersPauseIndividuallyAndWhileTheApplicationIsInactive() async { let clock = NotificationTestClock() @@ -145,7 +132,7 @@ struct WorkbenchNotificationTests { } } var shortHeight: CGFloat = 0 - for message in ["Java 服务正在准备", String(repeating: "A long notification must stay readable. ", count: 6)] { + for message in ["A short notification", String(repeating: "A long notification must stay readable. ", count: 6)] { let host = NSHostingView(rootView: WorkbenchNotificationBanner(message: message, occurrenceCount: 1, dismiss: {}) .environment(\.colorScheme, scheme)) @@ -221,25 +208,25 @@ struct WorkbenchNotificationTests { feature.setApplicationActive(false) defer { feature.clear() } - feature.show("Java service is ready") + feature.show("Repeated notification") #expect(feature.notifications.map(\.occurrenceCount) == [1]) #expect(feature.activeNotifications.map(\.occurrenceCount) == [1]) - feature.show("Java service is ready") + feature.show("Repeated notification") feature.show("No usages found") feature.markAllRead() - let repeatedEntry = try #require(feature.notifications.first { $0.message == "Java service is ready" }) - #expect(feature.notifications.map(\.message) == ["No usages found", "Java service is ready"]) + let repeatedEntry = try #require(feature.notifications.first { $0.message == "Repeated notification" }) + #expect(feature.notifications.map(\.message) == ["No usages found", "Repeated notification"]) - feature.show("Java service is ready") + feature.show("Repeated notification") // The third appearance must reuse the existing row instead of appending one. - #expect(feature.notifications.map(\.message) == ["Java service is ready", "No usages found"]) + #expect(feature.notifications.map(\.message) == ["Repeated notification", "No usages found"]) #expect(feature.notifications.map(\.occurrenceCount) == [3, 1]) #expect(!feature.notifications[0].isRead) #expect(feature.notifications[0].updatedAt >= repeatedEntry.updatedAt) // The balloon stack follows the merge instead of growing a second card. - #expect(feature.activeNotifications.map(\.message) == ["No usages found", "Java service is ready"]) + #expect(feature.activeNotifications.map(\.message) == ["No usages found", "Repeated notification"]) #expect(feature.activeNotifications.map(\.occurrenceCount) == [1, 3]) } @@ -391,10 +378,10 @@ struct WorkbenchNotificationTests { .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources") let bundle = try #require(Bundle(url: resources)) let locale = Locale(identifier: language) - let expected = language == "en" ? "Java service is ready" : "Java 服务已就绪" - #expect(WorkbenchNotificationPresentation.message("Java service is ready", occurrenceCount: 1, + let expected = language == "en" ? "No usages found" : "没有找到调用位置" + #expect(WorkbenchNotificationPresentation.message("No usages found", occurrenceCount: 1, locale: locale, bundle: bundle) == expected) - #expect(WorkbenchNotificationPresentation.message("Java service is ready", occurrenceCount: 2, + #expect(WorkbenchNotificationPresentation.message("No usages found", occurrenceCount: 2, locale: locale, bundle: bundle) == (language == "en" ? expected + " (2)" : expected + "(2)")) #expect(WorkbenchNotificationPresentation.message("External diagnostic: Example", occurrenceCount: 1, locale: locale, bundle: bundle) == "External diagnostic: Example") diff --git a/macos/Tests/LitheTests/WorkbenchMavenLayoutTests.swift b/macos/Tests/LitheTests/WorkbenchRightPaneLayoutTests.swift similarity index 75% rename from macos/Tests/LitheTests/WorkbenchMavenLayoutTests.swift rename to macos/Tests/LitheTests/WorkbenchRightPaneLayoutTests.swift index d368a9e99e..6a8dc0e39a 100644 --- a/macos/Tests/LitheTests/WorkbenchMavenLayoutTests.swift +++ b/macos/Tests/LitheTests/WorkbenchRightPaneLayoutTests.swift @@ -3,11 +3,11 @@ import Foundation import Testing @testable import Lithe -@Suite("Workbench Maven layout") +@Suite("Workbench right pane layout") @MainActor -struct WorkbenchMavenLayoutTests { +struct WorkbenchRightPaneLayoutTests { @Test func initialLayoutWidensTheSidebarWithoutOverwritingSavedDimensions() { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) let workspace = URL(fileURLWithPath: "/fixture/default-layout") #expect(store.load(for: workspace).sidebarWidth == 360) #expect(store.load(for: workspace).topPaneHeight == nil) @@ -22,40 +22,40 @@ struct WorkbenchMavenLayoutTests { let layout = try JSONDecoder().decode(WorkbenchLayout.self, from: data) #expect(layout.sidebarWidth == 320) #expect(layout.topPaneHeight == 280) - #expect(layout.mavenPaneWidth == nil) + #expect(layout.rightPaneWidth == nil) #expect(layout.branchPopupWidth == nil) #expect(layout.branchPopupHeight == nil) } - @Test func committedMavenWidthIsRestoredPerWorkspace() { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) - let workspace = URL(fileURLWithPath: "/fixture/maven-layout/project") - store.save(WorkbenchLayout(sidebarWidth: 300, topPaneHeight: 280, mavenPaneWidth: 410), for: workspace) + @Test func committedRightPaneWidthIsRestoredPerWorkspace() { + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) + let workspace = URL(fileURLWithPath: "/fixture/right-pane-layout/project") + store.save(WorkbenchLayout(sidebarWidth: 300, topPaneHeight: 280, rightPaneWidth: 410), for: workspace) let restored = store.load(for: workspace) - #expect(restored.mavenPaneWidth == 410) + #expect(restored.rightPaneWidth == 410) #expect(restored.sidebarWidth == 300) #expect(restored.topPaneHeight == 280) - #expect(store.load(for: URL(fileURLWithPath: "/fixture/maven-layout/other")).mavenPaneWidth == nil) + #expect(store.load(for: URL(fileURLWithPath: "/fixture/right-pane-layout/other")).rightPaneWidth == nil) } @Test func branchPopupSizeIsRestoredPerWorkspace() { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) let first = URL(fileURLWithPath: "/fixture/branch-popup/first") let second = URL(fileURLWithPath: "/fixture/branch-popup/second") store.save(WorkbenchLayout(sidebarWidth: 300, topPaneHeight: 280, - mavenPaneWidth: 410, branchPopupWidth: 620, branchPopupHeight: 560), for: first) + rightPaneWidth: 410, branchPopupWidth: 620, branchPopupHeight: 560), for: first) store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, branchPopupWidth: 480, branchPopupHeight: 420), for: second) #expect(store.load(for: first).branchPopupWidth == 620) #expect(store.load(for: first).branchPopupHeight == 560) #expect(store.load(for: second).branchPopupHeight == 420) #expect(store.load(for: second).branchPopupWidth == 480) - #expect(store.load(for: first).mavenPaneWidth == 410) + #expect(store.load(for: first).rightPaneWidth == 410) #expect(store.load(for: first).topPaneHeight == 280) } @Test(arguments: [-1.0, 0.0, .infinity]) func invalidBranchPopupWidthsFallBackToDefault(width: Double) { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) let workspace = URL(fileURLWithPath: "/fixture/branch-popup/invalid") store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, branchPopupWidth: width), for: workspace) #expect(store.load(for: workspace).branchPopupWidth == nil) @@ -63,7 +63,7 @@ struct WorkbenchMavenLayoutTests { @Test(arguments: [-1.0, 0.0, .infinity]) func invalidBranchPopupHeightsFallBackToDefault(height: Double) { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) let workspace = URL(fileURLWithPath: "/fixture/branch-popup/invalid-height") store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, branchPopupHeight: height), for: workspace) #expect(store.load(for: workspace).branchPopupHeight == nil) @@ -71,22 +71,22 @@ struct WorkbenchMavenLayoutTests { @Test(arguments: [30.0, 219.0]) func narrowSidebarWidthIsRestoredWithOtherLayoutValues(width: Double) { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) - let workspace = URL(fileURLWithPath: "/fixture/maven-layout/narrow-sidebar") - store.save(WorkbenchLayout(sidebarWidth: width, topPaneHeight: 280, mavenPaneWidth: 410), for: workspace) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) + let workspace = URL(fileURLWithPath: "/fixture/right-pane-layout/narrow-sidebar") + store.save(WorkbenchLayout(sidebarWidth: width, topPaneHeight: 280, rightPaneWidth: 410), for: workspace) let restored = store.load(for: workspace) #expect(restored.sidebarWidth == width) #expect(restored.topPaneHeight == 280) - #expect(restored.mavenPaneWidth == 410) + #expect(restored.rightPaneWidth == 410) } @Test(arguments: [-1.0, 0.0, 29.0, .infinity]) func invalidPersistedWidthsFallBackToDefault(width: Double) { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) - let workspace = URL(fileURLWithPath: "/fixture/maven-layout/project") - store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, mavenPaneWidth: width), for: workspace) - #expect(store.load(for: workspace).mavenPaneWidth == nil) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) + let workspace = URL(fileURLWithPath: "/fixture/right-pane-layout/project") + store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, rightPaneWidth: width), for: workspace) + #expect(store.load(for: workspace).rightPaneWidth == nil) } @Test(arguments: [0.0, 40.0, 640.0, 760.0, 1024.0, 1440.0]) @@ -106,10 +106,10 @@ struct WorkbenchMavenLayoutTests { } @Test func narrowWindowDividerMouseUpDoesNotOverwritePreferredWidth() throws { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) - let workspace = URL(fileURLWithPath: "/fixture/maven-layout/project") - store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, mavenPaneWidth: 410), for: workspace) - let preferred = CGFloat(try #require(store.load(for: workspace).mavenPaneWidth)) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) + let workspace = URL(fileURLWithPath: "/fixture/right-pane-layout/project") + store.save(WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, rightPaneWidth: 410), for: workspace) + let preferred = CGFloat(try #require(store.load(for: workspace).rightPaneWidth)) let narrowWidth = WorkbenchRightToolGeometry.resolvedWidth(preferred, in: 400, sidebarWidth: 320, isSidebarVisible: true) #expect(narrowWidth < preferred) @@ -117,12 +117,12 @@ struct WorkbenchMavenLayoutTests { narrowWidth, preferredWidth: preferred, in: 400, sidebarWidth: 320, isSidebarVisible: true ) { store.save( - WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, mavenPaneWidth: Double(committedWidth)), + WorkbenchLayout(sidebarWidth: 320, topPaneHeight: nil, rightPaneWidth: Double(committedWidth)), for: workspace ) } - let restored = CGFloat(try #require(store.load(for: workspace).mavenPaneWidth)) + let restored = CGFloat(try #require(store.load(for: workspace).rightPaneWidth)) #expect(restored == preferred) #expect(WorkbenchRightToolGeometry.resolvedWidth(restored, in: 1440, sidebarWidth: 320, isSidebarVisible: true) == preferred) #expect(WorkbenchRightToolGeometry.committedWidth( @@ -139,15 +139,15 @@ struct WorkbenchMavenLayoutTests { } @Test func paneWidthsAboveTheOldFixedCapsRemainPersisted() { - let store = WorkbenchLayoutStore(store: MavenLayoutTestStore()) - let workspace = URL(fileURLWithPath: "/fixture/maven-layout/wide-pane") - store.save(WorkbenchLayout(sidebarWidth: 800, topPaneHeight: nil, mavenPaneWidth: 900), for: workspace) + let store = WorkbenchLayoutStore(store: RightPaneLayoutTestStore()) + let workspace = URL(fileURLWithPath: "/fixture/right-pane-layout/wide-pane") + store.save(WorkbenchLayout(sidebarWidth: 800, topPaneHeight: nil, rightPaneWidth: 900), for: workspace) #expect(store.load(for: workspace).sidebarWidth == 800) - #expect(store.load(for: workspace).mavenPaneWidth == 900) + #expect(store.load(for: workspace).rightPaneWidth == 900) } } -private final class MavenLayoutTestStore: KeyValueStore { +private final class RightPaneLayoutTestStore: KeyValueStore { private var values: [String: Any] = [:] func data(forKey key: String) -> Data? { values[key] as? Data } func object(forKey key: String) -> Any? { values[key] } diff --git a/macos/Tests/LitheTests/WorkflowActionsSpy.swift b/macos/Tests/LitheTests/WorkflowActionsSpy.swift index e2d71e14ac..771edd83bd 100644 --- a/macos/Tests/LitheTests/WorkflowActionsSpy.swift +++ b/macos/Tests/LitheTests/WorkflowActionsSpy.swift @@ -43,10 +43,6 @@ final class WorkflowActionsSpy: DebugSessionCleanupActions, RunWorkflowActions { events.append("activate") } - func stopJavaTestResultServer() { - events.append("stop-java-result-server") - } - func stopDebugTerminalProcesses(for debugSessionID: DebugSessionID?) { events.append(debugSessionID == nil ? "stop-terminals" : "stop-session-terminals") stoppedTerminalSessionIDs.append(debugSessionID) @@ -90,9 +86,11 @@ final class WorkflowActionsSpy: DebugSessionCleanupActions, RunWorkflowActions { @MainActor final class NotificationSpy { private(set) var messages: [String] = [] + private(set) var arguments: [[String]] = [] - func notify(_ message: String) { + func notify(_ message: String, arguments: [String]) { messages.append(message) + self.arguments.append(arguments) } } @@ -101,7 +99,7 @@ final class NotificationSpy { /// extension. @MainActor func makeRunWorkflowCoordinator( - notify: @escaping @MainActor (String) -> Void = { _ in }, + notify: @escaping @MainActor (String, [String]) -> Void = { _, _ in }, onPendingActionChange: @escaping @MainActor () -> Void = {} ) -> RunWorkflowCoordinator { RunWorkflowCoordinator( diff --git a/macos/Tests/LitheTests/WorkspaceLanguageServerPreferencesTests.swift b/macos/Tests/LitheTests/WorkspaceLanguageServerPreferencesTests.swift index 56769f2e6b..a0192f5500 100644 --- a/macos/Tests/LitheTests/WorkspaceLanguageServerPreferencesTests.swift +++ b/macos/Tests/LitheTests/WorkspaceLanguageServerPreferencesTests.swift @@ -18,8 +18,8 @@ struct WorkspaceLanguageServerPreferencesTests { defer { defaults.removePersistentDomain(forName: suiteName) } let feature = makeFeature(store: MacUserDefaultsStore(defaults: defaults)) feature.reloadCatalog(for: workspace) - #expect(!feature.isDisabled("java")) - feature.setEnabled(false, providerID: "java") + #expect(!feature.isDisabled("node")) + feature.setEnabled(false, providerID: "node") feature.setEnabled(false, providerID: "go") feature.setEnabled(false, providerID: "rust") // A temporarily unavailable plugin must keep its preference so a later @@ -29,22 +29,22 @@ struct WorkspaceLanguageServerPreferencesTests { let reopenedDefaults = try #require(UserDefaults(suiteName: suiteName)) let reopened = makeFeature(store: MacUserDefaultsStore(defaults: reopenedDefaults)) reopened.reloadCatalog(for: workspace.appendingPathComponent("child/..", isDirectory: true)) - #expect(reopened.disabledProviderIDs == ["example-plugin-language", "go", "java", "rust"]) + #expect(reopened.disabledProviderIDs == ["example-plugin-language", "go", "node", "rust"]) reopened.reloadCatalog(for: URL(fileURLWithPath: "/example/another-project")) #expect(reopened.disabledProviderIDs.isEmpty) reopened.setEnabled(false, providerID: "python") reopened.reloadCatalog(for: workspace) - #expect(reopened.disabledProviderIDs == ["example-plugin-language", "go", "java", "rust"]) + #expect(reopened.disabledProviderIDs == ["example-plugin-language", "go", "node", "rust"]) } - @Test(arguments: ["java", "go", "rust"]) + @Test(arguments: ["node", "go", "rust"]) func reenablingPersistsBeforeMatchingDocumentsAreActivated(_ providerID: String) throws { let store = LanguagePreferencesTestStore() let feature = makeFeature(store: store) feature.reloadCatalog(for: workspace) let documentsByProvider = [ - "java": document("Main.java"), + "node": document("main.js"), "go": document("main.go"), "rust": document("main.rs") ] @@ -78,16 +78,16 @@ struct WorkspaceLanguageServerPreferencesTests { let store = LanguagePreferencesTestStore() let feature = makeFeature(store: store) feature.reloadCatalog(for: workspace) - feature.setEnabled(false, providerID: "java") + feature.setEnabled(false, providerID: "node") feature.resetWorkspaceState() - feature.toolConfigurationDidChange(providerID: "java") - #expect(feature.isDisabled("java")) + feature.toolConfigurationDidChange(providerID: "node") + #expect(feature.isDisabled("node")) feature.reloadCatalog(for: nil) #expect(feature.disabledProviderIDs.isEmpty) feature.reloadCatalog(for: workspace) - #expect(feature.isDisabled("java")) + #expect(feature.isDisabled("node")) } @Test @@ -136,9 +136,9 @@ struct WorkspaceLanguageServerPreferencesTests { let observation = feature.objectWillChange.sink { changes += 1 } defer { observation.cancel() } - feature.setEnabled(false, providerID: "java") + feature.setEnabled(false, providerID: "node") #expect(changes == 1) - feature.setEnabled(true, providerID: "java") + feature.setEnabled(true, providerID: "node") #expect(changes == 2) } @@ -146,48 +146,25 @@ struct WorkspaceLanguageServerPreferencesTests { func togglesWithoutAWorkspaceDoNotOverwritePreferences() { let store = LanguagePreferencesTestStore() let feature = makeFeature(store: store) - feature.setEnabled(false, providerID: "java") + feature.setEnabled(false, providerID: "node") #expect(feature.disabledProviderIDs.isEmpty) #expect(store.values.isEmpty) } @Test - func disabledJavaSkipsWorkspaceAndDocumentStartup() async { + func disabledLanguageSkipsDocumentStartup() async { let store = LanguagePreferencesTestStore() MacWorkspaceLanguageServerPreferencesStore(store: store) - .saveDisabledProviderIDs(["java"], for: workspace) + .saveDisabledProviderIDs(["node"], for: workspace) let model = makeAppModel(store: store) - defer { model.cancelJavaLanguageServerPreparation() } - // The injected workspace policy allows Java startup. Restoring the saved - // preference must prevent preparation even when Java files are eligible. model.languageToolingFeature.reloadCatalog(for: workspace) model.workspaceSessionCoordinator.beginWorkspace(at: workspace) - model.prepareJavaLanguageServerForWorkspaceIfNeeded( - at: workspace, - files: [workspace.appendingPathComponent("Main.java")] - ) - #expect(model.javaFeature.languageServerOperationID == nil) #expect(model.activeNotifications.isEmpty) - #expect(!model.activateLanguageServerIfAvailable(for: document("Main.java"))) - #expect(await model.javaNavigationMarkers(for: document("Main.java")) == []) - #expect(model.javaFeature.languageServerOperationID == nil) + #expect(!model.activateLanguageServerIfAvailable(for: document("main.js"))) #expect(model.languageToolingSessionsIfActive == nil) #expect(model.activeNotifications.isEmpty) - - // Re-enable on the same model to prove the setup reaches preparation. - // Cancel before the queued task runs so no JDK or real LSP is needed. - model.setLanguageServerEnabled(true, providerID: "java") - guard case .preparing(let owner) = model.javaFeature.languageServerWorkspaceState else { - Issue.record("Enabling Java should schedule workspace preparation") - await model.shutdownProjectSession() - return - } - let task = owner.task - #expect(task != nil) - model.cancelJavaLanguageServerPreparation() - await task?.value await model.shutdownProjectSession() } @@ -195,15 +172,15 @@ struct WorkspaceLanguageServerPreferencesTests { func maintenanceSessionsReadSavedPreferencesWithoutDocumentActivation() async throws { let store = LanguagePreferencesTestStore() let preferences = MacWorkspaceLanguageServerPreferencesStore(store: store) - preferences.saveDisabledProviderIDs(["java"], for: workspace) + preferences.saveDisabledProviderIDs(["python"], for: workspace) let model = makeAppModel(store: store, moduleLaunchMode: .normal) model.languageToolingFeature.reloadCatalog(for: workspace) model.workspaceSessionCoordinator.beginWorkspace(at: workspace) do { let sessions = try await model.languageSessionsForWorkspaceMaintenance() defer { sessions.stopAllLanguageServers() } - #expect(throws: LanguageToolingSessionError.providerDisabled("Java")) { - try sessions.startLanguageServer(providerID: "java", rootURL: workspace) + #expect(throws: LanguageToolingSessionError.providerDisabled("Python")) { + try sessions.startLanguageServer(providerID: "python", rootURL: workspace) } // A language first disabled after module activation must be observed // by the same manager, without recreating or rebinding the module. @@ -220,36 +197,15 @@ struct WorkspaceLanguageServerPreferencesTests { } @Test - func disablingJavaCancelsPendingPreparationAndSavesTheChoice() async { + func disablingALanguageSavesTheChoice() async { let store = LanguagePreferencesTestStore() let model = makeAppModel(store: store) model.languageToolingFeature.reloadCatalog(for: workspace) model.workspaceSessionCoordinator.beginWorkspace(at: workspace) - let owner = model.javaFeature.beginLanguageServerPreparation( - workspaceURL: workspace, - operationID: UUID() - ) - var reachedStartup = false - JavaLanguageServerPreparationCoordinator().schedule(for: owner) { - guard !Task.isCancelled else { return } - reachedStartup = true - } - let preparationTask = owner.task - defer { - preparationTask?.cancel() - model.cancelJavaLanguageServerPreparation() - } - // The checkbox is turned off before the queued preparation gets its - // first turn. Cancellation must prevent it from starting a server. - model.setLanguageServerEnabled(false, providerID: "java") - #expect(preparationTask?.isCancelled == true) - #expect(owner.task == nil) - #expect(model.javaFeature.languageServerOperationID == nil) + model.setLanguageServerEnabled(false, providerID: "node") #expect(MacWorkspaceLanguageServerPreferencesStore(store: store) - .disabledProviderIDs(for: workspace) == ["java"]) - await preparationTask?.value - #expect(!reachedStartup) + .disabledProviderIDs(for: workspace) == ["node"]) await model.shutdownProjectSession() } @@ -258,7 +214,7 @@ struct WorkspaceLanguageServerPreferencesTests { func cancelledActivationIsNeitherReportedNorRecordedAsAStartupFailure() throws { let feature = makeFeature(store: LanguagePreferencesTestStore()) feature.reloadCatalog(for: workspace) - let descriptor = try #require(feature.catalog.provider(for: document("Main.java").url)) + let descriptor = try #require(feature.catalog.provider(for: document("main.py").url)) var notifications: [String] = [] feature.configure(documentsProvider: { [] }, activateDocument: { _ in false }, notify: { notifications.append($0) }) @@ -276,7 +232,7 @@ struct WorkspaceLanguageServerPreferencesTests { func failureOfADisabledServerIsNotReported() throws { let feature = makeFeature(store: LanguagePreferencesTestStore()) feature.reloadCatalog(for: workspace) - let descriptor = try #require(feature.catalog.provider(for: document("Main.java").url)) + let descriptor = try #require(feature.catalog.provider(for: document("main.py").url)) var notifications: [String] = [] feature.configure(documentsProvider: { [] }, activateDocument: { _ in false }, notify: { notifications.append($0) }) @@ -310,33 +266,12 @@ struct WorkspaceLanguageServerPreferencesTests { let services = MacServiceContainer( store: store, settings: settings, - moduleLaunchMode: moduleLaunchMode, - javaMavenOperations: LanguagePreferencesJavaOperations() + moduleLaunchMode: moduleLaunchMode ).services return AppModel(settings: settings, services: services) } } -private struct LanguagePreferencesJavaOperations: JavaMavenOperations { - func javaWorkspacePolicy( - at rootURL: URL, - files: [URL], - changedFiles: [URL] - ) -> JavaWorkspacePolicyResult? { - JavaWorkspacePolicyResult( - shouldStart: true, - representativeJavaURL: rootURL.appendingPathComponent("Main.java"), - changes: [] - ) - } - - func codeVision(at rootURL: URL, targetPath: String, paths: [String]) -> [JavaCodeVisionValue] { [] } - func className(source: String, simpleName: String) -> String? { nil } - func sourceDefinition(source: String, declarationName: String, memberName: String?) -> (line: Int, utf16Column: Int)? { nil } - func serverPort(content: String, fileExtension: String) -> Int? { nil } - func structure(source: String, declarationSources: [String]) -> JavaStructureResult? { nil } -} - private struct LanguagePreferencesTestCatalogSource: LanguageProviderCatalogSource { func load(workspaceURL: URL?) -> LanguageProviderCatalogSnapshot { LanguageProviderCatalogSnapshot( diff --git a/rust/lithe-core/resources/lsp/language-providers.json b/rust/lithe-core/resources/lsp/language-providers.json index 75c4a4b6f0..4275a3d302 100644 --- a/rust/lithe-core/resources/lsp/language-providers.json +++ b/rust/lithe-core/resources/lsp/language-providers.json @@ -5,7 +5,7 @@ "id": "java", "displayName": "Java", "fileExtensions": ["java"], - "capabilities": ["run", "languageServer", "debugAdapter", "formatting", "testing"], + "capabilities": ["languageServer", "formatting"], "activationPolicy": "onDemand", "languageId": "java", "languageServerLaunch": { diff --git a/rust/lithe-core/src/build/commands.rs b/rust/lithe-core/src/build/commands.rs index 19e0f81b78..a63bdb1d69 100644 --- a/rust/lithe-core/src/build/commands.rs +++ b/rust/lithe-core/src/build/commands.rs @@ -8,7 +8,6 @@ use super::detect::{self, DetectRequest}; use super::invocation::{self, InvocationRequest, VersionCheckRequest}; -use super::language_import::{self, LanguageImportRequest}; use super::manifest::BuildSystemDeclaration; use super::options; use super::outputs::{ @@ -316,19 +315,6 @@ pub(crate) fn build_sync_fingerprint_command(payload: Value) -> Result Result { - with_build_system( - payload, - "build.languageImport", - "languageImport", - |build_system, request: &LanguageImportRequest| { - language_import::language_import(build_system, request) - }, - ) -} - /// `build.prepareDebugPlan`: a selected provider run's native debug preparation. pub(crate) fn build_prepare_debug_plan_command(payload: Value) -> Result { with_build_system( diff --git a/rust/lithe-core/src/build/integrations/maven.rs b/rust/lithe-core/src/build/integrations/maven.rs deleted file mode 100644 index 6e772cd3d3..0000000000 --- a/rust/lithe-core/src/build/integrations/maven.rs +++ /dev/null @@ -1,334 +0,0 @@ -//! The `maven` host integration: reactor models from the POM reader, the -//! dependency-tree goal and its text format, and Surefire/Failsafe results. -//! -//! Everything else about Maven (executables, options, lifecycle tasks, -//! diagnostics) is declared by the official Maven plugin's `plugin.json`. -//! The integration fills the model's `profiles` option values when the -//! plugin declares that option with `choicesFromModel`. - -use super::rejected; -use crate::build::decode::{self, join_relative, Workspace}; -use crate::build::manifest::ContentRootKind; -use crate::build::model::{ - add_integration_content_root, add_integration_option_value, add_integration_project, - ModelBuilder, -}; -use crate::build::outputs::{ - DecodeTestResultsRequest, DependencyNode, TestCaseResult, TestResults, TestStatus, TestSummary, -}; -use crate::build::plans::{invalid_selection, Selection}; -use crate::plugins::declarative::Validation; -use crate::project::{ - dependencies as maven_dependencies, dependency_tree_arguments, scan, - test_results as maven_test_results, validated_output_file, MavenDependenciesRequest, - MavenScanRequest, MavenTestReportsRequest, MavenTestResultsRequest, -}; -use crate::protocol::{ - MavenDependencyResponse, MavenModuleResponse, MavenSourceRootKind, MavenSourceRootResponse, -}; -use serde_json::{json, Map, Value}; -use std::collections::BTreeMap; - -/// Option whose choices the integration fills from the reactor's profiles. -const PROFILES_OPTION: &str = "profiles"; - -fn content_root_kind(kind: MavenSourceRootKind) -> ContentRootKind { - match kind { - MavenSourceRootKind::MainJava => ContentRootKind::Source, - MavenSourceRootKind::MainResources => ContentRootKind::Resource, - MavenSourceRootKind::TestJava => ContentRootKind::TestSource, - MavenSourceRootKind::TestResources => ContentRootKind::TestResource, - MavenSourceRootKind::GeneratedMain => ContentRootKind::GeneratedSource, - MavenSourceRootKind::GeneratedTest => ContentRootKind::GeneratedTestSource, - } -} - -#[allow(clippy::too_many_arguments)] -fn add_project( - builder: &mut ModelBuilder<'_>, - path: String, - artifact_id: &str, - group_id: Option<&String>, - version: Option<&String>, - packaging: &str, - source_roots: &[MavenSourceRootResponse], -) { - let mut properties = BTreeMap::from([ - ("artifactId".to_string(), artifact_id.to_string()), - ("packaging".to_string(), packaging.to_string()), - ]); - if let Some(group_id) = group_id { - properties.insert("groupId".to_string(), group_id.clone()); - } - if let Some(version) = version { - properties.insert("version".to_string(), version.clone()); - } - let Some(index) = add_integration_project(builder, path.clone(), artifact_id, properties) - else { - return; - }; - for source_root in source_roots { - add_integration_content_root( - builder, - index, - join_relative(&path, &source_root.path), - content_root_kind(source_root.kind), - ); - } -} - -fn add_modules(builder: &mut ModelBuilder<'_>, root: &str, modules: &[MavenModuleResponse]) { - for module in modules { - add_project( - builder, - join_relative(root, &module.relative_path), - &module.artifact_id, - module.group_id.as_ref(), - module.version.as_ref(), - &module.packaging, - &module.source_roots, - ); - add_modules(builder, root, &module.modules); - } -} - -/// Reads the reactor at the instance root. The scan is rooted there, so a -/// POM above the instance never takes over its model. -pub(super) fn model( - workspace: &Workspace, - root: &str, - builder: &mut ModelBuilder<'_>, -) -> Validation<()> { - let reactor = workspace - .read_path(root) - .ok_or_else(|| decode::invalid_output("The build-system root is outside the workspace."))?; - let scanned = scan(MavenScanRequest { - root: reactor.to_string_lossy().into_owned(), - paths: vec!["pom.xml".to_string()], - }) - .map_err(rejected)? - .ok_or_else(|| decode::invalid_output("The build-system root has no readable pom.xml."))?; - add_project( - builder, - join_relative(root, &scanned.relative_path), - &scanned.artifact_id, - scanned.group_id.as_ref(), - scanned.version.as_ref(), - &scanned.packaging, - &scanned.source_roots, - ); - add_modules(builder, root, &scanned.modules); - for profile in &scanned.profiles { - add_integration_option_value(builder, PROFILES_OPTION, &profile.id); - } - Ok(()) -} - -/// Selection flags and the dependency-tree goal: one project per plan, -/// because every project would overwrite the same output file. -pub(super) fn dependency_arguments( - project: Option<&Selection>, - output_file: Option<&str>, -) -> Validation> { - let output_file = output_file - .ok_or_else(|| invalid_selection("The Maven dependency tree needs outputFile.")) - .and_then(|path| validated_output_file(path).map_err(rejected))?; - let mut arguments = Vec::new(); - match project.map(|project| project.relative.as_str()) { - Some(module) if module != "." => arguments.extend(["-pl".to_string(), module.to_string()]), - _ => arguments.push("-N".to_string()), - } - arguments.extend(dependency_tree_arguments(&output_file)); - Ok(arguments) -} - -pub(super) fn dependency_plan_extra() -> Map { - let mut extra = Map::new(); - extra.insert("output".to_string(), json!("outputFile")); - extra.insert("decoder".to_string(), json!("hostIntegration")); - extra.insert("executesProjectCode".to_string(), json!(true)); - extra.insert("mayUseNetwork".to_string(), json!(true)); - extra -} - -fn dependency_node(dependency: MavenDependencyResponse) -> DependencyNode { - let mut properties = BTreeMap::from([ - ("type".to_string(), dependency.r#type), - ( - "resolution".to_string(), - serde_json::to_value(&dependency.resolution) - .ok() - .and_then(|value| value.as_str().map(str::to_string)) - .unwrap_or_default(), - ), - ]); - for (key, value) in [ - ("classifier", dependency.classifier), - ("selectedVersion", dependency.selected_version), - ("premanagedVersion", dependency.premanaged_version), - ("premanagedScope", dependency.premanaged_scope), - ("originalScope", dependency.original_scope), - ("ignoredScope", dependency.ignored_scope), - ] { - if let Some(value) = value { - properties.insert(key.to_string(), value); - } - } - DependencyNode { - name: dependency.artifact_id, - group: Some(dependency.group_id), - version: Some(dependency.version), - scope: Some(dependency.scope), - properties, - children: dependency - .children - .into_iter() - .map(dependency_node) - .collect(), - } -} - -pub(super) fn dependencies( - root: &str, - project: &str, - output_file: Option<&str>, -) -> Validation> { - let module_path = decode::relative_to(root, project) - .ok_or_else(|| invalid_selection("The project is outside the build-system root."))?; - let output_file = output_file - .ok_or_else(|| invalid_selection("Pass the outputFile the dependency plan wrote."))?; - let response = maven_dependencies(MavenDependenciesRequest { - module_path, - output_file: output_file.to_string(), - }) - .map_err(rejected)?; - Ok(response - .dependencies - .into_iter() - .map(dependency_node) - .collect()) -} - -fn status(value: &str) -> TestStatus { - match value { - "failed" => TestStatus::Failed, - "error" => TestStatus::Error, - "skipped" => TestStatus::Skipped, - _ => TestStatus::Passed, - } -} - -/// Splits a Surefire failure name (`method(Class)`, `Class.method`, or -/// `Class#method`) into suite and case. -fn split_failure_name(name: &str) -> (String, String) { - if let Some((method, rest)) = name.split_once('(') { - return (rest.trim_end_matches(')').to_string(), method.to_string()); - } - if let Some((class, method)) = name.rsplit_once('#').or_else(|| name.rsplit_once('.')) { - return (class.to_string(), method.to_string()); - } - (String::new(), name.to_string()) -} - -pub(super) fn test_results( - workspace: &Workspace, - root: &str, - project: &str, - request: &DecodeTestResultsRequest, -) -> Validation { - let reports = request - .not_before_millis - .map(|not_before_millis| MavenTestReportsRequest { - module: Some(project.to_string()), - source_path: None, - classes: request.suite.iter().cloned().collect(), - not_before_millis, - }); - let response = maven_test_results(MavenTestResultsRequest { - root: workspace.path.to_string_lossy().into_owned(), - output: request.output.clone(), - reports, - }) - .map_err(rejected)?; - let mut reported_cases = response.test_cases; - if let Some(not_before_millis) = request.not_before_millis { - // Reactor runs write reports in each module, never just the aggregator. - // Keep text parsing once while reusing Maven's report locations per module. - for directory in super::super::outputs::report_directories(root, project, request)? { - if directory == project { - continue; - } - let module = maven_test_results(MavenTestResultsRequest { - root: workspace.path.to_string_lossy().into_owned(), - output: String::new(), - reports: Some(MavenTestReportsRequest { - module: Some(directory), - source_path: None, - classes: request.suite.iter().cloned().collect(), - not_before_millis, - }), - }) - .map_err(rejected)?; - if reported_cases.len() + module.test_cases.len() - > super::super::outputs::MAX_TEST_CASES - { - return Err(decode::invalid_output( - "The reactor has too many test cases.", - )); - } - reported_cases.extend(module.test_cases); - } - } - let mut cases: Vec = reported_cases - .into_iter() - .map(|case| TestCaseResult { - project: None, - suite: case.class_name, - case: case.method, - status: status(&case.status), - message: case.message, - duration_millis: case.duration_millis, - path: None, - line: None, - invocations: case.invocations.max(1), - }) - .collect(); - // Failure details carry the source location the reports lack; a run - // without reports still lists its failures. - for detail in response.failure_details { - let (suite, case) = split_failure_name(&detail.name); - let status = if detail.kind == "error" { - TestStatus::Error - } else { - TestStatus::Failed - }; - match cases - .iter_mut() - .find(|existing| existing.suite == suite && existing.case == case) - { - Some(existing) => { - existing.path = existing.path.take().or(detail.path); - existing.line = existing.line.or(detail.line); - } - None => cases.push(TestCaseResult { - project: None, - suite, - case, - status, - message: detail.message, - duration_millis: None, - path: detail.path, - line: detail.line, - invocations: 1, - }), - } - } - let summary = (response.tests_run > 0 || cases.is_empty()).then_some(TestSummary { - total: response.tests_run, - passed: response.passed, - failed: response.failures, - errors: response.errors, - skipped: response.skipped, - }); - Ok(TestResults { cases, summary }) -} diff --git a/rust/lithe-core/src/build/integrations/mod.rs b/rust/lithe-core/src/build/integrations/mod.rs deleted file mode 100644 index 2d28be05ef..0000000000 --- a/rust/lithe-core/src/build/integrations/mod.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! Named host integrations: host code a build system may delegate one -//! concern to when its output fits neither a selector map nor a canonical -//! format yet. -//! -//! Only official plugins may name one, and each exists to migrate a -//! built-in tool onto the plugin model without changing its behavior. A new -//! build system never needs one; a new integration needs a reviewed reason -//! why the declarative contract cannot express it. - -mod maven; - -use super::decode::Workspace; -use super::manifest::{BuildSystemDeclaration, HOST_INTEGRATION_MAVEN}; -use super::model::ModelBuilder; -use super::outputs::{DecodeTestResultsRequest, DependencyNode, TestResults}; -use super::plans::{PlanContext, Selection}; -use super::template; -use crate::plugins::declarative::{PluginRejection, Validation}; -use crate::protocol::CoreError; -use serde_json::Value; - -fn missing(build_system: &BuildSystemDeclaration) -> PluginRejection { - PluginRejection::new( - "plugin.integration.unsupported", - format!( - "{} names no host integration this host provides.", - build_system.display_name - ), - ) -} - -/// Host-side failures surface as invalid output: the integration could not -/// read what the tool left behind. -fn rejected(error: CoreError) -> PluginRejection { - PluginRejection::new("plugin.build.invalidOutput", error.message) -} - -pub(crate) fn model( - build_system: &BuildSystemDeclaration, - workspace: &Workspace, - root: &str, - builder: &mut ModelBuilder<'_>, -) -> Validation<()> { - match build_system.integration() { - Some(HOST_INTEGRATION_MAVEN) => maven::model(workspace, root, builder), - _ => Err(missing(build_system)), - } -} - -pub(crate) fn dependency_plan( - context: &PlanContext<'_>, - project: Option<&Selection>, - output_file: Option<&str>, -) -> Validation { - match context.build_system.integration() { - Some(HOST_INTEGRATION_MAVEN) => { - let tail = maven::dependency_arguments(project, output_file)?; - context.plan_with_arguments( - integration_arguments(context, tail)?, - super::manifest::BuildExecution::Task, - maven::dependency_plan_extra(), - ) - } - _ => Err(missing(context.build_system)), - } -} - -pub(crate) fn dependencies( - build_system: &BuildSystemDeclaration, - root: &str, - project: &str, - output_file: Option<&str>, -) -> Validation> { - match build_system.integration() { - Some(HOST_INTEGRATION_MAVEN) => maven::dependencies(root, project, output_file), - _ => Err(missing(build_system)), - } -} - -pub(crate) fn test_results( - build_system: &BuildSystemDeclaration, - workspace: &Workspace, - root: &str, - project: &str, - request: &DecodeTestResultsRequest, -) -> Validation { - match build_system.integration() { - Some(HOST_INTEGRATION_MAVEN) => maven::test_results(workspace, root, project, request), - _ => Err(missing(build_system)), - } -} - -/// Global arguments, then the arguments of every option the globals do not -/// place themselves, then the integration's own: the same order a declared -/// command would produce when it lists `${optionArguments}` for the rest. -fn integration_arguments(context: &PlanContext<'_>, tail: Vec) -> Validation> { - let globals = &context.build_system.invocation.global_arguments; - let values = template::Values { - root: &context.root, - option_arguments: &context.contribution.arguments, - ..template::Values::default() - }; - let mut arguments = template::expand(globals, &values)?; - let (all, named) = template::option_references(globals); - if !all { - for (id, expanded) in &context.contribution.arguments { - if !named.contains(id) { - arguments.extend(expanded.iter().cloned()); - } - } - } - arguments.extend(tail); - Ok(arguments) -} diff --git a/rust/lithe-core/src/build/invocation.rs b/rust/lithe-core/src/build/invocation.rs index 1e097de24d..100df2eeb0 100644 --- a/rust/lithe-core/src/build/invocation.rs +++ b/rust/lithe-core/src/build/invocation.rs @@ -69,13 +69,12 @@ fn candidates( /// Arguments that make a host-managed runtime print its version and exit. /// Core owns them so hosts use the same probe, for build runtimes and for -/// plugin launch runtimes alike. Java needs `-version` for -/// Java 8 compatibility; its version is printed to stderr, which hosts must -/// capture together with stdout before checking the declared minimum. +/// plugin launch runtimes alike. Hosts capture stderr together with stdout +/// before checking the declared minimum. A tool definition probes the +/// runtimes it resolves itself, so other IDs have none. pub(crate) fn host_runtime_version_arguments(id: &str) -> Option<&'static [&'static str]> { match id { "go" => Some(&["version"]), - "java" => Some(&["-version"]), "node" => Some(&["--version"]), _ => None, } @@ -97,12 +96,19 @@ fn runtime( .as_ref() .map(|probe| json!({ "arguments": probe.arguments })) }; + // An implicit reference is the toolchain candidate of the tool + // definition with the same ID; resolving it checks `minimumVersion`. + let executables = if runtime.names_tool_definition() { + vec![json!({ "kind": "toolchain", "toolchainID": runtime.id, "root": root })] + } else { + candidates(&runtime.executables, root, platform, manifest, settings)? + }; Ok(json!({ "id": runtime.id, "displayName": runtime.display_name, "hostManaged": runtime.is_host_managed(), "minimumVersion": runtime.minimum_version, - "executables": candidates(&runtime.executables, root, platform, manifest, settings)?, + "executables": executables, "version": version, })) } @@ -188,8 +194,17 @@ pub(crate) fn check_version( format!("{} declares no runtime {id}.", build_system.display_name), ) })?; + if dependency.version.is_none() && dependency.checked_by_tool_definition() { + return Err(PluginRejection::new( + "plugin.build.unavailable", + format!( + "{} declares no version probe for {id}; its tool definition checks the version.", + build_system.display_name + ), + )); + } let found = if dependency.is_host_managed() { - reported_version(&dependency.id, &request.output) + reported_version(&request.output) } else { dependency .version diff --git a/rust/lithe-core/src/build/language_import.rs b/rust/lithe-core/src/build/language_import.rs deleted file mode 100644 index 9b84b4dc6a..0000000000 --- a/rust/lithe-core/src/build/language_import.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! `build.languageImport`: the Java language server's project import -//! settings for one build-system instance, from the user's build options. -//! -//! The result has the shapes `lsp.startServer` already accepts, the Maven -//! launch context (`mavenContext`) and the Gradle import context -//! (`javaGradle`), so a host forwards it without knowing which plugin -//! declared the build system. - -use super::decode::{self, Workspace}; -use super::manifest::{BuildSystemDeclaration, LanguageImportKind}; -use super::options; -use crate::plugins::declarative::Validation; -use serde::Deserialize; -use serde_json::{json, Map, Value}; -use std::collections::BTreeMap; - -/// Where Buildship looks for the wrapper, relative to the instance root. -const GRADLE_WRAPPER_DESCRIPTOR: &str = "gradle/wrapper/gradle-wrapper.properties"; - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub(crate) struct LanguageImportRequest { - pub(crate) workspace_root: String, - pub(crate) root: String, - /// Stored option values by option ID. - #[serde(default)] - pub(crate) options: BTreeMap, - /// The tool executable the host resolved for this instance; Maven reads - /// its installation settings next to it. - #[serde(default)] - pub(crate) executable_path: Option, -} - -/// `null` when the build system declares no import, otherwise -/// `{ kind: "maven", mavenContext }` or `{ kind: "gradle", javaGradle }`. -pub(crate) fn language_import( - build_system: &BuildSystemDeclaration, - request: &LanguageImportRequest, -) -> Validation { - let workspace = Workspace::new(&request.workspace_root)?; - let root = decode::request_path(&request.root, "root")?; - let Some(import) = &build_system.language_import else { - return Ok(Value::Null); - }; - let resolved = options::resolve(build_system, &request.options, None); - // Each setting is the effective value of the option the plugin mapped it - // to; an option with no effective value leaves the setting unset. - let setting = |name: &str| { - import - .options - .get(name) - .and_then(|option| resolved.values.get(option)) - }; - let text = |name: &str| setting(name).and_then(Value::as_str).map(str::to_string); - Ok(match import.kind { - LanguageImportKind::Maven => { - let profiles: Vec<&str> = setting("profiles") - .and_then(Value::as_array) - .map(|items| items.iter().filter_map(Value::as_str).collect()) - .unwrap_or_default(); - let mut context = Map::new(); - context.insert( - "version".into(), - json!(crate::project::MAVEN_CONTEXT_VERSION), - ); - context.insert("reactorPath".into(), json!(root)); - context.insert("profiles".into(), json!(profiles)); - for (key, value) in [ - ("settingsPath", text("settingsFile")), - ("localRepositoryPath", text("localRepository")), - ("mavenExecutablePath", request.executable_path.clone()), - ] { - if let Some(value) = value { - context.insert(key.into(), json!(value)); - } - } - json!({ "kind": "maven", "mavenContext": context }) - } - LanguageImportKind::Gradle => { - let wrapper = decode::join_relative(&root, GRADLE_WRAPPER_DESCRIPTOR); - let mut gradle = Map::new(); - gradle.insert( - "wrapperPresent".into(), - json!(workspace.read_path(&wrapper).is_some_and(|path| { - crate::remote::workspace_io::is_file(path).unwrap_or(false) - })), - ); - gradle.insert( - "offline".into(), - json!(setting("offline") == Some(&Value::Bool(true))), - ); - if let Some(home) = text("gradleUserHome") { - gradle.insert("userHome".into(), json!(home)); - } - json!({ "kind": "gradle", "javaGradle": gradle }) - } - }) -} diff --git a/rust/lithe-core/src/build/manifest.rs b/rust/lithe-core/src/build/manifest.rs index 842d0b6856..505eeaf161 100644 --- a/rust/lithe-core/src/build/manifest.rs +++ b/rust/lithe-core/src/build/manifest.rs @@ -7,15 +7,16 @@ //! one of the canonical `lithe*` formats. What no command can print is //! answered by a `provider`: a server process of the plugin, declared with //! the language-server launch fields or shared with one of its language -//! servers. The only named host code is a `hostIntegration`, reserved to -//! official plugins while Maven migrates. +//! servers. The only named host code is a `hostIntegration`: a host-side +//! model decoder any plugin selects by ID; the host never special-cases a +//! build tool by name. use super::select::{self, FieldSpec, Predicate}; use super::template::{self, Allowed, Availability, BuildArgument, Variable}; use crate::plugins::declarative::{ invalid, is_bare_command, is_identifier, is_safe_relative_path, is_setting_identifier, sorted_unique, template as template_error, validate_minimum_version, PluginRejection, - ServerProcess, ServerRole, UIIcon, Validation, KNOWN_RUNTIME_TOOLS_V2, + ServerProcess, ServerRole, UIIcon, Validation, KNOWN_RUNTIME_TOOLS, }; use regex::Regex; use serde::{Deserialize, Deserializer, Serialize}; @@ -24,9 +25,10 @@ use std::collections::{BTreeMap, BTreeSet}; /// First plugin API level with `buildSystems`. pub(crate) const BUILD_SYSTEMS_API_VERSION: u32 = 3; -/// Host integrations a build system may name; official plugins only. -pub(crate) const HOST_INTEGRATION_MAVEN: &str = "maven"; -const HOST_INTEGRATIONS: &[&str] = &[HOST_INTEGRATION_MAVEN]; +/// Host integrations a build system may name. The Core implements none: +/// every build tool is described by its plugin's data and backend, so any +/// name is refused with `plugin.integration.unsupported`. +const HOST_INTEGRATIONS: &[&str] = &[]; const MAX_BUILD_SYSTEMS: usize = 16; const MAX_LIST: usize = 32; @@ -86,9 +88,6 @@ pub(crate) struct BuildSystemDeclaration { pub(crate) sync: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) layout: Option, - /// How the Java language server imports this build system's projects. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub(crate) language_import: Option, } /// A server process that answers `lithe/build/*` requests over the LSP base @@ -193,7 +192,7 @@ pub(crate) enum Nesting { #[default] Separate, /// Only candidates with no candidate above them are instances; deeper - /// markers belong to them (Gradle builds, Maven reactors). + /// markers belong to them (multi-project builds and reactors). Outermost, } @@ -222,10 +221,12 @@ pub(crate) struct Invocation { pub(crate) use crate::plugins::executables::{ExecutableCandidate, ExecutableSource, Platform}; -/// A runtime the tool needs. Runtimes the host already manages (`java`, -/// `node`, `go`) take only an ID and an optional minimum version and follow -/// the user's runtime settings; any other runtime describes how to find and -/// probe it, so a community plugin is never limited to a host list. +/// A runtime the tool needs. Runtimes the host already manages (`node`, +/// `go`) take only an ID and an optional minimum version and follow the +/// user's runtime settings. Any other runtime either describes how to find +/// and probe it, or lists no executables and names the tool definition with +/// its ID, which finds the executable and checks `minimumVersion`. A +/// community plugin is never limited to a host list. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct RuntimeDependency { @@ -243,7 +244,29 @@ pub(crate) struct RuntimeDependency { impl RuntimeDependency { /// True when the host discovers this runtime with its own settings. pub(crate) fn is_host_managed(&self) -> bool { - KNOWN_RUNTIME_TOOLS_V2.contains(&self.id.as_str()) + KNOWN_RUNTIME_TOOLS.contains(&self.id.as_str()) + } + + /// True when the runtime is the tool definition with the same ID: it + /// lists no executables and the host does not manage it. Plans give it + /// a single toolchain candidate for that ID. + pub(crate) fn names_tool_definition(&self) -> bool { + self.executables.is_empty() && !self.is_host_managed() + } + + /// True when the tool definition the runtime resolves through checks + /// `minimumVersion`, so the manifest needs no version probe: a runtime + /// the host does not manage that is an implicit reference or has exactly + /// one toolchain candidate. + pub(crate) fn checked_by_tool_definition(&self) -> bool { + !self.is_host_managed() + && matches!( + self.executables.as_slice(), + [] | [ExecutableCandidate { + source: ExecutableSource::Toolchain { .. }, + .. + }] + ) } } @@ -315,7 +338,7 @@ pub(crate) enum OptionPresentation { /// icon only (offline mode, skipping tests). Toolbar, /// A checklist node at the top of the tool window's tree; multiSelect - /// options only (Maven profiles). + /// options only (build profiles). Tree, } @@ -920,50 +943,6 @@ pub(crate) struct LayoutDeclaration { pub(crate) excluded: Vec, } -/// The project import a language server performs for this build system, and -/// which of the plugin's options carry the import settings. -/// -/// The Java language server imports Maven and Gradle projects itself. Its -/// import has to use the profiles, settings, and caches the user chose for -/// the build tool, or the editor resolves other dependencies than the build. -/// A plugin names the import it matches and maps each import setting to one -/// of its own options; Core turns the user's values into the language -/// server's settings, so the host passes them on without knowing the plugin. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub(crate) struct LanguageImportDeclaration { - pub(crate) kind: LanguageImportKind, - /// Import setting -> option ID. Settings without an option keep the - /// language server's default. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] - pub(crate) options: BTreeMap, -} - -/// Project imports Lithe's Java language server knows. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) enum LanguageImportKind { - Maven, - Gradle, -} - -impl LanguageImportKind { - /// The import settings of this kind and the option kind each needs. - pub(crate) fn settings(self) -> &'static [(&'static str, OptionKind)] { - match self { - Self::Maven => &[ - ("profiles", OptionKind::MultiSelect), - ("settingsFile", OptionKind::File), - ("localRepository", OptionKind::Directory), - ], - Self::Gradle => &[ - ("offline", OptionKind::Boolean), - ("gradleUserHome", OptionKind::Directory), - ], - } - } -} - impl BuildSystemDeclaration { pub(crate) fn option(&self, id: &str) -> Option<&OptionDeclaration> { self.options.iter().find(|option| option.id == id) @@ -972,11 +951,6 @@ impl BuildSystemDeclaration { pub(crate) fn task(&self, id: &str) -> Option<&TaskDeclaration> { self.tasks.iter().find(|task| task.id == id) } - - /// True when the named host integration owns this build system. - pub(crate) fn integration(&self) -> Option<&str> { - self.host_integration.as_deref() - } } // MARK: Validation @@ -1290,6 +1264,15 @@ impl BuildSystemDeclaration { matches!(self.provider, Some(ProviderDeclaration::Process(_))) } + /// Whether a runtime dependency names a tool definition by its ID, which + /// plans turn into a toolchain candidate. + pub(crate) fn names_tool_definitions(&self) -> bool { + self.invocation + .runtime_dependencies + .iter() + .any(RuntimeDependency::names_tool_definition) + } + fn validate(&mut self, field: &str, context: &DeclarationContext<'_>) -> Validation<()> { if !is_entry_identifier(&self.id) { return Err(invalid( @@ -1332,43 +1315,9 @@ impl BuildSystemDeclaration { false, )?; } - self.validate_language_import(field)?; self.validate_option_emission(field) } - fn validate_language_import(&self, field: &str) -> Validation<()> { - let Some(import) = &self.language_import else { - return Ok(()); - }; - let settings = import.kind.settings(); - for (setting, option_id) in &import.options { - let field = format!("{field}.languageImport.options.{setting}"); - let Some((_, kind)) = settings.iter().find(|(name, _)| name == setting) else { - let known: Vec<&str> = settings.iter().map(|(name, _)| *name).collect(); - return Err(invalid( - field, - format!("This import has the settings {}.", known.join(", ")), - )); - }; - match self.option(option_id) { - Some(option) if option.kind == *kind => {} - Some(_) => { - return Err(invalid( - field, - format!("The option {option_id} has the wrong kind for this setting."), - )) - } - None => { - return Err(invalid( - field, - format!("The build system declares no option {option_id}."), - )) - } - } - } - Ok(()) - } - fn validate_integration(&self, field: &str, official: bool) -> Validation<()> { let Some(integration) = &self.host_integration else { let named = matches!(self.model, Some(ModelSource::HostIntegration)) @@ -1634,10 +1583,17 @@ impl BuildSystemDeclaration { let mut runtimes = BTreeSet::new(); for (index, runtime) in invocation.runtime_dependencies.iter_mut().enumerate() { let field = format!("{field}.runtimeDependencies[{index}]"); - if !is_entry_identifier(&runtime.id) || !runtimes.insert(runtime.id.clone()) { + // A runtime without executables is a tool-definition ID, which + // may also be plugin-qualified. + let valid_id = if runtime.names_tool_definition() { + crate::toolchain::definitions::tool_id(&runtime.id) + } else { + is_entry_identifier(&runtime.id) + }; + if !valid_id || !runtimes.insert(runtime.id.clone()) { return Err(invalid( format!("{field}.id"), - "Runtime IDs are unique identifiers.", + "Runtime IDs are unique identifiers; a runtime without executables is a tool-definition ID.", )); } if let Some(name) = &runtime.display_name { @@ -1647,9 +1603,8 @@ impl BuildSystemDeclaration { validate_minimum_version(minimum, &format!("{field}.minimumVersion"))?; } if runtime.is_host_managed() { - // The host finds these with the user's own runtime settings - // (the JDK chosen for the project, for example); a plugin - // must not route around that choice. + // The host finds these with the user's own runtime settings; + // a plugin must not route around that choice. let toolchain = runtime.executables.len() == 1 && matches!( runtime.executables[0].source, @@ -1675,10 +1630,24 @@ impl BuildSystemDeclaration { } continue; } - if runtime.executables.is_empty() || runtime.executables.len() > MAX_LIST { + if runtime.names_tool_definition() { + // The tool definition finds the executable and checks + // `minimumVersion`; a probe here would have nothing to run. + if runtime.version.is_some() { + return Err(invalid( + format!("{field}.version"), + format!( + "{} names a tool definition, which checks its version; declare only its minimumVersion.", + runtime.id + ), + )); + } + continue; + } + if runtime.executables.len() > MAX_LIST { return Err(invalid( format!("{field}.executables"), - "A plugin-described runtime needs 1-32 executable candidates.", + "A plugin-described runtime has at most 32 executable candidates.", )); } for (candidate_index, candidate) in runtime.executables.iter_mut().enumerate() { @@ -1698,10 +1667,12 @@ impl BuildSystemDeclaration { } match &runtime.version { Some(probe) => probe.validate(&format!("{field}.version"))?, - None if runtime.minimum_version.is_some() => { + None if runtime.minimum_version.is_some() + && !runtime.checked_by_tool_definition() => + { return Err(invalid( format!("{field}.version"), - "A minimumVersion needs a version probe.", + "A minimumVersion needs a version probe or a single toolchain candidate.", )) } None => {} diff --git a/rust/lithe-core/src/build/mod.rs b/rust/lithe-core/src/build/mod.rs index 91c0524ddd..6a5ebb41c0 100644 --- a/rust/lithe-core/src/build/mod.rs +++ b/rust/lithe-core/src/build/mod.rs @@ -10,8 +10,8 @@ //! executables, start processes, watch files, and store user choices. //! //! Nothing here starts a process or writes a file. Workspace files are only -//! read, and only where a command says so (static models, test reports, sync -//! fingerprints, and the `maven` integration). +//! read, and only where a command says so (static models, test reports, and +//! sync fingerprints). //! //! Note: the contract is recorded in .agents/notes/implemented/architecture/2026-10-17-build-system-plugin-contract.md @@ -20,9 +20,7 @@ mod configuration; mod debug_preparation; mod decode; mod detect; -mod integrations; mod invocation; -mod language_import; mod manifest; mod model; mod model_inputs; diff --git a/rust/lithe-core/src/build/model.rs b/rust/lithe-core/src/build/model.rs index c29306ed41..003cdd957f 100644 --- a/rust/lithe-core/src/build/model.rs +++ b/rust/lithe-core/src/build/model.rs @@ -835,32 +835,3 @@ pub(crate) fn map_canonical(builder: &mut ModelBuilder<'_>, document: Value) -> } Ok(()) } - -// MARK: Host integration input - -/// Adds a project found by a host integration. Paths are workspace-relative. -pub(crate) fn add_integration_project( - builder: &mut ModelBuilder<'_>, - path: String, - name: &str, - properties: BTreeMap, -) -> Option { - builder.add_project(path, name, None, None, properties) -} - -pub(crate) fn add_integration_content_root( - builder: &mut ModelBuilder<'_>, - project: usize, - path: String, - kind: ContentRootKind, -) { - builder.add_content_root(project, path, kind); -} - -pub(crate) fn add_integration_option_value( - builder: &mut ModelBuilder<'_>, - option: &str, - value: &str, -) { - builder.add_option_value(option, value); -} diff --git a/rust/lithe-core/src/build/outputs.rs b/rust/lithe-core/src/build/outputs.rs index 3087c7ebd2..5455dbe3c7 100644 --- a/rust/lithe-core/src/build/outputs.rs +++ b/rust/lithe-core/src/build/outputs.rs @@ -7,7 +7,6 @@ //! tool whose output fits no mapping still needs no host code. use super::decode::{self, join_relative, Format, Workspace}; -use super::integrations; use super::manifest::{ BuildSystemDeclaration, DependenciesSource, DependencyDecoder, DependencyRule, DiagnosticsDeclaration, DocumentDecoder, LinePattern, ModelDecoder, ModelSource, OutputChannel, @@ -15,7 +14,7 @@ use super::manifest::{ }; use super::model::{self, BuildModel, ModelBuilder}; use super::options; -use super::plans::{self, invalid_selection, unavailable}; +use super::plans::{self, invalid_selection, unavailable, unsupported_integration}; use super::select::{self, Node}; use crate::plugins::declarative::Validation; use quick_xml::events::{BytesStart, Event}; @@ -152,9 +151,7 @@ pub(crate) fn read_model( _ => model::map_canonical(&mut builder, decode::document(&text, Format::Json)?)?, } } - Some(ModelSource::HostIntegration) => { - integrations::model(build_system, workspace, root, &mut builder)?; - } + Some(ModelSource::HostIntegration) => return Err(unsupported_integration(build_system)), Some(ModelSource::Provider) => { model::map_canonical(&mut builder, provider_result(result)?.clone())?; } @@ -305,16 +302,6 @@ pub(crate) struct DecodeTestResultsRequest { /// The run's start; earlier report files are ignored. #[serde(default)] pub(crate) not_before_millis: Option, - /// The suite the run selected, if any. - #[serde(default)] - pub(crate) suite: Option, -} - -/// Aggregated results and their summary. -pub(crate) struct TestResults { - pub(crate) cases: Vec, - /// Counts reported by the tool when it prints its own summary. - pub(crate) summary: Option, } #[derive(Debug, Clone, Copy, Default, Serialize)] @@ -396,7 +383,7 @@ pub(crate) fn decode_test_results( }; decode::bounded_text(&request.output)?; let mut coverage = Vec::new(); - let results = match source { + let cases = match source { TestResultsSource::Provider => { let (cases, scopes) = provider_test_cases( request.result.as_ref().ok_or_else(|| { @@ -405,37 +392,26 @@ pub(crate) fn decode_test_results( &root, )?; coverage = scopes; - TestResults { - cases, - summary: None, - } - } - TestResultsSource::JunitXml { reports } => TestResults { - cases: report_cases( - &workspace, - &report_directories(&root, &directory, request)?, - reports, - request.not_before_millis, - |text, base| junit_cases(text, &workspace, base), - ), - summary: None, - }, - TestResultsSource::LitheTestResults { reports } => TestResults { - cases: report_cases( - &workspace, - &report_directories(&root, &directory, request)?, - reports, - request.not_before_millis, - |text, base| canonical_cases(text, &workspace, base), - ), - summary: None, - }, - TestResultsSource::HostIntegration => { - integrations::test_results(build_system, &workspace, &root, &directory, request)? + cases } + TestResultsSource::JunitXml { reports } => report_cases( + &workspace, + &report_directories(&root, &directory, request)?, + reports, + request.not_before_millis, + |text, base| junit_cases(text, &workspace, base), + ), + TestResultsSource::LitheTestResults { reports } => report_cases( + &workspace, + &report_directories(&root, &directory, request)?, + reports, + request.not_before_millis, + |text, base| canonical_cases(text, &workspace, base), + ), + TestResultsSource::HostIntegration => return Err(unsupported_integration(build_system)), }; - let cases = aggregate(results.cases); - let summary = results.summary.unwrap_or_else(|| summary(&cases)); + let cases = aggregate(cases); + let summary = summary(&cases); let mut result = json!({ "tests": cases, "summary": summary, @@ -615,8 +591,8 @@ fn attribute(element: &BytesStart<'_>, name: &[u8]) -> Option { } /// Parses one JUnit XML report: ``/`` with -/// ``, ``, and `` children, as written by Surefire, -/// Gradle, pytest, Jest, Go, and most other runners. +/// ``, ``, and `` children: the de facto report +/// format of pytest, Jest, Go test reporters, and most other runners. fn junit_cases(text: &str, workspace: &Workspace, base: &str) -> Option> { let mut reader = Reader::from_str(text); reader.config_mut().trim_text(true); @@ -1052,15 +1028,7 @@ pub(crate) fn decode_dependencies( CanonicalDependencies::deserialize(provider_result(request.result.as_ref())?), &mut budget, )?, - DependenciesSource::HostIntegration => { - let nodes = integrations::dependencies( - build_system, - &root, - &project, - request.output_file.as_deref(), - )?; - bound_tree(nodes, 0, &mut budget) - } + DependenciesSource::HostIntegration => return Err(unsupported_integration(build_system)), }; Ok(json!({ "project": project, diff --git a/rust/lithe-core/src/build/plans.rs b/rust/lithe-core/src/build/plans.rs index e3eca5bbda..f6ee980da5 100644 --- a/rust/lithe-core/src/build/plans.rs +++ b/rust/lithe-core/src/build/plans.rs @@ -9,7 +9,6 @@ //! instead of an argv plan. use super::decode::{self, join_relative}; -use super::integrations; use super::manifest::{ BuildExecution, BuildSystemDeclaration, DependenciesSource, ExecutableCandidate, ModelSource, OutputChannel, ProviderDeclaration, RunDeclaration, Scope, TaskSource, TestFilter, @@ -46,6 +45,20 @@ pub(crate) fn unavailable(build_system: &BuildSystemDeclaration, what: &str) -> ) } +/// Core provides no host integration any more: the only one moved a +/// built-in tool onto the plugin model, and that tool now ships as a plugin +/// that decodes its own output. A declaration that still names one fails +/// here instead of reaching tool-specific host code. +pub(super) fn unsupported_integration(build_system: &BuildSystemDeclaration) -> PluginRejection { + PluginRejection::new( + "plugin.integration.unsupported", + format!( + "{} names no host integration this host provides.", + build_system.display_name + ), + ) +} + /// A project, target, or task the host selected from the model. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] @@ -157,7 +170,8 @@ pub(crate) struct ProviderTool { /// Absolute path of the executable, after the host applied wrappers, /// environment variables, `PATH`, and the user's override. pub(crate) executable: String, - /// Selected runtime inputs, independent of the backend process's own JDK. + /// Selected runtime inputs, independent of the runtime the backend + /// process itself runs on. #[serde(default)] pub(crate) environment: BTreeMap, } @@ -965,11 +979,7 @@ pub(crate) fn dependency_plan( ), ) } - DependenciesSource::HostIntegration => integrations::dependency_plan( - &context, - project.as_ref(), - request.output_file.as_deref(), - ), + DependenciesSource::HostIntegration => Err(unsupported_integration(build_system)), DependenciesSource::Provider { scopes } => { check_scope(scopes)?; let mut params = provider_hints(request)?; diff --git a/rust/lithe-core/src/build/run_preparation.rs b/rust/lithe-core/src/build/run_preparation.rs index ef6d5ae819..829bffc377 100644 --- a/rust/lithe-core/src/build/run_preparation.rs +++ b/rust/lithe-core/src/build/run_preparation.rs @@ -1,5 +1,5 @@ //! Provider-owned run preparation and validation of portable launch plans. -//! Upstream providers own build/classpath facts; Core only validates selectors, +//! Upstream providers own build and launch facts; Core only validates selectors, //! bounded arguments, executable references, and workspace path containment. use super::decode::{self, Workspace}; diff --git a/rust/lithe-core/src/build/template.rs b/rust/lithe-core/src/build/template.rs index c6eb03d4e6..d665f1ab31 100644 --- a/rust/lithe-core/src/build/template.rs +++ b/rust/lithe-core/src/build/template.rs @@ -56,8 +56,8 @@ impl Conditions { } /// What the request selected. `nestedProjectSelected` means a project other -/// than the one at the build-system root, which tools such as Maven address -/// with a project-list flag. +/// than the one at the build-system root, which some tools address with a +/// project-list flag instead of a working directory. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[allow(clippy::enum_variant_names)] // The names are the manifest's wire format. diff --git a/rust/lithe-core/src/debug/adapters.rs b/rust/lithe-core/src/debug/adapters.rs index 20129e6c0b..fcb12710eb 100644 --- a/rust/lithe-core/src/debug/adapters.rs +++ b/rust/lithe-core/src/debug/adapters.rs @@ -81,9 +81,9 @@ const EXECUTABLE_VARIABLES: &[&str] = &[ /// What a candidate may start with, so a lookup stays beside the user's work. const EXECUTABLE_ROOTS: &[&str] = &["${workspaceFolder}/", "${fileDirectory}/"]; -/// Runtimes a `runSelectedRuntime` launch may name: the tools Run can select -/// a runtime for. -const SELECTED_RUNTIME_TOOLS: &[&str] = &["java", "node", "python"]; +/// Host-known runtimes a `runSelectedRuntime` launch may name below +/// `serverProcess` 4; any other short ID refers to a plugin tool definition. +const SELECTED_RUNTIME_TOOLS: &[&str] = &["node", "python"]; /// Target kinds a selector may match. const TARGET_KINDS: &[&str] = &["connection", "executable", "file", "process", "runTarget"]; diff --git a/rust/lithe-core/src/debug/engine.rs b/rust/lithe-core/src/debug/engine.rs index 0103ed748b..e2ff06836c 100644 --- a/rust/lithe-core/src/debug/engine.rs +++ b/rust/lithe-core/src/debug/engine.rs @@ -67,9 +67,6 @@ struct DebugSession { features: DebugAdapterFeatures, /// Declared filters used when a launch names none. default_stepping_filters: Option, - /// Neither features nor defaults were declared, so the engine keeps - /// recognizing adapters it knew before `debugAdapters` 3 by their ID. - undeclared: bool, debug_request_kind: Option, pending_launch: Option<(String, DebugLaunchConfiguration)>, outbound_frames: Vec>, @@ -133,7 +130,6 @@ pub(crate) fn create_session( .declared .check() .map_err(|(field, message)| invalid_request(message).with_details(field.to_string()))?; - let undeclared = request.declared.is_empty(); let DeclaredAdapterBehavior { features, defaults } = request.declared; let mut sessions = sessions_lock()?; if sessions.contains_key(&request.session_id) { @@ -196,7 +192,6 @@ pub(crate) fn create_session( default_stepping_filters: defaults .and_then(|defaults| defaults.step_filters) .map(|filters| DebugSteppingFilters::from(&filters)), - undeclared, debug_request_kind: None, pending_launch: None, outbound_frames: Vec::new(), @@ -270,7 +265,7 @@ pub(crate) fn stepping_filters( normalize_stepping_filters( request .filters - .unwrap_or_else(|| DebugSteppingFilters::defaults_for_adapter(&request.adapter_id)), + .unwrap_or_else(DebugSteppingFilters::unfiltered), ) } @@ -796,7 +791,6 @@ pub(crate) fn inspect(request: InspectRequest) -> Result Result<(), CoreError> { let request_kind = configuration.request; let mut arguments = configuration.arguments; - let legacy_java = self.undeclared && self.adapter_id == "java"; let filters = normalize_stepping_filters( configuration .stepping_filters .or_else(|| self.default_stepping_filters.clone()) - .unwrap_or_else(|| { - if self.undeclared { - DebugSteppingFilters::defaults_for_adapter(&self.adapter_id) - } else { - DebugSteppingFilters::unfiltered() - } - }), + .unwrap_or_else(DebugSteppingFilters::unfiltered), )?; - let filter_argument = match &self.features.step_filters { - Some(feature) => Some(feature.argument.clone()), - None if legacy_java => Some("stepFilters".to_string()), - None => None, - }; - if let Some(name) = filter_argument { - if !arguments.contains_key(&name) { - arguments.insert(name, step_filter_argument(&filters)); - } - } - if legacy_java && request_kind == DebugRequestKind::Launch { - // A DevTools classloader restart would discard the debugger's hot-replacement target. - let option = super::JAVA_DEBUG_DISABLE_DEVTOOLS_RESTART; - let vm_args = arguments.entry("vmArgs").or_insert_with(|| json!("")); - match vm_args { - Value::String(value) => { - *value = format!("{} {}", value, option).trim().to_owned(); - } - Value::Array(values) => values.push(json!(option)), - _ => return Err(invalid_request("Java vmArgs must be a string or an array.")), + // Only an adapter that declared the argument receives the filters; the + // engine never invents launch arguments for an undeclared adapter. + if let Some(feature) = &self.features.step_filters { + if !arguments.contains_key(&feature.argument) { + arguments.insert(feature.argument.clone(), step_filter_argument(&filters)); } } self.stepping_filters = filters; @@ -2305,7 +2277,7 @@ fn normalize_inspection( }, }), DebugInspectKind::RedefineClasses => { - // Java Debug Server can return DAP success with an application-level error. + // An adapter may return DAP success with an application-level error. if let Some(message) = body .get("errorMessage") .and_then(Value::as_str) @@ -2608,7 +2580,6 @@ fn stack_frame_matches_filters( .class_name_filters .iter() .any(|filter| match filter.as_str() { - "$JDK" => is_jdk_frame(name, source_path, presentation_hint), "$Libraries" => is_library_frame(source_path, presentation_hint, root_path), pattern => class_pattern_matches_frame(pattern, name, source_path), }) @@ -2641,61 +2612,6 @@ fn source_path_matches_pattern(source_path: &str, pattern: &str) -> bool { wildcard_match(&slash_pattern, &source_path) || wildcard_match(&dotted_pattern, &source_path) } -fn is_jdk_frame(name: &str, source_path: Option<&str>, presentation_hint: Option<&str>) -> bool { - if ["com.sun.", "java.", "javax.", "jdk.", "org.omg.", "sun."] - .iter() - .any(|prefix| name.starts_with(prefix)) - { - return true; - } - if presentation_hint == Some("subtle") && source_path.is_none() { - return true; - } - let Some(source_path) = source_path else { - return false; - }; - let source_path = source_path.replace('\\', "/"); - if source_path.contains("/java.base/") - || source_path.contains("/java.desktop/") - || source_path.contains("/java.logging/") - || source_path.contains("/java.management/") - || source_path.contains("/java.naming/") - || source_path.contains("/java.net.http/") - || source_path.contains("/java.sql/") - || source_path.contains("/java.xml/") - || source_path.contains("/jdk.") - { - return true; - } - [ - "java/applet", - "java/awt", - "java/beans", - "java/io", - "java/lang", - "java/math", - "java/net", - "java/nio", - "java/rmi", - "java/security", - "java/sql", - "java/text", - "java/time", - "java/util", - "javax", - "jdk", - "sun", - "com/sun", - "org/omg", - ] - .iter() - .any(|prefix| source_has_path_prefix(&source_path, prefix)) -} - -fn source_has_path_prefix(source_path: &str, prefix: &str) -> bool { - source_path.contains(&format!("/{prefix}/")) || source_path.contains(&format!("/{prefix}.")) -} - fn is_library_frame( source_path: Option<&str>, presentation_hint: Option<&str>, @@ -3300,7 +3216,7 @@ mod tests { #[test] fn stack_frame_reports_adapter_served_source_references() { - let filters = DebugSteppingFilters::defaults_for_adapter("lldb"); + let filters = DebugSteppingFilters::unfiltered(); let body = json!({"stackFrames": [ {"id": 1, "name": "main", "line": 9, "column": 1, "source": {"name": "main.c", "path": "/workspace/main.c"}}, @@ -3332,7 +3248,7 @@ mod tests { let result = normalize_inspection( DebugInspectKind::RedefineClasses, &case["body"], - &DebugSteppingFilters::defaults_for_adapter("java"), + &DebugSteppingFilters::unfiltered(), "/workspace", ); if case["failure"].as_bool() == Some(true) { @@ -3345,8 +3261,25 @@ mod tests { } #[test] - fn hot_replace_requires_java_and_preserves_paused_state() { - for (id, adapter) in [("hcr-java", "java"), ("hcr-other", "python")] { + fn hot_replace_requires_the_declaration_and_preserves_paused_state() { + let hot_swapping: DeclaredAdapterBehavior = serde_json::from_value(json!({ + "features": { + "hotCodeReplace": { + "request": "redefineClasses", + "changedField": "changedClasses", + "errorField": "errorMessage" + } + } + })) + .unwrap(); + for (id, adapter, declared) in [ + ("hcr-declared", "hotswap", hot_swapping), + ("hcr-other", "python", DeclaredAdapterBehavior::default()), + ] { + let declares_hot_replace = declared + .features + .as_ref() + .is_some_and(|features| features.hot_code_replace.is_some()); create_session(CreateSessionRequest { session_id: id.into(), adapter_id: adapter.into(), @@ -3355,7 +3288,7 @@ mod tests { supports_start_debugging_request: false, disabled_capabilities: Vec::new(), parent_session_id: None, - declared: Default::default(), + declared, }) .unwrap(); // The guard always removes the process-free session, including on assertion failure. @@ -3381,12 +3314,8 @@ mod tests { }) .unwrap(); let launch_frame = decode_frame(&launched.outbound_frames[0]); - if adapter == "java" { - assert_eq!( - launch_frame["arguments"]["vmArgs"], - "-Xmx256m -Dspring.devtools.restart.enabled=false" - ); - } + // Launch arguments pass through untouched for every adapter. + assert_eq!(launch_frame["arguments"]["vmArgs"], "-Xmx256m"); receive_messages( id, vec![response_message( @@ -3406,7 +3335,7 @@ mod tests { })) .unwrap(); let update = inspect(request); - if adapter != "java" { + if !declares_hot_replace { assert!(update.is_err()); continue; } @@ -3474,7 +3403,7 @@ mod tests { stack_frames: vec![DebugStackFrame { id: 7, name: "example.Main.run".to_string(), - source_path: Some("/workspace/Main.java".to_string()), + source_path: Some("/workspace/Main.c".to_string()), source_reference: None, line: 12, column: 1, @@ -3514,7 +3443,7 @@ mod tests { let session_id = format!("debug-disconnect-{request_name}"); create_session(CreateSessionRequest { session_id: session_id.clone(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -3640,26 +3569,22 @@ mod tests { } #[test] - fn java_stepping_filters_are_normalized_projected_and_mark_stack_frames() { + fn stepping_filters_are_normalized_projected_and_mark_stack_frames() { + // Without a declaration there are no built-in defaults for any adapter. let defaults = stepping_filters(DebugSteppingFiltersRequest { - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), filters: None, }) .unwrap(); - assert!(defaults.class_name_filters.contains(&"$JDK".to_string())); - assert!(defaults - .class_name_filters - .contains(&"$Libraries".to_string())); - assert!(defaults.skip_synthetics); - assert!(!defaults.skip_constructors); + assert_eq!(defaults, DebugSteppingFilters::unfiltered()); let filters = stepping_filters(DebugSteppingFiltersRequest { - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), filters: Some(DebugSteppingFilters { class_name_filters: vec![ - " org.mockito.* ".to_string(), - "$JDK".to_string(), - "org.mockito.*".to_string(), + " org.mocking.* ".to_string(), + "lib.core.*".to_string(), + "org.mocking.*".to_string(), String::new(), ], skip_synthetics: true, @@ -3669,10 +3594,10 @@ mod tests { }), }) .unwrap(); - assert_eq!(filters.class_name_filters, ["$JDK", "org.mockito.*"]); + assert_eq!(filters.class_name_filters, ["lib.core.*", "org.mocking.*"]); let multiline_error = stepping_filters(DebugSteppingFiltersRequest { - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), filters: Some(DebugSteppingFilters { class_name_filters: vec!["example.Valid\nexample.Invalid".to_string()], skip_synthetics: false, @@ -3685,7 +3610,7 @@ mod tests { assert!(matches!(multiline_error.code, ErrorCode::InvalidRequest)); let excessive_filter_error = stepping_filters(DebugSteppingFiltersRequest { - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), filters: Some(DebugSteppingFilters { class_name_filters: (0..257) .map(|index| format!("example.Type{index}")) @@ -3702,16 +3627,19 @@ mod tests { ErrorCode::InvalidRequest )); - let session_id = "debug-java-stepping-filters"; + let session_id = "debug-stepping-filters"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, disabled_capabilities: Vec::new(), parent_session_id: None, - declared: Default::default(), + declared: serde_json::from_value(json!({ + "features": {"stepFilters": {"argument": "stepFilters"}} + })) + .unwrap(), }) .unwrap(); launch(LaunchRequest { @@ -3733,7 +3661,7 @@ mod tests { assert_eq!(launch_request["command"], "launch"); assert_eq!( launch_request["arguments"]["stepFilters"]["skipClasses"], - json!(["$JDK", "org.mockito.*"]) + json!(["lib.core.*", "org.mocking.*"]) ); assert_eq!( launch_request["arguments"]["stepFilters"]["skipConstructors"], @@ -3781,9 +3709,9 @@ mod tests { json!({"stackFrames": [ { "id": 7, - "name": "Method.invoke(Object,Object[])", + "name": "lib.core.reflect.Method.invoke(Object,Object[])", "source": { - "path": "jdt://contents/java.base/java/lang/reflect/Method.class" + "path": "/deps/lib/core/reflect/Method.class" }, "line": 1, "column": 1 @@ -3792,7 +3720,7 @@ mod tests { "id": 8, "name": "MockMethodInterceptor.intercept(Object,Method,Object[],Invoker)", "source": { - "path": "jdt://contents/mockito-core/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.class" + "path": "/deps/mocking-core/org/mocking/internal/MockMethodInterceptor.class" }, "line": 1, "column": 1 @@ -3800,7 +3728,7 @@ mod tests { { "id": 9, "name": "example.LoginService.authenticate", - "source": {"path": "/workspace/LoginService.java"}, + "source": {"path": "/workspace/LoginService.c"}, "line": 24, "column": 5 } @@ -3827,14 +3755,14 @@ mod tests { }; assert!(stack_frame_matches_filters( "Dependency.call()", - Some("/dependencies/example/Dependency.java"), + Some("/dependencies/example/Dependency.c"), None, &library_filters, "/workspace" )); assert!(!stack_frame_matches_filters( "LoginService.authenticate()", - Some("/workspace/LoginService.java"), + Some("/workspace/LoginService.c"), None, &library_filters, "/workspace" @@ -3850,7 +3778,7 @@ mod tests { let session_id = "debug-engine-flow"; let created = create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -3879,7 +3807,7 @@ mod tests { assert!(queued.outbound_frames.is_empty()); set_breakpoints(SetBreakpointsRequest { session_id: session_id.to_string(), - source_path: "/workspace/src/Main.java".to_string(), + source_path: "/workspace/src/Main.c".to_string(), breakpoints: vec![ SourceBreakpoint { line: 12, @@ -4142,7 +4070,7 @@ mod tests { let source = fixture["sourcePath"].as_str().unwrap(); create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -4511,7 +4439,7 @@ mod tests { let session_id = "debug-data-breakpoint"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -4636,7 +4564,7 @@ mod tests { let session_id = "debug-set-variable"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -4768,7 +4696,7 @@ mod tests { let session_id = "debug-launch-rejected-detail"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -4830,7 +4758,7 @@ mod tests { let session_id = "debug-cancel-operation"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -4962,7 +4890,7 @@ mod tests { let session_id = "debug-advanced-control"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5066,7 +4994,7 @@ mod tests { let session_id = "debug-targeted-control"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5193,7 +5121,7 @@ mod tests { count: None, expression: None, context: None, - source_path: Some("/workspace/src/Main.java".to_string()), + source_path: Some("/workspace/src/Main.c".to_string()), line: Some(20), column: Some(5), memory_reference: None, @@ -5207,7 +5135,7 @@ mod tests { assert_eq!(request["command"], "gotoTargets"); assert_eq!( request["arguments"]["source"]["path"], - "/workspace/src/Main.java" + "/workspace/src/Main.c" ); assert_eq!(request["arguments"]["line"], 20); let goto_targets = receive_messages( @@ -5215,7 +5143,7 @@ mod tests { vec![response_message( 5, "gotoTargets", - json!({"targets": [{"id": 31, "label": "Main.java:20", "line": 20}]}), + json!({"targets": [{"id": 31, "label": "main.c:20", "line": 20}]}), )], ); assert!(goto_targets.events.iter().any(|event| matches!( @@ -5342,7 +5270,7 @@ mod tests { let session_id = "debug-exception-info"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5455,7 +5383,7 @@ mod tests { let session_id = "debug-variable-paging"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5555,7 +5483,7 @@ mod tests { let session_id = "debug-exception-info-unsupported"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5629,7 +5557,7 @@ mod tests { let session_id = "debug-run-in-terminal"; let created = create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: true, supports_start_debugging_request: false, @@ -5713,7 +5641,7 @@ mod tests { let session_id = "debug-run-in-terminal-invalid"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: true, supports_start_debugging_request: false, @@ -5750,7 +5678,7 @@ mod tests { let session_id = "debug-server-request"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5794,7 +5722,7 @@ mod tests { let session_id = "debug-capability-snapshot"; create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5853,7 +5781,7 @@ mod tests { fn child_request(session_id: &str, parent: Option<&str>) -> CreateSessionRequest { CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -5954,7 +5882,7 @@ mod tests { "stackTrace", json!({"totalFrames": 3, "stackFrames": [ {"id": 1, "name": "main", "line": 4, "column": 2, - "source": {"path": "/workspace/src/Main.java"}}, + "source": {"path": "/workspace/src/Main.c"}}, {"id": 2, "name": "decompiled", "line": 9, "source": {"name": "Lib.class", "sourceReference": 77}}, {"id": 3, "name": "jit", "line": 5, @@ -5978,7 +5906,7 @@ mod tests { assert_eq!(payload.thread_id, 11); assert!(matches!( &payload.frames[0].source, - Some(Source::Workspace(source)) if source.path == "src/Main.java" + Some(Source::Workspace(source)) if source.path == "src/Main.c" )); assert!(matches!( &payload.frames[1].source, @@ -5996,7 +5924,7 @@ mod tests { .unwrap(); } - /// Creates a paused Java-style session so reference-bound inspections can be issued. + /// Creates a paused session so reference-bound inspections can be issued. fn paused_session(session_id: &str) { paused_session_with_capabilities(session_id, json!({})); } @@ -6005,7 +5933,7 @@ mod tests { fn paused_session_with_capabilities(session_id: &str, capabilities: Value) { create_session(CreateSessionRequest { session_id: session_id.to_string(), - adapter_id: "java".to_string(), + adapter_id: "lldb".to_string(), root_path: "/workspace".to_string(), supports_run_in_terminal_request: false, supports_start_debugging_request: false, @@ -6433,7 +6361,7 @@ mod tests { #[test] fn sourceless_frames_keep_the_instruction_pointer_without_a_fake_line() { - let filters = DebugSteppingFilters::defaults_for_adapter("lldb"); + let filters = DebugSteppingFilters::unfiltered(); let body = json!({"stackFrames": [ {"id": 1, "name": "main", "line": 9, "column": 1, "instructionPointerReference": "0x100003f50", @@ -6467,7 +6395,7 @@ mod tests { #[test] fn registers_scope_keeps_its_presentation_hint() { - let filters = DebugSteppingFilters::defaults_for_adapter("lldb"); + let filters = DebugSteppingFilters::unfiltered(); let body = json!({"scopes": [ {"name": "Locals", "variablesReference": 3}, {"name": "Registers", "variablesReference": 4, @@ -7063,28 +6991,6 @@ mod tests { ); } - #[test] - fn a_declared_adapter_is_not_recognized_by_its_id() { - // Declaring behavior replaces the ID-based special cases kept for - // plugins that predate `debugAdapters` 3. - let session_id = "debug-declared-not-by-id"; - let _guard = SessionGuard(session_id); - let declared = serde_json::from_value(json!({ - "features": {"stepFilters": {"argument": "skipFilters"}} - })) - .unwrap(); - let launched = launch_session(session_id, "java", declared, json!({})); - - assert!(launched["arguments"].get("stepFilters").is_none()); - assert!(launched["arguments"].get("vmArgs").is_none()); - assert_eq!( - launched["arguments"]["skipFilters"]["skipClasses"], - json!([]) - ); - pause_session(session_id, &launched); - assert!(inspect(redefine_request(session_id, "apply")).is_err()); - } - #[test] fn invalid_declarations_are_refused_when_the_session_is_created() { let declared = serde_json::from_value(json!({ diff --git a/rust/lithe-core/src/debug/java_test.rs b/rust/lithe-core/src/debug/java_test.rs deleted file mode 100644 index 9723ab56a8..0000000000 --- a/rust/lithe-core/src/debug/java_test.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Deterministic Java test launch configuration shared by native products. - -use std::collections::HashSet; - -use serde::Deserialize; -use serde_json::{Map, Value}; - -use crate::protocol::{CoreError, ErrorCode}; - -use super::{DebugLaunchConfiguration, DebugRequestKind}; - -#[derive(Debug, Clone, Copy, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Java test framework whose runner arguments must be projected into DAP. -pub enum JavaTestFramework { - Junit, - Testng, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Platform-observed JDT LS launch metadata plus one loopback result port. -pub struct JavaTestLaunchRequest { - pub name: String, - pub framework: JavaTestFramework, - pub working_directory: String, - pub main_class: String, - #[serde(default)] - pub project_name: Option, - #[serde(default)] - pub class_paths: Vec, - #[serde(default)] - pub module_paths: Vec, - #[serde(default)] - pub vm_arguments: Vec, - #[serde(default)] - pub program_arguments: Vec, - pub result_port: u16, - #[serde(default)] - pub testng_runner_path: Option, - #[serde(default)] - pub testng_test_names: Vec, -} - -/// Creates the provider arguments consumed by Java Debug Server. -pub fn java_test_launch( - request: JavaTestLaunchRequest, -) -> Result { - let name = required(request.name, "Java test launch name is required.")?; - let working_directory = required( - request.working_directory, - "Java test working directory is required.", - )?; - let main_class = required(request.main_class, "Java test main class is required.")?; - if request.result_port == 0 { - return Err(invalid_request( - "Java test result port must be between 1 and 65535.", - )); - } - - let mut class_paths = non_empty_unique(request.class_paths); - let module_paths = non_empty_unique(request.module_paths); - let vm_arguments = non_empty(request.vm_arguments); - let mut arguments = Map::new(); - arguments.insert("mainClass".to_string(), Value::String(main_class)); - arguments.insert("cwd".to_string(), Value::String(working_directory)); - arguments.insert( - "console".to_string(), - Value::String("integratedTerminal".to_string()), - ); - if let Some(project_name) = optional_non_empty(request.project_name) { - arguments.insert("projectName".to_string(), Value::String(project_name)); - } - - let program_arguments = match request.framework { - JavaTestFramework::Junit => junit_arguments(request.program_arguments, request.result_port), - JavaTestFramework::Testng => { - let runner_path = required( - request.testng_runner_path.unwrap_or_default(), - "The Java TestNG runner is unavailable.", - )?; - if !class_paths.iter().any(|path| path == &runner_path) { - class_paths.push(runner_path); - } - let test_names = non_empty_unique(request.testng_test_names); - if test_names.is_empty() { - return Err(invalid_request( - "At least one TestNG test method is required.", - )); - } - std::iter::once(request.result_port.to_string()) - .chain(std::iter::once("testng".to_string())) - .chain(test_names) - .collect() - } - }; - - insert_string_array(&mut arguments, "classPaths", class_paths); - insert_string_array(&mut arguments, "modulePaths", module_paths); - insert_java_debug_arguments(&mut arguments, "args", program_arguments); - insert_java_debug_arguments(&mut arguments, "vmArgs", vm_arguments); - - Ok(DebugLaunchConfiguration { - name, - request: DebugRequestKind::Launch, - arguments, - stepping_filters: None, - }) -} - -fn junit_arguments(arguments: Vec, result_port: u16) -> Vec { - let mut arguments = arguments; - let port = result_port.to_string(); - if let Some(index) = arguments.iter().rposition(|value| value == "-port") { - if index + 1 < arguments.len() { - arguments[index + 1] = port; - return arguments; - } - } - arguments.push("-port".to_string()); - arguments.push(port); - arguments -} - -fn required(value: String, message: &str) -> Result { - let value = value.trim().to_string(); - if value.is_empty() { - Err(invalid_request(message)) - } else { - Ok(value) - } -} - -fn optional_non_empty(value: Option) -> Option { - value.and_then(|value| { - let value = value.trim().to_string(); - (!value.is_empty()).then_some(value) - }) -} - -fn non_empty(values: Vec) -> Vec { - values - .into_iter() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - .collect() -} - -fn non_empty_unique(values: Vec) -> Vec { - let mut seen = HashSet::new(); - non_empty(values) - .into_iter() - .filter(|value| seen.insert(value.clone())) - .collect() -} - -fn insert_string_array(arguments: &mut Map, key: &str, values: Vec) { - if values.is_empty() { - return; - } - arguments.insert( - key.to_string(), - Value::Array(values.into_iter().map(Value::String).collect()), - ); -} - -fn insert_java_debug_arguments(arguments: &mut Map, key: &str, values: Vec) { - let value = java_debug_argument_string(values); - if !value.is_empty() { - arguments.insert(key.to_string(), Value::String(value)); - } -} - -fn java_debug_argument_string(values: Vec) -> String { - // Java Test exposes arrays to VS Code, but Java Debug Server's DAP model - // accepts one command-line string. Mirror the upstream extension's - // serialization so the adapter can reconstruct spaces, quotes, and paths. - non_empty(values) - .into_iter() - .map(|value| { - if value - .chars() - .any(|character| character == '"' || character.is_whitespace()) - { - let escaped = value.chars().fold(String::new(), |mut result, character| { - if matches!(character, '"' | '\\') { - result.push('\\'); - } - result.push(character); - result - }); - format!("\"{escaped}\"") - } else { - value - } - }) - .collect::>() - .join(" ") -} - -fn invalid_request(message: &str) -> CoreError { - CoreError::new(ErrorCode::InvalidRequest, message) -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn junit_launch_replaces_the_server_placeholder_port() { - let configuration = java_test_launch(JavaTestLaunchRequest { - name: "UserServiceTest".to_string(), - framework: JavaTestFramework::Junit, - working_directory: "/workspace".to_string(), - main_class: "org.eclipse.jdt.internal.junit.runner.RemoteTestRunner".to_string(), - project_name: Some("service".to_string()), - class_paths: vec!["/workspace/classes".to_string()], - module_paths: Vec::new(), - vm_arguments: vec!["--enable-preview".to_string()], - program_arguments: vec![ - "-version".to_string(), - "3".to_string(), - "-port".to_string(), - "-1".to_string(), - ], - result_port: 43127, - testng_runner_path: None, - testng_test_names: Vec::new(), - }) - .expect("JUnit launch should resolve"); - - assert_eq!( - configuration.arguments["args"], - json!("-version 3 -port 43127") - ); - assert_eq!( - configuration.arguments["classPaths"], - json!(["/workspace/classes"]) - ); - assert_eq!(configuration.arguments["vmArgs"], json!("--enable-preview")); - } - - #[test] - fn testng_launch_appends_the_packaged_runner_once() { - let configuration = java_test_launch(JavaTestLaunchRequest { - name: "UserServiceTest".to_string(), - framework: JavaTestFramework::Testng, - working_directory: "/workspace".to_string(), - main_class: "com.microsoft.java.test.runner.Launcher".to_string(), - project_name: Some("service".to_string()), - class_paths: vec![ - "/workspace/classes".to_string(), - "/lithe/java-test-runner.jar".to_string(), - ], - module_paths: Vec::new(), - vm_arguments: Vec::new(), - program_arguments: Vec::new(), - result_port: 43128, - testng_runner_path: Some("/lithe/java-test-runner.jar".to_string()), - testng_test_names: vec![ - "example.UserServiceTest#logsIn".to_string(), - "example.UserServiceTest#logsIn".to_string(), - ], - }) - .expect("TestNG launch should resolve"); - - assert_eq!( - configuration.arguments["classPaths"], - json!(["/workspace/classes", "/lithe/java-test-runner.jar"]) - ); - assert_eq!( - configuration.arguments["args"], - json!("43128 testng example.UserServiceTest#logsIn") - ); - } - - #[test] - fn java_debug_arguments_match_the_adapter_command_line_contract() { - assert_eq!( - java_debug_argument_string(vec![ - "-Dlabel=hello world".to_string(), - "say\"hello".to_string(), - r"C:\plain".to_string(), - r"C:\Program Files\Java".to_string(), - ]), - r#""-Dlabel=hello world" "say\"hello" C:\plain "C:\\Program Files\\Java""# - ); - } -} diff --git a/rust/lithe-core/src/debug/mod.rs b/rust/lithe-core/src/debug/mod.rs index 920f78b01c..eb543db9cf 100644 --- a/rust/lithe-core/src/debug/mod.rs +++ b/rust/lithe-core/src/debug/mod.rs @@ -7,7 +7,6 @@ mod capabilities; mod disassembly_paging; mod endpoint; mod engine; -mod java_test; mod projection_v2; mod protocol; mod shortcut; @@ -20,12 +19,7 @@ pub(crate) use breakpoint_relocation::*; pub(crate) use disassembly_paging::{plan_disassembly_window, reduce_disassembly_page}; pub(crate) use endpoint::*; pub(crate) use engine::*; -pub(crate) use java_test::*; pub(crate) use shortcut::*; pub(crate) use transport_lifecycle::*; pub(crate) use types::*; pub(crate) use variable_paging::{plan_variable_page, reduce_variable_page}; - -/// Prevents DevTools from restarting the application while a debugger replaces classes. -pub(crate) const JAVA_DEBUG_DISABLE_DEVTOOLS_RESTART: &str = - "-Dspring.devtools.restart.enabled=false"; diff --git a/rust/lithe-core/src/debug/types.rs b/rust/lithe-core/src/debug/types.rs index 09d1bd1399..ac47f1dc60 100644 --- a/rust/lithe-core/src/debug/types.rs +++ b/rust/lithe-core/src/debug/types.rs @@ -133,12 +133,6 @@ fn is_declared_name(value: &str) -> bool { } impl DeclaredAdapterBehavior { - /// Whether the adapter declared nothing, so the engine keeps the - /// behaviour it had before `debugAdapters` 3. - pub(crate) fn is_empty(&self) -> bool { - self.features.is_none() && self.defaults.is_none() - } - /// Checks names and filters; an error names the declaration field and /// what is wrong with it. pub(crate) fn check(&self) -> Result<(), (&'static str, &'static str)> { @@ -249,7 +243,7 @@ pub struct DebugLaunchConfiguration { #[serde(rename_all = "camelCase")] /// Portable class and method filters used for stepping and stack-frame presentation. pub struct DebugSteppingFilters { - /// Adapter-neutral class-name patterns; Java also accepts `$JDK` and `$Libraries`. + /// Adapter-neutral class-name patterns; `$Libraries` matches frames outside the workspace. #[serde(default)] pub class_name_filters: Vec, /// Whether compiler-generated methods should be skipped. @@ -267,14 +261,6 @@ pub struct DebugSteppingFilters { } impl DebugSteppingFilters { - pub(crate) fn defaults_for_adapter(adapter_id: &str) -> Self { - if adapter_id == "java" { - Self::default() - } else { - Self::unfiltered() - } - } - pub(crate) fn unfiltered() -> Self { Self { class_name_filters: Vec::new(), @@ -287,48 +273,17 @@ impl DebugSteppingFilters { } impl Default for DebugSteppingFilters { + /// The Core has no adapter-specific defaults; plugins declare theirs in `debugAdapters`. fn default() -> Self { - Self { - class_name_filters: default_java_class_name_filters(), - skip_synthetics: true, - skip_static_initializers: true, - // IDEA leaves constructor skipping off by default because application - // initialization is often meaningful user code. - skip_constructors: false, - hide_filtered_stack_frames: true, - } + Self::unfiltered() } } -fn default_java_class_name_filters() -> Vec { - [ - "$JDK", - "$Libraries", - "com.ibm.ws.*", - "com.springsource.loaded.*", - "com.sun.proxy.*", - "javassist.*", - "jdk.proxy*.*", - "junit.*", - "net.bytebuddy.*", - "net.sf.cglib.*", - "org.apache.webbeans.*", - "org.junit.*", - "org.mockito.*", - "org.springframework.aop.framework.*", - "org.springframework.cglib.*", - "org.springsource.loaded.*", - ] - .into_iter() - .map(str::to_string) - .collect() -} - #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] /// Returns an adapter's defaults or normalizes a native client's stepping policy. pub struct DebugSteppingFiltersRequest { - /// Stable adapter identifier, such as `java`. + /// Stable adapter identifier, such as `lldb`. pub adapter_id: String, /// Optional client override; omission requests the adapter defaults. #[serde(default)] @@ -594,7 +549,7 @@ pub enum DebugInspectKind { GotoTargets, /// Debug Console completion proposals for the text typed so far. Completions, - /// Java Debug Server hot replacement; mutates classes in the debuggee. + /// Hot code replacement declared by the adapter; mutates code in the debuggee. RedefineClasses, /// Machine instructions around a memory reference, for the disassembly view. Disassemble, @@ -907,7 +862,7 @@ pub enum DebugOperationFailureCode { )] /// Typed terminal data for one caller-owned debug operation. pub enum DebugOperationResult { - /// Classes actually replaced by Java Debug Server (empty means no changes). + /// Classes the adapter actually replaced (empty means no changes). RedefineClasses { changed_classes: Vec, }, diff --git a/rust/lithe-core/src/diagnostics/catalog.rs b/rust/lithe-core/src/diagnostics/catalog.rs index f81486dae8..3e7fa6962b 100644 --- a/rust/lithe-core/src/diagnostics/catalog.rs +++ b/rust/lithe-core/src/diagnostics/catalog.rs @@ -206,23 +206,23 @@ mod tests { fn catalog_lookup_and_span_contract() { assert!(EVENTS.windows(2).all(|pair| pair[0].id < pair[1].id)); assert!(event_by_id("not.an.event").is_none()); - let event = event_by_id("lsp.build.execution.failed").unwrap(); - assert_eq!(event.channel, "lsp/{server}"); + let event = event_by_id("editor.sync.freeze.failed").unwrap(); + assert_eq!(event.channel, "editor"); assert_eq!(event.span, Some(SpanPhase::Failed)); let fields = BTreeMap::from([ - ("server".into(), json!("java")), - ("waiters".into(), json!(2)), - ("outcome".into(), json!("builder_failed")), + ("document".into(), json!("document-1")), + ("revision".into(), json!(2)), + ("status".into(), json!("mismatch")), ("duration_ms".into(), json!(311)), - ("error".into(), json!("build failed")), + ("error".into(), json!("freeze failed")), ("error_code".into(), json!(128)), ("error_domain".into(), json!("core")), ]); assert_eq!(validate_fields(event.id, &fields), Ok(())); for (key, value) in [ ("duration_ms", json!(-1)), - ("server", json!("../bad")), - ("outcome", json!("fetch --token secret")), + ("document", json!("../bad")), + ("status", json!("fetch --token secret")), ] { let mut invalid = fields.clone(); invalid.insert(key.into(), value); @@ -248,7 +248,7 @@ mod tests { #[test] fn catalog_text_and_optional_error_are_bounded() { let mut fields = BTreeMap::from([ - ("server".into(), json!("java")), + ("server".into(), json!("tool-a")), ("diagnostic".into(), json!("upstream diagnostic")), ]); assert!(validate_fields("lsp.stderr.received", &fields).is_ok()); @@ -263,7 +263,7 @@ mod tests { assert!(validate_fields("remote.upload.abort_failed", &fields).is_ok()); let fields = BTreeMap::from([ ("plugin".into(), json!("io.example")), - ("language".into(), json!("java")), + ("language".into(), json!("toml")), ("error".into(), json!("failed")), ]); assert_eq!( diff --git a/rust/lithe-core/src/diagnostics/catalog_generated.rs b/rust/lithe-core/src/diagnostics/catalog_generated.rs index 15ec4cd1e6..6ec904b85e 100644 --- a/rust/lithe-core/src/diagnostics/catalog_generated.rs +++ b/rust/lithe-core/src/diagnostics/catalog_generated.rs @@ -590,7 +590,7 @@ pub static EVENTS: &[EventMetadata] = &[ fields: &[ FieldMetadata { name: "count", field_type: FieldType::Int, required: true, description: "Number of failed storage removals summarized by this cleanup operation", reason: None }, FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "First filesystem failure category observed while removing owned temporary or history files", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Storage cleanup owner, e.g. snapshot-rollback, history-pruning, or jdt-settings", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Storage cleanup owner, e.g. snapshot-rollback or history-pruning", reason: None }, ], span: None, rate: 60, @@ -920,7 +920,7 @@ pub static EVENTS: &[EventMetadata] = &[ message: "File icon content inspection failed", fields: &[ FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Underlying failure at this operation boundary, preserving stable domain and code", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "File icon inspection kind, java or generic", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "File icon inspection kind, e.g. generic", reason: None }, ], span: None, rate: 30, @@ -1129,76 +1129,6 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "Lithe", }, - EventMetadata { - id: "lsp.build.execution.failed", - channel: "lsp/{server}", - level: LogLevel::Error, - message: "Language service project build for server {server} failed", - fields: &[ - FieldMetadata { name: "builder_failed_earlier", field_type: FieldType::Bool, required: false, description: "Whether an earlier builder failure was observed before this build completed", reason: None }, - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Monotonic time from lsp.build.execution.started to lsp.build.execution.failed, encoded in milliseconds", reason: None }, - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure that ended the lsp.build.execution operation, retaining its error code and domain without unredacted private details", reason: None }, - FieldMetadata { name: "marker_scope", field_type: FieldType::Token, required: false, description: "Diagnostic marker scope reported by the completed Java build", reason: None }, - FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "Project build completion category reported by the build reducer", reason: None }, - FieldMetadata { name: "recovery", field_type: FieldType::Bool, required: false, description: "Whether the completed Java build report represents a recovery attempt", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id that owns the project build", reason: None }, - FieldMetadata { name: "waited", field_type: FieldType::Duration, required: false, description: "Time spent waiting for build dispatch, encoded in milliseconds", reason: None }, - FieldMetadata { name: "waiters", field_type: FieldType::Int, required: true, description: "Number of callers waiting for the shared Java project build result", reason: None }, - ], - span: Some(SpanPhase::Failed), - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.build.execution.finished", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Language service project build for server {server} finished", - fields: &[ - FieldMetadata { name: "builder_failed_earlier", field_type: FieldType::Bool, required: false, description: "Whether an earlier builder failure was observed before this build completed", reason: None }, - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Monotonic time from lsp.build.execution.started to lsp.build.execution.finished, encoded in milliseconds", reason: None }, - FieldMetadata { name: "marker_scope", field_type: FieldType::Token, required: false, description: "Diagnostic marker scope reported by the completed Java build", reason: None }, - FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "Project build completion category reported by the build reducer", reason: None }, - FieldMetadata { name: "recovery", field_type: FieldType::Bool, required: false, description: "Whether the completed Java build report represents a recovery attempt", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id that owns the project build", reason: None }, - FieldMetadata { name: "waited", field_type: FieldType::Duration, required: false, description: "Time spent waiting for build dispatch, encoded in milliseconds", reason: None }, - FieldMetadata { name: "waiters", field_type: FieldType::Int, required: true, description: "Number of callers waiting for the shared Java project build result", reason: None }, - ], - span: Some(SpanPhase::Finished), - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.build.execution.started", - channel: "lsp/{server}", - level: LogLevel::Debug, - message: "Language service project build for server {server} started", - fields: &[ - FieldMetadata { name: "builder_failed_earlier", field_type: FieldType::Bool, required: false, description: "Whether an earlier builder failure was observed before this build completed", reason: None }, - FieldMetadata { name: "marker_scope", field_type: FieldType::Token, required: false, description: "Diagnostic marker scope reported by the completed Java build", reason: None }, - FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "Project build completion category reported by the build reducer", reason: None }, - FieldMetadata { name: "recovery", field_type: FieldType::Bool, required: false, description: "Whether the completed Java build report represents a recovery attempt", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id that owns the project build", reason: None }, - FieldMetadata { name: "waited", field_type: FieldType::Duration, required: false, description: "Time spent waiting for build dispatch, encoded in milliseconds", reason: None }, - FieldMetadata { name: "waiters", field_type: FieldType::Int, required: true, description: "Number of callers waiting for the shared Java project build result", reason: None }, - ], - span: Some(SpanPhase::Started), - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.build.waiting", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Project build waiting for server {server}: {reason}", - fields: &[ - FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Build dispatch blocker returned by the Java build reducer", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id that owns the queued build", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, EventMetadata { id: "lsp.cache.cleaned", channel: "lsp/{server}", @@ -1212,32 +1142,6 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "LanguageToolingSessionManager", }, - EventMetadata { - id: "lsp.configuration.cleaned", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Unused server configuration areas removed for server {server}", - fields: &[ - FieldMetadata { name: "removed", field_type: FieldType::Int, required: true, description: "Number of unused language server configuration areas removed", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose configuration areas were pruned", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.configuration.cleanup_failed", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Server configuration cleanup failed for server {server}", - fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem error raised while removing unused language server configuration areas", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose configuration cleanup failed", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, EventMetadata { id: "lsp.host.operation_failed", channel: "lsp/{server}", @@ -1252,151 +1156,6 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 120, owner: "LitheLanguageIntelligenceModule", }, - EventMetadata { - id: "lsp.maven.application_started", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven profile application started for server {server}", - fields: &[ - FieldMetadata { name: "projects", field_type: FieldType::Int, required: false, description: "Number of Java projects targeted by this Maven profile application, when known", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id applying the Maven profiles", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.applied", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven profiles applied for server {server}", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that successfully applied the Maven profiles", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.cancelled", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven profile application cancelled for server {server}", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose Maven profile application was cancelled", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.configuration_updated", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven configuration updated for server {server}", - fields: &[ - FieldMetadata { name: "profiles_updating", field_type: FieldType::Bool, required: true, description: "Whether a Maven profile application remains in progress after the update", reason: None }, - FieldMetadata { name: "projects_reloaded", field_type: FieldType::Bool, required: true, description: "Whether updating the Maven configuration reloaded Java projects", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that received the Maven configuration", reason: None }, - FieldMetadata { name: "settings_changed", field_type: FieldType::Bool, required: true, description: "Whether settings changed after the Java language service was initialized", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.partially_applied", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Maven profiles partially applied for server {server}", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose Maven profiles were only partially applied", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.project_failed", - channel: "lsp/{server}", - level: LogLevel::Error, - message: "Maven profile project {project} update failed for server {server} with outcome {outcome}", - fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Error reported for this Maven project update or synthesized for its timeout", reason: None }, - FieldMetadata { name: "outcome", field_type: FieldType::Token, required: true, description: "Maven project update result, e.g. failed or timed-out", reason: None }, - FieldMetadata { name: "project", field_type: FieldType::Path, required: true, description: "Project directory derived from the Maven update project URI, redacted before persistence", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id updating this Maven project", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.project_finished", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven profile project {project} update finished for server {server} with outcome {outcome}", - fields: &[ - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: false, description: "Elapsed time for this Maven project update in milliseconds, when available", reason: None }, - FieldMetadata { name: "outcome", field_type: FieldType::Token, required: true, description: "Maven project update result reported by the profile task reducer", reason: None }, - FieldMetadata { name: "project", field_type: FieldType::Path, required: true, description: "Project directory derived from the Maven update project URI, redacted before persistence", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id updating this Maven project", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.settings_forwarded", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Maven settings forwarded unchanged for server {server}: {reason}", - fields: &[ - FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Maven settings warning category explaining why the settings were forwarded unchanged", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id receiving the unchanged Maven settings", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.start_failed", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Pending Maven profile update failed to start for server {server}", - fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Error returned when starting the pending Maven profile update", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that could not dispatch the pending Maven update", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.task_updated", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Maven profile task state updated", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated server identity owning the Maven profile task", reason: None }, - FieldMetadata { name: "state", field_type: FieldType::Token, required: true, description: "Closed Maven profile task status supplied by the build coordinator", reason: None }, - ], - span: None, - rate: 60, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.maven.timed_out", - channel: "lsp/{server}", - level: LogLevel::Error, - message: "Maven profile application timed out for server {server}", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose Maven profile application exceeded its deadline", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, EventMetadata { id: "lsp.message.detail.logged", channel: "lsp/{server}", @@ -1509,69 +1268,6 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 120, owner: "lithe-core", }, - EventMetadata { - id: "lsp.navigation.cache_hit", - channel: "lsp/{server}", - level: LogLevel::Debug, - message: "Navigation markers served from cache for server {server} for {document}", - fields: &[ - FieldMetadata { name: "document", field_type: FieldType::Path, required: true, description: "Document path derived from the navigation request URI, redacted before persistence", reason: None }, - FieldMetadata { name: "document_version", field_type: FieldType::Int, required: true, description: "Document version used as part of the navigation marker cache key", reason: None }, - FieldMetadata { name: "markers", field_type: FieldType::Int, required: true, description: "Number of navigation markers returned from the cache", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id serving cached navigation markers", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.navigation.limited", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Navigation marker batch limited for server {server} for {document}", - fields: &[ - FieldMetadata { name: "document", field_type: FieldType::Path, required: true, description: "Document path for the limited navigation request, redacted before persistence", reason: None }, - FieldMetadata { name: "limit", field_type: FieldType::Int, required: true, description: "Maximum navigation tasks permitted by MAX_JAVA_NAVIGATION_TASKS", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that limited the navigation batch", reason: None }, - FieldMetadata { name: "tasks", field_type: FieldType::Int, required: true, description: "Number of navigation tasks requested before applying the batch limit", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.navigation.marker_failed", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Navigation marker verification failed for server {server} for {document}", - fields: &[ - FieldMetadata { name: "document", field_type: FieldType::Path, required: true, description: "Document path for the marker resolution request, redacted before persistence", reason: None }, - FieldMetadata { name: "document_version", field_type: FieldType::Int, required: true, description: "Document version associated with the marker resolution request", reason: None }, - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "JSON-RPC error returned while resolving one Java navigation marker", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id resolving the navigation marker", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.navigation.resolved", - channel: "lsp/{server}", - level: LogLevel::Debug, - message: "Navigation markers resolved for server {server} for {document}", - fields: &[ - FieldMetadata { name: "code_lenses", field_type: FieldType::Int, required: true, description: "Number of code lenses successfully resolved for the completed request", reason: None }, - FieldMetadata { name: "document", field_type: FieldType::Path, required: true, description: "Document path for the completed navigation request, redacted before persistence", reason: None }, - FieldMetadata { name: "document_version", field_type: FieldType::Int, required: true, description: "Document version associated with the completed navigation request", reason: None }, - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time from navigation request creation to marker completion, in milliseconds", reason: None }, - FieldMetadata { name: "markers", field_type: FieldType::Int, required: true, description: "Number of navigation markers produced by the completed request", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that resolved the navigation markers", reason: None }, - FieldMetadata { name: "tasks", field_type: FieldType::Int, required: true, description: "Total navigation resolution tasks belonging to the completed request", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, EventMetadata { id: "lsp.notification.received", channel: "lsp/{server}", @@ -1604,8 +1300,8 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Info, message: "Language service process started for server {server}", fields: &[ - FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Java runtime version used to launch the language server, when available", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose process started", reason: None }, + FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Runtime version reported for the language server launch, when available", reason: None }, + FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose process started", reason: None }, ], span: None, rate: 120, @@ -1617,7 +1313,7 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Info, message: "Language service protocol initialized for server {server}", fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose initialize handshake completed", reason: None }, + FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose initialize handshake completed", reason: None }, ], span: None, rate: 120, @@ -1758,73 +1454,6 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 120, owner: "lithe-core", }, - EventMetadata { - id: "lsp.workspace.import_finished", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Language service project import finished for server {server}", - fields: &[ - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: false, description: "Elapsed workspace import time in milliseconds, when reported by the readiness diagnostics", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id that reached ServiceReady", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.workspace.legacy_removed", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Legacy project files removed for server {server}", - fields: &[ - FieldMetadata { name: "removed_files", field_type: FieldType::Int, required: true, description: "Number of legacy Java project files removed from the workspace", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id whose legacy project metadata was removed", reason: None }, - FieldMetadata { name: "state_reset", field_type: FieldType::Bool, required: true, description: "Whether removing the legacy Java metadata also reset language server workspace state", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.workspace.progress_received", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Workspace import progress received for server {server} at {phase}", - fields: &[ - FieldMetadata { name: "completed", field_type: FieldType::Int, required: false, description: "Completed work units reported for the current import phase, when available", reason: None }, - FieldMetadata { name: "phase", field_type: FieldType::Token, required: true, description: "Workspace import phase reported by the Java language service", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id reporting workspace import progress", reason: None }, - FieldMetadata { name: "total", field_type: FieldType::Int, required: false, description: "Total work units reported for the current import phase, when available", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.workspace.stalled", - channel: "lsp/{server}", - level: LogLevel::Warn, - message: "Workspace import progress stalled for server {server}", - fields: &[ - FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time since the last workspace import progress observation, encoded in milliseconds", reason: None }, - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id still waiting for ServiceReady", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, - EventMetadata { - id: "lsp.workspace.waiting", - channel: "lsp/{server}", - level: LogLevel::Info, - message: "Workspace import waiting for service readiness for server {server}", - fields: &[ - FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated Java language server session id waiting for project import to reach ServiceReady", reason: None }, - ], - span: None, - rate: 120, - owner: "lithe-core", - }, EventMetadata { id: "perf.app.sampled", channel: "perf", @@ -2221,7 +1850,7 @@ pub static EVENTS: &[EventMetadata] = &[ message: "Engine process started for server {plugin}", fields: &[ FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity assigned by Core to this engine session", reason: None }, - FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Java runtime version used to launch the language server, when available", reason: None }, + FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Runtime version reported for the engine launch, when available", reason: None }, ], span: None, rate: 120, @@ -2243,9 +1872,11 @@ pub static EVENTS: &[EventMetadata] = &[ id: "plugins.host.request_failed", channel: "plugins/{plugin}/host", level: LogLevel::Error, - message: "Plugin host request failed", + message: "Plugin host request {method} failed with {code}", fields: &[ + FieldMetadata { name: "code", field_type: FieldType::Token, required: true, description: "Stable plugin.host.* failure code the backend received, independent of the native error's wording", reason: None }, FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Native host service error or stable host request failure code", reason: None }, + FieldMetadata { name: "method", field_type: FieldType::Token, required: true, description: "Host method or plugin function the request named, e.g. lithe/host/languageServer/notify; never its params", reason: None }, FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that owns this failed host request", reason: None }, ], span: None, @@ -2677,8 +2308,8 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Warn, message: "Build dependency {stage} cleanup failed", fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem error raised while deleting a Maven dependency-tree scratch file", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Dependency-tree cleanup target, e.g. current-scratch or abandoned-scratch", reason: None }, + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem error raised while deleting a build scratch file", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Build scratch cleanup target, e.g. provider-output or abandoned-scratch", reason: None }, ], span: None, rate: 60, @@ -3174,7 +2805,7 @@ pub static EVENTS: &[EventMetadata] = &[ message: "Engine process started for server {provider}", fields: &[ FieldMetadata { name: "provider", field_type: FieldType::Id, required: true, description: "Validated provider identity assigned by Core to this engine session", reason: None }, - FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Java runtime version used to launch the language server, when available", reason: None }, + FieldMetadata { name: "runtime_version", field_type: FieldType::Version, required: false, description: "Runtime version reported for the engine launch, when available", reason: None }, ], span: None, rate: 120, diff --git a/rust/lithe-core/src/diagnostics/filter.rs b/rust/lithe-core/src/diagnostics/filter.rs index 072c638a84..c5043579cd 100644 --- a/rust/lithe-core/src/diagnostics/filter.rs +++ b/rust/lithe-core/src/diagnostics/filter.rs @@ -569,18 +569,18 @@ mod tests { event: "app.failed".into(), op: Some("ABC-12".into()), msg: "A failure".into(), - fields: [("server".into(), "JDTLS".into())].into(), + fields: [("server".into(), "TOOL-A".into())].into(), }; for expression in [ - "level>=inf level:wrn op:abc event:APP channel:LS server=dt /FAIL/", - "JDTLS", + "level>=inf level:wrn op:abc event:APP channel:LS server=ol /FAIL/", + "TOOL-A", "-plugin:p", "seq:1", ] { assert!( CompiledFilter::compile(expression) .unwrap() - .matches(&record, "lsp/jdtls"), + .matches(&record, "lsp/tool-a"), "{expression}" ); } @@ -588,7 +588,7 @@ mod tests { assert!( !CompiledFilter::compile(expression) .unwrap() - .matches(&record, "lsp/jdtls"), + .matches(&record, "lsp/tool-a"), "{expression}" ); } diff --git a/rust/lithe-core/src/diagnostics/logging.rs b/rust/lithe-core/src/diagnostics/logging.rs index c9bf518160..94775719fd 100644 --- a/rust/lithe-core/src/diagnostics/logging.rs +++ b/rust/lithe-core/src/diagnostics/logging.rs @@ -33,7 +33,7 @@ pub const MAX_LOG_EXPORT_BYTES: usize = 10 * 1024 * 1024; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LogEventRequest { - /// Stable subsystem scope such as language.java; never a path. + /// Stable subsystem scope such as language.rust; never a path. pub scope: String, /// Human-readable lifecycle fact; credentials are scrubbed before persistence. pub message: String, @@ -48,7 +48,7 @@ pub struct LogEventRequest { pub struct PreparedLogEvent { /// One fixed routing domain from LOG_CATEGORIES. pub category: String, - /// Stable subsystem scope such as language.java; never a path. + /// Stable subsystem scope such as language.rust; never a path. pub scope: String, /// Human-readable lifecycle fact; credentials are scrubbed before persistence. pub message: String, @@ -62,7 +62,7 @@ pub fn log_category(scope: &str) -> &'static str { let prefix = scope.split(['.', ':', '/', '[']).next().unwrap_or(""); match prefix { "lsp" | "language" | "editor" | "index" => "language", - "run" | "debug" | "build" | "maven" | "gradle" => "run", + "run" | "debug" | "build" => "run", "git" | "vcs" => "git", "plugin" | "plugins" | "module" => "plugins", "perf" | "performance" | "memory" | "fps" => "performance", @@ -379,7 +379,7 @@ mod tests { fn scrubs_nested_secrets_before_json_escaping_and_bounds_arrays() { let event = prepare_log_event( serde_json::from_value(json!({ - "scope":"language.java", "message":"started", "fields":{ + "scope":"language.rust", "message":"started", "fields":{ "context":{"password":"fake-password","items":[{"accessToken":"fake-token"}]}, "sourceContent":"private source", "operationID":"operation-1" } diff --git a/rust/lithe-core/src/diagnostics/request_trace.rs b/rust/lithe-core/src/diagnostics/request_trace.rs index 62cd2dc385..6d9e2923eb 100644 --- a/rust/lithe-core/src/diagnostics/request_trace.rs +++ b/rust/lithe-core/src/diagnostics/request_trace.rs @@ -186,10 +186,6 @@ pub(crate) fn is_hot(method: &str) -> bool { | "lsp.builtinNavigation" | "lsp.mergeCompletions" | "lsp.problems.query" - | "java.codeVision" - | "java.navigationMarkers" - | "java.runMarkers" - | "java.structure" ) // Search-as-you-type issues one request per query revision. || matches!( diff --git a/rust/lithe-core/src/editor/line_edit.rs b/rust/lithe-core/src/editor/line_edit.rs index 1167d44715..19ddf90a30 100644 --- a/rust/lithe-core/src/editor/line_edit.rs +++ b/rust/lithe-core/src/editor/line_edit.rs @@ -137,9 +137,9 @@ pub fn line_comment_token(request: LineCommentTokenRequest) -> LineCommentToken fn lookup_line_comment_token(identifier: &str) -> Option<&'static str> { match identifier { // C family and other double-slash languages - "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "java" | "kt" | "kts" | "swift" - | "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "go" | "rs" | "cs" | "csharp" | "php" - | "dart" | "scala" | "groovy" | "m" | "mm" | "zig" | "javascript" | "javascriptreact" + "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "kt" | "kts" | "swift" | "js" + | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "go" | "rs" | "cs" | "csharp" | "php" | "dart" + | "scala" | "groovy" | "m" | "mm" | "zig" | "javascript" | "javascriptreact" | "typescript" | "typescriptreact" | "kotlin" | "rust" => Some("//"), // Hash languages "py" | "python" | "rb" | "ruby" | "sh" | "bash" | "zsh" | "shell" | "yml" | "yaml" diff --git a/rust/lithe-core/src/editor/tests.rs b/rust/lithe-core/src/editor/tests.rs index 977945533a..33a106b400 100644 --- a/rust/lithe-core/src/editor/tests.rs +++ b/rust/lithe-core/src/editor/tests.rs @@ -639,7 +639,6 @@ fn line_comment_token_maps_common_extensions_and_language_ids() { for (extension, expected) in [ ("swift", "//"), ("Swift", "//"), - ("java", "//"), ("ts", "//"), ("csharp", "//"), ("zig", "//"), diff --git a/rust/lithe-core/src/execution/configuration.rs b/rust/lithe-core/src/execution/configuration.rs index 9fe8824761..ff25f603a8 100644 --- a/rust/lithe-core/src/execution/configuration.rs +++ b/rust/lithe-core/src/execution/configuration.rs @@ -5,29 +5,23 @@ pub(crate) use project_toolchain::{project_toolchain, ProjectToolchainRequest}; use super::generated_layer::{self, GeneratedLayer}; use super::types::{Confidence, Execution, RunCategory}; -use crate::languages::{JavaEntrypointFact, JavaEntrypointFacts}; use crate::protocol::{invalid_relative_path, CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; -use std::path::{Component, Path, PathBuf}; +use std::path::{Path, PathBuf}; const VERSION: u32 = 2; const LEGACY_VERSION: u32 = 1; // Bumped when the detected layer changes; stale cached facts must regenerate. -const GENERATOR_REVISION: &str = "19"; +const GENERATOR_REVISION: &str = "20"; /// Toolchain requirements and `project.json` are separate documents that happen /// to live under `.lithe`. Their schema did not change with run-config v2, so /// they keep their own version and must not be validated against `VERSION`. const SIDECAR_VERSION: u32 = 1; -/// Recorded in `generator.inputs` instead of a content hash for a Java source -/// whose bytes generation never reads: only its presence feeds the Java path -/// set. Launchable classes come from JDT, so hashing every source would scan -/// the whole project on each inspection without detecting anything more. -const PATH_ONLY_INPUT: &str = "path"; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -40,14 +34,6 @@ pub struct InspectRequest { /// Host-owned local layer. When present, Core validates it instead of `.lithe/run/local.json`. #[serde(default)] pub local_document: Option, - /// JDT's current launchable classes (`lsp.request` operation - /// `javaEntrypoints`). When present, Core reports whether the generated - /// Java entries still match them; omitted while JDT is not ready. - #[serde(default)] - pub java_entrypoints: Option, - /// Current enabled Provider facts; omission leaves legacy clients unchanged. - #[serde(default)] - pub project_ownership: Option>, /// Complete generic run selectors; omission preserves older callers. #[serde(default)] pub provider_runs: Option>, @@ -58,26 +44,12 @@ pub struct InspectRequest { /// Request to regenerate detected configurations from the current project tree. pub struct GenerateRequest { pub root: String, - #[serde(default)] - pub paths: Vec, - #[serde(default)] - pub module_paths: Vec, - /// Current provider ownership, including an authoritative empty snapshot. - /// Omitted retains compatibility for the existing Windows generator. - #[serde(default)] - pub project_ownership: Option>, /// Complete generic run selectors; omission preserves older callers. #[serde(default)] pub provider_runs: Option>, - /// Launchable classes from the Java language service (`lsp.request` - /// operation `javaEntrypoints`). Absent while that service is not ready: - /// the previous generation's Java entries are carried forward instead of - /// being dropped, so the Run list does not empty during a cold start. - #[serde(default)] - pub java_entrypoints: Option, /// Application cache directory, outside the workspace. Generation records - /// its result there so the next session can list Java entries before the - /// language service answers; omitted, only this process remembers it. + /// its result there so the next session can list provider entries before + /// the providers answer again; omitted, only this process remembers it. #[serde(default)] pub cache_directory: Option, } @@ -103,7 +75,7 @@ pub struct ResolveRequest { pub struct ToolchainCandidate { /// Host-stable candidate identifier referenced by resolved configurations. pub id: String, - /// Toolchain role such as `java` or `maven`, not a display label. + /// Toolchain role such as `node`, not a display label. #[serde(rename = "type")] pub kind: String, #[serde(default)] @@ -118,21 +90,9 @@ pub struct ToolchainCandidate { pub struct LaunchPlanRequest { pub root: String, pub configuration_id: String, - #[serde(default)] - pub current_file: Option, - #[serde(default)] - pub class_path: Option, - /// JDT LS-resolved runtime paths for a project-owned Java main class. - #[serde(default)] - pub java_launch: Option, - #[serde(default)] - pub debug_port: Option, /// Host-owned local layer. When present, Core uses it instead of `.lithe/run/local.json`. #[serde(default)] pub local_document: Option, - /// Project Maven defaults supplied by the native host for Maven-backed plans. - #[serde(default)] - pub maven_context: Option, } /// Resolves saved Run choices without assembling a build tool's command line. @@ -150,37 +110,13 @@ pub struct ProviderLaunchInputsRequest { pub local_document: Option, } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Runtime path groups resolved by the Java project model before launch. -pub struct JavaLaunchRequest { - /// Host receipt: the current provider task already prepared build resources. - #[serde(default)] - pub build_prepared: bool, - pub main_class: String, - #[serde(default)] - pub class_paths: Vec, - #[serde(default)] - pub module_paths: Vec, -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] /// Global machine toolchain stored at document level in the local layer. pub struct ToolchainPaths { - #[serde(default)] - pub java_home_path: String, - #[serde(default)] - pub maven_executable_path: String, - #[serde(default)] - pub maven_java_home_path: String, /// Explicit executables for generic runtime toolchain IDs such as `project-node`. #[serde(default)] pub runtime_executable_paths: BTreeMap, - /// Machine-local selections by subproject root. Absent preserves saved - /// selections; an explicit empty map clears them. - #[serde(default)] - pub path_overrides: Option>, /// Generic consumer preferences in the same machine-local document. /// Absent preserves saved choices; an empty v1 document resets them. #[serde(default)] @@ -188,7 +124,7 @@ pub struct ToolchainPaths { } /// Replaces only generic preferences in a captured machine-local Run document. -/// Legacy fields remain owned by their existing consumers until cutover. +/// Other toolchain fields are preserved untouched for their owners. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateToolPreferencesRequest { @@ -210,7 +146,7 @@ pub fn update_tool_preferences(request: UpdateToolPreferencesRequest) -> Result< )); } configuration_ids(&document)?; - validate_toolchain_path_overrides(&document)?; + validate_tool_preferences(&document)?; crate::toolchain::preferences::validate(&request.preferences) .map_err(|error| CoreError::new(ErrorCode::InvalidRequest, error.message))?; let object = document @@ -224,21 +160,6 @@ pub fn update_tool_preferences(request: UpdateToolPreferencesRequest) -> Result< Ok(json!({"document":serde_json::to_string_pretty(&document).expect("validated Run document")})) } -/// Tool paths owned by a subproject; empty fields inherit the project defaults. -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct PathToolchainOverride { - /// JDK home; empty inherits the project JDK. - #[serde(default)] - pub java_home_path: String, - /// Maven executable or wrapper selection; empty inherits the project choice. - #[serde(default)] - pub maven_executable_path: String, - /// Maven's JDK home; empty inherits the project Maven JDK. - #[serde(default)] - pub maven_java_home_path: String, -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] /// Editable options applied to a team or machine-local configuration layer. @@ -249,27 +170,12 @@ pub struct UpdateOptionsRequest { pub configuration_id: String, #[serde(default)] pub working_directory: String, - #[serde(default)] - pub jvm_arguments: String, /// Common program arguments. `programArguments` remains a wire alias for /// clients from before the generic run-options migration. #[serde(default, alias = "programArguments")] pub arguments: String, #[serde(default)] pub environment: BTreeMap, - #[serde(default)] - pub maven_profiles: Vec, - /// Per-configuration Maven test policy. `None` inherits the project context; - /// `Some(false)` must remain distinct so a test configuration can override - /// a project-wide Skip Tests default. - #[serde(default)] - pub maven_skip_tests: Option, - #[serde(default)] - pub java_home_path: String, - #[serde(default)] - pub maven_executable_path: String, - #[serde(default)] - pub maven_java_home_path: String, /// Portable provider choices. Omission preserves the existing namespace. #[serde( default, @@ -296,11 +202,7 @@ pub struct CreateUserConfigurationRequest { /// UI configuration kind mapped to a namespaced provider during creation. #[serde(rename = "type")] pub kind: String, - #[serde(default)] - pub module: String, - #[serde(default)] - pub main_class: String, - /// A typed selector, never a cached executable or classpath. + /// A typed selector, never a cached executable or resolved launch payload. #[serde(default)] pub build: Option, } @@ -413,65 +315,31 @@ fn migrate_configuration_value(item: &mut Value) { let Some(object) = item.as_object_mut() else { return; }; + // v1 entries kept tool-specific launch fields at the top level. Core no + // longer interprets any of them; they stay inert because RunConfiguration + // ignores unknown keys, and the owning provider regenerates its payload. let legacy_type = object .remove("type") .and_then(|value| value.as_str().map(str::to_string)) - .unwrap_or_else(|| "java.current-file".to_string()); - - let mut maven = serde_json::Map::new(); - for (legacy_key, target_key) in [ - ("mainClass", "mainClass"), - ("module", "module"), - ("jvmArguments", "jvmArguments"), - ("programArguments", "programArguments"), - ("mavenProfiles", "profiles"), - ] { - if let Some(value) = object.remove(legacy_key) { - let is_empty = value - .as_array() - .map(|items| items.is_empty()) - .unwrap_or(false); - if !value.is_null() && !is_empty { - maven.insert(target_key.to_string(), value); - } - } - } + .filter(|value| valid_provider(value)) + .unwrap_or_else(|| "legacy.unknown".to_string()); if let Some(working_directory) = object.remove("workingDirectory") { object.insert("cwd".to_string(), working_directory); } - if !maven.is_empty() { - object - .entry("extensions") - .or_insert_with(|| json!({})) - .as_object_mut() - .map(|extensions| extensions.insert("maven".to_string(), Value::Object(maven))); - } - - let execution = match legacy_type.as_str() { - "java.current-file" => "application", - // A framework goal starts something long-running; a bare Maven goal - // runs to completion. - provider if framework_goal(provider).is_some() => "service", - _ => "task", - }; object.insert("provider".to_string(), json!(legacy_type)); - object.insert("execution".to_string(), json!(execution)); + object.insert("execution".to_string(), json!("task")); object.insert("confidence".to_string(), json!("native")); - object.insert("debug".to_string(), json!({ "adapter": "jdwp" })); } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] /// Fingerprint and inputs used to decide whether generated output is stale. /// -/// `inputs` maps each workspace-relative input to `sha256:` of its bytes, -/// or to `path` for a Java source that only counts by presence. +/// `inputs` maps each workspace-relative input to `sha256:` of its bytes. pub struct GeneratorMetadata { pub fingerprint: String, - /// Identity of the Provider facts that generated this document. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub provider_fingerprint: Option, - /// Identity of generic run declarations and opaque targets, separate from Java facts. + /// Identity of generic run declarations and opaque targets, separate from + /// the file inputs so a provider answer alone can mark the layer stale. #[serde(default, skip_serializing_if = "Option::is_none")] pub provider_run_fingerprint: Option, /// Unreadable inputs retained as unknown; a partial baseline cannot prove freshness. @@ -485,7 +353,7 @@ pub struct GeneratorMetadata { #[serde(rename_all = "camelCase")] /// Debug adapter supported by a runnable configuration. pub struct DebugCapability { - /// Stable adapter identifier, currently `jdwp` for JVM configurations. + /// Stable adapter identifier declared by the provider that owns the entry. pub adapter: String, } @@ -495,7 +363,7 @@ pub struct DebugCapability { pub struct RunConfiguration { pub id: String, pub name: String, - /// Open namespaced discriminator, e.g. `maven.module`, `npm.script`. + /// Open namespaced discriminator, e.g. `npm.script`, `cargo.run`. /// Deliberately not an enum: new ecosystems must not require a contract change. pub provider: String, #[serde(default)] @@ -520,7 +388,7 @@ pub struct RunConfiguration { pub debug: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub members: Vec, - /// Ecosystem-specific payload keyed by namespace (`maven`, `npm`, ...). + /// Ecosystem-specific payload keyed by namespace (`npm`, `build`, ...). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub extensions: BTreeMap, #[serde(default)] @@ -534,28 +402,6 @@ fn dot() -> String { ".".to_string() } -/// Accessors for the `maven` extension namespace. Keeps JDWP and Spring Boot -/// launch assembly working after the fields moved out of the common shape. -impl RunConfiguration { - pub fn extension_string(&self, namespace: &str, key: &str) -> Option { - self.extensions - .get(namespace)? - .get(key)? - .as_str() - .map(str::to_string) - } - - pub fn main_class(&self) -> Option { - self.extension_string("maven", "mainClass") - .or_else(|| self.extension_string("java", "mainClass")) - } - - pub fn module(&self) -> Option { - self.extension_string("maven", "module") - .or_else(|| self.extension_string("java", "module")) - } -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] /// Versioned requirements written separately from run configurations. @@ -578,12 +424,9 @@ pub struct ToolchainRequirement { pub minimum_version: Option, #[serde(default)] pub preferred_vendor: Option, - #[serde(default)] - pub wrapper: Option, + /// Exact version prefix; [`Self::minimum_version`] accepts newer releases. #[serde(default)] pub version: Option, - #[serde(default)] - pub java: Option, } /// Validates configuration and sidecar documents without mutating the workspace. @@ -639,11 +482,11 @@ pub fn inspect(request: InspectRequest) -> Result { let local = local_layer_document(&root, request.local_document.clone())?; let team = read_document_value(&root, "run/configurations.json")? .unwrap_or_else(|| json!({"version": VERSION, "configurations": []})); - if let Some((document, metadata)) = generated - .and_then(|document| Some((document, document.generator.as_ref()?))) + if let Some(metadata) = generated + .and_then(|document| document.generator.as_ref()) .filter(|_| request.check_fingerprint != Some(false)) { - let current_inputs = project_inputs(&root, &java_entry_sources(&document.configurations))?; + let current_inputs = project_inputs(&root)?; if !current_inputs.unreadable_paths.is_empty() || !metadata.unreadable_paths.is_empty() { let unknown = current_inputs .unreadable_paths @@ -654,7 +497,7 @@ pub fn inspect(request: InspectRequest) -> Result { } else if metadata.fingerprint != fingerprint_from_inputs(¤t_inputs.inputs) { // Stored inputs that no longer reproduce the stored fingerprint were // recorded by another generator revision, whose input rules (such - // as which sources are hashed) may differ from today's. + // as which manifests are hashed) may differ from today's. let generator_changed = fingerprint_from_inputs(&metadata.inputs) != metadata.fingerprint; let message = if metadata.inputs.is_empty() { @@ -670,79 +513,20 @@ pub fn inspect(request: InspectRequest) -> Result { })); } } - if let Some(projects) = &request.project_ownership { - super::project_ownership::validate(projects)?; + if let Some(runs) = &request.provider_runs { + super::provider_runs::validate(runs)?; if let Some(document) = generated { - let expected = super::project_ownership::fingerprint(projects); + let expected = super::provider_runs::fingerprint(runs); if document .generator .as_ref() - .and_then(|metadata| metadata.provider_fingerprint.as_deref()) + .and_then(|metadata| metadata.provider_run_fingerprint.as_deref()) != Some(expected.as_str()) { diagnostics.push(json!({"code":"staleProviderModel", "message":"Build provider model changed; regenerate Run configurations"})); } } } - if let Some(runs) = &request.provider_runs { - super::provider_runs::validate(runs)?; - if let Some(document) = generated { - let expected = super::provider_runs::fingerprint(runs); - if !diagnostics - .iter() - .any(|item| item["code"] == "staleProviderModel") - && document - .generator - .as_ref() - .and_then(|metadata| metadata.provider_run_fingerprint.as_deref()) - != Some(expected.as_str()) - { - diagnostics.push(json!({"code":"staleProviderModel", "message":"Build provider model changed; regenerate Run configurations"})); - } - } - } - if let (Some(document), Some(current)) = (generated, request.java_entrypoints.as_ref()) { - // Source hashing no longer notices a main method added to an existing - // class; JDT's answer does, and is cheaper than reading every source. - let recorded = java_entrypoint_keys(&java_entrypoints_from_document(&root, document)); - let current = java_entrypoint_keys(current); - if recorded != current { - let added = current.difference(&recorded).count(); - let removed = recorded.difference(¤t).count(); - diagnostics.push(json!({ - "code": "staleFingerprint", - "message": format!( - "Java entry points changed: {added} added, {removed} removed" - ) - })); - } - } - if let Some(document) = generated { - // A Java main entry without a recorded main class cannot launch and - // cannot be rebuilt from local sources -- JDT owns entry points -- so - // hosts must be told to regenerate while the language service can - // answer, instead of letting the stale entry surface as something - // else. A `spring-boot.maven` compatibility entry carries no main - // class by design and is not stale. - let stale = document - .configurations - .iter() - .filter(|configuration| configuration.provider == "java.main") - .filter(|configuration| { - configuration - .main_class() - .is_none_or(|main_class| main_class.trim().is_empty()) - }) - .count(); - if stale > 0 { - diagnostics.push(json!({ - "code": "staleJavaEntrypoint", - "message": format!( - "Java run entries are missing their main class ({stale}); regenerate run configurations" - ) - })); - } - } Ok(json!({ "status": if generated.is_some() || has_saved_build_run(&local) || has_saved_build_run(&team) { "ready" } else { "missing" }, // Saved provider tasks remain runnable before detection, but must not @@ -765,243 +549,20 @@ pub fn generate(request: GenerateRequest) -> Result { let root = existing_root(&request.root)?; let cache_directory = request.cache_directory.map(PathBuf::from); let previous = previous_generation(&root, cache_directory.as_deref()); - let mut paths = request - .paths - .into_iter() - .filter(|path| !is_nested_checkout_path(path)) - .collect::>(); - paths.sort(); - paths.dedup(); - if let Some(projects) = &request.project_ownership { - super::project_ownership::validate(projects)?; - } - let maven_root = if request.project_ownership.is_none() { - crate::project::maven_root(&root, &paths)? - } else { - None - }; - let maven_relative_path = maven_root - .as_ref() - .map(|(_, relative_path)| relative_path.as_str()); - let has_java_sources = paths - .iter() - .any(|path| path.to_lowercase().ends_with(".java")); - let has_maven_project = maven_relative_path.is_some() - || (request.project_ownership.is_none() - && (root.join("mvnw").is_file() || root.join("mvnw.cmd").is_file())); - // A Gradle build needs the same JDK requirement as Maven, and its sources may - // be Kotlin or Groovy rather than Java, so the build files count on their own. - let has_gradle_project = ["build.gradle", "build.gradle.kts", "gradlew"] - .iter() - .any(|name| root.join(name).is_file()); - let has_java_ecosystem = has_java_sources || has_maven_project || has_gradle_project; - let configured_module_paths = request - .module_paths - .into_iter() - .map(|path| workspace_build_path(maven_relative_path, &path)) - .collect(); - // Note: entry-point ownership is recorded in .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md - let (mut java_entrypoints, java_entrypoints_origin) = match request.java_entrypoints { - Some(facts) => (facts, "languageService"), - None => ( - previous - .as_ref() - .map(|document| java_entrypoints_from_document(&root, document)) - .unwrap_or_else(empty_java_entrypoints), - "previousGeneration", - ), - }; - // JDT imports nested checkouts such as `.worktree/*` as projects of their - // own; they are excluded here exactly as their source paths are above. - java_entrypoints - .entries - .retain(|entry| !is_nested_checkout_path(&entry.source_path)); - // Module ownership must follow the confirmed source set, even when the - // caller passes an empty or partial editor file list. - let entry_sources = java_entrypoints - .entries - .iter() - .map(|entry| entry.source_path.clone()) - .collect::>(); - let module_paths = match &request.project_ownership { - Some(projects) => projects - .iter() - .map(|project| project.path.clone()) - .collect(), - None => inferred_relative_build_projects(&root, &entry_sources, configured_module_paths), - }; - let scanned = crate::languages::run_configurations_from_entrypoints( - &root, - &java_entrypoints, - &module_paths, - )?; - let spring_entrypoints = scanned - .configurations - .iter() - .filter(|value| value.kind == "springBoot") - .cloned() - .collect::>(); - let mut maven_owners = BTreeMap::, Option<(PathBuf, String)>>::new(); - let configurations = scanned - .configurations - .into_iter() - .map(|mut value| -> Result { - let model_owner = request - .project_ownership - .as_ref() - .and_then(|projects| super::project_ownership::owner(projects, &value.source_path)); - if request.project_ownership.is_some() { - value.module_path = model_owner - .filter(|owner| owner.path != ".") - .map(|owner| owner.path.clone()); - value.source_set = model_owner - .map_or(crate::protocol::JavaSourceSetResponse::Other, |owner| { - owner.source_set(&value.source_path) - }); - } - let provider = match value.kind.as_str() { - "javaMain" | "springBoot" => "java.main", - "mavenModule" => "maven.module", - _ => "java.current-file", - }; - let id = java_configuration_id(&value); - let owner_key = value.module_path.clone(); - let build_owner = model_owner.and_then(|owner| owner.build.as_ref()); - let maven_owner = if request.project_ownership.is_some() { - None - } else if let Some(owner) = maven_owners.get(&owner_key) { - owner.clone() - } else { - let owner = maven_owner_for_module( - &root, - maven_root.as_ref(), - value.module_path.as_deref(), - )?; - maven_owners.insert(owner_key, owner.clone()); - owner - }; - let owner_relative_path = build_owner.map(|owner| owner.root.as_str()).or_else(|| { - maven_owner - .as_ref() - .map(|(_, relative_path)| relative_path.as_str()) - }); - let module_path = value - .module_path - .as_deref() - .map(|path| relative_build_project(owner_relative_path, path)) - .unwrap_or_else(dot); - let source_path = value.source_path; - // Maven ownership is per entry: one workspace can contain standalone - // Java files or multiple independent reactors in the same request. - let uses_maven_toolchain = maven_owner.is_some() && provider != "java.current-file"; - let mut toolchains = BTreeMap::new(); - toolchains.insert("java".to_string(), "project-jdk".to_string()); - if uses_maven_toolchain { - toolchains.insert("maven".to_string(), "project-maven".to_string()); - } - let mut extensions = BTreeMap::new(); - let mut java = json!({ "source": source_path, "sourceSet": value.source_set }); - if request.project_ownership.is_some() { - java["module"] = json!(module_path); - java["mainClass"] = json!(value.main_class); - if let Some(build) = build_owner { - java["build"] = json!(build); - } - } else { - let mut maven = serde_json::Map::new(); - maven.insert("module".to_string(), json!(module_path)); - if let Some(main_class) = value.main_class.as_ref() { - maven.insert("mainClass".to_string(), json!(main_class)); - } - extensions.insert("maven".to_string(), Value::Object(maven)); - } - extensions.insert("java".to_string(), java); - Ok(RunConfiguration { - id, - name: value.name, - provider: provider.to_string(), - execution: match provider { - "java.main" | "java.current-file" => Execution::Application, - _ => Execution::Task, - }, - category: RunCategory::Project, - command: None, - args: Vec::new(), - cwd: if provider == "java.current-file" { - ".".to_string() - } else { - owner_relative_path.unwrap_or(".").to_string() - }, - env: BTreeMap::new(), - confidence: Confidence::Native, - toolchains, - debug: (provider != "java.main").then(|| DebugCapability { - adapter: "jdwp".to_string(), - }), - members: Vec::new(), - extensions, - disabled: false, - source: Some(source_path), - }) - }) - .collect::, _>>()?; - let mut configurations = deduplicate_java_configurations(configurations); - if has_java_sources { - configurations.push(RunConfiguration { - id: "current-file".to_string(), - name: "Current File".to_string(), - provider: "java.current-file".to_string(), - execution: Execution::Application, - category: RunCategory::Project, - command: None, - args: Vec::new(), - cwd: ".".to_string(), - env: BTreeMap::new(), - confidence: Confidence::Native, - toolchains: [("java".to_string(), "project-jdk".to_string())] - .into_iter() - .collect(), - debug: Some(DebugCapability { - adapter: "jdwp".to_string(), - }), - members: Vec::new(), - extensions: [("maven".to_string(), json!({ "module": "." }))] - .into_iter() - .collect(), - disabled: false, - source: None, - }); - } - // Detectors run after the Java scan so a Java configuration always keeps its - // id: `detected_configurations` skips ids the Java pass already claimed - // rather than overwriting them, which would detach team and local overrides. - let claimed = configurations - .iter() - .map(|item| item.id.clone()) - .collect::>(); - let mut detected = detected_configurations( - &root, - (request.project_ownership.is_none() && request.provider_runs.is_none()) - .then(|| maven_root.as_ref().map(|(path, _)| path.as_path())) - .flatten(), - &claimed, - )?; + let mut configurations = detected_configurations(&root)?; if let Some(runs) = &request.provider_runs { super::provider_runs::validate(runs)?; - detected.extend( + let claimed = configurations + .iter() + .map(|item| item.id.clone()) + .collect::>(); + configurations.extend( super::provider_runs::configurations(runs) .into_iter() .filter(|item| !claimed.contains(&item.id)), ); } - if request.project_ownership.is_none() && request.provider_runs.is_none() { - retain_confirmed_spring_services(&mut detected, &spring_entrypoints, maven_relative_path); - } - // Counts real entry points, not documents: the always-present "Current File" - // fallback is excluded so an empty project still reports zero and the UI can - // say so, while a detected npm service correctly reports one. - configurations.extend(detected); - let mut snapshot = project_inputs(&root, &java_entry_sources(&configurations))?; + let mut snapshot = project_inputs(&root)?; // Unknown subtrees cannot delete known configurations or baseline inputs. // Invalid required documents still fail instead of being silently overwritten. let authoritative_service_ids = request.provider_runs.as_ref().map(|_| { @@ -1021,24 +582,11 @@ pub fn generate(request: GenerateRequest) -> Result { configurations.retain(|item| item.provider != "build.provider" || ids.contains(&item.id)); } disambiguate_configuration_names(&mut configurations); - let entry_count = configurations - .iter() - .filter(|item| item.id != "current-file") - .count(); - let requirements = detect_requirements( - &root, - maven_root.as_ref().map(|(path, _)| path.as_path()), - has_java_ecosystem, - &configurations, - request.project_ownership.as_deref(), - )?; + let entry_count = configurations.len(); + let requirements = detect_requirements(&root, &configurations)?; let generated = RunConfigurationDocument { version: VERSION, generator: Some(GeneratorMetadata { - provider_fingerprint: request - .project_ownership - .as_deref() - .map(super::project_ownership::fingerprint), provider_run_fingerprint: request .provider_runs .as_deref() @@ -1052,8 +600,7 @@ pub fn generate(request: GenerateRequest) -> Result { let response = json!({ "generated": generated, "toolchainRequirements": requirements, - "entryCount": entry_count, - "javaEntrypointsOrigin": java_entrypoints_origin + "entryCount": entry_count }); if let Some(cache_directory) = cache_directory.as_deref() { generated_layer::cache_document(cache_directory, &root, &generated); @@ -1072,11 +619,10 @@ pub fn generate(request: GenerateRequest) -> Result { /// the one cached by an earlier session, else the `.lithe/run/generated.json` /// older Lithe versions wrote into the workspace (read, never written). /// -/// Generation uses it only while the Java language service has not answered -/// yet, and to keep entries under a subtree it cannot read. Its Java entries -/// were JDT's answer last time; replaying them keeps ids and user overrides -/// attached until a fresh answer replaces them. An unreadable or invalid -/// previous document contributes nothing, because this generation replaces it. +/// Generation uses it only to keep entries under a subtree it cannot read: +/// replaying them keeps ids and user overrides attached until the subtree is +/// readable again. An unreadable or invalid previous document contributes +/// nothing, because this generation replaces it. fn previous_generation( root: &Path, cache_directory: Option<&Path>, @@ -1097,94 +643,11 @@ fn previous_generation( .filter(|document| validate_version(document.version).is_ok()) } -fn empty_java_entrypoints() -> JavaEntrypointFacts { - JavaEntrypointFacts { - schema_version: 1, - entries: Vec::new(), - } -} - -/// Java entry points a generated document was built from, in the shape JDT -/// reports them. Entries whose source no longer exists are dropped. -fn java_entrypoints_from_document( - root: &Path, - document: &RunConfigurationDocument, -) -> JavaEntrypointFacts { - let mut facts = empty_java_entrypoints(); - for configuration in &document.configurations { - if !is_java_entry_configuration(configuration) { - continue; - } - let (Some(source_path), Some(main_class)) = ( - configuration.extension_string("java", "source"), - configuration.main_class(), - ) else { - continue; - }; - if invalid_relative_path(&source_path) || !root.join(&source_path).is_file() { - continue; - } - facts.entries.push(JavaEntrypointFact { - source_path, - main_class, - project_name: None, - }); - } - facts.entries.sort_by(|left, right| { - (&left.source_path, &left.main_class).cmp(&(&right.source_path, &right.main_class)) - }); - facts.entries.dedup(); - facts -} - -fn is_java_entry_configuration(configuration: &RunConfiguration) -> bool { - matches!( - configuration.provider.as_str(), - "java.main" | "spring-boot.maven" - ) -} - -/// Java sources whose bytes generation reads (it labels Spring Boot entries -/// from them). Derived from the generated entries, so generation and -/// inspection hash exactly the same files. -fn java_entry_sources(configurations: &[RunConfiguration]) -> BTreeSet { - configurations - .iter() - .filter(|configuration| is_java_entry_configuration(configuration)) - .filter_map(|configuration| configuration.extension_string("java", "source")) - .collect() -} - -/// Comparable `(source, class)` pairs for entry points. JDT may prefix a -/// modular class with `module/`; generated entries store the class alone, and -/// nested checkouts are excluded exactly as generation excludes them. -fn java_entrypoint_keys(facts: &JavaEntrypointFacts) -> BTreeSet<(String, String)> { - facts - .entries - .iter() - .filter(|entry| !is_nested_checkout_path(&entry.source_path)) - .map(|entry| { - let source = entry - .source_path - .trim() - .replace('\\', "/") - .trim_matches('/') - .to_string(); - let class = entry - .main_class - .rsplit_once('/') - .map_or(entry.main_class.as_str(), |(_, class)| class) - .to_string(); - (source, class) - }) - .collect() -} - /// Qualifies display names that repeat across directories or modules. /// /// Ids already carry the directory, but the Run list shows only the name: three -/// Compose files each contributing `compose up`, or two modules each declaring -/// `Application`, are otherwise indistinguishable. The qualifier is the first +/// Compose files each contributing `compose up` are otherwise +/// indistinguishable. The qualifier is the first /// candidate that separates every entry in the group, so the shortest useful /// label wins and unique names are never decorated. fn disambiguate_configuration_names(configurations: &mut [RunConfiguration]) { @@ -1196,8 +659,7 @@ fn disambiguate_configuration_names(configurations: &mut [RunConfiguration]) { .push(index); } for indexes in groups.into_values().filter(|indexes| indexes.len() > 1) { - let candidates: [fn(&RunConfiguration) -> Option; 3] = [ - |configuration| configuration.module().filter(|module| module != "."), + let candidates: [fn(&RunConfiguration) -> Option; 2] = [ |configuration| Some(configuration.cwd.clone()).filter(|cwd| cwd != "."), |configuration| configuration.source.clone(), ]; @@ -1218,177 +680,14 @@ fn disambiguate_configuration_names(configurations: &mut [RunConfiguration]) { } } -fn workspace_build_path(build_root: Option<&str>, path: &str) -> String { - match (build_root, path) { - (Some(root), ".") => root.to_string(), - (Some(root), path) if root != "." => format!("{root}/{path}"), - _ => path.to_string(), - } -} - -fn relative_build_project(build_root: Option<&str>, path: &str) -> String { - let Some(root) = build_root.filter(|root| *root != ".") else { - return path.to_string(); - }; - if path == root { - ".".to_string() - } else { - path.strip_prefix(&(root.to_string() + "/")) - .unwrap_or(path) - .to_string() - } -} - -fn maven_owner_for_module( - root: &Path, - workspace_maven_root: Option<&(PathBuf, String)>, - module_path: Option<&str>, -) -> Result, CoreError> { - if let Some(module_path) = module_path { - let descriptor = if module_path == "." { - "pom.xml".to_string() - } else { - format!("{module_path}/pom.xml") - }; - return crate::project::maven_root(root, &[descriptor]); - } - - // A root-level Maven project has no relative module path. Nested reactors - // always contribute at least their reactor directory through module inference. - Ok(workspace_maven_root - .filter(|(_, relative_path)| relative_path == ".") - .cloned()) -} - -/// Whether a service is a Spring Boot service is decided by the build, not by an -/// annotation: `spring-boot-maven-plugin` is what makes `spring-boot:run` work at -/// all, and the Maven detector reads it from the declared module graph. The scan -/// keeps finding main classes -- that is genuinely per-file work -- it just no -/// longer decides what is a service. -/// -/// The annotation is still the only place a *main class* is named, so a scanned -/// `spring:` becomes `java-main:`: the same class -/// is still directly runnable, and the id says which judge produced it. -fn java_configuration_id(value: &crate::protocol::JavaRunConfigurationResponse) -> String { - match (value.kind.as_str(), value.main_class.as_deref()) { - ("springBoot", Some(main_class)) => format!("java-main:{main_class}"), - _ => value.id.clone(), - } -} - -/// Keeps stable ids for the usual one-module case while preserving same-named -/// main classes that belong to different modules. Repeated source paths within -/// one module are genuine duplicates and still collapse to one configuration. -fn deduplicate_java_configurations(configurations: Vec) -> Vec { - let mut grouped = BTreeMap::>::new(); - for configuration in configurations { - let module = java_module_identity(configuration.module().as_deref()); - grouped - .entry(configuration.id.clone()) - .or_default() - .entry((configuration.cwd.clone(), module)) - .or_insert(configuration); - } - - grouped - .into_iter() - .flat_map(|(base_id, modules)| { - let has_module_collision = modules.len() > 1; - let separate_reactors = modules - .keys() - .map(|(root, _)| root) - .collect::>() - .len() - > 1; - modules - .into_iter() - .map(move |((root, module), mut configuration)| { - if has_module_collision { - // Preserve existing single-reactor IDs, but two independent - // reactors can both have a module named `app` and main `Main`. - let module = if separate_reactors { - workspace_build_path(Some(&root), &module) - } else { - module - }; - configuration.id = format!("{base_id}:{module}"); - } - configuration - }) - }) - .collect() -} - -fn java_module_identity(module: Option<&str>) -> String { - let normalized = module - .unwrap_or(".") - .replace('\\', "/") - .split('/') - .filter(|component| !component.is_empty() && *component != ".") - .collect::>() - .join("/"); - if normalized.is_empty() { - ".".to_string() - } else { - normalized - } -} - -/// Keeps a Spring service only when JDT confirmed a unique application entry -/// in that exact module. An applied (possibly inherited) Maven plugin is only -/// a launch capability, never proof that a library module is an application. -/// Ambiguous modules retain their individually selectable Java entries. -fn retain_confirmed_spring_services( - configurations: &mut Vec, - entries: &[crate::protocol::JavaRunConfigurationResponse], - maven_root: Option<&str>, -) { - configurations.retain_mut(|configuration| { - if configuration.provider != "spring-boot.maven" { - return true; - } - let Some(module) = configuration.module() else { - return false; - }; - let workspace_module = workspace_build_path(maven_root, &module); - let mut matches = entries.iter().filter(|entry| { - java_module_identity(entry.module_path.as_deref()) == workspace_module - && entry.source_set != crate::protocol::JavaSourceSetResponse::Test - }); - let Some(entry) = matches.next() else { - return false; - }; - if matches.next().is_some() { - return false; - } - let maven = configuration - .extensions - .entry("maven".to_string()) - .or_insert_with(|| json!({})); - if let Some(object) = maven.as_object_mut() { - object.insert("mainClass".to_string(), json!(entry.main_class)); - } - let source_set = entry.source_set; - configuration.extensions.insert( - "java".to_string(), - json!({ "source": entry.source_path, "sourceSet": source_set }), - ); - true - }); -} - /// Translates detector output into the run-configuration contract. /// /// Nearly every detection is process-based: the detector resolved the command, /// so there is no ecosystem-specific launch assembly. A process may still name /// a runtime requirement for scoped compatibility diagnostics; a detection that /// transfers executable ownership to toolchains carries no command. -fn detected_configurations( - root: &Path, - maven_root: Option<&Path>, - claimed: &BTreeSet, -) -> Result, CoreError> { - Ok(super::detectors::detect_all(root, maven_root)? +fn detected_configurations(root: &Path) -> Result, CoreError> { + Ok(super::detectors::detect_all(root)? .into_iter() .map(|item| RunConfiguration { id: item.id(), @@ -1402,68 +701,16 @@ fn detected_configurations( env: item.env, confidence: item.confidence, toolchains: item.toolchains, - debug: item.debug.map(|adapter| DebugCapability { adapter }), + debug: None, members: Vec::new(), extensions: item.extensions, disabled: false, source: Some(item.source), }) - .filter(|item| !claimed.contains(&item.id)) .filter(|item| validate_configuration(item).is_ok()) .collect()) } -fn inferred_relative_build_projects( - root: &Path, - paths: &[String], - configured: Vec, -) -> Vec { - let mut modules = configured.into_iter().collect::>(); - for path in paths { - if !path.to_lowercase().ends_with(".java") { - continue; - } - let Some(relative) = normalize_project_relative(path) else { - continue; - }; - let mut directory = root.join(relative).parent().map(Path::to_path_buf); - while let Some(candidate) = directory { - if candidate == root { - break; - } - if candidate.join("pom.xml").is_file() { - if let Ok(relative) = candidate.strip_prefix(root) { - modules.insert(relative.to_string_lossy().replace('\\', "/")); - } - break; - } - directory = candidate.parent().map(Path::to_path_buf); - } - } - modules.into_iter().collect() -} - -fn normalize_project_relative(value: &str) -> Option { - let path = Path::new(value); - if path.is_absolute() - || path.components().any(|component| { - matches!( - component, - Component::ParentDir | Component::RootDir | Component::Prefix(_) - ) - }) - { - return None; - } - Some(path.to_path_buf()) -} - -fn is_nested_checkout_path(value: &str) -> bool { - value.split(['/', '\\']).any(|component| { - component.eq_ignore_ascii_case(".worktree") || component.eq_ignore_ascii_case(".worktrees") - }) -} - /// Merges generated, team, and local layers and selects compatible toolchains. pub fn resolve(request: ResolveRequest) -> Result { let root = existing_root(&request.root)?; @@ -1515,13 +762,8 @@ pub fn resolve(request: ResolveRequest) -> Result { } } } - apply_maven_reactor_ownership(&mut configurations, &generated); - apply_build_project_ownership(&mut configurations, &generated); normalize_runtime_consumption(&mut configurations); let global_toolchain = local.get("toolchain").cloned(); - if let Some(toolchain) = global_toolchain.as_ref() { - apply_global_toolchain(&mut configurations, toolchain); - } diagnostics.extend(toolchain_diagnostics( &root, &request.toolchain_candidates, @@ -1554,31 +796,6 @@ pub fn resolve(request: ResolveRequest) -> Result { })); continue; } - if let Some(module) = configuration.module().filter(|value| value != ".") { - // `maven.module` is relative to the reactor that owns the entry, not - // to the effective `cwd`: a user-chosen working directory such as - // the module itself must not turn `web` into `web/web`. Entries - // without detected ownership were validated against the root. - let reactor = configuration - .extensions - .get("java") - .and_then(|java| java.get("build")) - .and_then(|build| build.get("root")) - .and_then(Value::as_str) - .map(str::to_owned) - .or_else(|| configuration.extension_string("maven", "reactorPath")) - .unwrap_or_else(dot); - let workspace_module = workspace_build_path(Some(&reactor), &module); - if !project_directory_exists(&root, &workspace_module) { - configuration.disabled = true; - diagnostics.push(json!({ - "id": configuration.id, - "code": "missingModule", - "message": format!("Module directory does not exist: {module}") - })); - continue; - } - } if !project_directory_exists(&root, &configuration.cwd) { configuration.disabled = true; diagnostics.push(json!({ @@ -1586,24 +803,6 @@ pub fn resolve(request: ResolveRequest) -> Result { "code": "missingWorkingDirectory", "message": format!("Working directory does not exist: {}", configuration.cwd) })); - continue; - } - // Whether the class is launchable is JDT's answer at launch time; here - // only the source file the entry was generated from must still exist. - // `extensions.java.source` is the Java file the entry came from; - // `configuration.source` names a layer or detector manifest instead. - let entry_source = configuration - .extension_string("java", "source") - .filter(|_| configuration.main_class().is_some()); - if let Some(source) = entry_source { - if invalid_relative_path(&source) || !root.join(&source).is_file() { - configuration.disabled = true; - diagnostics.push(json!({ - "id": configuration.id, - "code": "missingMainClass", - "message": format!("Main class source no longer exists: {source}") - })); - } } } configurations.retain(|configuration| !configuration.disabled); @@ -1640,7 +839,7 @@ pub fn resolve(request: ResolveRequest) -> Result { } /// Prefer a detected service when the project names no default, otherwise -/// select the first available entry other than Current File. +/// select the first available entry. fn detected_default( generated: &RunConfigurationDocument, available: &[RunConfiguration], @@ -1657,18 +856,14 @@ fn detected_default( by_selector.entry(selector).or_insert(configuration); } } - let detected = generated - .configurations - .iter() - .filter(|configuration| configuration.id != "current-file") - .filter_map(|configuration| { - by_id.get(configuration.id.as_str()).copied().or_else(|| { - let selector = super::provider_runs::selector( - &serde_json::to_value(configuration).expect("configuration encodes"), - )?; - by_selector.get(&selector).copied() - }) - }); + let detected = generated.configurations.iter().filter_map(|configuration| { + by_id.get(configuration.id.as_str()).copied().or_else(|| { + let selector = super::provider_runs::selector( + &serde_json::to_value(configuration).expect("configuration encodes"), + )?; + by_selector.get(&selector).copied() + }) + }); detected .clone() .find(|configuration| configuration.execution == Execution::Service) @@ -1676,109 +871,6 @@ fn detected_default( .map(|configuration| configuration.id.clone()) } -/// Retains the detected reactor independently of team/local working-directory overrides. -fn apply_maven_reactor_ownership(configurations: &mut [RunConfiguration], generated: &Value) { - let owners: BTreeMap<_, _> = generated["configurations"] - .as_array() - .into_iter() - .flatten() - .filter(|value| value["toolchains"]["maven"].is_string()) - .filter_map(|value| Some((value["id"].as_str()?, value["cwd"].as_str().unwrap_or(".")))) - .collect(); - for configuration in configurations { - // Ownership comes from detection, never from an override or effective cwd. - if let Some(extension) = configuration - .extensions - .get_mut("maven") - .and_then(Value::as_object_mut) - { - extension.remove("reactorPath"); - } - if configuration.provider == "java.current-file" { - continue; - } - if let Some(reactor) = owners.get(configuration.id.as_str()) { - if let Some(extension) = configuration - .extensions - .entry("maven".to_string()) - .or_insert_with(|| json!({})) - .as_object_mut() - { - extension.insert("reactorPath".to_string(), json!(reactor)); - } - } - } -} - -/// Build identity is a current model fact, never a user override or inferred cwd. -fn apply_build_project_ownership(configurations: &mut [RunConfiguration], generated: &Value) { - let owners = generated["configurations"] - .as_array() - .into_iter() - .flatten() - .filter_map(|value| { - Some(( - value["id"].as_str()?, - value["extensions"]["java"].get("build")?.clone(), - )) - }) - .collect::>(); - for configuration in configurations { - if let Some(java) = configuration - .extensions - .get_mut("java") - .and_then(Value::as_object_mut) - { - java.remove("build"); - } - if let Some(owner) = owners.get(configuration.id.as_str()) { - // A null or scalar namespace must not revoke a current model owner. - let java = configuration - .extensions - .entry("java".into()) - .or_insert_with(|| json!({})); - if !java.is_object() { - *java = json!({}); - } - java.as_object_mut() - .expect("normalized namespace") - .insert("build".into(), owner.clone()); - } - } -} - -fn apply_global_toolchain(configurations: &mut [RunConfiguration], toolchain: &Value) { - let java_home = toolchain["java"]["homePath"].as_str().unwrap_or(""); - let maven_executable = toolchain["maven"]["executablePath"].as_str().unwrap_or(""); - let maven_java_home = toolchain["maven"]["javaHomePath"].as_str().unwrap_or(""); - for configuration in configurations { - if !configuration.toolchains.contains_key("java") - && !configuration.toolchains.contains_key("maven") - { - continue; - } - let java = configuration - .extensions - .entry("java".to_string()) - .or_insert_with(|| json!({})); - if let Some(object) = java.as_object_mut() { - insert_toolchain_default(object, "homePath", java_home); - insert_toolchain_default(object, "mavenExecutablePath", maven_executable); - insert_toolchain_default(object, "mavenJavaHomePath", maven_java_home); - } - } -} - -fn insert_toolchain_default(object: &mut serde_json::Map, key: &str, value: &str) { - let has_override = object - .get(key) - .and_then(Value::as_str) - .is_some_and(|configured| !configured.trim().is_empty()); - if !has_override { - object.insert(key.to_string(), json!(value)); - } -} - /// Persists editable configuration options in the requested ownership layer. pub fn update_options(mut request: UpdateOptionsRequest) -> Result { let root = existing_root(&request.root)?; @@ -1831,6 +923,9 @@ pub fn save_editor_changes(mut request: UpdateOptionsRequest) -> Result, @@ -1838,32 +933,15 @@ fn update_toolchain_document( ) -> Result { let mut document = local_layer_document(root, local_document)?; validate_version_value(&document)?; - let preferences = toolchain - .preferences - .or_else(|| document["toolchain"].get("preferences").cloned()); - let overrides = toolchain - .path_overrides - .map(|value| json!(value)) - .or_else(|| { - document - .get("toolchain") - .and_then(|value| value.get("pathOverrides")) - .cloned() - }); - document["toolchain"] = json!({ - "java": { "homePath": toolchain.java_home_path }, - "maven": { - "executablePath": toolchain.maven_executable_path, - "javaHomePath": toolchain.maven_java_home_path - } - }); - if let Some(overrides) = overrides { - document["toolchain"]["pathOverrides"] = overrides; - } - if let Some(preferences) = preferences { - document["toolchain"]["preferences"] = preferences; + let mut saved = document["toolchain"] + .as_object() + .cloned() + .unwrap_or_default(); + if let Some(preferences) = toolchain.preferences { + saved.insert("preferences".to_string(), preferences); } - validate_toolchain_path_overrides(&document)?; + document["toolchain"] = Value::Object(saved); + validate_tool_preferences(&document)?; Ok(document) } @@ -1918,7 +996,6 @@ fn update_configuration_options( .ok_or_else(|| { CoreError::new(ErrorCode::InvalidRequest, "Run configuration was not found") })?; - let uses_maven_capability = is_maven_backed(provider); if let Some(options) = &request.provider_run_options { if provider != "build.provider" { return Err(CoreError::new( @@ -1928,12 +1005,6 @@ fn update_configuration_options( } options.validate()?; } - let java_home_path = - normalize_scoped_toolchain_path(&root, &request.scope, &request.java_home_path)?; - let maven_executable_path = - normalize_scoped_toolchain_path(&root, &request.scope, &request.maven_executable_path)?; - let maven_java_home_path = - normalize_scoped_toolchain_path(&root, &request.scope, &request.maven_java_home_path)?; let working_directory = if request.working_directory.trim().is_empty() { None } else { @@ -1959,52 +1030,11 @@ fn update_configuration_options( if let Some(working_directory) = working_directory.as_ref() { patch["cwd"] = json!(working_directory); } - let mut java_extension = serde_json::Map::new(); - if !java_home_path.is_empty() { - java_extension.insert("homePath".to_string(), json!(java_home_path)); - } - if !maven_executable_path.is_empty() { - java_extension.insert( - "mavenExecutablePath".to_string(), - json!(maven_executable_path), - ); - } - if !maven_java_home_path.is_empty() { - java_extension.insert("mavenJavaHomePath".to_string(), json!(maven_java_home_path)); - } + patch["args"] = json!(split_arguments(&request.arguments)); if provider == "build.provider" { - patch["args"] = json!(split_arguments(&request.arguments)); if let Some(options) = &request.provider_run_options { patch["extensions"] = json!({"build-run":options}); } - } else if uses_maven_capability { - let mut maven_extension = serde_json::Map::from_iter([ - ( - "jvmArguments".to_string(), - json!(split_arguments(&request.jvm_arguments)), - ), - ( - "programArguments".to_string(), - json!(split_arguments(&request.arguments)), - ), - ( - "profiles".to_string(), - json!(request.maven_profiles.into_iter().collect::>()), - ), - ]); - if let Some(skip_tests) = request.maven_skip_tests { - maven_extension.insert("skipTests".to_string(), json!(skip_tests)); - } - let mut extensions = - serde_json::Map::from_iter([("maven".to_string(), Value::Object(maven_extension))]); - if !java_extension.is_empty() { - extensions.insert("java".to_string(), Value::Object(java_extension)); - } - patch["extensions"] = Value::Object(extensions); - } else if !java_extension.is_empty() { - patch["extensions"] = json!({ "java": java_extension }); - } else { - patch["args"] = json!(split_arguments(&request.arguments)); } if let Some(existing) = configurations .iter_mut() @@ -2016,13 +1046,9 @@ fn update_configuration_options( "Run configuration must be an object", ) })?; - remove_java_toolchain_overrides(target)?; if working_directory.is_none() { target.remove("cwd"); } - if uses_maven_capability && request.maven_skip_tests.is_none() { - remove_maven_skip_tests_override(target); - } for (key, value) in patch.as_object_mut().expect("patch is an object") { if key == "extensions" { merge_extensions(target, value)?; @@ -2042,50 +1068,6 @@ fn update_configuration_options( Ok(document) } -fn remove_java_toolchain_overrides( - configuration: &mut serde_json::Map, -) -> Result<(), CoreError> { - let Some(extensions) = configuration.get_mut("extensions") else { - return Ok(()); - }; - let extensions = extensions.as_object_mut().ok_or_else(|| { - CoreError::new( - ErrorCode::ParseFailed, - "Run configuration extensions must be an object", - ) - })?; - if let Some(java) = extensions.get_mut("java") { - let java = java.as_object_mut().ok_or_else(|| { - CoreError::new( - ErrorCode::ParseFailed, - "Run configuration Java extension must be an object", - ) - })?; - for key in ["homePath", "mavenExecutablePath", "mavenJavaHomePath"] { - java.remove(key); - } - if java.is_empty() { - extensions.remove("java"); - } - } - if extensions.is_empty() { - configuration.remove("extensions"); - } - Ok(()) -} - -fn remove_maven_skip_tests_override(configuration: &mut serde_json::Map) { - let Some(maven) = configuration - .get_mut("extensions") - .and_then(Value::as_object_mut) - .and_then(|extensions| extensions.get_mut("maven")) - .and_then(Value::as_object_mut) - else { - return; - }; - maven.remove("skipTests"); -} - /// Only explicit provider references make an ungenerated workspace runnable. fn has_saved_build_run(document: &Value) -> bool { document["configurations"] @@ -2185,167 +1167,32 @@ fn create_build_provider_configuration( let typed: RunConfiguration = serde_json::from_value(configuration.clone()) .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration"))?; validate_configuration(&typed)?; - if let Some(index) = existing { - items[index] = configuration; - } else { - items.push(configuration); - } - items.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str())); - Ok( - json!({"id":id,"document":serde_json::to_string_pretty(&document).expect("document encodes")}), - ) -} - -/// Creates a user configuration while preserving stable IDs in existing layers. -pub fn create_user_configuration( - request: CreateUserConfigurationRequest, -) -> Result { - let root = existing_root(&request.root)?; - if request.kind == "buildProvider" { - return create_build_provider_configuration(&root, &request); - } - if request.build.is_some() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Build reference requires a buildProvider configuration", - )); - } - let relative = scope_document(&request.scope)?; - let name = request.name.trim(); - if name.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Configuration name is required", - )); - } - let configuration_kind = match request.kind.as_str() { - "springBoot" => "spring-boot.maven", - "quarkus" => "quarkus.maven", - "micronaut" => "micronaut.maven", - "mavenModule" => "maven.module", - _ => { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Only Maven framework and Maven Module configurations can be created", - )); - } - }; - let module = normalize_project_directory( - &root, - if request.module.trim().is_empty() { - "." - } else { - request.module.trim() - }, - )?; - let main_class = request.main_class.trim(); - if configuration_kind == "spring-boot.maven" { - if main_class.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Spring Boot main class is required", - )); - } - } - let mut existing_ids = detected_ids(&root); - for source in ["run/configurations.json", "run/local.json"] { - if let Some(document) = read_document_value(&root, source)? { - validate_version_value(&document)?; - existing_ids.extend(configuration_ids(&document)?.into_keys()); - } - } - let id = unique_user_configuration_id(name, &existing_ids); - let mut document = read_document_value(&root, relative)? - .unwrap_or_else(|| json!({"version": VERSION, "configurations": []})); - validate_version_value(&document)?; - let configurations = document["configurations"] - .as_array_mut() - .ok_or_else(|| CoreError::new(ErrorCode::ParseFailed, "configurations must be an array"))?; - let mut maven = json!({ - "module": module, - "jvmArguments": [], - "programArguments": [], - "profiles": [] - }); - if !main_class.is_empty() { - maven["mainClass"] = json!(main_class); + if let Some(index) = existing { + items[index] = configuration; + } else { + items.push(configuration); } - let configuration = json!({ - "id": id, - "name": name, - "provider": configuration_kind, - // A framework goal starts something long-running; a bare Maven goal runs to - // completion. - "execution": if framework_goal(configuration_kind).is_some() { "service" } else { "task" }, - "confidence": "native", - "toolchains": {"java": "project-jdk", "maven": "project-maven"}, - "debug": {"adapter": "jdwp"}, - "extensions": {"maven": maven} - }); - configurations.push(configuration); - configurations.sort_by(|left, right| { - left["id"] - .as_str() - .unwrap_or("") - .cmp(right["id"].as_str().unwrap_or("")) - }); - Ok(json!({ - "id": id, - "document": serde_json::to_string_pretty(&document).expect("document should encode") - })) -} - -/// Builds the workspace-relative directory that receives compiled `.class` -/// files for a standalone Java run. -/// -/// Output is namespaced per configuration so concurrent runs of different files -/// do not clobber each other, and lives under `.lithe/run` where the run store -/// already writes generated artifacts and maintains the gitignore. -fn compile_output_directory(configuration_id: &str) -> String { - format!( - ".lithe/run/classes/{}", - sanitize_path_segment(configuration_id) + items.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str())); + Ok( + json!({"id":id,"document":serde_json::to_string_pretty(&document).expect("document encodes")}), ) } -/// Replaces characters that are unsafe in a single path segment with `-`. -/// -/// Configuration ids such as `java-main:com.example.App` contain `:`, which is -/// illegal in Windows file names, so the segment is normalized to -/// `[A-Za-z0-9._-]` while staying deterministic. -fn sanitize_path_segment(value: &str) -> String { - value - .chars() - .map(|character| { - if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') { - character - } else { - '-' - } - }) - .collect() -} - -/// Assembles a `javac` pre-launch step compiling `source` into `output_dir`. +/// Creates a user configuration while preserving stable IDs in existing layers. /// -/// The step reuses the run's Java toolchain via `tool: "javac"`; the host -/// resolves the sibling compiler and joins `classpath` with the platform -/// separator. `classpath` is omitted when empty so bare standalone files carry -/// no extra fields. -fn javac_compile_step( - java_toolchain: &str, - output_dir: &str, - source: &str, - classpath: &[Value], -) -> Value { - let mut step = json!({ - "executable": { "toolchain": java_toolchain, "tool": "javac" }, - "arguments": ["-d", output_dir, source], - }); - if !classpath.is_empty() { - step["classpath"] = Value::Array(classpath.to_vec()); +/// Only build provider references can be authored: every other runnable entry +/// is declared by the plugin that owns its launch semantics. +pub fn create_user_configuration( + request: CreateUserConfigurationRequest, +) -> Result { + let root = existing_root(&request.root)?; + if request.kind == "buildProvider" { + return create_build_provider_configuration(&root, &request); } - step + Err(CoreError::new( + ErrorCode::NotSupported, + "Only build provider configurations can be created", + )) } /// Extracts existing Run document values; framework goals and runtime semantics stay in providers. @@ -2441,24 +1288,16 @@ pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result` rather than -/// `java .java`, because the single-file source launcher (JEP 330) is a -/// JDK 11+ feature and would fail on JDK 8. See the Agent Note -/// `2026-09-17-standalone-java-compile-then-run`. +/// Core only assembles process-based plans: a detector or provider either named +/// the command, or transferred executable ownership to a runtime toolchain. +/// Ecosystem launch semantics stay in the plugin that declared the run. pub fn create_launch_plan(request: LaunchPlanRequest) -> Result { - let workspace_root = existing_root(&request.root)?; - let has_explicit_cwd_override = configuration_override_has_key( - &workspace_root, - request.local_document.as_ref(), - &request.configuration_id, - "cwd", - )?; + existing_root(&request.root)?; let resolved = resolve(ResolveRequest { team_document: None, - root: request.root.clone(), + root: request.root, toolchain_candidates: Vec::new(), - local_document: request.local_document.clone(), + local_document: request.local_document, })?; let config = resolved["configurations"] .as_array() @@ -2472,11 +1311,6 @@ pub fn create_launch_plan(request: LaunchPlanRequest) -> Result Result = Vec::new(); - let mut plan_classpath: Vec = Vec::new(); - let mut plan_modulepath: Vec = Vec::new(); - let java_toolchain = config["toolchains"]["java"] - .as_str() - .unwrap_or("project-jdk") - .to_string(); - let is_current = provider == "java.current-file"; - let is_java_main = provider == "java.main"; - let uses_maven_toolchain = config["toolchains"]["maven"] - .as_str() - .is_some_and(|value| !value.is_empty()); - let is_direct_java_project_launch = (is_java_main && request.java_launch.is_some()) - || (uses_maven_toolchain - && (is_java_main - || (provider == "spring-boot.maven" - && config["extensions"]["java"]["source"].is_string()))); - let goal = framework_goal(provider); - // A framework that owns its own debug agent takes a port instead of raw JVM - // flags, so JDWP must not also be forced into `jvmArguments`: two agents on - // one port fail to bind and the service never starts. - let jvm_agent_debug = goal.map_or(true, |goal| matches!(goal.debug, FrameworkDebug::JvmAgent)); - if let Some(port) = request.debug_port.filter(|_| jvm_agent_debug) { - jvm_arguments.insert( - 0, - json!(format!( - "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{port}" - )), - ); - jvm_arguments.insert(1, json!("-Duser.language=en")); - jvm_arguments.insert(2, json!("-Duser.country=US")); - if is_direct_java_project_launch { - jvm_arguments.push(json!(crate::debug::JAVA_DEBUG_DISABLE_DEVTOOLS_RESTART)); - } - } - if is_current { - let current_file = request.current_file.clone().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Current File requires a Java source path", - ) - })?; - if invalid_relative_path(¤t_file) || !current_file.to_lowercase().ends_with(".java") { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Current Java source path is invalid", - )); - } - // Compile then launch by class name instead of `java .java`: the - // single-file source launcher (JEP 330) only exists on JDK 11+, so a - // JDK 8 project fails to load `File.java` as a class. Reading the source - // yields the qualified class the JVM will resolve after compilation. - let source_text = crate::languages::read_text(&workspace_root.join(¤t_file)) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Current Java source could not be read", - ) - .with_details(error.to_string()) - })?; - let main_class = crate::languages::standalone_launch_class(¤t_file, &source_text); - let output_directory = compile_output_directory(&request.configuration_id); - // Compiled output leads the classpath so a fresh build shadows any stale - // class; the host prepends any project classpath the request supplies. - plan_classpath.push(json!(output_directory)); - let mut compile_classpath: Vec = Vec::new(); - if let Some(class_path) = request.class_path.clone().filter(|value| !value.is_empty()) { - plan_classpath.push(json!(class_path)); - compile_classpath.push(json!(class_path)); - } - pre_launch_steps.push(javac_compile_step( - &java_toolchain, - &output_directory, - ¤t_file, - &compile_classpath, - )); - arguments.extend(jvm_arguments); - arguments.push(json!(main_class)); - arguments.extend(program_arguments); - } else if is_direct_java_project_launch { - let java_launch = request.java_launch.as_ref().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java project launch metadata is unavailable; wait for the Java language service and try again", - ) - })?; - if java_launch.class_paths.is_empty() && java_launch.module_paths.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java project launch metadata contains no runtime paths", - )); - } - if java_launch.main_class.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java project launch metadata is missing its main class", - )); - } - let _configured_main = maven["mainClass"].as_str().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java project launch is missing its main class", - ) - })?; - // JDT already built and resolved the target's paths. This applies to - // unmanaged and Gradle projects too; never compile the one source again - // with javac and discard upstream dependency/module paths. - plan_classpath.extend(java_launch.class_paths.iter().cloned().map(Value::String)); - plan_modulepath.extend(java_launch.module_paths.iter().cloned().map(Value::String)); - arguments.extend(jvm_arguments); - if java_launch.main_class.split_once('/').is_some() { - // JDT prefixes JPMS targets as `module/name.Type`. Java Debug - // Server accepts that identity directly, while the `java` CLI - // requires the module launcher flag. - arguments.push(json!("-m")); - } - arguments.push(json!(java_launch.main_class)); - arguments.extend(program_arguments); - // Only Maven owns a resource-processing phase; unmanaged and Gradle - // targets launch directly from the JDT paths. A host receipt that the - // provider task already prepared resources also skips the Maven step. - if uses_maven_toolchain && !java_launch.build_prepared { - // JDT's incremental build is not Maven's resource-processing phase. - // Maven owns filtering, custom resource roots and reactor dependencies. - let reactor_path = maven["reactorPath"].as_str().unwrap_or("."); - let mut context = request.maven_context.clone().unwrap_or( - crate::project::MavenLaunchContextRequest { - version: 1, - reactor_path: reactor_path.to_string(), - profiles: Vec::new(), - settings_path: None, - local_repository_path: None, - skip_tests: false, - maven_executable_path: None, - java_home_path: None, - }, - ); - context.reactor_path = reactor_path.to_string(); - let mut resource_module = maven["module"].as_str().map(str::to_string); - if let Some(module) = resource_module.as_deref().filter(|module| *module != ".") { - let reactor_root = workspace_root.join(reactor_path); - let declared = crate::project::declared_modules(&reactor_root)?; - if !declared - .iter() - .any(|candidate| candidate.relative_path == module) - { - // An independently imported child POM is not selectable with -pl. - // Let the shared planner validate its own project boundary instead. - context.reactor_path = format!("{reactor_path}/{module}"); - resource_module = None; - } - } - if let Some(profiles) = maven["profiles"] - .as_array() - .filter(|items| !items.is_empty()) - { - context.profiles = profiles - .iter() - .filter_map(Value::as_str) - .map(str::to_string) - .collect(); - } - if let Some(skip_tests) = maven.get("skipTests").and_then(Value::as_bool) { - context.skip_tests = skip_tests; - } - let reactor_pom = workspace_root.join(&context.reactor_path).join("pom.xml"); - let mut resource_arguments = vec![ - "-f".to_string(), - reactor_pom.to_string_lossy().into_owned(), - "resources:resources".to_string(), - ]; - if config["extensions"]["java"]["sourceSet"] == "test" { - resource_arguments.push("resources:testResources".to_string()); - } - let resource_plan = crate::project::launch_plan_with_arguments( - request.root.clone(), - context, - resource_module, - resource_arguments, - true, - )?; - pre_launch_steps.push(json!({ - "executable": resource_plan.executable, - "arguments": resource_plan.arguments, - // The reactor directory is the step's own resolution root: the host - // finds the project's Maven wrapper there even when the application - // working directory is overridden, and the absolute `-f` above keeps - // the POM anchored. - "workingDirectory": resource_plan.working_directory, - })); - } - } else if is_java_main { - let source = config["extensions"]["java"]["source"] - .as_str() - .filter(|value| !value.is_empty()) - .ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java application is missing its source path", - ) - })?; - if invalid_relative_path(source) || !source.to_lowercase().ends_with(".java") { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java source path is invalid", - )); - } - if crate::project::maven_root(&workspace_root, &[source.to_string()])?.is_some() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java application belongs to a Maven project; regenerate run configurations", - ) - .with_details(source)); - } - // Standalone `java.main` compiles then launches by class name for the - // same JDK 8 compatibility reason as Current File above. The qualified - // main class is normally recorded at generation time; fall back to - // reading the source so hand-written configurations still launch. - let main = match maven["mainClass"] - .as_str() - .filter(|value| !value.is_empty()) - { - Some(main_class) => main_class.to_string(), - None => { - let source_text = crate::languages::read_text(&workspace_root.join(source)) - .map_err(|error| { - CoreError::new(ErrorCode::InvalidRequest, "Java source could not be read") - .with_details(error.to_string()) - })?; - crate::languages::standalone_launch_class(source, &source_text) - } - }; - let output_directory = compile_output_directory(&request.configuration_id); - plan_classpath.push(json!(output_directory)); - pre_launch_steps.push(javac_compile_step( - &java_toolchain, - &output_directory, - source, - &[], - )); - arguments.extend(jvm_arguments); - arguments.push(json!(main)); - arguments.extend(program_arguments); - } else { - // `maven.module` has no framework goal: it runs whatever goals the - // configuration names, so only the reactor selection applies. - if request.maven_context.is_none() { - arguments.extend([json!("-B"), json!("-ntp")]); - if let Some(module) = maven["module"].as_str().filter(|m| *m != ".") { - arguments.extend([json!("-pl"), json!(module), json!("-am")]); - } - if let Some(profiles) = maven["profiles"].as_array().filter(|p| !p.is_empty()) { - arguments.extend([ - json!("-P"), - json!(profiles - .iter() - .filter_map(Value::as_str) - .collect::>() - .join(",")), - ]); - } - } - if let Some(goal) = goal { - arguments.extend(framework_arguments( - goal, - maven, - &jvm_arguments, - &program_arguments, - request.debug_port, - )); - arguments.push(json!(goal.goal)); - } - } - let executable_kind = if is_current || is_direct_java_project_launch || is_java_main { - "java" - } else { - "maven" - }; - let executable_toolchain = config["toolchains"][executable_kind] - .as_str() - .ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Run configuration is missing its executable toolchain", - ) - .with_details(executable_kind) - })?; - let mut working_directory = config["cwd"].as_str().unwrap_or(".").to_string(); - let has_explicit_working_directory = working_directory != "." || has_explicit_cwd_override; - if executable_kind == "maven" { - if let Some(mut context) = request.maven_context { - if let Some(profiles) = maven["profiles"] - .as_array() - .filter(|items| !items.is_empty()) - { - context.profiles = profiles - .iter() - .filter_map(Value::as_str) - .map(str::to_string) - .collect(); - } - if let Some(skip_tests) = maven.get("skipTests").and_then(Value::as_bool) { - context.skip_tests = skip_tests; - } - let module = maven["module"].as_str().map(str::to_string); - let trailing_arguments = arguments - .into_iter() - .filter_map(|value| value.as_str().map(str::to_string)) - .collect(); - let shared_plan = crate::project::launch_plan_with_arguments( - request.root, - context, - module, - trailing_arguments, - true, - )?; - arguments = shared_plan - .arguments - .into_iter() - .map(Value::String) - .collect(); - if !has_explicit_working_directory { - working_directory = shared_plan.working_directory; - } - } - } - let mut plan = json!({ - "executable": { "toolchain": executable_toolchain }, - "arguments": arguments, - "workingDirectory": working_directory, - "environment": { - "JAVA_HOME": { "toolchain": java_toolchain, "property": "home" } - } - }); - // Optional fields stay absent for ordinary process and Maven-goal plans. - // Direct Java project launches carry the paths their language model resolved. - if !pre_launch_steps.is_empty() { - plan["preLaunchSteps"] = Value::Array(pre_launch_steps); - } - if !plan_classpath.is_empty() { - plan["classpath"] = Value::Array(plan_classpath); - } - if !plan_modulepath.is_empty() { - plan["modulepath"] = Value::Array(plan_modulepath); - } - Ok(plan) + Err(CoreError::new( + ErrorCode::InvalidRequest, + "Run provider must declare a command or runtime toolchain", + ) + .with_details(config["provider"].as_str().unwrap_or(""))) } /// Returns whether a user-owned layer explicitly sets one configuration key. /// -/// Generated `cwd: "."` is the schema default and may inherit the selected -/// reactor. A project or local `cwd: "."`, however, is an intentional override +/// Generated `cwd: "."` is the schema default and may inherit the provider +/// root. A project or local `cwd: "."`, however, is an intentional override /// and must keep the workspace root. fn configuration_override_has_key( root: &Path, @@ -2882,132 +1354,13 @@ fn configuration_override_has_key( Ok(false) } -/// Providers the launch layer assembles a JVM command line for, rather than -/// spawning a process the detector described. -/// -/// These are the providers whose `Detected` names toolchains instead of a -/// command, so `create_launch_plan` has to know each one. Every other ecosystem -/// is dispatched from the configuration itself and needs no entry here. -fn is_maven_backed(provider: &str) -> bool { - matches!(provider, "java.current-file" | "java.main" | "maven.module") - || framework_goal(provider).is_some() -} - -/// How a framework's Maven goal expects a debugger to be attached. -#[derive(Clone, Copy, PartialEq)] -enum FrameworkDebug { - /// The goal forwards JVM arguments verbatim, so JDWP goes in among them. - JvmAgent, - /// The goal starts the agent itself, given a port. `properties` are appended - /// in order with the port substituted for `{port}`. - Managed(&'static [&'static str]), -} - -/// A framework's `mvn` goal and the property names its arguments travel under. -/// -/// Each plugin invented its own names for the same three things, so the goal name -/// alone is not enough to launch one: passing Spring's `-Dspring-boot.run.*` to -/// `quarkus:dev` is silently ignored and the service starts with none of the -/// user's arguments. Grouping the names with the goal keeps that mapping in one -/// place per framework. -struct FrameworkGoal { - goal: &'static str, - /// Property carrying JVM arguments as one space-joined string. - jvm_arguments: &'static str, - /// Property carrying application arguments as one space-joined string. - program_arguments: &'static str, - /// Property naming the main class, where the goal accepts one. Quarkus and - /// Micronaut resolve it from the build instead, so only Spring Boot has one. - main_class: Option<&'static str>, - debug: FrameworkDebug, -} - -/// Verified against each plugin's own goal documentation: Spring Boot's -/// `spring-boot:run`, Quarkus' `DevMojo` (`${jvm.args}`, `${quarkus.args}`, -/// `${debug}`, `${suspend}`), and the Micronaut plugin's `run` mojo (`mn.jvmArgs`, -/// `mn.appArgs`, `mn.debug*`). -fn framework_goal(provider: &str) -> Option<&'static FrameworkGoal> { - const SPRING_BOOT: FrameworkGoal = FrameworkGoal { - goal: "spring-boot:run", - jvm_arguments: "spring-boot.run.jvmArguments", - program_arguments: "spring-boot.run.arguments", - main_class: Some("spring-boot.run.main-class"), - debug: FrameworkDebug::JvmAgent, - }; - // Quarkus dev mode already listens on 5005 without suspending. An explicit - // port plus `suspend=y` matches what the IDE needs: the debugger must be - // attached before the service gets past startup, or breakpoints in - // initialisation never hit. - const QUARKUS: FrameworkGoal = FrameworkGoal { - goal: "quarkus:dev", - jvm_arguments: "jvm.args", - program_arguments: "quarkus.args", - main_class: None, - debug: FrameworkDebug::Managed(&["-Ddebug={port}", "-Dsuspend=y"]), - }; - const MICRONAUT: FrameworkGoal = FrameworkGoal { - goal: "mn:run", - jvm_arguments: "mn.jvmArgs", - program_arguments: "mn.appArgs", - main_class: None, - debug: FrameworkDebug::Managed(&[ - "-Dmn.debug=true", - "-Dmn.debug.port={port}", - "-Dmn.debug.suspend=true", - ]), - }; - match provider { - "spring-boot.maven" => Some(&SPRING_BOOT), - "quarkus.maven" => Some(&QUARKUS), - "micronaut.maven" => Some(&MICRONAUT), - _ => None, - } -} - -/// The `-D` properties that carry a configuration's options into a framework -/// goal. Order is fixed so a plan is reproducible across calls. -fn framework_arguments( - goal: &FrameworkGoal, - maven: &Value, - jvm_arguments: &[Value], - program_arguments: &[Value], - debug_port: Option, -) -> Vec { - let mut arguments = Vec::new(); - if let (Some(property), Some(main)) = (goal.main_class, maven["mainClass"].as_str()) { - arguments.push(json!(format!("-D{property}={main}"))); - } - if !jvm_arguments.is_empty() { - arguments.push(json!(format!( - "-D{}={}", - goal.jvm_arguments, - string_arguments(jvm_arguments) - ))); - } - if !program_arguments.is_empty() { - arguments.push(json!(format!( - "-D{}={}", - goal.program_arguments, - string_arguments(program_arguments) - ))); - } - if let (Some(port), FrameworkDebug::Managed(properties)) = (debug_port, goal.debug) { - arguments.extend( - properties - .iter() - .map(|property| json!(property.replace("{port}", &port.to_string()))), - ); - } - arguments -} - /// Launch plan for configurations that name their own executable. /// /// `executable.command` is a bare program name resolved on PATH by the host, as /// opposed to `executable.toolchain` which the host resolves from its toolchain /// registry. The two are mutually exclusive and the host branches on which key -/// is present. No JAVA_HOME is injected -- a Go or Node service has no use for -/// it, and injecting it would leak a Java assumption into every ecosystem. +/// is present. No toolchain home variable is injected: the plan carries only +/// the configuration's own environment. fn process_launch_plan(config: &Value, command: &str) -> Result { if command.contains('/') || command.contains('\\') { return Err(CoreError::new( @@ -3055,21 +1408,13 @@ fn toolchain_process_launch_plan(config: &Value, toolchain: &str) -> Result String { - values - .iter() - .filter_map(Value::as_str) - .collect::>() - .join(" ") -} - fn validate_version_value(document: &Value) -> Result<(), CoreError> { let version = document.get("version").and_then(Value::as_u64).unwrap_or(0) as u32; validate_version(version)?; - validate_toolchain_path_overrides(document) + validate_tool_preferences(document) } -fn validate_toolchain_path_overrides(document: &Value) -> Result<(), CoreError> { +fn validate_tool_preferences(document: &Value) -> Result<(), CoreError> { if let Some(preferences) = document .get("toolchain") .and_then(|value| value.get("preferences")) @@ -3077,42 +1422,6 @@ fn validate_toolchain_path_overrides(document: &Value) -> Result<(), CoreError> crate::toolchain::preferences::validate(preferences) .map_err(|error| CoreError::new(ErrorCode::InvalidRequest, error.message))?; } - let Some(value) = document - .get("toolchain") - .and_then(|value| value.get("pathOverrides")) - else { - return Ok(()); - }; - let invalid = || { - CoreError::new(ErrorCode::InvalidRequest, "Subproject toolchain paths must use bounded workspace-relative roots and valid tool paths") - }; - let overrides = value.as_object().ok_or_else(invalid)?; - if overrides.len() > 256 { - return Err(invalid()); - } - for (path, value) in overrides { - if path.is_empty() - || path.len() > 1024 - || path.contains(['\\', ':']) - || path.chars().any(char::is_control) - || path - .split('/') - .any(|part| part.is_empty() || matches!(part, "." | "..")) - { - return Err(invalid()); - } - let paths: PathToolchainOverride = - serde_json::from_value(value.clone()).map_err(|_| invalid())?; - for value in [ - &paths.java_home_path, - &paths.maven_executable_path, - &paths.maven_java_home_path, - ] { - if value.len() > 4096 || value.trim() != value || value.chars().any(char::is_control) { - return Err(invalid()); - } - } - } Ok(()) } @@ -3307,8 +1616,8 @@ fn normalize_runtime_consumption(configurations: &mut [RunConfiguration]) { /// Deep-merges the `extensions` object one namespace at a time. /// -/// A shallow insert would let a layer that touches a single maven key drop the -/// whole npm namespace it never mentioned. +/// A shallow insert would let a layer that touches a single `build-run` key +/// drop the whole `npm` namespace it never mentioned. fn merge_extensions( target: &mut serde_json::Map, patch: &mut Value, @@ -3427,18 +1736,12 @@ fn validate_configuration(configuration: &RunConfiguration) -> Result<(), CoreEr )); } } - let module = configuration.module().unwrap_or_else(|| ".".to_string()); - for (field, value) in [ - ("module", module.as_str()), - ("workingDirectory", configuration.cwd.as_str()), - ] { - if invalid_relative_path(value) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Run configuration contains an invalid project-relative path", - ) - .with_details(format!("{field}: {value}"))); - } + if invalid_relative_path(&configuration.cwd) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Run configuration contains an invalid project-relative path", + ) + .with_details(format!("workingDirectory: {}", configuration.cwd))); } Ok(()) } @@ -3467,22 +1770,6 @@ fn scope_document(scope: &str) -> Result<&'static str, CoreError> { } } -fn normalize_scoped_toolchain_path( - root: &Path, - scope: &str, - value: &str, -) -> Result { - let value = value.trim(); - if value.is_empty() { - return Ok(String::new()); - } - if scope == "project" { - normalize_project_directory(root, value) - } else { - Ok(value.to_string()) - } -} - /// Validates the literal value of a `cwd` override before it is persisted. /// /// Resolution disables a configuration whose `cwd` is missing and hides it from @@ -3682,9 +1969,8 @@ fn detected_ids(root: &Path) -> BTreeSet { } /// Toolchain requirements of `root`: those of this session's latest -/// generation, else derived from the project's own declarations (`pom.xml`, -/// `.java-version`, the Maven wrapper) so a JDK can be chosen before the Run -/// list has been identified. +/// generation, else those derived from the project's own declarations, so a +/// runtime can be checked before the Run list has been generated. pub fn read_requirements(root: &Path) -> Result, CoreError> { if let Some(layer) = generated_layer::get(root) { return Ok(Some(layer.requirements.clone())); @@ -3692,12 +1978,7 @@ pub fn read_requirements(root: &Path) -> Result Result, CoreError> { @@ -3718,64 +1999,13 @@ fn read_local_toolchains(root: &Path) -> Result, CoreError> { Ok(Some(document)) } +/// Only roles a Run actually consumes become requirements; Core reads the +/// generic declarations it understands and leaves tool-specific version files to +/// the plugin that owns the toolchain. fn detect_requirements( root: &Path, - maven_root: Option<&Path>, - has_java_ecosystem: bool, configurations: &[RunConfiguration], - projects: Option<&[super::project_ownership::RunProjectOwnership]>, ) -> Result { - let mut jdk = ToolchainRequirement { - kind: "java".to_string(), - minimum_version: None, - preferred_vendor: None, - wrapper: None, - version: None, - java: None, - }; - let mut maven = ToolchainRequirement { - kind: "maven".to_string(), - minimum_version: None, - preferred_vendor: None, - wrapper: None, - version: None, - java: Some("project-jdk".to_string()), - }; - let maven_root = maven_root.unwrap_or(root); - let pom = maven_root.join("pom.xml"); - if let Some(projects) = projects { - jdk.minimum_version = projects - .iter() - .filter_map(|project| project.minimum_java_version.as_deref()) - .filter_map(|value| value.parse::().ok()) - .max() - .map(|value| value.to_string()); - } else if let Ok(text) = fs::read_to_string(pom) { - let re = regex::Regex::new(r"(?:maven.compiler.release|maven.compiler.source|maven.compiler.target|java.version)\s*>?\s*[:=]?\s*([0-9]+(?:\.[0-9]+)?)").unwrap(); - // Java 8 projects commonly declare `1.8`; keep the feature version - // instead of the legacy `1` prefix. - jdk.minimum_version = re - .captures(&text) - .and_then(|c| c.get(1)) - .and_then(|m| major_version(m.as_str())); - } - if let Some((version, vendor)) = - declared_java_version(maven_root).or_else(|| declared_java_version(root)) - { - jdk.minimum_version = if projects.is_some() { - jdk.minimum_version - .as_deref() - .and_then(major_version) - .filter(|floor| version_parts(floor) > version_parts(&version)) - .or(Some(version)) - } else { - Some(version) - }; - jdk.preferred_vendor = vendor; - } - if projects.is_none() && maven_root.join("mvnw").exists() { - maven.wrapper = Some("./mvnw".to_string()); - } let mut toolchains = BTreeMap::new(); let consumes = |toolchain: &str| { configurations.iter().any(|configuration| { @@ -3785,23 +2015,6 @@ fn detect_requirements( .any(|candidate| candidate == toolchain) }) }; - if has_java_ecosystem - || consumes("project-jdk") - || projects.is_some_and(|projects| { - projects - .iter() - .any(|project| project.minimum_java_version.is_some()) - }) - { - toolchains.insert("project-jdk".to_string(), jdk); - } - if projects.is_none() - && (maven_root.join("pom.xml").is_file() - || maven_root.join("mvnw").is_file() - || consumes("project-maven")) - { - toolchains.insert("project-maven".to_string(), maven); - } if consumes("project-node") { toolchains.insert( "project-node".to_string(), @@ -3819,9 +2032,7 @@ fn generic_requirement(kind: &str, minimum_version: Option) -> Toolchain kind: kind.to_string(), minimum_version, preferred_vendor: None, - wrapper: None, version: None, - java: None, } } @@ -3868,17 +2079,10 @@ fn toolchain_diagnostics( .as_deref() .or(requirement.version.as_deref()); if let Some(required) = required_version { - // Maven wrapper properties historically landed in `version`. Treat - // that field as a minimum for Maven so already-written requirement - // documents do not block newer system Maven installs. - let treat_as_minimum = requirement.minimum_version.is_some() - || (requirement.kind == "maven" && requirement.version.is_some()); - if !version_satisfies( - &requirement.kind, - &candidate.version, - required, - treat_as_minimum, - ) { + // `version` is an exact prefix match; only `minimumVersion` accepts + // newer releases. + let treat_as_minimum = requirement.minimum_version.is_some(); + if !version_satisfies(&candidate.version, required, treat_as_minimum) { append_toolchain_diagnostics( &mut diagnostics, &consumer_ids, @@ -3905,7 +2109,7 @@ fn toolchain_diagnostics( json!({ "code": "toolchainVendorMismatch", "toolchain": id, - "message": format!("Preferred Java vendor is {vendor}") + "message": format!("Preferred {} vendor is {vendor}", requirement.kind) }), ); } @@ -3929,17 +2133,12 @@ fn append_toolchain_diagnostics( } } -/// Answers whether `actual` meets `required` for one toolchain kind. -/// -/// `minimum` compares ordered versions; otherwise `actual` must start with -/// `required`, which is how a dialect such as Java compares feature versions. -pub fn version_satisfies(kind: &str, actual: &str, required: &str, minimum: bool) -> bool { - let mut actual_parts = version_parts(actual); - let mut required_parts = version_parts(required); - if kind == "java" { - actual_parts = java_feature_version_parts(actual_parts); - required_parts = java_feature_version_parts(required_parts); - } +/// Compares numeric version components. A minimum accepts any later version; +/// otherwise `required` must be a component prefix of `actual` (`20` matches +/// `20.11.1`). Tool-specific version schemes are normalized by their owner first. +pub fn version_satisfies(actual: &str, required: &str, minimum: bool) -> bool { + let actual_parts = version_parts(actual); + let required_parts = version_parts(required); if actual_parts.is_empty() || required_parts.is_empty() { return false; } @@ -3962,18 +2161,7 @@ pub fn version_parts(value: &str) -> Vec { .collect() } -/// Drops the legacy `1.` prefix Java 8 and earlier report (`1.8.0_504`), so -/// those runtimes compare on the same feature-version scale as `8` or `17.0.12`. -pub fn java_feature_version_parts(parts: Vec) -> Vec { - if parts.len() > 1 && parts[0] == 1 { - parts[1..].to_vec() - } else { - parts - } -} - -/// Collects generation inputs. Java sources count by path unless generation -/// reads their content (`content_sources`); every other input is hashed. +/// Collects generation inputs; every input is hashed by content. struct ProjectInputs { inputs: BTreeMap, unreadable_paths: BTreeSet, @@ -3987,13 +2175,7 @@ fn retain_unknown_inputs( previous: RunConfigurationDocument, ) { for configuration in previous.configurations { - let source = configuration.source.as_deref().or_else(|| { - configuration - .extensions - .get("java")? - .get("source")? - .as_str() - }); + let source = configuration.source.as_deref(); if source.is_some_and(|path| under_unknown(path, &snapshot.unreadable_paths)) && !configurations .iter() @@ -4023,10 +2205,7 @@ fn incomplete_scan_diagnostic(paths: &BTreeSet) -> Value { paths.iter().cloned().collect::>().join(", "))}) } -fn project_inputs( - root: &Path, - content_sources: &BTreeSet, -) -> Result { +fn project_inputs(root: &Path) -> Result { let scan = super::workspace_scan::scan_run_workspace(root, None)?; let mut result = ProjectInputs { inputs: BTreeMap::new(), @@ -4043,10 +2222,6 @@ fn project_inputs( .expect("scan stays within root") .to_string_lossy() .replace('\\', "/"); - if relative.ends_with(".java") && !content_sources.contains(&relative) { - result.inputs.insert(relative, PATH_ONLY_INPUT.to_string()); - continue; - } crate::protocol::cancellation::check()?; // The scan lists files through the workspace adapter, so content reads // must use the same adapter or remote projects look permanently unreadable. @@ -4100,19 +2275,10 @@ fn input_change_summary( } fn fingerprint_input(path: &Path) -> bool { - if path.extension().and_then(|extension| extension.to_str()) == Some("java") { - return true; - } matches!( path.file_name().and_then(|name| name.to_str()), Some( - "pom.xml" - | "mvnw.cmd" - | "mvnw" - | "maven-wrapper.properties" - | ".java-version" - | ".sdkmanrc" - | "mise.toml" + "mise.toml" | "package.json" | "package-lock.json" | "pnpm-lock.yaml" @@ -4190,55 +2356,6 @@ fn project_manifest_paths(root: &Path, names: &[&str]) -> Vec { .collect() } -fn declared_java_version(root: &Path) -> Option<(String, Option)> { - if let Ok(text) = fs::read_to_string(root.join(".java-version")) { - let value = text.trim(); - if let Some(version) = major_version(value) { - return Some((version, vendor_from_version(value))); - } - } - if let Ok(text) = fs::read_to_string(root.join(".sdkmanrc")) { - if let Some(value) = text - .lines() - .find_map(|line| line.trim().strip_prefix("java=")) - { - return major_version(value).map(|version| (version, vendor_from_version(value))); - } - } - if let Ok(text) = fs::read_to_string(root.join("mise.toml")) { - let expression = regex::Regex::new(r#"(?m)^\s*java\s*=\s*["']([^"']+)["']"#).ok()?; - if let Some(value) = expression - .captures(&text) - .and_then(|capture| capture.get(1)) - { - let value = value.as_str(); - return major_version(value).map(|version| (version, vendor_from_version(value))); - } - } - None -} - -fn major_version(value: &str) -> Option { - regex::Regex::new(r"(?:^|[^0-9])(?:1\.)?([0-9]{1,2})(?:[._+-]|$)") - .ok()? - .captures(value) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str().to_string()) -} - -fn vendor_from_version(value: &str) -> Option { - let lower = value.to_lowercase(); - if lower.contains("tem") || lower.contains("temurin") { - Some("temurin".to_string()) - } else if lower.contains("zulu") { - Some("zulu".to_string()) - } else if lower.contains("graal") { - Some("graalvm".to_string()) - } else { - None - } -} - fn existing_root(value: &str) -> Result { let path = PathBuf::from(value); if !path.is_dir() { diff --git a/rust/lithe-core/src/execution/configuration/project_toolchain.rs b/rust/lithe-core/src/execution/configuration/project_toolchain.rs index 536af84c20..49ca239703 100644 --- a/rust/lithe-core/src/execution/configuration/project_toolchain.rs +++ b/rust/lithe-core/src/execution/configuration/project_toolchain.rs @@ -1,7 +1,7 @@ -//! Read-only project tool paths for an authoritative workspace-relative owner. -//! Platforms discover/probe executables; Core resolves only saved Run defaults -//! the nearest path override, and explicit per-Run paths. It never inspects -//! a POM or runs a tool. +//! Read-only project tool selections for an authoritative workspace-relative +//! owner. Platforms discover and probe executables; Core only returns the saved +//! machine-local runtime paths, tool preferences and the per-Run defined tools. +//! It never inspects a build file or runs a tool. use super::{existing_root, local_layer_document, read_local_toolchains, validate_version_value}; use crate::protocol::{invalid_relative_path, CoreError, ErrorCode}; @@ -15,19 +15,18 @@ use std::collections::BTreeMap; pub(crate) struct ProjectToolchainRequest { /// Absolute native workspace root, owned by the platform. pub(crate) root: String, - /// Current Provider project/reactor root, relative to that workspace. + /// Current Provider project root, relative to that workspace. pub(crate) path: String, /// Optional host-owned replacement for the local Run document. #[serde(default)] pub(crate) local_document: Option, - /// Optional Run whose explicit path overrides take precedence over the - /// canonical project/reactor selection. Empty fields keep that selection. + /// Optional Run whose provider-declared tools are reported; it must belong + /// to the same provider instance as `path`. #[serde(default)] pub(crate) configuration_id: Option, } -/// Returns paths, never resolved executables. Empty override fields inherit the -/// workspace defaults, rather than falling through a second ancestor override. +/// Returns saved paths, never resolved executables. pub(crate) fn project_toolchain(request: ProjectToolchainRequest) -> Result { if request.path.len() > 1024 || invalid_relative_path(&request.path) @@ -48,14 +47,9 @@ pub(crate) fn project_toolchain(request: ProjectToolchainRequest) -> Result Result Result Result Result Vec { - let Some(file) = ctx.any_of(BUILD_FILES) else { - return Vec::new(); - }; - let Some(text) = ctx.read(file) else { - return Vec::new(); - }; - let Some(invocation) = Invocation::resolve(ctx) else { - return Vec::new(); - }; - if let Some((plugin, task)) = service_plugin(&text) { - return vec![configuration( - ctx, - &invocation, - "gradle.service", - task, - file, - true, - ) - .with_extension( - "gradle", - serde_json::json!({ "task": task, "plugin": plugin, "project": invocation.project }), - )]; - } - if applies_plugin(&text, "application") { - return vec![ - configuration(ctx, &invocation, "gradle.application", "run", file, false) - .with_extension( - "gradle", - serde_json::json!({ "task": "run", "project": invocation.project }), - ), - ]; - } - Vec::new() -} - -/// Where Gradle must be invoked from, and how the task is addressed from there. -/// -/// Gradle only resolves task paths from the directory holding the wrapper and -/// settings file, so a subproject cannot run from its own directory: the build -/// runs at the root and names the task `:module:bootRun`. -struct Invocation { - /// Project-relative directory the command runs in. - cwd: String, - /// Task prefix, empty for a root build. - prefix: String, - /// Gradle project path, `:` for the root build. - project: String, -} - -impl Invocation { - fn resolve(ctx: &DirectoryContext) -> Option { - let build_root = build_root(ctx)?; - if build_root == ctx.relative { - return Some(Self { - cwd: build_root, - prefix: String::new(), - project: ":".to_string(), - }); - } - // Strip the build root from the module path so the task prefix is - // expressed relative to the build, not to the project. - let relative = if build_root == "." { - ctx.relative.as_str() - } else { - ctx.relative.strip_prefix(&format!("{build_root}/"))? - }; - let project = format!(":{}", relative.replace('/', ":")); - Some(Self { - cwd: build_root, - prefix: format!("{project}:"), - project, - }) - } -} - -/// Walks up to the nearest directory holding a settings file, which is what -/// defines a Gradle build. A build file with no settings file above it is a -/// standalone single-project build. -fn build_root(ctx: &DirectoryContext) -> Option { - let mut directory = Some(ctx.path.as_path()); - while let Some(path) = directory { - if SETTINGS_FILES.iter().any(|name| path.join(name).is_file()) { - return relative_to_root(ctx, path); - } - if path == ctx.root { - break; - } - directory = path.parent().filter(|parent| parent.starts_with(&ctx.root)); - } - // No settings file anywhere above: the build file stands on its own. - Some(ctx.relative.clone()) -} - -fn relative_to_root(ctx: &DirectoryContext, path: &std::path::Path) -> Option { - if path == ctx.root { - return Some(".".to_string()); - } - let relative = path.strip_prefix(&ctx.root).ok()?; - Some(relative.to_string_lossy().replace('\\', "/")) -} - -fn configuration( - ctx: &DirectoryContext, - invocation: &Invocation, - provider: &str, - task: &str, - source: &str, - service: bool, -) -> Detected { - // Subproject tasks all run from the build root, so `cwd` cannot tell two - // modules apart and the name carries the whole Gradle project path. A leaf - // name would collide across parents (`a:orders` and `b:orders`) and dedup - // would silently drop one of the two services. - let name = if invocation.project == ":" { - task.to_string() - } else { - invocation.project.trim_start_matches(':').to_string() - }; - let argument = format!("{}{task}", invocation.prefix); - let detected = if service { - Detected::service( - provider, - &name, - "gradle", - vec![argument.as_str()], - ctx, - source, - ) - } else { - Detected::application( - provider, - &name, - "gradle", - vec![argument.as_str()], - ctx, - source, - ) - }; - detected - .with_cwd(&invocation.cwd) - .with_confidence(Confidence::Declared) - .requiring_toolchain("java", "project-jdk") -} - -fn service_plugin(text: &str) -> Option<(&'static str, &'static str)> { - SERVICE_PLUGINS - .iter() - .copied() - .find(|(plugin, _)| applies_plugin(text, plugin)) -} - -/// Recognises both plugin syntaxes without parsing Groovy or Kotlin: -/// `id 'org.springframework.boot'` in a `plugins` block, and the legacy -/// `apply plugin: 'org.springframework.boot'`. Commented-out lines are skipped -/// so a disabled plugin does not contribute a configuration. -fn applies_plugin(text: &str, plugin: &str) -> bool { - text.lines() - .map(str::trim) - .filter(|line| !line.starts_with("//") && !line.starts_with('*')) - .any(|line| { - (line.contains("id ") - || line.contains("id(") - || line.contains("apply plugin") - || line.contains("apply(plugin")) - && [ - format!("\"{plugin}\""), - format!("'{plugin}'"), - // Kotlin accessor form: `kotlin("jvm")` style shorthands are - // not plugin ids, but `alias(libs.plugins.spring.boot)` and - // bare `org.springframework.boot` do appear unquoted. - format!(" {plugin} "), - ] - .iter() - .any(|needle| line.contains(needle.as_str())) - }) -} diff --git a/rust/lithe-core/src/execution/detectors/maven.rs b/rust/lithe-core/src/execution/detectors/maven.rs deleted file mode 100644 index cdd398bc47..0000000000 --- a/rust/lithe-core/src/execution/detectors/maven.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Maven service candidates from the declared reactor and applied plugins. - -use super::super::types::Confidence; -use super::{Detected, DirectoryContext}; -use crate::project::{declared_modules, DeclaredModule}; -use std::collections::BTreeMap; - -/// Plugins that offer a framework launch goal, paired with the provider that -/// records how the launch layer must address it. -/// -/// A framework is identified by the plugin it applies rather than by a -/// dependency or an annotation: the plugin is what contributes the goal that -/// starts the service, so if it is absent there is nothing to run whatever the -/// sources say. Each framework needs its own provider because the goals take -/// their arguments under different property names -- see `maven_arguments`. -/// -/// The group is part of the identity: Maven resolves a declaration without a -/// `` to `org.apache.maven.plugins`, so a bare `spring-boot-maven-plugin` -/// names another artifact entirely and does not select this provider. -/// -/// A framework may publish its plugin under more than one official group. -/// Quarkus republishes the plugin under the platform's own `io.quarkus.platform` -/// group, and Micronaut 4.0 moved to `io.micronaut.maven` while -/// `io.micronaut.build` stays for the 3.x line. Each of those coordinates is -/// listed, and a same-named plugin under any other group still selects nothing. -const SERVICE_PLUGINS: &[(&str, &str, &str)] = &[ - ( - "org.springframework.boot", - "spring-boot-maven-plugin", - "spring-boot.maven", - ), - ("io.quarkus", "quarkus-maven-plugin", "quarkus.maven"), - ( - "io.quarkus.platform", - "quarkus-maven-plugin", - "quarkus.maven", - ), - ( - "io.micronaut.build", - "micronaut-maven-plugin", - "micronaut.maven", - ), - ( - "io.micronaut.maven", - "micronaut-maven-plugin", - "micronaut.maven", - ), -]; - -/// Maven modules are *declared*, not discovered, so this detector reads the -/// module graph from the selected Maven root instead of judging each directory -/// the shared walk visits. -/// -/// A directory-driven scan gets Maven wrong in both directions: `` may -/// name a directory the walk prunes (one called `build` or `out` is invisible), -/// while a leftover `pom.xml` outside the graph is not part of the build at all. -/// Reading the graph once at the root is also cheaper than parsing every pom the -/// walk happens to pass. -pub fn detect(ctx: &DirectoryContext) -> Vec { - if !ctx.has("pom.xml") { - return Vec::new(); - } - let Ok(modules) = declared_modules(&ctx.path) else { - return Vec::new(); - }; - let names = service_names(&modules); - modules - .iter() - .filter(|module| !module.is_aggregator()) - .filter_map(|module| { - let provider = service_provider(module)?; - let name = names.get(&module.relative_path)?; - Some(service(ctx, module, name, provider)) - }) - .collect() -} - -/// The provider for the first framework plugin a module applies. -/// -/// A module applying two of these is misconfigured -- only one goal can own the -/// process -- so table order decides rather than emitting two services that -/// would both claim the same port. -fn service_provider(module: &DeclaredModule) -> Option<&'static str> { - SERVICE_PLUGINS - .iter() - .find(|(group_id, artifact_id, _)| module.applies_plugin(group_id, artifact_id)) - .map(|(_, _, provider)| *provider) -} - -/// A Maven framework module belongs to one reactor root and is addressed by its -/// module path. Every such configuration therefore shares one `cwd`, so the -/// name is what keeps two modules apart during dedup. -/// -/// `artifactId` is Maven's own name for a module and is what a developer -/// recognises, but it is only unique per `groupId`. Where two modules share one, -/// both fall back to their path so neither is silently dropped. -fn service_names(modules: &[DeclaredModule]) -> BTreeMap { - let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); - for module in modules { - *counts.entry(module.artifact_id.as_str()).or_default() += 1; - } - modules - .iter() - .map(|module| { - let unique = counts.get(module.artifact_id.as_str()) == Some(&1); - let name = if unique { - module.artifact_id.clone() - } else { - module.relative_path.clone() - }; - (module.relative_path.clone(), name) - }) - .collect() -} - -/// These frameworks use project toolchain bindings rather than a command on -/// `PATH`. The main class is deliberately absent: the Java scan supplies it only -/// after JDT confirms a unique Spring application entry in this module. The -/// generator drops unmatched Spring candidates; other frameworks retain their Maven goal. -fn service( - ctx: &DirectoryContext, - module: &DeclaredModule, - name: &str, - provider: &str, -) -> Detected { - // The detection is made at the root but the evidence is the module's own - // pom, which is what the "why is this here" affordance should point at. - let source = if module.relative_path == "." { - "pom.xml".to_string() - } else { - format!("{}/pom.xml", module.relative_path) - }; - // The command is discarded by `with_toolchains`: Maven is reached through - // the project binding, which may be `./mvnw` rather than a program on PATH. - Detected::service(provider, name, "", Vec::new(), ctx, &source) - .with_toolchains(&[("java", "project-jdk"), ("maven", "project-maven")]) - .with_debug("jdwp") - .with_confidence(Confidence::Declared) - .with_extension( - "maven", - serde_json::json!({ "module": module.relative_path }), - ) -} diff --git a/rust/lithe-core/src/execution/detectors/mod.rs b/rust/lithe-core/src/execution/detectors/mod.rs index 10830c3450..9ee3bb7109 100644 --- a/rust/lithe-core/src/execution/detectors/mod.rs +++ b/rust/lithe-core/src/execution/detectors/mod.rs @@ -5,18 +5,14 @@ //! the tree themselves: a shared walk is the only way the cost stays bounded as //! ecosystems are added. //! -//! An ecosystem whose layout is *declared* rather than discovered reads its own -//! manifest graph instead -- see `maven`. The caller selects the Maven root -//! because it may sit below the opened workspace. That is not a shortcut around -//! the shared walk: a declared graph names directories the walk prunes, and -//! omits ones it would visit. +//! Ecosystems whose layout is *declared* by a build model rather than +//! discovered from manifests belong to a build provider plugin, which reports +//! its runs through `build.provider` instead of a detector here. mod cargo; mod compose; mod go; -mod gradle; mod make; -mod maven; mod npm; mod procfile; mod python; @@ -45,18 +41,17 @@ pub struct Detected { /// Whether this runs the project or the infrastructure it depends on. pub category: RunCategory, pub confidence: Confidence, - /// The program to spawn, or `None` when `toolchains` names the executable. + /// The program to spawn. Detectors always name one; `None` is reserved for + /// launches whose executable comes from a toolchain binding. pub command: Option, pub args: Vec, /// Project-relative directory the command runs in. pub cwd: String, pub env: BTreeMap, - /// Toolchain bindings by role, e.g. `{java: project-jdk}`. A process-based - /// detection may retain `command` while declaring a runtime it consumes. + /// Toolchain bindings by role, e.g. `{runtime: project-node}`. A + /// process-based detection retains `command` while declaring a runtime it + /// consumes. pub toolchains: BTreeMap, - /// The debug adapter this service supports, when launching it under a - /// debugger is something the launch layer already knows how to assemble. - pub debug: Option, pub extensions: BTreeMap, /// Which manifest produced this, for the "why is this here" affordance. pub source: String, @@ -135,7 +130,6 @@ impl Detected { cwd: ctx.relative.clone(), env: BTreeMap::new(), toolchains: BTreeMap::new(), - debug: None, extensions: BTreeMap::new(), source: ctx.join_relative(source), } @@ -153,23 +147,6 @@ impl Detected { self } - /// Hands the executable to a toolchain instead of spawning `command`. - /// - /// Most detections name a program that is on `PATH`, which is what keeps a - /// new ecosystem from needing changes in the launch layer. An ecosystem - /// whose launch is assembled from a toolchain rather than a command line -- - /// Maven's `spring-boot:run`, addressed through the project JDK and Maven - /// binding -- takes this instead, and the launch layer must already know - /// that provider. - pub fn with_toolchains(mut self, toolchains: &[(&str, &str)]) -> Self { - self.command = None; - self.toolchains = toolchains - .iter() - .map(|(role, name)| (role.to_string(), name.to_string())) - .collect(); - self - } - /// Declares a runtime requirement while keeping the detector-owned command. /// /// Process-based detectors still own their command, but Core needs the @@ -179,21 +156,6 @@ impl Detected { self } - /// Declares the debug adapter supported by this detection. - pub fn with_debug(mut self, adapter: &str) -> Self { - self.debug = Some(adapter.to_string()); - self - } - - /// Overrides the directory the command runs in. Defaults to the directory - /// the detection was made in, which is wrong when a build must be invoked - /// from its root -- a Gradle subproject, or a Maven module addressed by - /// `-pl` from the reactor root. - pub fn with_cwd(mut self, cwd: &str) -> Self { - self.cwd = cwd.to_string(); - self - } - /// Attaches provider-specific metadata without expanding the shared schema. pub fn with_extension(mut self, namespace: &str, value: serde_json::Value) -> Self { self.extensions.insert(namespace.to_string(), value); @@ -231,7 +193,6 @@ const DETECTORS: &[DetectFn] = &[ python::detect, cargo::detect, go::detect, - gradle::detect, make::detect, shell::detect_just, ]; @@ -239,7 +200,7 @@ const DETECTORS: &[DetectFn] = &[ /// Runs every detector over the project and returns deduplicated results /// ordered shallowest-directory-first, so the top-level service of a monorepo /// reads before its packages. -pub fn detect_all(root: &Path, maven_root: Option<&Path>) -> Result, CoreError> { +pub fn detect_all(root: &Path) -> Result, CoreError> { let directories = scan(root)?; let mut found = Vec::new(); for context in &directories { @@ -247,11 +208,6 @@ pub fn detect_all(root: &Path, maven_root: Option<&Path>) -> Result Result, CoreError> { - let entries = match fs::read_dir(path) { - Ok(entries) => entries, - // Detection skips a directory the host cannot list, as it does locally, - // but a dropped link must not pass for a project without manifests. - Err(error) if fs::is_transport_failure(&error) => return Err(error.into()), - Err(_) => return Ok(None), - }; - let files = entries - .flatten() - .filter_map(|entry| { - let kind = entry.file_type().ok()?; - (!kind.is_dir()).then(|| entry.file_name().to_str().map(str::to_string))? - }) - .collect(); - Ok(Some(Self { - root: root.to_path_buf(), - path: path.to_path_buf(), - relative: relative_path(root, path)?, - files, - })) - } - /// Reports whether the directory contains an entry with the exact name. pub fn has(&self, name: &str) -> bool { self.files.contains(name) diff --git a/rust/lithe-core/src/execution/environment.rs b/rust/lithe-core/src/execution/environment.rs index 2a5d96f269..d5f9d1981c 100644 --- a/rust/lithe-core/src/execution/environment.rs +++ b/rust/lithe-core/src/execution/environment.rs @@ -4,20 +4,20 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; -/// Platform-resolved homes and inherited environment for one launch step. +/// Inherited environment and explicit overrides for one launch step. +/// +/// Toolchain-specific variables (a runtime home, a build tool's own home) are +/// owned by the plugin that defines the toolchain; it supplies them as literal +/// overrides, so Core never names a tool here. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LaunchEnvironmentRequest { - /// Toolchain of this step, not the later application process. - pub toolchain: Option, - /// Resolved project JDK home. - pub java_home: Option, - /// Resolved Maven JVM home, falling back to the project home when absent. - pub maven_java_home: Option, - /// Native parent process environment; selected homes override it. + /// Native parent process environment; explicit overrides replace it. #[serde(default)] pub inherited: BTreeMap, /// Plan bindings followed by explicit user overrides, already merged by key. + /// Only string values are applied: a structured binding the host could not + /// resolve to text has no defined value and must not reach the process. #[serde(default)] pub overrides: BTreeMap, /// Windows environment keys are case-insensitive even in a Rust map. @@ -32,8 +32,7 @@ pub struct LaunchEnvironmentResponse { pub environment: BTreeMap, } -/// Applies inherited < selected toolchain < explicit launch overrides. -/// Maven steps use their Maven JDK; direct Java steps retain the project JDK. +/// Applies inherited < explicit launch overrides. pub fn resolve_launch_environment(request: LaunchEnvironmentRequest) -> LaunchEnvironmentResponse { let mut environment = BTreeMap::new(); let mut insert = |key: String, value: String| { @@ -47,43 +46,9 @@ pub fn resolve_launch_environment(request: LaunchEnvironmentRequest) -> LaunchEn for (key, value) in request.inherited { insert(key, value); } - let selected = if request.toolchain.as_deref() == Some("project-maven") { - request - .maven_java_home - .as_ref() - .or(request.java_home.as_ref()) - } else if request.toolchain.as_deref() == Some("project-jdk") { - request.java_home.as_ref() - } else { - None - }; - if let Some(home) = selected { - insert("JAVA_HOME".into(), home.clone()); - } for (key, value) in request.overrides { - let resolved = if let Some(text) = value.as_str() { - Some(text.to_owned()) - } else if value.get("property").and_then(Value::as_str) == Some("home") { - // A pre-launch Maven step may inherit its application's Java binding. - // The executable's role owns JAVA_HOME; literal user overrides remain - // authoritative. Other variables keep their explicit binding. - if key.eq_ignore_ascii_case("JAVA_HOME") && selected.is_some() { - selected.cloned() - } else { - match value.get("toolchain").and_then(Value::as_str) { - Some("project-jdk") => request.java_home.clone(), - Some("project-maven") => request - .maven_java_home - .clone() - .or(request.java_home.clone()), - _ => None, - } - } - } else { - None - }; - if let Some(value) = resolved { - insert(key, value); + if let Some(text) = value.as_str() { + insert(key, text.to_owned()); } } LaunchEnvironmentResponse { environment } @@ -152,20 +117,24 @@ mod tests { } } + // A structured binding that reaches Core unresolved names no value, so it + // must be dropped rather than leak an empty or stale variable. #[test] - fn shared_launch_environment_fixtures() { - let cases: Value = serde_json::from_str(include_str!( - "../../../../shared/fixtures/execution/launch-environment-v1.json" - )) + fn overrides_replace_inherited_values_and_drop_unresolved_bindings() { + let request: LaunchEnvironmentRequest = serde_json::from_value(serde_json::json!({ + "inherited": { "Path": "bin", "TOOL_A_HOME": "inherited" }, + "overrides": { + "TOOL_A_HOME": "selected", + "TOOL_B_HOME": { "toolchain": "tool-b", "property": "home" } + }, + "caseInsensitive": true + })) .unwrap(); - for case in cases["cases"].as_array().unwrap() { - let request = serde_json::from_value(case["request"].clone()).unwrap(); - assert_eq!( - serde_json::to_value(resolve_launch_environment(request)).unwrap(), - case["expected"], - "{}", - case["name"] - ); - } + assert_eq!( + serde_json::to_value(resolve_launch_environment(request)).unwrap(), + serde_json::json!({ + "environment": { "PATH": "bin", "TOOL_A_HOME": "selected" } + }) + ); } } diff --git a/rust/lithe-core/src/execution/generated_layer.rs b/rust/lithe-core/src/execution/generated_layer.rs index b0432dc74e..e21dae4bd6 100644 --- a/rust/lithe-core/src/execution/generated_layer.rs +++ b/rust/lithe-core/src/execution/generated_layer.rs @@ -1,16 +1,17 @@ //! Detected run configurations, held in memory for each workspace. //! -//! Generation derives the detected layer from the project tree and, for Java, -//! from the language service's answer. That makes it session state, not a +//! Generation derives the detected layer from the project tree and from the +//! runs build provider plugins report. That makes it session state, not a //! project document: it lives here, keyed by workspace, and is replaced by each //! generation. Nothing is written into the workspace, so opening a project //! never fails on a read-only checkout and never leaves files for version //! control. Only configurations a user saves are project documents. //! -//! The one thing worth carrying across sessions is the Java entry points JDT -//! reported last time, so the Run list is complete before the language service -//! answers again. Hosts pass an application cache directory for that; the cache -//! is an optimization, and failing to read or write it changes nothing else. +//! The one thing worth carrying across sessions is the last generated document, +//! so retained entries keep their ids and the Run list is complete before +//! providers answer again. Hosts pass an application cache directory for that; +//! the cache is an optimization, and failing to read or write it changes +//! nothing else. use super::configuration::{RunConfigurationDocument, ToolchainRequirementsDocument}; use serde_json::{json, Value}; @@ -118,15 +119,6 @@ pub(crate) fn seed(root: &Path, document: Option, requirements: Option, - /// Host-read snapshot for UI-safe selection; mutually exclusive with `root`. - /// The same document validation and selection policy apply to both sources. - pub requirements: Option, - /// Usable executable homes probed by the platform. - pub candidates: Vec, - /// The platform's unconstrained choice; used when requirements are absent - /// or no candidate satisfies them. This keeps fallback behavior explicit. - pub fallback_id: Option, -} - -/// Selected candidate and an actionable warning when no compatible JDK exists. -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct JavaSelection { - /// Selected identity, or absent when the host found no usable JDK. - pub id: Option, - /// No candidate satisfies the minimum; the fallback remains usable. - pub warning: Option, -} - -/// Orders equivalent sources numerically, including legacy Java `1.8` versions. -/// Stable IDs break equal-version ties independently of filesystem enumeration. -pub fn compare_java_candidates( - left: &JavaSelectionCandidate, - right: &JavaSelectionCandidate, -) -> std::cmp::Ordering { - left.priority - .cmp(&right.priority) - .then_with(|| { - java_feature_version_parts(version_parts(&right.version)) - .cmp(&java_feature_version_parts(version_parts(&left.version))) - }) - .then_with(|| left.id.cmp(&right.id)) -} - -/// Reuses Core's requirement reader and version semantics without generating -/// requirements, probing executables, or changing an explicit user selection. -pub fn select_java(request: JavaSelectionRequest) -> Result { - if request.root.is_some() && request.requirements.is_some() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java selection must use either a workspace or a requirements snapshot", - )); - } - let document = request.requirements.or(request - .root - .as_deref() - .map(read_requirements) - .transpose()? - .flatten()); - if let Some(document) = &document { - super::configuration::validate_sidecar_version(document.version)?; - } - let minimum = document - .as_ref() - .and_then(|doc| doc.toolchains.get("project-jdk")) - .filter(|requirement| requirement.kind == "java") - .and_then(|requirement| requirement.minimum_version.as_deref()); - Ok(select_java_candidates( - &request.candidates, - request.fallback_id.as_deref(), - minimum, - )) -} - -/// Java feature version (`8` for `1.8.0_402`, `21` for `21.0.4`); `None` when unknown. -fn java_feature(version: &str) -> Option { - java_feature_version_parts(version_parts(version)) - .first() - .copied() -} - -/// Applies only the project's declared Java version; explicit paths and vendor -/// preferences remain the responsibility of existing launch validation and diagnostics. -/// -/// A JDK of exactly the declared feature version wins over a newer one, even from a -/// higher-priority source such as `JAVA_HOME`: a Java 8 project must not run on the -/// JDK 21 a shell exports. Without one, the oldest newer JDK is the closest match. -/// Source priority only breaks ties within the same feature version. -/// -/// The policy follows OpenIDEA's `pick_jdk` (`crates/ide-sdk/src/java.rs`, -/// , Apache-2.0); see the repository `NOTICE`. -pub fn select_java_candidates( - candidates: &[JavaSelectionCandidate], - fallback_id: Option<&str>, - minimum: Option<&str>, -) -> JavaSelection { - let fallback = candidates - .iter() - .find(|candidate| Some(candidate.id.as_str()) == fallback_id) - .or_else(|| { - candidates - .iter() - .min_by(|a, b| compare_java_candidates(a, b)) - }); - let Some(minimum) = minimum else { - return JavaSelection { - id: fallback.map(|candidate| candidate.id.clone()), - warning: None, - }; - }; - let required = java_feature(minimum); - let distance = |candidate: &JavaSelectionCandidate| { - java_feature(&candidate.version) - .zip(required) - .map(|(feature, required)| feature.saturating_sub(required)) - }; - let matching = candidates - .iter() - .filter(|candidate| version_satisfies("java", &candidate.version, minimum, true)) - .min_by(|a, b| { - distance(a) - .cmp(&distance(b)) - .then_with(|| compare_java_candidates(a, b)) - }); - JavaSelection { - id: matching.or(fallback).map(|candidate| candidate.id.clone()), - warning: matching.is_none().then(|| format!("No installed JDK satisfies Java {minimum} or newer. Install a compatible JDK or choose one in project settings.")), - } -} diff --git a/rust/lithe-core/src/execution/launch_command.rs b/rust/lithe-core/src/execution/launch_command.rs deleted file mode 100644 index 24758441e9..0000000000 --- a/rust/lithe-core/src/execution/launch_command.rs +++ /dev/null @@ -1,593 +0,0 @@ -//! Keeps an assembled launch command within the operating system's limit. -//! -//! A Java project launch passes the resolved runtime classpath on the command -//! line. For a large multi-module Maven project that is hundreds of absolute -//! jar paths, and Windows refuses to create a process whose command line -//! exceeds 32,767 UTF-16 code units. The JDK's own answer is an argument file: -//! `java @file` reads options from disk, so only the short reference stays on -//! the command line. -//! -//! Core decides whether shortening is required and what the file must contain. -//! The host owns the filesystem: it chooses the path, writes the file, and -//! deletes it after that execution exits. The returned text is Unicode; the -//! host must encode it losslessly with the launcher's native platform encoding. -//! JEP 400 does not make Windows launcher argument files UTF-8. -//! -//! JDK 8 has no argument files, so a launch for that release always stays -//! direct here. - -use serde::{Deserialize, Serialize}; -use std::path::Path; - -/// Maximum command line `CreateProcessW` accepts, including its terminating -/// null. Exceeding it fails the spawn with `ERROR_FILENAME_EXCED_RANGE` (206). -pub const WINDOWS_COMMAND_LINE_LIMIT: usize = 32_767; - -/// Headroom for the null terminator and for host quoting that this estimate -/// does not model exactly. Shortening early costs nothing; shortening too late -/// fails the launch. -const COMMAND_LINE_MARGIN: usize = 2_048; - -/// Options whose value is a joined list of absolute paths. These carry -/// practically all of an oversized command line, so moving them into the -/// argument file leaves the JVM options and program arguments untouched. -const PATH_LIST_OPTIONS: &[&str] = &["-cp", "-classpath", "--class-path", "-p", "--module-path"]; - -/// How a host should pass the assembled arguments to the operating system. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum LaunchCommandPlan { - /// The command line fits: spawn with the original arguments. - Direct, - /// The command line is too long. Write `argfile_contents` to the argfile - /// path that was supplied, then spawn with `arguments`. - Argfile { - /// Arguments to spawn with; the moved options become one `@file` entry. - arguments: Vec, - /// Complete argument-file text, already quoted and newline terminated. - argfile_contents: String, - }, -} - -/// JSON request used by hosts that cannot call the Rust planner directly. -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LaunchCommandPlanRequest { - /// Java executable path used for launcher detection. - pub executable: String, - /// Complete argument vector before shortening. - pub arguments: Vec, - /// Host-owned path that may be referenced by an argument-file plan. - pub argfile_path: String, - /// Optional host-specific command-line cap; null uses the Windows cap. - pub limit: Option, - /// JDK feature version read by the host from its `release` file. - pub java_feature_version: Option, - /// Host-read release files, nearest first; Core interprets their contents. - pub java_release_contents: Option>, -} - -/// JSON response for [`LaunchCommandPlanRequest`]. -#[derive(Debug, Serialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -pub enum LaunchCommandPlanResponse { - /// The original argument vector is safe to spawn directly. - Direct, - /// The host must write `argfileContents` before spawning `arguments`. - Argfile { - /// Arguments with path-list options replaced by an `@file` reference. - arguments: Vec, - /// Newline-terminated JDK argument-file contents. - #[serde(rename = "argfileContents")] - argfile_contents: String, - }, -} - -impl From for LaunchCommandPlanResponse { - fn from(plan: LaunchCommandPlan) -> Self { - match plan { - LaunchCommandPlan::Direct => Self::Direct, - LaunchCommandPlan::Argfile { - arguments, - argfile_contents, - } => Self::Argfile { - arguments, - argfile_contents, - }, - } - } -} - -/// Plans a launch through the shared JSON command dispatcher. -pub fn plan_launch_command_request(request: LaunchCommandPlanRequest) -> LaunchCommandPlanResponse { - let version = request.java_feature_version.or_else(|| { - request - .java_release_contents - .as_ref()? - .iter() - .find(|contents| { - contents - .lines() - .any(|line| line.trim().starts_with("JAVA_VERSION=")) - }) - .and_then(|contents| java_feature_version_from_release(contents)) - }); - plan_launch_command( - &request.executable, - &request.arguments, - Path::new(&request.argfile_path), - request.limit, - version, - ) - .into() -} - -/// First JDK release that accepts `@file` argument files. -const MINIMUM_ARGFILE_JAVA_VERSION: u32 = 9; - -/// Reads the feature version from a JDK `release` file. -/// -/// `JAVA_VERSION="21.0.2"` yields 21 and the legacy `"1.8.0_392"` yields 8. -/// Hosts pass the result to [`plan_launch_command`], which needs it to know -/// whether an argument file is supported. Encoding is the host's responsibility. -pub fn java_feature_version_from_release(contents: &str) -> Option { - let value = java_version_from_release(contents)?; - release_feature_version(value) -} - -/// Borrows the full version from JDK-owned release metadata without running Java. -/// Native discovery uses this value with the shared runtime candidate ordering; -/// absent or unrecognized metadata must not trigger an implicit process probe. -pub fn java_version_from_release(contents: &str) -> Option<&str> { - let value = contents - .lines() - .find_map(|line| line.trim().strip_prefix("JAVA_VERSION="))? - .trim() - .trim_matches('"'); - release_feature_version(value)?; - Some(value) -} - -fn release_feature_version(value: &str) -> Option { - let mut parts = value.split(['.', '_', '-', '+']); - let first = parts.next()?.parse::().ok()?; - if first == 1 { - parts.next()?.parse::().ok() - } else { - Some(first) - } -} - -/// Plans how to spawn `executable` with `arguments` under `limit`. -/// -/// `argfile_path` is the file the host will write when the returned plan asks -/// for one; it is only referenced, never created here. `limit` defaults to the -/// Windows command-line cap, which is the only mainstream limit small enough -/// for a Java class path to reach. `java_feature_version` is the JVM that will -/// expand the file; `None` means unknown and keeps the plan conservative. -pub fn plan_launch_command( - executable: &str, - arguments: &[String], - argfile_path: &Path, - limit: Option, - java_feature_version: Option, -) -> LaunchCommandPlan { - let executable_name = executable.rsplit(['/', '\\']).next().unwrap_or(executable); - if !["java", "java.exe", "javaw", "javaw.exe"] - .iter() - .any(|name| executable_name.eq_ignore_ascii_case(name)) - || !java_feature_version.is_some_and(|version| version >= MINIMUM_ARGFILE_JAVA_VERSION) - { - return LaunchCommandPlan::Direct; - } - let limit = limit.unwrap_or(WINDOWS_COMMAND_LINE_LIMIT); - let budget = limit.saturating_sub(COMMAND_LINE_MARGIN); - if command_line_length(executable, arguments) <= budget { - return LaunchCommandPlan::Direct; - } - let mut remaining = Vec::with_capacity(arguments.len()); - let mut argfile_lines = Vec::new(); - let mut index = 0; - while index < arguments.len() { - let argument = arguments[index].as_str(); - let value = arguments.get(index + 1); - // The first application target ends launcher options. Everything after - // it belongs to the program, even when named -p or --class-path. - if !argument.starts_with('-') - || matches!(argument, "-jar" | "-m" | "--module") - || argument.starts_with("--module=") - { - remaining.extend_from_slice(&arguments[index..]); - break; - } - if argument == "--disable-@files" { - return LaunchCommandPlan::Direct; - } - match value { - Some(value) if PATH_LIST_OPTIONS.contains(&argument) => { - if argfile_lines.is_empty() { - remaining.push(format!("@{}", argfile_path.display())); - } - argfile_lines.push(argument.to_string()); - argfile_lines.push(quote_argfile_value(value)); - index += 2; - } - Some(value) - if matches!( - argument, - "--add-modules" - | "--limit-modules" - | "--add-reads" - | "--add-exports" - | "--add-opens" - | "--patch-module" - | "--upgrade-module-path" - | "--enable-native-access" - | "--source" - | "--describe-module" - | "-d" - ) => - { - remaining.push(argument.to_string()); - remaining.push(value.clone()); - index += 2; - } - _ => { - remaining.push(argument.to_string()); - index += 1; - } - } - } - if argfile_lines.is_empty() { - // Nothing movable: the caller's own arguments are oversized, and the - // host should report the operating system's refusal rather than - // silently rewrite a command it does not understand. - return LaunchCommandPlan::Direct; - } - let mut argfile_contents = argfile_lines.join("\n"); - argfile_contents.push('\n'); - LaunchCommandPlan::Argfile { - arguments: remaining, - argfile_contents, - } -} - -/// Estimates the command line the host will hand to the operating system. -/// -/// Windows counts UTF-16 code units, and each argument containing whitespace or -/// a quote is wrapped in quotes. The estimate never has to be exact because -/// [`COMMAND_LINE_MARGIN`] absorbs the difference. -fn command_line_length(executable: &str, arguments: &[String]) -> usize { - let mut length = quoted_length(executable); - for argument in arguments { - length += 1 + quoted_length(argument); - } - length -} - -fn quoted_length(value: &str) -> usize { - let units = value.encode_utf16().count(); - if value.is_empty() || value.contains([' ', '\t', '"']) { - units + 2 + value.matches('"').count() - } else { - units - } -} - -/// Quotes one value for a JDK argument file. -/// -/// Inside a quoted argfile string the backslash is an escape character, so -/// every separator in a Windows path has to be doubled. Quoting also keeps -/// paths that contain spaces in one argument. -fn quote_argfile_value(value: &str) -> String { - let escaped = value.replace('\\', "\\\\").replace('"', "\\\""); - format!("\"{escaped}\"") -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - fn argfile() -> PathBuf { - PathBuf::from("C:\\Temp\\lithe-run\\launch.argfile") - } - - /// Mirrors a real Maven runtime classpath: absolute repository paths whose - /// length is what pushes a multi-module project past the Windows limit. - fn classpath(entries: usize) -> String { - (0..entries) - .map(|index| { - format!( - "C:\\Users\\developer\\.m2\\repository\\org\\springframework\\boot\\spring-boot-starter-{index}\\3.2.{index}\\spring-boot-starter-{index}-3.2.{index}.jar" - ) - }) - .collect::>() - .join(";") - } - - #[test] - fn a_command_that_fits_is_spawned_unchanged() { - let arguments = vec![ - "-cp".to_string(), - classpath(4), - "org.dromara.DromaraApplication".to_string(), - ]; - assert_eq!( - plan_launch_command( - "C:\\jdk\\bin\\java.exe", - &arguments, - &argfile(), - None, - Some(21) - ), - LaunchCommandPlan::Direct - ); - } - - /// Regression: RuoYi-Vue-Plus resolves hundreds of jars, and the inline - /// `-cp` made `CreateProcessW` fail before the JVM ever started. - #[test] - fn an_oversized_classpath_moves_into_an_argument_file() { - let entries = classpath(500); - let arguments = vec![ - "-Dfile.encoding=UTF-8".to_string(), - "-cp".to_string(), - entries.clone(), - "org.dromara.DromaraApplication".to_string(), - "--spring.profiles.active=dev".to_string(), - ]; - - let plan = plan_launch_command( - "C:\\jdk\\bin\\java.exe", - &arguments, - &argfile(), - None, - Some(21), - ); - let LaunchCommandPlan::Argfile { - arguments: shortened, - argfile_contents, - } = plan - else { - panic!("an oversized classpath must be shortened"); - }; - // The argfile replaces the option in place, so JVM options still - // precede the main class and program arguments still follow it. - assert_eq!( - shortened, - [ - "-Dfile.encoding=UTF-8", - "@C:\\Temp\\lithe-run\\launch.argfile", - "org.dromara.DromaraApplication", - "--spring.profiles.active=dev", - ] - ); - assert!( - command_line_length("C:\\jdk\\bin\\java.exe", &shortened) < 1_000, - "the remaining command line must be short: {shortened:?}" - ); - let expected_value = format!("\"{}\"", entries.replace('\\', "\\\\")); - assert_eq!(argfile_contents, format!("-cp\n{expected_value}\n")); - } - - #[test] - fn module_paths_are_moved_with_the_classpath() { - let arguments = vec![ - "--module-path".to_string(), - classpath(300), - "-cp".to_string(), - classpath(300), - "-m".to_string(), - "app/com.example.Main".to_string(), - ]; - - let LaunchCommandPlan::Argfile { - arguments: shortened, - argfile_contents, - } = plan_launch_command( - "C:\\jdk\\bin\\java.exe", - &arguments, - &argfile(), - None, - Some(21), - ) - else { - panic!("both path lists must be shortened"); - }; - // One argfile reference covers every moved option, and `-m` keeps its - // own value because it names a module, not a path list. - assert_eq!( - shortened, - [ - "@C:\\Temp\\lithe-run\\launch.argfile", - "-m", - "app/com.example.Main", - ] - ); - assert!(argfile_contents.starts_with("--module-path\n")); - assert!(argfile_contents.contains("\n-cp\n")); - assert!(argfile_contents.ends_with('\n')); - } - - #[test] - fn a_value_with_spaces_stays_one_argument_in_the_file() { - let entries = format!("C:\\Program Files\\lib.jar;{}", classpath(500)); - let arguments = vec!["-cp".to_string(), entries, "Main".to_string()]; - - let LaunchCommandPlan::Argfile { - argfile_contents, .. - } = plan_launch_command("java", &arguments, &argfile(), None, Some(21)) - else { - panic!("an oversized classpath must be shortened"); - }; - assert!(argfile_contents.contains("\"C:\\\\Program Files\\\\lib.jar;")); - } - - #[test] - fn an_oversized_command_without_path_lists_is_left_to_the_operating_system() { - let arguments = vec!["Main".to_string(), classpath(500)]; - assert_eq!( - plan_launch_command("java", &arguments, &argfile(), None, Some(21)), - LaunchCommandPlan::Direct - ); - } - - #[test] - fn the_limit_is_configurable_for_hosts_with_a_different_cap() { - let arguments = vec![ - "-cp".to_string(), - classpath(20), - "com.example.Main".to_string(), - ]; - assert_eq!( - plan_launch_command("java", &arguments, &argfile(), None, Some(21)), - LaunchCommandPlan::Direct - ); - assert!(matches!( - plan_launch_command("java", &arguments, &argfile(), Some(2_500), Some(21)), - LaunchCommandPlan::Argfile { .. } - )); - } - - #[test] - fn unicode_text_is_returned_for_the_host_to_encode_on_supported_jdks() { - let arguments = vec![ - "-cp".into(), - format!("C:\\Users\\示例;{}", classpath(500)), - "Main".into(), - ]; - for version in [9, 17, 21] { - let LaunchCommandPlan::Argfile { - argfile_contents, .. - } = plan_launch_command("java.exe", &arguments, &argfile(), None, Some(version)) - else { - panic!("a known supported JDK can use a host-encoded file"); - }; - assert!(argfile_contents.contains("示例")); - } - } - - #[test] - fn non_java_and_unknown_or_unsupported_jdks_are_not_rewritten() { - let arguments = vec!["-p".into(), classpath(500)]; - for executable in ["node.exe", "python.exe", "custom-launcher"] { - assert_eq!( - plan_launch_command(executable, &arguments, &argfile(), None, Some(21)), - LaunchCommandPlan::Direct - ); - } - for version in [None, Some(8)] { - assert_eq!( - plan_launch_command("java.exe", &arguments, &argfile(), None, version), - LaunchCommandPlan::Direct - ); - } - } - - #[test] - fn application_arguments_keep_their_meaning_after_every_launch_target() { - for target in [ - vec!["Main"], - vec!["-jar", "app.jar"], - vec!["-m", "app/Main"], - vec!["--module=app/Main"], - ] { - let mut arguments = vec!["-cp".into(), classpath(500)]; - arguments.extend(target.into_iter().map(str::to_string)); - arguments.extend(["-p", "8080", "--class-path", "program-value"].map(str::to_string)); - let LaunchCommandPlan::Argfile { - arguments: shortened, - argfile_contents, - } = plan_launch_command("java.exe", &arguments, &argfile(), None, Some(21)) - else { - panic!("classpath should move"); - }; - assert_eq!(&shortened[1..], &arguments[2..]); - assert!(!argfile_contents.contains("8080")); - assert!(!argfile_contents.contains("program-value")); - } - } - - #[test] - fn launcher_option_values_are_not_mistaken_for_path_options() { - let arguments = vec![ - "--add-modules".into(), - "-p".into(), - "-cp".into(), - classpath(500), - "Main".into(), - ]; - let LaunchCommandPlan::Argfile { - arguments: shortened, - .. - } = plan_launch_command("java.exe", &arguments, &argfile(), None, Some(21)) - else { - panic!("classpath should move"); - }; - assert_eq!(&shortened[..2], &arguments[..2]); - let disabled = vec![ - "--disable-@files".into(), - "-cp".into(), - classpath(500), - "Main".into(), - ]; - assert_eq!( - plan_launch_command("java.exe", &disabled, &argfile(), None, Some(21)), - LaunchCommandPlan::Direct - ); - } - - #[test] - fn launch_command_uses_host_read_release_contents_for_jdk_version() { - let mut request = serde_json::json!({ - "id": "java-version", "command": "execution.planLaunchCommand", - "payload": { - "executable": "/jdk/bin/java", "arguments": ["-cp", classpath(500), "Main"], - "argfilePath": "/tmp/launch.args", "javaReleaseContents": [ - "IMPLEMENTOR=\"fixture\"\n", "JAVA_VERSION=\"21.0.2\"\n" - ] - } - }); - let response: serde_json::Value = - serde_json::from_str(&crate::execute_json(&request.to_string())).unwrap(); - assert_eq!(response["ok"], true, "{response}"); - assert_eq!(response["data"]["kind"], "argfile"); - request["payload"]["javaReleaseContents"] = - serde_json::json!(["JAVA_VERSION=\"unknown\"\n", "JAVA_VERSION=\"21\"\n"]); - let response: serde_json::Value = - serde_json::from_str(&crate::execute_json(&request.to_string())).unwrap(); - assert_eq!(response["data"]["kind"], "direct"); - request["payload"]["javaFeatureVersion"] = serde_json::json!(21); - let response: serde_json::Value = - serde_json::from_str(&crate::execute_json(&request.to_string())).unwrap(); - assert_eq!(response["data"]["kind"], "argfile"); - } - - #[test] - fn the_release_file_reports_the_feature_version() { - for version in ["21.0.2", "1.8.0_392", "25-ea+35", "17.0.12+7"] { - let release = format!("IMPLEMENTOR=\"fixture\"\nJAVA_VERSION=\"{version}\"\n"); - assert_eq!(java_version_from_release(&release), Some(version)); - } - assert_eq!( - java_version_from_release("JAVA_VERSION=\"unknown\"\n"), - None - ); - assert_eq!( - java_feature_version_from_release("IMPLEMENTOR=\"x\"\nJAVA_VERSION=\"21.0.2\"\n"), - Some(21) - ); - assert_eq!( - java_feature_version_from_release("JAVA_VERSION=\"1.8.0_392\"\n"), - Some(8) - ); - assert_eq!( - java_feature_version_from_release("JAVA_VERSION=\"17\"\n"), - Some(17) - ); - assert_eq!( - java_feature_version_from_release("MODULES=\"java.base\"\n"), - None - ); - } -} diff --git a/rust/lithe-core/src/execution/mod.rs b/rust/lithe-core/src/execution/mod.rs index 2530a7f527..7fa3cd2bfe 100644 --- a/rust/lithe-core/src/execution/mod.rs +++ b/rust/lithe-core/src/execution/mod.rs @@ -5,20 +5,13 @@ mod configuration; mod context_selection; mod detectors; pub(crate) mod generated_layer; -mod java_selection; -mod launch_command; -mod project_ownership; mod provider_run_options; mod provider_runs; -// Toolchain requirement reading that a host-side Java selector needs without -// owning Core's in-process generated layer. +// Toolchain requirement reading for hosts that select a toolchain candidate +// without owning Core's in-process generated layer. pub use configuration::{ - java_feature_version_parts, read_requirements, validate_sidecar_version, version_parts, - version_satisfies, ToolchainRequirementsDocument, -}; -pub use java_selection::{ - compare_java_candidates, select_java, select_java_candidates, JavaSelection, - JavaSelectionCandidate, JavaSelectionRequest, + read_requirements, validate_sidecar_version, version_parts, version_satisfies, + ToolchainRequirementsDocument, }; mod types; @@ -26,11 +19,6 @@ pub(crate) use argument_text::{format_argument_text, ArgumentTextRequest}; pub(crate) use configuration::*; pub(crate) use context_selection::{select_context_configuration, ContextSelectionRequest}; pub(crate) use detectors::{scan, DirectoryContext}; -pub use launch_command::{ - java_feature_version_from_release, java_version_from_release, plan_launch_command, - plan_launch_command_request, LaunchCommandPlan, LaunchCommandPlanRequest, - LaunchCommandPlanResponse, WINDOWS_COMMAND_LINE_LIMIT, -}; pub(crate) mod workspace_scan; pub use workspace_scan::is_run_scan_excluded_directory; diff --git a/rust/lithe-core/src/execution/project_ownership.rs b/rust/lithe-core/src/execution/project_ownership.rs deleted file mode 100644 index c70079dc26..0000000000 --- a/rust/lithe-core/src/execution/project_ownership.rs +++ /dev/null @@ -1,200 +0,0 @@ -//! Validates current provider project/source ownership for Run generation. -//! This is a projection of upstream models, never a descriptor scanner. - -use crate::protocol::{CoreError, ErrorCode, JavaSourceSetResponse}; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; - -/// One current build-model project and its own Java content roots. -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RunProjectOwnership { - /// Workspace-relative project directory, including `.` for the root. - pub path: String, - /// Upstream project label; never interpreted as a framework or selector. - #[serde(default)] - pub name: Option, - /// Compiler language floor published by the upstream execution model. - #[serde(default)] - pub minimum_java_version: Option, - /// Exact current build-model owner; no build-system semantics are interpreted. - #[serde(default)] - pub build: Option, - /// Source roles published for this project by the build model. - #[serde(default)] - pub content_roots: Vec, -} - -/// Opaque build-model identity used to route native language preparation. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RunBuildProjectReference { - /// Enabled package contributing this model. - #[serde(rename = "pluginID")] - pub plugin_id: String, - /// Declaration within the package. - #[serde(rename = "buildSystemID")] - pub build_system_id: String, - /// Workspace-relative instance directory. - pub root: String, - /// Provider-owned project identity, not a filesystem path. - #[serde(rename = "projectID")] - pub project_id: String, -} - -/// A source directory and upstream-owned role; paths are workspace-relative. -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RunSourceRoot { - pub path: String, - /// `source`, `testSource`, `generatedSource` or `generatedTestSource`. - pub kind: String, -} - -fn contains(root: &str, path: &str) -> bool { - root == "." || root == path || path.starts_with(&(root.to_string() + "/")) -} - -fn portable(path: &str) -> bool { - !path.is_empty() - && path.len() <= 4096 - && !path.contains(['\\', '\0', ':']) - && (path == "." - || path - .split('/') - .all(|part| !part.is_empty() && part != "." && part != "..")) -} - -/// Rejects incomplete, duplicate or escaping host projections before generation. -pub(super) fn validate(projects: &[RunProjectOwnership]) -> Result<(), CoreError> { - let invalid = || { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid provider project ownership for Run generation", - ) - }; - if projects.len() > 2000 - || projects - .iter() - .map(|p| p.content_roots.len()) - .sum::() - > 10000 - { - return Err(invalid()); - } - let mut paths = BTreeSet::new(); - for project in projects { - if !portable(&project.path) - || !paths.insert(&project.path) - || project.build.as_ref().is_some_and(|build| { - !crate::plugins::declarative::is_plugin_id(&build.plugin_id) - || !crate::plugins::declarative::is_identifier(&build.build_system_id) - || build.build_system_id.len() > 120 - || build.project_id.is_empty() - || build.project_id.len() > 256 - || build.project_id.chars().any(char::is_control) - || !portable(&build.root) - || !contains(&build.root, &project.path) - }) - { - return Err(invalid()); - } - if project - .minimum_java_version - .as_deref() - .is_some_and(|value| { - value.parse::().ok().is_none_or(|feature| { - feature == 0 || feature > 999 || feature.to_string() != value - }) - }) - { - return Err(invalid()); - } - let mut roots = BTreeSet::new(); - for root in &project.content_roots { - if !portable(&root.path) - || project - .build - .as_ref() - .is_some_and(|build| !contains(&build.root, &root.path)) - || !roots.insert((&root.path, &root.kind)) - || !matches!( - root.kind.as_str(), - "source" | "testSource" | "generatedSource" | "generatedTestSource" - ) - { - return Err(invalid()); - } - } - } - Ok(()) -} - -/// Prefer exact upstream source roots, then the deepest project boundary. -pub(super) fn owner<'a>( - projects: &'a [RunProjectOwnership], - source: &str, -) -> Option<&'a RunProjectOwnership> { - projects - .iter() - .filter_map(|project| { - let source_depth = project - .content_roots - .iter() - .filter(|root| contains(&root.path, source)) - .map(|root| root.path.len()) - .max(); - (source_depth.is_some() || contains(&project.path, source)) - .then_some((source_depth, project)) - }) - .max_by(|(left_depth, left), (right_depth, right)| { - (left_depth, left.path.len(), &left.path).cmp(&( - right_depth, - right.path.len(), - &right.path, - )) - }) - .map(|(_, project)| project) -} - -impl RunProjectOwnership { - /// Source set comes from the selected project's roots, not a directory name. - pub(super) fn source_set(&self, source: &str) -> JavaSourceSetResponse { - match self - .content_roots - .iter() - .filter(|root| contains(&root.path, source)) - .max_by(|left, right| { - (left.path.len(), &left.kind).cmp(&(right.path.len(), &right.kind)) - }) - .map(|root| root.kind.as_str()) - { - Some("testSource" | "generatedTestSource") => JavaSourceSetResponse::Test, - Some("source" | "generatedSource") => JavaSourceSetResponse::Main, - _ => JavaSourceSetResponse::Other, - } - } -} - -/// Stable identity for all facts consumed by generation, independent of list order. -pub(super) fn fingerprint(projects: &[RunProjectOwnership]) -> String { - use sha2::{Digest, Sha256}; - let mut projects = projects.iter().collect::>(); - projects.sort_by(|left, right| left.path.cmp(&right.path)); - let canonical = projects - .into_iter() - .map(|project| { - let roots = project - .content_roots - .iter() - .map(|root| (&root.path, &root.kind)) - .collect::>(); - serde_json::json!({"path":project.path,"name":project.name,"build":project.build, - "minimumJavaVersion":project.minimum_java_version, - "contentRoots":roots}) - }) - .collect::>(); - let bytes = - serde_json::to_vec(&canonical).expect("Provider ownership contains only JSON-safe values"); - format!("sha256:{:x}", Sha256::digest(bytes)) -} diff --git a/rust/lithe-core/src/execution/types.rs b/rust/lithe-core/src/execution/types.rs index e90b246f49..c0b9c4c7ef 100644 --- a/rust/lithe-core/src/execution/types.rs +++ b/rust/lithe-core/src/execution/types.rs @@ -43,10 +43,10 @@ impl Default for Confidence { /// Whether a configuration runs the project itself or the external services it /// depends on. /// -/// A Docker Compose file in a Java repository usually declares databases and -/// caches, not the application. Both are runnable, but presenting nineteen -/// containers beside the one Spring Boot service buries it, so hosts group -/// infrastructure separately instead of dropping it. +/// A Docker Compose file in an application repository usually declares +/// databases and caches, not the application. Both are runnable, but presenting +/// nineteen containers beside the one application service buries it, so hosts +/// group infrastructure separately instead of dropping it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RunCategory { diff --git a/rust/lithe-core/src/execution/workspace_scan.rs b/rust/lithe-core/src/execution/workspace_scan.rs index 7345931663..3cba2e1444 100644 --- a/rust/lithe-core/src/execution/workspace_scan.rs +++ b/rust/lithe-core/src/execution/workspace_scan.rs @@ -50,7 +50,7 @@ const EXCLUDED_DIRECTORIES: &[&str] = &[ "Pods", ]; -/// Default pruning for automatic run discovery, fingerprints and host Java lists. +/// Default pruning for automatic run discovery, fingerprints and host file lists. /// Hidden source directories are allowed unless explicitly named here. pub fn is_run_scan_excluded_directory(name: &str) -> bool { EXCLUDED_DIRECTORIES @@ -193,11 +193,11 @@ mod tests { } else if path.ends_with("a-blocked") { Err(io::Error::from(io::ErrorKind::PermissionDenied)) } else { - Ok(vec![(path.join("Main.java"), false, false)]) + Ok(vec![(path.join("main.txt"), false, false)]) } }; let unknown = visit_with_reader(root, None, &read, |directory| { - if directory.files.contains("Main.java") { + if directory.files.contains("main.txt") { ControlFlow::Break(()) } else { ControlFlow::Continue(()) @@ -224,7 +224,7 @@ mod tests { (root.join(".pytest_cache"), true, false), ]) } else if path.ends_with(".sources") { - Ok(vec![(path.join("Main.java"), false, false)]) + Ok(vec![(path.join("main.txt"), false, false)]) } else { Err(io::Error::from(io::ErrorKind::PermissionDenied)) } @@ -234,7 +234,7 @@ mod tests { assert!(result .directories .iter() - .any(|dir| dir.files.contains("Main.java"))); + .any(|dir| dir.files.contains("main.txt"))); assert!(scan_with_reader(root, None, &|_| Err(io::Error::from( io::ErrorKind::PermissionDenied ))) @@ -247,14 +247,14 @@ mod tests { assert_eq!(path, root, "links must never be traversed"); Ok(vec![ (root.join("cycle"), true, true), - (root.join("Main.java"), false, false), + (root.join("main.txt"), false, false), ]) }) .unwrap(); assert_eq!(result.directories.len(), 1); assert_eq!( result.directories[0].files, - BTreeSet::from(["Main.java".into()]) + BTreeSet::from(["main.txt".into()]) ); } } diff --git a/rust/lithe-core/src/git/mod.rs b/rust/lithe-core/src/git/mod.rs index 710e6081b6..37c002b521 100644 --- a/rust/lithe-core/src/git/mod.rs +++ b/rust/lithe-core/src/git/mod.rs @@ -8613,39 +8613,6 @@ pub(crate) fn ignored_paths( /// below it keeps large reactors from failing to start the query. const LS_FILES_PATHSPEC_BUDGET: usize = 16 * 1024; -/// Returns the entries of `candidates` that the Git repository enclosing -/// `directory` does not track. -/// -/// Candidates are paths relative to `directory` with `/` separators. `None` -/// means Git could not answer — `directory` is outside any work tree, the -/// repository is unreadable, or Git is unavailable — and callers must treat -/// every candidate as possibly owned by the user. -pub(crate) fn untracked_candidates(directory: &Path, candidates: &[String]) -> Option> { - let mut tracked = HashSet::new(); - for batch in pathspec_batches(candidates, LS_FILES_PATHSPEC_BUDGET) { - let mut arguments = vec!["--literal-pathspecs", "ls-files", "-z", "--"]; - arguments.extend(batch.iter().map(String::as_str)); - let output = run_git(directory, &arguments).ok()?; - if !output.status.success() { - return None; - } - tracked.extend( - output - .stdout - .split(|byte| *byte == 0) - .filter(|record| !record.is_empty()) - .map(|record| String::from_utf8_lossy(record).into_owned()), - ); - } - Some( - candidates - .iter() - .filter(|candidate| !tracked.contains(candidate.as_str())) - .cloned() - .collect(), - ) -} - /// Splits `paths` into consecutive non-empty batches whose summed byte length /// stays within `budget`; a single longer path forms its own batch. fn pathspec_batches(paths: &[String], budget: usize) -> Vec<&[String]> { diff --git a/rust/lithe-core/src/languages/java.rs b/rust/lithe-core/src/languages/java.rs deleted file mode 100644 index 8a1da7fb52..0000000000 --- a/rust/lithe-core/src/languages/java.rs +++ /dev/null @@ -1,1185 +0,0 @@ -//! Lightweight Java source and Maven-aware run-configuration inspection. - -use crate::protocol::{CoreError, ErrorCode}; -use crate::protocol::{ - JavaClassNameResponse, JavaCodeVisionHintResponse, JavaCodeVisionResponse, - JavaFoldRegionResponse, JavaInlayHintResponse, JavaMainClassResponse, - JavaRunConfigurationResponse, JavaRunConfigurationsResponse, JavaServerPortResponse, - JavaSourceSetResponse, JavaStructureResponse, -}; -use regex::Regex; -use serde::Deserialize; -use std::collections::{HashMap, HashSet}; -use std::fs; -use std::path::{Component, Path, PathBuf}; - -/// Launchable classes JDT reported, in the shape `lsp.request` returns for the -/// `javaEntrypoints` operation. -/// -/// Note: entry-point ownership is recorded in .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct JavaEntrypointFacts { - pub schema_version: u32, - pub entries: Vec, -} - -/// One class JDT confirmed the JVM can launch. -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct JavaEntrypointFact { - /// Workspace-relative source path with `/` separators. - pub source_path: String, - /// Class name as JDT reports it, possibly prefixed with `module/`. - pub main_class: String, - #[serde(default)] - pub project_name: Option, -} - -/// Only schema version this Core understands for [`JavaEntrypointFacts`]. -const JAVA_ENTRYPOINT_FACTS_SCHEMA_VERSION: u32 = 1; - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Source inputs for lightweight folds, markers, and inlay hints. -pub struct JavaStructureRequest { - pub source: String, - #[serde(default)] - pub declaration_sources: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Workspace sources used to count references for Code Vision hints. -pub struct JavaCodeVisionRequest { - pub root: String, - pub target_path: String, - #[serde(default)] - pub paths: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Source and simple name used to resolve a package-qualified class name. -pub struct JavaClassNameRequest { - pub source: String, - pub simple_name: String, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Source lookup for a type, method, or field declaration. -pub struct JavaSourceDefinitionRequest { - pub source: String, - pub declaration_name: String, - #[serde(default)] - pub member_name: Option, - /// Only a real member declaration counts, never a call or an assignment. - #[serde(default)] - pub declarations_only: bool, - /// Where the member is used. Resolves it from that scope instead of as a - /// member of `declaration_name`, and finds nothing when syntax cannot tell. - #[serde(default)] - pub reference: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Zero-based position of the first character of a member reference. -pub struct JavaSourceReference { - pub line: usize, - pub utf16_column: usize, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Spring configuration content inspected for a declared server port. -pub struct JavaServerPortRequest { - pub content: String, - pub file_extension: String, -} - -/// Builds Java and Spring Boot run entries from the entry points JDT confirmed. -/// -/// Whether a class is launchable is JDT's answer and is taken as given; this -/// never inspects a signature. Source is read only to label a confirmed entry -/// as a Spring Boot service, which is a product classification. -pub(crate) fn run_configurations_from_entrypoints( - root: &Path, - facts: &JavaEntrypointFacts, - module_paths: &[String], -) -> Result { - if facts.schema_version != JAVA_ENTRYPOINT_FACTS_SCHEMA_VERSION { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Unsupported Java entry-point schema version", - ) - .with_details(facts.schema_version.to_string())); - } - // Sorted so the outcome does not depend on the order JDT or a previous - // generation listed the entries in. - let mut entries = facts.entries.iter().collect::>(); - entries.sort_by(|left, right| { - (&left.source_path, &left.main_class).cmp(&(&right.source_path, &right.main_class)) - }); - let mut main_classes = Vec::new(); - for fact in entries { - let relative = normalize_relative(&fact.source_path).ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java entry-point source path must be workspace-relative", - ) - .with_details(fact.source_path.clone()) - })?; - // Source is read only to classify a confirmed entry as a Spring Boot - // service. An entry whose source cannot be decoded (missing file or an - // unknown legacy charset) becomes a plain Java entry instead of failing - // the whole run list; JDT already confirmed the class is launchable. - let source = crate::languages::read_text(&root.join(&relative)).unwrap_or_default(); - // A modular project reports `module/pkg.Type`; configuration ids and - // names use the class itself so they stay stable across that change. - let qualified_name = fact - .main_class - .rsplit_once('/') - .map_or(fact.main_class.as_str(), |(_, class)| class) - .to_string(); - let simple_name = qualified_name - .rsplit_once('.') - .map_or(qualified_name.as_str(), |(_, name)| name) - .to_string(); - main_classes.push(JavaMainClassResponse { - path: relative, - qualified_name, - simple_name, - is_spring_boot: super::java_syntax::declares_spring_boot_application(&source), - }); - } - - let mut configurations = main_classes - .iter() - .map(|value| JavaRunConfigurationResponse { - id: if value.is_spring_boot { - format!("spring:{}", value.qualified_name) - } else { - format!("java-main:{}", value.qualified_name) - }, - name: value.simple_name.clone(), - kind: if value.is_spring_boot { - "springBoot".to_string() - } else { - "javaMain".to_string() - }, - module_path: module_path(&value.path, module_paths), - main_class: Some(value.qualified_name.clone()), - source_path: value.path.clone(), - source_set: java_source_set(&value.path), - }) - .collect::>(); - configurations.sort_by(|left, right| { - kind_order(&left.kind) - .cmp(&kind_order(&right.kind)) - .then_with(|| left.name.to_lowercase().cmp(&right.name.to_lowercase())) - .then_with(|| left.source_path.cmp(&right.source_path)) - }); - - Ok(JavaRunConfigurationsResponse { - main_classes, - configurations, - }) -} - -/// Computes lightweight Java structure without starting a language server. -pub fn structure(request: JavaStructureRequest) -> Result { - let source = request.source; - Ok(JavaStructureResponse { - fold_regions: fold_regions(&source), - inlay_hints: parameter_hints(&source, &request.declaration_sources), - syntax_highlights: super::java_syntax::syntax_highlights(&source), - }) -} - -/// Counts workspace references for declarations in the target source file. -pub fn code_vision(request: JavaCodeVisionRequest) -> Result { - let root = existing_root(&request.root)?; - let target_path = normalize_relative(&request.target_path).ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java target path must be relative", - ) - })?; - let target_source = crate::languages::read_text(&root.join(&target_path)).map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Could not read Java target source") - .with_details(error.to_string()) - })?; - let mut sources = Vec::new(); - for path in request.paths { - let Some(relative) = normalize_relative(&path) else { - continue; - }; - if !relative.to_lowercase().ends_with(".java") { - continue; - } - if let Ok(source) = crate::languages::read_text(&root.join(relative)) { - sources.push(source); - } - } - let mut hints = Vec::new(); - for (line, column, symbol) in java_declarations(&target_source) { - let expression = - Regex::new(&format!(r"\b{}\b", regex::escape(&symbol))).map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Could not parse Java symbol") - .with_details(error.to_string()) - })?; - let count = sources - .iter() - .map(|source| expression.find_iter(source).count()) - .sum::(); - hints.push(JavaCodeVisionHintResponse { - line, - utf16_column: column, - symbol, - usage_count: count.saturating_sub(1), - }); - } - Ok(JavaCodeVisionResponse { hints }) -} - -/// Resolves a simple class name against the source package declaration. -pub fn class_name(request: JavaClassNameRequest) -> Result { - let package = Regex::new(r"(?m)^\s*package\s+([A-Za-z_][A-Za-z0-9_.]*)\s*;") - .expect("static Java package expression is valid") - .captures(&request.source) - .and_then(|captures| captures.get(1).map(|value| value.as_str().to_string())); - Ok(JavaClassNameResponse { - class_name: package - .map(|value| format!("{}.{}", value, request.simple_name)) - .unwrap_or(request.simple_name), - }) -} - -/// Finds a type or member declaration in one Java source document. -pub fn source_definition( - request: JavaSourceDefinitionRequest, -) -> Result, CoreError> { - let lines = request.source.split('\n').collect::>(); - if let Some(member) = request.member_name { - let declared = match &request.reference { - Some(reference) => referenced_member(&request.source, &member, reference), - None => member_declaration(&request.source, &request.declaration_name, &member), - }; - if let Some((line, utf16_column)) = declared { - return Ok(Some(crate::protocol::JavaSourceDefinitionResponse { - line, - utf16_column, - })); - } - if request.declarations_only { - return Ok(None); - } - let method = - Regex::new(&format!(r"\b{}\s*\(", regex::escape(&member))).map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Could not parse Java member") - .with_details(error.to_string()) - })?; - for (line_number, line) in lines.iter().enumerate() { - if let Some(found) = method.find(line) { - let prefix = line[..found.start()].trim(); - if !prefix.starts_with('*') - && !prefix.starts_with("//") - && !prefix.contains('#') - && !prefix.ends_with('.') - { - return Ok(Some(crate::protocol::JavaSourceDefinitionResponse { - line: line_number, - utf16_column: utf16_column(line, found.start()), - })); - } - } - } - let field = - Regex::new(&format!(r"\b{}\s*(?:=|;)", regex::escape(&member))).map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Could not parse Java field") - .with_details(error.to_string()) - })?; - for (line_number, line) in lines.iter().enumerate() { - if let Some(found) = field.find(line) { - return Ok(Some(crate::protocol::JavaSourceDefinitionResponse { - line: line_number, - utf16_column: utf16_column(line, found.start()), - })); - } - } - } - - let declaration = Regex::new(&format!( - r"\b(?:class|interface|enum|record)\s+{}\b", - regex::escape(&request.declaration_name) - )) - .map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Could not parse Java declaration") - .with_details(error.to_string()) - })?; - for (line_number, line) in lines.iter().enumerate() { - if let Some(found) = declaration.find(line) { - let offset = line[found.start()..found.end()] - .find(&request.declaration_name) - .map(|value| found.start() + value) - .unwrap_or(found.start()); - return Ok(Some(crate::protocol::JavaSourceDefinitionResponse { - line: line_number, - utf16_column: utf16_column(line, offset), - })); - } - } - Ok(None) -} - -fn parse_java(source: &str) -> Option { - let mut parser = tree_sitter::Parser::new(); - parser - .set_language(&tree_sitter_java::LANGUAGE.into()) - .ok()?; - parser.parse(source, None) -} - -/// Zero-based line and UTF-16 column of a declared name. -fn declaration_position(source: &str, declared: tree_sitter::Node) -> Option<(usize, usize)> { - let point = declared.start_position(); - let line = source.split('\n').nth(point.row)?; - Some((point.row, utf16_column(line, point.column))) -} - -#[derive(Clone, Copy, Eq, PartialEq)] -enum MemberKind { - Method, - Field, -} - -fn is_type_body(node: tree_sitter::Node) -> bool { - matches!( - node.kind(), - "class_body" | "interface_body" | "enum_body" | "annotation_type_body" - ) -} - -fn has_name(node: tree_sitter::Node, source: &str, name: &str) -> bool { - node.child_by_field_name("name") - .is_some_and(|declared| declared.utf8_text(source.as_bytes()) == Ok(name)) -} - -/// Finds a member declared directly in a type body, not in a type nested inside it. -/// -/// `kind` narrows the search because Java keeps methods and fields in separate -/// namespaces; `None` accepts either. -fn direct_member<'tree>( - body: tree_sitter::Node<'tree>, - name: &str, - kind: Option, - source: &str, -) -> Option> { - let accepts = |wanted: MemberKind| kind.is_none_or(|kind| kind == wanted); - let named = |node: tree_sitter::Node<'tree>| { - has_name(node, source, name) - .then(|| node.child_by_field_name("name")) - .flatten() - }; - // A record component is a field the body can use without declaring it. - if let Some(components) = body - .parent() - .filter(|parent| parent.kind() == "record_declaration" && accepts(MemberKind::Field)) - .and_then(|parent| parent.child_by_field_name("parameters")) - { - let mut cursor = components.walk(); - let component = components - .named_children(&mut cursor) - .find_map(|component| named(component)); - if component.is_some() { - return component; - } - } - let mut cursor = body.walk(); - for member in body.named_children(&mut cursor) { - let declared = match member.kind() { - "method_declaration" if accepts(MemberKind::Method) => named(member), - "enum_constant" | "annotation_type_element_declaration" - if accepts(MemberKind::Field) => - { - named(member) - } - "field_declaration" | "constant_declaration" if accepts(MemberKind::Field) => { - let mut declarators = member.walk(); - let declared = member - .children_by_field_name("declarator", &mut declarators) - .find_map(|declarator| named(declarator)); - declared - } - "enum_body_declarations" => direct_member(member, name, kind, source), - _ => None, - }; - if declared.is_some() { - return declared; - } - } - None -} - -/// Finds a method, field, or enum constant that the type `type_name` declares itself. -fn member_declaration(source: &str, type_name: &str, name: &str) -> Option<(usize, usize)> { - let tree = parse_java(source)?; - let mut pending = vec![tree.root_node()]; - while let Some(node) = pending.pop() { - if let Some(body) = node - .child_by_field_name("body") - .filter(|body| is_type_body(*body) && has_name(node, source, type_name)) - { - let declared = direct_member(body, name, None, source)?; - return declaration_position(source, declared); - } - // Reversed so the stack visits declarations in source order. - let mut cursor = node.walk(); - let children: Vec<_> = node.children(&mut cursor).collect(); - pending.extend(children.into_iter().rev()); - } - None -} - -/// Whether a type may inherit a member, which syntax cannot see. -fn may_inherit(declaration: tree_sitter::Node) -> bool { - let mut cursor = declaration.walk(); - let extends_interfaces = declaration - .children(&mut cursor) - .any(|child| child.kind() == "extends_interfaces"); - extends_interfaces - || matches!( - declaration.kind(), - "object_creation_expression" | "enum_constant" - ) - || declaration.child_by_field_name("superclass").is_some() - || declaration.child_by_field_name("interfaces").is_some() -} - -/// Whether a member's code declares a local variable or parameter called `name`. -/// -/// This ignores block scope on purpose. A same-named local elsewhere in the -/// member makes the answer uncertain, and an uncertain name stays unanswered. -fn declares_local(member: tree_sitter::Node, name: &str, source: &str) -> bool { - let mut pending = vec![member]; - while let Some(node) = pending.pop() { - let declares = match node.kind() { - "variable_declarator" => { - !matches!( - node.parent().map(|parent| parent.kind()), - Some("field_declaration" | "constant_declaration") - ) && has_name(node, source, name) - } - "formal_parameter" - | "catch_formal_parameter" - | "enhanced_for_statement" - | "resource" - | "instanceof_expression" => has_name(node, source, name), - "inferred_parameters" - | "lambda_expression" - | "type_pattern" - | "record_pattern_component" => { - let mut cursor = node.walk(); - let declares = node - .named_children(&mut cursor) - .filter(|child| child.kind() == "identifier") - .any(|child| child.utf8_text(source.as_bytes()) == Ok(name)); - declares - } - _ => false, - }; - if declares { - return true; - } - let mut cursor = node.walk(); - pending.extend( - node.named_children(&mut cursor) - .filter(|child| !is_type_body(*child)), - ); - } - false -} - -/// Resolves a member reference to the declaration its scope binds it to. -/// -/// Only a plain name or a `this.` access qualifies: any other receiver has a -/// type that syntax cannot resolve. The search starts in the innermost type and -/// moves outward, stopping at a type that may inherit the name and, for a plain -/// field name, at a local that may shadow it. -fn referenced_member( - source: &str, - name: &str, - reference: &JavaSourceReference, -) -> Option<(usize, usize)> { - let tree = parse_java(source)?; - let line = source.split('\n').nth(reference.line)?; - let mut utf16_offset = 0; - let byte = line - .char_indices() - .find(|(_, character)| { - let reached = utf16_offset >= reference.utf16_column; - utf16_offset += character.len_utf16(); - reached - })? - .0; - let start = tree_sitter::Point::new(reference.line, byte); - let end = tree_sitter::Point::new(reference.line, byte + 1); - let identifier = tree.root_node().descendant_for_point_range(start, end)?; - if identifier.kind() != "identifier" || identifier.utf8_text(source.as_bytes()) != Ok(name) { - return None; - } - - let parent = identifier.parent()?; - let receiver = match parent.kind() { - "method_invocation" if parent.child_by_field_name("name") == Some(identifier) => { - parent.child_by_field_name("object") - } - "field_access" if parent.child_by_field_name("field") == Some(identifier) => { - parent.child_by_field_name("object") - } - "method_reference" | "element_value_pair" | "labeled_statement" | "break_statement" - | "continue_statement" => return None, - _ => None, - }; - if receiver.is_some_and(|receiver| receiver.kind() != "this") { - return None; - } - let is_call = parent.kind() == "method_invocation" - && parent.child_by_field_name("name") == Some(identifier); - let kind = if is_call { - MemberKind::Method - } else { - MemberKind::Field - }; - - let mut inner = identifier; - while let Some(scope) = inner.parent() { - if is_type_body(scope) { - if kind == MemberKind::Field - && receiver.is_none() - && declares_local(inner, name, source) - { - return None; - } - if let Some(declared) = direct_member(scope, name, Some(kind), source) { - return declaration_position(source, declared); - } - if receiver.is_some() || scope.parent().is_none_or(may_inherit) { - return None; - } - } - inner = scope; - } - None -} - -/// Reads a Spring server port from properties or YAML content. -pub fn server_port(request: JavaServerPortRequest) -> Result { - if request.file_extension.eq_ignore_ascii_case("properties") { - for line in request.content.lines() { - let value = line.trim(); - if value.starts_with('#') { - continue; - } - let Some((key, port)) = - value.split_once(|character| character == ':' || character == '=') - else { - continue; - }; - if key.trim() == "server.port" { - return Ok(JavaServerPortResponse { - port: port.trim().parse().ok(), - }); - } - } - return Ok(JavaServerPortResponse { port: None }); - } - - let mut in_server_section = false; - for line in request.content.lines() { - let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') { - continue; - } - if trimmed == "server:" { - in_server_section = true; - continue; - } - if in_server_section && line.chars().next().is_some_and(char::is_whitespace) { - if let Some((key, port)) = trimmed.split_once(':') { - if key.trim() == "port" { - return Ok(JavaServerPortResponse { - port: port.trim().parse().ok(), - }); - } - } - continue; - } - in_server_section = false; - } - Ok(JavaServerPortResponse { port: None }) -} - -/// Returns the fully qualified class name to launch for a standalone Java file. -/// -/// Standalone runs compile the file with `javac` and then start it with -/// `java `, so the launcher needs the class name the JVM will look up — -/// not the file path. The name is derived structurally (declared package plus -/// [`launch_class_name`]) and does not require a `main` method: when the file -/// has none, the JVM emits its own clear diagnostic, which is more useful than a -/// Core error. Files without any `class` declaration fall back to the file stem, -/// matching the convention `javac` uses for the generated class. -pub(crate) fn standalone_launch_class(path: &str, source: &str) -> String { - let simple_name = launch_class_name(path, source).unwrap_or_else(|| file_stem(path)); - match declared_package(source) { - Some(package) => format!("{package}.{simple_name}"), - None => simple_name, - } -} - -/// Picks the simple class name the JVM should launch for a single source file. -/// -/// A compilable `.java` file names its public class after the file, so the file -/// stem is the reliable answer whenever the source actually declares that class. -/// Preferring the stem also rejects a `class` token that only appears in a -/// comment, and a helper class that happens to be declared before the public -/// one. When no declared class matches the stem the first declared class is -/// used, which is the JDK source launcher's rule (JEP 330), and `None` is -/// returned when the source declares no class at all — a compact source file, -/// whose implicit class `javac` names after the file. -/// -/// This is `javac` naming, not entry-point detection: which classes are -/// launchable is JDT's answer, and the JVM reports a class without a usable -/// `main` itself. -fn launch_class_name(path: &str, source: &str) -> Option { - let classes = declared_classes(source); - if classes.is_empty() { - return None; - } - let stem = file_stem(path); - if classes.iter().any(|(_, name)| name == &stem) { - return Some(stem); - } - classes.first().map(|(_, name)| name.clone()) -} - -/// Returns every declared class name paired with the byte offset of its -/// declaration, in source order, ignoring modifiers such as `public`/`final`. -fn declared_classes(source: &str) -> Vec<(usize, String)> { - let class_pattern = - Regex::new(r"\b(?:public\s+)?(?:final\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)") - .expect("class declaration pattern is a valid regex"); - class_pattern - .captures_iter(source) - .filter_map(|captures| { - let name = captures.get(1)?; - Some((captures.get(0)?.start(), name.as_str().to_string())) - }) - .collect() -} - -/// Extracts the declared package, or `None` for the default package. -fn declared_package(source: &str) -> Option { - Regex::new(r"(?m)^\s*package\s+([A-Za-z_$][A-Za-z0-9_$.]*)\s*;") - .ok()? - .captures(source) - .and_then(|captures| captures.get(1).map(|value| value.as_str().to_string())) -} - -/// Returns the file name without directories or the `.java` extension. -fn file_stem(path: &str) -> String { - let name = path.rsplit('/').next().unwrap_or(path); - name.strip_suffix(".java") - .or_else(|| name.strip_suffix(".JAVA")) - .unwrap_or(name) - .to_string() -} - -fn module_path(path: &str, modules: &[String]) -> Option { - modules - .iter() - .filter(|module| is_inside(path, module)) - .max_by_key(|module| module.len()) - .cloned() -} - -fn java_source_set(path: &str) -> JavaSourceSetResponse { - let normalized = path.to_ascii_lowercase(); - if normalized.starts_with("src/test/") || normalized.contains("/src/test/") { - JavaSourceSetResponse::Test - } else if normalized.starts_with("src/main/") || normalized.contains("/src/main/") { - JavaSourceSetResponse::Main - } else { - JavaSourceSetResponse::Other - } -} - -fn is_inside(path: &str, directory: &str) -> bool { - path == directory || path.starts_with(&(directory.trim_end_matches('/').to_string() + "/")) -} - -fn kind_order(kind: &str) -> usize { - match kind { - "springBoot" => 0, - "javaMain" => 1, - _ => 2, - } -} - -fn fold_regions(source: &str) -> Vec { - let mut regions = import_region(source).into_iter().collect::>(); - regions.extend(comment_regions(source)); - regions.extend(brace_regions(source)); - regions.sort_by(|left, right| { - left.start_line - .cmp(&right.start_line) - .then_with(|| right.end_line.cmp(&left.end_line)) - }); - regions -} - -fn import_region(source: &str) -> Option { - let expression = Regex::new(r"(?m)^[ \t]*import[ \t]+[^;]+;[ \t]*$").ok()?; - let matches = expression.find_iter(source).collect::>(); - let first = matches.first()?; - let last = matches.last()?; - if matches.len() < 2 { - return None; - } - Some(JavaFoldRegionResponse { - kind: "imports".to_string(), - start_line: line_number(source, first.start()), - end_line: line_number(source, last.start()), - hidden_start: utf16_offset(source, line_end(source, first.start())), - hidden_length: utf16_offset(source, line_end(source, last.start())) - .saturating_sub(utf16_offset(source, line_end(source, first.start()))), - }) -} - -fn comment_regions(source: &str) -> Vec { - let Ok(expression) = Regex::new(r"/\*[\s\S]*?\*/") else { - return Vec::new(); - }; - expression - .find_iter(source) - .filter_map(|matched| { - let start_line = line_number(source, matched.start()); - let end_line = line_number(source, matched.end()); - (end_line > start_line).then(|| JavaFoldRegionResponse { - kind: "comment".to_string(), - start_line, - end_line, - hidden_start: utf16_offset(source, line_end(source, matched.start())), - hidden_length: utf16_offset(source, matched.end()) - .saturating_sub(utf16_offset(source, line_end(source, matched.start()))), - }) - }) - .collect() -} - -fn brace_regions(source: &str) -> Vec { - let bytes = source.as_bytes(); - let mut stack: Vec<(usize, String)> = Vec::new(); - let mut regions = Vec::new(); - let mut index = 0; - let mut state = ScanState::Code; - while index < bytes.len() { - let character = bytes[index]; - let next = bytes.get(index + 1).copied().unwrap_or_default(); - match state { - ScanState::Code => match character { - b'"' => state = ScanState::String, - b'\'' => state = ScanState::Character, - b'/' if next == b'/' => { - state = ScanState::LineComment; - index += 1; - } - b'/' if next == b'*' => { - state = ScanState::BlockComment; - index += 1; - } - b'{' => { - let start = line_start(source, index); - stack.push((index, source[start..index].to_string())); - } - b'}' => { - if let Some((opening, prefix)) = stack.pop() { - let start_line = line_number(source, opening); - let end_line = line_number(source, index); - let hidden_start = line_end(source, opening); - let hidden_end = line_start(source, index); - if end_line > start_line && hidden_end > hidden_start { - regions.push(JavaFoldRegionResponse { - kind: classify(&prefix), - start_line, - end_line, - hidden_start: utf16_offset(source, hidden_start), - hidden_length: utf16_offset(source, hidden_end) - .saturating_sub(utf16_offset(source, hidden_start)), - }); - } - } - } - _ => {} - }, - ScanState::String => { - if character == b'\\' { - index += 1; - } else if character == b'"' { - state = ScanState::Code; - } - } - ScanState::Character => { - if character == b'\\' { - index += 1; - } else if character == b'\'' { - state = ScanState::Code; - } - } - ScanState::LineComment => { - if character == b'\n' { - state = ScanState::Code; - } - } - ScanState::BlockComment => { - if character == b'*' && next == b'/' { - state = ScanState::Code; - index += 1; - } - } - } - index += 1; - } - regions -} - -fn classify(prefix: &str) -> String { - if Regex::new(r"\b(class|interface|enum|record|struct|protocol|extension|actor)\b") - .expect("static Java type expression is valid") - .is_match(prefix) - { - "type".to_string() - } else if prefix.contains('(') && prefix.contains(')') { - "method".to_string() - } else { - "block".to_string() - } -} - -fn parameter_hints(source: &str, declaration_sources: &[String]) -> Vec { - let declaration_pattern = - Regex::new(r"\b([A-Za-z_$][A-Za-z0-9_$]*)[ \t]*\(([^(){};]*)\)[ \t]*(?:throws[^{]+)?\{") - .expect("static Java declaration expression is valid"); - let mut declarations: HashMap>> = HashMap::new(); - for text in declaration_sources { - for matched in declaration_pattern.captures_iter(text) { - let Some(name) = matched.get(1).map(|value| value.as_str()) else { - continue; - }; - if ["if", "for", "while", "switch", "catch", "new"].contains(&name) { - continue; - } - let parameters = matched - .get(2) - .map(|value| split_parameters(value.as_str())) - .unwrap_or_default(); - if !parameters.is_empty() { - declarations - .entry(name.to_string()) - .or_default() - .push(parameters); - } - } - } - let call_pattern = Regex::new(r"\b([A-Za-z_$][A-Za-z0-9_$]*)[ \t]*\(([^(){};]*)\)") - .expect("static Java call expression is valid"); - let mut hints = Vec::new(); - for matched in call_pattern.captures_iter(source) { - let Some(name) = matched.get(1).map(|value| value.as_str()) else { - continue; - }; - let Some(arguments) = matched.get(2) else { - continue; - }; - if looks_like_parameter_list(arguments.as_str()) { - continue; - } - let starts = argument_starts(source, arguments.start(), arguments.end()); - let Some(parameters) = declarations - .get(name) - .and_then(|values| values.iter().find(|value| value.len() == starts.len())) - else { - continue; - }; - let suffix = source[matched.get(0).unwrap().end()..] - .chars() - .take(40) - .collect::(); - let suffix = suffix.trim_start(); - if suffix.starts_with('{') || suffix.starts_with("throws ") { - continue; - } - for (index, start) in starts.iter().enumerate() { - hints.push(JavaInlayHintResponse { - line: line_number(source, *start), - utf16_column: utf16_offset(source, *start) - .saturating_sub(utf16_offset(source, line_start(source, *start))), - label: parameters[index].clone(), - }); - } - } - let mut seen = HashSet::new(); - hints.retain(|value| seen.insert((value.line, value.utf16_column, value.label.clone()))); - hints.sort_by(|left, right| { - left.line - .cmp(&right.line) - .then_with(|| left.utf16_column.cmp(&right.utf16_column)) - }); - hints -} - -fn java_declarations(source: &str) -> Vec<(usize, usize, String)> { - let type_pattern = - Regex::new(r"\b(?:class|interface|enum|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)") - .expect("static Java type expression is valid"); - let method_pattern = - Regex::new(r"\b([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^;{}]*\)\s*(?:throws\s+[^{}]+)?\{") - .expect("static Java method expression is valid"); - let ignored = [ - "if", - "for", - "while", - "switch", - "catch", - "try", - "synchronized", - "new", - ]; - let mut result = Vec::new(); - for (line_index, line) in source.split('\n').enumerate() { - if let Some(captures) = type_pattern.captures(line) { - if let Some(symbol) = captures.get(1) { - result.push(( - line_index, - utf16_column(line, symbol.start()), - symbol.as_str().to_string(), - )); - continue; - } - } - if let Some(captures) = method_pattern.captures(line) { - if let Some(symbol) = captures.get(1) { - if !ignored.contains(&symbol.as_str()) { - result.push(( - line_index, - utf16_column(line, symbol.start()), - symbol.as_str().to_string(), - )); - } - } - } - } - result -} - -fn utf16_column(line: &str, byte: usize) -> usize { - line[..byte.min(line.len())].encode_utf16().count() -} - -fn split_parameters(value: &str) -> Vec { - value - .split(',') - .filter_map(|parameter| { - let cleaned = Regex::new(r"@[A-Za-z_$][A-Za-z0-9_$]*(?:\([^)]*\))?") - .expect("static Java annotation expression is valid") - .replace_all(parameter, "") - .trim() - .to_string(); - cleaned - .split_whitespace() - .last() - .map(|value| value.to_string()) - }) - .collect() -} - -fn looks_like_parameter_list(value: &str) -> bool { - let identifier = Regex::new(r"^[A-Za-z_$][A-Za-z0-9_$]*$") - .expect("static Java identifier expression is valid"); - !value.trim().is_empty() - && value.split(',').all(|item| { - let words = item.split_whitespace().collect::>(); - words.len() >= 2 && identifier.is_match(words.last().copied().unwrap_or_default()) - }) -} - -fn argument_starts(source: &str, start: usize, end: usize) -> Vec { - if start >= end { - return Vec::new(); - } - let bytes = source.as_bytes(); - let mut result = Vec::new(); - let mut item_start = start; - let mut index = start; - let mut depth: usize = 0; - let mut quote = None; - while index < end { - let character = bytes[index]; - if let Some(active) = quote { - if character == b'\\' { - index += 1; - } else if character == active { - quote = None; - } - } else if character == b'"' || character == b'\'' { - quote = Some(character); - } else if matches!(character, b'(' | b'[' | b'{') { - depth += 1; - } else if matches!(character, b')' | b']' | b'}') { - depth = depth.saturating_sub(1); - } else if character == b',' && depth == 0 { - if let Some(value) = first_non_whitespace(source, item_start, index) { - result.push(value); - } - item_start = index + 1; - } - index += 1; - } - if let Some(value) = first_non_whitespace(source, item_start, end) { - result.push(value); - } - result -} - -fn first_non_whitespace(source: &str, start: usize, end: usize) -> Option { - source[start..end] - .char_indices() - .find(|(_, character)| !character.is_whitespace()) - .map(|(offset, _)| start + offset) -} - -fn existing_root(value: &str) -> Result { - let path = PathBuf::from(value); - let metadata = fs::metadata(&path) - .map_err(|_| CoreError::new(ErrorCode::WorkspaceNotFound, "Workspace does not exist"))?; - if !metadata.is_dir() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Workspace root must be a directory", - )); - } - path.canonicalize().map_err(CoreError::from) -} - -fn normalize_relative(value: &str) -> Option { - let path = Path::new(value.trim()); - if path.as_os_str().is_empty() - || path.is_absolute() - || path - .components() - .any(|value| matches!(value, Component::ParentDir)) - { - return None; - } - Some( - path.to_string_lossy() - .replace('\\', "/") - .trim_matches('/') - .to_string(), - ) -} - -fn line_number(source: &str, byte: usize) -> usize { - source[..byte.min(source.len())] - .bytes() - .filter(|value| *value == b'\n') - .count() -} - -fn line_start(source: &str, byte: usize) -> usize { - source[..byte.min(source.len())] - .rfind('\n') - .map(|value| value + 1) - .unwrap_or(0) -} - -fn line_end(source: &str, byte: usize) -> usize { - source[byte.min(source.len())..] - .find('\n') - .map(|value| byte.min(source.len()) + value + 1) - .unwrap_or(source.len()) -} - -fn utf16_offset(source: &str, byte: usize) -> usize { - source[..byte.min(source.len())].encode_utf16().count() -} - -/// Lexical region used to exclude strings, characters, and comments from scans. -enum ScanState { - Code, - String, - Character, - LineComment, - BlockComment, -} - -#[cfg(test)] -mod launch_class_tests { - use super::standalone_launch_class; - - #[test] - fn prefers_the_public_class_named_after_the_file() { - // A helper class declared first must not be chosen over the public class, - // which a compilable file always names after the file. - let source = "class Helper {} public class App { public static void main(String[] a) {} }"; - assert_eq!(standalone_launch_class("src/App.java", source), "App"); - } - - #[test] - fn ignores_a_class_token_inside_a_comment() { - // `// class Widget` must not be mistaken for a declaration. - let source = "// helper class Widget lives elsewhere\npublic class App { public static void main(String[] a) {} }"; - assert_eq!(standalone_launch_class("src/App.java", source), "App"); - } - - #[test] - fn falls_back_to_the_first_class_like_the_jdk_source_launcher() { - // With no class named after the file, the first top-level class is - // launched — the JDK source launcher's own rule (JEP 330). Lithe does - // not look for a `main` signature; the JVM reports a class without one. - let source = "class Utils {}\nclass Runner { public static void main(String[] a) {} }"; - assert_eq!( - standalone_launch_class("scratch/Scratch.java", source), - "Utils" - ); - } - - #[test] - fn a_compact_source_file_launches_the_class_javac_names_after_it() { - let source = "void main() {\n IO.println(\"compact\");\n}\n"; - assert_eq!( - standalone_launch_class("scratch/Compact.java", source), - "Compact" - ); - } - - #[test] - fn qualifies_with_the_declared_package() { - let source = - "package com.example; public class App { public static void main(String[] a) {} }"; - assert_eq!( - standalone_launch_class("src/App.java", source), - "com.example.App" - ); - } - - #[test] - fn falls_back_to_the_file_stem_without_any_class() { - assert_eq!( - standalone_launch_class("src/Loose.java", "int x = 1;"), - "Loose" - ); - } -} diff --git a/rust/lithe-core/src/languages/java_syntax.rs b/rust/lithe-core/src/languages/java_syntax.rs deleted file mode 100644 index cca3ff560d..0000000000 --- a/rust/lithe-core/src/languages/java_syntax.rs +++ /dev/null @@ -1,556 +0,0 @@ -//! Deterministic Java syntax classification for native editor renderers. - -use crate::protocol::JavaSyntaxHighlightResponse; -use std::collections::HashSet; -use tree_sitter::{Node, Parser}; - -#[derive(Default)] -struct JavaSymbols<'a> { - fields: HashSet<&'a str>, - constants: HashSet<&'a str>, - parameters: HashSet<&'a str>, -} - -/// Classifies Java source into sorted, non-overlapping UTF-16 token ranges. -pub(super) fn syntax_highlights(source: &str) -> Vec { - let mut parser = Parser::new(); - if parser - .set_language(&tree_sitter_java::LANGUAGE.into()) - .is_err() - { - return Vec::new(); - } - let Some(tree) = parser.parse(source, None) else { - return Vec::new(); - }; - let mut values = Vec::new(); - let utf16_offsets = utf16_offsets(source); - let mut symbols = JavaSymbols::default(); - collect_symbols(tree.root_node(), source.as_bytes(), &mut symbols); - collect_highlights( - tree.root_node(), - source, - &utf16_offsets, - &symbols, - &mut values, - ); - values.sort_by_key(|value| (value.utf16_start, value.utf16_length)); - values.dedup_by(|left, right| { - left.utf16_start == right.utf16_start && left.utf16_length == right.utf16_length - }); - values -} - -/// Reports whether a type in this source carries `@SpringBootApplication`. -/// -/// This labels an entry point JDT already confirmed as a Spring Boot service; -/// it never decides whether a class is launchable. The syntax tree is used so -/// that the annotation name inside a string literal or comment does not count. -pub(super) fn declares_spring_boot_application(source: &str) -> bool { - let mut parser = Parser::new(); - if parser - .set_language(&tree_sitter_java::LANGUAGE.into()) - .is_err() - { - return false; - } - let Some(tree) = parser.parse(source, None) else { - return false; - }; - contains_spring_boot_annotation(tree.root_node(), source.as_bytes()) -} - -fn contains_spring_boot_annotation(node: Node<'_>, source: &[u8]) -> bool { - if matches!(node.kind(), "marker_annotation" | "annotation") - && node - .child_by_field_name("name") - .and_then(|name| name.utf8_text(source).ok()) - .is_some_and(|name| { - name == "SpringBootApplication" || name.ends_with(".SpringBootApplication") - }) - { - return true; - } - let mut cursor = node.walk(); - let found = node - .children(&mut cursor) - .any(|child| contains_spring_boot_annotation(child, source)); - found -} - -fn collect_highlights( - node: Node<'_>, - source: &str, - utf16_offsets: &[usize], - symbols: &JavaSymbols<'_>, - values: &mut Vec, -) { - if let Some(role) = whole_node_role(node, source.as_bytes()) { - push_highlight(node, role, utf16_offsets, values); - return; - } - if node.child_count() == 0 { - if let Some(role) = role_for_leaf(node, source.as_bytes(), symbols) { - push_highlight(node, role, utf16_offsets, values); - } - return; - } - let mut cursor = node.walk(); - for child in node.children(&mut cursor) { - collect_highlights(child, source, utf16_offsets, symbols, values); - } -} - -fn collect_symbols<'a>(node: Node<'_>, source: &'a [u8], symbols: &mut JavaSymbols<'a>) { - if matches!(node.kind(), "formal_parameter" | "spread_parameter") { - if let Some(name) = node - .child_by_field_name("name") - .and_then(|value| value.utf8_text(source).ok()) - { - symbols.parameters.insert(name); - } - } else if node.kind() == "variable_declarator" && has_ancestor(node, "field_declaration") { - if let Some(name) = node - .child_by_field_name("name") - .and_then(|value| value.utf8_text(source).ok()) - { - let is_constant = ancestor_text(node, "field_declaration", source) - .is_some_and(|text| has_modifier(text, "static") && has_modifier(text, "final")); - if is_constant { - symbols.constants.insert(name); - } else { - symbols.fields.insert(name); - } - } - } - let mut cursor = node.walk(); - for child in node.children(&mut cursor) { - collect_symbols(child, source, symbols); - } -} - -fn utf16_offsets(source: &str) -> Vec { - let mut offsets = vec![0; source.len() + 1]; - let mut utf16_offset = 0; - for (byte_offset, character) in source.char_indices() { - offsets[byte_offset] = utf16_offset; - utf16_offset += character.len_utf16(); - offsets[byte_offset + character.len_utf8()] = utf16_offset; - } - offsets -} - -fn whole_node_role(node: Node<'_>, source: &[u8]) -> Option<&'static str> { - match node.kind() { - "line_comment" | "block_comment" => Some( - if node - .utf8_text(source) - .is_ok_and(|text| text.as_bytes().starts_with(&[b'/', b'*', b'*'])) - { - "documentationComment" - } else { - "comment" - }, - ), - "string_literal" | "character_literal" | "text_block" => Some("string"), - "decimal_integer_literal" - | "hex_integer_literal" - | "octal_integer_literal" - | "binary_integer_literal" - | "decimal_floating_point_literal" - | "hex_floating_point_literal" => Some("number"), - "boolean_type" | "integral_type" | "floating_point_type" | "void_type" => Some("keyword"), - _ => None, - } -} - -fn push_highlight( - node: Node<'_>, - role: &str, - utf16_offsets: &[usize], - values: &mut Vec, -) { - let Some(&utf16_start) = utf16_offsets.get(node.start_byte()) else { - return; - }; - let Some(&utf16_end) = utf16_offsets.get(node.end_byte()) else { - return; - }; - let utf16_length = utf16_end.saturating_sub(utf16_start); - if utf16_length == 0 { - return; - } - values.push(JavaSyntaxHighlightResponse { - utf16_start, - utf16_length, - role: role.to_string(), - }); -} - -fn role_for_leaf(node: Node<'_>, source: &[u8], symbols: &JavaSymbols<'_>) -> Option<&'static str> { - let kind = node.kind(); - if kind == "@" - || (matches!(kind, "identifier" | "type_identifier") - && (has_ancestor(node, "marker_annotation") || has_ancestor(node, "annotation"))) - { - return Some("annotation"); - } - if matches!(kind, "true" | "false") { - return Some("boolean"); - } - if kind == "null_literal" { - return Some("null"); - } - if kind == "identifier" { - return Some(identifier_role(node, source, symbols)); - } - if kind == "type_identifier" { - return Some(if has_ancestor(node, "type_parameters") { - "typeParameter" - } else { - "type" - }); - } - if is_keyword(kind) { - return Some("keyword"); - } - if !node.is_named() { - return Some(if is_operator(kind) { - "operator" - } else { - "punctuation" - }); - } - None -} - -fn identifier_role(node: Node<'_>, source: &[u8], symbols: &JavaSymbols<'_>) -> &'static str { - let Some(parent) = node.parent() else { - return "variable"; - }; - if field_is(parent, "name", node) { - return match parent.kind() { - "method_declaration" | "constructor_declaration" => "functionDeclaration", - "method_invocation" => "functionCall", - "formal_parameter" | "spread_parameter" | "receiver_parameter" => "parameter", - "class_declaration" - | "interface_declaration" - | "enum_declaration" - | "record_declaration" - | "annotation_type_declaration" => "type", - _ => declaration_identifier_role(node, source), - }; - } - if has_ancestor(node, "method_invocation") && field_is(parent, "name", node) { - return "functionCall"; - } - if parent.kind() == "field_access" && field_is(parent, "field", node) { - return "field"; - } - if has_ancestor(node, "type_parameters") { - return "typeParameter"; - } - if has_type_ancestor(node) { - return "type"; - } - if let Ok(name) = node.utf8_text(source) { - if symbols.parameters.contains(name) { - return "parameter"; - } - if symbols.constants.contains(name) { - return "constant"; - } - if symbols.fields.contains(name) { - return "field"; - } - if name - .chars() - .next() - .is_some_and(|character| character.is_ascii_uppercase()) - { - return "type"; - } - } - "variable" -} - -fn declaration_identifier_role(node: Node<'_>, source: &[u8]) -> &'static str { - if has_ancestor(node, "formal_parameter") || has_ancestor(node, "spread_parameter") { - return "parameter"; - } - if has_ancestor(node, "field_declaration") { - return if ancestor_text(node, "field_declaration", source) - .is_some_and(|text| has_modifier(text, "static") && has_modifier(text, "final")) - { - "constant" - } else { - "field" - }; - } - if has_ancestor(node, "local_variable_declaration") - || has_ancestor(node, "resource") - || has_ancestor(node, "catch_formal_parameter") - || has_ancestor(node, "enhanced_for_statement") - { - return "variable"; - } - "variable" -} - -fn field_is(parent: Node<'_>, name: &str, node: Node<'_>) -> bool { - parent - .child_by_field_name(name) - .is_some_and(|value| value.id() == node.id()) -} - -fn has_ancestor(mut node: Node<'_>, kind: &str) -> bool { - while let Some(parent) = node.parent() { - if parent.kind() == kind { - return true; - } - node = parent; - } - false -} - -fn has_type_ancestor(mut node: Node<'_>) -> bool { - while let Some(parent) = node.parent() { - if matches!( - parent.kind(), - "type_arguments" - | "superclass" - | "super_interfaces" - | "extends_interfaces" - | "object_creation_expression" - | "cast_expression" - | "instanceof_expression" - | "array_type" - | "generic_type" - | "scoped_type_identifier" - ) { - return true; - } - if matches!(parent.kind(), "method_invocation" | "expression_statement") { - return false; - } - node = parent; - } - false -} - -fn ancestor_text<'a>(mut node: Node<'_>, kind: &str, source: &'a [u8]) -> Option<&'a str> { - while let Some(parent) = node.parent() { - if parent.kind() == kind { - return parent.utf8_text(source).ok(); - } - node = parent; - } - None -} - -fn has_modifier(text: &str, expected: &str) -> bool { - text.split(|character: char| !character.is_ascii_alphanumeric() && character != '_') - .any(|word| word == expected) -} - -fn is_keyword(kind: &str) -> bool { - matches!( - kind, - "abstract" - | "assert" - | "break" - | "case" - | "catch" - | "class" - | "continue" - | "default" - | "do" - | "else" - | "enum" - | "exports" - | "extends" - | "final" - | "finally" - | "for" - | "if" - | "implements" - | "import" - | "instanceof" - | "interface" - | "module" - | "native" - | "new" - | "non-sealed" - | "open" - | "opens" - | "package" - | "permits" - | "private" - | "protected" - | "provides" - | "public" - | "record" - | "requires" - | "return" - | "sealed" - | "static" - | "strictfp" - | "super" - | "switch" - | "synchronized" - | "this" - | "throw" - | "throws" - | "to" - | "transient" - | "transitive" - | "try" - | "uses" - | "volatile" - | "while" - | "with" - | "yield" - | "void" - | "boolean_type" - | "integral_type" - | "floating_point_type" - ) -} - -fn is_operator(kind: &str) -> bool { - matches!( - kind, - "=" | ">" - | "<" - | "!" - | "~" - | "?" - | ":" - | "->" - | "==" - | ">=" - | "<=" - | "!=" - | "&&" - | "||" - | "++" - | "--" - | "+" - | "-" - | "*" - | "/" - | "&" - | "|" - | "^" - | "%" - | "<<" - | ">>" - | ">>>" - | "+=" - | "-=" - | "*=" - | "/=" - | "&=" - | "|=" - | "^=" - | "%=" - | "<<=" - | ">>=" - | ">>>=" - | "::" - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn classifies_java_declarations_references_and_literals() { - let source = concat!( - "/", - "** Docs *", - "/\n", - r#"@Deprecated class Demo { - static final int LIMIT = 2; - String field; - Demo(String value) { - String local = value; - this.field = call(local); - } -}"# - ); - - let values = syntax_highlights(source); - let classified = values - .iter() - .map(|value| { - let token = String::from_utf16( - &source.encode_utf16().collect::>() - [value.utf16_start..value.utf16_start + value.utf16_length], - ) - .expect("highlight range should contain valid UTF-16"); - (token, value.role.as_str()) - }) - .collect::>(); - - let documentation = ["/", "** Docs *", "/"].concat(); - assert!(classified.contains(&(documentation, "documentationComment"))); - assert!(classified.contains(&("@".to_string(), "annotation"))); - assert!(classified.contains(&("Deprecated".to_string(), "annotation"))); - assert!(classified.contains(&("Demo".to_string(), "type"))); - assert!(classified.contains(&("T".to_string(), "typeParameter"))); - assert!(classified.contains(&("LIMIT".to_string(), "constant"))); - assert!(classified.contains(&("field".to_string(), "field"))); - assert!(classified.contains(&("Demo".to_string(), "functionDeclaration"))); - assert!(classified.contains(&("value".to_string(), "parameter"))); - assert!(classified.contains(&("local".to_string(), "variable"))); - assert!(classified.contains(&("call".to_string(), "functionCall"))); - assert!(classified.contains(&("2".to_string(), "number"))); - assert!( - classified - .iter() - .filter(|(token, role)| token == "field" && *role == "field") - .count() - >= 2 - ); - assert!( - classified - .iter() - .filter(|(token, role)| token == "local" && *role == "variable") - .count() - >= 2 - ); - } - - #[test] - fn reports_document_relative_utf16_offsets_after_non_ascii_text() { - let source = "class Demo { String text = \"😀\"; int count = 1; }"; - let values = syntax_highlights(source); - let count_start = source.find("count").expect("count should exist"); - let expected = source[..count_start].encode_utf16().count(); - - assert!(values.iter().any(|value| { - value.utf16_start == expected && value.utf16_length == 5 && value.role == "field" - })); - } - - /// The annotation name inside a string literal or comment is text: only a - /// declared annotation labels an entry point as a Spring Boot service. - #[test] - fn spring_boot_label_requires_a_declared_annotation() { - let embedded = concat!( - "class TemplateTest {\n", - " String annotation = \"@SpringBootApplication\";\n", - " // @SpringBootApplication\n", - "}\n" - ); - assert!(!declares_spring_boot_application(embedded)); - for declared in [ - "@SpringBootApplication\npublic class App {}\n", - "@org.springframework.boot.autoconfigure.SpringBootApplication(scanBasePackages = \"x\")\nclass App {}\n", - ] { - assert!(declares_spring_boot_application(declared), "{declared}"); - } - } -} diff --git a/rust/lithe-core/src/languages/mod.rs b/rust/lithe-core/src/languages/mod.rs deleted file mode 100644 index 1fc1d7a601..0000000000 --- a/rust/lithe-core/src/languages/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! Language-specific project inspection that is independent from LSP transport. - -mod java; -mod java_syntax; -mod mybatis; -mod spring; -mod text; - -pub(crate) use java::*; -pub(crate) use mybatis::*; -pub(crate) use spring::*; -pub(crate) use text::*; diff --git a/rust/lithe-core/src/languages/mybatis.rs b/rust/lithe-core/src/languages/mybatis.rs deleted file mode 100644 index 32974547e7..0000000000 --- a/rust/lithe-core/src/languages/mybatis.rs +++ /dev/null @@ -1,492 +0,0 @@ -//! Deterministic MyBatis mapper-interface and XML statement indexing. - -use crate::protocol::{CoreError, ErrorCode, MybatisIndexResponse, MybatisStatementResponse}; -use regex::Regex; -use serde::Deserialize; -use std::collections::{HashMap, HashSet}; -use std::fs; -use std::path::{Component, Path, PathBuf}; -use std::sync::LazyLock; -use tree_sitter::{Node, Parser}; - -static XML_COMMENT: LazyLock = - LazyLock::new(|| Regex::new(r"(?s)").expect("literal pattern is valid")); -static MAPPER_TAG: LazyLock = - LazyLock::new(|| Regex::new(r#"(?is)]*)>"#).expect("literal pattern is valid")); -static STATEMENT_TAG: LazyLock = LazyLock::new(|| { - Regex::new(r#"(?is)<(select|insert|update|delete)\b([^>]*)>"#) - .expect("literal pattern is valid") -}); -static ATTRIBUTE_NAMESPACE: LazyLock = LazyLock::new(|| { - Regex::new(r#"namespace\s*=\s*["']([^"']+)["']"#).expect("literal pattern is valid") -}); -static ATTRIBUTE_ID: LazyLock = LazyLock::new(|| { - Regex::new(r#"\bid\s*=\s*["']([^"']+)["']"#).expect("literal pattern is valid") -}); - -/// Regular Java and mapper XML files stay well below this; larger dumps are skipped. -const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024; - -#[cfg(test)] -thread_local! { - static DISK_READS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; -} - -#[cfg(test)] -pub(crate) fn take_mybatis_disk_reads() -> Vec { - DISK_READS.with(|paths| paths.take()) -} - -#[cfg(test)] -fn record_disk_read(path: &str) { - DISK_READS.with(|paths| paths.borrow_mut().push(path.to_string())); -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Workspace paths used to pair mapper interfaces with XML statements. -pub struct MybatisIndexRequest { - /// Absolute workspace root. Relative paths are rejected. - pub root: String, - /// Workspace-relative Java and XML files to read. - #[serde(default)] - pub paths: Vec, - /// Unsaved buffer text keyed by workspace-relative path. - #[serde(default)] - pub text_overrides: HashMap, -} - -#[derive(Clone)] -struct JavaMethod { - name: String, - line: usize, - column: usize, - end_column: usize, - end_line: usize, -} - -#[derive(Clone)] -struct JavaType { - qualified_name: String, - path: String, - methods: Vec, -} - -struct XmlStatement { - statement_id: String, - kind: String, - line: usize, - column: usize, - end_column: usize, -} - -struct XmlMapper { - namespace: String, - path: String, - statements: Vec, -} - -/// Builds one cross-file MyBatis mapper index without starting a language server. -pub fn mybatis_index(request: MybatisIndexRequest) -> Result { - let root = existing_directory(&request.root)?; - let paths = request - .paths - .into_iter() - .filter_map(|path| normalize_relative(&path)) - .collect::>(); - - let mut parser = Parser::new(); - let java_parser = parser - .set_language(&tree_sitter_java::LANGUAGE.into()) - .is_ok(); - - // XML mappers name every Java type worth parsing. A mapper interface lives - // in a file named after its top-level type, which is one segment of some - // namespace (`a.b.Outer.Inner` names `Outer.java`). Parsing every Java - // source instead dominated the index on large projects, and hosts rebuild - // the index whenever a Java buffer changes. - let mut xml_mappers = Vec::new(); - let mut java_paths = Vec::new(); - for path in &paths { - if !is_mybatis_source_path(path) { - continue; - } - if is_java_path(path) { - java_paths.push(path); - continue; - } - let Some(content) = source_content(&root, path, &request.text_overrides) else { - continue; - }; - if let Some(mapper) = xml_mapper(&slash_path(path), &content) { - xml_mappers.push(mapper); - } - } - let mapper_type_names = xml_mappers - .iter() - .flat_map(|mapper| mapper.namespace.split('.')) - .map(str::to_owned) - .collect::>(); - - let mut java_types = Vec::new(); - if java_parser { - for path in java_paths { - let names_mapper_type = path - .file_stem() - .and_then(|stem| stem.to_str()) - .is_some_and(|stem| mapper_type_names.contains(stem)); - if !names_mapper_type { - continue; - } - let Some(content) = source_content(&root, path, &request.text_overrides) else { - continue; - }; - java_types.extend(java_mapper_types(&mut parser, &slash_path(path), &content)); - } - } - - java_types.sort_by(|left, right| { - left.qualified_name - .cmp(&right.qualified_name) - .then_with(|| left.path.cmp(&right.path)) - }); - xml_mappers.sort_by(|left, right| { - left.namespace - .cmp(&right.namespace) - .then_with(|| left.path.cmp(&right.path)) - }); - - let mut statements = Vec::new(); - for mapper in &xml_mappers { - let Some(java_type) = java_types - .iter() - .find(|candidate| candidate.qualified_name == mapper.namespace) - else { - continue; - }; - for xml_statement in &mapper.statements { - let Some(method) = java_type - .methods - .iter() - .find(|candidate| candidate.name == xml_statement.statement_id) - else { - continue; - }; - statements.push(MybatisStatementResponse { - id: format!( - "{}#{}:{}:{}", - mapper.namespace, xml_statement.statement_id, mapper.path, xml_statement.line - ), - namespace: mapper.namespace.clone(), - statement_id: xml_statement.statement_id.clone(), - kind: xml_statement.kind.clone(), - java_path: java_type.path.clone(), - java_line: method.line, - java_column: method.column, - java_end_line: method.end_line, - java_end_column: method.end_column, - xml_path: mapper.path.clone(), - xml_line: xml_statement.line, - xml_column: xml_statement.column, - xml_end_column: xml_statement.end_column, - }); - } - } - statements.sort_by(|left, right| { - left.namespace - .cmp(&right.namespace) - .then_with(|| left.statement_id.cmp(&right.statement_id)) - .then_with(|| left.xml_path.cmp(&right.xml_path)) - .then_with(|| left.xml_line.cmp(&right.xml_line)) - .then_with(|| left.java_path.cmp(&right.java_path)) - .then_with(|| left.java_line.cmp(&right.java_line)) - }); - Ok(MybatisIndexResponse { statements }) -} - -fn java_mapper_types(parser: &mut Parser, path: &str, source: &str) -> Vec { - let Some(tree) = parser.parse(source, None) else { - return Vec::new(); - }; - let bytes = source.as_bytes(); - let package = package_name(tree.root_node(), bytes); - let mut types = Vec::new(); - collect_types(tree.root_node(), path, &package, source, bytes, &mut types); - types -} - -fn collect_types( - root: Node<'_>, - path: &str, - package: &str, - source: &str, - bytes: &[u8], - types: &mut Vec, -) { - // Java expression trees can be thousands of nodes deep even in small files. - // Keep traversal state on the heap instead of consuming the host thread's stack. - let mut pending = vec![root]; - while let Some(node) = pending.pop() { - if matches!(node.kind(), "class_declaration" | "interface_declaration") { - if let Some(java_type) = java_type(node, path, package, source, bytes) { - types.push(java_type); - } - } - // Reverse the push order to preserve the recursive walk's source preorder. - for index in (0..node.child_count()).rev() { - if let Some(child) = node.child(index) { - pending.push(child); - } - } - } -} - -fn java_type( - node: Node<'_>, - path: &str, - package: &str, - source: &str, - bytes: &[u8], -) -> Option { - let qualified_name = qualified_type_name(node, package, bytes)?; - let mut methods = Vec::new(); - if let Some(body) = node.child_by_field_name("body") { - collect_abstract_methods(body, source, bytes, &mut methods); - } - Some(JavaType { - qualified_name, - path: path.to_string(), - methods, - }) -} - -fn collect_abstract_methods( - body: Node<'_>, - source: &str, - bytes: &[u8], - methods: &mut Vec, -) { - let mut cursor = body.walk(); - for child in body.children(&mut cursor) { - if child.kind() != "method_declaration" { - continue; - } - // Methods with a body, including default methods, are not XML-mapped. - if child.child_by_field_name("body").is_some() { - continue; - } - let Some(name_node) = child.child_by_field_name("name") else { - continue; - }; - let Ok(name) = name_node.utf8_text(bytes) else { - continue; - }; - if methods.iter().any(|existing| existing.name == name) { - continue; - } - let (line, column) = line_column(source, name_node.start_byte()); - let (_, end_column) = line_column(source, name_node.end_byte()); - let (end_line, _) = line_column(source, child.end_byte().saturating_sub(1)); - methods.push(JavaMethod { - name: name.to_string(), - line, - column, - end_column, - end_line, - }); - } -} - -fn package_name(root: Node<'_>, bytes: &[u8]) -> String { - let mut cursor = root.walk(); - for child in root.children(&mut cursor) { - if child.kind() != "package_declaration" { - continue; - } - let mut inner = child.walk(); - for part in child.children(&mut inner) { - if matches!(part.kind(), "identifier" | "scoped_identifier") { - return part.utf8_text(bytes).unwrap_or_default().to_string(); - } - } - } - String::new() -} - -fn qualified_type_name(mut node: Node<'_>, package: &str, bytes: &[u8]) -> Option { - let mut parts = Vec::new(); - loop { - if matches!(node.kind(), "class_declaration" | "interface_declaration") { - let name = node.child_by_field_name("name")?.utf8_text(bytes).ok()?; - parts.push(name.to_string()); - } - match node.parent() { - Some(parent) => node = parent, - None => break, - } - } - parts.reverse(); - if parts.is_empty() { - return None; - } - let joined = parts.join("."); - Some(if package.is_empty() { - joined - } else { - format!("{package}.{joined}") - }) -} - -fn xml_mapper(path: &str, source: &str) -> Option { - let comments = XML_COMMENT - .find_iter(source) - .map(|matched| matched.range()) - .collect::>(); - let mapper = MAPPER_TAG.captures_iter(source).find(|capture| { - capture - .get(0) - .is_some_and(|matched| !in_ranges(&comments, matched.start())) - })?; - let attributes = mapper.get(1)?.as_str(); - let namespace = ATTRIBUTE_NAMESPACE - .captures(attributes) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str().trim().to_string()) - .filter(|value| !value.is_empty())?; - let mapper_end = mapper.get(0)?.end(); - let mut statements = Vec::new(); - for capture in STATEMENT_TAG.captures_iter(source) { - let Some(full) = capture.get(0) else { continue }; - if full.start() < mapper_end || in_ranges(&comments, full.start()) { - continue; - } - let kind = capture - .get(1) - .map(|value| value.as_str().to_ascii_lowercase())?; - let attributes = capture - .get(2) - .map(|value| value.as_str()) - .unwrap_or_default(); - let Some(id_capture) = ATTRIBUTE_ID.captures(attributes) else { - continue; - }; - let statement_id = id_capture.get(1)?.as_str().trim().to_string(); - if statement_id.is_empty() { - continue; - } - let id_start_in_attributes = id_capture.get(1)?.start(); - let attribute_start = capture - .get(2) - .map(|value| value.start()) - .unwrap_or(full.start()); - let id_start = attribute_start + id_start_in_attributes; - let (line, column) = line_column(source, id_start); - let end_column = column + statement_id.encode_utf16().count(); - statements.push(XmlStatement { - statement_id, - kind, - line, - column, - end_column, - }); - } - statements.sort_by(|left, right| { - left.statement_id - .cmp(&right.statement_id) - .then_with(|| left.line.cmp(&right.line)) - }); - Some(XmlMapper { - namespace, - path: path.to_string(), - statements, - }) -} - -fn is_java_path(path: &Path) -> bool { - path.extension() - .and_then(|value| value.to_str()) - .is_some_and(|extension| extension.eq_ignore_ascii_case("java")) -} - -fn is_mybatis_source_path(path: &Path) -> bool { - match path - .extension() - .and_then(|value| value.to_str()) - .map(str::to_ascii_lowercase) - .as_deref() - { - Some("java") => true, - Some("xml") => !path - .file_name() - .and_then(|value| value.to_str()) - .is_some_and(|name| name.eq_ignore_ascii_case("pom.xml")), - _ => false, - } -} - -fn source_content(root: &Path, path: &Path, overrides: &HashMap) -> Option { - let relative = slash_path(path); - if let Some(text) = overrides.get(&relative) { - return Some(text.clone()); - } - let absolute = root.join(path); - let metadata = fs::metadata(&absolute).ok()?; - if !metadata.is_file() || metadata.len() > MAX_SOURCE_BYTES { - return None; - } - #[cfg(test)] - record_disk_read(&relative); - fs::read_to_string(absolute).ok() -} - -fn existing_directory(value: &str) -> Result { - let path = PathBuf::from(value); - if !path.is_absolute() || !path.is_dir() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "MyBatis index root must be an existing absolute directory", - )); - } - Ok(path) -} - -fn normalize_relative(value: &str) -> Option { - let path = Path::new(value); - if path.is_absolute() || value.contains('\0') { - return None; - } - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - Component::Normal(value) => normalized.push(value), - Component::CurDir => {} - _ => return None, - } - } - (!normalized.as_os_str().is_empty()).then_some(normalized) -} - -fn slash_path(path: &Path) -> String { - path.components() - .filter_map(|part| match part { - Component::Normal(value) => value.to_str(), - _ => None, - }) - .collect::>() - .join("/") -} - -fn in_ranges(ranges: &[std::ops::Range], offset: usize) -> bool { - ranges.iter().any(|range| range.contains(&offset)) -} - -fn line_column(source: &str, byte_offset: usize) -> (usize, usize) { - let prefix = source.get(..byte_offset).unwrap_or(source); - let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1; - let last_line_start = prefix.rfind('\n').map(|index| index + 1).unwrap_or(0); - let column = source - .get(last_line_start..byte_offset) - .map(|value| value.encode_utf16().count() + 1) - .unwrap_or(1); - (line, column) -} diff --git a/rust/lithe-core/src/languages/spring.rs b/rust/lithe-core/src/languages/spring.rs deleted file mode 100644 index 6b384c11f3..0000000000 --- a/rust/lithe-core/src/languages/spring.rs +++ /dev/null @@ -1,2443 +0,0 @@ -//! Deterministic Spring Boot configuration and source semantic indexing. - -use crate::protocol::cancellation; -use crate::protocol::{ - CoreError, ErrorCode, SpringBeanResponse, SpringConfigurationValueResponse, - SpringDiagnosticResponse, SpringEndpointResponse, SpringIndexResponse, SpringInjectionResponse, - SpringPropertyReferenceResponse, SpringPropertyResponse, -}; -use regex::Regex; -use serde::Deserialize; -use serde_json::Value; -use std::collections::{HashMap, HashSet}; -use std::fs::{self, File}; -use std::io::Read; -use std::path::{Component, Path, PathBuf}; -use std::sync::{Arc, Condvar, LazyLock, Mutex, OnceLock}; -use std::time::Duration; -use zip::ZipArchive; - -const MAX_METADATA_ARCHIVES: usize = 20_000; - -/// A waiter rechecks cancellation at this interval while another request owns -/// the repository scan. -const REPOSITORY_WAIT_SLICE: Duration = Duration::from_millis(50); - -static REPOSITORY_METADATA_CACHE: OnceLock>>> = - OnceLock::new(); - -/// One repository's metadata cache entry. -/// -/// The first request that misses the cache owns the archive walk; concurrent -/// requests wait on `ready` instead of scanning the same JARs again. -struct RepositoryMetadataSlot { - state: Mutex, - ready: Condvar, -} - -impl RepositoryMetadataSlot { - fn latest_scan(&self) -> u64 { - self.state - .lock() - .expect("repository metadata state should not be poisoned") - .scan() - } -} - -/// Progress of one repository scan and the snapshot it publishes. -/// -/// Every variant carries the number of the latest scan that started, counted -/// from 1. A refresh request records that number when it arrives and accepts -/// only a snapshot from a later scan: a walk that began before the refresh may -/// have listed the repository before new archives were downloaded. -enum RepositoryMetadataState { - /// A request currently owns the scan. - Scanning(u64), - /// A completed snapshot shared by every reader until a refresh claims it. - Ready { - scan: u64, - properties: Arc>, - }, - /// The owner was cancelled or interrupted, so the next reader retries. - Failed(u64), -} - -impl RepositoryMetadataState { - fn scan(&self) -> u64 { - match self { - Self::Scanning(scan) | Self::Failed(scan) | Self::Ready { scan, .. } => *scan, - } - } -} - -/// Outcome of joining a repository scan. -#[derive(Debug)] -enum RepositoryClaim { - /// A snapshot this request may reuse. - Shared(Vec), - /// This request now owns the scan with the given number. - Owned(u64), -} - -/// Publishes `Failed` if the scan owner unwinds without completing the state -/// transition, so waiters never block on a scan that can no longer finish. -struct RepositoryScanCompletion<'a> { - slot: &'a RepositoryMetadataSlot, - published: bool, -} - -impl Drop for RepositoryScanCompletion<'_> { - fn drop(&mut self) { - if self.published { - return; - } - if let Ok(mut state) = self.slot.state.lock() { - if let RepositoryMetadataState::Scanning(scan) = *state { - *state = RepositoryMetadataState::Failed(scan); - } - } - self.slot.ready.notify_all(); - } -} - -/// One Java parameter declaration: optional annotations, an optional `final`, -/// the type, and the parameter name. Record components and constructor -/// parameters share this grammar, so they must not drift into two patterns. -static JAVA_PARAMETER_DECLARATION: LazyLock = LazyLock::new(|| { - Regex::new( - r"(?:@[A-Za-z0-9_$.]+(?:\([^)]*\))?\s+)*(?:final\s+)?([A-Za-z0-9_$.<>?]+)\s+([A-Za-z_$][A-Za-z0-9_$]*)$", - ) - .expect("literal pattern is valid") -}); - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Workspace paths and an optional trusted dependency repository to index. -pub struct SpringIndexRequest { - pub root: String, - #[serde(default)] - pub paths: Vec, - #[serde(default)] - pub metadata_repository: Option, - /// Trusted dependency repositories whose Spring metadata may be indexed. - #[serde(default)] - pub metadata_repositories: Vec, - /// Forces a dependency metadata rescan. Interactive document updates keep - /// this false so they reuse the process-local repository snapshot. - #[serde(default)] - pub refresh_dependency_metadata: bool, - #[serde(default)] - pub text_overrides: HashMap, -} - -/// Builds one cross-file Spring index without starting an additional server. -pub fn spring_index(request: SpringIndexRequest) -> Result { - cancellation::check()?; - let root = existing_directory(&request.root)?; - let paths = request - .paths - .into_iter() - .filter_map(|path| normalize_relative(&path)) - .collect::>(); - let mut properties = built_in_properties(); - for path in &paths { - cancellation::check()?; - if is_metadata_path(path) { - if let Some(content) = source_content(&root, path, &request.text_overrides) { - append_metadata(&content, None, &mut properties); - } - } - } - let mut repositories = request.metadata_repositories; - if let Some(repository) = request.metadata_repository { - repositories.push(repository); - } - repositories.sort(); - repositories.dedup(); - for repository in repositories { - properties.extend(repository_metadata( - Path::new(&repository), - request.refresh_dependency_metadata, - )?); - } - - let mut java_sources = Vec::new(); - for path in &paths { - cancellation::check()?; - if path.extension().and_then(|value| value.to_str()) == Some("java") { - if let Some(source) = source_content(&root, path, &request.text_overrides) { - java_sources.push((slash_path(path), source)); - } - } - } - append_configuration_properties(&java_sources, &mut properties)?; - deduplicate_properties(&mut properties); - - let mut values = Vec::new(); - for path in &paths { - cancellation::check()?; - let relative = slash_path(path); - let name = path - .file_name() - .and_then(|value| value.to_str()) - .unwrap_or_default(); - if !is_application_configuration(name) { - continue; - } - let Some(content) = source_content(&root, path, &request.text_overrides) else { - continue; - }; - if name.ends_with(".properties") { - values.extend(parse_properties(&relative, &content)); - } else { - values.extend(parse_yaml(&relative, &content)); - } - } - attach_property_targets(&properties, &mut values); - mark_profile_overrides(&mut values); - let mut diagnostics = configuration_diagnostics(&properties, &values); - let property_references = property_reference_index(&java_sources)?; - let (beans, injections, injection_diagnostics) = bean_index(&java_sources)?; - diagnostics.extend(injection_diagnostics); - diagnostics.sort_by(|left, right| { - left.path - .cmp(&right.path) - .then_with(|| left.line.cmp(&right.line)) - .then_with(|| left.column.cmp(&right.column)) - .then_with(|| left.message.cmp(&right.message)) - }); - let endpoints = endpoint_index(&java_sources)?; - - Ok(SpringIndexResponse { - properties, - values, - property_references, - diagnostics, - beans, - injections, - endpoints, - }) -} - -fn property_reference_index( - sources: &[(String, String)], -) -> Result, CoreError> { - static ANNOTATION: LazyLock = LazyLock::new(|| { - Regex::new(r#"@Value\s*\(\s*[\"']\$\{\s*([^}:\s]+)(?::[^}]*)?\s*\}[\"']\s*\)"#) - .expect("literal pattern is valid") - }); - let mut references = Vec::new(); - for (path, source) in sources { - cancellation::check()?; - for (index, line) in source.lines().enumerate() { - for capture in ANNOTATION.captures_iter(line) { - let Some(key) = capture.get(1) else { continue }; - references.push(SpringPropertyReferenceResponse { - key: canonical_property_name(key.as_str()), - path: path.clone(), - line: index + 1, - column: key.start() + 1, - }); - } - } - } - references.sort_by(|left, right| { - left.path - .cmp(&right.path) - .then_with(|| left.line.cmp(&right.line)) - .then_with(|| left.column.cmp(&right.column)) - }); - Ok(references) -} - -fn source_content(root: &Path, path: &Path, overrides: &HashMap) -> Option { - overrides - .get(&slash_path(path)) - .cloned() - .or_else(|| fs::read_to_string(root.join(path)).ok()) -} - -fn existing_directory(value: &str) -> Result { - let path = PathBuf::from(value); - if !path.is_absolute() || !path.is_dir() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Spring index root must be an existing absolute directory", - )); - } - Ok(path) -} - -fn normalize_relative(value: &str) -> Option { - let path = Path::new(value); - if path.is_absolute() || value.contains('\0') { - return None; - } - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - Component::Normal(value) => normalized.push(value), - Component::CurDir => {} - _ => return None, - } - } - (!normalized.as_os_str().is_empty()).then_some(normalized) -} - -fn slash_path(path: &Path) -> String { - path.components() - .filter_map(|part| match part { - Component::Normal(value) => value.to_str(), - _ => None, - }) - .collect::>() - .join("/") -} - -fn is_metadata_path(path: &Path) -> bool { - matches!( - path.file_name().and_then(|value| value.to_str()), - Some("spring-configuration-metadata.json") - | Some("additional-spring-configuration-metadata.json") - ) -} - -fn repository_metadata( - repository: &Path, - refresh: bool, -) -> Result, CoreError> { - repository_metadata_with(repository, refresh, scan_repository_metadata) -} - -/// Loads one repository snapshot while sharing a single in-progress scan. -/// -/// `scan` is injectable so the coordination behavior can be tested without a -/// large archive fixture. -fn repository_metadata_with( - repository: &Path, - refresh: bool, - scan: impl FnOnce(&Path) -> Result, CoreError>, -) -> Result, CoreError> { - cancellation::check()?; - if !repository.is_absolute() || !repository.is_dir() { - return Ok(Vec::new()); - } - let key = repository - .canonicalize() - .unwrap_or_else(|_| repository.to_path_buf()); - let (slot, owned_scan) = { - let mut cache = REPOSITORY_METADATA_CACHE - .get_or_init(|| Mutex::new(HashMap::new())) - .lock() - .expect("repository metadata cache should not be poisoned"); - match cache.get(&key) { - Some(slot) => (Arc::clone(slot), None), - None => { - let slot = Arc::new(RepositoryMetadataSlot { - state: Mutex::new(RepositoryMetadataState::Scanning(1)), - ready: Condvar::new(), - }); - cache.insert(key.clone(), Arc::clone(&slot)); - (slot, Some(1)) - } - } - }; - let scan_number = match owned_scan { - Some(scan_number) => scan_number, - None => { - let arrival = slot.latest_scan(); - match claim_repository_scan(&slot, refresh, arrival)? { - RepositoryClaim::Shared(properties) => return Ok(properties), - RepositoryClaim::Owned(scan_number) => scan_number, - } - } - }; - - let mut completion = RepositoryScanCompletion { - slot: &slot, - published: false, - }; - let result = scan(&key); - { - let mut state = slot - .state - .lock() - .expect("repository metadata state should not be poisoned"); - *state = match &result { - Ok(properties) => RepositoryMetadataState::Ready { - scan: scan_number, - properties: Arc::new(properties.clone()), - }, - Err(_) => RepositoryMetadataState::Failed(scan_number), - }; - completion.published = true; - } - slot.ready.notify_all(); - result -} - -/// Waits for the current owner or claims the scan for this request. -/// -/// Returns a shared snapshot when it is ready and no refresh was requested. -/// `arrival` is the latest scan number seen when the request arrived. A -/// refresh accepts only a snapshot from a scan numbered after it, so a refresh -/// that lands mid-scan waits for that walk and then starts its own; refreshes -/// that land during the same walk still share one follow-up scan. -fn claim_repository_scan( - slot: &RepositoryMetadataSlot, - refresh: bool, - arrival: u64, -) -> Result { - let mut state = slot - .state - .lock() - .expect("repository metadata state should not be poisoned"); - loop { - match &*state { - RepositoryMetadataState::Ready { scan, properties } if !refresh || *scan > arrival => { - return Ok(RepositoryClaim::Shared((**properties).clone())); - } - RepositoryMetadataState::Ready { .. } | RepositoryMetadataState::Failed(_) => { - let scan = state.scan() + 1; - *state = RepositoryMetadataState::Scanning(scan); - return Ok(RepositoryClaim::Owned(scan)); - } - RepositoryMetadataState::Scanning(_) => { - let (next, _) = slot - .ready - .wait_timeout(state, REPOSITORY_WAIT_SLICE) - .expect("repository metadata wait should not be poisoned"); - state = next; - // A cancelled request must release its worker thread rather - // than wait for a scan whose result it will discard. - cancellation::check()?; - } - } - } -} - -fn scan_repository_metadata(repository: &Path) -> Result, CoreError> { - let mut properties = Vec::new(); - let mut pending = vec![repository.to_path_buf()]; - let mut archive_count = 0usize; - while let Some(directory) = pending.pop() { - cancellation::check()?; - let Ok(entries) = fs::read_dir(directory) else { - continue; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - pending.push(path); - } else if path.extension().and_then(|value| value.to_str()) == Some("jar") { - archive_count += 1; - if archive_count > MAX_METADATA_ARCHIVES { - return Ok(properties); - } - append_archive_metadata(&path, &mut properties)?; - } - } - } - deduplicate_properties(&mut properties); - Ok(properties) -} - -fn append_archive_metadata( - path: &Path, - properties: &mut Vec, -) -> Result<(), CoreError> { - cancellation::check()?; - let Ok(file) = File::open(path) else { - return Ok(()); - }; - let Ok(mut archive) = ZipArchive::new(file) else { - return Ok(()); - }; - for name in [ - "META-INF/spring-configuration-metadata.json", - "META-INF/additional-spring-configuration-metadata.json", - ] { - let Ok(mut entry) = archive.by_name(name) else { - continue; - }; - let mut content = String::new(); - if entry.read_to_string(&mut content).is_ok() { - append_metadata(&content, None, properties); - } - } - Ok(()) -} - -fn append_metadata( - content: &str, - source_path: Option<&str>, - properties: &mut Vec, -) { - let Ok(document) = serde_json::from_str::(content) else { - return; - }; - let Some(items) = document.get("properties").and_then(Value::as_array) else { - return; - }; - for item in items { - let Some(name) = item.get("name").and_then(Value::as_str) else { - continue; - }; - properties.push(SpringPropertyResponse { - name: name.to_string(), - type_name: item.get("type").and_then(Value::as_str).map(String::from), - description: item - .get("description") - .and_then(Value::as_str) - .map(String::from), - default_value: item.get("defaultValue").map(json_scalar), - source_path: source_path.map(String::from), - source_line: None, - source_column: None, - }); - } -} - -fn json_scalar(value: &Value) -> String { - value - .as_str() - .map(String::from) - .unwrap_or_else(|| value.to_string()) -} - -fn built_in_properties() -> Vec { - [ - ( - "server.port", - "java.lang.Integer", - "HTTP server port.", - "8080", - ), - ( - "spring.application.name", - "java.lang.String", - "Application name.", - "", - ), - ( - "spring.profiles.active", - "java.util.List", - "Active profiles.", - "", - ), - ( - "spring.config.activate.on-profile", - "java.lang.String", - "Profile expression for this document.", - "", - ), - ( - "spring.datasource.url", - "java.lang.String", - "JDBC URL of the database.", - "", - ), - ( - "spring.datasource.username", - "java.lang.String", - "Database login username.", - "", - ), - ( - "spring.datasource.password", - "java.lang.String", - "Database login password.", - "", - ), - ( - "spring.jpa.hibernate.ddl-auto", - "java.lang.String", - "Hibernate schema generation mode.", - "none", - ), - ( - "logging.level.root", - "java.lang.String", - "Root logger level.", - "info", - ), - ( - "management.endpoints.web.exposure.include", - "java.util.Set", - "Exposed actuator endpoints.", - "", - ), - ] - .into_iter() - .map( - |(name, type_name, description, default_value)| SpringPropertyResponse { - name: name.to_string(), - type_name: Some(type_name.to_string()), - description: Some(description.to_string()), - default_value: (!default_value.is_empty()).then(|| default_value.to_string()), - source_path: None, - source_line: None, - source_column: None, - }, - ) - .collect() -} - -fn append_configuration_properties( - sources: &[(String, String)], - properties: &mut Vec, -) -> Result<(), CoreError> { - static ANNOTATION: LazyLock = LazyLock::new(|| { - Regex::new( - r#"(?s)@ConfigurationProperties\s*\(\s*(?:prefix\s*=\s*)?[\"']([^\"']+)[\"'][^)]*\).*?\b(?:class|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)"#, - ) - .expect("literal pattern is valid") - }); - let mut types = HashMap::new(); - for (path, source) in sources { - cancellation::check()?; - for value in parse_configuration_types(path, source) { - types.insert(value.name.clone(), value); - } - } - for (_, source) in sources { - cancellation::check()?; - for capture in ANNOTATION.captures_iter(source) { - let Some(prefix) = capture.get(1) else { - continue; - }; - let Some(type_name) = capture.get(2) else { - continue; - }; - append_configuration_type( - canonical_property_name(prefix.as_str()), - type_name.as_str(), - &types, - &mut HashSet::new(), - properties, - ); - } - } - Ok(()) -} - -#[derive(Clone)] -struct ConfigurationField { - name: String, - type_name: String, - path: String, - line: usize, - column: usize, - default_value: Option, -} - -struct ConfigurationType { - name: String, - fields: Vec, - body_depth: isize, -} - -fn parse_configuration_types(path: &str, source: &str) -> Vec { - static DECLARATION: LazyLock = LazyLock::new(|| { - Regex::new(r"\b(?:class|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*\(([^)]*)\))?") - .expect("literal pattern is valid") - }); - static FIELD: LazyLock = LazyLock::new(|| { - Regex::new( - r"(?:private|protected|public)\s+(?:static\s+)?(?:final\s+)?([A-Za-z0-9_$.<>?, ]+)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:=\s*([^;]+))?;", - ) - .expect("literal pattern is valid") - }); - let mut types = Vec::::new(); - let mut stack = Vec::::new(); - let mut depth = 0isize; - for (index, line) in source.lines().enumerate() { - if let Some(capture) = DECLARATION.captures(line) { - let name = capture.get(1).unwrap(); - let body_depth = depth + brace_delta(line); - let mut value = ConfigurationType { - name: name.as_str().to_string(), - fields: Vec::new(), - body_depth, - }; - if let Some(components) = capture.get(2) { - value.fields.extend(parse_record_components( - path, - index + 1, - line, - components.as_str(), - )); - } - types.push(value); - stack.push(types.len() - 1); - } else if let Some(type_index) = stack.last().copied() { - if depth == types[type_index].body_depth { - if let Some(capture) = FIELD.captures(line) { - let name = capture.get(2).unwrap(); - types[type_index].fields.push(ConfigurationField { - name: name.as_str().to_string(), - type_name: capture.get(1).unwrap().as_str().trim().to_string(), - path: path.to_string(), - line: index + 1, - column: name.start() + 1, - default_value: capture.get(3).map(|value| { - value.as_str().trim().trim_matches(['\'', '"']).to_string() - }), - }); - } - } - } - depth += brace_delta(line); - while stack - .last() - .is_some_and(|type_index| depth < types[*type_index].body_depth) - { - stack.pop(); - } - } - types -} - -fn parse_record_components( - path: &str, - line_number: usize, - line: &str, - components: &str, -) -> Vec { - split_parameters(components) - .into_iter() - .filter_map(|value| { - let capture = JAVA_PARAMETER_DECLARATION.captures(value.trim())?; - let name = capture.get(2)?; - Some(ConfigurationField { - name: name.as_str().to_string(), - type_name: capture.get(1)?.as_str().trim().to_string(), - path: path.to_string(), - line: line_number, - column: line.find(name.as_str()).unwrap_or(0) + 1, - default_value: None, - }) - }) - .collect() -} - -fn brace_delta(line: &str) -> isize { - line.chars().fold(0, |value, character| match character { - '{' => value + 1, - '}' => value - 1, - _ => value, - }) -} - -fn append_configuration_type( - prefix: String, - type_name: &str, - types: &HashMap, - visiting: &mut HashSet, - properties: &mut Vec, -) { - let type_name = simple_type(type_name); - if !visiting.insert(type_name.clone()) { - return; - } - let Some(value) = types.get(&type_name) else { - visiting.remove(&type_name); - return; - }; - for field in &value.fields { - let name = format!("{}.{}", prefix, kebab_case(&field.name)); - let nested_type = simple_type(&field.type_name); - if types.contains_key(&nested_type) { - append_configuration_type(name, &nested_type, types, visiting, properties); - } else { - properties.push(SpringPropertyResponse { - name, - type_name: Some(field.type_name.clone()), - description: Some(format!("Binds to `{}`.", field.name)), - default_value: field.default_value.clone(), - source_path: Some(field.path.clone()), - source_line: Some(field.line), - source_column: Some(field.column), - }); - } - } - visiting.remove(&type_name); -} - -fn kebab_case(value: &str) -> String { - let mut result = String::new(); - for character in value.chars() { - if character.is_uppercase() { - if !result.is_empty() { - result.push('-'); - } - result.extend(character.to_lowercase()); - } else if character == '_' { - result.push('-'); - } else { - result.push(character); - } - } - result -} - -fn canonical_property_name(value: &str) -> String { - value - .split('.') - .map(|part| kebab_case(part.trim()).to_ascii_lowercase()) - .collect::>() - .join(".") -} - -fn deduplicate_properties(properties: &mut Vec) { - properties.sort_by(|left, right| { - left.name - .cmp(&right.name) - .then_with(|| left.source_path.is_none().cmp(&right.source_path.is_none())) - }); - properties.dedup_by(|right, left| right.name == left.name); -} - -fn is_application_configuration(name: &str) -> bool { - name == "application.properties" - || (name.starts_with("application") - && (name.ends_with(".yml") || name.ends_with(".yaml") || name.ends_with(".properties"))) -} - -fn profile_from_path(path: &str) -> Option { - let name = Path::new(path).file_name()?.to_str()?; - let stem = name - .strip_suffix(".properties") - .or_else(|| name.strip_suffix(".yaml")) - .or_else(|| name.strip_suffix(".yml"))?; - stem.strip_prefix("application-") - .filter(|value| !value.is_empty()) - .map(String::from) -} - -fn parse_properties(path: &str, content: &str) -> Vec { - let profile = profile_from_path(path); - logical_property_lines(content) - .into_iter() - .filter_map(|(index, line)| { - let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('!') { - return None; - } - let separator = property_separator(trimmed)?; - let key = trimmed[..separator].trim(); - if key.is_empty() { - return None; - } - Some(SpringConfigurationValueResponse { - key: canonical_property_name(&unescape_property(key)), - value: unescape_property(trimmed[separator + 1..].trim()), - path: path.to_string(), - line: index, - column: line.find(key).unwrap_or(0) + 1, - profile: profile.clone(), - overrides_base_value: false, - target_path: None, - target_line: None, - target_column: None, - }) - }) - .collect() -} - -fn logical_property_lines(content: &str) -> Vec<(usize, String)> { - let mut values = Vec::new(); - let mut pending: Option<(usize, String)> = None; - for (index, line) in content.lines().enumerate() { - let start_line = index + 1; - let mut part = line.to_string(); - let continued = part - .chars() - .rev() - .take_while(|value| *value == '\\') - .count() - % 2 - == 1; - if continued { - part.pop(); - } - if let Some((_, value)) = pending.as_mut() { - value.push_str(part.trim_start()); - } else { - pending = Some((start_line, part)); - } - if !continued { - if let Some(value) = pending.take() { - values.push(value); - } - } - } - if let Some(value) = pending { - values.push(value); - } - values -} - -fn property_separator(value: &str) -> Option { - let mut escaped = false; - for (index, character) in value.char_indices() { - if escaped { - escaped = false; - continue; - } - if character == '\\' { - escaped = true; - } else if character == '=' || character == ':' || character.is_whitespace() { - return Some(index); - } - } - None -} - -fn unescape_property(value: &str) -> String { - value - .replace("\\:", ":") - .replace("\\=", "=") - .replace("\\ ", " ") - .replace("\\\\", "\\") -} - -fn parse_yaml(path: &str, content: &str) -> Vec { - let file_profile = profile_from_path(path); - let lines = content.lines().collect::>(); - let mut values = Vec::new(); - let mut document_start = 0usize; - for index in 0..=lines.len() { - if index == lines.len() || lines[index].trim() == "---" { - values.extend(parse_yaml_document( - path, - &lines[document_start..index], - document_start, - file_profile.clone(), - )); - document_start = index + 1; - } - } - values -} - -fn parse_yaml_document( - path: &str, - lines: &[&str], - line_offset: usize, - file_profile: Option, -) -> Vec { - let mut stack: Vec<(usize, String)> = Vec::new(); - let mut values = Vec::new(); - for (index, line) in lines.iter().enumerate() { - let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') { - continue; - } - if let Some(item) = trimmed - .strip_prefix('-') - .map(str::trim) - .filter(|value| !value.is_empty()) - { - let key = stack - .iter() - .map(|(_, part)| part.as_str()) - .collect::>() - .join("."); - if !key.is_empty() { - values.push(SpringConfigurationValueResponse { - key: canonical_property_name(&key), - value: item.trim_matches(['\'', '"']).to_string(), - path: path.to_string(), - line: line_offset + index + 1, - column: line.find('-').unwrap_or(0) + 1, - profile: None, - overrides_base_value: false, - target_path: None, - target_line: None, - target_column: None, - }); - } - continue; - } - let Some(separator) = trimmed.find(':') else { - continue; - }; - let key = trimmed[..separator].trim().trim_matches(['\'', '"']); - if key.is_empty() { - continue; - } - let indent = line - .chars() - .take_while(|value| value.is_whitespace()) - .count(); - while stack.last().is_some_and(|(level, _)| *level >= indent) { - stack.pop(); - } - let value = trimmed[separator + 1..].trim().trim_matches(['\'', '"']); - let mut parts = stack - .iter() - .map(|(_, part)| part.clone()) - .collect::>(); - parts.push(key.to_string()); - let full_key = canonical_property_name(&parts.join(".")); - if value.is_empty() { - stack.push((indent, key.to_string())); - continue; - } - values.push(SpringConfigurationValueResponse { - key: full_key, - value: value.to_string(), - path: path.to_string(), - line: line_offset + index + 1, - column: line.find(key).unwrap_or(0) + 1, - profile: None, - overrides_base_value: false, - target_path: None, - target_line: None, - target_column: None, - }); - } - let profile = file_profile.or_else(|| { - values - .iter() - .find(|value| value.key == "spring.config.activate.on-profile") - .map(|value| value.value.clone()) - }); - for value in &mut values { - value.profile = profile.clone(); - } - values -} - -fn attach_property_targets( - properties: &[SpringPropertyResponse], - values: &mut [SpringConfigurationValueResponse], -) { - let by_name = properties - .iter() - .map(|property| (canonical_property_name(&property.name), property)) - .collect::>(); - for value in values { - if let Some(property) = by_name.get(&canonical_property_name(&value.key)) { - value.target_path = property.source_path.clone(); - value.target_line = property.source_line; - value.target_column = property.source_column; - } - } -} - -fn mark_profile_overrides(values: &mut [SpringConfigurationValueResponse]) { - let base_keys = values - .iter() - .filter(|value| value.profile.is_none()) - .map(|value| value.key.clone()) - .collect::>(); - for value in values { - value.overrides_base_value = value.profile.is_some() && base_keys.contains(&value.key); - } -} - -fn configuration_diagnostics( - properties: &[SpringPropertyResponse], - values: &[SpringConfigurationValueResponse], -) -> Vec { - let known = properties - .iter() - .map(|property| canonical_property_name(&property.name)) - .collect::>(); - let types = properties - .iter() - .filter_map(|property| { - property - .type_name - .as_deref() - .map(|type_name| (canonical_property_name(&property.name), type_name)) - }) - .collect::>(); - let mut diagnostics = Vec::new(); - for value in values { - let canonical_key = canonical_property_name(&value.key); - if !known.contains(&canonical_key) { - diagnostics.push(SpringDiagnosticResponse { - path: value.path.clone(), - line: value.line, - column: value.column, - severity: "warning".to_string(), - message: format!("Unknown Spring configuration property `{}`", value.key), - }); - continue; - } - let Some(type_name) = types.get(&canonical_key) else { - continue; - }; - let valid = if type_name.contains("Boolean") || *type_name == "boolean" { - matches!(value.value.as_str(), "true" | "false") - } else if type_name.contains("Integer") || *type_name == "int" || *type_name == "long" { - value.value.parse::().is_ok() - } else { - true - }; - if !valid { - diagnostics.push(SpringDiagnosticResponse { - path: value.path.clone(), - line: value.line, - column: value.column, - severity: "error".to_string(), - message: format!("`{}` is not a valid value for `{}`", value.value, type_name), - }); - } - } - diagnostics -} - -#[derive(Clone)] -struct IndexedBean { - response: SpringBeanResponse, - names: HashSet, - assignable_types: HashSet, - primary: bool, -} - -struct RawInjection { - path: String, - line: usize, - column: usize, - type_name: String, - qualifier: Option, -} - -fn bean_index( - sources: &[(String, String)], -) -> Result< - ( - Vec, - Vec, - Vec, - ), - CoreError, -> { - static TYPE_DECLARATION: LazyLock = LazyLock::new(|| { - Regex::new(r"\b(class|interface|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)([^\{]*)") - .expect("literal pattern is valid") - }); - static METHOD: LazyLock = LazyLock::new(|| { - Regex::new( - r"(?:public|protected|private)?\s*(?:static\s+)?(?:final\s+)?([A-Za-z0-9_$.<>?]+)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(", - ) - .expect("literal pattern is valid") - }); - static FIELD: LazyLock = LazyLock::new(|| { - Regex::new( - r"(?:private|protected|public)\s+(?:static\s+)?(?:final\s+)?([A-Za-z0-9_$.<>?]+)\s+([A-Za-z_$][A-Za-z0-9_$]*)", - ) - .expect("literal pattern is valid") - }); - let mut supertypes = HashMap::>::new(); - for (_, source) in sources { - cancellation::check()?; - for capture in TYPE_DECLARATION.captures_iter(source) { - let Some(name) = capture.get(2) else { continue }; - let tail = capture - .get(3) - .map(|value| value.as_str()) - .unwrap_or_default(); - supertypes.insert(name.as_str().to_string(), declared_supertypes(tail)); - } - } - - let mut indexed_beans = Vec::new(); - let mut raw_injections = Vec::new(); - for (path, source) in sources { - cancellation::check()?; - let lines = source.lines().collect::>(); - let source_type = TYPE_DECLARATION - .captures(source) - .and_then(|capture| capture.get(2)) - .map(|value| value.as_str().to_string()); - // The constructor pattern depends on the declaring type, so it cannot be - // a file-independent constant, but it is identical for every line of one - // source and must not be rebuilt inside the line loop below. - let constructor_pattern = source_type.as_deref().and_then(constructor_regex); - let constructor_count = constructor_pattern - .as_ref() - .map_or(0, |pattern| pattern.captures_iter(source).count()); - for (index, line) in lines.iter().enumerate() { - let context = annotation_context(&lines, index); - if let Some(capture) = TYPE_DECLARATION.captures(line) { - if has_component_annotation(&context) { - let name = capture.get(2).unwrap(); - let default_name = lower_camel(name.as_str()); - let bean_name = component_name(&context).unwrap_or(default_name); - let mut names = HashSet::from([bean_name.clone()]); - names.extend(qualifier_names(&context)); - indexed_beans.push(IndexedBean { - response: SpringBeanResponse { - id: format!("{}:{}", path, bean_name), - name: bean_name, - type_name: name.as_str().to_string(), - path: path.clone(), - line: index + 1, - column: name.start() + 1, - kind: "component".to_string(), - }, - names, - assignable_types: assignable_types(name.as_str(), &supertypes), - primary: SpringAnnotation::Primary.is_present(&context), - }); - } - } - if SpringAnnotation::Bean.is_present(&context) { - if let Some(capture) = METHOD.captures(line) { - let type_name = simple_type(capture.get(1).unwrap().as_str()); - let declaration_name = capture.get(2).unwrap(); - let aliases = bean_names(&context); - let bean_name = aliases - .first() - .cloned() - .unwrap_or_else(|| declaration_name.as_str().to_string()); - let mut names = aliases.into_iter().collect::>(); - names.insert(bean_name.clone()); - names.extend(qualifier_names(&context)); - indexed_beans.push(IndexedBean { - response: SpringBeanResponse { - id: format!("{}:{}", path, bean_name), - name: bean_name, - type_name: type_name.clone(), - path: path.clone(), - line: index + 1, - column: declaration_name.start() + 1, - kind: "beanMethod".to_string(), - }, - names, - assignable_types: assignable_types(&type_name, &supertypes), - primary: SpringAnnotation::Primary.is_present(&context), - }); - } - } - if is_injection_context(&context) { - if let Some(capture) = FIELD.captures(line) { - let type_name = simple_type(capture.get(1).unwrap().as_str()); - let name = capture.get(2).unwrap(); - raw_injections.push(RawInjection { - path: path.clone(), - line: index + 1, - column: name.start() + 1, - type_name, - qualifier: injection_qualifier(&context), - }); - } - } - let Some(pattern) = constructor_pattern.as_ref() else { - continue; - }; - let Some(opening) = pattern.find(line).map(|value| value.end() - 1) else { - continue; - }; - if !is_injection_context(&context) && constructor_count != 1 { - continue; - } - let Some(closing) = line.rfind(')').filter(|value| *value > opening) else { - continue; - }; - raw_injections.extend(parse_constructor_injections( - path, - index + 1, - line, - &line[opening + 1..closing], - )); - } - } - - indexed_beans.sort_by(|left, right| { - left.response - .name - .cmp(&right.response.name) - .then_with(|| left.response.path.cmp(&right.response.path)) - }); - let mut diagnostics = Vec::new(); - let mut injections = raw_injections - .into_iter() - .map(|injection| { - let mut candidates = indexed_beans - .iter() - .filter(|bean| bean.assignable_types.contains(&injection.type_name)) - .collect::>(); - if let Some(qualifier) = injection.qualifier.as_deref() { - candidates.retain(|bean| bean.names.contains(qualifier)); - } else { - let primary = candidates - .iter() - .copied() - .filter(|bean| bean.primary) - .collect::>(); - if !primary.is_empty() { - candidates = primary; - } - } - if candidates.is_empty() { - diagnostics.push(SpringDiagnosticResponse { - path: injection.path.clone(), - line: injection.line, - column: injection.column, - severity: "warning".to_string(), - message: format!( - "No Spring bean satisfies injection type `{}`{}", - injection.type_name, - injection - .qualifier - .as_deref() - .map(|value| format!(" with qualifier `{value}`")) - .unwrap_or_default() - ), - }); - } else if candidates.len() > 1 { - diagnostics.push(SpringDiagnosticResponse { - path: injection.path.clone(), - line: injection.line, - column: injection.column, - severity: "warning".to_string(), - message: format!( - "Multiple Spring beans satisfy injection type `{}`", - injection.type_name - ), - }); - } - SpringInjectionResponse { - path: injection.path, - line: injection.line, - column: injection.column, - type_name: injection.type_name, - qualifier: injection.qualifier, - bean_ids: candidates - .into_iter() - .map(|bean| bean.response.id.clone()) - .collect(), - } - }) - .collect::>(); - injections.sort_by(|left, right| { - left.path - .cmp(&right.path) - .then_with(|| left.line.cmp(&right.line)) - .then_with(|| left.column.cmp(&right.column)) - }); - let beans = indexed_beans - .into_iter() - .map(|bean| bean.response) - .collect(); - Ok((beans, injections, diagnostics)) -} - -fn annotation_context(lines: &[&str], index: usize) -> String { - let mut values = vec![lines[index].trim().to_string()]; - for previous in lines[..index].iter().rev().take(8) { - let trimmed = previous.trim(); - if trimmed.is_empty() { - continue; - } - if trimmed.starts_with('@') - || trimmed.starts_with("value") - || trimmed.starts_with("name") - || trimmed == ")" - || trimmed == "}" - { - values.insert(0, trimmed.to_string()); - } else { - break; - } - } - values.join(" ") -} - -/// Matches `@Name` only when the name is not a prefix of a longer annotation, -/// so `@Bean` does not match `@BeanFactory`. -fn annotation_boundary_pattern(name: &str) -> Regex { - Regex::new(&format!(r"@{}(?:\s|\(|$)", regex::escape(name))) - .expect("an escaped annotation name is a valid pattern") -} - -/// Declares the Spring annotations this module recognizes exactly once, and -/// derives the type, the spelling, the full list, and the compiled pattern from -/// that one declaration. -/// -/// Detection runs several times for every line of every Java source, so each -/// pattern is compiled once for the process. `pattern` matches on `self` instead -/// of looking the annotation up in a table, which leaves the compiler to reject -/// a case that was added without a pattern. -macro_rules! spring_annotations { - ($($variant:ident => $name:literal),+ $(,)?) => { - #[derive(Clone, Copy)] - pub(crate) enum SpringAnnotation { - $($variant),+ - } - - impl SpringAnnotation { - /// Every recognized annotation, in declaration order. Production - /// code reaches a pattern through a case rather than this list. - #[cfg(test)] - pub(crate) const ALL: &'static [Self] = &[$(Self::$variant),+]; - - #[cfg(test)] - pub(crate) fn name(self) -> &'static str { - match self { - $(Self::$variant => $name),+ - } - } - - pub(crate) fn pattern(self) -> &'static Regex { - match self { - $(Self::$variant => { - static PATTERN: LazyLock = - LazyLock::new(|| annotation_boundary_pattern($name)); - &PATTERN - })+ - } - } - } - }; -} - -spring_annotations! { - Autowired => "Autowired", - Bean => "Bean", - Component => "Component", - Configuration => "Configuration", - Controller => "Controller", - Inject => "Inject", - Primary => "Primary", - Repository => "Repository", - Resource => "Resource", - RestController => "RestController", - Service => "Service", -} - -/// Declares the Spring web mapping annotations exactly once, and derives the -/// type, spelling, boundary pattern, fixed HTTP method, and test list from that -/// one declaration. `RequestMapping` carries `None` so methods come from its -/// `RequestMethod.*` arguments instead. -macro_rules! spring_mapping_annotations { - ($($variant:ident => $name:literal, $method:expr),+ $(,)?) => { - #[derive(Clone, Copy, Debug, Eq, PartialEq)] - enum SpringMappingAnnotation { - $($variant),+ - } - - impl SpringMappingAnnotation { - /// Every recognized mapping annotation. Production selection walks - /// this list and keeps the earliest source match, not declaration - /// order by itself. - const ALL: &'static [Self] = &[$(Self::$variant),+]; - - #[cfg(test)] - fn name(self) -> &'static str { - match self { - $(Self::$variant => $name),+ - } - } - - fn pattern(self) -> &'static Regex { - match self { - $(Self::$variant => { - static PATTERN: LazyLock = - LazyLock::new(|| annotation_boundary_pattern($name)); - &PATTERN - })+ - } - } - - /// Fixed verb for method mappings; `None` for [`Self::RequestMapping`]. - fn fixed_http_method(self) -> Option<&'static str> { - match self { - $(Self::$variant => $method),+ - } - } - - #[cfg(test)] - fn is_present(self, context: &str) -> bool { - self.pattern().is_match(context) - } - } - }; -} - -spring_mapping_annotations! { - GetMapping => "GetMapping", Some("GET"), - PostMapping => "PostMapping", Some("POST"), - PutMapping => "PutMapping", Some("PUT"), - DeleteMapping => "DeleteMapping", Some("DELETE"), - PatchMapping => "PatchMapping", Some("PATCH"), - RequestMapping => "RequestMapping", None, -} - -impl SpringAnnotation { - /// Annotations that declare a Spring component on a type declaration. - /// Detection and naming share this closed set so they cannot drift; when - /// several are present, the leftmost source match wins rather than this - /// array's declaration order. - const COMPONENTS: [Self; 6] = [ - Self::Component, - Self::Service, - Self::Repository, - Self::Controller, - Self::RestController, - Self::Configuration, - ]; - - /// Annotations that mark a field or constructor parameter for injection. - const INJECTIONS: [Self; 3] = [Self::Autowired, Self::Inject, Self::Resource]; - - pub(crate) fn is_present(self, context: &str) -> bool { - self.pattern().is_match(context) - } -} - -fn has_component_annotation(context: &str) -> bool { - SpringAnnotation::COMPONENTS - .iter() - .any(|annotation| annotation.is_present(context)) -} - -/// Returns the explicit name of the earliest component annotation in source -/// order. The value is read only from that annotation's own argument list so a -/// later neighbor such as `@Component("c")` cannot pollute `@Service("s")`. -/// An empty string such as `@Component("")` is not a name; callers then use -/// the default type name. -fn component_name(context: &str) -> Option { - let start = earliest_component_annotation_start(context)?; - quoted_values(isolate_annotation_at(context, start)) - .into_iter() - .find(|value| !value.is_empty()) -} - -/// Locates every exact component annotation with the cached boundary patterns -/// and keeps the leftmost source start. Array order in [`SpringAnnotation::COMPONENTS`] -/// is not a priority. -fn earliest_component_annotation_start(context: &str) -> Option { - SpringAnnotation::COMPONENTS - .iter() - .filter_map(|annotation| { - annotation - .pattern() - .find(context) - .map(|found| found.start()) - }) - .min() -} - -fn qualifier_names(context: &str) -> Vec { - static PATTERN: LazyLock = LazyLock::new(|| { - Regex::new(r#"@Qualifier\s*\(\s*[\"']([^\"']+)[\"']\s*\)"#) - .expect("literal pattern is valid") - }); - PATTERN - .captures_iter(context) - .filter_map(|capture| capture.get(1).map(|value| value.as_str().to_string())) - .collect() -} - -/// Returns declared `@Bean` aliases from the exact `@Bean` annotation only. -/// A prefix decoy such as `@BeanFactory("decoy")` cannot supply the name. -fn bean_names(context: &str) -> Vec { - let Some(found) = SpringAnnotation::Bean.pattern().find(context) else { - return Vec::new(); - }; - quoted_values(isolate_annotation_at(context, found.start())) - .into_iter() - .filter(|value| !value.is_empty()) - .collect() -} - -fn quoted_values(value: &str) -> Vec { - static PATTERN: LazyLock = - LazyLock::new(|| Regex::new(r#"[\"']([^\"']*)[\"']"#).expect("literal pattern is valid")); - PATTERN - .captures_iter(value) - .filter_map(|capture| capture.get(1).map(|item| item.as_str().to_string())) - .collect() -} - -fn declared_supertypes(tail: &str) -> Vec { - // Indexed by the fixed keyword order below, which the result order depends on. - static PATTERNS: LazyLock<[Regex; 2]> = LazyLock::new(|| { - ["extends", "implements"].map(|keyword| { - Regex::new(&format!( - r"\b{}\s+([^\{{]+?)(?:\b(?:extends|implements)\b|$)", - keyword - )) - .expect("literal keyword produces a valid pattern") - }) - }); - let mut values = Vec::new(); - for pattern in PATTERNS.iter() { - if let Some(capture) = pattern.captures(tail) { - values.extend( - capture[1] - .split(',') - .map(simple_type) - .filter(|value| !value.is_empty()), - ); - } - } - values -} - -fn assignable_types(type_name: &str, supertypes: &HashMap>) -> HashSet { - let mut values = HashSet::new(); - let mut pending = vec![simple_type(type_name)]; - while let Some(value) = pending.pop() { - if !values.insert(value.clone()) { - continue; - } - if let Some(parents) = supertypes.get(&value) { - pending.extend(parents.iter().cloned()); - } - } - values -} - -fn is_injection_context(context: &str) -> bool { - SpringAnnotation::INJECTIONS - .iter() - .any(|annotation| annotation.is_present(context)) -} - -fn injection_qualifier(context: &str) -> Option { - qualifier_names(context).into_iter().next().or_else(|| { - static RESOURCE: LazyLock = LazyLock::new(|| { - Regex::new(r#"@Resource\s*\([^\)]*name\s*=\s*[\"']([^\"']+)[\"']"#) - .expect("literal pattern is valid") - }); - RESOURCE - .captures(context) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str().to_string()) - }) -} - -fn constructor_regex(type_name: &str) -> Option { - Regex::new(&format!( - r"(?:public|protected|private)?\s*{}\s*\(", - regex::escape(type_name) - )) - .ok() -} - -fn parse_constructor_injections( - path: &str, - line_number: usize, - line: &str, - parameters: &str, -) -> Vec { - split_parameters(parameters) - .into_iter() - .filter_map(|parameter| { - let capture = JAVA_PARAMETER_DECLARATION.captures(parameter.trim())?; - let variable = capture.get(2)?; - Some(RawInjection { - path: path.to_string(), - line: line_number, - column: line.find(variable.as_str()).unwrap_or(0) + 1, - type_name: simple_type(capture.get(1)?.as_str()), - qualifier: injection_qualifier(parameter), - }) - }) - .collect() -} - -fn split_parameters(value: &str) -> Vec<&str> { - let mut values = Vec::new(); - let mut start = 0usize; - let mut depth = 0usize; - for (index, character) in value.char_indices() { - match character { - '<' | '(' | '{' | '[' => depth += 1, - '>' | ')' | '}' | ']' => depth = depth.saturating_sub(1), - ',' if depth == 0 => { - values.push(&value[start..index]); - start = index + 1; - } - _ => {} - } - } - if start < value.len() { - values.push(&value[start..]); - } - values -} - -fn endpoint_index(sources: &[(String, String)]) -> Result, CoreError> { - static CLASS: LazyLock = LazyLock::new(|| { - Regex::new(r"\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)").expect("literal pattern is valid") - }); - static METHOD: LazyLock = LazyLock::new(|| { - Regex::new(r"[A-Za-z0-9_$.<>?]+\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(") - .expect("literal pattern is valid") - }); - let mut endpoints = Vec::new(); - for (path, source) in sources { - cancellation::check()?; - if !SpringAnnotation::Controller.is_present(source) - && !SpringAnnotation::RestController.is_present(source) - { - continue; - } - let controller = CLASS - .captures(source) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str().to_string()) - .unwrap_or_else(|| "Controller".to_string()); - let lines = source.lines().collect::>(); - let mut base_routes = vec![String::new()]; - let mut index = 0usize; - while index < lines.len() { - if !lines[index].trim_start().starts_with('@') { - index += 1; - continue; - } - let (annotation, annotation_end) = annotation_block(&lines, index); - let Some((mapping_annotation, methods, routes)) = mapping(&annotation) else { - index = annotation_end + 1; - continue; - }; - let declaration_index = next_declaration_index(&lines, annotation_end + 1); - let declaration = declaration_index - .and_then(|value| lines.get(value).copied()) - .unwrap_or_default(); - // Class-level base routes come only from an exact @RequestMapping, not - // a longer custom name that merely starts with that spelling. - if mapping_annotation == SpringMappingAnnotation::RequestMapping - && CLASS.is_match(declaration) - { - base_routes = routes; - index = annotation_end + 1; - continue; - } - let method_name = METHOD - .captures(declaration) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str()) - .unwrap_or("handler"); - for base_route in &base_routes { - for route in &routes { - let joined = join_route(base_route, route); - endpoints.push(SpringEndpointResponse { - id: format!("{}:{}:{}:{}", path, index + 1, methods.join(","), joined), - http_methods: methods.clone(), - route: joined, - controller: controller.clone(), - method: method_name.to_string(), - path: path.clone(), - line: index + 1, - column: lines[index].find('@').unwrap_or(0) + 1, - }); - } - } - index = annotation_end + 1; - } - } - endpoints.sort_by(|left, right| { - left.route - .cmp(&right.route) - .then_with(|| left.http_methods.cmp(&right.http_methods)) - }); - Ok(endpoints) -} - -/// Finds the earliest exact Mapping annotation in `annotation_text` and returns -/// its HTTP methods and routes. Custom names that only share a standard prefix -/// (for example `@GetMappingCustom`) do not match. -/// -/// When several Mapping annotations appear in one context, the leftmost source -/// span wins so selection does not depend on declaration order in -/// [`SpringMappingAnnotation::ALL`]. -fn mapping(annotation_text: &str) -> Option<(SpringMappingAnnotation, Vec, Vec)> { - let (annotation, isolated) = find_mapping_annotation(annotation_text)?; - let methods = match annotation.fixed_http_method() { - Some(method) => vec![method.to_string()], - None => request_mapping_methods(isolated), - }; - Some((annotation, methods, annotation_routes(isolated))) -} - -/// Returns the earliest exact Mapping annotation and the isolated annotation -/// text used for route and `RequestMethod` parsing. -fn find_mapping_annotation(text: &str) -> Option<(SpringMappingAnnotation, &str)> { - let mut best: Option<(usize, SpringMappingAnnotation)> = None; - for &annotation in SpringMappingAnnotation::ALL { - if let Some(found) = annotation.pattern().find(text) { - let start = found.start(); - match best { - Some((best_start, _)) if start >= best_start => {} - _ => best = Some((start, annotation)), - } - } - } - let (start, annotation) = best?; - Some((annotation, isolate_annotation_at(text, start))) -} - -/// Slices one annotation starting at `start` (`@Name` followed by an optional -/// argument list) so name or route extraction cannot read string literals from -/// a neighboring decoy. -/// -/// A later annotation's `(` is not this annotation's argument list. After the -/// name, only whitespace may appear before `(`. Parentheses inside quoted -/// strings, including escaped quotes, do not change the argument-list depth. -fn isolate_annotation_at(text: &str, start: usize) -> &str { - let rest = &text[start..]; - let name_end = rest - .char_indices() - .skip(1) - .find(|(_, character)| { - !(character.is_ascii_alphanumeric() || *character == '_' || *character == '$') - }) - .map(|(index, _)| index) - .unwrap_or(rest.len()); - let after_name = rest.get(name_end..).unwrap_or(""); - let whitespace_len = after_name - .chars() - .take_while(|character| character.is_whitespace()) - .map(char::len_utf8) - .sum::(); - let after_whitespace = after_name.get(whitespace_len..).unwrap_or(""); - if !after_whitespace.starts_with('(') { - return &rest[..name_end]; - } - let open_index = name_end + whitespace_len; - let mut depth = 0isize; - let mut in_string = None; - let mut escaped = false; - for (index, character) in rest[open_index..].char_indices() { - if let Some(quote) = in_string { - if escaped { - escaped = false; - continue; - } - if character == '\\' { - escaped = true; - continue; - } - if character == quote { - in_string = None; - } - continue; - } - match character { - '"' | '\'' => in_string = Some(character), - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - return &rest[..open_index + index + 1]; - } - } - _ => {} - } - } - rest -} - -fn request_mapping_methods(annotation: &str) -> Vec { - static METHOD_PATTERN: LazyLock = LazyLock::new(|| { - Regex::new(r"RequestMethod\.(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE)") - .expect("literal pattern is valid") - }); - let mut methods = METHOD_PATTERN - .captures_iter(annotation) - .filter_map(|capture| capture.get(1).map(|value| value.as_str().to_string())) - .collect::>(); - if methods.is_empty() { - methods.push("ANY".to_string()); - } - methods.sort(); - methods.dedup(); - methods -} - -fn annotation_routes(annotation: &str) -> Vec { - static NAMED: LazyLock = LazyLock::new(|| { - Regex::new(r#"(?:value|path)\s*=\s*(\{[^}]*\}|[\"'][^\"']*[\"'])"#) - .expect("literal pattern is valid") - }); - let expression = NAMED - .captures(annotation) - .and_then(|capture| capture.get(1)) - .map(|value| value.as_str()) - .or_else(|| { - let start = annotation.find('(')? + 1; - let end = annotation.rfind(')')?; - let value = annotation[start..end].trim(); - (value.starts_with(['\'', '"', '{'])).then_some(value) - }); - let mut routes = expression.map(quoted_values).unwrap_or_default(); - if routes.is_empty() { - routes.push(String::new()); - } - routes.sort(); - routes.dedup(); - routes -} - -fn annotation_block(lines: &[&str], start: usize) -> (String, usize) { - let mut value = String::new(); - let mut depth = 0isize; - let mut saw_parenthesis = false; - let mut end = start; - for (index, line) in lines.iter().enumerate().skip(start) { - if !value.is_empty() { - value.push(' '); - } - value.push_str(line.trim()); - for character in line.chars() { - if character == '(' { - depth += 1; - saw_parenthesis = true; - } else if character == ')' { - depth -= 1; - } - } - end = index; - if !saw_parenthesis || depth <= 0 { - break; - } - } - (value, end) -} - -fn next_declaration_index(lines: &[&str], start: usize) -> Option { - lines - .iter() - .enumerate() - .skip(start) - .take(12) - .find_map(|(index, line)| { - let trimmed = line.trim(); - (!trimmed.is_empty() && !trimmed.starts_with('@')).then_some(index) - }) -} - -fn join_route(base: &str, route: &str) -> String { - let value = format!("{}/{}", base.trim_matches('/'), route.trim_matches('/')); - let trimmed = value.trim_matches('/'); - if trimmed.is_empty() { - "/".to_string() - } else { - format!("/{trimmed}") - } -} - -fn simple_type(value: &str) -> String { - value - .split('<') - .next() - .unwrap_or(value) - .rsplit('.') - .next() - .unwrap_or(value) - .trim() - .to_string() -} - -fn lower_camel(value: &str) -> String { - let mut characters = value.chars(); - characters - .next() - .map(|first| first.to_lowercase().collect::() + characters.as_str()) - .unwrap_or_default() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashSet; - - /// `spring_annotations!` derives the type, the spelling, `ALL`, and the - /// compiled pattern from one declaration, so a case cannot exist without a - /// pattern. This covers the boundary each entry has to keep. - #[test] - fn every_supported_annotation_has_a_compiled_boundary_pattern() { - for annotation in SpringAnnotation::ALL.iter().copied() { - let name = annotation.name(); - assert!( - annotation.is_present(&format!("@{name} public class Demo")), - "{name} should match its own annotation" - ); - assert!( - annotation.is_present(&format!("@{name}(\"value\")")), - "{name} should match when it carries arguments" - ); - assert!( - annotation.is_present(&format!("@{name}")), - "{name} should match at the end of a context" - ); - assert!( - !annotation.is_present(&format!("@{name}Extended public class Demo")), - "{name} must not match a longer annotation sharing its prefix" - ); - } - - let names = SpringAnnotation::ALL - .iter() - .map(|annotation| annotation.name()) - .collect::>(); - assert_eq!( - names.len(), - SpringAnnotation::ALL.len(), - "every case needs a distinct annotation name" - ); - } - - /// Component detection and component naming must recognize the same - /// annotations, so both read COMPONENTS instead of repeating the list. - #[test] - fn component_detection_and_naming_recognize_the_same_annotations() { - for annotation in SpringAnnotation::COMPONENTS { - let name = annotation.name(); - assert!( - has_component_annotation(&format!("@{name}\npublic class Demo")), - "{name} should be detected as a component annotation" - ); - assert_eq!( - component_name(&format!("@{name}(\"custom\")\npublic class Demo")).as_deref(), - Some("custom"), - "{name} should expose its declared bean name" - ); - } - - assert!(!has_component_annotation("@Bean\npublic Clock clock()")); - assert_eq!(component_name("@Qualifier(\"custom\")"), None); - } - - /// `@BeanFactory` shares a prefix with `@Bean`, so a naive `@Bean` search - /// would take the decoy name. Naming must reuse the cached boundary match. - #[test] - fn bean_names_uses_the_exact_bean_annotation_not_a_prefix() { - assert_eq!( - bean_names(r#"@BeanFactory("decoy") @Bean("real")"#), - vec!["real".to_string()] - ); - assert_eq!(bean_names(r#"@BeanFactory("decoy")"#), Vec::::new()); - assert_eq!(bean_names(r#"@Bean("real")"#), vec!["real".to_string()]); - assert_eq!(bean_names("@Bean"), Vec::::new()); - assert_eq!( - bean_names(r#"@BeanFactory("decoy") @Bean"#), - Vec::::new() - ); - } - - /// A `(` inside a string is not the annotation argument list. Counting it - /// would swallow the real closer and pull a later neighbor into the aliases. - #[test] - fn isolate_annotation_at_ignores_parentheses_inside_strings() { - assert_eq!( - isolate_annotation_at(r#"@Bean("foo(") @Bean("bar")"#, 0), - r#"@Bean("foo(")"# - ); - assert_eq!( - isolate_annotation_at(r#"@Bean('foo(') @Service("s")"#, 0), - r#"@Bean('foo(')"# - ); - assert_eq!( - isolate_annotation_at(r#"@Bean("foo\")") @Bean("bar")"#, 0), - r#"@Bean("foo\")")"# - ); - assert_eq!( - bean_names(r#"@Bean("foo(") @Bean("bar")"#), - vec!["foo(".to_string()] - ); - assert_eq!( - component_name(r#"@Service("s(") @Component("c")"#).as_deref(), - Some("s(") - ); - let mapping_with_paren = mapping(r#"@GetMapping("/foo(") @PostMapping("/bar")"#) - .expect("GetMapping with a parenthesis in its route should still isolate"); - assert_eq!(mapping_with_paren.0, SpringMappingAnnotation::GetMapping); - assert_eq!(mapping_with_paren.2, vec!["/foo(".to_string()]); - } - - /// A wide capture can start at the first closing quote and swallow - /// `) @Component(`. Isolation plus source-position selection must keep - /// the first annotation's own value, independent of COMPONENTS order. - #[test] - fn component_name_selects_the_earliest_annotation_and_isolates_its_value() { - assert_eq!( - component_name(r#"@Service("s") @Component("c")"#).as_deref(), - Some("s") - ); - assert_eq!( - component_name(r#"@Component("c") @Service("s")"#).as_deref(), - Some("c") - ); - assert_ne!( - component_name(r#"@Service("s") @Component("c")"#).as_deref(), - Some(") @Component(") - ); - assert_eq!(component_name("@Service @Component"), None); - assert_eq!(component_name(r#"@Service @Component("c")"#), None); - assert_eq!(component_name("@Service"), None); - assert_eq!(component_name("@ServiceLocator(\"x\")"), None); - } - - /// `quoted_values` accepts empty captures. An empty annotation value is not - /// an explicit bean name, so naming must return None and let bean_index use - /// the default type or method name. - #[test] - fn empty_annotation_values_are_not_explicit_bean_names() { - assert_eq!(component_name(r#"@Component("")"#), None); - assert_eq!(component_name(r#"@Service('')"#), None); - assert_eq!( - component_name(r#"@Component("") @Service("s")"#), - None, - "an empty leftmost name must not take a later neighbor" - ); - assert_eq!(bean_names(r#"@Bean("")"#), Vec::::new()); - } - - /// Record components and constructor parameters share one pattern, so a - /// declaration parsed by one path must be parsed identically by the other. - #[test] - fn record_components_and_constructor_parameters_share_one_declaration_pattern() { - let parameters = "@Qualifier(\"stripe\") final PaymentService payments"; - let fields = parse_record_components("Demo.java", 1, parameters, parameters); - let injections = parse_constructor_injections("Demo.java", 1, parameters, parameters); - - assert_eq!(fields.len(), 1); - assert_eq!(injections.len(), 1); - assert_eq!(fields[0].name, "payments"); - assert_eq!(fields[0].type_name, "PaymentService"); - assert_eq!(injections[0].type_name, "PaymentService"); - } - - /// Mapping detection must use the same closed set for spelling, boundary - /// matching, and HTTP methods so a prefix decoy cannot become an endpoint. - #[test] - fn every_mapping_annotation_has_a_compiled_boundary_pattern() { - for annotation in SpringMappingAnnotation::ALL.iter().copied() { - let name = annotation.name(); - assert!( - annotation.is_present(&format!("@{name}(\"/x\")")), - "{name} should match its own annotation" - ); - assert!( - annotation.is_present(&format!("@{name}")), - "{name} should match at the end of a context" - ); - assert!( - !annotation.is_present(&format!("@{name}Custom(\"/x\")")), - "{name} must not match a longer annotation sharing its prefix" - ); - } - - let names = SpringMappingAnnotation::ALL - .iter() - .map(|annotation| annotation.name()) - .collect::>(); - assert_eq!( - names.len(), - SpringMappingAnnotation::ALL.len(), - "every mapping case needs a distinct annotation name" - ); - } - - #[test] - fn mapping_rejects_custom_annotations_that_only_share_a_standard_prefix() { - assert!(mapping("@GetMappingCustom(\"/x\")").is_none()); - assert!(mapping("@PostMappingCustom(\"/x\")").is_none()); - assert!(mapping("@PutMappingCustom(\"/x\")").is_none()); - assert!(mapping("@DeleteMappingCustom(\"/x\")").is_none()); - assert!(mapping("@PatchMappingCustom(\"/x\")").is_none()); - assert!(mapping("@RequestMappingFoo(\"/base\")").is_none()); - } - - #[test] - fn mapping_keeps_standard_annotations_and_request_method_arrays() { - let get = mapping("@GetMapping(\"/x\")").expect("GetMapping should match"); - assert_eq!(get.0, SpringMappingAnnotation::GetMapping); - assert_eq!(get.1, vec!["GET".to_string()]); - assert_eq!(get.2, vec!["/x".to_string()]); - - let post = mapping("@PostMapping(path = \"/y\")").expect("PostMapping should match"); - assert_eq!(post.1, vec!["POST".to_string()]); - assert_eq!(post.2, vec!["/y".to_string()]); - - let put = mapping("@PutMapping(\"/z\")").expect("PutMapping should match"); - assert_eq!(put.1, vec!["PUT".to_string()]); - - let delete = mapping("@DeleteMapping(\"/d\")").expect("DeleteMapping should match"); - assert_eq!(delete.1, vec!["DELETE".to_string()]); - - let patch = mapping("@PatchMapping(\"/p\")").expect("PatchMapping should match"); - assert_eq!(patch.1, vec!["PATCH".to_string()]); - - let any = mapping("@RequestMapping(\"/base\")").expect("RequestMapping should match"); - assert_eq!(any.0, SpringMappingAnnotation::RequestMapping); - assert_eq!(any.1, vec!["ANY".to_string()]); - assert_eq!(any.2, vec!["/base".to_string()]); - - let multi = mapping( - "@RequestMapping(path = \"/multi\", method = { RequestMethod.POST, RequestMethod.GET, RequestMethod.GET })", - ) - .expect("RequestMapping with methods should match"); - assert_eq!(multi.1, vec!["GET".to_string(), "POST".to_string()]); - assert_eq!(multi.2, vec!["/multi".to_string()]); - } - - #[test] - fn mapping_selects_the_earliest_annotation_and_isolates_its_routes() { - let selected = mapping("@GetMappingCustom(\"/decoy\") @PostMapping(\"/real\")") - .expect("exact PostMapping should still match"); - assert_eq!(selected.0, SpringMappingAnnotation::PostMapping); - assert_eq!(selected.1, vec!["POST".to_string()]); - assert_eq!(selected.2, vec!["/real".to_string()]); - - let leftmost = mapping("@PutMapping(\"/first\") @GetMapping(\"/second\")") - .expect("leftmost Mapping should win"); - assert_eq!(leftmost.0, SpringMappingAnnotation::PutMapping); - assert_eq!(leftmost.2, vec!["/first".to_string()]); - } - - #[test] - fn mapping_does_not_take_routes_from_a_following_unrelated_annotation() { - let bare = - mapping("@GetMapping @Custom(\"/decoy\")").expect("bare GetMapping should still match"); - assert_eq!(bare.0, SpringMappingAnnotation::GetMapping); - assert_eq!(bare.1, vec!["GET".to_string()]); - assert_eq!(bare.2, vec![String::new()]); - - let spaced = mapping("@GetMapping (\"/x\") @Custom(\"/decoy\")") - .expect("GetMapping with its own argument list should keep that route"); - assert_eq!(spaced.2, vec!["/x".to_string()]); - } - - fn temporary_repository_root(label: &str) -> PathBuf { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should be valid") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-core-spring-{label}-{}-{nonce}", - std::process::id() - )); - fs::create_dir_all(&root).expect("temporary repository should be creatable"); - root - } - - /// A large Maven workspace can have several index requests in flight. Only - /// one may walk the dependency repository; the others must observe its - /// snapshot instead of reopening every archive. - #[test] - fn concurrent_repository_readers_share_one_scan() { - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{mpsc, Arc}; - use std::thread; - - let root = temporary_repository_root("single-flight"); - let scans = Arc::new(AtomicUsize::new(0)); - let (scan_started, started) = mpsc::channel(); - let (release, released) = mpsc::channel::<()>(); - - let owner_root = root.clone(); - let owner_scans = Arc::clone(&scans); - let owner = thread::spawn(move || { - let _scope = crate::protocol::cancellation::Scope::begin(None, Some(5_000)); - repository_metadata_with(&owner_root, false, |_| { - owner_scans.fetch_add(1, Ordering::SeqCst); - scan_started.send(()).expect("scan start should notify"); - released - .recv_timeout(Duration::from_secs(5)) - .expect("scan release should arrive"); - Ok(vec![]) - }) - }); - started - .recv_timeout(Duration::from_secs(5)) - .expect("owner scan should start"); - - let waiter_root = root.clone(); - let waiter_scans = Arc::clone(&scans); - let waiter = thread::spawn(move || { - let _scope = crate::protocol::cancellation::Scope::begin(None, Some(5_000)); - repository_metadata_with(&waiter_root, false, |_| { - waiter_scans.fetch_add(1, Ordering::SeqCst); - Ok(vec![]) - }) - }); - // Release the owner only after the waiter has passed the cache lookup - // and holds the slot, so the waiter must join the running scan. - wait_for_slot_holders(&root, 4); - release.send(()).expect("owner scan should be releasable"); - - owner - .join() - .expect("owner thread should finish") - .expect("owner scan should succeed"); - waiter - .join() - .expect("waiter thread should finish") - .expect("waiter should reuse the owner snapshot"); - assert_eq!( - scans.load(Ordering::SeqCst), - 1, - "concurrent readers must not repeat the repository walk" - ); - - fs::remove_dir_all(root).expect("temporary repository should be removable"); - } - - /// Refreshes that arrive during the same walk share one follow-up scan, but - /// a refresh never accepts a snapshot from a walk that started before it. - #[test] - fn refresh_requests_accept_only_scans_started_after_they_arrived() { - let slot = RepositoryMetadataSlot { - state: Mutex::new(RepositoryMetadataState::Ready { - scan: 2, - properties: Arc::new(Vec::new()), - }), - ready: Condvar::new(), - }; - - assert!(matches!( - claim_repository_scan(&slot, true, 1) - .expect("a refresh that arrived before scan 2 should not wait"), - RepositoryClaim::Shared(_) - )); - assert!( - matches!( - claim_repository_scan(&slot, true, 2) - .expect("a refresh that arrived after scan 2 started should claim"), - RepositoryClaim::Owned(3) - ), - "a refresh must not reuse a walk that started before it" - ); - assert!(matches!( - *slot.state.lock().unwrap(), - RepositoryMetadataState::Scanning(3) - )); - } - - /// A refresh that lands while an ordinary scan is walking the repository - /// may miss archives downloaded before the refresh. It must wait for that - /// walk and then scan again instead of reusing its snapshot. - #[test] - fn a_refresh_during_a_running_scan_rescans_after_it() { - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::mpsc; - use std::thread; - - let root = temporary_repository_root("refresh-mid-scan"); - let (scan_started, started) = mpsc::channel(); - let (release, released) = mpsc::channel::<()>(); - - let owner_root = root.clone(); - let owner = thread::spawn(move || { - let _scope = crate::protocol::cancellation::Scope::begin(None, Some(5_000)); - repository_metadata_with(&owner_root, false, |_| { - scan_started.send(()).expect("scan start should notify"); - released - .recv_timeout(Duration::from_secs(5)) - .expect("scan release should arrive"); - Ok(vec![]) - }) - }); - started - .recv_timeout(Duration::from_secs(5)) - .expect("owner scan should start"); - - let refresh_root = root.clone(); - let refresh_scans = Arc::new(AtomicUsize::new(0)); - let counter = Arc::clone(&refresh_scans); - let refresher = thread::spawn(move || { - let _scope = crate::protocol::cancellation::Scope::begin(None, Some(5_000)); - repository_metadata_with(&refresh_root, true, |_| { - counter.fetch_add(1, Ordering::SeqCst); - Ok(vec![]) - }) - }); - wait_for_slot_holders(&root, 4); - release.send(()).expect("owner scan should be releasable"); - - owner - .join() - .expect("owner thread should finish") - .expect("owner scan should succeed"); - refresher - .join() - .expect("refresh thread should finish") - .expect("refresh scan should succeed"); - assert_eq!( - refresh_scans.load(Ordering::SeqCst), - 1, - "a refresh must not reuse a walk that started before it" - ); - - fs::remove_dir_all(root).expect("temporary repository should be removable"); - } - - /// Blocks until `holders` references to the repository slot exist: the - /// cache, the running owner, this test, and each request that joined it. - fn wait_for_slot_holders(root: &Path, holders: usize) { - let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - let slot = Arc::clone( - REPOSITORY_METADATA_CACHE - .get() - .expect("the owner should have created the cache") - .lock() - .unwrap() - .get(&key) - .expect("the owner should have created the slot"), - ); - let deadline = std::time::Instant::now() + Duration::from_secs(5); - while Arc::strong_count(&slot) < holders { - assert!( - std::time::Instant::now() < deadline, - "a second request should join the running scan" - ); - std::thread::yield_now(); - } - } - - /// A waiter belongs to one request. Cancelling that request must release - /// its worker instead of blocking until the owner finishes. - #[test] - fn a_cancelled_waiter_stops_waiting_for_the_repository_owner() { - let slot = RepositoryMetadataSlot { - state: Mutex::new(RepositoryMetadataState::Scanning(1)), - ready: Condvar::new(), - }; - let operation = "spring-repository-waiter-cancel"; - let _scope = crate::protocol::cancellation::Scope::begin(Some(operation.to_string()), None); - assert!(crate::protocol::cancellation::cancel(operation)); - - let error = claim_repository_scan(&slot, false, 1) - .expect_err("a cancelled waiter must stop waiting"); - assert!(matches!(error.code, ErrorCode::Cancelled)); - } - - /// Cancellation must reach the archive walk itself, not only the command - /// entry point, so a timed-out workspace scan releases its worker. - #[test] - fn a_cancelled_request_stops_before_walking_repository_archives() { - let root = temporary_repository_root("cancelled-scan"); - fs::write(root.join("dependency.jar"), b"not a zip archive") - .expect("archive fixture should be writable"); - let operation = "spring-repository-scan-cancel"; - let _scope = crate::protocol::cancellation::Scope::begin(Some(operation.to_string()), None); - assert!(crate::protocol::cancellation::cancel(operation)); - - assert!(matches!( - repository_metadata(&root, true) - .expect_err("a cancelled request must not scan") - .code, - ErrorCode::Cancelled - )); - assert!(matches!( - scan_repository_metadata(&root) - .expect_err("a cancelled scan must stop before reading archives") - .code, - ErrorCode::Cancelled - )); - - fs::remove_dir_all(root).expect("temporary repository should be removable"); - } -} diff --git a/rust/lithe-core/src/languages/text.rs b/rust/lithe-core/src/languages/text.rs deleted file mode 100644 index a725a3ee3d..0000000000 --- a/rust/lithe-core/src/languages/text.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Lossy text reading for Core's classification passes. - -use std::fs; -use std::io; -use std::path::Path; - -/// Reads a file as text, replacing bytes that are not valid UTF-8 with the -/// Unicode replacement character instead of failing. The markers Core scans -/// for (Spring Boot annotations, launch class names) are ASCII and survive -/// replacement, so a GBK-encoded source never fails a whole run-configuration -/// batch. The native file adapters remain the only byte-to-text converters for -/// documents; this lossy view never guesses a legacy charset and only backs -/// analysis, not editing. -pub fn read_text(path: &Path) -> io::Result { - fs::read(path).map(|bytes| String::from_utf8_lossy(&bytes).into_owned()) -} - -#[cfg(test)] -mod tests { - use super::read_text; - use std::fs; - use std::path::PathBuf; - - fn temp_dir(name: &str) -> PathBuf { - std::env::temp_dir().join(format!("lithe-text-{name}")) - } - - #[test] - fn passes_through_valid_utf8_without_change() { - let dir = temp_dir("utf8-test"); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("app.java"); - let source = "public class App {}\n"; - fs::write(&path, source).unwrap(); - assert_eq!(read_text(&path).unwrap(), source); - fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn replaces_invalid_utf8_bytes_instead_of_failing() { - // GBK bytes for a Chinese greeting are not valid UTF-8. The ASCII - // structure that classification depends on must survive. - let dir = temp_dir("gbk-test"); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("gbk.java"); - let gbk: &[u8] = - b"public class Gbk { public static void main(String[] args) { System.out.println(\"\xC4\xE3\xBA\xC3\"); } }"; - fs::write(&path, gbk).unwrap(); - let decoded = read_text(&path).unwrap(); - assert!(decoded.contains("public class Gbk")); - assert!(decoded.contains("main(String[] args)")); - fs::remove_dir_all(&dir).unwrap(); - } -} diff --git a/rust/lithe-core/src/lib.rs b/rust/lithe-core/src/lib.rs index 63052a4d3d..d3729d0afb 100644 --- a/rust/lithe-core/src/lib.rs +++ b/rust/lithe-core/src/lib.rs @@ -13,7 +13,6 @@ pub mod execution; mod git; mod github; mod keymap; -mod languages; mod lsp; mod mcp; mod network; diff --git a/rust/lithe-core/src/lsp/interface/client.rs b/rust/lithe-core/src/lsp/interface/client.rs index 9a83e40bf8..ae65cc3a17 100644 --- a/rust/lithe-core/src/lsp/interface/client.rs +++ b/rust/lithe-core/src/lsp/interface/client.rs @@ -291,13 +291,6 @@ pub(crate) fn client_feature_request_canonical( client_feature_request_with_document_ownership(request, true) } -/// Allocates a feature request for a provider-owned virtual document. -pub(crate) fn client_provider_document_feature_request_canonical( - request: ClientFeatureRequest, -) -> Result { - client_feature_request_with_document_ownership(request, false) -} - fn client_feature_request_with_document_ownership( request: ClientFeatureRequest, require_open_document: bool, @@ -1059,7 +1052,6 @@ fn validate_lsp_method(method: &str) -> Result<(), CoreError> { | "textDocument/codeAction" | "completionItem/resolve" | "codeAction/resolve" - | "java/findLinks" | "workspace/executeCommand" => Ok(()), _ => Err(CoreError::new( ErrorCode::NotSupported, @@ -1159,13 +1151,6 @@ fn feature_request_params(request: &ClientFeatureRequest) -> Result Ok(json!({ - "type": "superImplementation", - "position": { - "textDocument": text_document, - "position": lsp_position_json(required_position(request)?) - } - })), "codeAction/resolve" => request.code_action.clone().ok_or_else(|| { CoreError::new( ErrorCode::InvalidRequest, @@ -1385,7 +1370,6 @@ fn lsp_feature_result_for_method(method: Option<&str>, result: Option<&Value>) - | Some("textDocument/declaration") | Some("textDocument/typeDefinition") | Some("textDocument/implementation") - | Some("java/findLinks") | Some("textDocument/references") => Some(json!({ "locations": parse_locations(result) })), diff --git a/rust/lithe-core/src/lsp/interface/engine.rs b/rust/lithe-core/src/lsp/interface/engine.rs index 0c08036115..cf59bb4891 100644 --- a/rust/lithe-core/src/lsp/interface/engine.rs +++ b/rust/lithe-core/src/lsp/interface/engine.rs @@ -11,46 +11,16 @@ 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, - client_open_document, client_provider_document_feature_request_canonical, client_shutdown, - frame_message, parse_server_messages, ClientChangeDocumentRequest, ClientCloseDocumentRequest, - ClientFeatureRequest, ClientInitializeRequest, ClientOpenDocumentRequest, - ClientShutdownRequest, FrameMessageRequest, LspClientDiagnostic, LspClientDocument, - LspClientState, LspDocumentContentChange, LspPosition, LspRange, ParseServerMessagesRequest, + client_open_document, client_shutdown, frame_message, parse_server_messages, + ClientChangeDocumentRequest, ClientCloseDocumentRequest, ClientFeatureRequest, + ClientInitializeRequest, ClientOpenDocumentRequest, ClientShutdownRequest, FrameMessageRequest, + LspClientDiagnostic, LspClientDocument, LspClientState, LspDocumentContentChange, LspPosition, + LspRange, ParseServerMessagesRequest, }; use crate::diagnostics::plugin_operations::{ self as plugin_operations, Attempt, AttemptHandoff, AttemptSlot, Stage as AttemptStage, LANGUAGE_SERVER_START, }; -use crate::lsp::languages::java_entrypoints::{ - java_entrypoints_command, normalize_java_entrypoints, -}; -use crate::lsp::languages::java_launch::{ - JavaLaunchAction, JavaLaunchFailure, JavaLaunchPreparation, -}; -use crate::lsp::languages::java_main_methods::{ - java_main_methods_command, normalize_java_main_methods, -}; -use crate::lsp::languages::java_tests::{java_test_items_command, normalize_java_test_items}; -use crate::lsp::languages::jdt::{ - adapt_initialization_options, adapt_start, import_progress, initialized_notification, - is_structured_import_notification, is_virtual_source_uri, jdt_java_runtimes, - maven_profile_fingerprint, maven_profile_update_requests, normalize_location, - project_update_notification, readiness_signal, settings_notification, virtual_source_content, - virtual_source_resolve_params, waits_for_service_ready, workspace_configuration, - JdtDirectLaunchResources, JdtGradleConfiguration, JdtJavaRuntime, JdtMavenConfiguration, - JdtReadinessSignal, JdtSettings, JdtStartContext, ProviderLocation, WorkspaceConfigurationItem, -}; -use crate::lsp::languages::jdt::{MavenProfileProjectResult, MavenProfileTaskStatus}; -use crate::lsp::languages::jdt_build::{ - is_java_build_command, java_build_failure, java_build_outcome, java_build_report, - project_job_progress, JavaBuildCoordinator, JavaBuildDeparture, JavaBuildDispatch, - JavaBuildReport, DEFAULT_JAVA_BUILD_TIMEOUT_MS, -}; -#[cfg(test)] -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, @@ -58,7 +28,6 @@ use crate::plugins::language_server_sessions::{ use crate::protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::Read; use std::path::{Path, PathBuf}; @@ -68,8 +37,6 @@ use std::thread; use std::time::{Duration, Instant}; const DEFAULT_INITIALIZE_TIMEOUT_MS: u64 = 10_000; -const DEFAULT_SERVICE_READY_IDLE_TIMEOUT_MS: u64 = 45_000; -const DEFAULT_SERVICE_READY_ABSOLUTE_TIMEOUT_MS: u64 = 10 * 60_000; const DEFAULT_REQUEST_TIMEOUT_MS: u64 = 30_000; const DEFAULT_SHUTDOWN_TIMEOUT_MS: u64 = 2_000; /// Upper bound of one build-provider request. A model request can load a @@ -87,8 +54,6 @@ const MAX_KEYMAP_IMPORT_TIMEOUT_MS: u64 = 60_000; const MONITOR_INTERVAL_MS: u64 = 10; /// Shared plugin diagnostic budget per process session and monotonic minute. const MAX_PLUGIN_DIAGNOSTICS_PER_MINUTE: u16 = 600; -/// JSON-RPC method carrying Java Debug Server build commands. -const JAVA_BUILD_METHOD: &str = "workspace/executeCommand"; static ENGINE: OnceLock = OnceLock::new(); @@ -173,87 +138,14 @@ pub struct StartServerRequest { /// `workspaceConfiguration` template. Must be an object when present. #[serde(default)] pub workspace_configuration: Option, - #[serde(default)] - pub runtime_executable_path: Option, - /// Files discovered by the platform adapter for shell-free JDT LS startup. - #[serde(default)] - pub jdtls_launch_resources: Option, - #[serde(default)] - pub cache_directory: Option, - /// Platform-computed digest of the workspace's build-system structure. - /// Providers that keep durable per-workspace state (JDT LS) mix this into - /// their state-directory name so a structurally changed workspace does not - /// reuse a stale project model. See `JdtStartContext::workspace_fingerprint`. - #[serde(default)] - pub workspace_fingerprint: Option, - /// Project Maven context applied to JDT LS settings and imported modules. - #[serde(default)] - pub maven_context: Option, - /// JDKs the platform found on this machine, most preferred first. JDT LS - /// binds each project to the one matching its release; without them it - /// can only compile for the JDK it runs on. - #[serde(default)] - pub java_runtimes: Vec, - /// Gradle import context the platform adapter detected at the workspace - /// root. `None` for workspaces that are not Gradle projects, so Maven-only - /// workspaces never receive `java.import` settings. - #[serde(default)] - pub java_gradle: Option, #[serde(default = "default_initialize_timeout")] pub initialize_timeout_milliseconds: u64, - /// Quiet-progress warning threshold while waiting for provider readiness. - /// The historical wire name is retained; only the absolute cap terminates import. - #[serde(default = "default_service_ready_idle_timeout")] - pub service_ready_idle_timeout_milliseconds: u64, - /// Absolute safety cap for provider-specific preparation even while active. - #[serde(default = "default_service_ready_absolute_timeout")] - pub service_ready_absolute_timeout_milliseconds: u64, #[serde(default = "default_request_timeout")] pub request_timeout_milliseconds: u64, - /// Bound for one Java project build requested through - /// `vscode.java.buildWorkspace`, including the wait for project - /// configuration and earlier builds. Ordinary requests keep - /// `request_timeout_milliseconds`. - #[serde(default = "default_java_build_timeout")] - pub java_build_timeout_milliseconds: u64, #[serde(default = "default_shutdown_timeout")] pub shutdown_timeout_milliseconds: u64, } -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Platform-resolved files that let Rust launch JDT LS with bundled Java. -pub struct JdtlsLaunchResources { - /// Equinox launcher selected deterministically from the JDT LS installation. - pub launcher_jar_path: String, - /// OS-specific Eclipse configuration directory for the current product. - pub configuration_directory: String, - /// Lombok agent shipped with the selected JDT LS installation. - pub lombok_agent_path: String, - /// Legacy Java Debug Server bundle retained for older platform clients. - #[serde(default)] - pub java_debug_bundle_path: Option, - /// Ordered Java extension bundles loaded through JDT LS initialization. - /// - /// When the legacy Debug field is also present, Core loads it first and - /// removes duplicate paths while preserving the remaining caller order. - #[serde(default)] - pub java_extension_bundle_paths: Vec, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// A JDK installation the platform discovered for the Java language service. -pub struct JavaRuntimeCandidate { - /// The platform-selected project JDK, independent of the server JVM. - #[serde(default)] - pub is_default: bool, - /// JDK home directory. - pub home_path: String, - /// Version reported by `java -version`, such as `25.0.4` or `1.8.0_402`. - pub version: String, -} - #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] /// Identity and initial lifecycle state of a newly created session. @@ -332,34 +224,6 @@ pub enum WorkspaceFileChangeKind { Deleted, } -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Requests semantic Java navigation markers for one synchronized document. -pub struct JavaNavigationMarkersRequest { - pub session_id: String, - #[serde(default)] - pub operation_id: Option, - pub uri: String, - #[serde(default)] - pub document_version: Option, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Resolves one previously published Java marker at click time. -pub struct JavaResolveNavigationRequest { - pub session_id: String, - #[serde(default)] - pub operation_id: Option, - pub uri: String, - pub line: i64, - pub utf16_column: i64, - pub direction: String, - pub relation: String, - #[serde(default)] - pub document_version: Option, -} - #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] /// Request to remove a document from a session's synchronized state. @@ -386,8 +250,6 @@ pub enum LspSemanticOperation { References, /// `textDocument/implementation`. Implementation, - /// JDT LS `java/findLinks` with the `superImplementation` relation. - JavaSuperImplementation, /// `textDocument/rename`. Rename, /// `textDocument/formatting`. @@ -408,17 +270,6 @@ pub enum LspSemanticOperation { SemanticTokens, /// `textDocument/codeLens`. CodeLens, - /// Provider-specific retrieval of a read-only virtual document. - VirtualDocument, - /// JDT discovery of launchable Java classes in the session workspace, - /// normalized into workspace-relative entry points. - JavaEntrypoints, - /// Java Test extension discovery for one source file, normalized into - /// typed class and method items. - JavaTestItems, - /// JDT discovery of launchable `main` methods in one source file, - /// normalized with the source range of each method name. - JavaMainMethods, } #[derive(Debug, Clone, Deserialize)] @@ -432,8 +283,6 @@ pub struct SemanticRequest { #[serde(default)] pub uri: Option, #[serde(default)] - pub virtual_uri: Option, - #[serde(default)] pub position: Option, #[serde(default)] pub new_name: Option, @@ -452,20 +301,6 @@ pub struct SemanticRequest { pub command: Option, } -/// One saved Java source to prepare through the owning JDT session. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct JavaPrepareLaunchRequest { - pub session_id: String, - #[serde(default)] - pub operation_id: Option, - /// Absolute native path used only for the upstream build request. - pub source_path: String, - /// Optional persisted selector to disambiguate multiple mains in one source. - #[serde(default)] - pub main_class: Option, -} - #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] /// One build-provider request, forwarded as `build.modelPlan` or @@ -707,8 +542,6 @@ pub struct CancelOperationRequest { /// Ordered events drained from a session since the previous poll. pub struct PollEventsResponse { pub events: Vec, - /// Current Java preparation projection, including when the event queue was already drained. - pub project_preparation: Option, } #[derive(Debug, Clone, Deserialize)] @@ -779,11 +612,6 @@ pub struct LspRuntimeEvent { pub message: Option, #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub maven_profile_project: Option, - /// Structured aggregate state for the Maven profile task. - #[serde(skip_serializing_if = "Option::is_none")] - pub maven_profile_task: Option, } #[derive(Debug, Clone, Serialize)] @@ -813,10 +641,6 @@ pub struct LspRuntimeError { pub underlying_message: Option, #[serde(skip_serializing_if = "Option::is_none")] pub process_exit_code: Option, - /// Evidence behind an unsuccessful Java launch build. Present only for - /// `javaBuild` failures; hosts that do not read it are unaffected. - #[serde(skip_serializing_if = "Option::is_none")] - pub java_build_report: Option, /// Plugin-defined code of a failed plugin function (`error.data.code`), /// passed through for the plugin's own UI; Lithe never branches on it. #[serde(skip_serializing_if = "Option::is_none")] @@ -852,25 +676,6 @@ enum PendingKind { Initialize, /// Ordinary semantic feature whose result becomes an operation event. Feature, - /// Provider-specific source retrieval normalized as a virtual document. - VirtualDocument, - /// Java Debug Server main-class discovery normalized as entry points. - JavaEntrypoints, - /// Java Test extension file discovery normalized as typed test items. - JavaTestItems, - /// Java Debug Server per-file `main` discovery normalized as main methods. - JavaMainMethods, - /// CodeLens-derived Java gutter marker projection. - JavaNavigationMarkers, - /// One JDT LS CodeLens resolve step in a bounded marker batch. - JavaNavigationMarkerResolve, - /// Click-time Java parent or implementation resolution. - JavaResolveNavigation, - /// JDT LS project setting update that applies selected Maven profiles. - JdtMavenProfiles, - /// 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, @@ -890,23 +695,6 @@ struct PendingRequest { deadline: Instant, } -/// Launch discovery delayed until the same project-configuration gate as builds. -/// No JSON-RPC request exists until dispatch, so cancellation writes nothing. -struct JavaEntrypointWaiter { - operation_id: String, - created_at: Instant, - deadline: Instant, -} - -/// Latest completed marker projection for one synchronized document. -/// -/// Only one version per URI is retained. This bounds memory while preventing -/// view refreshes from repeating the same multi-request JDT LS batch. -struct JavaNavigationMarkerCacheEntry { - document_version: i64, - markers: Vec, -} - /// Links one host operation to the exact backend request and function it owns. struct PendingFunctionCall { function_id: String, @@ -915,7 +703,6 @@ struct PendingFunctionCall { } struct SessionState { - preparation_snapshot: Option, lifecycle: LspLifecycleState, client: LspClientState, pending: BTreeMap, @@ -926,46 +713,16 @@ struct SessionState { /// Symbolic-link facts about the open documents, rebuilt lazily from /// `client.open_documents`. linked_document_paths: LinkedDocumentPaths, - java_navigation_marker_batches: BTreeMap, - java_navigation_marker_cache: BTreeMap, /// Latest workspace event per URI observed before protocol initialization. /// The engine owns and drains this queue exactly once after `initialized`. pending_workspace_file_changes: BTreeMap, events: VecDeque, next_sequence: u64, initialize_deadline: Option, - service_ready_idle_timeout: Duration, - service_ready_absolute_timeout: Duration, - java_preparation: Option, shutdown_deadline: Option, request_timeout: Duration, shutdown_timeout: Duration, terminal_event_emitted: bool, - maven_profile_status: MavenProfileTaskStatus, - maven_profile_results: BTreeMap, - maven_profile_queue: VecDeque, - maven_profile_deadline: Option, - maven_profile_applied_fingerprint: Option, - /// Fingerprint of the configuration the running profile task applies. A - /// configuration replaced while the task runs is applied by a follow-up - /// task instead of being recorded as applied. - maven_profile_running_fingerprint: Option, - /// A newer profile selection waiting for the previous batch to drain. - maven_profile_update_pending: bool, - /// Explicit reload retained until JDT LS has imported its projects. - maven_project_reload_pending: bool, - // Request IDs retain their owning task generation until a terminal response - // arrives, including responses to advisory cancellation after a timeout. - maven_profile_generation: u64, - maven_profile_request_generations: BTreeMap, - /// Serialized, configuration-gated `vscode.java.buildWorkspace` calls. - java_builds: JavaBuildCoordinator, - java_entrypoint_waiters: VecDeque, - /// Launch attempts share their operation ID across discovery, build and classpath. - java_launches: BTreeMap, - /// Already allocated classpath requests; the bounded writer sends only live ones. - java_launch_messages: Vec<(String, Vec)>, - java_build_timeout: Duration, /// Deadline cancellations awaiting the outbound worker, never written by the monitor. deadline_cancellations: Vec, /// Bounds an outbound maintenance write independently of caller deadlines. @@ -1001,32 +758,12 @@ struct RuntimeSession { log_identity: SessionLogIdentity, /// Fixed workspace host, inherited by protocol workers; never a global selection. workspace_host: Option, - /// Maven import settings JDT LS currently holds. Replaced as a whole when - /// the workspace's Maven configuration changes; never held across another - /// lock. - jdt_maven_configuration: Mutex>>, - /// Inputs for rebuilding `jdt_maven_configuration`; `None` when the session - /// started without a Maven context. - maven_inputs: Option, - /// Serializes configuration preparation and publication without blocking - /// protocol processing on filesystem I/O. Never acquired by protocol workers. - maven_update_order: Mutex<()>, /// Plugin-declared settings answered to `workspace/configuration`. /// Replaced as a whole by `lsp.updateWorkspaceConfiguration`; never held /// across another lock. plugin_configuration: Mutex>>, - /// JDKs JDT LS may bind projects to, one per execution environment. - jdt_java_runtimes: Vec, - /// Plugin completion options fixed at initialize, retained for later Java - /// configuration notifications and section pulls through the same adapter. - jdt_completion: Option, - /// Immutable plugin input retained when workspace exclusions change or are removed. - jdt_import_exclusions: Option, - /// Gradle import settings JDT LS holds. Fixed for the session's lifetime - /// because the wrapper is a property of the workspace root at startup. - jdt_gradle_configuration: Option, - /// Workspace URI the server was initialized with; scopes workspace-wide - /// queries such as Java entry-point discovery. + /// Workspace URI the server was initialized with; scopes indexing + /// exclusions and other workspace-wide checks to this session's root. root_uri: String, /// Serializes policy eligibility with document/file-event publication and /// policy withdrawal. Acquire before outbound_order; Git scans stay outside @@ -1065,22 +802,10 @@ fn default_initialize_timeout() -> u64 { DEFAULT_INITIALIZE_TIMEOUT_MS } -fn default_service_ready_idle_timeout() -> u64 { - DEFAULT_SERVICE_READY_IDLE_TIMEOUT_MS -} - -fn default_service_ready_absolute_timeout() -> u64 { - DEFAULT_SERVICE_READY_ABSOLUTE_TIMEOUT_MS -} - fn default_request_timeout() -> u64 { DEFAULT_REQUEST_TIMEOUT_MS } -fn default_java_build_timeout() -> u64 { - DEFAULT_JAVA_BUILD_TIMEOUT_MS -} - fn default_shutdown_timeout() -> u64 { DEFAULT_SHUTDOWN_TIMEOUT_MS } @@ -1250,16 +975,10 @@ fn apply_indexing_to_sessions( .remove(&uri); } } - if session.provider_id == "java" { - let order = session.lock_outbound_order()?; - if session.lock_state()?.client.initialized { - let maven = session.maven_configuration(); - let notification = settings_notification(session.jdt_settings(maven.as_deref())); - let message = serde_json::to_string(&json!({"jsonrpc":"2.0", "method":notification.method, "params":notification.params})).map_err(|error| CoreError::new(ErrorCode::Unknown, error.to_string()))?; - session.send_messages_or_fail(&order, vec![message], "indexingChanged")?; - } - } - if session.provider_id != "java" { + // Exclusions are folded into the configuration answered through + // `workspace/configuration`, so an initialized server is told to pull + // the changed sections again instead of keeping its old import scope. + { let order = session.lock_outbound_order()?; if session.lock_state()?.client.initialized { if let Some(configuration) = session.plugin_configuration() { @@ -1295,55 +1014,6 @@ pub fn stop_server(request: SessionRequest) -> Result<(), CoreError> { engine().session(&request.session_id)?.stop() } -/// Retries the selected Maven profile application without restarting JDTLS. -pub fn retry_maven_profiles(request: SessionRequest) -> Result<(), CoreError> { - let session = engine().session(&request.session_id)?; - session.retry_maven_profiles() -} - -/// Replaces the Maven configuration of a running Java session. -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct UpdateMavenConfigurationRequest { - pub session_id: String, - /// The workspace's current Maven context, as a Maven launch would use it. - pub maven_context: crate::project::MavenLaunchContextRequest, - /// Force JDT LS to re-resolve every Maven project even when the settings - /// themselves did not change. Set by the explicit reload action. - #[serde(default)] - pub reload_projects: bool, -} - -/// What an update asked JDT LS to do. Each step runs asynchronously inside -/// JDT LS; resolution problems arrive later as `pom.xml` diagnostics. -#[derive(Debug, Serialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct UpdateMavenConfigurationResponse { - /// New settings documents were sent; JDT LS re-imports every Maven - /// project because of them. - pub settings_changed: bool, - /// Settings were unchanged, so a forced project update was requested. - pub projects_reloaded: bool, - /// Profile application was started for changed profiles. - pub profiles_updating: bool, -} - -/// Sends a changed Maven configuration to a running Java session. -/// -/// JDT LS receives the change through its own mechanisms instead of a restart: -/// changed settings documents through `workspace/didChangeConfiguration`, -/// which makes it force-update every Maven project, and an explicit reload -/// through `java/projectConfigurationsUpdate`. A restart reuses the workspace -/// state and skips projects whose `pom.xml` did not change, so artifacts that -/// failed to resolve under the old settings would stay missing. -pub fn update_maven_configuration( - request: UpdateMavenConfigurationRequest, -) -> Result { - engine() - .session(&request.session_id)? - .update_maven_configuration(request.maven_context, request.reload_projects) -} - impl RuntimeSession { /// Plugin configuration the server currently sees, if any. fn plugin_configuration(&self) -> Option> { @@ -1405,184 +1075,6 @@ impl RuntimeSession { self.send_messages_or_fail(&outbound_order, messages, "workspaceConfigurationUpdate")?; Ok(UpdateWorkspaceConfigurationResponse { sent: initialized }) } - - /// The Maven import settings JDT LS currently holds. - fn maven_configuration(&self) -> Option> { - self.jdt_maven_configuration - .lock() - .map(|configuration| configuration.clone()) - .unwrap_or_else(|poisoned| poisoned.into_inner().clone()) - } - - /// Java settings Lithe owns for this session, as sent to JDT LS. - fn jdt_settings<'a>(&'a self, maven: Option<&'a JdtMavenConfiguration>) -> JdtSettings<'a> { - JdtSettings { - indexing_root_uri: Some(&self.root_uri), - completion: self.jdt_completion.as_ref(), - import_exclusions: self.jdt_import_exclusions.as_ref(), - maven, - gradle: self.jdt_gradle_configuration.as_ref(), - java_runtimes: &self.jdt_java_runtimes, - } - } - - fn update_maven_configuration( - &self, - context: crate::project::MavenLaunchContextRequest, - reload_projects: bool, - ) -> Result { - let Some(inputs) = self - .maven_inputs - .as_ref() - .filter(|_| self.provider_id == "java") - else { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Maven configuration updates require a Java language session started for a Maven project.", - )); - }; - let _update_order = self.maven_update_order.lock().map_err(|_| { - CoreError::new( - ErrorCode::InvalidRequest, - "Maven configuration update lock failed.", - ) - })?; - // Disk I/O holds only the update serializer, never a protocol/state lock. - let (next, warnings) = inputs.configuration(context)?; - let next = Arc::new(next); - - let outbound_order = self.lock_outbound_order()?; - let (initialized, ready) = { - let state = self.lock_state()?; - if matches!( - state.lifecycle, - LspLifecycleState::Stopping - | LspLifecycleState::Stopped - | LspLifecycleState::Failed - ) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The Java language session is no longer running.", - )); - } - // Under `outbound_order`, an initialized client has already sent - // the `initialized` settings notification. Before that point the - // pending notification reads the configuration stored below. - ( - state.client.initialized, - state.lifecycle == LspLifecycleState::Ready, - ) - }; - let previous = { - let mut current = self - .jdt_maven_configuration - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - current.replace(next.clone()) - }; - let settings_changed = previous.as_ref().is_none_or(|previous| { - previous.settings_path != next.settings_path - || previous.global_settings_path != next.global_settings_path - }); - let profiles_changed = previous - .as_ref() - .is_none_or(|previous| previous.profiles != next.profiles); - - { - let mut state = self.lock_state()?; - state.maven_profile_update_pending |= profiles_changed; - state.maven_project_reload_pending |= reload_projects && !ready; - } - let mut messages = Vec::new(); - let mut projects_reloaded = false; - if initialized { - let notification = if settings_changed { - Some(settings_notification(self.jdt_settings(Some(&next)))) - } else if reload_projects && ready { - projects_reloaded = true; - project_update_notification(&next) - } else { - None - }; - if let Some(notification) = notification { - messages.push( - json!({ - "jsonrpc": "2.0", - "method": notification.method, - "params": notification.params - }) - .to_string(), - ); - } - } - // Before readiness, the profile task starts with the stored - // configuration once the import publishes `ServiceReady`. - let mut profiles_updating = false; - if ready && profiles_changed { - let (requests, pending) = self.maven_profile_requests()?; - messages.extend(requests); - profiles_updating = pending; - } - self.send_messages_or_fail(&outbound_order, messages, "mavenConfigurationUpdate")?; - drop(outbound_order); - - for detail in warnings { - self.log_issue( - "warn", - "mavenSettings", - "mavenSettingsUnchanged", - EngineLog::MavenSettingsForwarded, - "Maven settings were passed to the Java language service unchanged", - Some(detail), - ); - } - let response = UpdateMavenConfigurationResponse { - settings_changed: initialized && settings_changed, - projects_reloaded, - profiles_updating, - }; - self.log( - "info", - EngineLog::MavenConfigurationUpdated.with_fields(json!(response)), - "Java language service received the updated Maven configuration", - Some(json!(response).to_string()), - ); - Ok(response) - } - - fn retry_maven_profiles(&self) -> Result<(), CoreError> { - let outbound_order = self.lock_outbound_order()?; - let state = self.lock_state()?; - if self.provider_id != "java" || state.lifecycle != LspLifecycleState::Ready { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Maven profile retry requires a ready Java language session.", - )); - } - if state.maven_profile_status == MavenProfileTaskStatus::Running { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Maven profile application is already running.", - )); - } - if state - .pending - .values() - .any(|pending| pending.kind == PendingKind::JdtMavenProfiles) - { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Previous Maven requests are still stopping. Retry after they finish, or restart the Java language session.", - )); - } - drop(state); - self.lock_state()?.maven_profile_applied_fingerprint = None; - let (messages, pending) = self.maven_profile_requests()?; - if pending { - self.send_messages_or_fail(&outbound_order, messages, "mavenProfileRetry")?; - } - Ok(()) - } } /// Opens or replaces the synchronized contents of one document. @@ -1608,96 +1100,6 @@ pub fn workspace_files_changed(request: WorkspaceFilesChangedRequest) -> Result< .workspace_files_changed(request.changes) } -/// Queues one shared Java gutter marker request against the active LSP session. -pub fn java_navigation_markers( - request: JavaNavigationMarkersRequest, -) -> Result { - let operation_id = request - .operation_id - .clone() - .unwrap_or_else(|| engine().next_operation_id()); - let session = engine().session(&request.session_id)?; - if session.complete_cached_java_navigation_markers( - &operation_id, - &request.uri, - request.document_version, - )? { - return Ok(OperationResponse { operation_id }); - } - session.request_with_kind( - SemanticRequest { - session_id: request.session_id, - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, - uri: Some(request.uri), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - request.document_version, - )?; - Ok(OperationResponse { operation_id }) -} - -/// Queues one click-time Java parent or implementation lookup. -pub fn java_resolve_navigation( - request: JavaResolveNavigationRequest, -) -> Result { - let operation_id = request - .operation_id - .clone() - .unwrap_or_else(|| engine().next_operation_id()); - let operation = match request.direction.as_str() { - "down" => LspSemanticOperation::Implementation, - "up" => LspSemanticOperation::JavaSuperImplementation, - _ => { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java navigation direction must be up or down.", - )) - } - }; - if !matches!(request.relation.as_str(), "interface" | "inheritance") { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java navigation relation must be interface or inheritance.", - )); - } - let session = engine().session(&request.session_id)?; - session.request_with_kind( - SemanticRequest { - session_id: request.session_id, - operation_id: Some(operation_id.clone()), - operation, - uri: Some(request.uri), - virtual_uri: None, - position: Some(LspPosition { - line: request.line, - utf16_column: request.utf16_column, - }), - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaResolveNavigation, - request.document_version, - )?; - Ok(OperationResponse { operation_id }) -} - /// Notifies the server that a synchronized document has closed. pub fn close_document(request: CloseDocumentRequest) -> Result<(), CoreError> { engine() @@ -1717,20 +1119,6 @@ pub fn semantic_request(request: SemanticRequest) -> Result Result { - let operation_id = request - .operation_id - .clone() - .unwrap_or_else(|| engine().next_operation_id()); - engine() - .session(&request.session_id)? - .prepare_java_launch(request, operation_id.clone())?; - Ok(OperationResponse { operation_id }) -} - /// Sends one build-provider request to a session that negotiated the protocol. pub fn build_provider_request( request: BuildProviderRequest, @@ -1874,32 +1262,16 @@ pub fn set_detailed_diagnostics(request: SetDetailedDiagnosticsRequest) -> Resul /// Drains all currently queued events in deterministic sequence order. pub fn poll_events(request: SessionRequest) -> Result { - let session = engine().session(&request.session_id)?; - let events = session.poll_events()?; - let project_preparation = session - .lock_state()? - .preparation_snapshot - .as_ref() - .map(|snapshot| json!(snapshot)); - Ok(PollEventsResponse { - events, - project_preparation, - }) + let events = engine().session(&request.session_id)?.poll_events()?; + Ok(PollEventsResponse { events }) } /// Waits until queued events exist or the supplied timeout elapses. pub fn wait_events(request: WaitEventsRequest) -> Result { - let session = engine().session(&request.session_id)?; - let events = session.wait_events(Duration::from_millis(request.timeout_milliseconds))?; - let project_preparation = session - .lock_state()? - .preparation_snapshot - .as_ref() - .map(|snapshot| json!(snapshot)); - Ok(PollEventsResponse { - events, - project_preparation, - }) + let events = engine() + .session(&request.session_id)? + .wait_events(Duration::from_millis(request.timeout_milliseconds))?; + Ok(PollEventsResponse { events }) } /// Stops a session if necessary and removes all state owned by it. @@ -1911,70 +1283,6 @@ fn engine() -> &'static LspEngine { ENGINE.get_or_init(LspEngine::new) } -/// Inputs a Java session keeps so it can rebuild its Maven import settings -/// when the workspace's Maven configuration changes after startup. -#[derive(Debug)] -struct SessionMavenInputs { - workspace_root: PathBuf, - /// Content-addressed settings copies inside this session's `-data` directory. - settings_directory: Option, - /// Maven's default user settings, used when none are configured. - default_user_settings: Option, -} - -impl SessionMavenInputs { - /// Validates `context` and produces the settings JDT LS receives, plus - /// warnings for documents that degraded to their original paths. - fn configuration( - &self, - context: crate::project::MavenLaunchContextRequest, - ) -> Result<(JdtMavenConfiguration, Vec), CoreError> { - let working_directory = self.workspace_root.to_string_lossy().into_owned(); - let configuration = crate::project::jdt_configuration(&working_directory, context)?; - let project_uris = configuration - .project_paths - .iter() - .map(|path| { - let directory = if path == "." { - self.workspace_root.clone() - } else { - self.workspace_root.join(path) - }; - url::Url::from_directory_path(directory) - .map(|url| url.to_string()) - .map_err(|_| { - CoreError::new( - ErrorCode::InvalidRequest, - "Maven project path cannot be represented as a URI", - ) - }) - }) - .collect::, _>>()?; - let materialized = match &self.settings_directory { - Some(directory) => crate::lsp::languages::jdt_maven_settings::materialize( - directory, - &configuration, - self.default_user_settings.as_deref(), - )?, - None => crate::lsp::languages::jdt_maven_settings::MaterializedMavenSettings { - user_settings_path: configuration.settings_path.clone(), - global_settings_path: configuration.global_settings_path.clone(), - warnings: Vec::new(), - }, - }; - Ok(( - JdtMavenConfiguration { - settings_path: materialized.user_settings_path, - global_settings_path: materialized.global_settings_path, - profiles: configuration.profiles, - project_uris, - source_paths: configuration.source_paths, - }, - materialized.warnings, - )) - } -} - impl LspEngine { fn new() -> Self { Self::with_launcher(Arc::new(SystemProcessLauncher)) @@ -2073,13 +1381,6 @@ impl LspEngine { ) -> Result { validate_start_request(&request)?; self.cleanup_failed_start()?; - if crate::remote::workspace::is_remote() && request.provider_id.eq_ignore_ascii_case("java") - { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Remote Java language servers require a host-compatible plugin launch plan", - )); - } if crate::remote::workspace::is_remote() && request .session_policy @@ -2113,144 +1414,14 @@ impl LspEngine { } Ok(()) }; - let startup_started_at = Instant::now(); let session_id = format!( "lsp-session-{}", self.next_session_id.fetch_add(1, Ordering::Relaxed) ); let workspace_root = PathBuf::from(&request.working_directory); - // Resolved before the Maven context because an overridden local - // repository is delivered to JDT LS as a settings document written here. - let data_root = request - .cache_directory - .as_deref() - .map(PathBuf::from) - .unwrap_or_else(|| std::env::temp_dir().join("lithe-lsp")); - let selected_java_executable = request - .runtime_executable_path - .as_deref() - .map(PathBuf::from) - .or_else(|| java_executable_from_environment(&request.environment)); - let java_extension_bundle_paths = request - .jdtls_launch_resources - .as_ref() - .map(|resources| { - let mut paths = Vec::new(); - if let Some(path) = &resources.java_debug_bundle_path { - paths.push(PathBuf::from(path)); - } - for path in &resources.java_extension_bundle_paths { - let path = PathBuf::from(path); - if !paths.contains(&path) { - paths.push(path); - } - } - paths - }) - .unwrap_or_default(); - // The packaged configuration directory belongs to the installed - // product and must stay byte-identical; Equinox receives a writable - // copy in the host cache instead. - let configuration_area = request - .jdtls_launch_resources - .as_ref() - .map(|resources| { - prepare_jdt_configuration_area( - &data_root, - Path::new(&resources.configuration_directory), - unix_seconds_now(), - ) - }) - .transpose()?; - let adaptation = adapt_start(&JdtStartContext { - provider_id: request.provider_id.clone(), - workspace_root: workspace_root.clone(), - data_root, - selected_java_executable, - direct_launch_resources: request - .jdtls_launch_resources - .as_ref() - .zip(configuration_area.as_ref()) - .map(|(resources, configuration_area)| JdtDirectLaunchResources { - launcher_jar_path: PathBuf::from(&resources.launcher_jar_path), - configuration_directory: configuration_area.directory.clone(), - lombok_agent_path: PathBuf::from(&resources.lombok_agent_path), - java_debug_bundle_path: resources - .java_debug_bundle_path - .as_deref() - .map(PathBuf::from), - }), - arguments: request.arguments.clone(), - workspace_fingerprint: request.workspace_fingerprint.clone(), - }); - // Runs before the cache disposition is read: a reset state directory is - // reported as `new`, which is what the following import will be. - let legacy_metadata_cleanup = adaptation - .data_directory - .as_ref() - .map(|directory| prepare_jdt_workspace(&workspace_root, directory)) - .transpose()? - .filter(|cleanup| !cleanup.removed_files.is_empty()); - let java_cache_disposition = adaptation.data_directory.as_ref().map(|directory| { - if directory.join(".metadata").is_dir() { - "reused" - } else { - "new" - } - }); - if let Some(directory) = &adaptation.data_directory { - std::fs::create_dir_all(directory).map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not create the language-server state directory.", - ) - .with_details(error.to_string()) - })?; - } - // Built after the state directory exists and after any reset of it, - // because the settings copies JDT LS reads live inside that directory. - let maven_inputs = request.maven_context.as_ref().map(|_| SessionMavenInputs { - workspace_root: workspace_root.clone(), - settings_directory: adaptation - .data_directory - .as_deref() - .map(crate::lsp::languages::jdt_maven_settings::settings_directory), - default_user_settings: - crate::lsp::languages::jdt_maven_settings::default_user_settings_path( - &request.environment, - ), - }); - let mut maven_settings_warnings = Vec::new(); - let jdt_maven_configuration = match (&maven_inputs, request.maven_context.clone()) { - (Some(inputs), Some(context)) => { - let (configuration, warnings) = inputs.configuration(context)?; - maven_settings_warnings = warnings; - Some(Arc::new(configuration)) - } - _ => None, - }; - let initialize_timeout = Duration::from_millis(request.initialize_timeout_milliseconds); - let service_ready_idle_timeout = - Duration::from_millis(request.service_ready_idle_timeout_milliseconds); - let service_ready_absolute_timeout = - Duration::from_millis(request.service_ready_absolute_timeout_milliseconds); let request_timeout = Duration::from_millis(request.request_timeout_milliseconds); - let java_build_timeout = Duration::from_millis(request.java_build_timeout_milliseconds); let shutdown_timeout = Duration::from_millis(request.shutdown_timeout_milliseconds); - let jdt_java_runtimes = jdt_java_runtimes(&request.java_runtimes); - let jdt_completion = request - .initialization_options - .as_ref() - .and_then(|options| options.pointer("/settings/java/completion")) - .filter(|completion| completion.is_object()) - .cloned(); - let jdt_import_exclusions = request - .initialization_options - .as_ref() - .and_then(|options| options.pointer("/settings/java/import/exclusions")) - .filter(|exclusions| exclusions.is_array()) - .cloned(); let workspace_configuration = checked_workspace_configuration(request.workspace_configuration)?; let initialize = client_initialize_for_plugin( @@ -2271,46 +1442,20 @@ impl LspEngine { root_uri: request.root_uri.clone(), process_id: (!crate::remote::workspace::is_remote()) .then_some(std::process::id() as i64), - initialization_options: adapt_initialization_options( - &request.provider_id, - request.initialization_options, - &java_extension_bundle_paths, - JdtSettings { - indexing_root_uri: Some(&request.root_uri), - completion: jdt_completion.as_ref(), - import_exclusions: jdt_import_exclusions.as_ref(), - maven: jdt_maven_configuration.as_deref(), - gradle: request.java_gradle.as_ref(), - java_runtimes: &jdt_java_runtimes, - }, - ), + initialization_options: request.initialization_options, }, request.plugin_id.is_some(), )?; let process = self.launcher.launch(LspProcessSpec { - executable: adaptation - .executable - .unwrap_or_else(|| PathBuf::from(&request.executable_path)), - arguments: adaptation.arguments, + executable: PathBuf::from(&request.executable_path), + arguments: request.arguments, working_directory: workspace_root, environment: request.environment, })?; - let process_start_elapsed = startup_started_at.elapsed(); let request_id = (initialize.state.next_request_id - 1).to_string(); let now = Instant::now(); let process_id = process.handle.process_id(); - let java_preparation = java_cache_disposition.map(|cache_disposition| { - JavaPreparationDiagnostics::new( - startup_started_at, - process_start_elapsed, - cache_disposition, - request.workspace_fingerprint.is_some(), - ) - }); - 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), @@ -2324,14 +1469,7 @@ impl LspEngine { provider_id: request.provider_id, plugin_id: request.plugin_id, workspace_host: crate::remote::workspace::current(), - jdt_maven_configuration: Mutex::new(jdt_maven_configuration), - maven_inputs, - maven_update_order: Mutex::new(()), plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)), - jdt_java_runtimes, - jdt_completion, - jdt_import_exclusions, - jdt_gradle_configuration: request.java_gradle, root_uri: request.root_uri, indexing_roots: Mutex::default(), indexing_revision: std::sync::atomic::AtomicU64::new(0), @@ -2358,35 +1496,14 @@ impl LspEngine { request_by_operation: BTreeMap::new(), function_by_operation: BTreeMap::new(), linked_document_paths: LinkedDocumentPaths::default(), - java_navigation_marker_batches: BTreeMap::new(), - java_navigation_marker_cache: BTreeMap::new(), pending_workspace_file_changes: BTreeMap::new(), - preparation_snapshot: None, events: VecDeque::new(), next_sequence: 1, initialize_deadline: Some(now + initialize_timeout), - service_ready_idle_timeout, - service_ready_absolute_timeout, - java_preparation, shutdown_deadline: None, request_timeout, shutdown_timeout, terminal_event_emitted: false, - maven_profile_status: MavenProfileTaskStatus::Idle, - maven_profile_results: BTreeMap::new(), - maven_profile_queue: VecDeque::new(), - maven_profile_deadline: None, - maven_profile_applied_fingerprint: None, - maven_profile_running_fingerprint: None, - maven_profile_update_pending: false, - maven_project_reload_pending: false, - maven_profile_generation: 0, - maven_profile_request_generations: BTreeMap::new(), - java_builds: JavaBuildCoordinator::default(), - java_entrypoint_waiters: VecDeque::new(), - java_launches: BTreeMap::new(), - java_launch_messages: Vec::new(), - java_build_timeout, deadline_cancellations: Vec::new(), maintenance_write_deadline: None, plugin_server, @@ -2407,61 +1524,12 @@ impl LspEngine { session.transition(LspLifecycleState::Created, None)?; session.transition(LspLifecycleState::ProcessStarting, None)?; session.transition(LspLifecycleState::Initializing, None)?; - { - session.log( - "info", - EngineLog::ProcessStarted, - "Java language service process started", - java_startup_detail, - ); - } - if let Some(cleanup) = legacy_metadata_cleanup { - // Lithe deleted files from the user's project; keep a trace of which - // ones and why the following import starts from scratch. - session.log( - "info", - EngineLog::LegacyRemoved.with_fields(json!({"removedFiles": cleanup.removed_files, "stateReset": cleanup.state_reset})), - "Removed Java project files that earlier versions left in the workspace", - Some( - json!({ - "removedFiles": cleanup.removed_files, - "stateReset": cleanup.state_reset, - }) - .to_string(), - ), - ); - } - for detail in maven_settings_warnings { - session.log_issue( - "warn", - "mavenSettings", - "mavenSettingsUnchanged", - EngineLog::MavenSettingsForwarded, - "Maven settings were passed to the Java language service unchanged", - Some(detail), - ); - } - if let Some(area) = configuration_area { - if !area.removed_keys.is_empty() { - session.log( - "info", - EngineLog::ConfigurationCleaned - .with_fields(json!({"removedKeys": area.removed_keys})), - "Removed unused Java language-server configuration areas", - Some(json!({ "removedKeys": area.removed_keys }).to_string()), - ); - } - if let Some(failure) = area.cleanup_failure { - session.log_issue( - "warn", - "configurationCleanup", - "configurationCleanupFailed", - EngineLog::ConfigurationCleanupFailed, - "Unused Java language-server configuration areas could not be removed", - Some(failure), - ); - } - } + session.log( + "info", + EngineLog::ProcessStarted, + "Language server process started", + None, + ); // Register before checking the prepared generation. A policy change // either retires that generation or sees this session for its update. @@ -2587,8 +1655,9 @@ impl RuntimeSession { let Some(document) = state.client.open_documents.get(&request.uri) else { return Ok(false); }; - // JDT discards and reloads its working copy on didSave. A delayed - // save must not discard a newer editor revision already synchronized. + // A server may reload its working copy from the saved text. A + // delayed save must not discard a newer editor revision already + // synchronized. if *document.text != request.text { return Ok(false); } @@ -2631,10 +1700,7 @@ impl RuntimeSession { let message = { let mut state = self.lock_state()?; ensure_not_terminal(state.lifecycle)?; - if !state.client.initialized - || (waits_for_service_ready(&self.provider_id) - && state.lifecycle != LspLifecycleState::Ready) - { + if !state.client.initialized { state.pending_workspace_file_changes.extend(normalized); return Ok(()); } @@ -2674,7 +1740,7 @@ impl RuntimeSession { if let Some(document) = state.client.open_documents.get(&uri) { // Hosts commonly publish both a ranged edit and the resulting // full text. Repeating that full text must not create another - // JDTLS reconciliation cycle or advance the semantic version. + // server reconciliation cycle or advance the semantic version. if request.content_changes.is_empty() && *document.text == *request.text { return Ok(SyncDocumentResponse { document_version: document.version.max(1), @@ -2682,15 +1748,7 @@ impl RuntimeSession { }); } } - state.java_navigation_marker_cache.remove(&uri); - // JDT LS associates working copies with the Java project model that - // exists when `didOpen` arrives. Opening restored documents before - // `ServiceReady` can permanently bind them to an incomplete Maven - // model, so retain only their latest text until import finishes. - let can_sync_on_wire = state.client.initialized - && (!waits_for_service_ready(&self.provider_id) - || state.lifecycle == LspLifecycleState::Ready); - if can_sync_on_wire { + if state.client.initialized { let response = if state .client .open_documents @@ -2773,7 +1831,6 @@ impl RuntimeSession { "Cannot close a document that is not owned by the language-server session.", )); }; - state.java_navigation_marker_cache.remove(uri); cleared = state.client.diagnostics.contains_key(uri); if document.version == 0 { state.client.open_documents.remove(uri); @@ -2794,155 +1851,6 @@ impl RuntimeSession { self.send_messages_or_fail(&outbound_order, messages, "documentClose") } - fn complete_cached_java_navigation_markers( - &self, - operation_id: &str, - uri: &str, - requested_document_version: Option, - ) -> Result { - let mut state = self.lock_state()?; - if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { - return Ok(false); - } - if state.request_by_operation.contains_key(operation_id) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The language-server operation ID is already pending.", - )); - } - let current_version = state - .client - .open_documents - .get(uri) - .map(|document| document.version.max(1)); - let Some(entry) = state.java_navigation_marker_cache.get(uri) else { - return Ok(false); - }; - let expected_version = requested_document_version.or(current_version); - if expected_version != Some(entry.document_version) - || current_version != Some(entry.document_version) - { - return Ok(false); - } - let document_version = entry.document_version; - let markers = entry.markers.clone(); - push_log_event( - self, - &mut state, - "debug", - EngineLog::NavigationCacheHit.with_fields(json!({"operationId": operation_id, "document": uri, "document_version": document_version, "markers": markers.len()})), - "Java navigation markers served from cache", - Some(format!( - "operationId={operation_id}, uri={uri}, documentVersion={document_version}, markers={}", - markers.len() - )), - ); - push_request_event( - self, - &mut state, - operation_id, - "textDocument/codeLens", - Some(json!({ - "documentVersion": document_version, - "markers": markers - })), - None, - ); - Ok(true) - } - - /// Allocates the first request and attempt atomically, so cancellation always - /// finds the current upstream request or the existing build coordinator waiter. - fn prepare_java_launch( - &self, - request: JavaPrepareLaunchRequest, - operation_id: String, - ) -> Result<(), CoreError> { - if self.provider_id != "java" { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Java launch preparation requires the Java language service.", - )); - } - let canonical_root = canonical_workspace_root(&self.root_uri); - let preparation = JavaLaunchPreparation::new( - &self.root_uri, - canonical_root.as_deref(), - request.source_path, - request.main_class, - ) - .map_err(|message| CoreError::new(ErrorCode::InvalidRequest, message))?; - let outbound_order = self.lock_outbound_order()?; - let (messages, request_id) = { - let mut state = self.lock_state()?; - if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Language server is not ready.", - )); - } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - || state.java_launches.contains_key(&operation_id) - || state - .java_entrypoint_waiters - .iter() - .any(|waiter| waiter.operation_id == operation_id) - { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The language-server operation ID is already pending.", - )); - } - let now = Instant::now(); - if java_configuration_running(&mut state, now) { - if state.java_entrypoint_waiters.len() >= 128 { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java entry-point discovery queue is full.", - )); - } - let deadline = now + state.java_build_timeout; - state - .java_entrypoint_waiters - .push_back(JavaEntrypointWaiter { - operation_id: operation_id.clone(), - created_at: now, - deadline, - }); - state.java_launches.insert(operation_id, preparation); - return Ok(()); - } - let response = allocate_raw_request( - state.client.clone(), - "workspace/executeCommand", - java_entrypoints_command(), - )?; - let request_id = (response.state.next_request_id - 1).to_string(); - let now = Instant::now(); - let timeout = state.request_timeout; - state.client = response.state; - state.pending.insert( - request_id.clone(), - PendingRequest { - kind: PendingKind::JavaEntrypoints, - operation_id: Some(operation_id.clone()), - method: "workspace/executeCommand".to_string(), - document_uri: None, - document_version: None, - created_at: now, - deadline: now + timeout, - }, - ); - state - .request_by_operation - .insert(operation_id.clone(), request_id.clone()); - state.java_launches.insert(operation_id, preparation); - (response.messages, request_id) - }; - self.send_request_or_fail(&outbound_order, messages, &request_id) - } - fn request(&self, request: SemanticRequest, operation_id: String) -> Result<(), CoreError> { let document_version = request.uri.as_deref().and_then(|uri| { self.lock_state().ok().and_then(|state| { @@ -2953,14 +1861,12 @@ impl RuntimeSession { .map(|document| document.version.max(1)) }) }); - let pending_kind = match request.operation { - LspSemanticOperation::VirtualDocument => PendingKind::VirtualDocument, - LspSemanticOperation::JavaEntrypoints => PendingKind::JavaEntrypoints, - LspSemanticOperation::JavaTestItems => PendingKind::JavaTestItems, - LspSemanticOperation::JavaMainMethods => PendingKind::JavaMainMethods, - _ => PendingKind::Feature, - }; - self.request_with_kind(request, operation_id, pending_kind, document_version) + self.request_with_kind( + request, + operation_id, + PendingKind::Feature, + document_version, + ) } /// Writes a build-provider request. It needs no open document, so it is @@ -2987,13 +1893,7 @@ impl RuntimeSession { "Language server is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - || state - .java_entrypoint_waiters - .iter() - .any(|waiter| waiter.operation_id == operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The language-server operation ID is already pending.", @@ -3242,9 +2142,7 @@ impl RuntimeSession { "Plugin backend is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The operation ID is already pending.", @@ -3315,9 +2213,7 @@ impl RuntimeSession { "Language server is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The language-server operation ID is already pending.", @@ -3388,13 +2284,7 @@ impl RuntimeSession { "Language server is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - || state - .java_entrypoint_waiters - .iter() - .any(|waiter| waiter.operation_id == operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The language-server operation ID is already pending.", @@ -3478,13 +2368,7 @@ impl RuntimeSession { "Language server is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - || state - .java_entrypoint_waiters - .iter() - .any(|waiter| waiter.operation_id == operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The language-server operation ID is already pending.", @@ -3753,13 +2637,7 @@ impl RuntimeSession { "Language server is not ready.", )); } - if state.request_by_operation.contains_key(&operation_id) - || state.java_builds.contains(&operation_id) - || state - .java_entrypoint_waiters - .iter() - .any(|waiter| waiter.operation_id == operation_id) - { + if state.request_by_operation.contains_key(&operation_id) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The language-server operation ID is already pending.", @@ -3783,7 +2661,7 @@ impl RuntimeSession { if current_version != expected_version { return Err(CoreError::new( ErrorCode::Cancelled, - "The document changed before the Java navigation request started.", + "The document changed before the language-server request started.", ) .with_details(format!( "expectedVersion={expected_version}, currentVersion={current_version}" @@ -3807,80 +2685,8 @@ impl RuntimeSession { } } - // Java project builds are queued behind project configuration and - // earlier builds instead of being written immediately. - if request.operation == LspSemanticOperation::ExecuteCommand { - if let Some(command) = request - .command - .as_ref() - .filter(|command| is_java_build_command(&self.provider_id, command)) - { - let now = Instant::now(); - let timeout = state.java_build_timeout; - state - .java_builds - .enqueue(operation_id, command.clone(), now, timeout); - let messages = self.dispatch_java_build_locked(&mut state, now); - drop(state); - return self.send_messages_or_fail(&outbound_order, messages, "javaBuild"); - } - } - - // Profile updates return before m2e has changed the Java projects. - // Discovering first and only gating the later build can select an - // old entry point or miss a source root introduced by the profile. - if self.provider_id == "java" - && request.operation == LspSemanticOperation::JavaEntrypoints - && java_configuration_running(&mut state, Instant::now()) - { - if state.java_entrypoint_waiters.len() >= 128 { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Too many Java entry-point requests are waiting for project configuration.", - )); - } - let now = Instant::now(); - let timeout = state.java_build_timeout; - state - .java_entrypoint_waiters - .push_back(JavaEntrypointWaiter { - operation_id, - created_at: now, - deadline: now + timeout, - }); - return Ok(()); - } - let pending_kind = requested_kind; let response = match request.operation { - LspSemanticOperation::JavaSuperImplementation => { - let uri = uri.clone().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java super navigation requires a document URI.", - ) - })?; - let position = request.position.ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java super navigation requires a document position.", - ) - })?; - allocate_raw_request( - state.client.clone(), - method, - json!({ - "type": "superImplementation", - "position": { - "textDocument": { "uri": uri }, - "position": { - "line": position.line, - "character": position.utf16_column - } - } - }), - )? - } LspSemanticOperation::ExecuteCommand => { let command = request.command.ok_or_else(|| { CoreError::new( @@ -3890,76 +2696,6 @@ impl RuntimeSession { })?; allocate_raw_request(state.client.clone(), method, command)? } - LspSemanticOperation::JavaEntrypoints => { - if self.provider_id != "java" { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Java entry-point discovery requires the Java language service.", - )); - } - allocate_raw_request(state.client.clone(), method, java_entrypoints_command())? - } - LspSemanticOperation::JavaTestItems => { - if self.provider_id != "java" { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Java test discovery requires the Java language service.", - )); - } - let uri = uri.clone().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java test discovery requires a document URI.", - ) - })?; - allocate_raw_request( - state.client.clone(), - method, - java_test_items_command(&uri), - )? - } - LspSemanticOperation::JavaMainMethods => { - if self.provider_id != "java" { - return Err(CoreError::new( - ErrorCode::NotSupported, - "Java main-method discovery requires the Java language service.", - )); - } - let uri = uri.clone().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Java main-method discovery requires a document URI.", - ) - })?; - allocate_raw_request( - state.client.clone(), - method, - java_main_methods_command(&uri), - )? - } - LspSemanticOperation::VirtualDocument => { - let virtual_uri = request.virtual_uri.as_deref().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "Virtual-document resolution requires virtualUri.", - ) - })?; - let params = virtual_source_resolve_params(&self.provider_id, virtual_uri) - .ok_or_else(|| { - CoreError::new( - ErrorCode::NotSupported, - "The provider cannot resolve this virtual document URI.", - ) - })?; - allocate_raw_request( - state.client.clone(), - method, - json!({ - "command": params.command, - "arguments": params.arguments - }), - )? - } _ => { let uri = uri.clone().ok_or_else(|| { CoreError::new( @@ -3972,8 +2708,7 @@ impl RuntimeSession { .open_documents .get(&uri) .is_some_and(|document| document.version > 0); - let provider_owns_document = is_virtual_source_uri(&self.provider_id, &uri); - if !document_is_open && !provider_owns_document { + if !document_is_open { return Err(CoreError::new( ErrorCode::InvalidRequest, "The document is not open in the language server.", @@ -3992,11 +2727,7 @@ impl RuntimeSession { code_action: request.code_action, command: request.command, }; - if provider_owns_document { - client_provider_document_feature_request_canonical(feature_request)? - } else { - client_feature_request_canonical(feature_request)? - } + client_feature_request_canonical(feature_request)? } }; let request_id = (response.state.next_request_id - 1).to_string(); @@ -4059,58 +2790,6 @@ impl RuntimeSession { let outbound_order = self.lock_outbound_order()?; let request_id = { let mut state = self.lock_state()?; - if let Some(index) = state - .java_entrypoint_waiters - .iter() - .position(|waiter| waiter.operation_id == operation_id) - { - state.java_entrypoint_waiters.remove(index); - let error = runtime_error( - self, - "requestCancelled", - "request", - Some(JAVA_BUILD_METHOD), - None, - "Language-server request was cancelled.", - None, - None, - ); - push_request_event( - self, - &mut state, - operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - return Ok(()); - } - if let Some(departure) = state.java_builds.cancel(operation_id) { - let error = runtime_error( - self, - "requestCancelled", - "request", - Some(JAVA_BUILD_METHOD), - None, - "Language-server request was cancelled.", - None, - None, - ); - push_request_event( - self, - &mut state, - operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - drop(state); - return self.send_messages_or_fail( - &outbound_order, - java_build_cancellation(departure), - "requestCancel", - ); - } if state .plugin_server .as_ref() @@ -4137,7 +2816,6 @@ impl RuntimeSession { state.client.pending_requests.remove(&request_id); state.client.pending_semantic_legends.remove(&request_id); state.function_by_operation.remove(operation_id); - state.java_navigation_marker_batches.remove(operation_id); let error = runtime_error( self, "requestCancelled", @@ -4171,7 +2849,6 @@ impl RuntimeSession { let outbound_order = self.lock_outbound_order()?; let (messages, force_kill) = { let mut state = self.lock_state()?; - let mut cancel_messages = Vec::new(); if matches!( state.lifecycle, LspLifecycleState::Stopped | LspLifecycleState::Failed @@ -4181,44 +2858,6 @@ impl RuntimeSession { if state.lifecycle == LspLifecycleState::Stopping { return Ok(()); } - if state.maven_profile_status == MavenProfileTaskStatus::Running { - state.maven_profile_status = MavenProfileTaskStatus::Cancelled; - push_maven_profile_task_event(self, &mut state, MavenProfileTaskStatus::Cancelled); - state.maven_profile_queue.clear(); - state.maven_profile_deadline = None; - let cancelled_maven_ids: Vec = state - .pending - .iter() - .filter_map(|(id, pending)| { - (pending.kind == PendingKind::JdtMavenProfiles).then_some(id.clone()) - }) - .collect(); - cancel_messages = cancelled_maven_ids - .iter() - .map(|id| { - json!({ - "jsonrpc": "2.0", - "method": "$/cancelRequest", - "params": { "id": id } - }) - .to_string() - }) - .collect(); - for id in cancelled_maven_ids { - state.pending.remove(&id); - state.client.pending_requests.remove(&id); - state.client.pending_semantic_legends.remove(&id); - state.maven_profile_request_generations.remove(&id); - } - push_log_event( - self, - &mut state, - "info", - EngineLog::MavenCancelled, - "Maven profile application cancelled with the session", - None, - ); - } fail_feature_requests( self, &mut state, @@ -4253,13 +2892,11 @@ impl RuntimeSession { }, ); state.client = response.state; - let mut messages = cancel_messages; - messages.extend(response.messages); - (messages, false) + (response.messages, false) } else { state.client.pending_requests.clear(); state.pending.clear(); - (cancel_messages, true) + (Vec::new(), true) } }; self.send_messages_or_fail(&outbound_order, messages, "shutdown")?; @@ -4330,7 +2967,6 @@ impl RuntimeSession { open_documents: state.client.open_documents.clone(), pending_operation_ids: { let mut ids: Vec = state.request_by_operation.keys().cloned().collect(); - ids.extend(state.java_builds.operation_ids()); ids.sort(); ids }, @@ -4539,8 +3175,6 @@ impl RuntimeSession { } } after_policy_check(); - let readiness = readiness_signal(&self.provider_id, method, value.get("params")); - let java_import_progress = import_progress(&self.provider_id, method, value.get("params")); if method == Some("workspace/configuration") { if let Some(response) = self.provider_configuration_response(&value)? { return self.send_messages_or_fail( @@ -4573,9 +3207,6 @@ impl RuntimeSession { let mut flush_documents = false; let mut ready_server_info = None; let mut fail_initialize: Option<(String, Option)> = None; - let mut service_ready = false; - let mut apply_maven_context = false; - let mut fail_service_ready = None; { let mut state = self.lock_state()?; state.client = reduced.state; @@ -4606,31 +3237,6 @@ impl RuntimeSession { } else { plugin_operations::finish(&self.startup_attempt, None); state.initialize_deadline = None; - if waits_for_service_ready(&self.provider_id) { - let now = Instant::now(); - let idle_timeout = state.service_ready_idle_timeout; - let absolute_timeout = state.service_ready_absolute_timeout; - let initialize_elapsed = pending_before - .as_ref() - .map(|pending| now.saturating_duration_since(pending.created_at)) - .unwrap_or_default(); - if let Some(diagnostics) = state.java_preparation.as_mut() { - let detail = diagnostics.begin_readiness( - now, - initialize_elapsed, - idle_timeout, - absolute_timeout, - ); - push_log_event( - self, - &mut state, - "info", - EngineLog::ProtocolInitialized, - "Java language service protocol initialized", - Some(detail), - ); - } - } ready_server_info = parse_server_info(&value); flush_documents = true; } @@ -4814,12 +3420,12 @@ impl RuntimeSession { ) }); 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. + // A plugin-owned server marks locations that are not + // files read-only; answers from other servers pass through. let result = if state.plugin_server.is_some() { plugin_server::normalize_navigation_result(result) } else { - normalize_provider_navigation_result(&self.provider_id, result) + result }; push_request_event( self, @@ -4848,563 +3454,6 @@ impl RuntimeSession { } } } - Some(PendingKind::JavaNavigationMarkers) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let event = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()); - let server_error = - event.and_then(|event| event.error.as_ref()).map(|detail| { - runtime_error( - self, - "serverError", - "javaNavigationMarkers", - Some(&pending.method), - pending.document_uri.as_deref(), - "Language server returned an error.", - Some(detail), - None, - ) - }); - if let Some(error) = server_error { - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - None, - Some(error), - ); - } else { - let raw_lenses = value - .get("result") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - let source = pending - .document_uri - .as_deref() - .and_then(|uri| state.client.open_documents.get(uri)) - .map(|document| document.text.as_ref()) - .unwrap_or_default(); - let batch = JavaNavigationMarkerBatch::new( - &raw_lenses, - source, - pending.created_at, - pending.deadline, - ); - let total_tasks = batch.total_tasks(); - state - .java_navigation_marker_batches - .insert(operation_id.clone(), batch); - if total_tasks > MAX_JAVA_NAVIGATION_TASKS { - push_issue_log_event( - self, - &mut state, - "warning", - "navigation", - "navigationLimited", - EngineLog::NavigationLimited.with_fields(json!({"operationId": operation_id, "document": pending.document_uri, "tasks": total_tasks, "limit": MAX_JAVA_NAVIGATION_TASKS})), - "Java navigation marker batch was limited", - Some(format!( - "operationId={operation_id}, uri={}, documentVersion={}, tasks={total_tasks}, limit={MAX_JAVA_NAVIGATION_TASKS}", - pending.document_uri.as_deref().unwrap_or(""), - pending.document_version.unwrap_or_default() - )), - ); - } - if !queue_next_java_marker_resolve( - &mut state, - operation_id, - pending, - &mut outbound, - )? { - finish_java_navigation_marker_batch( - self, - &mut state, - operation_id, - pending, - ); - } - } - } - } - } - Some(PendingKind::JavaNavigationMarkerResolve) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - if value.get("error").is_none() { - if let Some(batch) = - state.java_navigation_marker_batches.get_mut(operation_id) - { - batch.record_active_result(value.get("result")); - } - } else { - push_issue_log_event( - self, - &mut state, - "warning", - "navigation", - "navigationMarkerFailed", - EngineLog::NavigationMarkerFailed.with_fields(json!({"operationId": operation_id, "document": pending.document_uri, "document_version": pending.document_version, "failureCode": "server_error"})), - "JDT LS could not verify one Java navigation marker", - Some(format!( - "operationId={operation_id}, uri={}, documentVersion={}, error={}", - pending.document_uri.as_deref().unwrap_or(""), - pending.document_version.unwrap_or_default(), - value.get("error").map(Value::to_string).unwrap_or_default() - )), - ); - } - if !queue_next_java_marker_resolve( - &mut state, - operation_id, - pending, - &mut outbound, - )? { - finish_java_navigation_marker_batch( - self, - &mut state, - operation_id, - pending, - ); - } - } - } - } - Some(PendingKind::JavaResolveNavigation) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let event = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()); - let error = - event.and_then(|event| event.error.as_ref()).map(|detail| { - runtime_error( - self, - "serverError", - "javaResolveNavigation", - Some(&pending.method), - pending.document_uri.as_deref(), - "Language server returned an error.", - Some(detail), - None, - ) - }); - let normalized = normalize_provider_navigation_result( - &self.provider_id, - event.and_then(|event| event.result.clone()), - ); - let locations = normalized - .as_ref() - .and_then(|result| result.get("locations")) - .cloned() - .unwrap_or_else(|| Value::Array(Vec::new())); - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - Some(json!({ - "documentVersion": pending.document_version, - "locations": locations - })), - error, - ); - } - } - } - Some(PendingKind::JdtMavenProfiles) => { - // JDT LS error payloads may contain absolute workspace paths - // or URLs. Keep the user-facing project result actionable - // without persisting the opaque server payload in logs. - let server_error = value - .get("error") - .map(|_| "Maven profile project update failed.".to_string()); - let request_key = response_id.as_ref().cloned().unwrap_or_default(); - let response_generation = - state.maven_profile_request_generations.remove(&request_key); - if response_generation != Some(state.maven_profile_generation) - || state.maven_profile_status != MavenProfileTaskStatus::Running - { - return Ok(()); - } - let mut completed_result = None; - if let Some(result) = state.maven_profile_results.get_mut(&request_key) { - result.status = if server_error.is_some() { - MavenProfileTaskStatus::Failed - } else { - MavenProfileTaskStatus::Succeeded - }; - result.error_details = server_error.clone(); - let project_uri = redacted_project_uri(&result.project_uri); - let status = result.status; - let error_details = result.error_details.clone(); - completed_result = Some(result.clone()); - let detail = serde_json::to_string(&json!({ - "projectUri": project_uri, - "status": status, - "errorDetails": error_details, - })) - .expect("JSON values serialize without fallible map keys"); - if status == MavenProfileTaskStatus::Failed { - push_issue_log_event( - self, - &mut state, - "error", - "mavenProfile", - "mavenProfileUpdateFailed", - EngineLog::MavenProjectFinished.with_fields( - json!({"projectUri": project_uri, "status": status}), - ), - "Maven profile project update completed", - Some(detail), - ); - } else { - push_log_event( - self, - &mut state, - "info", - EngineLog::MavenProjectFinished.with_fields( - json!({"projectUri": project_uri, "status": status}), - ), - "Maven profile project update completed", - Some(detail), - ); - } - } - if let Some(result) = completed_result { - push_maven_profile_project_event(self, &mut state, result); - } - if let Some(params) = state.maven_profile_queue.pop_front() { - let project_uri = params - .get("arguments") - .and_then(Value::as_array) - .and_then(|arguments| arguments.first()) - .and_then(Value::as_str) - .map(str::to_string); - let response = allocate_raw_request( - state.client.clone(), - "workspace/executeCommand", - params, - )?; - let next_id = (response.state.next_request_id - 1).to_string(); - state.client = response.state; - let next_deadline = state.maven_profile_deadline.unwrap_or_else(|| { - Instant::now() + state.service_ready_absolute_timeout - }); - state.pending.insert( - next_id.clone(), - PendingRequest { - kind: PendingKind::JdtMavenProfiles, - operation_id: None, - method: "workspace/executeCommand".to_string(), - document_uri: None, - document_version: None, - created_at: Instant::now(), - deadline: next_deadline, - }, - ); - let generation = state.maven_profile_generation; - state - .maven_profile_request_generations - .insert(next_id.clone(), generation); - if let Some(uri) = project_uri { - if let Some((queued_id, _)) = state - .maven_profile_results - .iter() - .find(|(id, result)| { - id.starts_with("queued:") && result.project_uri == uri - }) - .map(|(id, result)| (id.clone(), result.clone())) - { - state.maven_profile_results.remove(&queued_id); - } - let project_result = MavenProfileProjectResult { - project_uri: uri, - status: MavenProfileTaskStatus::Running, - error_details: None, - }; - state - .maven_profile_results - .insert(next_id, project_result.clone()); - push_maven_profile_project_event(self, &mut state, project_result); - } - outbound.extend(response.messages); - } - if !state - .pending - .values() - .any(|pending| pending.kind == PendingKind::JdtMavenProfiles) - && state.maven_profile_queue.is_empty() - { - state.maven_profile_status = if state - .maven_profile_results - .values() - .any(|result| result.status == MavenProfileTaskStatus::Failed) - { - MavenProfileTaskStatus::PartiallySucceeded - } else { - MavenProfileTaskStatus::Succeeded - }; - let task_status = state.maven_profile_status; - push_maven_profile_task_event(self, &mut state, task_status); - let applied = state.maven_profile_running_fingerprint.take(); - // A newer configuration must run even when this batch failed. - apply_maven_context |= applied - != maven_profile_fingerprint(self.maven_configuration().as_deref()); - if state.maven_profile_status == MavenProfileTaskStatus::Succeeded { - state.maven_profile_applied_fingerprint = applied; - } - let profile_log_level = - if state.maven_profile_status == MavenProfileTaskStatus::Succeeded { - "info" - } else { - "warning" - }; - let profile_log_message = - if state.maven_profile_status == MavenProfileTaskStatus::Succeeded { - "Java language service applied Maven profiles" - } else { - "Java language service partially applied Maven profiles" - }; - let identity = - if state.maven_profile_status == MavenProfileTaskStatus::Succeeded { - EngineLog::MavenApplied - } else { - EngineLog::MavenPartiallyApplied - }; - push_log_event( - self, - &mut state, - profile_log_level, - identity, - profile_log_message, - None, - ); - state.maven_profile_deadline = None; - } - } - Some(PendingKind::JavaBuild) => { - if let Some(request_id) = response_id.as_deref() { - let event = reduced - .events - .iter() - .find(|event| event.request_id.as_deref() == Some(request_id)); - self.complete_java_build_locked(&mut state, request_id, event); - } - } - Some(PendingKind::VirtualDocument) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let reduced_event = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()); - let server_error = reduced_event - .and_then(|event| event.error.as_ref()) - .map(|detail| { - runtime_error( - self, - "serverError", - "request", - Some(&pending.method), - None, - "Language server returned an error.", - Some(detail), - None, - ) - }); - let content = value.get("result").and_then(|result| { - virtual_source_content(&self.provider_id, result) - }); - let invalid_result = if server_error.is_none() && content.is_none() { - Some(runtime_error( - self, - "invalidServerResult", - "request", - Some(&pending.method), - None, - "Language server returned no virtual-document text.", - None, - None, - )) - } else { - None - }; - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - content.map(|text| json!({ "text": text })), - server_error.or(invalid_result), - ); - } - } - } - Some(PendingKind::JavaEntrypoints) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let server_error = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()) - .and_then(|event| event.error.as_ref()) - .map(|detail| { - runtime_error( - self, - "serverError", - "request", - Some(&pending.method), - None, - "Language server returned an error.", - Some(detail), - None, - ) - }); - let canonical_root = canonical_workspace_root(&self.root_uri); - let entrypoints = value.get("result").and_then(|result| { - normalize_java_entrypoints( - &self.root_uri, - canonical_root.as_deref(), - result, - ) - }); - // A malformed answer must not look like "no - // entry points": callers keep their last good list. - let invalid_result = if server_error.is_none() && entrypoints.is_none() - { - Some(runtime_error( - self, - "invalidServerResult", - "request", - Some(&pending.method), - None, - "Language server returned no Java entry-point list.", - None, - None, - )) - } else { - None - }; - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - entrypoints.map(|entrypoints| { - serde_json::to_value(entrypoints) - .expect("Java entry points should encode") - }), - server_error.or(invalid_result), - ); - } - } - } - Some(PendingKind::JavaTestItems) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let server_error = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()) - .and_then(|event| event.error.as_ref()) - .map(|detail| { - runtime_error( - self, - "serverError", - "request", - Some(&pending.method), - pending.document_uri.as_deref(), - "Java Test extension returned an error.", - Some(detail), - None, - ) - }); - let items = value.get("result").and_then(normalize_java_test_items); - let invalid_result = if server_error.is_none() && items.is_none() { - Some(runtime_error( - self, - "invalidServerResult", - "request", - Some(&pending.method), - pending.document_uri.as_deref(), - "Java Test extension returned no test-item list.", - None, - None, - )) - } else { - None - }; - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - items.map(|items| { - serde_json::to_value(items) - .expect("Java test items should encode") - }), - server_error.or(invalid_result), - ); - } - } - } - Some(PendingKind::JavaMainMethods) => { - if let Some(pending) = pending_before.as_ref() { - if let Some(operation_id) = &pending.operation_id { - let server_error = reduced - .events - .iter() - .find(|event| event.request_id.as_ref() == response_id.as_ref()) - .and_then(|event| event.error.as_ref()) - .map(|detail| { - runtime_error( - self, - "serverError", - "request", - Some(&pending.method), - pending.document_uri.as_deref(), - "Language server returned an error.", - Some(detail), - None, - ) - }); - let methods = value.get("result").and_then(normalize_java_main_methods); - // A malformed answer must not look like "no main - // methods": callers keep their last good markers. - let invalid_result = if server_error.is_none() && methods.is_none() { - Some(runtime_error( - self, - "invalidServerResult", - "request", - Some(&pending.method), - pending.document_uri.as_deref(), - "Language server returned no Java main-method list.", - None, - None, - )) - } else { - None - }; - push_request_event( - self, - &mut state, - operation_id, - &pending.method, - methods.map(|methods| { - serde_json::to_value(methods) - .expect("Java main methods should encode") - }), - server_error.or(invalid_result), - ); - } - } - } Some(PendingKind::Shutdown) => { // The reducer emits `exit` only after the shutdown response. state.shutdown_deadline = Some(Instant::now() + state.shutdown_timeout); @@ -5412,45 +3461,6 @@ impl RuntimeSession { None => {} } - let suppress_structured_java_preparation_notification = state.lifecycle - == LspLifecycleState::Initializing - && (java_import_progress.is_some() || readiness.is_some()); - if state.lifecycle == LspLifecycleState::Initializing { - if let Some(progress) = java_import_progress { - let detail = state.java_preparation.as_mut().and_then(|diagnostics| { - diagnostics.record_progress(progress, Instant::now()) - }); - if let Some(detail) = detail { - let fields = state - .java_preparation - .as_ref() - .map(|d| d.log_progress(Instant::now())) - .unwrap_or(Value::Null); - push_log_event( - self, - &mut state, - "info", - EngineLog::WorkspaceProgressReceived.with_fields(fields), - "Java workspace import progress", - Some(detail), - ); - } - } - } - - if state.lifecycle == LspLifecycleState::Initializing { - match readiness.as_ref() { - Some(JdtReadinessSignal::Ready) if state.client.initialized => { - service_ready = true; - apply_maven_context = true; - } - Some(JdtReadinessSignal::Failed(detail)) => { - fail_service_ready = Some(detail.clone()); - } - _ => {} - } - } - for event in reduced.events { if event.kind == "notification" { outbound.extend(observe_plugin_server_notification( @@ -5534,13 +3544,7 @@ impl RuntimeSession { )? { // The backend withdrew one of its own host requests. - } else if event.kind == "notification" - && !(suppress_structured_java_preparation_notification - && is_structured_import_notification( - &self.provider_id, - event.method.as_deref(), - )) - { + } else if event.kind == "notification" { let method = event.method.as_deref().unwrap_or("unknown"); let params = event.result.as_ref().unwrap_or(&Value::Null); if method != "$/logTrace" || state.detailed_diagnostics { @@ -5562,16 +3566,6 @@ impl RuntimeSession { let capabilities = state.client.server_capabilities.clone(); push_features_event(self, &mut state, capabilities); } - let now = Instant::now(); - if let Some(progress) = - project_job_progress(&self.provider_id, method, value.get("params")) - { - state.java_builds.observe_progress(progress, now); - } - // A build response, a finished project job, or finished Maven - // profiles can each unblock the next queued build. - outbound.extend(self.dispatch_java_build_locked(&mut state, now)); - outbound.extend(self.dispatch_java_entrypoints_locked(&mut state, now)); } if let Some((code, detail)) = fail_initialize { @@ -5585,36 +3579,11 @@ impl RuntimeSession { self.kill_process(); return Ok(()); } - if let Some(detail) = fail_service_ready { - self.fail( - "serviceReadyFailed", - "serviceReady", - "Java language service failed while preparing the workspace.", - Some(detail), - None, - ); - self.kill_process(); - return Ok(()); - } if flush_documents { - if let Some(notification) = initialized_notification( - &self.provider_id, - self.jdt_settings(self.maven_configuration().as_deref()), - ) { - outbound.push( - json!({ - "jsonrpc": "2.0", - "method": notification.method, - "params": notification.params - }) - .to_string(), - ); - } else if let Some(configuration) = self.plugin_configuration() { + if let Some(configuration) = self.plugin_configuration() { outbound.push(plugin_configuration_notification(&configuration)); } - if !waits_for_service_ready(&self.provider_id) { - outbound.extend(self.flush_queued_documents()?); - } + outbound.extend(self.flush_queued_documents()?); let diagnostics_enabled = self.lock_state()?.requested_diagnostics; if diagnostics_enabled { // LSP forbids setTrace before the initialize response. This batch @@ -5627,97 +3596,20 @@ impl RuntimeSession { if let Some(info) = ready_server_info { push_server_info_event(self, &mut state, info); } - if !waits_for_service_ready(&self.provider_id) { - push_log_event( - self, - &mut state, - "info", - EngineLog::ProtocolInitialized, - "Language service protocol initialized", - None, - ); - } - if waits_for_service_ready(&self.provider_id) { - push_log_event( - self, - &mut state, - "info", - EngineLog::WorkspaceWaiting, - "Waiting for the Java language service to finish project import", - None, - ); - } else { - transition_locked(self, &mut state, LspLifecycleState::Ready, None); - let capabilities = state.client.server_capabilities.clone(); - push_features_event(self, &mut state, capabilities); - } + push_log_event( + self, + &mut state, + "info", + EngineLog::ProtocolInitialized, + "Language service protocol initialized", + None, + ); + transition_locked(self, &mut state, LspLifecycleState::Ready, None); + let capabilities = state.client.server_capabilities.clone(); + push_features_event(self, &mut state, capabilities); return Ok(()); } - if service_ready { - let reload = { - let mut state = self.lock_state()?; - std::mem::take(&mut state.maven_project_reload_pending) - }; - if reload { - if let Some(notification) = self - .maven_configuration() - .as_deref() - .and_then(project_update_notification) - { - outbound.push( - json!({ - "jsonrpc": "2.0", "method": notification.method, - "params": notification.params - }) - .to_string(), - ); - } - } - } - if apply_maven_context { - let (profile_requests, profiles_pending) = self.maven_profile_requests()?; - if profiles_pending { - let mut state = self.lock_state()?; - push_log_event( - self, - &mut state, - "info", - EngineLog::MavenApplicationStarted, - "Java language service applying Maven profiles", - None, - ); - } - outbound.extend(profile_requests); - } self.send_messages_or_fail(&outbound_order, outbound, "serverResponse")?; - if service_ready { - self.lock_state()?.initialize_deadline = None; - let queued_messages = self.flush_queued_documents()?; - self.send_messages_or_fail(&outbound_order, queued_messages, "serviceReady")?; - { - let mut state = self.lock_state()?; - let ready_fields = state - .java_preparation - .as_ref() - .map(|d| d.log_import(Instant::now())) - .unwrap_or(Value::Null); - let ready_detail = state - .java_preparation - .as_mut() - .map(|diagnostics| diagnostics.ready_detail(Instant::now())); - transition_locked(self, &mut state, LspLifecycleState::Ready, None); - let capabilities = state.client.server_capabilities.clone(); - push_features_event(self, &mut state, capabilities); - push_log_event( - self, - &mut state, - "info", - EngineLog::WorkspaceImportFinished.with_fields(ready_fields), - "Java language service finished project import", - ready_detail, - ); - } - } Ok(()) } @@ -5728,38 +3620,21 @@ impl RuntimeSession { let Some(id) = message.get("id") else { return Ok(None); }; - let items: Vec = message + let Some(configuration) = self.plugin_configuration() else { + return Ok(None); + }; + // Each item asks for one section; `scopeUri` is ignored because a + // session carries one configuration for its whole workspace. + let values: Vec = message .get("params") .and_then(|params| params.get("items")) .and_then(Value::as_array) .into_iter() .flatten() - .map(|item| WorkspaceConfigurationItem { - scope_uri: item - .get("scopeUri") - .and_then(Value::as_str) - .map(ToString::to_string), - section: item - .get("section") - .and_then(Value::as_str) - .map(ToString::to_string), + .map(|item| { + configuration_section(&configuration, item.get("section").and_then(Value::as_str)) }) .collect(); - let maven = self.maven_configuration(); - let values = match workspace_configuration( - &self.provider_id, - &items, - self.jdt_settings(maven.as_deref()), - ) { - Some(values) => values, - None => match self.plugin_configuration() { - Some(configuration) => items - .iter() - .map(|item| configuration_section(&configuration, item.section.as_deref())) - .collect(), - None => return Ok(None), - }, - }; Ok(Some( serde_json::to_string(&json!({ "jsonrpc": "2.0", @@ -5776,118 +3651,6 @@ impl RuntimeSession { )) } - fn maven_profile_requests(&self) -> Result<(Vec, bool), CoreError> { - let maven = self.maven_configuration(); - let fingerprint = maven_profile_fingerprint(maven.as_deref()); - let requests = maven_profile_update_requests(maven.as_deref()); - let mut state = self.lock_state()?; - if requests.is_empty() { - state.maven_profile_update_pending = false; - return Ok((Vec::new(), false)); - } - if state.maven_profile_applied_fingerprint.as_ref() == fingerprint.as_ref() - && state.maven_profile_status == MavenProfileTaskStatus::Succeeded - { - state.maven_profile_update_pending = false; - return Ok((Vec::new(), false)); - } - if state - .pending - .values() - .any(|pending| pending.kind == PendingKind::JdtMavenProfiles) - { - return Ok((Vec::new(), true)); - } - let now = Instant::now(); - // Maven profile application is a long-running workspace task, not a - // regular interactive LSP request. Bound it by the service-ready - // absolute safety limit rather than the short request timeout. - let deadline = now + state.service_ready_absolute_timeout; - state.maven_profile_deadline = Some(deadline); - state.maven_profile_running_fingerprint = fingerprint; - state.maven_profile_update_pending = false; - let project_count = requests.len(); - const MAX_IN_FLIGHT: usize = 8; - let requests = requests; - state - .maven_profile_queue - .extend(requests.iter().skip(MAX_IN_FLIGHT).cloned()); - state.maven_profile_status = MavenProfileTaskStatus::Running; - push_maven_profile_task_event(self, &mut state, MavenProfileTaskStatus::Running); - state.maven_profile_generation = state.maven_profile_generation.wrapping_add(1); - state.maven_profile_request_generations.clear(); - state.maven_profile_results.clear(); - // Register queued projects up front so a task timeout still emits a - // terminal result for every project, not only the first batch. - for (index, params) in requests.iter().enumerate().skip(MAX_IN_FLIGHT) { - if let Some(uri) = params - .get("arguments") - .and_then(Value::as_array) - .and_then(|arguments| arguments.first()) - .and_then(Value::as_str) - { - state.maven_profile_results.insert( - format!("queued:{index}"), - MavenProfileProjectResult { - project_uri: uri.to_string(), - status: MavenProfileTaskStatus::Running, - error_details: None, - }, - ); - } - } - let mut messages = Vec::with_capacity(requests.len()); - for params in requests.into_iter().take(MAX_IN_FLIGHT) { - let project_uri = params - .get("arguments") - .and_then(Value::as_array) - .and_then(|arguments| arguments.first()) - .and_then(Value::as_str) - .map(str::to_string); - let response = - allocate_raw_request(state.client.clone(), "workspace/executeCommand", 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::JdtMavenProfiles, - operation_id: None, - method: "workspace/executeCommand".to_string(), - document_uri: None, - document_version: None, - created_at: now, - deadline, - }, - ); - let generation = state.maven_profile_generation; - state - .maven_profile_request_generations - .insert(request_id.clone(), generation); - if let Some(uri) = project_uri { - let project_result = MavenProfileProjectResult { - project_uri: uri, - status: MavenProfileTaskStatus::Running, - error_details: None, - }; - state - .maven_profile_results - .insert(request_id, project_result.clone()); - push_maven_profile_project_event(self, &mut state, project_result); - } - messages.extend(response.messages); - } - push_log_event( - self, - &mut state, - "info", - EngineLog::MavenApplicationStarted.with_fields(json!({"projectCount": project_count})), - "Applying Maven profiles to Java projects", - Some(format!("projectCount={project_count}")), - ); - Ok((messages, true)) - } - fn flush_queued_documents(&self) -> Result, CoreError> { let queued = { let state = self.lock_state()?; @@ -5923,285 +3686,7 @@ impl RuntimeSession { flush_queued_documents_locked(&mut state) } - /// Writes queued launch discovery only after m2e and JDT configuration settle. - fn dispatch_java_entrypoints_locked( - &self, - state: &mut SessionState, - now: Instant, - ) -> Vec { - if state.lifecycle != LspLifecycleState::Ready - || !state.client.initialized - || java_configuration_running(state, now) - { - return Vec::new(); - } - let mut messages = Vec::new(); - for waiter in std::mem::take(&mut state.java_entrypoint_waiters) { - if now >= waiter.deadline { - let error = runtime_error( - self, - "requestTimeout", - "javaProjectConfiguration", - Some(JAVA_BUILD_METHOD), - None, - "Java entry-point discovery timed out waiting for project configuration.", - None, - None, - ); - push_request_event( - self, - state, - &waiter.operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - continue; - } - let response = match allocate_raw_request( - state.client.clone(), - JAVA_BUILD_METHOD, - java_entrypoints_command(), - ) { - Ok(response) => response, - Err(error) => { - let error = runtime_error( - self, - "invalidRequest", - "javaProjectConfiguration", - Some(JAVA_BUILD_METHOD), - None, - "Could not encode the Java entry-point request.", - Some(&error.message), - None, - ); - push_request_event( - self, - state, - &waiter.operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - continue; - } - }; - let request_id = (response.state.next_request_id - 1).to_string(); - state.client = response.state; - state - .request_by_operation - .insert(waiter.operation_id.clone(), request_id.clone()); - state.pending.insert( - request_id, - PendingRequest { - kind: PendingKind::JavaEntrypoints, - operation_id: Some(waiter.operation_id), - method: JAVA_BUILD_METHOD.to_string(), - document_uri: None, - document_version: None, - created_at: waiter.created_at, - deadline: waiter.deadline, - }, - ); - messages.extend(response.messages); - } - messages - } - - /// Starts the next queued Java build when nothing blocks it. The caller - /// holds `outbound_order` and must write the returned messages before - /// releasing it, so request IDs reach the server in allocation order. - fn dispatch_java_build_locked(&self, state: &mut SessionState, now: Instant) -> Vec { - if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { - return Vec::new(); - } - let maven_profiles_running = state.maven_profile_update_pending - || state.maven_profile_status == MavenProfileTaskStatus::Running; - let mut allocated = None; - let dispatch = state - .java_builds - .dispatch(maven_profiles_running, now, |command| { - let response = - allocate_raw_request(state.client.clone(), JAVA_BUILD_METHOD, command.clone())?; - let request_id = (response.state.next_request_id - 1).to_string(); - allocated = Some(response); - Ok::<_, CoreError>(request_id) - }); - refresh_project_preparation(self, state); - let dispatch = match dispatch { - Ok(dispatch) => dispatch, - Err((error, operation_ids)) => { - let detail = core_error_detail(&error); - for operation_id in operation_ids { - let error = runtime_error( - self, - "invalidRequest", - "javaBuild", - Some(JAVA_BUILD_METHOD), - None, - "Could not encode the Java project build request.", - Some(&detail), - None, - ); - push_request_event( - self, - state, - &operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - } - return Vec::new(); - } - }; - match dispatch { - JavaBuildDispatch::Idle => Vec::new(), - JavaBuildDispatch::Blocked { block, newly } => { - if newly { - push_log_event( - self, - state, - "info", - EngineLog::BuildWaiting.with_fields(json!({"reason": block.as_str()})), - "Java project build is waiting", - Some(json!({ "reason": block.as_str() }).to_string()), - ); - } - Vec::new() - } - JavaBuildDispatch::Started { - request_id, - waiter_count, - waited, - } => { - let Some(response) = allocated else { - return Vec::new(); - }; - state.client = response.state; - state.pending.insert( - request_id, - PendingRequest { - kind: PendingKind::JavaBuild, - operation_id: None, - method: JAVA_BUILD_METHOD.to_string(), - document_uri: None, - document_version: None, - created_at: now, - // Callers own their deadlines in the coordinator; this - // entry lives until JDT answers, even after timeouts. - deadline: now + state.java_build_timeout, - }, - ); - push_log_event( - self, - state, - "info", - EngineLog::BuildExecution.with_fields(json!({"waiterCount": waiter_count, "waitedMilliseconds": waited.as_millis() as u64})), - "Java project build started", - Some( - json!({ - "waiterCount": waiter_count, - "waitedMilliseconds": waited.as_millis() as u64, - }) - .to_string(), - ), - ); - response.messages - } - } - } - - /// Publishes the terminal result of a Java build to every caller sharing it. - fn complete_java_build_locked( - &self, - state: &mut SessionState, - request_id: &str, - event: Option<&super::LspClientEvent>, - ) { - let Some(completed) = state.java_builds.complete(request_id, Instant::now()) else { - return; - }; - let raw_status = event - .and_then(|event| event.result.as_ref()) - .and_then(|result| result.get("value")); - let outcome = java_build_outcome(raw_status); - // Captured before recording this outcome so the first builder failure - // reports itself as the origin rather than as a later casualty. - let builder_failed_earlier = state.java_builds.builder_failed_earlier(); - state.java_builds.observe_outcome(outcome); - let report = java_build_report( - outcome, - &completed.command, - builder_failed_earlier, - completed.elapsed, - ); - let error = if let Some(detail) = event.and_then(|event| event.error.as_deref()) { - Some(runtime_error( - self, - "serverError", - "javaBuild", - Some(JAVA_BUILD_METHOD), - None, - "Language server returned an error.", - Some(detail), - None, - )) - } else { - java_build_failure(outcome).map(|(code, message)| { - runtime_error( - self, - code, - "javaBuild", - Some(JAVA_BUILD_METHOD), - None, - message, - raw_status.map(Value::to_string).as_deref(), - None, - ) - }) - }; - let error = error.map(|mut error| { - error.java_build_report = Some(report); - error - }); - let result = if error.is_none() { - event.and_then(|event| event.result.clone()) - } else { - None - }; - push_log_event( - self, - state, - if error.is_none() { "info" } else { "warning" }, - EngineLog::BuildExecution.with_fields(json!({"outcome": format!("{outcome:?}"), "errorCode": error.as_ref().map(|e| &e.code), "elapsedMilliseconds": completed.elapsed.as_millis() as u64, "waiterCount": completed.operation_ids.len(), "markerScope": report.marker_scope, "builderFailedEarlier": report.builder_failed_earlier, "recovery": report.recovery})), - "Java project build finished", - Some( - json!({ - "outcome": format!("{outcome:?}"), - "errorCode": error.as_ref().map(|error| error.code.clone()), - "elapsedMilliseconds": completed.elapsed.as_millis() as u64, - "waiterCount": completed.operation_ids.len(), - "markerScope": report.marker_scope, - "builderFailedEarlier": report.builder_failed_earlier, - "recovery": report.recovery, - }) - .to_string(), - ), - ); - for operation_id in completed.operation_ids { - push_request_event( - self, - state, - &operation_id, - JAVA_BUILD_METHOD, - result.clone(), - error.clone(), - ); - } - } - - /// One session-owned writer retries queued builds and sends deadline cancellations. + /// One session-owned writer sends deadline cancellations off the monitor thread. /// The monitor remains free to terminate a stalled write and expire other callers. fn spawn_outbound_maintenance(self: &Arc) { let session = self.clone(); @@ -6214,66 +3699,25 @@ impl RuntimeSession { } fn pump_outbound_maintenance(&self) { - if !self.lock_state().is_ok_and(|state| { - state.java_builds.has_queued() - || !state.java_entrypoint_waiters.is_empty() - || !state.java_launch_messages.is_empty() - || !state.deadline_cancellations.is_empty() - || (state.maven_profile_update_pending - && state.lifecycle == LspLifecycleState::Ready - && !state - .pending - .values() - .any(|pending| pending.kind == PendingKind::JdtMavenProfiles)) - }) { + if !self + .lock_state() + .is_ok_and(|state| !state.deadline_cancellations.is_empty()) + { return; } let Ok(outbound_order) = self.outbound_order.try_lock() else { return; }; - // Timed-out requests retain their slots until terminal replies arrive. - // Only then may a newer selection start; never automatically retry the - // same failed configuration. - let update_profiles = self.lock_state().is_ok_and(|state| { - state.maven_profile_update_pending && state.lifecycle == LspLifecycleState::Ready - }); - let profile_messages = if update_profiles { - match self.maven_profile_requests() { - Ok((messages, _)) => messages, - Err(error) => { - self.log_issue( - "warn", - "mavenProfileStart", - "mavenProfileStartFailed", - EngineLog::MavenStartFailed, - "Could not start the pending Maven profile update", - Some(error.message), - ); - return; - } - } - } else { - Vec::new() - }; let Ok(mut state) = self.lock_state() else { return; }; - let mut messages: Vec = std::mem::take(&mut state.deadline_cancellations) + let messages: Vec = std::mem::take(&mut state.deadline_cancellations) .into_iter() .map(|id| { json!({ "jsonrpc": "2.0", "method": "$/cancelRequest", "params": { "id": id } }) .to_string() }) .collect(); - messages.extend(profile_messages); - for (request_id, queued) in std::mem::take(&mut state.java_launch_messages) { - // Cancellation or timeout can win before the writer acquires its lock. - if state.pending.contains_key(&request_id) { - messages.extend(queued); - } - } - messages.extend(self.dispatch_java_build_locked(&mut state, Instant::now())); - messages.extend(self.dispatch_java_entrypoints_locked(&mut state, Instant::now())); if messages.is_empty() { return; } @@ -6296,8 +3740,6 @@ impl RuntimeSession { self.relay.expire(now); let mut cancellations = Vec::new(); let mut initialize_timeout = false; - let mut service_ready_timeout = None; - let mut maven_context_timeout = false; let mut shutdown_timeout = false; let mut maintenance_write_timeout = false; let mut relay_write_timeout = false; @@ -6325,58 +3767,13 @@ impl RuntimeSession { // so exactly one of the two records the attempt. plugin_operations::finish(&self.startup_attempt, Some(AttemptStage::Timeout)); } - let applying_maven_context = state - .pending - .values() - .any(|pending| pending.kind == PendingKind::JdtMavenProfiles); - if state.lifecycle == LspLifecycleState::Initializing - && !initialize_timeout - && !applying_maven_context - { - service_ready_timeout = state - .java_preparation - .as_mut() - .and_then(|diagnostics| diagnostics.take_timeout(now)); - if service_ready_timeout.is_none() { - let warning = state - .java_preparation - .as_mut() - .and_then(|diagnostics| diagnostics.take_idle_warning(now)); - if let Some(detail) = warning { - let fields = state - .java_preparation - .as_ref() - .map(|d| d.log_progress(now)) - .unwrap_or(Value::Null); - push_issue_log_event( - self, - &mut state, - "warning", - "workspaceImport", - "workspaceImportStalled", - EngineLog::WorkspaceStalled.with_fields(fields), - "Java workspace import has not reported progress; still waiting for ServiceReady", - Some(detail), - ); - } - } - } - let expired: Vec<_> = state .pending .iter() .filter(|(_, pending)| { matches!( pending.kind, - PendingKind::Feature - | PendingKind::VirtualDocument - | PendingKind::JavaEntrypoints - | PendingKind::JavaTestItems - | PendingKind::JavaMainMethods - | PendingKind::JavaNavigationMarkers - | PendingKind::JavaNavigationMarkerResolve - | PendingKind::JavaResolveNavigation - | PendingKind::PluginServer + PendingKind::Feature | PendingKind::PluginServer ) && now >= pending.deadline }) .map(|(id, _)| id.clone()) @@ -6390,7 +3787,6 @@ impl RuntimeSession { if let Some(operation_id) = pending.operation_id.as_deref() { state.request_by_operation.remove(operation_id); state.function_by_operation.remove(operation_id); - state.java_navigation_marker_batches.remove(operation_id); let elapsed = now.saturating_duration_since(pending.created_at); let error = runtime_error( self, @@ -6439,159 +3835,21 @@ impl RuntimeSession { Some(error), ); } - let maven_profiles_running = - state.maven_profile_status == MavenProfileTaskStatus::Running; - let departure = state.java_builds.expire(maven_profiles_running, now); - let mut waiting = std::mem::take(&mut state.java_entrypoint_waiters); - while let Some(waiter) = waiting.pop_front() { - if now < waiter.deadline { - state.java_entrypoint_waiters.push_back(waiter); - continue; - } - let error = runtime_error( + if state.lifecycle == LspLifecycleState::Stopping + && state + .shutdown_deadline + .is_some_and(|deadline| now >= deadline) + { + state.shutdown_deadline = None; + shutdown_timeout = true; + push_issue_log_event( self, - "requestTimeout", - "javaProjectConfiguration", - Some(JAVA_BUILD_METHOD), - None, - "Java entry-point discovery timed out waiting for project configuration.", - Some(&format!( - "elapsedMilliseconds={}", - now.saturating_duration_since(waiter.created_at).as_millis() - )), - None, - ); - push_request_event( - self, - &mut state, - &waiter.operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - } - for waiter in &departure.expired { - let error = runtime_error( - self, - "requestTimeout", - "javaBuild", - Some(JAVA_BUILD_METHOD), - None, - "The Java project build did not finish in time.", - Some(&format!( - "elapsedMilliseconds={}, phase={}", - waiter.elapsed.as_millis(), - waiter.phase - )), - None, - ); - push_request_event( - self, - &mut state, - &waiter.operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - } - // Advisory: the in-flight slot remains until JDT answers. - cancellations.extend(departure.cancel_request_id); - let expired_maven_requests: Vec<_> = state - .pending - .iter() - .filter(|(_, pending)| { - state.maven_profile_status == MavenProfileTaskStatus::Running - && pending.kind == PendingKind::JdtMavenProfiles - && now >= pending.deadline - }) - .map(|(id, _)| id.clone()) - .collect(); - if !expired_maven_requests.is_empty() { - maven_context_timeout = true; - state.maven_profile_queue.clear(); - state.maven_profile_deadline = None; - let timed_out_projects: Vec<_> = state - .maven_profile_results - .values_mut() - .filter_map(|result| { - if result.status == MavenProfileTaskStatus::Running { - result.status = MavenProfileTaskStatus::TimedOut; - result.error_details = - Some("Maven profile project update timed out.".to_string()); - Some((result.project_uri.clone(), result.error_details.clone())) - } else { - None - } - }) - .collect(); - for (project_uri, error_details) in timed_out_projects { - let detail = serde_json::to_string(&json!({ - "projectUri": redacted_project_uri(&project_uri), - "status": MavenProfileTaskStatus::TimedOut, - "errorDetails": error_details, - })) - .expect("JSON values serialize without fallible map keys"); - push_issue_log_event( - self, - &mut state, - "error", - "mavenProfile", - "mavenProfileUpdateFailed", - EngineLog::MavenProjectFinished.with_fields(json!({"projectUri": redacted_project_uri(&project_uri), "status": MavenProfileTaskStatus::TimedOut})), - "Maven profile project update completed", - Some(detail), - ); - push_maven_profile_project_event( - self, - &mut state, - MavenProfileProjectResult { - project_uri, - status: MavenProfileTaskStatus::TimedOut, - error_details, - }, - ); - } - let succeeded = state - .maven_profile_results - .values() - .filter(|result| result.status == MavenProfileTaskStatus::Succeeded) - .count(); - let timed_out = state - .maven_profile_results - .values() - .filter(|result| result.status == MavenProfileTaskStatus::TimedOut) - .count(); - state.maven_profile_status = if succeeded == 0 && timed_out > 0 { - MavenProfileTaskStatus::TimedOut - } else if timed_out > 0 { - MavenProfileTaskStatus::PartiallySucceeded - } else { - MavenProfileTaskStatus::Failed - }; - let task_status = state.maven_profile_status; - push_maven_profile_task_event(self, &mut state, task_status); - state.maven_profile_applied_fingerprint = None; - for request_id in expired_maven_requests { - // Cancellation is advisory. Retain the in-flight slot until - // the server responds so retry cannot overlap the old batch. - cancellations.push(request_id); - } - } - if state.lifecycle == LspLifecycleState::Stopping - && state - .shutdown_deadline - .is_some_and(|deadline| now >= deadline) - { - state.shutdown_deadline = None; - shutdown_timeout = true; - push_issue_log_event( - self, - &mut state, - "warning", - "shutdown", - "shutdownTimeout", - EngineLog::ShutdownTimedOut, - "Language-server shutdown timed out; forcing termination", + &mut state, + "warning", + "shutdown", + "shutdownTimeout", + EngineLog::ShutdownTimedOut, + "Language-server shutdown timed out; forcing termination", None, ); } @@ -6626,28 +3884,6 @@ impl RuntimeSession { None, ); self.kill_process(); - } else if let Some(detail) = service_ready_timeout { - self.fail( - "serviceReadyTimeout", - "serviceReady", - "Java language service project import timed out.", - Some(detail), - None, - ); - self.kill_process(); - } else if maven_context_timeout { - if let Ok(mut state) = self.lock_state() { - push_issue_log_event( - self, - &mut state, - "error", - "mavenProfile", - "mavenProfileTimeout", - EngineLog::MavenTimedOut, - "JDT LS Maven profile application timed out; session remains available", - None, - ); - } } else if shutdown_timeout { self.kill_process(); } @@ -6726,7 +3962,6 @@ impl RuntimeSession { if let Some(operation_id) = pending.operation_id.as_deref() { state.request_by_operation.remove(operation_id); state.function_by_operation.remove(operation_id); - state.java_navigation_marker_batches.remove(operation_id); let error = runtime_error( self, code, @@ -6979,33 +4214,9 @@ fn validate_start_request(request: &StartServerRequest) -> Result<(), CoreError> if !request.root_uri.contains("://") || request.root_uri.contains('\0') { return Err(invalid_field("rootUri")); } - if let Some(resources) = &request.jdtls_launch_resources { - if !request.provider_id.trim().eq_ignore_ascii_case("java") { - return Err(invalid_field("jdtlsLaunchResources/providerId")); - } - if !is_valid_process_path(request.runtime_executable_path.as_deref()) - || !is_valid_process_path(Some(&resources.launcher_jar_path)) - || !is_valid_process_path(Some(&resources.configuration_directory)) - || !is_valid_process_path(Some(&resources.lombok_agent_path)) - || resources - .java_debug_bundle_path - .as_deref() - .is_some_and(|path| !is_valid_process_path(Some(path))) - || resources - .java_extension_bundle_paths - .iter() - .any(|path| !is_valid_process_path(Some(path))) - { - return Err(invalid_field("jdtlsLaunchResources/runtimeExecutablePath")); - } - } Ok(()) } -fn is_valid_process_path(path: Option<&str>) -> bool { - path.is_some_and(|path| !path.trim().is_empty() && !path.contains('\0')) -} - fn invalid_field(field: &str) -> CoreError { CoreError::new( ErrorCode::InvalidRequest, @@ -7043,21 +4254,6 @@ fn ensure_not_terminal(lifecycle: LspLifecycleState) -> Result<(), CoreError> { } } -/// Wall-clock seconds used only to age cache directories; a clock before the -/// Unix epoch makes every area look freshly used rather than expired. -fn unix_seconds_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |elapsed| elapsed.as_secs()) -} - -fn java_executable_from_environment(environment: &BTreeMap) -> Option { - environment.get("JAVA_HOME").map(|home| { - let executable = if cfg!(windows) { "java.exe" } else { "java" }; - Path::new(home).join("bin").join(executable) - }) -} - /// The file a `file:` URI resolves to once symbolic links are followed, or /// `None` for other schemes and for files that do not exist. fn resolved_file_of_uri(uri: &str) -> Option { @@ -7106,8 +4302,8 @@ impl LinkedDocumentPaths { /// Re-addresses published diagnostics to the open document they describe. /// /// A server reports a file at its resolved location while the host may have -/// opened it through a symbolic link (JDT answers `/private/tmp/...` for a -/// document opened as `/tmp/...` on macOS). The client reducer matches URIs +/// opened it through a symbolic link (a server may answer `/private/tmp/...` +/// for a document opened as `/tmp/...` on macOS). The client reducer matches URIs /// textually and would drop such diagnostics, so when no open document carries /// the published URI this returns the message rewritten to the URI of the open /// document that resolves to the same file. Returns `None` when the message @@ -7155,7 +4351,7 @@ fn canonical_workspace_path(root_uri: &str) -> Option { fn canonical_workspace_root(root_uri: &str) -> Option { let canonical = canonical_workspace_path(root_uri)?; let canonical = canonical.to_string_lossy().replace('\\', "/"); - // Windows canonical paths carry a verbatim `\\?\` prefix that JDT never reports. + // Windows canonical paths carry a verbatim `\\?\` prefix that language servers never report. Some( canonical .strip_prefix("//?/UNC/") @@ -7174,17 +4370,12 @@ fn semantic_method(operation: LspSemanticOperation) -> &'static str { LspSemanticOperation::TypeDefinition => "textDocument/typeDefinition", LspSemanticOperation::References => "textDocument/references", LspSemanticOperation::Implementation => "textDocument/implementation", - LspSemanticOperation::JavaSuperImplementation => "java/findLinks", LspSemanticOperation::Rename => "textDocument/rename", LspSemanticOperation::Formatting => "textDocument/formatting", LspSemanticOperation::CodeActions => "textDocument/codeAction", LspSemanticOperation::ResolveCompletion => "completionItem/resolve", LspSemanticOperation::ResolveCodeAction => "codeAction/resolve", - LspSemanticOperation::ExecuteCommand - | LspSemanticOperation::VirtualDocument - | LspSemanticOperation::JavaEntrypoints - | LspSemanticOperation::JavaTestItems - | LspSemanticOperation::JavaMainMethods => "workspace/executeCommand", + LspSemanticOperation::ExecuteCommand => "workspace/executeCommand", LspSemanticOperation::InlayHints => "textDocument/inlayHint", LspSemanticOperation::FoldingRanges => "textDocument/foldingRange", LspSemanticOperation::SemanticTokens => "textDocument/semanticTokens/full", @@ -7201,17 +4392,12 @@ fn semantic_capability(operation: LspSemanticOperation) -> Option<&'static str> LspSemanticOperation::TypeDefinition => Some("typeDefinition"), LspSemanticOperation::References => Some("references"), LspSemanticOperation::Implementation => Some("implementation"), - LspSemanticOperation::JavaSuperImplementation => Some("definition"), LspSemanticOperation::Rename => Some("rename"), LspSemanticOperation::Formatting => Some("formatting"), LspSemanticOperation::CodeActions => Some("codeActions"), LspSemanticOperation::ResolveCompletion => Some("completionResolve"), LspSemanticOperation::ResolveCodeAction => Some("codeActionResolve"), - LspSemanticOperation::ExecuteCommand - | LspSemanticOperation::VirtualDocument - | LspSemanticOperation::JavaEntrypoints - | LspSemanticOperation::JavaTestItems - | LspSemanticOperation::JavaMainMethods => Some("executeCommand"), + LspSemanticOperation::ExecuteCommand => Some("executeCommand"), LspSemanticOperation::InlayHints => Some("inlayHints"), LspSemanticOperation::FoldingRanges => Some("foldingRanges"), LspSemanticOperation::SemanticTokens => Some("semanticTokens"), @@ -7219,117 +4405,6 @@ fn semantic_capability(operation: LspSemanticOperation) -> Option<&'static str> } } -fn queue_next_java_marker_resolve( - state: &mut SessionState, - operation_id: &str, - pending: &PendingRequest, - outbound: &mut Vec, -) -> Result { - let next = state - .java_navigation_marker_batches - .get_mut(operation_id) - .and_then(JavaNavigationMarkerBatch::take_next); - let Some(task) = next else { - return Ok(false); - }; - let uri = pending.document_uri.as_deref().unwrap_or_default(); - let (method, params) = task.request(uri); - let response = allocate_raw_request(state.client.clone(), method, params)?; - let request_id = (response.state.next_request_id - 1).to_string(); - let (created_at, deadline) = state - .java_navigation_marker_batches - .get(operation_id) - .map(|batch| (batch.created_at(), batch.deadline())) - .unwrap_or((pending.created_at, pending.deadline)); - state.client = response.state; - state.pending.insert( - request_id.clone(), - PendingRequest { - kind: PendingKind::JavaNavigationMarkerResolve, - operation_id: Some(operation_id.to_string()), - method: method.to_string(), - document_uri: pending.document_uri.clone(), - document_version: pending.document_version, - created_at, - deadline, - }, - ); - state - .request_by_operation - .insert(operation_id.to_string(), request_id); - outbound.extend(response.messages); - Ok(true) -} - -fn finish_java_navigation_marker_batch( - session: &RuntimeSession, - state: &mut SessionState, - operation_id: &str, - pending: &PendingRequest, -) { - let Some(batch) = state.java_navigation_marker_batches.remove(operation_id) else { - return; - }; - state.request_by_operation.remove(operation_id); - state.function_by_operation.remove(operation_id); - let source = pending - .document_uri - .as_deref() - .and_then(|uri| state.client.open_documents.get(uri)) - .map(|document| document.text.clone()) - .unwrap_or_default(); - let created_at = batch.created_at(); - let total_tasks = batch.total_tasks(); - let resolved_lens_count = batch.resolved_lens_count(); - let markers = batch.finish(&source); - if let (Some(uri), Some(document_version)) = - (pending.document_uri.as_ref(), pending.document_version) - { - let is_current = state - .client - .open_documents - .get(uri) - .is_some_and(|document| document.version.max(1) == document_version); - if is_current { - state.java_navigation_marker_cache.insert( - uri.clone(), - JavaNavigationMarkerCacheEntry { - document_version, - markers: markers.clone(), - }, - ); - } - } - let elapsed = Instant::now().saturating_duration_since(created_at); - push_log_event( - session, - state, - "debug", - EngineLog::NavigationResolved.with_fields(json!({"operationId": operation_id, "document": pending.document_uri, "document_version": pending.document_version, "duration_ms": elapsed.as_millis() as u64, "tasks": total_tasks, "code_lenses": resolved_lens_count, "markers": markers.len()})), - "Java navigation markers resolved", - Some(format!( - "operationId={operation_id}, uri={}, documentVersion={}, durationMilliseconds={}, tasks={}, codeLenses={}, markers={}", - pending.document_uri.as_deref().unwrap_or(""), - pending.document_version.unwrap_or_default(), - elapsed.as_millis(), - total_tasks, - resolved_lens_count, - markers.len() - )), - ); - push_request_event( - session, - state, - operation_id, - "textDocument/codeLens", - Some(json!({ - "documentVersion": pending.document_version, - "markers": markers - })), - None, - ); -} - fn allocate_raw_request( mut state: LspClientState, method: &str, @@ -7384,21 +4459,11 @@ fn enqueue_runtime_event( state: &mut SessionState, mut event: LspRuntimeEvent, ) { - if event.event.is_some() - || event.maven_profile_project.is_some() - || event.maven_profile_task.is_some() - { - let (id, fields) = if let Some(result) = &event.maven_profile_project { - EngineLog::maven_project_fact(&session.log_identity, result) - } else if let Some(status) = event.maven_profile_task { - let input = json!({"state": status}); - EngineLog::MavenTaskUpdated.fact(&session.log_identity, &input, None) - } else { - ( - event.event.take().expect("source catalog identity"), - event.fields.take().expect("source catalog fields"), - ) - }; + if event.event.is_some() { + let (id, fields) = ( + event.event.take().expect("source catalog identity"), + event.fields.take().expect("source catalog fields"), + ); let level = if id == "log.dropped" { Some(crate::diagnostics::record::LogLevel::Warn) } else { @@ -7432,64 +4497,6 @@ fn enqueue_runtime_event( } } state.events.push_back(event); - refresh_project_preparation(session, state); - session.event_signal.notify_all(); -} - -// Reuse the build coordinator's gate; never infer readiness from a log message. -/// The configuration barrier is shared by discovery and the following build. -fn java_configuration_running(state: &mut SessionState, now: Instant) -> bool { - state.maven_profile_update_pending - || state.maven_profile_status == MavenProfileTaskStatus::Running - || state.java_builds.project_configuration_running(now) -} - -fn refresh_project_preparation(session: &RuntimeSession, state: &mut SessionState) { - if session.provider_id != "java" { - return; - } - let configuring = state - .java_builds - .project_configuration_running(Instant::now()); - let snapshot = crate::lsp::languages::project_preparation::snapshot( - state.lifecycle, - state.maven_profile_status, - configuring, - state.java_builds.in_flight_request_id().is_some(), - ); - if state.preparation_snapshot.as_ref() == Some(&snapshot) { - return; - } - let result = json!(snapshot); - state.preparation_snapshot = Some(snapshot); - let sequence = take_sequence(state); - state.events.push_back(LspRuntimeEvent { - kind: "projectPreparation".to_string(), - channel: None, - plugin_id: None, - role: None, - event: None, - fields: None, - catalog_level: None, - sequence, - provider_id: session.provider_id.clone(), - session_id: session.id.clone(), - state: None, - operation_id: None, - method: None, - uri: None, - version: None, - diagnostics: None, - result: Some(result), - error: None, - capabilities: None, - server_info: None, - level: None, - message: None, - detail: None, - maven_profile_project: None, - maven_profile_task: None, - }); session.event_signal.notify_all(); } @@ -7530,8 +4537,6 @@ fn push_cleanup_fact( level: Some("warning".to_string()), message: Some("Engine process cleanup failed".to_string()), detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -7597,8 +4602,6 @@ fn transition_locked( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -7629,87 +4632,6 @@ fn push_request_event( ); return; } - let (result, error) = if let Some(mut preparation) = state.java_launches.remove(operation_id) { - match preparation.advance(result, error) { - Ok(JavaLaunchAction::Build(command)) => { - state.java_builds.enqueue( - operation_id.to_string(), - command, - Instant::now(), - state.java_build_timeout, - ); - state - .java_launches - .insert(operation_id.to_string(), preparation); - return; - } - Ok(JavaLaunchAction::Classpath(command)) => { - match allocate_raw_request( - state.client.clone(), - "workspace/executeCommand", - command, - ) { - Ok(response) => { - let request_id = (response.state.next_request_id - 1).to_string(); - let now = Instant::now(); - state.client = response.state; - state.pending.insert( - request_id.clone(), - PendingRequest { - kind: PendingKind::Feature, - operation_id: Some(operation_id.to_string()), - method: "workspace/executeCommand".to_string(), - document_uri: None, - document_version: None, - created_at: now, - deadline: now + state.request_timeout, - }, - ); - state - .request_by_operation - .insert(operation_id.to_string(), request_id.clone()); - state - .java_launch_messages - .push((request_id, response.messages)); - state - .java_launches - .insert(operation_id.to_string(), preparation); - return; - } - Err(error) => ( - None, - Some(runtime_error( - session, - "invalidServerResult", - "javaLaunch", - Some(method), - None, - &error.message, - None, - None, - )), - ), - } - } - Ok(JavaLaunchAction::Complete(result)) => (Some(result), None), - Err(JavaLaunchFailure::Upstream(error)) => (None, Some(error)), - Err(JavaLaunchFailure::Invalid(message)) => ( - None, - Some(runtime_error( - session, - "invalidServerResult", - "javaLaunch", - Some(method), - None, - message, - None, - None, - )), - ), - } - } else { - (result, error) - }; enqueue_request_completed(session, state, operation_id, method, result, error); } @@ -7783,8 +4705,6 @@ fn enqueue_request_completed( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -7916,8 +4836,6 @@ fn push_build_progress_locked( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -7976,8 +4894,6 @@ fn push_function_progress_locked( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8013,8 +4929,6 @@ fn push_vcs_provider_event(session: &RuntimeSession, state: &mut SessionState, r level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8054,8 +4968,6 @@ fn push_negotiated_provider_event( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8127,8 +5039,6 @@ fn cancel_host_request_locked( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); Ok(true) @@ -8196,8 +5106,6 @@ fn forward_host_request_locked( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); Ok(Vec::new()) @@ -8232,8 +5140,6 @@ fn push_functions_event(session: &RuntimeSession, state: &mut SessionState, resu level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8450,47 +5356,6 @@ fn plugin_server_answer( (Some(json!({ "value": result })), None) } -fn normalize_provider_navigation_result( - provider_id: &str, - mut result: Option, -) -> Option { - let locations = result - .as_mut() - .and_then(|result| result.get_mut("locations")) - .and_then(Value::as_array_mut); - let Some(locations) = locations else { - return result; - }; - - for location in locations { - let Some(uri) = location - .get("uri") - .and_then(Value::as_str) - .map(ToString::to_string) - else { - continue; - }; - let normalized = normalize_location( - provider_id, - ProviderLocation { - uri, - is_read_only: location - .get("isReadOnly") - .and_then(Value::as_bool) - .unwrap_or(false), - display_path: location - .get("displayPath") - .and_then(Value::as_str) - .map(ToString::to_string), - }, - ); - location["isReadOnly"] = Value::Bool(normalized.is_read_only); - location["displayPath"] = normalized.display_path.map_or(Value::Null, Value::String); - } - - result -} - fn cancel_stale_document_requests_locked( session: &RuntimeSession, state: &mut SessionState, @@ -8519,7 +5384,6 @@ fn cancel_stale_document_requests_locked( if let Some(operation_id) = pending.operation_id.as_deref() { state.request_by_operation.remove(operation_id); state.function_by_operation.remove(operation_id); - state.java_navigation_marker_batches.remove(operation_id); let error = runtime_error( session, "staleDocumentVersion", @@ -8561,7 +5425,6 @@ fn is_stale_sensitive_method(method: &str) -> bool { | "textDocument/codeLens" | "codeLens/resolve" | "textDocument/implementation" - | "java/findLinks" ) } @@ -8600,8 +5463,6 @@ fn push_diagnostics_event( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8635,8 +5496,6 @@ fn push_semantic_tokens_refresh_event(session: &RuntimeSession, state: &mut Sess level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8674,8 +5533,6 @@ fn push_features_event( level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8709,8 +5566,6 @@ fn push_server_info_event(session: &RuntimeSession, state: &mut SessionState, in level: None, message: None, detail: None, - maven_profile_project: None, - maven_profile_task: None, }, ); } @@ -8860,197 +5715,56 @@ fn push_classified_log_event( level: Some(level.to_string()), message: Some(message.to_string()), detail: detail.filter(|value| !value.is_empty()), - maven_profile_project: None, - maven_profile_task: None, }, ); } -fn push_maven_profile_project_event( +fn take_sequence(state: &mut SessionState) -> u64 { + let sequence = state.next_sequence; + state.next_sequence += 1; + sequence +} + +fn runtime_error( session: &RuntimeSession, - state: &mut SessionState, - mut result: MavenProfileProjectResult, -) { - // The structured event is consumed by both hosts and may be persisted by - // UI state, so keep the same redacted project identity as ordinary logs. - result.project_uri = redacted_project_uri(&result.project_uri); - let sequence = take_sequence(state); - enqueue_runtime_event( - session, - state, - LspRuntimeEvent { - kind: "log".to_string(), - channel: None, - plugin_id: None, - role: None, - event: None, - fields: None, - catalog_level: None, - sequence, - provider_id: session.provider_id.clone(), - session_id: session.id.clone(), - state: None, - operation_id: None, - method: None, - uri: None, - version: None, - diagnostics: None, - result: None, - error: None, - capabilities: None, - server_info: None, - level: Some( - match result.status { - MavenProfileTaskStatus::Failed | MavenProfileTaskStatus::TimedOut => "error", - MavenProfileTaskStatus::PartiallySucceeded => "warning", - _ => "info", - } - .to_string(), - ), - message: Some( - match result.status { - MavenProfileTaskStatus::Running => "Maven profile project update running", - MavenProfileTaskStatus::Failed => "Maven profile project update failed", - MavenProfileTaskStatus::TimedOut => "Maven profile project update timed out", - MavenProfileTaskStatus::Cancelled => "Maven profile project update cancelled", - _ => "Maven profile project update completed", - } - .to_string(), - ), - detail: None, - maven_profile_project: Some(result), - maven_profile_task: None, - }, - ); + code: &str, + stage: &str, + method: Option<&str>, + document_uri: Option<&str>, + message: &str, + underlying: Option<&str>, + process_exit_code: Option, +) -> LspRuntimeError { + LspRuntimeError { + code: code.to_string(), + provider_id: session.provider_id.clone(), + session_id: session.id.clone(), + stage: stage.to_string(), + method: method.map(ToString::to_string), + document_uri: document_uri.map(ToString::to_string), + message: message.to_string(), + underlying_message: underlying.map(ToString::to_string), + process_exit_code, + plugin_error_code: None, + details: None, + } } -fn push_maven_profile_task_event( +fn fail_feature_requests( session: &RuntimeSession, state: &mut SessionState, - status: MavenProfileTaskStatus, + code: &str, + stage: &str, + message: &str, + exit_code: Option, ) { - let sequence = take_sequence(state); - enqueue_runtime_event( - session, - state, - LspRuntimeEvent { - kind: "log".to_string(), - channel: None, - plugin_id: None, - role: None, - event: None, - fields: None, - catalog_level: None, - sequence, - provider_id: session.provider_id.clone(), - session_id: session.id.clone(), - state: None, - operation_id: None, - method: None, - uri: None, - version: None, - diagnostics: None, - result: None, - error: None, - capabilities: None, - server_info: None, - level: Some("info".to_string()), - message: Some("Maven profile task state changed".to_string()), - detail: None, - maven_profile_project: None, - maven_profile_task: Some(status), - }, - ); -} - -/// Keeps Maven project diagnostics useful while omitting the user's absolute -/// workspace path from the persisted runtime log. -fn redacted_project_uri(uri: &str) -> String { - let trimmed = uri.trim_end_matches('/'); - let name = trimmed.rsplit('/').next().filter(|value| !value.is_empty()); - let digest = Sha256::digest(uri.as_bytes()); - let suffix = format!("{:x}", digest)[..8].to_string(); - match name { - Some(name) => format!("file:///{name}-{suffix}"), - None => format!("file:///workspace-{suffix}"), - } -} - -fn take_sequence(state: &mut SessionState) -> u64 { - let sequence = state.next_sequence; - state.next_sequence += 1; - sequence -} - -fn runtime_error( - session: &RuntimeSession, - code: &str, - stage: &str, - method: Option<&str>, - document_uri: Option<&str>, - message: &str, - underlying: Option<&str>, - process_exit_code: Option, -) -> LspRuntimeError { - LspRuntimeError { - code: code.to_string(), - provider_id: session.provider_id.clone(), - session_id: session.id.clone(), - stage: stage.to_string(), - method: method.map(ToString::to_string), - document_uri: document_uri.map(ToString::to_string), - message: message.to_string(), - underlying_message: underlying.map(ToString::to_string), - process_exit_code, - java_build_report: None, - plugin_error_code: None, - details: None, - } -} - -fn fail_feature_requests( - session: &RuntimeSession, - state: &mut SessionState, - code: &str, - stage: &str, - message: &str, - exit_code: Option, -) { - for waiter in std::mem::take(&mut state.java_entrypoint_waiters) { - let error = runtime_error( - session, - code, - stage, - Some(JAVA_BUILD_METHOD), - None, - message, - None, - exit_code, - ); - push_request_event( - session, - state, - &waiter.operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - } let pending: Vec<_> = state .pending .iter() .filter(|(_, pending)| { matches!( pending.kind, - PendingKind::Feature - | PendingKind::VirtualDocument - | PendingKind::JavaEntrypoints - | PendingKind::JavaTestItems - | PendingKind::JavaMainMethods - | PendingKind::JavaNavigationMarkers - | PendingKind::JavaNavigationMarkerResolve - | PendingKind::JavaResolveNavigation - | PendingKind::PluginServer + PendingKind::Feature | PendingKind::PluginServer ) }) .map(|(request_id, pending)| (request_id.clone(), pending.clone())) @@ -9062,7 +5776,6 @@ fn fail_feature_requests( if let Some(operation_id) = pending.operation_id.as_deref() { state.request_by_operation.remove(operation_id); state.function_by_operation.remove(operation_id); - state.java_navigation_marker_batches.remove(operation_id); let error = runtime_error( session, code, @@ -9109,47 +5822,6 @@ fn fail_feature_requests( 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); - state.client.pending_requests.remove(&request_id); - } - for operation_id in build_operation_ids { - let error = runtime_error( - session, - code, - stage, - Some(JAVA_BUILD_METHOD), - None, - message, - None, - exit_code, - ); - push_request_event( - session, - state, - &operation_id, - JAVA_BUILD_METHOD, - None, - Some(error), - ); - } -} - -/// Serializes the advisory JDT cancellation a departure requires, if any. -fn java_build_cancellation(departure: JavaBuildDeparture) -> Vec { - departure - .cancel_request_id - .map(|id| { - json!({ - "jsonrpc": "2.0", - "method": "$/cancelRequest", - "params": { "id": id } - }) - .to_string() - }) - .into_iter() - .collect() } fn clear_runtime_diagnostics(session: &RuntimeSession, state: &mut SessionState) { @@ -9191,18 +5863,10 @@ fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionState) { state.client.toolchain_providers.clear(); state.client.keymap_import_providers.clear(); state.linked_document_paths = LinkedDocumentPaths::default(); - state.java_navigation_marker_batches.clear(); - state.java_navigation_marker_cache.clear(); - state.java_builds = JavaBuildCoordinator::default(); - state.java_entrypoint_waiters.clear(); - state.java_launches.clear(); - state.java_launch_messages.clear(); state.deadline_cancellations.clear(); state.maintenance_write_deadline = None; state.relay_write_deadline = None; state.pending_workspace_file_changes.clear(); - state.maven_profile_update_pending = false; - state.maven_project_reload_pending = false; state.initialize_deadline = None; state.shutdown_deadline = None; push_features_event(session, state, Vec::new()); @@ -9283,10 +5947,6 @@ fn workspace_file_changes_notification( #[path = "engine_function_relay_tests.rs"] mod function_relay_tests; -#[cfg(test)] -#[path = "engine_real_jdt_tests.rs"] -mod real_jdt_tests; - #[cfg(test)] mod tests { use super::super::scripted::ScriptedServer; @@ -9302,24 +5962,9 @@ mod tests { }) } - /// Contents of the one file Core reads from a packaged configuration directory. - const PACKAGED_JDTLS_CONFIG_INI: &str = - "osgi.bundles=reference\\:file\\:org.eclipse.jdt.ls.core_1.61.0.jar@4\\:start\n"; - - /// Creates `installation/jdtls/config_mac` holding only the shipped `config.ini`. - fn packaged_jdtls_configuration(installation: &Path) -> PathBuf { - let configuration = installation.join("jdtls").join("config_mac"); - std::fs::create_dir_all(&configuration).expect("packaged configuration should be created"); - std::fs::write(configuration.join("config.ini"), PACKAGED_JDTLS_CONFIG_INI) - .expect("packaged config.ini should be written"); - configuration - } - pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest { let _ = server; StartServerRequest { - // A non-Java provider keeps JDT argument adaptation out of the way; - // `adapt_start` is covered by its own tests. provider_id: "gopls".to_string(), role: SessionRole::LanguageServer, log_subject: None, @@ -9337,18 +5982,8 @@ mod tests { working_directory: "/workspace".to_string(), initialization_options: None, workspace_configuration: None, - runtime_executable_path: None, - jdtls_launch_resources: None, - cache_directory: None, - workspace_fingerprint: None, - maven_context: None, - java_runtimes: Vec::new(), - java_gradle: None, initialize_timeout_milliseconds: 10_000, - service_ready_idle_timeout_milliseconds: 45_000, - service_ready_absolute_timeout_milliseconds: 600_000, request_timeout_milliseconds: 10_000, - java_build_timeout_milliseconds: DEFAULT_JAVA_BUILD_TIMEOUT_MS, shutdown_timeout_milliseconds: 10_000, } } @@ -9462,7 +6097,7 @@ mod tests { let mut request = start_request(&server); request.workspace_configuration = Some(json!(["not an object"])); assert!(engine.start_server(request).is_err()); - assert!(server.launched_spec().is_none()); + assert!(!server.was_launched()); } /// An engine with a scripted server behind it, plus the started session. @@ -9512,11 +6147,12 @@ mod tests { } } - struct TemporaryMavenWorkspace { + /// A throw-away workspace with a nested directory tree, removed on drop. + struct TemporaryWorkspace { root: PathBuf, } - impl TemporaryMavenWorkspace { + impl TemporaryWorkspace { fn recursive(label: &str) -> Self { static NEXT_ID: AtomicU64 = AtomicU64::new(1); let root = std::env::temp_dir().join(format!( @@ -9525,73 +6161,24 @@ mod tests { NEXT_ID.fetch_add(1, Ordering::Relaxed) )); std::fs::create_dir_all(root.join("reactor/module-a/nested")) - .expect("recursive Maven fixture should be creatable"); + .expect("nested fixture should be creatable"); std::fs::write( - root.join("reactor/pom.xml"), - r#"reactorpommodule-a"#, + root.join("reactor/module-a/nested/main.go"), + "package main\n", ) - .expect("reactor pom should be writable"); - std::fs::write( - root.join("reactor/module-a/pom.xml"), - r#"module-apomnested"#, - ) - .expect("module pom should be writable"); - std::fs::write( - root.join("reactor/module-a/nested/pom.xml"), - r#"nested"#, - ) - .expect("nested module pom should be writable"); + .expect("fixture file should be writable"); Self { root } } fn configure(&self, request: &mut StartServerRequest) { - request.provider_id = "java".to_string(); request.root_uri = url::Url::from_directory_path(&self.root) .expect("fixture root should convert to a URI") .to_string(); request.working_directory = self.root.to_string_lossy().into_owned(); - request.cache_directory = Some(self.root.join("cache").to_string_lossy().into_owned()); - request.maven_context = Some(crate::project::MavenLaunchContextRequest { - version: 1, - reactor_path: "reactor".to_string(), - profiles: vec![ - "enterprise".to_string(), - "dev".to_string(), - "enterprise".to_string(), - ], - settings_path: Some("/local/settings.xml".to_string()), - local_repository_path: None, - skip_tests: true, - maven_executable_path: Some("/local/maven/bin/mvn".to_string()), - java_home_path: Some("/local/jdk".to_string()), - }); - } - } - - impl TemporaryMavenWorkspace { - /// The fixture's Maven context with a real settings file and the given - /// local repository override. - fn context_with_settings( - &self, - settings: &str, - local_repository: Option<&str>, - ) -> crate::project::MavenLaunchContextRequest { - let settings_path = self.root.join("settings.xml"); - std::fs::write(&settings_path, settings).expect("settings fixture should be writable"); - crate::project::MavenLaunchContextRequest { - version: 1, - reactor_path: "reactor".to_string(), - profiles: vec!["dev".to_string()], - settings_path: Some(settings_path.to_string_lossy().into_owned()), - local_repository_path: local_repository.map(ToString::to_string), - skip_tests: true, - maven_executable_path: None, - java_home_path: None, - } } } - impl Drop for TemporaryMavenWorkspace { + impl Drop for TemporaryWorkspace { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.root); } @@ -9699,7 +6286,6 @@ mod tests { operation_id: Some(operation_id.clone()), operation, uri: Some(uri.to_string()), - virtual_uri: None, position: Some(LspPosition { line: 0, utf16_column: 0, @@ -9718,32 +6304,6 @@ mod tests { operation_id } - /// Issues a workspace `executeCommand` request and returns its operation ID. - fn execute_command(&self, command: Value) -> String { - let operation_id = self.engine.next_operation_id(); - self.session() - .request( - SemanticRequest { - session_id: self.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::ExecuteCommand, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: Some(command), - }, - operation_id.clone(), - ) - .expect("a ready session should accept the command"); - operation_id - } - /// The recorded JSON-RPC message with the given request ID. fn written_request(&self, request_id: &str) -> Value { self.server @@ -9762,146 +6322,6 @@ mod tests { } } - /// Owns an opt-in real-process smoke session and removes every temporary - /// resource even when the smoke test unwinds after a failed assertion. - pub(super) struct RealSmokeCleanup<'a> { - pub(super) engine: &'a LspEngine, - pub(super) session_id: String, - pub(super) root: PathBuf, - } - - impl Drop for RealSmokeCleanup<'_> { - fn drop(&mut self) { - if let Ok(session) = self.engine.session(&self.session_id) { - let _ = session.stop(); - let deadline = Instant::now() + Duration::from_secs(10); - while Instant::now() < deadline { - let terminal = session.snapshot().is_ok_and(|snapshot| { - matches!( - snapshot.state, - LspLifecycleState::Stopped | LspLifecycleState::Failed - ) - }); - if terminal { - break; - } - let _ = session.poll_events(); - thread::sleep(Duration::from_millis(20)); - } - if session.snapshot().is_ok_and(|snapshot| { - !matches!( - snapshot.state, - LspLifecycleState::Stopped | LspLifecycleState::Failed - ) - }) { - session.kill_process(); - } - } - let _ = self.engine.destroy(&self.session_id); - let _ = std::fs::remove_dir_all(&self.root); - } - } - - pub(super) fn await_real_smoke_ready( - session: &Arc, - ) -> Result, String> { - let deadline = Instant::now() + Duration::from_secs(90); - let mut events = Vec::new(); - while Instant::now() < deadline { - events.extend(session.poll_events().map_err(|error| error.message)?); - let snapshot = session.snapshot().map_err(|error| error.message)?; - match snapshot.state { - LspLifecycleState::Ready => { - events.extend(session.poll_events().map_err(|error| error.message)?); - return Ok(events); - } - LspLifecycleState::Failed => { - return Err(format!("JDTLS failed during initialization: {events:?}")); - } - _ => thread::sleep(Duration::from_millis(20)), - } - } - Err(format!( - "JDTLS did not become ready before the smoke timeout: {events:?}" - )) - } - - fn real_smoke_request( - engine: &LspEngine, - session: &Arc, - operation: LspSemanticOperation, - uri: Option<&str>, - virtual_uri: Option<&str>, - position: Option, - ) -> Result { - let operation_id = engine.next_operation_id(); - session - .request( - SemanticRequest { - session_id: session.id.clone(), - operation_id: Some(operation_id.clone()), - operation, - uri: uri.map(str::to_string), - virtual_uri: virtual_uri.map(str::to_string), - position, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .map_err(|error| error.message)?; - - let deadline = Instant::now() + Duration::from_secs(35); - while Instant::now() < deadline { - for event in session.poll_events().map_err(|error| error.message)? { - if event.operation_id.as_deref() != Some(operation_id.as_str()) { - continue; - } - if let Some(error) = event.error { - return Err(format!( - "JDTLS smoke request {} failed: {error:?}", - semantic_method(operation) - )); - } - return event.result.ok_or_else(|| { - format!( - "JDTLS smoke request {} returned no result", - semantic_method(operation) - ) - }); - } - thread::sleep(Duration::from_millis(20)); - } - Err(format!( - "JDTLS smoke request {} timed out", - semantic_method(operation) - )) - } - - fn real_smoke_locations(result: &Value) -> &[Value] { - result - .get("locations") - .and_then(Value::as_array) - .map(Vec::as_slice) - .unwrap_or_default() - } - - fn real_smoke_token_position(text: &str, marker: &str, token_offset: usize) -> LspPosition { - let marker_index = text.find(marker).expect("smoke marker should exist") + token_offset; - let prefix = &text[..marker_index]; - let line = prefix.bytes().filter(|byte| *byte == b'\n').count() as i64; - let line_prefix = prefix.rsplit_once('\n').map_or(prefix, |(_, tail)| tail); - LspPosition { - line, - utf16_column: line_prefix.encode_utf16().count() as i64, - } - } - /// Criterion 1: a spawned process that never initializes cannot become ready. #[test] fn a_server_that_never_answers_initialize_fails_instead_of_becoming_ready() { @@ -9960,5396 +6380,1693 @@ mod tests { ); } - #[test] - fn java_waits_for_service_ready_after_standard_initialize() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness + /// Messages the scripted server received for `method`, in order. + fn notifications(harness: &Harness, method: &str) -> Vec { + harness .server - .await_notification("workspace/didChangeConfiguration")); - - assert_eq!( - harness.snapshot().state, - LspLifecycleState::Initializing, - "the initialize response alone must not advertise a usable Java index" - ); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady", "message": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); + .messages() + .into_iter() + .filter(|message| message.get("method").and_then(Value::as_str) == Some(method)) + .collect() } #[test] - fn java_applies_maven_settings_and_recursive_profiles_before_ready() { - let workspace = TemporaryMavenWorkspace::recursive("maven-context-ready"); - let mut harness = Harness::start(|request| workspace.configure(request)); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - - let configuration = harness - .notification("workspace/didChangeConfiguration") - .expect("Java configuration notification should be sent"); - assert_eq!( - configuration["params"]["settings"]["java"]["configuration"]["maven"]["userSettings"], - "/local/settings.xml" - ); - assert_eq!( - configuration["params"]["settings"]["java"]["project"]["sourcePaths"], - json!([ - "reactor/module-a/nested/src/main/java", - "reactor/module-a/nested/src/test/java", - "reactor/module-a/nested/target/generated-sources", - "reactor/module-a/nested/target/generated-test-sources" - ]) + fn structured_logging_warnings_keep_source_stage_and_code() { + let harness = Harness::ready(); + let session = harness.session(); + session.log_issue( + "warn", + "processCleanup", + "processCleanupFailed", + EngineLog::ProcessCleanupFailed, + "Cleanup failed", + None, ); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - - let request_ids: Vec<_> = (0..3) - .map(|index| { - harness - .server - .await_request_at("workspace/executeCommand", index) - .expect("every recursive Maven project should receive its profile update") - }) - .collect(); - let updates: Vec<_> = harness - .server - .messages() - .into_iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) == Some("workspace/executeCommand") - }) - .collect(); - let expected_uris = ["reactor/", "reactor/module-a/", "reactor/module-a/nested/"]; - assert_eq!(updates.len(), expected_uris.len()); - for (update, expected_uri) in updates.iter().zip(expected_uris) { - let project_uri = update["params"]["arguments"][0] - .as_str() - .expect("the project URI should be a string"); - assert!( - project_uri.ends_with(expected_uri), - "unexpected URI: {project_uri}" - ); - assert_eq!( - update["params"]["arguments"][1]["org.eclipse.m2e.core.selectedProfiles"], - "dev,enterprise" - ); - } - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - for request_id in &request_ids[..2] { - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": null - })); - } - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "test/profile-response-barrier" - })); - harness - .await_event(|event| event.message.as_deref() == Some("test/profile-response-barrier")); - assert_eq!( - harness - .server - .messages() - .iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) - == Some("workspace/executeCommand") - }) - .count(), - 3, - "a duplicate readiness notification must not enqueue duplicate profile updates" - ); - assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); - let started_log = harness - .events - .iter() - .find(|event| { - event.message.as_deref() == Some("Applying Maven profiles to Java projects") - }) - .unwrap(); - assert_eq!(started_log.detail.as_deref(), Some("projectCount=3")); - assert_eq!(started_log.fields.as_ref().unwrap()["projects"], 3); - let completed_logs: Vec<_> = harness - .events - .iter() - .filter(|event| { - event.kind == "log" - && event.maven_profile_project.is_none() - && event.message.as_deref() == Some("Maven profile project update completed") - }) - .collect(); - assert_eq!(completed_logs.len(), 2); - assert!(completed_logs - .iter() - .all(|event| { event.level.as_deref() == Some("info") && event.error.is_none() })); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_ids[2], - "result": null - })); - harness.await_state(LspLifecycleState::Ready); - } - - #[test] - fn java_profile_update_error_keeps_the_session_available() { - let workspace = TemporaryMavenWorkspace::recursive("maven-context-failure"); - let mut harness = Harness::start(|request| workspace.configure(request)); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .expect("the Maven profile request should be sent"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "error": { "code": -32603, "message": "Maven project update failed" } - })); - let project_event = harness.await_event(|event| { - event - .maven_profile_project - .as_ref() - .is_some_and(|result| result.status == MavenProfileTaskStatus::Failed) - }); - assert_eq!( - project_event - .maven_profile_project - .as_ref() - .map(|result| result.status), - Some(MavenProfileTaskStatus::Failed) - ); - let project_uri = project_event - .maven_profile_project - .as_ref() - .map(|result| result.project_uri.as_str()) - .unwrap_or_default(); - assert!(!project_uri.contains("/Users/") && !project_uri.contains("\\Users\\")); - assert!(project_event.error.is_none()); - assert!(harness.events.iter().any(|event| { - event.kind == "log" - && event.level.as_deref() == Some("error") - && event.error.as_ref().is_some_and(|error| { - error.stage == "mavenProfile" && error.code == "mavenProfileUpdateFailed" - }) - })); - harness.await_state(LspLifecycleState::Ready); - assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); - } - - /// Messages the scripted server received for `method`, in order. - fn notifications(harness: &Harness, method: &str) -> Vec { - harness - .server - .messages() - .into_iter() - .filter(|message| message.get("method").and_then(Value::as_str) == Some(method)) - .collect() - } - - fn user_settings(notification: &Value) -> String { - notification["params"]["settings"]["java"]["configuration"]["maven"]["userSettings"] - .as_str() - .expect("userSettings should be a path") - .to_string() - } - - #[test] - fn a_maven_settings_change_reaches_the_running_java_session() { - // Regression for #970: saving Maven settings only marked a reload, and - // a restart reused the workspace state without re-resolving. The change - // must reach the live session as a new settings path, which is what - // makes JDT LS force-update every Maven project. - let workspace = TemporaryMavenWorkspace::recursive("maven-update-settings"); - let initial = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(initial.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let before = notifications(&harness, "workspace/didChangeConfiguration"); - assert_eq!(before.len(), 1); - let profile_updates = notifications(&harness, "workspace/executeCommand").len(); - - let mut changed = initial.clone(); - changed.local_repository_path = Some("/fixture/repository".to_string()); - let response = harness - .session() - .update_maven_configuration(changed, false) - .expect("a running Java session should accept the update"); - - assert_eq!( - response, - UpdateMavenConfigurationResponse { - settings_changed: true, - projects_reloaded: false, - profiles_updating: false, - } - ); - let after = notifications(&harness, "workspace/didChangeConfiguration"); - assert_eq!(after.len(), 2); - let (old_path, new_path) = (user_settings(&before[0]), user_settings(&after[1])); - assert_ne!( - old_path, new_path, - "a changed document must arrive under a new path" - ); - let document = std::fs::read_to_string(&new_path).expect("the new copy should exist"); - assert!(document.contains("/fixture/repository")); - assert_eq!( - notifications(&harness, "workspace/executeCommand").len(), - profile_updates, - "unchanged profiles must not restart the profile task" - ); - assert!(notifications(&harness, "java/projectConfigurationsUpdate").is_empty()); - } - - #[test] - fn an_explicit_maven_reload_forces_a_project_update_when_settings_are_unchanged() { - // JDT LS skips re-importing projects whose pom.xml did not change, so - // reloading must use its forced "update project" notification. - let workspace = TemporaryMavenWorkspace::recursive("maven-update-reload"); - let context = workspace.context_with_settings("", Some("/fixture/repository")); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(context.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - - let quiet = harness - .session() - .update_maven_configuration(context.clone(), false) - .expect("an unchanged update should be accepted"); - let reload = harness - .session() - .update_maven_configuration(context, true) - .expect("a reload should be accepted"); - - assert!(!quiet.settings_changed && !quiet.projects_reloaded); - assert!(!reload.settings_changed && reload.projects_reloaded); - assert_eq!( - notifications(&harness, "workspace/didChangeConfiguration").len(), - 1 - ); - let updates = notifications(&harness, "java/projectConfigurationsUpdate"); - assert_eq!( - updates.len(), - 1, - "only the explicit reload forces an update" - ); - let identifiers = updates[0]["params"]["identifiers"] - .as_array() - .expect("identifiers should be an array"); - let suffixes = ["reactor/", "reactor/module-a/", "reactor/module-a/nested/"]; - assert_eq!(identifiers.len(), suffixes.len()); - for (identifier, suffix) in identifiers.iter().zip(suffixes) { - let uri = identifier["uri"].as_str().expect("identifier URI"); - assert!(uri.ends_with(suffix), "unexpected project URI {uri}"); - } - } - - #[test] - fn a_maven_update_before_initialized_is_sent_with_the_initial_settings() { - // Before the handshake completes JDT LS cannot take a configuration - // change; the pending post-initialize notification carries it instead. - let workspace = TemporaryMavenWorkspace::recursive("maven-update-early"); - let initial = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(initial.clone()); - }); - let mut changed = initial; - changed.local_repository_path = Some("/fixture/early".to_string()); - - let response = harness - .session() - .update_maven_configuration(changed, true) - .expect("an initializing session should accept the update"); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - - assert!(!response.settings_changed && !response.projects_reloaded); - let sent = notifications(&harness, "workspace/didChangeConfiguration"); - assert_eq!(sent.len(), 1); - let document = - std::fs::read_to_string(user_settings(&sent[0])).expect("the copy should exist"); - assert!(document.contains("/fixture/early")); - assert_eq!( - notifications(&harness, "java/projectConfigurationsUpdate").len(), - 1 - ); - } - - #[test] - fn unchanged_settings_reload_before_initialize_waits_for_service_ready() { - let workspace = TemporaryMavenWorkspace::recursive("maven-reload-before-ready"); - let context = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(context.clone()); - }); - let session = harness.session(); - session - .update_maven_configuration(context.clone(), true) - .unwrap(); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - // Reloads coalesce, including another request during project import. - session.update_maven_configuration(context, true).unwrap(); - assert!(notifications(&harness, "java/projectConfigurationsUpdate").is_empty()); - session - .handle_server_message( - json!({ - "jsonrpc": "2.0", "method": "language/status", - "params": { "type": "ServiceReady" } - }) - .to_string(), - ) - .unwrap(); - harness.await_state(LspLifecycleState::Ready); - assert_eq!( - notifications(&harness, "java/projectConfigurationsUpdate").len(), - 1 - ); - session - .handle_server_message( - json!({ - "jsonrpc": "2.0", "method": "language/status", - "params": { "type": "ServiceReady" } - }) - .to_string(), - ) - .unwrap(); - assert_eq!( - notifications(&harness, "java/projectConfigurationsUpdate").len(), - 1 - ); - } - - #[test] - fn changed_maven_profiles_restart_the_profile_task_on_a_ready_session() { - let workspace = TemporaryMavenWorkspace::recursive("maven-update-profiles"); - let initial = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(initial.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - for index in 0..3 { - let id = harness - .server - .await_request_at("workspace/executeCommand", index) - .expect("the initial profile task should update every project"); - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": id, "result": null })); - } - harness.await_event(|event| { - event.maven_profile_task == Some(MavenProfileTaskStatus::Succeeded) - }); - - let mut changed = initial; - changed.profiles = vec!["prod".to_string()]; - let response = harness - .session() - .update_maven_configuration(changed, false) - .expect("a profile change should be accepted"); - - assert!(response.profiles_updating); - assert!(!response.settings_changed); - let updates = notifications(&harness, "workspace/executeCommand"); - assert_eq!(updates.len(), 6); - assert_eq!( - updates[5]["params"]["arguments"][1]["org.eclipse.m2e.core.selectedProfiles"], - "prod" - ); - } - - #[test] - fn a_profile_change_during_a_running_profile_task_is_applied_afterwards() { - // The running task applies the old profiles. Recording the new - // configuration as applied when it finishes would silently drop the - // user's change, so a follow-up task must apply it. - let workspace = TemporaryMavenWorkspace::recursive("maven-update-profiles-running"); - let initial = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(initial.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let first_batch: Vec<_> = (0..3) - .map(|index| { - harness - .server - .await_request_at("workspace/executeCommand", index) - .expect("the initial profile task should update every project") - }) - .collect(); - - let mut changed = initial; - changed.profiles = vec!["prod".to_string()]; - let response = harness - .session() - .update_maven_configuration(changed, false) - .expect("a profile change should be accepted while the task runs"); - assert!(response.profiles_updating); - assert_eq!(notifications(&harness, "workspace/executeCommand").len(), 3); - - for id in first_batch { - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": id, "result": null })); - } - let follow_up = harness - .server - .await_request_at("workspace/executeCommand", 5) - .expect("the changed profiles should be applied by a follow-up task"); - let request = harness - .server - .messages() - .into_iter() - .find(|message| message["id"] == follow_up) - .expect("the follow-up request should be recorded"); - assert_eq!( - request["params"]["arguments"][1]["org.eclipse.m2e.core.selectedProfiles"], - "prod" - ); - } - - #[test] - fn a_new_profile_selection_runs_after_a_failed_batch() { - profile_selection_after_unsuccessful_batch(false); - } - - #[test] - fn a_new_profile_selection_waits_for_timed_out_requests_to_drain() { - profile_selection_after_unsuccessful_batch(true); - } - - fn profile_selection_after_unsuccessful_batch(timeout: bool) { - let workspace = TemporaryMavenWorkspace::recursive("maven-profile-failure-followup"); - let context = workspace.context_with_settings("", None); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.maven_context = Some(context.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let session = harness.session(); - let first_batch: Vec<_> = (0..3) - .map(|index| { - harness - .server - .await_request_at("workspace/executeCommand", index) - .unwrap() - }) - .collect(); - let mut next = context; - next.profiles = vec!["prod".to_string()]; - assert!( - session - .update_maven_configuration(next, false) - .unwrap() - .profiles_updating - ); - if timeout { - // Advance the owned deadlines directly; no wall-clock wait or overlap. - { - let mut state = session.lock_state().unwrap(); - for pending in state.pending.values_mut() { - if pending.kind == PendingKind::JdtMavenProfiles { - pending.deadline = Instant::now(); - } - } - } - session.expire_deadlines(); - } - for (index, id) in first_batch.into_iter().enumerate() { - session - .handle_server_message( - json!({ - "jsonrpc": "2.0", "id": id, - "error": { "code": -32603, "message": "old profile failed" } - }) - .to_string(), - ) - .unwrap(); - session.pump_outbound_maintenance(); - if index < 2 { - assert_eq!(notifications(&harness, "workspace/executeCommand").len(), 3); - } - } - let second_batch: Vec<_> = (3..6) - .map(|index| { - harness - .server - .await_request_at("workspace/executeCommand", index) - .unwrap() - }) - .collect(); - for request in notifications(&harness, "workspace/executeCommand") - .iter() - .skip(3) - { - assert_eq!( - request["params"]["arguments"][1]["org.eclipse.m2e.core.selectedProfiles"], - "prod" - ); - } - // A failure of the latest selection is terminal, not an infinite retry loop. - for id in second_batch { - session - .handle_server_message( - json!({ - "jsonrpc": "2.0", "id": id, - "error": { "code": -32603, "message": "new profile failed" } - }) - .to_string(), - ) - .unwrap(); - } - session.pump_outbound_maintenance(); - assert_eq!(notifications(&harness, "workspace/executeCommand").len(), 6); - } - - #[test] - fn a_session_without_a_maven_context_rejects_maven_updates() { - let workspace = TemporaryMavenWorkspace::recursive("maven-update-reject"); - let harness = Harness::ready(); - - let error = harness - .session() - .update_maven_configuration(workspace.context_with_settings("", None), true) - .expect_err("a session without Maven import settings cannot be updated"); - - assert!(matches!(error.code, ErrorCode::InvalidRequest)); - } - - #[test] - fn structured_logging_warnings_keep_source_stage_and_code() { - let harness = Harness::ready(); - let session = harness.session(); - session.log_issue( - "warn", - "configurationCleanup", - "configurationCleanupFailed", - EngineLog::ConfigurationCleanupFailed, - "Cleanup failed", - None, - ); - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|event| event.kind == "log") - .unwrap(); - assert_eq!(event.level.as_deref(), Some("warn")); - let error = event.error.unwrap(); - assert_eq!(error.code, "configurationCleanupFailed"); - assert_eq!(error.stage, "configurationCleanup"); - assert!(error.underlying_message.is_none()); - for (stage, code) in [ - ("stderr", "upstreamStderr"), - ("stderr", "stderrReadFailed"), - ("shutdown", "shutdownTimeout"), - ] { - session.log_issue( - "warning", - stage, - code, - if code == "upstreamStderr" { - EngineLog::StderrReceived - } else if code == "stderrReadFailed" { - EngineLog::StderrReadFailed - } else { - EngineLog::ShutdownTimedOut - }, - "Updated diagnostic wording", - None, - ); - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|event| event.kind == "log") - .unwrap(); - assert_eq!(event.level.as_deref(), Some("warning")); - let error = event.error.unwrap(); - assert_eq!(error.stage, stage); - assert_eq!(error.code, code); - } - // Ordinary logs must remain unclassified even when their wording matches an issue. - session.log( - "warning", - EngineLog::StderrReceived, - "Language-server stderr", - None, - ); - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|event| event.kind == "log") - .unwrap(); - assert!(event.error.is_none()); - } - - #[test] - fn lifecycle_catalog_identity_preserves_v1_event_without_extra_log() { - for role in [ - SessionRole::LanguageServer, - SessionRole::Vcs, - SessionRole::Build, - SessionRole::Toolchain, - SessionRole::Backend, - ] { - let harness = Harness::start(|request| { - request.role = role; - request.provider_id = "c++".into(); - request.log_subject = Some("git".into()); - request.plugin_id = Some("io.example.tools".into()); - }); - let session = harness.session(); - session.active.store(false, Ordering::Release); - session.kill_process(); - let mut state = session.state.lock().unwrap(); - state.events.clear(); - let sequence = state.next_sequence; - transition_locked(&session, &mut state, LspLifecycleState::Stopped, None); - assert!(!state.events.iter().any(|e| e.kind == "log")); - let event = state.events.front().unwrap(); - let (id, fields) = EngineLog::SessionUpdated.fact( - &session.log_identity, - &json!({"state": "stopped"}), - None, - ); - assert_eq!(event.event.as_deref(), Some(id.as_str())); - assert_eq!(event.fields.as_ref(), Some(&fields)); - assert_eq!( - event.channel.as_deref(), - Some(session.log_identity.channel().as_str()) - ); - assert_eq!(event.role, Some(role)); - assert_eq!(event.plugin_id.as_deref(), Some("io.example.tools")); - assert_eq!( - event.catalog_level, - Some(crate::diagnostics::record::LogLevel::Debug) - ); - let mut legacy = serde_json::to_value(event).unwrap(); - for key in [ - "channel", - "pluginId", - "role", - "event", - "fields", - "catalogLevel", - ] { - legacy.as_object_mut().unwrap().remove(key); - } - assert_eq!( - legacy, - json!({"type": "stateChanged", "sequence": sequence, - "providerId": "c++", "sessionId": session.id, "state": "stopped"}) - ); - state.events.clear(); - let error = runtime_error( - &session, - "processCleanupFailed", - "cleanup", - None, - None, - "Engine process cleanup failed", - None, - None, - ); - let (id, fields) = EngineLog::ProcessCleanupFailed.fact( - &session.log_identity, - &Value::Null, - Some(&error), - ); - push_cleanup_fact(&session, &mut state, id, fields, error); - let event = state.events.front().unwrap(); - assert_eq!( - event.channel.as_deref(), - Some(session.log_identity.channel().as_str()) - ); - assert_eq!( - event.catalog_level, - Some(crate::diagnostics::record::LogLevel::Warn) - ); - assert_eq!(event.kind, "log"); - assert_eq!(event.level.as_deref(), Some("warning")); - assert_eq!( - event.message.as_deref(), - Some("Engine process cleanup failed") - ); - assert!(event.detail.is_none() && event.state.is_none()); - assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("processCleanupFailed") - ); - } - } - - #[test] - fn v1_detail_is_independent_of_catalog_fields() { - let harness = Harness::start(|_| {}); - let session = harness.session(); - struct Cleanup(Arc); - impl Drop for Cleanup { - fn drop(&mut self) { - self.0.active.store(false, Ordering::Release); - self.0.kill_process(); - } - } - let _cleanup = Cleanup(session.clone()); - session.poll_events().unwrap(); - let line = " upstream diagnostic "; - session.log_issue( - "warning", - "stderr", - "upstreamStderr", - EngineLog::StderrReceived.with_fields(json!({"diagnostic": line, "truncated": false})), - "Language-server stderr", - Some(line.into()), - ); - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|e| e.event.as_deref() == Some("lsp.stderr.received")) - .unwrap(); - assert_eq!(event.level.as_deref(), Some("warning")); - assert_eq!(event.message.as_deref(), Some("Language-server stderr")); - assert_eq!(event.detail.as_deref(), Some(line)); - assert_eq!(event.fields.as_ref().unwrap()["diagnostic"], line); - assert_eq!(event.fields.as_ref().unwrap()["truncated"], false); - // A JSON-looking v1 detail cannot supply or overwrite a catalog fact. - session.log( - "info", - EngineLog::MavenApplicationStarted.with_fields(json!({"projectCount": 2})), - "Applying Maven profiles to Java projects", - Some("{\"projectCount\":999}".into()), - ); - let event = session.poll_events().unwrap().into_iter().next().unwrap(); - assert_eq!(event.fields.unwrap()["projects"], 2); - } - - #[test] - fn engine_logging_wire_fixture_preserves_defaults_and_routes_new_commands() { - let fixture: Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/diagnostics/engine-logging-v2.json" - )) - .unwrap(); - let request: StartServerRequest = serde_json::from_value(fixture["start"].clone()).unwrap(); - assert_eq!(request.role, SessionRole::Vcs); - assert_eq!( - SessionLogIdentity::new( - request.role, - &request.provider_id, - request.plugin_id.as_deref(), - request.log_subject.as_deref() - ) - .channel(), - "vcs/git" - ); - let mut legacy = fixture["start"].clone(); - legacy.as_object_mut().unwrap().remove("role"); - legacy.as_object_mut().unwrap().remove("logSubject"); - assert_eq!( - serde_json::from_value::(legacy) - .unwrap() - .role, - SessionRole::LanguageServer - ); - for name in ["trace", "drain", "resolveSubject"] { - assert!(crate::protocol::CoreCommand::parse( - fixture[name]["command"].as_str().unwrap() - ) - .is_some()); - } - let response: Value = serde_json::from_str(&crate::runtime::execute_json( - &fixture["resolveSubject"].to_string(), - )) - .unwrap(); - assert_eq!(response["data"], fixture["resolveSubject"]["result"]); - let request: SetDetailedDiagnosticsRequest = - serde_json::from_value(fixture["trace"]["payload"].clone()).unwrap(); - assert!(request.enabled); - let response: Value = - serde_json::from_str(&crate::runtime::execute_json(&fixture["drain"].to_string())) - .unwrap(); - assert_eq!(response["ok"], true); - assert!(response["data"]["events"].is_array()); - assert!(response["data"]["dropped"].as_u64().is_some()); - } - - #[test] - fn detailed_diagnostics_waits_for_initialized_and_keeps_the_latest_request() { - for enabled in [true, false] { - let harness = Harness::start(|_| {}); - let session = harness.session(); - struct Cleanup(Arc); - impl Drop for Cleanup { - fn drop(&mut self) { - self.0.active.store(false, Ordering::Release); - self.0.kill_process(); - } - } - let _cleanup = Cleanup(session.clone()); - session.set_detailed_diagnostics(true).unwrap(); - if !enabled { - session.set_detailed_diagnostics(false).unwrap(); - } - assert!(!harness - .server - .messages() - .iter() - .any(|m| m["method"] == "$/setTrace")); - assert!(!session.lock_state().unwrap().detailed_diagnostics); - - // Drive the real handshake handler synchronously; no reader timing - // or sleep is needed to establish the notification ordering. - let initialize = harness.server.await_request("initialize").unwrap(); - session - .handle_server_message( - json!({ - "jsonrpc":"2.0", "id":initialize, - "result":{"capabilities":ready_capabilities()} - }) - .to_string(), - ) - .unwrap(); - let methods: Vec<_> = harness - .server - .messages() - .into_iter() - .filter_map(|m| m["method"].as_str().map(str::to_owned)) - .collect(); - if enabled { - let initialized = methods.iter().position(|m| m == "initialized").unwrap(); - let trace = methods.iter().position(|m| m == "$/setTrace").unwrap(); - assert!(trace > initialized); - } else { - assert!(!methods.iter().any(|m| m == "$/setTrace")); - } - assert_eq!(session.lock_state().unwrap().detailed_diagnostics, enabled); - session.set_detailed_diagnostics(false).unwrap(); - assert_eq!( - harness.server.messages().last().unwrap()["params"], - json!({"value":"off"}) - ); - } - } - - #[test] - fn upstream_catalog_messages_trace_toggle_and_v1_fields_coexist() { - let harness = Harness::start(|request| { - request.role = SessionRole::Vcs; - request.log_subject = Some("git".into()); - request.plugin_id = Some("io.example.git".into()); - request.provider_id = "opaque:provider:git".into(); - }); - let session = harness.session(); - struct Cleanup(Arc); - impl Drop for Cleanup { - fn drop(&mut self) { - self.0.active.store(false, Ordering::Release); - self.0.kill_process(); - } - } - let _cleanup = Cleanup(session.clone()); - let initialize = harness.server.await_request("initialize").unwrap(); - session - .handle_server_message( - json!({ - "jsonrpc":"2.0", "id":initialize, "result":{"capabilities":{}} - }) - .to_string(), - ) - .unwrap(); - session.poll_events().unwrap(); - session.log( - "warning", - EngineLog::Dropped.with_fields(json!({"count": 7})), - "Engine stderr lines dropped", - Some("count=7".into()), - ); - let dropped = session - .poll_events() - .unwrap() - .into_iter() - .find(|event| event.event.as_deref() == Some("log.dropped")) - .unwrap(); - assert_eq!(dropped.channel.as_deref(), Some("vcs/git")); - assert_eq!(dropped.fields.unwrap()["count"], 7); - for (method, expected) in [ - ("window/logMessage", "vcs.message.warning.logged"), - ("window/showMessage", "vcs.message.warning.shown"), - ] { - session.handle_server_message(json!({"jsonrpc":"2.0", "method":method, "params":{"type":2,"message":"warning token=private-value"}}).to_string()).unwrap(); - let events = session.poll_events().unwrap(); - let event = events - .iter() - .find(|e| e.event.as_deref() == Some(expected)) - .expect("upstream catalog event"); - assert_eq!(event.channel.as_deref(), Some("vcs/git")); - assert_eq!(event.plugin_id.as_deref(), Some("io.example.git")); - assert_eq!(event.role, Some(SessionRole::Vcs)); - assert_eq!( - event.catalog_level, - Some(crate::diagnostics::record::LogLevel::Warn) - ); - assert_eq!(event.message.as_deref(), Some(method)); - assert!(event.level.is_some() && event.detail.is_some()); - let fields = event.fields.as_ref().unwrap(); - assert_eq!(fields["severity"], "warning"); - assert!(!fields["diagnostic"] - .as_str() - .unwrap() - .contains("private-value")); - } - let trace = json!({"jsonrpc":"2.0", "method":"$/logTrace", "params":{ - "message":"trace token=fixture-secret", "verbose":json!({ - "textDocument":{"text":"private_source_marker"} - }).to_string() - }}) - .to_string(); - session.handle_server_message(trace.clone()).unwrap(); - assert!(!session - .poll_events() - .unwrap() - .iter() - .any(|e| e.event.as_deref() == Some("vcs.trace.received"))); - session.set_detailed_diagnostics(true).unwrap(); - assert_eq!( - harness.server.messages().last().unwrap()["params"], - json!({"value":"verbose"}) - ); - session.handle_server_message(trace.clone()).unwrap(); - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|e| e.event.as_deref() == Some("vcs.trace.received")) - .unwrap(); - assert_eq!( - event.catalog_level, - Some(crate::diagnostics::record::LogLevel::Debug) - ); - assert_eq!(event.level.as_deref(), Some("info")); - let fields = event.fields.unwrap(); - assert_eq!(fields["diagnostic"], "trace token="); - let encoded = crate::diagnostics::record::encode_log_batch( - serde_json::from_value(json!({"validateCatalog":true,"events":[{ - "ts":"2026-11-03T00:00:00.000Z", "seq":1, "level":"DEBUG", - "event":"vcs.trace.received", "msg":"", "fields":fields - }]})) - .unwrap(), - ); - let line = encoded.results[0].line.as_ref().unwrap(); - assert!(!line.contains("private_source_marker")); - assert!(!line.contains("fixture-secret")); - session.set_detailed_diagnostics(false).unwrap(); - assert_eq!( - harness.server.messages().last().unwrap()["params"], - json!({"value":"off"}) - ); - session.handle_server_message(trace).unwrap(); - assert!(!session - .poll_events() - .unwrap() - .iter() - .any(|e| e.event.as_deref() == Some("vcs.trace.received"))); - assert!( - serde_json::from_value::(json!({"sessionId":"s"})) - .is_err() - ); - } - - #[test] - fn maven_profile_log_redacts_absolute_project_paths() { - let redacted = redacted_project_uri("file:///Users/alice/workspace/module-a/"); - assert!(redacted.starts_with("file:///module-a-")); - assert!(!redacted.contains("alice")); - assert_ne!( - redacted_project_uri("file:///workspace/service-a/common/"), - redacted_project_uri("file:///workspace/service-b/common/") - ); - } - - #[test] - fn maven_profile_project_log_matches_its_status() { - let harness = Harness::ready(); - let session = harness.session(); - for (status, level, message) in [ - ( - MavenProfileTaskStatus::Running, - "info", - "Maven profile project update running", - ), - ( - MavenProfileTaskStatus::Succeeded, - "info", - "Maven profile project update completed", - ), - ( - MavenProfileTaskStatus::Failed, - "error", - "Maven profile project update failed", - ), - ( - MavenProfileTaskStatus::TimedOut, - "error", - "Maven profile project update timed out", - ), - ] { - { - let mut state = session.lock_state().unwrap(); - push_maven_profile_project_event( - &session, - &mut state, - MavenProfileProjectResult { - project_uri: "file:///workspace/module".to_string(), - status, - error_details: None, - }, - ); - } - let event = session - .poll_events() - .unwrap() - .into_iter() - .find(|event| event.maven_profile_project.is_some()) - .unwrap(); - assert_eq!(event.level.as_deref(), Some(level)); - assert_eq!(event.message.as_deref(), Some(message)); - assert!(event.error.is_none()); - assert_eq!(event.maven_profile_project.unwrap().status, status); - } - } - - #[test] - fn maven_profile_retry_waits_for_ready_and_cancelled_responses() { - let workspace = TemporaryMavenWorkspace::recursive("maven-retry"); - let mut modules = String::new(); - for index in 0..9 { - let name = format!("module-{index}"); - let directory = workspace.root.join("reactor").join(&name); - std::fs::create_dir_all(&directory).unwrap(); - std::fs::write( - directory.join("pom.xml"), - format!("{name}"), - ) - .unwrap(); - modules.push_str(&format!("{name}")); - } - std::fs::write( - workspace.root.join("reactor/pom.xml"), - format!( - "reactor{modules}" - ), - ) - .unwrap(); - let mut harness = Harness::start(|request| workspace.configure(request)); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - let session = harness.session(); - assert!(session.retry_maven_profiles().is_err()); - assert_eq!(harness.snapshot().state, LspLifecycleState::Initializing); - harness.server.send(json!({ - "jsonrpc": "2.0", "method": "language/status", - "params": { "type": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); - let ids: Vec<_> = (0..8) - .map(|index| { - harness - .server - .await_request_at("workspace/executeCommand", index) - .unwrap() - }) - .collect(); - assert!(session.retry_maven_profiles().is_err()); - { - let mut state = session.lock_state().unwrap(); - for pending in state.pending.values_mut() { - if pending.kind == PendingKind::JdtMavenProfiles { - pending.deadline = Instant::now(); - } - } - } - session.expire_deadlines(); - assert!(harness.server.await_notification("$/cancelRequest")); - assert!(session.retry_maven_profiles().is_err()); - let cancelled_ids: Vec<_> = harness - .server - .messages() - .iter() - .filter(|message| message["method"] == "$/cancelRequest") - .map(|message| message["params"]["id"].clone()) - .collect(); - assert_eq!(cancelled_ids.len(), 8); - assert!(ids.iter().all(|id| cancelled_ids.contains(&json!(id)))); - // Feed terminal responses synchronously: cancellation must keep every - // old slot occupied until its response arrives, without updating results. - for (index, id) in ids.iter().enumerate() { - session.handle_server_message(json!({ - "jsonrpc": "2.0", "id": id, "error": { "code": -32800, "message": "cancelled" } - }).to_string()).unwrap(); - if index < ids.len() - 1 { - assert!(session.retry_maven_profiles().is_err()); - } - } - assert!(session - .lock_state() - .unwrap() - .maven_profile_results - .values() - .all(|result| result.status == MavenProfileTaskStatus::TimedOut)); - session.retry_maven_profiles().unwrap(); - assert!(harness - .server - .await_request_at("workspace/executeCommand", 15) - .is_some()); - assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); - } - - #[test] - fn java_service_error_fails_the_preparing_session() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "Error", "message": "Project import failed" } - })); - harness.await_state(LspLifecycleState::Failed); - - let failure = harness - .events - .iter() - .find_map(|event| event.error.as_ref()) - .expect("the Java service error should be retained"); - assert_eq!(failure.code, "serviceReadyFailed"); - assert_eq!(failure.stage, "serviceReady"); - assert_eq!( - failure.underlying_message.as_deref(), - Some("Project import failed") - ); - } - - #[test] - fn java_quiet_import_remains_alive_until_service_ready() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - let session = harness.session(); - // A quiet m2e batch is not a heartbeat failure. Advance only the deadline - // clock so the test needs neither a real project nor a 46-second sleep. - session.expire_deadlines_at(Instant::now() + Duration::from_secs(46)); - let warning = harness.await_event(|event| { - event.error.as_ref().is_some_and(|error| { - error.stage == "workspaceImport" && error.code == "workspaceImportStalled" - }) - }); - assert_eq!(warning.kind, "log"); - assert_eq!(warning.level.as_deref(), Some("warning")); - assert_eq!(harness.snapshot().state, LspLifecycleState::Initializing); - harness.server.send(json!({ - "jsonrpc": "2.0", "method": "language/status", - "params": { "type": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); - assert!(!harness - .events - .iter() - .any(|event| event.kind != "log" && event.error.is_some())); - } - - #[test] - fn java_preparation_absolute_timeout_covers_quiet_project_import() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - harness - .session() - .expire_deadlines_at(Instant::now() + Duration::from_secs(601)); - harness.await_state(LspLifecycleState::Failed); - - let failure = harness - .events - .iter() - .find_map(|event| event.error.as_ref()) - .expect("project import timeout should be reported"); - assert_eq!(failure.code, "serviceReadyTimeout"); - assert_eq!(failure.stage, "serviceReady"); - let detail: Value = - serde_json::from_str(failure.underlying_message.as_deref().unwrap()).unwrap(); - assert_eq!(detail["timeoutKind"], "absolute"); - assert_eq!(detail["classification"], "noProgressStall"); - } - - #[test] - fn java_import_notifications_are_logged_after_service_ready() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness.server.await_notification("initialized")); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "$/progress", - "params": { - "token": "java-import", - "value": { - "kind": "report", - "message": "Importing Maven project(s) - Importing project module-a", - "percentage": 20 - } - } - })); - harness.await_event(|event| { - event.message.as_deref() == Some("Java workspace import progress") - }); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); - assert!( - !harness.events.iter().any(|event| { - matches!( - event.message.as_deref(), - Some("$/progress" | "language/status") - ) - }), - "structured preparation notifications should not be logged twice" - ); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "$/progress", - "params": { - "token": "java-build", - "value": { - "kind": "report", - "message": "Building workspace - Project 'module-a'", - "percentage": 50 - } - } - })); - harness.await_event(|event| event.message.as_deref() == Some("$/progress")); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { - "type": "Error", - "message": "Background build failed" - } - })); - harness.await_event(|event| event.message.as_deref() == Some("language/status")); - assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); - } - - #[test] - fn java_documents_wait_for_service_ready_and_latest_text_wins() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - let uri = "file:///workspace/Main.java"; - harness.sync(uri, "class Main {}"); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - assert!(!harness - .server - .messages() - .iter() - .any(|message| message["method"] == "textDocument/didOpen")); - - harness.sync(uri, "class Main { int value; }"); - assert_eq!(harness.snapshot().state, LspLifecycleState::Initializing); - assert_eq!(harness.snapshot().open_documents[uri].version, 0); - assert!(!harness.server.messages().iter().any(|message| { - matches!( - message["method"].as_str(), - Some("textDocument/didOpen" | "textDocument/didChange") - ) - })); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); - - let document_messages: Vec<_> = harness - .server - .messages() - .into_iter() - .filter(|message| { - matches!( - message["method"].as_str(), - Some("textDocument/didOpen" | "textDocument/didChange") - ) - }) - .collect(); - assert_eq!(document_messages.len(), 1); - assert_eq!(document_messages[0]["method"], "textDocument/didOpen"); - assert_eq!( - document_messages[0]["params"]["textDocument"]["text"], - "class Main { int value; }" - ); - assert_eq!(harness.snapshot().open_documents[uri].version, 1); - } - - #[test] - fn ranged_edits_extend_text_retained_before_the_server_is_ready() { - let harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - let uri = "file:///workspace/First.java"; - harness.sync(uri, "class First {}"); - let appended = LspDocumentContentChange { - range: Some(LspRange { - start: LspPosition { - line: 0, - utf16_column: 11, - }, - end: LspPosition { - line: 0, - utf16_column: 11, - }, - }), - text: "Renamed".to_string(), - }; - harness - .session() - .sync_document(SyncDocumentRequest { - session_id: harness.session_id.clone(), - uri: uri.to_string(), - language_id: "java".to_string(), - text: String::new(), - content_changes: vec![appended.clone()], - }) - .expect("ranged edits should extend the retained text"); - - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - assert!(harness.server.await_notification("textDocument/didOpen")); - let written = String::from_utf8_lossy(&harness.server.written_bytes()).into_owned(); - assert!(written.contains("class FirstRenamed {}")); - - let error = harness - .session() - .sync_document(SyncDocumentRequest { - session_id: harness.session_id.clone(), - uri: "file:///workspace/Unknown.java".to_string(), - language_id: "java".to_string(), - text: String::new(), - content_changes: vec![appended], - }) - .expect_err("edits to an unknown document cannot be resolved"); - assert_eq!(error.details.as_deref(), Some("documentNotSynchronized")); - } - - #[test] - fn java_ready_flush_precedes_concurrent_edits_and_closes() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - let first_uri = "file:///workspace/First.java"; - let second_uri = "file:///workspace/Second.java"; - harness.sync(first_uri, "class First {}"); - harness.sync(second_uri, "class Second {}"); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - - // Hold the first restored didOpen before it reaches the server. The - // complete ready flush must retain outbound ownership and keep Ready - // private until every restored document has been written. - harness.server.pause_input(); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - assert!( - harness.server.await_input_pause(), - "the restored document flush should reach the write barrier" - ); - assert_eq!( - harness.snapshot().state, - LspLifecycleState::Initializing, - "Ready must not be published before queued didOpen messages are written" - ); - - let start = Arc::new(std::sync::Barrier::new(3)); - let edit_session = harness.session(); - let edit_session_id = harness.session_id.clone(); - let edit_start = start.clone(); - let edit = thread::spawn(move || { - edit_start.wait(); - edit_session.sync_document(SyncDocumentRequest { - session_id: edit_session_id, - uri: second_uri.to_string(), - language_id: "java".to_string(), - text: "class Second { int value; }".to_string(), - content_changes: Vec::new(), - }) - }); - let close_session = harness.session(); - let close_start = start.clone(); - let close = thread::spawn(move || { - close_start.wait(); - close_session.close_document(first_uri) - }); - start.wait(); - - assert!( - harness.session().outbound_order.try_lock().is_err(), - "the ready flush should exclude concurrent protocol state commits" - ); - harness.server.resume_input(); - edit.join() - .expect("the concurrent edit thread should finish") - .expect("the concurrent edit should succeed after Ready"); - close - .join() - .expect("the concurrent close thread should finish") - .expect("the concurrent close should succeed after Ready"); - harness.await_state(LspLifecycleState::Ready); - - let document_messages: Vec<_> = harness - .server - .messages() - .into_iter() - .filter(|message| { - matches!( - message["method"].as_str(), - Some( - "textDocument/didOpen" | "textDocument/didChange" | "textDocument/didClose" - ) - ) - }) - .collect(); - assert_eq!(document_messages.len(), 4); - assert_eq!(document_messages[0]["method"], "textDocument/didOpen"); - assert_eq!( - document_messages[0]["params"]["textDocument"]["uri"], - first_uri - ); - assert_eq!(document_messages[1]["method"], "textDocument/didOpen"); - assert_eq!( - document_messages[1]["params"]["textDocument"]["uri"], - second_uri - ); - assert!(document_messages[2..].iter().any(|message| { - message["method"] == "textDocument/didChange" - && message["params"]["textDocument"]["uri"] == second_uri - && message["params"]["textDocument"]["version"] == 2 - })); - assert!(document_messages[2..].iter().any(|message| { - message["method"] == "textDocument/didClose" - && message["params"]["textDocument"]["uri"] == first_uri - })); - - let snapshot = harness.snapshot(); - assert!(!snapshot.open_documents.contains_key(first_uri)); - assert_eq!(snapshot.open_documents[second_uri].version, 2); - assert_eq!( - &*snapshot.open_documents[second_uri].text, - "class Second { int value; }" - ); - } - - /// A path descriptor reaches the server with reserved characters escaped. - #[test] - fn native_path_emits_the_canonical_uri_on_the_lsp_wire() { - let harness = Harness::ready(); - let mut payload = json!({"sessionId":harness.session_id, "languageId":"go", "text":"package main", - "uri":{"path":"/workspace/A#B.go","platform":"posix"}}); - crate::lsp::resolve_request_paths("lsp.syncDocument", &mut payload).unwrap(); - let request: SyncDocumentRequest = serde_json::from_value(payload).unwrap(); - harness - .session() - .sync_document(request) - .expect("document should synchronize"); - assert!(harness.server.await_notification("textDocument/didOpen")); - let opened = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "textDocument/didOpen") - .unwrap(); - assert_eq!( - opened["params"]["textDocument"]["uri"], - "file:///workspace/A%23B.go" - ); - } - - /// Criterion 3: two syncs emit open version 1 then change version 2. - #[test] - fn consecutive_syncs_open_at_version_one_and_change_to_version_two() { - let harness = Harness::ready(); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - harness.sync(uri, "package main\nfunc main() {}"); - - let versions: Vec<_> = harness - .server - .messages() - .into_iter() - .filter_map(|message| { - let method = message.get("method")?.as_str()?.to_string(); - let document = message.get("params")?.get("textDocument")?; - let version = document.get("version")?.as_i64()?; - Some((method, version)) - }) - .collect(); - assert_eq!( - versions, - vec![ - ("textDocument/didOpen".to_string(), 1), - ("textDocument/didChange".to_string(), 2) - ] - ); - assert_eq!(harness.snapshot().open_documents[uri].version, 2); - } - - #[test] - fn all_documents_synced_during_initialize_are_opened_when_ready() { - let mut harness = Harness::start(|_| {}); - let first_uri = "file:///workspace/first.go"; - let second_uri = "file:///workspace/second.go"; - harness.sync(first_uri, "package main\nvar first = 1"); - harness.sync(second_uri, "package main\nvar second = 2"); - - harness.server.complete_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - - let opened_uris: Vec<_> = harness - .server - .messages() - .into_iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) == Some("textDocument/didOpen") - }) - .filter_map(|message| { - message - .get("params")? - .get("textDocument")? - .get("uri")? - .as_str() - .map(ToString::to_string) - }) - .collect(); - assert_eq!( - opened_uris, - vec![first_uri.to_string(), second_uri.to_string()] - ); - let snapshot = harness.snapshot(); - assert_eq!(snapshot.open_documents[first_uri].version, 1); - assert_eq!(snapshot.open_documents[second_uri].version, 1); - } - - #[test] - fn workspace_file_changes_queue_until_initialize_and_collapse_watcher_bursts() { - let mut harness = Harness::start(|_| {}); - harness - .session() - .workspace_files_changed(vec![ - WorkspaceFileChange { - uri: "file:///workspace/pom.xml".to_string(), - kind: WorkspaceFileChangeKind::Changed, - }, - WorkspaceFileChange { - uri: "file:///workspace/src/Main.java".to_string(), - kind: WorkspaceFileChangeKind::Created, - }, - WorkspaceFileChange { - uri: "file:///workspace/src/Main.java".to_string(), - kind: WorkspaceFileChangeKind::Changed, - }, - ]) - .expect("watcher events should queue before initialize"); - assert!(!harness - .server - .messages() - .iter() - .any(|message| { message["method"] == "workspace/didChangeWatchedFiles" })); - - harness.server.complete_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let notification = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "workspace/didChangeWatchedFiles") - .expect("queued watcher events should flush after initialize"); - assert_eq!( - notification["params"]["changes"], - json!([ - { "uri": "file:///workspace/pom.xml", "type": 2 }, - { "uri": "file:///workspace/src/Main.java", "type": 2 } - ]) - ); - } - - #[test] - fn java_workspace_changes_wait_for_service_ready() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - }); - harness - .session() - .workspace_files_changed(vec![WorkspaceFileChange { - uri: "file:///workspace/src/Main.java".to_string(), - kind: WorkspaceFileChangeKind::Changed, - }]) - .expect("Java watcher events should queue while project import is pending"); - harness.server.complete_initialize(ready_capabilities()); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - assert!(!harness - .server - .messages() - .iter() - .any(|message| { message["method"] == "workspace/didChangeWatchedFiles" })); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - harness.await_state(LspLifecycleState::Ready); - - let notification = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "workspace/didChangeWatchedFiles") - .expect("queued Java watcher events should flush after project import"); - assert_eq!( - notification["params"]["changes"], - json!([{ "uri": "file:///workspace/src/Main.java", "type": 2 }]) - ); - } - - /// Criterion 4: a crash fails pending operations with `serverExited`. - #[test] - fn a_crash_fails_every_pending_operation_once_with_server_exited() { - let mut harness = Harness::ready(); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - let hover = harness.request(LspSemanticOperation::Hover, uri); - let definition = harness.request(LspSemanticOperation::Definition, uri); - - harness.server.exit(Some(134)); - harness.await_state(LspLifecycleState::Failed); - - let failures: Vec<_> = harness - .events - .iter() - .filter(|event| event.kind == "requestCompleted") - .collect(); - assert_eq!( - failures.len(), - 2, - "each pending operation must fail exactly once" - ); - for event in failures { - let error = event.error.as_ref().expect("a crash cannot yield a result"); - assert_eq!(error.code, "serverExited"); - assert_eq!(error.process_exit_code, Some(134)); - } - let completed: Vec<_> = harness - .events - .iter() - .filter_map(|event| event.operation_id.clone()) - .collect(); - assert!(completed.contains(&hover) && completed.contains(&definition)); - assert!(harness.snapshot().pending_operation_ids.is_empty()); - } - - /// Criterion 5: a request deadline removes the pending request. - /// Criterion 6: a late response after that timeout is ignored. - #[test] - fn a_timed_out_request_is_removed_cancelled_and_deaf_to_its_late_response() { - let mut harness = Harness::start(|request| { - request.request_timeout_milliseconds = 30; - }); - harness.server.complete_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - let operation = harness.request(LspSemanticOperation::Hover, uri); - let request_id = harness - .server - .await_request("textDocument/hover") - .expect("the hover request should reach the server"); - - let timeout = harness - .await_event(|event| { - event - .error - .as_ref() - .is_some_and(|error| error.code == "requestTimeout") - }) - .clone(); - assert_eq!(timeout.operation_id.as_deref(), Some(operation.as_str())); - assert!(harness.snapshot().pending_operation_ids.is_empty()); - // The completion event is queued before the cancellation is written, so - // the wire assertion has to wait for the write rather than assume it. - assert!( - harness.server.await_notification("$/cancelRequest"), - "a timed-out request must be cancelled on the wire" - ); - - // The server answers anyway. Nothing may reach the application: the - // operation has already been completed with its timeout error. - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": { "contents": "too late" } - })); - thread::sleep(Duration::from_millis(50)); - harness.poll(); - let completions = harness - .events - .iter() - .filter(|event| event.operation_id.as_deref() == Some(operation.as_str())) - .count(); - assert_eq!( - completions, 1, - "a late response must not complete the operation a second time" - ); - } - - /// Criterion 7: responses from an old session cannot affect a restarted one. - #[test] - fn a_restarted_session_ignores_the_previous_session_s_responses() { - // The first session is taken to Ready and then torn down. Its hover - // request id is recorded first, because every session numbers its - // requests from one: an id alone cannot tell two sessions apart, so only - // per-session pending state can reject a foreign response. - let mut first = Harness::ready(); - let uri = "file:///workspace/main.go"; - first.sync(uri, "package main"); - first.request(LspSemanticOperation::Hover, uri); - let stale_id = first - .server - .await_request("textDocument/hover") - .expect("the hover request should reach the server"); - first.server.exit(Some(0)); - first.await_state(LspLifecycleState::Failed); - first.engine.destroy(&first.session_id).unwrap(); - - let mut restarted = Harness::ready(); - restarted.sync(uri, "package main"); - let operation = restarted.request(LspSemanticOperation::Hover, uri); - assert_eq!( - restarted - .server - .await_request("textDocument/hover") - .as_deref(), - Some(stale_id.as_str()), - "the restarted session must reuse the id, or this proves nothing" - ); - - // Delivered to the new session, the id does match a pending request, so - // isolation cannot rest on ids. It rests on the process: the old - // session's reader thread is gone with its process, so its responses - // have no path into the new session at all. - let before = restarted.snapshot(); - first.server.send(json!({ - "jsonrpc": "2.0", - "id": stale_id, - "result": { "contents": "from the dead session" } - })); - thread::sleep(Duration::from_millis(50)); - restarted.poll(); - assert_eq!( - restarted.snapshot().pending_operation_ids, - before.pending_operation_ids, - "the old session's response must not complete the new session's request" - ); - assert!( - !restarted - .events - .iter() - .any(|event| event.kind == "requestCompleted"), - "no operation may complete from a foreign session's traffic" - ); - - // The new session's own response still lands, so the isolation above is - // not merely a dead session. - restarted.server.send(json!({ - "jsonrpc": "2.0", - "id": stale_id, - "result": { "contents": "from the live session" } - })); - let completion = restarted - .await_event(|event| event.kind == "requestCompleted") - .clone(); - assert_eq!(completion.operation_id.as_deref(), Some(operation.as_str())); - assert_eq!( - completion - .result - .as_ref() - .and_then(|result| result.get("hover")?.get("contents")) - .and_then(Value::as_str), - Some("from the live session") - ); - } - - /// Provider adaptation has to reach the process boundary, not just the - /// adapter: the arguments a Windows launcher receives are the ones asserted - /// here. - #[test] - fn the_launched_process_receives_the_adapted_provider_arguments() { - let server = ScriptedServer::new(); - let engine = LspEngine::with_launcher(server.launcher()); - let cache = std::env::temp_dir().join("lithe-core-engine-tests"); - let mut request = start_request(&server); - request.provider_id = "java".to_string(); - request.arguments = vec!["-data".to_string(), "/stale/data".to_string()]; - request.runtime_executable_path = Some("/opt/jdk/bin/java".to_string()); - request.cache_directory = Some(cache.to_string_lossy().into_owned()); - engine - .start_server(request) - .expect("the server should start"); - - let spec = server - .launched_spec() - .expect("starting a server must launch a process"); - assert_eq!(spec.executable, "/usr/bin/scripted-server"); - assert_eq!(spec.working_directory, "/workspace"); - assert!( - !spec - .arguments - .iter() - .any(|argument| argument == "/stale/data"), - "a caller-supplied -data must be replaced, not appended: {:?}", - spec.arguments - ); - assert_eq!( - spec.arguments - .iter() - .position(|argument| argument == "--java-executable") - .map(|index| spec.arguments[index + 1].as_str()), - Some("/opt/jdk/bin/java") - ); - let data = spec - .arguments - .iter() - .position(|argument| argument == "-data") - .map(|index| spec.arguments[index + 1].clone()) - .expect("JDT requires a data directory"); - assert!(Path::new(&data).starts_with(&cache)); - assert!( - Path::new(&data).is_dir(), - "the data directory must exist before the server starts" - ); - let _ = std::fs::remove_dir_all(&cache); - } - - /// Lithe deletes files from the user's project before JDT LS starts; the - /// session log is the only place a user or support can see which ones. - #[test] - fn java_start_logs_legacy_project_files_it_removed() { - let root = - std::env::temp_dir().join(format!("lithe-core-legacy-metadata-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let workspace = root.join("workspace"); - std::fs::create_dir_all(&workspace).expect("workspace should be creatable"); - std::fs::write(workspace.join("pom.xml"), "").expect("pom should be writable"); - std::fs::write(workspace.join(".classpath"), "legacy") - .expect("classpath should be writable"); - let initialized = std::process::Command::new("git") - .args(["init", "-q"]) - .current_dir(&workspace) - .status() - .expect("git should run"); - assert!(initialized.success()); - - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.working_directory = workspace.to_string_lossy().into_owned(); - request.cache_directory = Some(root.join("cache").to_string_lossy().into_owned()); - }); - let detail = harness - .await_event(|event| { - event.kind == "log" - && event.message.as_deref() - == Some("Removed Java project files that earlier versions left in the workspace") - }) - .detail - .clone() - .expect("the log must name the removed files"); - let removed_on_disk = !workspace.join(".classpath").exists(); - let _ = std::fs::remove_dir_all(&root); - - assert!(removed_on_disk); - assert_eq!( - serde_json::from_str::(&detail).expect("detail should be JSON"), - json!({ "removedFiles": [".classpath"], "stateReset": false }) - ); - } - - #[test] - fn structured_jdtls_resources_launch_the_runtime_executable_directly() { - let server = ScriptedServer::new(); - let engine = LspEngine::with_launcher(server.launcher()); - let root = std::env::temp_dir().join(format!( - "lithe-core-direct-jdtls-tests-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&root); - let cache = root.join("cache"); - let packaged_configuration = packaged_jdtls_configuration(&root.join("installation")); - let mut request = start_request(&server); - request.provider_id = "java".to_string(); - request.arguments = vec!["--jvm-arg=-Duser.language=en".to_string()]; - request.runtime_executable_path = Some("/opt/lithe/jdk/bin/java".to_string()); - request.jdtls_launch_resources = Some(JdtlsLaunchResources { - launcher_jar_path: "/opt/lithe/jdtls/plugins/equinox.jar".to_string(), - configuration_directory: packaged_configuration.to_string_lossy().into_owned(), - lombok_agent_path: "/opt/lithe/jdtls/lombok/lombok.jar".to_string(), - java_debug_bundle_path: Some( - "/opt/lithe/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar" - .to_string(), - ), - java_extension_bundle_paths: vec![ - "/opt/lithe/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar" - .to_string(), - "/opt/lithe/jdtls/java-test/extensions/com.microsoft.java.test.plugin-0.42.0.jar" - .to_string(), - ], - }); - request.cache_directory = Some(cache.to_string_lossy().into_owned()); - engine - .start_server(request) - .expect("the server should start with direct Java"); - - let spec = server - .launched_spec() - .expect("starting a server must launch a process"); - assert_eq!(spec.executable, "/opt/lithe/jdk/bin/java"); - assert_eq!( - spec.arguments.first().map(String::as_str), - Some("-javaagent:/opt/lithe/jdtls/lombok/lombok.jar") - ); - assert!(spec.arguments.contains(&"-Duser.language=en".to_string())); - assert_eq!( - spec.arguments - .iter() - .position(|argument| argument == "-jar") - .map(|index| spec.arguments[index + 1].as_str()), - Some("/opt/lithe/jdtls/plugins/equinox.jar") - ); - // Equinox writes into -configuration, so it must name the writable - // copy in the cache and never the packaged directory. - let configuration = spec - .arguments - .iter() - .position(|argument| argument == "-configuration") - .map(|index| PathBuf::from(&spec.arguments[index + 1])) - .expect("direct launch must pass a configuration area"); - let copied_config = std::fs::read(configuration.join("config.ini")); - let packaged_entries = std::fs::read_dir(&packaged_configuration) - .expect("packaged configuration should stay readable") - .count(); - assert!(!spec - .arguments - .iter() - .any(|argument| argument.starts_with("--java-executable"))); - let _ = std::fs::remove_dir_all(&root); - - assert!(configuration.starts_with(cache.join("jdtls-configuration"))); - assert_eq!( - copied_config.ok().as_deref(), - Some(PACKAGED_JDTLS_CONFIG_INI.as_bytes()) - ); - assert_eq!(packaged_entries, 1, "only the shipped config.ini remains"); - } - - /// A write that fails mid-session is a transport failure, not a silent drop. - #[test] - fn a_broken_stdin_fails_the_session_and_stops_writing() { - let mut harness = Harness::ready(); - let written = harness.server.written_bytes().len(); - harness.server.break_input(); - let error = harness - .session() - .sync_document(SyncDocumentRequest { - session_id: harness.session_id.clone(), - uri: "file:///workspace/main.go".to_string(), - language_id: "go".to_string(), - text: "package main".to_string(), - content_changes: Vec::new(), - }) - .expect_err("a broken pipe must surface to the caller"); - assert!(matches!(error.code, ErrorCode::ProcessFailed)); - - harness.await_state(LspLifecycleState::Failed); - let failure = harness - .events - .iter() - .find_map(|event| event.error.as_ref()) - .expect("the failure should be reported as a runtime error"); - assert_eq!(failure.code, "transportFailed"); - assert_eq!( - harness.server.written_bytes().len(), - written, - "nothing may be written after the pipe breaks" - ); - } - - /// The stopped session's own late response is dropped rather than acted on, - /// which is the same rule seen from the other side of a restart. - #[test] - fn a_response_to_an_already_failed_session_is_logged_and_dropped() { - let mut harness = Harness::ready(); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - harness.request(LspSemanticOperation::Hover, uri); - let request_id = harness - .server - .await_request("textDocument/hover") - .expect("the hover request should reach the server"); - - harness.server.exit(Some(1)); - harness.await_state(LspLifecycleState::Failed); - let completions = harness - .events - .iter() - .filter(|event| event.kind == "requestCompleted") - .count(); - assert_eq!(completions, 1, "the crash already completed the operation"); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": { "contents": "unreachable" } - })); - thread::sleep(Duration::from_millis(50)); - harness.poll(); - assert_eq!( - harness - .events - .iter() - .filter(|event| event.kind == "requestCompleted") - .count(), - completions, - "a response after the terminal state must not complete anything" - ); - assert_eq!(harness.snapshot().state, LspLifecycleState::Failed); - } - - #[test] - fn indexing_java_retains_plugin_exclusions_across_all_configuration_channels() { - let workspace = TemporaryMavenWorkspace::recursive("indexing-java-base"); - let root = workspace.root.canonicalize().unwrap(); - let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - struct Lease { - root: PathBuf, - revision: u64, - } - impl Drop for Lease { - fn drop(&mut self) { - let _ = crate::project::indexing::release( - crate::project::indexing::ReleaseIndexingRequest { - owner_id: None, - root: self.root.to_string_lossy().into_owned(), - revision: self.revision, - }, - ); - } - } - let mut lease = Lease { - root: root.clone(), - revision: 0, - }; - let plugin = json!({"settings":{"java":{"import":{"exclusions":["**/vendor/**"]}}}}); - let mut harness = Harness::start(|request| { - workspace.configure(request); - request.root_uri = root_uri.clone(); - request.initialization_options = Some(plugin.clone()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - for (index, excluded) in [true, false, true, false].into_iter().enumerate() { - let status = crate::project::indexing::configure(serde_json::from_value(json!({ - "root":root,"manualExcludedDirectories":if excluded {vec!["reactor"]} else {vec![]}, - "includedDirectories":[],"gitIgnoreEnabled":false - })).unwrap()).unwrap(); - lease.revision = status.revision; - apply_indexing_to_sessions(&root, vec![harness.session()]).unwrap(); - let mut expected = vec![json!("**/vendor/**")]; - if excluded { - let directory = root.join("reactor").to_string_lossy().replace('\\', "/"); - expected.extend([json!(directory), json!(format!("{directory}/**"))]); - } - let notifications = notifications(&harness, "workspace/didChangeConfiguration"); - assert_eq!( - notifications.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"], - json!(expected) - ); - let id = format!("indexing-java-{index}"); - harness.server.send(json!({"jsonrpc":"2.0", "id":id, "method":"workspace/configuration", "params":{"items":[ - {"section":"java.import.exclusions"},{"section":"java.import"},{"section":"java"} - ]}})); - let reply = await_reply(&harness, &id); - assert_eq!(reply["result"][0], json!(expected)); - assert_eq!(reply["result"][1]["exclusions"], json!(expected)); - assert_eq!(reply["result"][2]["import"]["exclusions"], json!(expected)); - } - assert_eq!( - harness.session().jdt_import_exclusions, - Some(json!(["**/vendor/**"])) - ); - // Restarting from the same immutable plugin input must not accumulate old overlays. - let restarted = Harness::start(|request| { - workspace.configure(request); - request.root_uri = root_uri; - request.initialization_options = Some(plugin); - }); - let initialize = notifications(&restarted, "initialize").pop().unwrap(); - assert_eq!( - initialize["params"]["initializationOptions"]["settings"]["java"]["import"] - ["exclusions"], - json!(["**/vendor/**"]) - ); - } - - #[test] - fn indexing_policy_withdrawal_serializes_with_a_checked_document_commit() { - assert_policy_withdrawal_serializes_with_checked_commit(false); - } - - #[test] - fn indexing_policy_withdrawal_serializes_with_checked_diagnostics() { - assert_policy_withdrawal_serializes_with_checked_commit(true); - } - - fn assert_policy_withdrawal_serializes_with_checked_commit(diagnostics: bool) { - let workspace = TemporaryMavenWorkspace::recursive("indexing-document-commit"); - let root = workspace.root.canonicalize().unwrap(); - let mut policy = IndexingPolicyFixture::new(root.clone()); - let mut harness = Harness::start(|request| workspace.configure(request)); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let uri = url::Url::from_file_path(root.join("reactor/Hidden.java")) - .unwrap() - .to_string(); - let session = harness.session(); - let (checked_tx, checked_rx) = std::sync::mpsc::channel(); - let (release_tx, release_rx) = std::sync::mpsc::channel(); - let (sync_done_tx, sync_done_rx) = std::sync::mpsc::channel(); - let syncing = { - let session = session.clone(); - let uri = uri.clone(); - thread::spawn(move || { - let checked = || { - checked_tx.send(()).unwrap(); - release_rx - .recv_timeout(Duration::from_secs(3)) - .expect("document commit was not released"); - }; - let result = if diagnostics { - session.handle_server_message_after_policy_check(json!({"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{ - "uri":uri,"diagnostics":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"message":"old diagnostic"}] - }}).to_string(), checked) - } else { - session - .sync_document_after_policy_check( - SyncDocumentRequest { - session_id: session.id.clone(), - uri, - language_id: "java".into(), - text: "class Hidden {}".into(), - content_changes: Vec::new(), - }, - checked, - ) - .map(|_| ()) - }; - let _ = sync_done_tx.send(()); - result - }) - }; - checked_rx - .recv_timeout(Duration::from_secs(3)) - .expect("document eligibility was not reached"); - assert!( - matches!( - session.indexing_roots.try_lock(), - Err(std::sync::TryLockError::WouldBlock) - ), - "eligibility and document publication must retain the policy serialization guard" - ); - policy.exclude(&["reactor"]); - let (update_done_tx, update_done_rx) = std::sync::mpsc::channel(); - let updating = { - let session = session.clone(); - let root = root.clone(); - thread::spawn(move || { - let result = apply_indexing_to_sessions(&root, vec![session]); - let _ = update_done_tx.send(()); - result - }) - }; - release_tx.send(()).unwrap(); - sync_done_rx - .recv_timeout(Duration::from_secs(3)) - .expect("document commit did not finish"); - update_done_rx - .recv_timeout(Duration::from_secs(3)) - .expect("policy update did not finish"); - syncing.join().unwrap().unwrap(); - updating.join().unwrap().unwrap(); - assert!(!harness.snapshot().open_documents.contains_key(&uri)); - assert!(!session - .lock_state() - .unwrap() - .client - .diagnostics - .contains_key(&uri)); - if !diagnostics { - assert!(notifications(&harness, "textDocument/didClose") - .iter() - .any(|message| message["params"]["textDocument"]["uri"] == uri)); - } - } - - #[test] - fn indexing_policy_withdraws_queued_file_changes_before_service_readiness() { - let workspace = TemporaryMavenWorkspace::recursive("indexing-pending-file-changes"); - let root = workspace.root.canonicalize().unwrap(); - let mut policy = IndexingPolicyFixture::new(root.clone()); - let mut harness = Harness::start(|request| workspace.configure(request)); - let hidden = url::Url::from_file_path(root.join("reactor/Hidden.java")) - .unwrap() - .to_string(); - let visible = url::Url::from_file_path(root.join("Visible.java")) - .unwrap() - .to_string(); - harness - .session() - .workspace_files_changed(vec![ - WorkspaceFileChange { - uri: hidden.clone(), - kind: WorkspaceFileChangeKind::Created, - }, - WorkspaceFileChange { - uri: visible.clone(), - kind: WorkspaceFileChangeKind::Created, - }, - ]) - .unwrap(); - assert_eq!( - harness - .session() - .lock_state() - .unwrap() - .pending_workspace_file_changes - .len(), - 2 - ); - policy.exclude(&["reactor"]); - // The policy is installed, but this independent session has not received - // its withdrawal callback yet. Readiness must recheck queued eligibility. - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let changes = notifications(&harness, "workspace/didChangeWatchedFiles"); - assert!(changes.iter().any(|message| message["params"]["changes"] - .as_array() - .unwrap() - .iter() - .any(|change| change["uri"] == visible))); - assert!(!changes.iter().any(|message| message["params"]["changes"] - .as_array() - .unwrap() - .iter() - .any(|change| change["uri"] == hidden))); - } - - #[test] - fn indexing_startup_cancels_when_policy_changes_during_process_launch() { - const CANCELLED_PLUGIN: &str = "io.example.indexing-cancel-launch"; - struct RetireOnLaunch { - inner: Arc, - root: PathBuf, - revision: Arc, - process: Arc>>>, - } - impl LspProcessLauncher for RetireOnLaunch { - fn launch( - &self, - spec: LspProcessSpec, - ) -> Result { - let process = self.inner.launch(spec)?; - *self.process.lock().unwrap() = Some(process.handle.clone()); - let status = crate::project::indexing::configure(serde_json::from_value(json!({ - "root": self.root, "manualExcludedDirectories": ["reactor"], "includedDirectories": [], "gitIgnoreEnabled": false - })).unwrap())?; - self.revision.store(status.revision, Ordering::Release); - Ok(process) - } - } - struct Cleanup { - root: PathBuf, - revision: Arc, - process: Arc>>>, - } - impl Drop for Cleanup { - fn drop(&mut self) { - if let Some(process) = self.process.lock().unwrap().as_ref() { - process.terminate(); - } - let _ = crate::project::indexing::release( - crate::project::indexing::ReleaseIndexingRequest { - root: self.root.to_string_lossy().into_owned(), - owner_id: None, - revision: self.revision.load(Ordering::Acquire), - }, - ); - } - } - for (initially_configured, cleanup_blocked, native_owner) in [ - (false, false, false), - (true, false, false), - (false, true, false), - (true, true, false), - (false, false, true), - (true, false, true), - (false, true, true), - (true, true, true), - ] { - let workspace = TemporaryMavenWorkspace::recursive(&format!( - "indexing-startup-retired-{initially_configured}" - )); - let root = workspace.root.canonicalize().unwrap(); - let installed = if initially_configured { - crate::project::indexing::configure(serde_json::from_value(json!({ - "root":root,"manualExcludedDirectories":[],"includedDirectories":[],"gitIgnoreEnabled":false - })).unwrap()).unwrap().revision - } else { - 0 - }; - let cleanup = Cleanup { - root: root.clone(), - revision: Arc::new(AtomicU64::new(installed)), - process: Arc::new(Mutex::new(None)), - }; - let server = ScriptedServer::new(); - server.block_cleanup(cleanup_blocked); - let engine = LspEngine::with_launcher(Arc::new(RetireOnLaunch { - inner: server.launcher(), - root: root.clone(), - revision: cleanup.revision.clone(), - process: cleanup.process.clone(), - })); - let mut request = start_request(&server); - request.provider_id = "python".into(); - request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - request.working_directory = root.to_string_lossy().into_owned(); - request.startup_operation = Some(AttemptHandoff { - plugin_id: CANCELLED_PLUGIN.to_string(), - operation_id: "indexing-cancel-before-registration".to_string(), - elapsed_ms: 5, - }); - let mut registered = None; - let result = if native_owner { - engine.start_server_owned(request, |id| registered = Some(id.to_owned())) - } else { - engine.start_server(request) - }; - assert!(matches!(result.unwrap_err().code, ErrorCode::Cancelled)); - if cleanup_blocked { - let id = if native_owner { - registered.expect("incomplete disposal must reach the native owner") - } else { - engine - .lock_failed_starts() - .unwrap() - .first() - .cloned() - .expect("incomplete wire disposal retains its internal owner") - }; - assert!(engine.destroy(&id).is_err()); - assert!(engine.session(&id).is_ok()); - server.block_cleanup(false); - if native_owner { - engine - .destroy(&id) - .expect("native owner can retry verified disposal"); - } else { - engine - .cleanup_failed_start() - .expect("wire retry confirms disposal"); - assert!(engine.lock_failed_starts().unwrap().is_empty()); - } - } else { - assert!( - registered.is_none(), - "disposed startup needs no native barrier" - ); - } - assert!(engine.lock_sessions().unwrap().is_empty()); - assert!( - server.input_was_closed(), - "the cancelled startup owns process termination" - ); - assert!( - plugin_operations::test_capture::take(CANCELLED_PLUGIN).is_empty(), - "a cancelled start records no plugin operation result" - ); - } - } - - #[test] - fn native_owner_retains_indexing_cancellation_after_registration() { - const CANCELLED_PLUGIN: &str = "io.example.indexing-cancel-registered"; - let workspace = TemporaryMavenWorkspace::recursive("indexing-owned-startup"); - let root = workspace.root.canonicalize().unwrap(); - let mut policy = IndexingPolicyFixture::new(root.clone()); - let server = ScriptedServer::new(); - server.block_cleanup(true); - let engine = LspEngine::with_launcher(server.launcher()); - let mut request = start_request(&server); - request.provider_id = "python".into(); - request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - request.working_directory = root.to_string_lossy().into_owned(); - request.startup_operation = Some(AttemptHandoff { - plugin_id: CANCELLED_PLUGIN.to_string(), - operation_id: "indexing-cancel-after-registration".to_string(), - elapsed_ms: 5, - }); - let mut registered = None; - let result = engine.start_server_owned(request, |id| { - registered = Some(id.to_owned()); - // Revoke between the initial policy check and initialize write. - policy.exclude(&["reactor"]); - }); - assert!(matches!(result.unwrap_err().code, ErrorCode::Cancelled)); - let id = registered.expect("native owner received its session"); - assert!(engine.destroy(&id).is_err()); - assert!(engine.session(&id).is_ok()); - server.block_cleanup(false); - engine - .destroy(&id) - .expect("native owner confirms process disposal"); - assert!(engine.session(&id).is_err()); - assert!( - plugin_operations::test_capture::take(CANCELLED_PLUGIN).is_empty(), - "a cancelled start records no plugin operation result" - ); - } - - #[test] - fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions() { - let workspace = TemporaryMavenWorkspace::recursive("indexing-released-standalone"); - let root = workspace.root.canonicalize().unwrap(); - let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - let status = crate::project::indexing::configure(serde_json::from_value(json!({ - "root": root, "manualExcludedDirectories": ["reactor"], "includedDirectories": [], "gitIgnoreEnabled": false - })).unwrap()).unwrap(); - let old = crate::project::indexing::context(&root).unwrap(); - crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { - root: root.to_string_lossy().into_owned(), - revision: status.revision, - owner_id: None, - }) - .unwrap(); - assert!( - old.check().is_err(), - "late inventory readers must remain cancelled" - ); - let harness = Harness::start(|request| { - workspace.configure(request); - request.root_uri = root_uri.clone(); - request.initialization_options = - Some(json!({"settings":{"java":{"import":{"exclusions":["**/vendor/**"]}}}})); - }); - let initialize = notifications(&harness, "initialize").pop().unwrap(); - assert_eq!( - initialize["params"]["initializationOptions"]["settings"]["java"]["import"] - ["exclusions"], - json!(["**/vendor/**"]) - ); - let file_uri = url::Url::from_file_path(root.join("reactor/Visible.java")) - .unwrap() - .to_string(); - assert!(!crate::project::indexing::uri_is_excluded(&root_uri, &file_uri).unwrap()); - } - - #[test] - fn indexing_cold_start_resolves_git_before_provider_initialization() { - let workspace = TemporaryMavenWorkspace::recursive("indexing-cold-start"); - let root = workspace.root.canonicalize().unwrap(); - std::fs::create_dir_all(root.join("ignored")).unwrap(); - std::fs::write(root.join("ignored/hidden.txt"), "hidden").unwrap(); - std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap(); - let git = crate::git::execute_git_readonly( - &root.to_string_lossy(), - &["init".into(), "--quiet".into()], - None, - ) - .unwrap(); - assert_eq!(git.exit_code, 0, "{}", git.stderr); - let status = crate::project::indexing::configure(serde_json::from_value(json!({ - "root": root, "manualExcludedDirectories": [], "includedDirectories": [], "gitIgnoreEnabled": true - })).unwrap()).unwrap(); - let harness = Harness::start(|request| { - workspace.configure(request); - request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - request.initialization_options = - Some(json!({"settings":{"java":{"import":{"exclusions":["**/vendor/**"]}}}})); - }); - let initialize = notifications(&harness, "initialize").pop().unwrap(); - let excluded = root.join("ignored").to_string_lossy().replace('\\', "/"); - assert_eq!( - initialize["params"]["initializationOptions"]["settings"]["java"]["import"] - ["exclusions"], - json!(["**/vendor/**", excluded, format!("{excluded}/**")]) - ); - for (provider, pointer) in [ - ("go", "/gopls/directoryFilters"), - ("rust", "/rust-analyzer/files/exclude"), - ] { - let value = crate::lsp::languages::indexing::configuration( - provider, - &harness.session().root_uri, - None, - ) - .unwrap(); - assert!(value - .pointer(pointer) - .unwrap() - .as_array() - .unwrap() - .iter() - .any(|item| item - == if provider == "go" { - "-ignored" - } else { - "ignored" - })); - } - crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { - root: root.to_string_lossy().into_owned(), - revision: status.revision, - owner_id: None, - }) - .unwrap(); - } - - #[test] - fn indexing_watcher_rebuild_publishes_recomputed_git_exclusions_to_java() { - // This regression owns indexing notifications, not Maven reactor discovery. - // Keep unrelated recursive projects out of the real Git ignore inventory. - let workspace = ScratchDirectory(std::env::temp_dir().join(format!( - "lithe-indexing-watcher-provider-{}", - std::process::id() - ))); - std::fs::create_dir_all(&workspace.0).unwrap(); - let root = workspace.0.canonicalize().unwrap(); - std::fs::create_dir_all(root.join("ignored")).unwrap(); - std::fs::write(root.join("ignored/hidden.txt"), "hidden").unwrap(); - std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap(); - let git = crate::git::execute_git_readonly( - &root.to_string_lossy(), - &["init".into(), "--quiet".into()], - None, - ) - .unwrap(); - assert_eq!(git.exit_code, 0, "{}", git.stderr); - let mut harness = Harness::start(|request| { - request.provider_id = "java".into(); - request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - request.working_directory = root.to_string_lossy().into_owned(); - request.cache_directory = Some(root.join("cache").to_string_lossy().into_owned()); - }); - harness - .server - .complete_java_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - // Production notifications address the registry. Install this scripted - // session under a fixture-unique key and remove it even on assertion failure. - struct Registered { - key: String, - root: PathBuf, - revision: u64, - } - impl Drop for Registered { - fn drop(&mut self) { - engine().sessions.lock().unwrap().remove(&self.key); - let _ = crate::project::indexing::release( - crate::project::indexing::ReleaseIndexingRequest { - owner_id: None, - root: self.root.to_string_lossy().into_owned(), - revision: self.revision, - }, - ); - } - } - let mut registered = Registered { - key: root.to_string_lossy().into_owned(), - root: root.clone(), - revision: 0, - }; - engine() - .sessions - .lock() - .unwrap() - .insert(registered.key.clone(), harness.session()); - let status = crate::project::indexing::configure( - serde_json::from_value(json!({ - "root":root,"manualExcludedDirectories":[],"includedDirectories":[], - "gitIgnoreEnabled":true,"paths":["ignored"] - })) - .unwrap(), - ) - .unwrap(); - registered.revision = status.revision; - let before = notifications(&harness, "workspace/didChangeConfiguration"); - assert!( - before.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"] - .as_array() - .unwrap() - .len() - >= 2 - ); - // Hosts first refresh with no paths, before rebuilding their inventory. - let refreshed = crate::project::indexing::configure( - serde_json::from_value(json!({ - "root":root,"manualExcludedDirectories":[],"includedDirectories":[], - "gitIgnoreEnabled":true,"refresh":true,"paths":[] - })) - .unwrap(), - ) - .unwrap(); - registered.revision = refreshed.revision; - let host_refresh = notifications(&harness, "workspace/didChangeConfiguration"); - assert_eq!( - host_refresh.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"], - before.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"] - ); - crate::project::files::update_search_index( - serde_json::from_value(json!({ - "root":root,"paths":[".gitignore"] - })) - .unwrap(), - ) - .unwrap(); - let after = notifications(&harness, "workspace/didChangeConfiguration"); - assert!(after.len() > before.len()); - assert_eq!( - after.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"], - before.last().unwrap()["params"]["settings"]["java"]["import"]["exclusions"] - ); - assert_eq!( - harness.session().indexing_revision.load(Ordering::Acquire), - crate::project::indexing::context(&root).unwrap().revision - ); - } - - #[test] - fn indexing_change_withdraws_open_working_copies_and_rejects_sync() { - let workspace = TemporaryMavenWorkspace::recursive("indexing-working-copy"); - let root = workspace.root.canonicalize().unwrap(); - let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - let mut harness = Harness::start(|request| { - request.root_uri = root_uri.clone(); - request.working_directory = root.to_string_lossy().into_owned(); - }); - harness.server.complete_initialize(ready_capabilities()); - harness.await_state(LspLifecycleState::Ready); - let uri = url::Url::from_file_path(root.join("reactor/main.go")) - .unwrap() - .to_string(); - harness.sync(&uri, "package main"); - let status = crate::project::indexing::configure( - serde_json::from_value(json!({ - "root":root,"manualExcludedDirectories":["reactor"], - "includedDirectories":[],"gitIgnoreEnabled":false - })) - .unwrap(), - ) - .unwrap(); - apply_indexing_to_sessions(&root, vec![harness.session()]).unwrap(); - assert!(!harness - .session() - .lock_state() - .unwrap() - .client - .open_documents - .contains_key(&uri)); - assert!(crate::project::indexing::uri_is_excluded(&root_uri, &uri).unwrap()); - let session = harness.session(); - assert!(session - .sync_document(SyncDocumentRequest { - session_id: harness.session_id.clone(), - uri: uri.clone(), - language_id: "go".into(), - text: "package main".into(), - content_changes: Vec::new(), - }) - .is_err()); - session.handle_server_message(json!({"jsonrpc":"2.0","method":"textDocument/publishDiagnostics", "params":{ - "uri":uri,"diagnostics":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"severity":1,"message":"late"}] - }}).to_string()).unwrap(); - assert!(!session - .lock_state() - .unwrap() - .client - .diagnostics - .contains_key(&uri)); - - assert_eq!( - harness.session().indexing_revision.load(Ordering::Acquire), - status.revision - ); - crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { - owner_id: None, - root: root.to_string_lossy().into_owned(), - revision: status.revision, - }) - .unwrap(); - } - - /// Criterion 8: diagnostics for a stale document version are ignored. - /// Criterion 9: closing a document clears document and diagnostic state. - #[test] - fn diagnostics_follow_the_current_document_version_and_clear_on_close() { - let mut harness = Harness::ready(); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - harness.sync(uri, "package main\nfunc main() {}"); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { - "uri": uri, - "version": 2, - "diagnostics": [{ - "range": { - "start": { "line": 1, "character": 0 }, - "end": { "line": 1, "character": 4 } - }, - "severity": 1, - "message": "current" - }] - } - })); - harness.await_event(|event| { - event.kind == "diagnostics" - && event - .diagnostics - .as_ref() - .is_some_and(|list| list.len() == 1) - }); - assert_eq!(harness.snapshot().diagnostic_versions[uri], 2); - - // Version 1 is behind the open document, so it cannot replace version 2. - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { "uri": uri, "version": 1, "diagnostics": [] } - })); - thread::sleep(Duration::from_millis(50)); - harness.poll(); - assert_eq!( - harness.snapshot().diagnostic_versions[uri], - 2, - "a stale version must not clear current diagnostics" - ); - - harness.session().close_document(uri).unwrap(); - let snapshot = harness.snapshot(); - assert!(!snapshot.open_documents.contains_key(uri)); - assert!(!snapshot.diagnostic_versions.contains_key(uri)); - assert!( - harness.notification("textDocument/didClose").is_some(), - "the server must be told the document closed" - ); - // Clearing is published so the editor drops its markers, rather than - // leaving them until the next unrelated publish. - let cleared = harness - .poll() - .iter() - .rev() - .find(|event| event.kind == "diagnostics" && event.uri.as_deref() == Some(uri)); - assert_eq!( - cleared - .and_then(|event| event.diagnostics.as_ref()) - .map(Vec::len), - Some(0) - ); - } - - /// A declarative plugin start handed off by the host ends in exactly one Core - /// result: `initialize` success, an exit before it, or nothing for a user stop. - /// Later exits belong to the session, not the start. A plugin API 1 server - /// starts host-owned, so the handoff alone names the plugin; a session owned - /// by a different plugin records nothing. - #[test] - fn declarative_plugin_start_records_one_host_operation_per_attempt() { - const PLUGIN: &str = "io.example.declarative-start"; - const OTHER: &str = "io.example.declarative-start-other"; - let handoff = |operation_id: &'static str, owner: Option<&'static str>| { - move |request: &mut StartServerRequest| { - request.plugin_id = owner.map(str::to_string); - request.startup_operation = Some(AttemptHandoff { - plugin_id: PLUGIN.to_string(), - operation_id: operation_id.to_string(), - elapsed_ms: 5, - }); - } - }; - - let mut ready = Harness::start(handoff("declarative-ready", Some(PLUGIN))); - ready.server.complete_initialize(ready_capabilities()); - ready.await_state(LspLifecycleState::Ready); - ready.server.exit(Some(1)); - ready.await_state(LspLifecycleState::Failed); - - let mut exited = Harness::start(handoff("declarative-exited", None)); - exited.server.exit(Some(2)); - exited.await_state(LspLifecycleState::Failed); - - let mut stopped = Harness::start(handoff("declarative-stopped", Some(PLUGIN))); - stopped.session().stop().unwrap(); - stopped.await_state(LspLifecycleState::Stopped); - - let mut foreign = Harness::start(handoff("declarative-foreign", Some(OTHER))); - foreign.server.exit(Some(3)); - foreign.await_state(LspLifecycleState::Failed); - assert!(plugin_operations::test_capture::take(OTHER).is_empty()); - - let facts = plugin_operations::test_capture::take(PLUGIN); - assert!(facts - .iter() - .all(|fact| std::ptr::eq(fact.contribution, &LANGUAGE_SERVER_START))); - let results: Vec<_> = facts - .into_iter() - .map(|fact| (fact.operation_id, fact.failure)) - .collect(); - assert_eq!( - results, - [ - (Some("declarative-ready".to_string()), None), - ( - Some("declarative-exited".to_string()), - Some(AttemptStage::Exit) - ), - ] - ); - } - - /// startServer failing after spawn is a `launch` failure, and an initialize - /// timeout decided under the state lock is the only result even when the - /// response arrives afterwards. - #[test] - fn declarative_plugin_start_attributes_write_failure_and_timeout() { - const PLUGIN: &str = "io.example.declarative-start-failures"; - let handoff = |operation_id: &str, request: &mut StartServerRequest| { - request.plugin_id = Some(PLUGIN.to_string()); - request.startup_operation = Some(AttemptHandoff { - plugin_id: PLUGIN.to_string(), - operation_id: operation_id.to_string(), - elapsed_ms: 5, - }); - }; - - let broken = ScriptedServer::new(); - broken.break_input(); - let engine = LspEngine::with_launcher(broken.launcher()); - let mut request = start_request(&broken); - handoff("declarative-write-failed", &mut request); - assert!(engine.start_server(request).is_err()); - - let mut timed_out = Harness::start(|request| { - handoff("declarative-timed-out", request); - request.initialize_timeout_milliseconds = 60_000; - }); - timed_out - .session() - .expire_deadlines_at(Instant::now() + Duration::from_secs(61)); - timed_out.await_state(LspLifecycleState::Failed); - timed_out.server.complete_initialize(ready_capabilities()); - - let results: Vec<_> = plugin_operations::test_capture::take(PLUGIN) - .into_iter() - .map(|fact| (fact.operation_id, fact.failure)) - .collect(); - assert_eq!( - results, - [ - ( - Some("declarative-write-failed".to_string()), - Some(AttemptStage::Launch) - ), - ( - Some("declarative-timed-out".to_string()), - Some(AttemptStage::Timeout) - ), - ] - ); - } - - /// Criterion 10: shutdown sends exit after the response, and a shutdown that - /// is never answered force-terminates. - #[test] - fn shutdown_sends_exit_after_the_response_and_force_terminates_on_timeout() { - let mut harness = Harness::ready(); - harness.session().stop().unwrap(); - let shutdown_id = harness - .server - .await_request("shutdown") - .expect("stop should request shutdown"); - assert!( - harness.notification("exit").is_none(), - "exit must not precede the shutdown response" - ); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": shutdown_id, - "result": null - })); - assert!( - harness.server.await_notification("exit"), - "exit must follow the shutdown response" - ); - harness.server.exit(Some(0)); - harness.await_state(LspLifecycleState::Stopped); - - let mut silent = Harness::start(|request| { - request.shutdown_timeout_milliseconds = 30; - }); - silent.server.complete_initialize(ready_capabilities()); - silent.await_state(LspLifecycleState::Ready); - silent.session().stop().unwrap(); - silent - .server - .await_request("shutdown") - .expect("stop should request shutdown"); - // No response ever arrives, so the deadline must kill the process - // instead of leaving the session stuck in Stopping. - silent.await_state(LspLifecycleState::Stopped); - silent.await_event(|event| { - event.kind == "log" - && event.error.as_ref().is_some_and(|error| { - error.stage == "shutdown" && error.code == "shutdownTimeout" - }) - }); - } - - /// Criterion 11: a malformed `Content-Length` is a transport failure. - #[test] - fn a_malformed_content_length_header_fails_the_session_in_transport() { - let mut harness = Harness::ready(); - harness.server.send_raw(b"Content-Length: banana\r\n\r\n{}"); - harness.await_state(LspLifecycleState::Failed); - - let failure = harness - .events - .iter() - .find_map(|event| event.error.as_ref()) - .expect("bad framing should be reported as a runtime error"); - assert_eq!(failure.code, "transportFailed"); - assert_eq!(failure.stage, "transport"); - } - - /// Criterion 12: a partial frame is retained until it completes. - /// Criterion 13: consecutive frames are handled in order. - #[test] - fn partial_frames_are_buffered_and_consecutive_frames_arrive_in_order() { - let mut harness = Harness::ready(); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - - let split = |uri: &str, message: &str| { - let body = json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { - "uri": uri, - "version": 1, - "diagnostics": [{ - "range": { - "start": { "line": 0, "character": 0 }, - "end": { "line": 0, "character": 1 } - }, - "severity": 1, - "message": message - }] - } - }) - .to_string(); - format!("Content-Length: {}\r\n\r\n{body}", body.len()) - }; - - let first = split(uri, "first"); - let boundary = first.len() - 12; - harness.server.send_raw(first[..boundary].as_bytes()); - thread::sleep(Duration::from_millis(40)); - harness.poll(); - assert!( - !harness - .events - .iter() - .any(|event| event.kind == "diagnostics"), - "an incomplete frame must not be delivered" - ); - - // The tail of the first frame and a whole second frame arrive together, - // which is exactly how a stream coalesces writes. - harness - .server - .send_raw(format!("{}{}", &first[boundary..], split(uri, "second")).as_bytes()); - harness.await_event(|event| { - event - .diagnostics - .as_ref() - .and_then(|list| list.first()) - .is_some_and(|diagnostic| diagnostic.message == "second") - }); - let delivered: Vec<_> = harness - .events - .iter() - .filter(|event| event.kind == "diagnostics") - .filter_map(|event| event.diagnostics.as_ref()) - .filter_map(|list| list.first()) - .map(|diagnostic| diagnostic.message.clone()) - .collect(); - assert_eq!(delivered, vec!["first".to_string(), "second".to_string()]); - assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); - } - - /// Criterion 14: dynamic registration and unregistration change availability. - #[test] - fn dynamic_capability_registration_and_unregistration_change_availability() { - let mut harness = Harness::start(|_| {}); - // Formatting is absent from the static capabilities, so it can only - // become available through dynamic registration. - harness - .server - .complete_initialize(json!({ "hoverProvider": true })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/main.go"; - harness.sync(uri, "package main"); - assert!(harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some("op-formatting".to_string()), - operation: LspSemanticOperation::Formatting, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - "op-formatting".to_string(), - ) - .is_err()); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": "registration-1", - "method": "client/registerCapability", - "params": { - "registrations": [{ - "id": "formatting-1", - "method": "textDocument/formatting", - "registerOptions": {} - }] - } - })); - let registered = harness - .await_event(|event| { - event - .capabilities - .as_ref() - .is_some_and(|names| names.iter().any(|name| name == "formatting")) - }) - .clone(); - assert_eq!(registered.kind, "featuresChanged"); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": "registration-2", - "method": "client/unregisterCapability", - "params": { - "unregisterations": [{ - "id": "formatting-1", - "method": "textDocument/formatting" - }] - } - })); - // The initialize handshake also emitted a formatting-free feature set, so - // the withdrawal is only identifiable by coming after the registration. - let registered_at = registered.sequence; - harness.await_event(|event| { - event.kind == "featuresChanged" - && event.sequence > registered_at - && event - .capabilities - .as_ref() - .is_some_and(|names| !names.iter().any(|name| name == "formatting")) - }); - assert!( - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some("op-formatting-2".to_string()), - operation: LspSemanticOperation::Formatting, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - "op-formatting-2".to_string(), - ) - .is_err(), - "an unregistered capability must stop being offered" - ); - } - - /// Criterion 15: replacing the workspace stops the old root and clears it. - #[test] - fn replacing_the_workspace_stops_the_old_root_and_clears_its_state() { - let old_server = ScriptedServer::new(); - let engine = LspEngine::with_launcher(old_server.launcher()); - let old = engine.start_server(start_request(&old_server)).unwrap(); - old_server.complete_initialize(ready_capabilities()); - let old_session = engine.session(&old.session_id).unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline - && old_session.snapshot().unwrap().state != LspLifecycleState::Ready - { - thread::sleep(Duration::from_millis(2)); - } - let uri = "file:///workspace/main.go"; - old_session - .sync_document(SyncDocumentRequest { - session_id: old.session_id.clone(), - uri: uri.to_string(), - language_id: "go".to_string(), - text: "package main".to_string(), - content_changes: Vec::new(), - }) - .unwrap(); - old_server.send(json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { - "uri": uri, - "version": 1, - "diagnostics": [{ - "range": { - "start": { "line": 0, "character": 0 }, - "end": { "line": 0, "character": 1 } - }, - "severity": 1, - "message": "old root" - }] - } - })); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline - && !old_session - .snapshot() - .unwrap() - .diagnostic_versions - .contains_key(uri) - { - thread::sleep(Duration::from_millis(2)); - } - - old_session.stop().unwrap(); - let shutdown = old_server.await_request("shutdown").unwrap(); - old_server.send(json!({ "jsonrpc": "2.0", "id": shutdown, "result": null })); - old_server.exit(Some(0)); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline - && old_session.snapshot().unwrap().state != LspLifecycleState::Stopped - { - thread::sleep(Duration::from_millis(2)); - } - - let stopped = old_session.snapshot().unwrap(); - assert_eq!(stopped.root_uri, "file:///workspace"); - assert_eq!(stopped.state, LspLifecycleState::Stopped); - assert!(stopped.open_documents.is_empty()); - assert!(stopped.diagnostic_versions.is_empty()); - assert!(stopped.pending_operation_ids.is_empty()); - assert!( - old_server.input_was_closed(), - "the old root's stdin must be released" - ); - - // Only a stopped session may be destroyed, and a destroyed one is - // unreachable, so the replacement cannot inherit any of its state. - engine.destroy(&old.session_id).unwrap(); - assert!(engine.session(&old.session_id).is_err()); - assert!(old_session - .sync_document(SyncDocumentRequest { - session_id: old.session_id.clone(), - uri: uri.to_string(), - language_id: "go".to_string(), - text: "package main".to_string(), - content_changes: Vec::new(), - }) - .is_err()); - } - - #[test] - fn semantic_operations_are_protocol_methods_but_never_expose_request_ids() { - assert_eq!( - semantic_method(LspSemanticOperation::Definition), - "textDocument/definition" - ); - assert_eq!( - semantic_capability(LspSemanticOperation::VirtualDocument), - Some("executeCommand") - ); - } - - #[test] - fn workspace_execute_command_does_not_require_an_open_document() { - let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "executeCommandProvider": { "commands": ["source.fix"] } - })); - harness.await_state(LspLifecycleState::Ready); - let operation_id = harness.engine.next_operation_id(); - - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::ExecuteCommand, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: Some(json!({ - "title": "Apply fix", - "command": "source.fix", - "arguments": [] - })), - }, - operation_id, - ) - .expect("workspace commands should not be gated on an open document"); - - let request = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "workspace/executeCommand") - .expect("the command should reach the language server"); - assert_eq!(request["params"]["command"], "source.fix"); - assert!(request["params"].get("textDocument").is_none()); - } - - #[test] - fn java_start_enables_and_normalizes_class_file_navigation() { - let completion_fixture: Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/lsp/java-completion-v1.json" - )) - .unwrap(); - let root = std::env::temp_dir().join(format!( - "lithe-core-java-navigation-tests-{}", - std::process::id() - )); - let cache = root.join("cache"); - let packaged_configuration = packaged_jdtls_configuration(&root.join("installation")); - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.cache_directory = Some(cache.to_string_lossy().into_owned()); - request.runtime_executable_path = Some("/opt/lithe/jdk/bin/java".to_string()); - request.jdtls_launch_resources = Some(JdtlsLaunchResources { - launcher_jar_path: "/opt/lithe/jdtls/plugins/equinox.jar".to_string(), - configuration_directory: packaged_configuration.to_string_lossy().into_owned(), - lombok_agent_path: "/opt/lithe/jdtls/lombok/lombok.jar".to_string(), - java_debug_bundle_path: Some("/plugins/java-debug.jar".to_string()), - java_extension_bundle_paths: vec![ - "/plugins/java-debug.jar".to_string(), - "/plugins/java-test.jar".to_string(), - ], - }); - request.initialization_options = Some(json!({ - "extendedClientCapabilities": { "customCapability": true }, - "bundles": ["/plugins/catalog.jar"], - "settings": { "java": { "completion": completion_fixture["pluginCompletion"] } } - })); - }); - let initialize = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "initialize") - .expect("the initialize request should reach JDT LS"); - assert_eq!( - initialize["params"]["initializationOptions"]["extendedClientCapabilities"] - ["classFileContentsSupport"], - true - ); - assert_eq!( - initialize["params"]["initializationOptions"]["extendedClientCapabilities"] - ["customCapability"], - true - ); - assert_eq!( - initialize["params"]["initializationOptions"]["bundles"], - json!([ - "/plugins/catalog.jar", - "/plugins/java-debug.jar", - "/plugins/java-test.jar" - ]) - ); - - harness - .server - .complete_java_initialize(json!({ "definitionProvider": true })); - harness.await_state(LspLifecycleState::Ready); - let expected_completion = &completion_fixture["javaSettings"]["completion"]; - assert_eq!( - initialize["params"]["initializationOptions"]["settings"]["java"]["completion"], - *expected_completion, - ); - assert!(harness - .server - .await_notification("workspace/didChangeConfiguration")); - let notification = harness - .server - .messages() - .into_iter() - .find(|message| message["method"] == "workspace/didChangeConfiguration") - .unwrap(); - assert_eq!( - notification["params"]["settings"]["java"]["completion"], - *expected_completion - ); - harness.server.send(json!({ - "jsonrpc": "2.0", "id": "java-completion-config", "method": "workspace/configuration", - "params": { "items": completion_fixture["workspaceConfigurationSections"] - .as_array().unwrap().iter().map(|section| json!({ "section": section })).collect::>() } - })); - let configuration = await_reply(&harness, "java-completion-config"); - assert_eq!( - configuration["result"][0]["completion"], - *expected_completion - ); - assert_eq!(configuration["result"][1], *expected_completion); - assert_eq!( - configuration["result"][2], - expected_completion["guessMethodArguments"] - ); - assert_eq!( - configuration["result"][3], - expected_completion["favoriteStaticMembers"] - ); - assert_eq!( - configuration["result"][4], - expected_completion["filteredTypes"] - ); - assert_eq!(configuration["result"][5], Value::Null); - let uri = "file:///workspace/Main.java"; - harness.sync(uri, "class Main { String value; }"); - let operation_id = harness.request(LspSemanticOperation::Definition, uri); - let request_id = harness - .server - .await_request("textDocument/definition") - .expect("the definition request should reach JDT LS"); - let virtual_uri = "jdt://contents/java.base/java/lang/String.class?=demo"; - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": [{ - "uri": virtual_uri, - "range": { - "start": { "line": 10, "character": 4 }, - "end": { "line": 10, "character": 10 } - } - }] - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - let location = &event.result.as_ref().unwrap()["locations"][0]; - assert_eq!(location["uri"], virtual_uri); - assert_eq!(location["isReadOnly"], true); - assert_eq!(location["displayPath"], "java.base/java/lang/String.java"); - - let _ = std::fs::remove_dir_all(root); - } - - #[test] - fn java_virtual_document_returns_decompiled_text_without_an_open_document() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.cache_directory = Some("/tmp/lithe-lsp-engine-tests".to_string()); - }); - harness.server.complete_java_initialize(json!({ - "executeCommandProvider": { "commands": ["java.decompile"] } - })); - harness.await_state(LspLifecycleState::Ready); - let operation_id = harness.engine.next_operation_id(); - let virtual_uri = "jdt://contents/java.base/java/lang/String.class"; - - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::VirtualDocument, - uri: None, - virtual_uri: Some(virtual_uri.to_string()), - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .expect("virtual documents should not require an open file"); - - let request_id = harness - .server - .await_request("workspace/executeCommand") - .expect("the decompile command should reach JDT LS"); - let request = harness - .server - .messages() - .into_iter() - .find(|message| message["id"] == request_id) - .expect("the decompile request should be recorded"); - assert_eq!(request["params"]["command"], "java.decompile"); - assert_eq!(request["params"]["arguments"], json!([virtual_uri])); - - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": "public final class String {}" - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert_eq!( - event.result, - Some(json!({ - "text": "public final class String {}" - })) - ); - assert!(event.error.is_none()); - } - - fn request_java_entrypoints(harness: &Harness) -> (String, String) { - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaEntrypoints, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .expect("entry-point discovery should not require an open file"); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .expect("main-class discovery should reach JDT LS"); - (operation_id, request_id) - } - - #[test] - fn document_saves_honor_server_options_and_never_replace_newer_editor_text() { - let fixture: Value = serde_json::from_str(include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../shared/fixtures/lsp/document-save-v1.json" - ))) - .unwrap(); - for case in fixture["cases"].as_array().unwrap() { - let option = &case["saveOption"]; - let mut harness = Harness::start(|_| {}); - let mut capabilities = ready_capabilities(); - capabilities["textDocumentSync"] = json!({"change": 1, "save": option}); - harness.server.complete_initialize(capabilities); - harness.await_state(LspLifecycleState::Ready); - let uri = case["uri"].as_str().unwrap(); - let saved_text = case["savedText"].as_str().unwrap(); - harness.sync(uri, saved_text); - let saved = || SaveDocumentRequest { - session_id: harness.session_id.clone(), - uri: uri.to_string(), - text: saved_text.to_string(), - }; - let supported = case["sent"].as_bool().unwrap(); - assert_eq!(harness.session().save_document(saved()).unwrap(), supported); - if supported { - let notification = harness - .server - .await_notification_at("textDocument/didSave", 0) - .unwrap(); - assert_eq!(notification["params"]["textDocument"]["uri"], uri); - assert_eq!( - notification["params"].get("text"), - case["includeText"] - .as_bool() - .unwrap() - .then_some(&json!(saved_text)) - ); - } - harness.sync(uri, "newer unsaved edit"); - assert!(!harness.session().save_document(saved()).unwrap()); - let session = harness.session(); - let state = session.lock_state().unwrap(); - assert_eq!( - state.client.open_documents[uri].text.as_ref(), - "newer unsaved edit" - ); - assert_eq!(state.client.open_documents[uri].version, 2); - } - } - - fn java_entrypoints_harness() -> Harness { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.cache_directory = Some("/tmp/lithe-lsp-engine-tests".to_string()); - }); - harness.server.complete_java_initialize(json!({ - "executeCommandProvider": { "commands": ["vscode.java.resolveMainClass"] } - })); - harness.await_state(LspLifecycleState::Ready); - harness - } - - fn queue_java_entrypoints(harness: &Harness, operation: &str) -> Result<(), CoreError> { - harness.session().request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation.into()), - operation: LspSemanticOperation::JavaEntrypoints, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation.into(), - ) - } - - #[test] - fn java_entrypoints_wait_for_profiles_and_project_jobs_before_querying_the_server() { - let mut harness = java_entrypoints_harness(); - let session = harness.session(); - session.lock_state().unwrap().maven_profile_status = MavenProfileTaskStatus::Running; - queue_java_entrypoints(&harness, "launch-discovery").unwrap(); - assert!(queue_java_entrypoints(&harness, "launch-discovery").is_err()); - session.pump_outbound_maintenance(); - assert!(!harness - .server - .messages() - .iter() - .any(|m| m["method"] == "workspace/executeCommand")); - { - let mut state = session.lock_state().unwrap(); - state.java_builds.observe_progress( - crate::lsp::languages::jdt_build::ProjectJobProgress::Begin { - token: "project-update".into(), - label: "Update project app".into(), + let event = session + .poll_events() + .unwrap() + .into_iter() + .find(|event| event.kind == "log") + .unwrap(); + assert_eq!(event.level.as_deref(), Some("warn")); + let error = event.error.unwrap(); + assert_eq!(error.code, "processCleanupFailed"); + assert_eq!(error.stage, "processCleanup"); + assert!(error.underlying_message.is_none()); + for (stage, code) in [ + ("stderr", "upstreamStderr"), + ("stderr", "stderrReadFailed"), + ("shutdown", "shutdownTimeout"), + ] { + session.log_issue( + "warning", + stage, + code, + if code == "upstreamStderr" { + EngineLog::StderrReceived + } else if code == "stderrReadFailed" { + EngineLog::StderrReadFailed + } else { + EngineLog::ShutdownTimedOut }, - Instant::now(), + "Updated diagnostic wording", + None, ); - state.maven_profile_status = MavenProfileTaskStatus::Succeeded; + let event = session + .poll_events() + .unwrap() + .into_iter() + .find(|event| event.kind == "log") + .unwrap(); + assert_eq!(event.level.as_deref(), Some("warning")); + let error = event.error.unwrap(); + assert_eq!(error.stage, stage); + assert_eq!(error.code, code); } - session.pump_outbound_maintenance(); - assert!(!harness - .server - .messages() - .iter() - .any(|m| m["method"] == "workspace/executeCommand")); - session.lock_state().unwrap().java_builds.observe_progress( - crate::lsp::languages::jdt_build::ProjectJobProgress::End { - token: "project-update".into(), - }, - Instant::now(), + // Ordinary logs must remain unclassified even when their wording matches an issue. + session.log( + "warning", + EngineLog::StderrReceived, + "Language-server stderr", + None, ); - session.pump_outbound_maintenance(); - let id = harness - .server - .await_request("workspace/executeCommand") + let event = session + .poll_events() + .unwrap() + .into_iter() + .find(|event| event.kind == "log") .unwrap(); - harness - .server - .send(json!({"jsonrpc":"2.0","id":id,"result":[]})); - let event = harness.await_event(|e| { - e.operation_id.as_deref() == Some("launch-discovery") && e.kind == "requestCompleted" - }); - assert!(event.error.is_none(), "{event:?}"); - assert_eq!(event.result.as_ref().unwrap()["entries"], json!([])); + assert!(event.error.is_none()); } #[test] - fn java_entrypoints_waiters_cancel_timeout_and_stop_without_a_discovery_or_wire_cancellation() { - for mode in ["cancel", "timeout", "stop"] { - let mut harness = java_entrypoints_harness(); + fn lifecycle_catalog_identity_preserves_v1_event_without_extra_log() { + for role in [ + SessionRole::LanguageServer, + SessionRole::Vcs, + SessionRole::Build, + SessionRole::Toolchain, + SessionRole::Backend, + ] { + let harness = Harness::start(|request| { + request.role = role; + request.provider_id = "c++".into(); + request.log_subject = Some("git".into()); + request.plugin_id = Some("io.example.tools".into()); + }); let session = harness.session(); - session.lock_state().unwrap().maven_profile_status = MavenProfileTaskStatus::Running; - queue_java_entrypoints(&harness, mode).unwrap(); - match mode { - "cancel" => session.cancel_operation(mode).unwrap(), - "timeout" => session.expire_deadlines_at(Instant::now() + Duration::from_secs(601)), - _ => session.stop().unwrap(), + session.active.store(false, Ordering::Release); + session.kill_process(); + let mut state = session.state.lock().unwrap(); + state.events.clear(); + let sequence = state.next_sequence; + transition_locked(&session, &mut state, LspLifecycleState::Stopped, None); + assert!(!state.events.iter().any(|e| e.kind == "log")); + let event = state.events.front().unwrap(); + let (id, fields) = EngineLog::SessionUpdated.fact( + &session.log_identity, + &json!({"state": "stopped"}), + None, + ); + assert_eq!(event.event.as_deref(), Some(id.as_str())); + assert_eq!(event.fields.as_ref(), Some(&fields)); + assert_eq!( + event.channel.as_deref(), + Some(session.log_identity.channel().as_str()) + ); + assert_eq!(event.role, Some(role)); + assert_eq!(event.plugin_id.as_deref(), Some("io.example.tools")); + assert_eq!( + event.catalog_level, + Some(crate::diagnostics::record::LogLevel::Debug) + ); + let mut legacy = serde_json::to_value(event).unwrap(); + for key in [ + "channel", + "pluginId", + "role", + "event", + "fields", + "catalogLevel", + ] { + legacy.as_object_mut().unwrap().remove(key); } - let event = harness.await_event(|e| { - e.operation_id.as_deref() == Some(mode) && e.kind == "requestCompleted" - }); - assert!(event.error.is_some()); - assert!(session - .lock_state() - .unwrap() - .java_entrypoint_waiters - .is_empty()); - assert!(!harness.server.messages().iter().any(|m| { - m["params"]["command"] == "vscode.java.resolveMainClass" - || m["method"] == "$/cancelRequest" - })); + assert_eq!( + legacy, + json!({"type": "stateChanged", "sequence": sequence, + "providerId": "c++", "sessionId": session.id, "state": "stopped"}) + ); + state.events.clear(); + let error = runtime_error( + &session, + "processCleanupFailed", + "cleanup", + None, + None, + "Engine process cleanup failed", + None, + None, + ); + let (id, fields) = EngineLog::ProcessCleanupFailed.fact( + &session.log_identity, + &Value::Null, + Some(&error), + ); + push_cleanup_fact(&session, &mut state, id, fields, error); + let event = state.events.front().unwrap(); + assert_eq!( + event.channel.as_deref(), + Some(session.log_identity.channel().as_str()) + ); + assert_eq!( + event.catalog_level, + Some(crate::diagnostics::record::LogLevel::Warn) + ); + assert_eq!(event.kind, "log"); + assert_eq!(event.level.as_deref(), Some("warning")); + assert_eq!( + event.message.as_deref(), + Some("Engine process cleanup failed") + ); + assert!(event.detail.is_none() && event.state.is_none()); + assert_eq!( + event.error.as_ref().map(|error| error.code.as_str()), + Some("processCleanupFailed") + ); } } #[test] - fn java_entrypoints_configuration_wait_queue_is_bounded() { - let harness = java_entrypoints_harness(); - harness.session().lock_state().unwrap().maven_profile_status = - MavenProfileTaskStatus::Running; - for index in 0..128 { - queue_java_entrypoints(&harness, &format!("queued-{index}")).unwrap(); + fn v1_detail_is_independent_of_catalog_fields() { + let harness = Harness::start(|_| {}); + let session = harness.session(); + struct Cleanup(Arc); + impl Drop for Cleanup { + fn drop(&mut self) { + self.0.active.store(false, Ordering::Release); + self.0.kill_process(); + } } - assert!(queue_java_entrypoints(&harness, "overflow").is_err()); + let _cleanup = Cleanup(session.clone()); + session.poll_events().unwrap(); + let line = " upstream diagnostic "; + session.log_issue( + "warning", + "stderr", + "upstreamStderr", + EngineLog::StderrReceived.with_fields(json!({"diagnostic": line, "truncated": false})), + "Language-server stderr", + Some(line.into()), + ); + let event = session + .poll_events() + .unwrap() + .into_iter() + .find(|e| e.event.as_deref() == Some("lsp.stderr.received")) + .unwrap(); + assert_eq!(event.level.as_deref(), Some("warning")); + assert_eq!(event.message.as_deref(), Some("Language-server stderr")); + assert_eq!(event.detail.as_deref(), Some(line)); + assert_eq!(event.fields.as_ref().unwrap()["diagnostic"], line); + assert_eq!(event.fields.as_ref().unwrap()["truncated"], false); + // A JSON-looking v1 detail cannot supply or overwrite a catalog fact. + session.log( + "info", + EngineLog::StderrReceived.with_fields(json!({"diagnostic": "kept", "truncated": true})), + "Language-server stderr", + Some("{\"diagnostic\":\"overwritten\",\"truncated\":false}".into()), + ); + let event = session.poll_events().unwrap().into_iter().next().unwrap(); + let fields = event.fields.unwrap(); + assert_eq!(fields["diagnostic"], "kept"); + assert_eq!(fields["truncated"], true); } - fn begin_java_launch(harness: &Harness) -> (String, String) { - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .prepare_java_launch( - JavaPrepareLaunchRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - source_path: "/workspace/app/src/TestMain.java".to_string(), - main_class: Some("demo.TestMain".to_string()), - }, - operation_id.clone(), + #[test] + fn engine_logging_wire_fixture_preserves_defaults_and_routes_new_commands() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../shared/fixtures/diagnostics/engine-logging-v2.json" + )) + .unwrap(); + let request: StartServerRequest = serde_json::from_value(fixture["start"].clone()).unwrap(); + assert_eq!(request.role, SessionRole::Vcs); + assert_eq!( + SessionLogIdentity::new( + request.role, + &request.provider_id, + request.plugin_id.as_deref(), + request.log_subject.as_deref() ) - .expect("Java launch should start"); - let discovery = harness - .server - .await_request("workspace/executeCommand") - .expect("entry request"); - (operation_id, discovery) + .channel(), + "vcs/git" + ); + let mut legacy = fixture["start"].clone(); + legacy.as_object_mut().unwrap().remove("role"); + legacy.as_object_mut().unwrap().remove("logSubject"); + assert_eq!( + serde_json::from_value::(legacy) + .unwrap() + .role, + SessionRole::LanguageServer + ); + for name in ["trace", "drain", "resolveSubject"] { + assert!(crate::protocol::CoreCommand::parse( + fixture[name]["command"].as_str().unwrap() + ) + .is_some()); + } + let response: Value = serde_json::from_str(&crate::runtime::execute_json( + &fixture["resolveSubject"].to_string(), + )) + .unwrap(); + assert_eq!(response["data"], fixture["resolveSubject"]["result"]); + let request: SetDetailedDiagnosticsRequest = + serde_json::from_value(fixture["trace"]["payload"].clone()).unwrap(); + assert!(request.enabled); + let response: Value = + serde_json::from_str(&crate::runtime::execute_json(&fixture["drain"].to_string())) + .unwrap(); + assert_eq!(response["ok"], true); + assert!(response["data"]["events"].is_array()); + assert!(response["data"]["dropped"].as_u64().is_some()); } - fn answer_java_launch_entries(harness: &Harness, request_id: &str) { - harness.server.send(json!({"jsonrpc": "2.0", "id": request_id, "result": [ - {"mainClass": "demo.Other", "projectName": "app", "filePath": "/workspace/app/src/TestMain.java"}, - {"mainClass": "test.module/demo.TestMain", "projectName": "app", "filePath": "/workspace/app/src/TestMain.java"}, - {"mainClass": "demo.TestMain", "projectName": "lib", "filePath": "/workspace/lib/src/TestMain.java"} - ]})); - } + #[test] + fn detailed_diagnostics_waits_for_initialized_and_keeps_the_latest_request() { + for enabled in [true, false] { + let harness = Harness::start(|_| {}); + let session = harness.session(); + struct Cleanup(Arc); + impl Drop for Cleanup { + fn drop(&mut self) { + self.0.active.store(false, Ordering::Release); + self.0.kill_process(); + } + } + let _cleanup = Cleanup(session.clone()); + session.set_detailed_diagnostics(true).unwrap(); + if !enabled { + session.set_detailed_diagnostics(false).unwrap(); + } + assert!(!harness + .server + .messages() + .iter() + .any(|m| m["method"] == "$/setTrace")); + assert!(!session.lock_state().unwrap().detailed_diagnostics); - /// The composed operation must wait for the same import barrier as discovery. - #[test] - fn java_launch_preparation_waits_for_configuration_and_reclaims_queued_attempts() { - for outcome in ["launch", "cancel", "timeout", "stop"] { - let mut harness = java_entrypoints_harness(); - let session = harness.session(); - session.lock_state().unwrap().maven_profile_status = MavenProfileTaskStatus::Running; + // Drive the real handshake handler synchronously; no reader timing + // or sleep is needed to establish the notification ordering. + let initialize = harness.server.await_request("initialize").unwrap(); session - .prepare_java_launch( - JavaPrepareLaunchRequest { - session_id: harness.session_id.clone(), - operation_id: Some(outcome.into()), - source_path: "/workspace/app/src/TestMain.java".into(), - main_class: Some("demo.TestMain".into()), - }, - outcome.into(), + .handle_server_message( + json!({ + "jsonrpc":"2.0", "id":initialize, + "result":{"capabilities":ready_capabilities()} + }) + .to_string(), ) .unwrap(); - session.pump_outbound_maintenance(); - assert!(!harness + let methods: Vec<_> = harness .server .messages() - .iter() - .any(|message| message["method"] == "workspace/executeCommand")); - match outcome { - "launch" => { - session.lock_state().unwrap().maven_profile_status = - MavenProfileTaskStatus::Succeeded; - session.pump_outbound_maintenance(); - let request = harness - .server - .await_request("workspace/executeCommand") - .unwrap(); - answer_java_launch_entries(&harness, &request); - harness - .server - .await_request_at("workspace/executeCommand", 1) - .unwrap(); - session.cancel_operation(outcome).unwrap(); - } - "cancel" => session.cancel_operation(outcome).unwrap(), - "timeout" => session.expire_deadlines_at(Instant::now() + Duration::from_secs(601)), - _ => session.stop().unwrap(), + .into_iter() + .filter_map(|m| m["method"].as_str().map(str::to_owned)) + .collect(); + if enabled { + let initialized = methods.iter().position(|m| m == "initialized").unwrap(); + let trace = methods.iter().position(|m| m == "$/setTrace").unwrap(); + assert!(trace > initialized); + } else { + assert!(!methods.iter().any(|m| m == "$/setTrace")); } - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(outcome) && event.kind == "requestCompleted" - }); - assert!(event.error.is_some(), "{outcome}: {event:?}"); - let state = session.lock_state().unwrap(); - assert!(state.java_entrypoint_waiters.is_empty()); - assert!(!state.java_launches.contains_key(outcome)); + assert_eq!(session.lock_state().unwrap().detailed_diagnostics, enabled); + session.set_detailed_diagnostics(false).unwrap(); + assert_eq!( + harness.server.messages().last().unwrap()["params"], + json!({"value":"off"}) + ); } } #[test] - fn java_launch_preparation_owns_selection_build_and_classpath_under_one_operation() { - let mut harness = java_entrypoints_harness(); - let (operation, discovery) = begin_java_launch(&harness); - answer_java_launch_entries(&harness, &discovery); - let build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("build request"); - let request = harness.written_request(&build); - assert_eq!(request["params"]["command"], "vscode.java.buildWorkspace"); - let payload: Value = - serde_json::from_str(request["params"]["arguments"][0].as_str().unwrap()).unwrap(); - assert_eq!( - payload, - json!({"mainClass": "test.module/demo.TestMain", "projectName": "app", - "filePath": "/workspace/app/src/TestMain.java", "isFullBuild": false}) + fn upstream_catalog_messages_trace_toggle_and_v1_fields_coexist() { + let harness = Harness::start(|request| { + request.role = SessionRole::Vcs; + request.log_subject = Some("git".into()); + request.plugin_id = Some("io.example.git".into()); + request.provider_id = "opaque:provider:git".into(); + }); + let session = harness.session(); + struct Cleanup(Arc); + impl Drop for Cleanup { + fn drop(&mut self) { + self.0.active.store(false, Ordering::Release); + self.0.kill_process(); + } + } + let _cleanup = Cleanup(session.clone()); + let initialize = harness.server.await_request("initialize").unwrap(); + session + .handle_server_message( + json!({ + "jsonrpc":"2.0", "id":initialize, "result":{"capabilities":{}} + }) + .to_string(), + ) + .unwrap(); + session.poll_events().unwrap(); + session.log( + "warning", + EngineLog::Dropped.with_fields(json!({"count": 7})), + "Engine stderr lines dropped", + Some("count=7".into()), ); - assert!(!harness - .poll() + let dropped = session + .poll_events() + .unwrap() + .into_iter() + .find(|event| event.event.as_deref() == Some("log.dropped")) + .unwrap(); + assert_eq!(dropped.channel.as_deref(), Some("vcs/git")); + assert_eq!(dropped.fields.unwrap()["count"], 7); + for (method, expected) in [ + ("window/logMessage", "vcs.message.warning.logged"), + ("window/showMessage", "vcs.message.warning.shown"), + ] { + session.handle_server_message(json!({"jsonrpc":"2.0", "method":method, "params":{"type":2,"message":"warning token=private-value"}}).to_string()).unwrap(); + let events = session.poll_events().unwrap(); + let event = events + .iter() + .find(|e| e.event.as_deref() == Some(expected)) + .expect("upstream catalog event"); + assert_eq!(event.channel.as_deref(), Some("vcs/git")); + assert_eq!(event.plugin_id.as_deref(), Some("io.example.git")); + assert_eq!(event.role, Some(SessionRole::Vcs)); + assert_eq!( + event.catalog_level, + Some(crate::diagnostics::record::LogLevel::Warn) + ); + assert_eq!(event.message.as_deref(), Some(method)); + assert!(event.level.is_some() && event.detail.is_some()); + let fields = event.fields.as_ref().unwrap(); + assert_eq!(fields["severity"], "warning"); + assert!(!fields["diagnostic"] + .as_str() + .unwrap() + .contains("private-value")); + } + let trace = json!({"jsonrpc":"2.0", "method":"$/logTrace", "params":{ + "message":"trace token=fixture-secret", "verbose":json!({ + "textDocument":{"text":"private_source_marker"} + }).to_string() + }}) + .to_string(); + session.handle_server_message(trace.clone()).unwrap(); + assert!(!session + .poll_events() + .unwrap() .iter() - .any(|event| event.operation_id.as_deref() == Some(&operation))); - harness - .server - .send(json!({"jsonrpc": "2.0", "id": build, "result": 1})); - let paths = harness - .server - .await_request_at("workspace/executeCommand", 2) - .expect("classpath request"); + .any(|e| e.event.as_deref() == Some("vcs.trace.received"))); + session.set_detailed_diagnostics(true).unwrap(); assert_eq!( - harness.written_request(&paths)["params"], - json!({ - "command": "vscode.java.resolveClasspath", "arguments": ["test.module/demo.TestMain", "app"] - }) + harness.server.messages().last().unwrap()["params"], + json!({"value":"verbose"}) ); - harness.server.send(json!({"jsonrpc": "2.0", "id": paths, "result": [ - ["/workspace/app/custom-modules"], ["/workspace/app/custom-tests", "/cache/junit.jar"] - ]})); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(&operation)) - .clone(); - assert!(event.error.is_none(), "{event:?}"); + session.handle_server_message(trace.clone()).unwrap(); + let event = session + .poll_events() + .unwrap() + .into_iter() + .find(|e| e.event.as_deref() == Some("vcs.trace.received")) + .unwrap(); assert_eq!( - event.result.unwrap(), - json!({"kind": "ready", "target": { - "mainClass": "test.module/demo.TestMain", "projectName": "app", - "modulePaths": ["/workspace/app/custom-modules"], "classPaths": ["/workspace/app/custom-tests", "/cache/junit.jar"] - }}) + event.catalog_level, + Some(crate::diagnostics::record::LogLevel::Debug) + ); + assert_eq!(event.level.as_deref(), Some("info")); + let fields = event.fields.unwrap(); + assert_eq!(fields["diagnostic"], "trace token="); + let encoded = crate::diagnostics::record::encode_log_batch( + serde_json::from_value(json!({"validateCatalog":true,"events":[{ + "ts":"2026-11-03T00:00:00.000Z", "seq":1, "level":"DEBUG", + "event":"vcs.trace.received", "msg":"", "fields":fields + }]})) + .unwrap(), ); + let line = encoded.results[0].line.as_ref().unwrap(); + assert!(!line.contains("private_source_marker")); + assert!(!line.contains("fixture-secret")); + session.set_detailed_diagnostics(false).unwrap(); assert_eq!( - harness - .poll() - .iter() - .filter(|event| event.operation_id.as_deref() == Some(&operation)) - .count(), - 1 + harness.server.messages().last().unwrap()["params"], + json!({"value":"off"}) ); - assert!(harness.snapshot().pending_operation_ids.is_empty()); - assert!(harness - .session() - .lock_state() + session.handle_server_message(trace).unwrap(); + assert!(!session + .poll_events() .unwrap() - .java_launches - .is_empty()); - } - - #[test] - fn java_launch_preparation_preserves_failed_build_evidence_with_resolved_paths() { - for (status, code) in [(0, "javaBuildFailed"), (2, "javaBuildCompilationErrors")] { - let mut harness = java_entrypoints_harness(); - let (operation, discovery) = begin_java_launch(&harness); - answer_java_launch_entries(&harness, &discovery); - let build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("build request"); - harness - .server - .send(json!({"jsonrpc": "2.0", "id": build, "result": status})); - let paths = harness - .server - .await_request_at("workspace/executeCommand", 2) - .expect("classpath request after terminal build"); - harness.server.send( - json!({"jsonrpc": "2.0", "id": paths, "result": [[], ["/workspace/app/out"]]}), - ); - let event = - harness.await_event(|event| event.operation_id.as_deref() == Some(&operation)); - assert!(event.error.is_none()); - let result = event.result.as_ref().unwrap(); - assert_eq!(result["kind"], "buildFailed"); - assert_eq!(result["failure"]["code"], code); - assert_eq!(result["failure"]["report"]["markerScope"], "launchTarget"); - assert_eq!( - result["target"]["classPaths"], - json!(["/workspace/app/out"]) - ); - } + .iter() + .any(|e| e.event.as_deref() == Some("vcs.trace.received"))); + assert!( + serde_json::from_value::(json!({"sessionId":"s"})) + .is_err() + ); } #[test] - fn java_launch_preparation_rejects_cancelled_build_without_resolving_paths() { - let mut harness = java_entrypoints_harness(); - let (operation, discovery) = begin_java_launch(&harness); - answer_java_launch_entries(&harness, &discovery); - let build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("build request"); + fn ranged_edits_extend_text_retained_before_the_server_is_ready() { + let mut harness = Harness::start(|request| { + request.provider_id = "gopls".to_string(); + }); + let uri = "file:///workspace/First.java"; + harness.sync(uri, "class First {}"); + let appended = LspDocumentContentChange { + range: Some(LspRange { + start: LspPosition { + line: 0, + utf16_column: 11, + }, + end: LspPosition { + line: 0, + utf16_column: 11, + }, + }), + text: "Renamed".to_string(), + }; harness - .server - .send(json!({"jsonrpc": "2.0", "id": build, "result": 3})); - let event = harness.await_event(|event| event.operation_id.as_deref() == Some(&operation)); - assert_eq!(event.error.as_ref().unwrap().code, "javaBuildCancelled"); - assert!(event.result.is_none()); - assert!(harness .session() - .lock_state() - .unwrap() - .java_launches - .is_empty()); - assert!(!harness - .server - .messages() - .iter() - .any(|message| message["params"]["command"] == "vscode.java.resolveClasspath")); - } + .sync_document(SyncDocumentRequest { + session_id: harness.session_id.clone(), + uri: uri.to_string(), + language_id: "java".to_string(), + text: String::new(), + content_changes: vec![appended.clone()], + }) + .expect("ranged edits should extend the retained text"); - #[test] - fn java_launch_preparation_cancel_during_build_ignores_its_late_success() { - let mut harness = java_entrypoints_harness(); - let (operation, discovery) = begin_java_launch(&harness); - answer_java_launch_entries(&harness, &discovery); - let build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("build request"); - harness + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + assert!(harness.server.await_notification("textDocument/didOpen")); + let written = String::from_utf8_lossy(&harness.server.written_bytes()).into_owned(); + assert!(written.contains("class FirstRenamed {}")); + + let error = harness .session() - .cancel_operation(&operation) - .expect("cancel composed launch"); - let event = harness.await_event(|event| event.operation_id.as_deref() == Some(&operation)); - assert_eq!(event.error.as_ref().unwrap().code, "requestCancelled"); - harness - .server - .send(json!({"jsonrpc": "2.0", "id": build, "result": 1})); - // The log is emitted after the late build answer was processed; no sleep - // or negative timeout is used to infer that no next stage was scheduled. + .sync_document(SyncDocumentRequest { + session_id: harness.session_id.clone(), + uri: "file:///workspace/Unknown.java".to_string(), + language_id: "java".to_string(), + text: String::new(), + content_changes: vec![appended], + }) + .expect_err("edits to an unknown document cannot be resolved"); + assert_eq!(error.details.as_deref(), Some("documentNotSynchronized")); + } + + /// A path descriptor reaches the server with reserved characters escaped. + #[test] + fn native_path_emits_the_canonical_uri_on_the_lsp_wire() { + let harness = Harness::ready(); + let mut payload = json!({"sessionId":harness.session_id, "languageId":"go", "text":"package main", + "uri":{"path":"/workspace/A#B.go","platform":"posix"}}); + crate::lsp::resolve_request_paths("lsp.syncDocument", &mut payload).unwrap(); + let request: SyncDocumentRequest = serde_json::from_value(payload).unwrap(); harness - .await_event(|event| event.message.as_deref() == Some("Java project build finished")); - assert!(harness .session() - .lock_state() - .unwrap() - .java_launches - .is_empty()); - assert!(!harness + .sync_document(request) + .expect("document should synchronize"); + assert!(harness.server.await_notification("textDocument/didOpen")); + let opened = harness .server .messages() - .iter() - .any(|message| message["params"]["command"] == "vscode.java.resolveClasspath")); + .into_iter() + .find(|message| message["method"] == "textDocument/didOpen") + .unwrap(); assert_eq!( - harness - .poll() - .iter() - .filter(|event| event.operation_id.as_deref() == Some(&operation)) - .count(), - 1 + opened["params"]["textDocument"]["uri"], + "file:///workspace/A%23B.go" ); } + /// Criterion 3: two syncs emit open version 1 then change version 2. #[test] - fn java_launch_preparation_rejects_malformed_classpath_instead_of_dropping_entries() { - for paths in [ - json!([[], []]), - json!([[], [42]]), - json!([[], [" "]]), - json!([null, ["/out"]]), - ] { - let mut harness = java_entrypoints_harness(); - let (operation, discovery) = begin_java_launch(&harness); - answer_java_launch_entries(&harness, &discovery); - let build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("build request"); - harness - .server - .send(json!({"jsonrpc": "2.0", "id": build, "result": 1})); - let request = harness - .server - .await_request_at("workspace/executeCommand", 2) - .expect("classpath request"); - harness - .server - .send(json!({"jsonrpc": "2.0", "id": request, "result": paths})); - let event = - harness.await_event(|event| event.operation_id.as_deref() == Some(&operation)); - assert_eq!(event.error.as_ref().unwrap().code, "invalidServerResult"); - assert!(event.result.is_none()); - } - } + fn consecutive_syncs_open_at_version_one_and_change_to_version_two() { + let harness = Harness::ready(); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + harness.sync(uri, "package main\nfunc main() {}"); - #[test] - fn java_entrypoints_asks_jdt_for_the_workspace_and_normalizes_the_answer() { - let mut harness = java_entrypoints_harness(); - let (operation_id, request_id) = request_java_entrypoints(&harness); - let request = harness + let versions: Vec<_> = harness .server .messages() .into_iter() - .find(|message| message["id"] == request_id) - .expect("the discovery request should be recorded"); - assert_eq!(request["params"]["command"], "vscode.java.resolveMainClass"); - assert_eq!(request["params"]["arguments"], json!([])); - - // Java 25 forms (no-argument, instance) arrive from JDT like any other - // entry; Core must pass them through without judging the signature. - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": [ - { "mainClass": "demo.StaticNoArgs", "projectName": "app", "filePath": "/workspace/src/main/java/demo/StaticNoArgs.java" }, - { "mainClass": "Compact", "projectName": "app", "filePath": "/workspace/src/main/java/Compact.java" }, - { "mainClass": "demo.Pathless", "projectName": "app" } - ] - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.error.is_none(), "{event:?}"); + .filter_map(|message| { + let method = message.get("method")?.as_str()?.to_string(); + let document = message.get("params")?.get("textDocument")?; + let version = document.get("version")?.as_i64()?; + Some((method, version)) + }) + .collect(); assert_eq!( - event.result, - Some(json!({ - "schemaVersion": 1, - "entries": [ - { "sourcePath": "src/main/java/Compact.java", "mainClass": "Compact", "projectName": "app" }, - { "sourcePath": "src/main/java/demo/StaticNoArgs.java", "mainClass": "demo.StaticNoArgs", "projectName": "app" } - ], - "diagnostics": [ - { "code": "missingSourcePath", "mainClass": "demo.Pathless" } - ] - })) + versions, + vec![ + ("textDocument/didOpen".to_string(), 1), + ("textDocument/didChange".to_string(), 2) + ] ); + assert_eq!(harness.snapshot().open_documents[uri].version, 2); } - /// Removes a scratch directory when the owning test ends or unwinds. - struct ScratchDirectory(PathBuf); - - impl Drop for ScratchDirectory { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - // Regression: JDT publishes diagnostics under the resolved path of a file - // the host opened through a symbolic link; matching the URIs textually - // dropped every Java error in such a workspace. - #[cfg(unix)] #[test] - fn diagnostics_published_under_the_resolved_path_reach_the_linked_document() { - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let scratch = ScratchDirectory(std::env::temp_dir().join(format!( - "lithe-linked-diagnostics-{}-{stamp}", - std::process::id() - ))); - let workspace = scratch.0.join("resolved"); - std::fs::create_dir_all(&workspace).expect("workspace should be creatable"); - std::fs::write(workspace.join("main.go"), "package main").expect("source file"); - let link = scratch.0.join("link"); - std::os::unix::fs::symlink(&workspace, &link).expect("link should be creatable"); - let opened_uri = url::Url::from_file_path(link.join("main.go")) - .expect("linked file converts to a URI") - .to_string(); - let published_uri = url::Url::from_file_path( - workspace - .canonicalize() - .expect("workspace canonicalizes") - .join("main.go"), - ) - .expect("resolved file converts to a URI") - .to_string(); - assert_ne!(opened_uri, published_uri); + fn all_documents_synced_during_initialize_are_opened_when_ready() { + let mut harness = Harness::start(|_| {}); + let first_uri = "file:///workspace/first.go"; + let second_uri = "file:///workspace/second.go"; + harness.sync(first_uri, "package main\nvar first = 1"); + harness.sync(second_uri, "package main\nvar second = 2"); - let mut harness = Harness::ready(); - harness.sync(&opened_uri, "package main"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { - "uri": published_uri, - "diagnostics": [{ - "range": { - "start": { "line": 0, "character": 0 }, - "end": { "line": 0, "character": 7 } - }, - "severity": 1, - "message": "reported at the resolved path" - }] - } - })); - let event = harness - .await_event(|event| event.kind == "diagnostics") - .clone(); - assert_eq!(event.uri.as_deref(), Some(opened_uri.as_str())); - assert_eq!(event.diagnostics.map(|list| list.len()), Some(1)); - } + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); - fn open_document(uri: &str) -> (String, LspClientDocument) { - ( - uri.to_string(), - LspClientDocument { - uri: uri.to_string(), - language_id: "go".to_string(), - version: 1, - text: "".into(), - }, - ) + let opened_uris: Vec<_> = harness + .server + .messages() + .into_iter() + .filter(|message| { + message.get("method").and_then(Value::as_str) == Some("textDocument/didOpen") + }) + .filter_map(|message| { + message + .get("params")? + .get("textDocument")? + .get("uri")? + .as_str() + .map(ToString::to_string) + }) + .collect(); + assert_eq!( + opened_uris, + vec![first_uri.to_string(), second_uri.to_string()] + ); + let snapshot = harness.snapshot(); + assert_eq!(snapshot.open_documents[first_uri].version, 1); + assert_eq!(snapshot.open_documents[second_uri].version, 1); } - // Servers publish for many files nobody has open. A session whose documents - // were not opened through a link must remember that and leave those - // messages untouched; closing a document must forget what was learned. - #[cfg(unix)] #[test] - fn diagnostics_for_unlinked_documents_are_left_alone_and_forgotten_on_close() { - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let scratch = ScratchDirectory(std::env::temp_dir().join(format!( - "lithe-unlinked-diagnostics-{}-{stamp}", - std::process::id() - ))); - std::fs::create_dir_all(&scratch.0).expect("scratch should be creatable"); - let real = scratch.0.canonicalize().expect("scratch canonicalizes"); - std::fs::write(real.join("main.go"), "package main").expect("source file"); - std::fs::write(real.join("other.go"), "package main").expect("source file"); - let uri_of = |name: &str| { - url::Url::from_file_path(real.join(name)) - .expect("file converts to a URI") - .to_string() - }; - let message = |uri: &str| { - json!({ - "jsonrpc": "2.0", - "method": "textDocument/publishDiagnostics", - "params": { "uri": uri, "diagnostics": [] } - }) - }; + fn workspace_file_changes_queue_until_initialize_and_collapse_watcher_bursts() { + let mut harness = Harness::start(|_| {}); + harness + .session() + .workspace_files_changed(vec![ + WorkspaceFileChange { + uri: "file:///workspace/pom.xml".to_string(), + kind: WorkspaceFileChangeKind::Changed, + }, + WorkspaceFileChange { + uri: "file:///workspace/src/Main.java".to_string(), + kind: WorkspaceFileChangeKind::Created, + }, + WorkspaceFileChange { + uri: "file:///workspace/src/Main.java".to_string(), + kind: WorkspaceFileChangeKind::Changed, + }, + ]) + .expect("watcher events should queue before initialize"); + assert!(!harness + .server + .messages() + .iter() + .any(|message| { message["method"] == "workspace/didChangeWatchedFiles" })); - let documents: BTreeMap<_, _> = [open_document(&uri_of("main.go"))].into(); - let mut linked = LinkedDocumentPaths::default(); + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + let notification = harness + .server + .messages() + .into_iter() + .find(|message| message["method"] == "workspace/didChangeWatchedFiles") + .expect("queued watcher events should flush after initialize"); assert_eq!( - diagnostics_addressed_to_open_document( - &documents, - &mut linked, - &message(&uri_of("other.go")) - ), - None - ); - assert!(linked.resolved.is_empty()); - assert!(linked.examined.contains(&uri_of("main.go"))); - - diagnostics_addressed_to_open_document( - &BTreeMap::new(), - &mut linked, - &message(&uri_of("other.go")), + notification["params"]["changes"], + json!([ + { "uri": "file:///workspace/pom.xml", "type": 2 }, + { "uri": "file:///workspace/src/Main.java", "type": 2 } + ]) ); - assert!(linked.examined.is_empty()); } + /// Criterion 4: a crash fails pending operations with `serverExited`. #[test] - fn a_malformed_java_entrypoint_answer_is_an_error_not_an_empty_list() { - // Reporting "no entry points" here would let callers wipe a good list. - let mut harness = java_entrypoints_harness(); - let (operation_id, request_id) = request_java_entrypoints(&harness); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": { "unexpected": true } - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.result.is_none(), "{event:?}"); + fn a_crash_fails_every_pending_operation_once_with_server_exited() { + let mut harness = Harness::ready(); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + let hover = harness.request(LspSemanticOperation::Hover, uri); + let definition = harness.request(LspSemanticOperation::Definition, uri); + + harness.server.exit(Some(134)); + harness.await_state(LspLifecycleState::Failed); + + let failures: Vec<_> = harness + .events + .iter() + .filter(|event| event.kind == "requestCompleted") + .collect(); assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("invalidServerResult") + failures.len(), + 2, + "each pending operation must fail exactly once" ); + for event in failures { + let error = event.error.as_ref().expect("a crash cannot yield a result"); + assert_eq!(error.code, "serverExited"); + assert_eq!(error.process_exit_code, Some(134)); + } + let completed: Vec<_> = harness + .events + .iter() + .filter_map(|event| event.operation_id.clone()) + .collect(); + assert!(completed.contains(&hover) && completed.contains(&definition)); + assert!(harness.snapshot().pending_operation_ids.is_empty()); } + /// Criterion 5: a request deadline removes the pending request. + /// Criterion 6: a late response after that timeout is ignored. #[test] - fn a_java_entrypoint_server_error_is_reported() { - let mut harness = java_entrypoints_harness(); - let (operation_id, request_id) = request_java_entrypoints(&harness); + fn a_timed_out_request_is_removed_cancelled_and_deaf_to_its_late_response() { + let mut harness = Harness::start(|request| { + request.request_timeout_milliseconds = 30; + }); + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + let operation = harness.request(LspSemanticOperation::Hover, uri); + let request_id = harness + .server + .await_request("textDocument/hover") + .expect("the hover request should reach the server"); + + let timeout = harness + .await_event(|event| { + event + .error + .as_ref() + .is_some_and(|error| error.code == "requestTimeout") + }) + .clone(); + assert_eq!(timeout.operation_id.as_deref(), Some(operation.as_str())); + assert!(harness.snapshot().pending_operation_ids.is_empty()); + // The completion event is queued before the cancellation is written, so + // the wire assertion has to wait for the write rather than assume it. + assert!( + harness.server.await_notification("$/cancelRequest"), + "a timed-out request must be cancelled on the wire" + ); + + // The server answers anyway. Nothing may reach the application: the + // operation has already been completed with its timeout error. harness.server.send(json!({ "jsonrpc": "2.0", "id": request_id, - "error": { "code": -32601, "message": "No delegateCommandHandler for vscode.java.resolveMainClass" } + "result": { "contents": "too late" } })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.result.is_none(), "{event:?}"); + thread::sleep(Duration::from_millis(50)); + harness.poll(); + let completions = harness + .events + .iter() + .filter(|event| event.operation_id.as_deref() == Some(operation.as_str())) + .count(); assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("serverError") + completions, 1, + "a late response must not complete the operation a second time" ); } + /// Criterion 7: responses from an old session cannot affect a restarted one. #[test] - fn java_entrypoints_are_refused_for_other_languages() { - let mut harness = Harness::start(|_| {}); - harness + fn a_restarted_session_ignores_the_previous_session_s_responses() { + // The first session is taken to Ready and then torn down. Its hover + // request id is recorded first, because every session numbers its + // requests from one: an id alone cannot tell two sessions apart, so only + // per-session pending state can reject a foreign response. + let mut first = Harness::ready(); + let uri = "file:///workspace/main.go"; + first.sync(uri, "package main"); + first.request(LspSemanticOperation::Hover, uri); + let stale_id = first .server - .complete_initialize(json!({ "executeCommandProvider": {} })); - harness.await_state(LspLifecycleState::Ready); - let operation_id = harness.engine.next_operation_id(); - let error = harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaEntrypoints, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id, - ) - .expect_err("only the Java provider can discover Java entry points"); - assert!(matches!(error.code, ErrorCode::NotSupported), "{error:?}"); - } + .await_request("textDocument/hover") + .expect("the hover request should reach the server"); + first.server.exit(Some(0)); + first.await_state(LspLifecycleState::Failed); + first.engine.destroy(&first.session_id).unwrap(); - #[test] - fn java_test_items_ask_the_extension_for_one_file_and_normalize_the_answer() { - let mut harness = java_entrypoints_harness(); - let operation_id = harness.engine.next_operation_id(); - let uri = "file:///workspace/src/test/java/demo/OddlyNamedSpec.java"; - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaTestItems, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .expect("test discovery should not require the file to be open"); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .expect("test discovery should reach the Java Test extension"); - let request = harness - .server - .messages() - .into_iter() - .find(|message| message["id"] == request_id) - .expect("the discovery request should be recorded"); + let mut restarted = Harness::ready(); + restarted.sync(uri, "package main"); + let operation = restarted.request(LspSemanticOperation::Hover, uri); assert_eq!( - request["params"], - json!({ - "command": "vscode.java.test.findTestTypesAndMethods", - "arguments": [uri] - }) + restarted + .server + .await_request("textDocument/hover") + .as_deref(), + Some(stale_id.as_str()), + "the restarted session must reuse the id, or this proves nothing" ); - harness.server.send(json!({ + + // Delivered to the new session, the id does match a pending request, so + // isolation cannot rest on ids. It rests on the process: the old + // session's reader thread is gone with its process, so its responses + // have no path into the new session at all. + let before = restarted.snapshot(); + first.server.send(json!({ "jsonrpc": "2.0", - "id": request_id, - "result": [{ - "id": "class-id", - "label": "OddlyNamedSpec", - "fullName": "demo.OddlyNamedSpec", - "projectName": "app", - "testKind": 0, - "testLevel": 5, - "children": [{ - "id": "method-id", - "label": "customAnnotation()", - "fullName": "demo.OddlyNamedSpec#customAnnotation()", - "projectName": "app", - "testKind": 0, - "testLevel": 6, - "jdtHandler": "method-handler", - "range": { - "start": { "line": 7, "character": 2 }, - "end": { "line": 9, "character": 3 } - } - }] - }] + "id": stale_id, + "result": { "contents": "from the dead session" } })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.error.is_none(), "{event:?}"); + thread::sleep(Duration::from_millis(50)); + restarted.poll(); assert_eq!( - event - .result - .as_ref() - .and_then(|value| value["schemaVersion"].as_u64()), - Some(1) + restarted.snapshot().pending_operation_ids, + before.pending_operation_ids, + "the old session's response must not complete the new session's request" + ); + assert!( + !restarted + .events + .iter() + .any(|event| event.kind == "requestCompleted"), + "no operation may complete from a foreign session's traffic" ); + + // The new session's own response still lands, so the isolation above is + // not merely a dead session. + restarted.server.send(json!({ + "jsonrpc": "2.0", + "id": stale_id, + "result": { "contents": "from the live session" } + })); + let completion = restarted + .await_event(|event| event.kind == "requestCompleted") + .clone(); + assert_eq!(completion.operation_id.as_deref(), Some(operation.as_str())); assert_eq!( - event + completion .result .as_ref() - .map(|value| &value["items"][0]["children"][0]["jdtHandler"]), - Some(&json!("method-handler")) + .and_then(|result| result.get("hover")?.get("contents")) + .and_then(Value::as_str), + Some("from the live session") ); } - fn request_java_main_methods(harness: &mut Harness, uri: &str) -> (String, String) { - let operation_id = harness.engine.next_operation_id(); - harness + /// A write that fails mid-session is a transport failure, not a silent drop. + #[test] + fn a_broken_stdin_fails_the_session_and_stops_writing() { + let mut harness = Harness::ready(); + let written = harness.server.written_bytes().len(); + harness.server.break_input(); + let error = harness .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaMainMethods, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .expect("main-method discovery should not require the file to be open"); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .expect("main-method discovery should reach the Java Debug Server"); - (operation_id, request_id) - } + .sync_document(SyncDocumentRequest { + session_id: harness.session_id.clone(), + uri: "file:///workspace/main.go".to_string(), + language_id: "go".to_string(), + text: "package main".to_string(), + content_changes: Vec::new(), + }) + .expect_err("a broken pipe must surface to the caller"); + assert!(matches!(error.code, ErrorCode::ProcessFailed)); - #[test] - fn java_main_methods_ask_java_debug_for_one_file_and_normalize_the_answer() { - let mut harness = java_entrypoints_harness(); - let uri = "file:///workspace/src/main/java/demo/App.java"; - let (operation_id, request_id) = request_java_main_methods(&mut harness, uri); - let request = harness - .server - .messages() - .into_iter() - .find(|message| message["id"] == request_id) - .expect("the discovery request should be recorded"); + harness.await_state(LspLifecycleState::Failed); + let failure = harness + .events + .iter() + .find_map(|event| event.error.as_ref()) + .expect("the failure should be reported as a runtime error"); + assert_eq!(failure.code, "transportFailed"); assert_eq!( - request["params"], - json!({ "command": "vscode.java.resolveMainMethod", "arguments": [uri] }) + harness.server.written_bytes().len(), + written, + "nothing may be written after the pipe breaks" ); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": [{ - "range": { - "start": { "line": 4, "character": 23 }, - "end": { "line": 4, "character": 27 } - }, - "mainClass": "demo.App", - "projectName": "app" - }] - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.error.is_none(), "{event:?}"); - let result = event.result.expect("main methods"); - assert_eq!(result["schemaVersion"], json!(1)); - assert_eq!(result["methods"][0]["mainClass"], json!("demo.App")); - assert_eq!(result["methods"][0]["range"]["startLine"], json!(4)); } + /// The stopped session's own late response is dropped rather than acted on, + /// which is the same rule seen from the other side of a restart. #[test] - fn malformed_java_main_method_answer_is_an_error_not_an_empty_list() { - let mut harness = java_entrypoints_harness(); - let (operation_id, request_id) = request_java_main_methods( - &mut harness, - "file:///workspace/src/main/java/demo/App.java", - ); + fn a_response_to_an_already_failed_session_is_logged_and_dropped() { + let mut harness = Harness::ready(); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + harness.request(LspSemanticOperation::Hover, uri); + let request_id = harness + .server + .await_request("textDocument/hover") + .expect("the hover request should reach the server"); + + harness.server.exit(Some(1)); + harness.await_state(LspLifecycleState::Failed); + let completions = harness + .events + .iter() + .filter(|event| event.kind == "requestCompleted") + .count(); + assert_eq!(completions, 1, "the crash already completed the operation"); + harness.server.send(json!({ "jsonrpc": "2.0", "id": request_id, - "result": { "unexpected": true } + "result": { "contents": "unreachable" } })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.result.is_none()); + thread::sleep(Duration::from_millis(50)); + harness.poll(); assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("invalidServerResult") + harness + .events + .iter() + .filter(|event| event.kind == "requestCompleted") + .count(), + completions, + "a response after the terminal state must not complete anything" ); + assert_eq!(harness.snapshot().state, LspLifecycleState::Failed); } #[test] - fn malformed_java_test_answer_is_an_error_not_an_empty_list() { - let mut harness = java_entrypoints_harness(); - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaTestItems, - uri: Some("file:///workspace/src/test/java/demo/App.java".to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .unwrap(); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .unwrap(); - harness.server.send(json!({ - "jsonrpc": "2.0", "id": request_id, "result": { "unexpected": true } - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.result.is_none(), "{event:?}"); - assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("invalidServerResult") + fn indexing_policy_withdrawal_serializes_with_a_checked_document_commit() { + assert_policy_withdrawal_serializes_with_checked_commit(false); + } + + #[test] + fn indexing_policy_withdrawal_serializes_with_checked_diagnostics() { + assert_policy_withdrawal_serializes_with_checked_commit(true); + } + + fn assert_policy_withdrawal_serializes_with_checked_commit(diagnostics: bool) { + let workspace = TemporaryWorkspace::recursive("indexing-document-commit"); + let root = workspace.root.canonicalize().unwrap(); + let mut policy = IndexingPolicyFixture::new(root.clone()); + let mut harness = Harness::start(|request| workspace.configure(request)); + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + let uri = url::Url::from_file_path(root.join("reactor/hidden.go")) + .unwrap() + .to_string(); + let session = harness.session(); + let (checked_tx, checked_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (sync_done_tx, sync_done_rx) = std::sync::mpsc::channel(); + let syncing = { + let session = session.clone(); + let uri = uri.clone(); + thread::spawn(move || { + let checked = || { + checked_tx.send(()).unwrap(); + release_rx + .recv_timeout(Duration::from_secs(3)) + .expect("document commit was not released"); + }; + let result = if diagnostics { + session.handle_server_message_after_policy_check(json!({"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{ + "uri":uri,"diagnostics":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"message":"old diagnostic"}] + }}).to_string(), checked) + } else { + session + .sync_document_after_policy_check( + SyncDocumentRequest { + session_id: session.id.clone(), + uri, + language_id: "java".into(), + text: "class Hidden {}".into(), + content_changes: Vec::new(), + }, + checked, + ) + .map(|_| ()) + }; + let _ = sync_done_tx.send(()); + result + }) + }; + checked_rx + .recv_timeout(Duration::from_secs(3)) + .expect("document eligibility was not reached"); + assert!( + matches!( + session.indexing_roots.try_lock(), + Err(std::sync::TryLockError::WouldBlock) + ), + "eligibility and document publication must retain the policy serialization guard" ); + policy.exclude(&["reactor"]); + let (update_done_tx, update_done_rx) = std::sync::mpsc::channel(); + let updating = { + let session = session.clone(); + let root = root.clone(); + thread::spawn(move || { + let result = apply_indexing_to_sessions(&root, vec![session]); + let _ = update_done_tx.send(()); + result + }) + }; + release_tx.send(()).unwrap(); + sync_done_rx + .recv_timeout(Duration::from_secs(3)) + .expect("document commit did not finish"); + update_done_rx + .recv_timeout(Duration::from_secs(3)) + .expect("policy update did not finish"); + syncing.join().unwrap().unwrap(); + updating.join().unwrap().unwrap(); + assert!(!harness.snapshot().open_documents.contains_key(&uri)); + assert!(!session + .lock_state() + .unwrap() + .client + .diagnostics + .contains_key(&uri)); + if !diagnostics { + assert!(notifications(&harness, "textDocument/didClose") + .iter() + .any(|message| message["params"]["textDocument"]["uri"] == uri)); + } } #[test] - fn null_java_test_answer_for_a_file_without_tests_is_an_empty_list() { - // Issue #840: vscode-java-test answers `null` for a file with no tests; - // that must not surface as an `invalidServerResult` error in the logs. - let mut harness = java_entrypoints_harness(); - let operation_id = harness.engine.next_operation_id(); + fn indexing_policy_withdraws_queued_file_changes_before_service_readiness() { + let workspace = TemporaryWorkspace::recursive("indexing-pending-file-changes"); + let root = workspace.root.canonicalize().unwrap(); + let mut policy = IndexingPolicyFixture::new(root.clone()); + let mut harness = Harness::start(|request| workspace.configure(request)); + let hidden = url::Url::from_file_path(root.join("reactor/hidden.go")) + .unwrap() + .to_string(); + let visible = url::Url::from_file_path(root.join("visible.go")) + .unwrap() + .to_string(); harness .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaTestItems, - uri: Some("file:///workspace/src/main/java/demo/App.java".to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, + .workspace_files_changed(vec![ + WorkspaceFileChange { + uri: hidden.clone(), + kind: WorkspaceFileChangeKind::Created, }, - operation_id.clone(), - ) - .unwrap(); - let request_id = harness - .server - .await_request("workspace/executeCommand") + WorkspaceFileChange { + uri: visible.clone(), + kind: WorkspaceFileChangeKind::Created, + }, + ]) .unwrap(); - harness.server.send(json!({ - "jsonrpc": "2.0", "id": request_id, "result": null - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - assert!(event.error.is_none(), "{event:?}"); assert_eq!( - event.result, - Some(json!({ "schemaVersion": 1, "items": [], "diagnostics": [] })) - ); - } - - #[test] - fn wait_events_returns_queued_events_without_waiting_the_timeout() { - let harness = Harness::start(|_| {}); - let started = Instant::now(); - let events = harness - .session() - .wait_events(Duration::from_secs(2)) - .expect("waiting should succeed"); - assert!( - !events.is_empty(), - "starting a session should enqueue at least one lifecycle event" - ); - assert!( - started.elapsed() < Duration::from_millis(500), - "queued events must not wait out the timeout" + harness + .session() + .lock_state() + .unwrap() + .pending_workspace_file_changes + .len(), + 2 ); + policy.exclude(&["reactor"]); + // The policy is installed, but this independent session has not received + // its withdrawal callback yet. Readiness must recheck queued eligibility. + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + let changes = notifications(&harness, "workspace/didChangeWatchedFiles"); + assert!(changes.iter().any(|message| message["params"]["changes"] + .as_array() + .unwrap() + .iter() + .any(|change| change["uri"] == visible))); + assert!(!changes.iter().any(|message| message["params"]["changes"] + .as_array() + .unwrap() + .iter() + .any(|change| change["uri"] == hidden))); } #[test] - fn wait_events_times_out_with_an_empty_queue() { - let mut harness = Harness::ready(); - harness.poll(); - let started = Instant::now(); - let events = harness - .session() - .wait_events(Duration::from_millis(40)) - .expect("waiting should succeed"); - assert!(events.is_empty()); - assert!(started.elapsed() >= Duration::from_millis(30)); + fn indexing_startup_cancels_when_policy_changes_during_process_launch() { + const CANCELLED_PLUGIN: &str = "io.example.indexing-cancel-launch"; + struct RetireOnLaunch { + inner: Arc, + root: PathBuf, + revision: Arc, + process: Arc>>>, + } + impl LspProcessLauncher for RetireOnLaunch { + fn launch( + &self, + spec: LspProcessSpec, + ) -> Result { + let process = self.inner.launch(spec)?; + *self.process.lock().unwrap() = Some(process.handle.clone()); + let status = crate::project::indexing::configure(serde_json::from_value(json!({ + "root": self.root, "manualExcludedDirectories": ["reactor"], "includedDirectories": [], "gitIgnoreEnabled": false + })).unwrap())?; + self.revision.store(status.revision, Ordering::Release); + Ok(process) + } + } + struct Cleanup { + root: PathBuf, + revision: Arc, + process: Arc>>>, + } + impl Drop for Cleanup { + fn drop(&mut self) { + if let Some(process) = self.process.lock().unwrap().as_ref() { + process.terminate(); + } + let _ = crate::project::indexing::release( + crate::project::indexing::ReleaseIndexingRequest { + root: self.root.to_string_lossy().into_owned(), + owner_id: None, + revision: self.revision.load(Ordering::Acquire), + }, + ); + } + } + for (initially_configured, cleanup_blocked, native_owner) in [ + (false, false, false), + (true, false, false), + (false, true, false), + (true, true, false), + (false, false, true), + (true, false, true), + (false, true, true), + (true, true, true), + ] { + let workspace = TemporaryWorkspace::recursive(&format!( + "indexing-startup-retired-{initially_configured}" + )); + let root = workspace.root.canonicalize().unwrap(); + let installed = if initially_configured { + crate::project::indexing::configure(serde_json::from_value(json!({ + "root":root,"manualExcludedDirectories":[],"includedDirectories":[],"gitIgnoreEnabled":false + })).unwrap()).unwrap().revision + } else { + 0 + }; + let cleanup = Cleanup { + root: root.clone(), + revision: Arc::new(AtomicU64::new(installed)), + process: Arc::new(Mutex::new(None)), + }; + let server = ScriptedServer::new(); + server.block_cleanup(cleanup_blocked); + let engine = LspEngine::with_launcher(Arc::new(RetireOnLaunch { + inner: server.launcher(), + root: root.clone(), + revision: cleanup.revision.clone(), + process: cleanup.process.clone(), + })); + let mut request = start_request(&server); + request.provider_id = "python".into(); + request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + request.working_directory = root.to_string_lossy().into_owned(); + request.startup_operation = Some(AttemptHandoff { + plugin_id: CANCELLED_PLUGIN.to_string(), + operation_id: "indexing-cancel-before-registration".to_string(), + elapsed_ms: 5, + }); + let mut registered = None; + let result = if native_owner { + engine.start_server_owned(request, |id| registered = Some(id.to_owned())) + } else { + engine.start_server(request) + }; + assert!(matches!(result.unwrap_err().code, ErrorCode::Cancelled)); + if cleanup_blocked { + let id = if native_owner { + registered.expect("incomplete disposal must reach the native owner") + } else { + engine + .lock_failed_starts() + .unwrap() + .first() + .cloned() + .expect("incomplete wire disposal retains its internal owner") + }; + assert!(engine.destroy(&id).is_err()); + assert!(engine.session(&id).is_ok()); + server.block_cleanup(false); + if native_owner { + engine + .destroy(&id) + .expect("native owner can retry verified disposal"); + } else { + engine + .cleanup_failed_start() + .expect("wire retry confirms disposal"); + assert!(engine.lock_failed_starts().unwrap().is_empty()); + } + } else { + assert!( + registered.is_none(), + "disposed startup needs no native barrier" + ); + } + assert!(engine.lock_sessions().unwrap().is_empty()); + assert!( + server.input_was_closed(), + "the cancelled startup owns process termination" + ); + assert!( + plugin_operations::test_capture::take(CANCELLED_PLUGIN).is_empty(), + "a cancelled start records no plugin operation result" + ); + } } #[test] - fn wait_events_wakes_when_the_session_enqueues_a_lifecycle_event() { - let mut harness = Harness::ready(); - harness.poll(); - let session = harness.session(); - let waiter = thread::spawn({ - let session = Arc::clone(&session); - move || { - session - .wait_events(Duration::from_secs(2)) - .expect("waiting should succeed") - } + fn native_owner_retains_indexing_cancellation_after_registration() { + const CANCELLED_PLUGIN: &str = "io.example.indexing-cancel-registered"; + let workspace = TemporaryWorkspace::recursive("indexing-owned-startup"); + let root = workspace.root.canonicalize().unwrap(); + let mut policy = IndexingPolicyFixture::new(root.clone()); + let server = ScriptedServer::new(); + server.block_cleanup(true); + let engine = LspEngine::with_launcher(server.launcher()); + let mut request = start_request(&server); + request.provider_id = "python".into(); + request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + request.working_directory = root.to_string_lossy().into_owned(); + request.startup_operation = Some(AttemptHandoff { + plugin_id: CANCELLED_PLUGIN.to_string(), + operation_id: "indexing-cancel-after-registration".to_string(), + elapsed_ms: 5, }); - thread::sleep(Duration::from_millis(30)); - session.stop().expect("the session should stop"); - let events = waiter.join().expect("the waiter thread should finish"); + let mut registered = None; + let result = engine.start_server_owned(request, |id| { + registered = Some(id.to_owned()); + // Revoke between the initial policy check and initialize write. + policy.exclude(&["reactor"]); + }); + assert!(matches!(result.unwrap_err().code, ErrorCode::Cancelled)); + let id = registered.expect("native owner received its session"); + assert!(engine.destroy(&id).is_err()); + assert!(engine.session(&id).is_ok()); + server.block_cleanup(false); + engine + .destroy(&id) + .expect("native owner confirms process disposal"); + assert!(engine.session(&id).is_err()); assert!( - events.iter().any(|event| event.kind == "stateChanged"), - "stop should wake waiters with a lifecycle event, got {events:?}" + plugin_operations::test_capture::take(CANCELLED_PLUGIN).is_empty(), + "a cancelled start records no plugin operation result" ); } #[test] - fn wait_events_errors_after_terminal_state_events_are_drained() { - let mut harness = Harness::ready(); - harness.poll(); - harness.session().stop().unwrap(); - let shutdown_id = harness - .server - .await_request("shutdown") - .expect("stop should request shutdown"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": shutdown_id, - "result": null - })); + fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions() { + let workspace = TemporaryWorkspace::recursive("indexing-released-standalone"); + let root = workspace.root.canonicalize().unwrap(); + let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + let status = crate::project::indexing::configure(serde_json::from_value(json!({ + "root": root, "manualExcludedDirectories": ["reactor"], "includedDirectories": [], "gitIgnoreEnabled": false + })).unwrap()).unwrap(); + let old = crate::project::indexing::context(&root).unwrap(); + crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { + root: root.to_string_lossy().into_owned(), + revision: status.revision, + owner_id: None, + }) + .unwrap(); assert!( - harness.server.await_notification("exit"), - "exit must follow the shutdown response" + old.check().is_err(), + "late inventory readers must remain cancelled" ); - harness.server.exit(Some(0)); - harness.await_state(LspLifecycleState::Stopped); - - // Drain any remaining lifecycle events from the stop transition. - loop { - let events = match harness.session().wait_events(Duration::from_millis(20)) { - Ok(events) => events, - Err(error) => { - assert!(matches!(error.code, ErrorCode::ProcessFailed)); - assert_eq!(error.details.as_deref(), Some("sessionStopped")); - return; - } - }; - if events.is_empty() { - break; - } - } - - let error = harness - .session() - .wait_events(Duration::from_millis(50)) - .expect_err("drained terminal sessions must not return empty Ok"); - assert!(matches!(error.code, ErrorCode::ProcessFailed)); - assert_eq!(error.details.as_deref(), Some("sessionStopped")); + let harness = Harness::start(|request| { + workspace.configure(request); + request.root_uri = root_uri.clone(); + request.initialization_options = + Some(json!({"settings":{"java":{"import":{"exclusions":["**/vendor/**"]}}}})); + }); + let initialize = notifications(&harness, "initialize").pop().unwrap(); + assert_eq!( + initialize["params"]["initializationOptions"]["settings"]["java"]["import"] + ["exclusions"], + json!(["**/vendor/**"]) + ); + let file_uri = url::Url::from_file_path(root.join("reactor/visible.go")) + .unwrap() + .to_string(); + assert!(!crate::project::indexing::uri_is_excluded(&root_uri, &file_uri).unwrap()); } #[test] - fn java_virtual_semantics_bypass_did_open_without_weakening_physical_ownership() { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.cache_directory = Some("/tmp/lithe-lsp-engine-tests".to_string()); + fn indexing_cold_start_resolves_git_before_provider_initialization() { + let workspace = TemporaryWorkspace::recursive("indexing-cold-start"); + let root = workspace.root.canonicalize().unwrap(); + std::fs::create_dir_all(root.join("ignored")).unwrap(); + std::fs::write(root.join("ignored/hidden.txt"), "hidden").unwrap(); + std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap(); + let git = crate::git::execute_git_readonly( + &root.to_string_lossy(), + &["init".into(), "--quiet".into()], + None, + ) + .unwrap(); + assert_eq!(git.exit_code, 0, "{}", git.stderr); + let status = crate::project::indexing::configure(serde_json::from_value(json!({ + "root": root, "manualExcludedDirectories": [], "includedDirectories": [], "gitIgnoreEnabled": true + })).unwrap()).unwrap(); + let harness = Harness::start(|request| { + workspace.configure(request); + request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); }); - harness.server.complete_java_initialize(json!({ - "referencesProvider": true - })); - harness.await_state(LspLifecycleState::Ready); - let virtual_uri = "jdt://contents/java.base/java/lang/String.class?=smoke"; - let operation_id = harness.request(LspSemanticOperation::References, virtual_uri); - let request_id = harness - .server - .await_request("textDocument/references") - .expect("virtual references should reach JDT LS without didOpen"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": [] - })); - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())); - assert!(event.error.is_none()); - - let physical_operation_id = harness.engine.next_operation_id(); - let error = harness - .session() - .request( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(physical_operation_id.clone()), - operation: LspSemanticOperation::References, - uri: Some("file:///workspace/Unopened.java".to_string()), - virtual_uri: None, - position: Some(LspPosition { - line: 0, - utf16_column: 0, - }), - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - physical_operation_id, + assert!(notifications(&harness, "initialize").pop().is_some()); + for (provider, pointer) in [ + ("go", "/gopls/directoryFilters"), + ("rust", "/rust-analyzer/files/exclude"), + ] { + let value = crate::lsp::languages::indexing::configuration( + provider, + &harness.session().root_uri, + None, ) - .expect_err("an unopened physical document must remain rejected"); - assert_eq!( - error.message, - "The document is not open in the language server." - ); + .unwrap(); + assert!(value + .pointer(pointer) + .unwrap() + .as_array() + .unwrap() + .iter() + .any(|item| item + == if provider == "go" { + "-ignored" + } else { + "ignored" + })); + } + crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { + root: root.to_string_lossy().into_owned(), + revision: status.revision, + owner_id: None, + }) + .unwrap(); } #[test] - fn real_jdtls_routes_physical_and_virtual_references() { - let Ok(executable_path) = std::env::var("LITHE_JDTLS_SMOKE_EXECUTABLE") else { - return; - }; - let java_path = std::env::var("LITHE_JDTLS_SMOKE_JAVA") - .expect("LITHE_JDTLS_SMOKE_JAVA must accompany the JDTLS smoke executable"); - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-real-jdtls-smoke-{}-{stamp}", - std::process::id() - )); - let workspace = root.join("workspace"); - let source_directory = workspace - .join("src") - .join("main") - .join("java") - .join("smoke"); - let dependency_source_directory = root.join("dependency-source").join("dependency"); - let dependency_classes = root.join("dependency-classes"); - let dependency_jar = workspace.join("lib").join("smoke-dependency.jar"); - std::fs::create_dir_all(&source_directory).expect("smoke source directory should exist"); - std::fs::create_dir_all(&dependency_source_directory) - .expect("smoke dependency source directory should exist"); - std::fs::create_dir_all(&dependency_classes) - .expect("smoke dependency classes directory should exist"); - std::fs::create_dir_all( - dependency_jar - .parent() - .expect("dependency JAR should have a parent"), - ) - .expect("smoke dependency library directory should exist"); - let java_home = PathBuf::from(&java_path) - .parent() - .and_then(Path::parent) - .expect("smoke Java executable should be inside a JDK bin directory") - .to_path_buf(); - let executable_suffix = if cfg!(windows) { ".exe" } else { "" }; - let dependency_source = dependency_source_directory.join("Widget.java"); - std::fs::write( - &dependency_source, - "package dependency; public class Widget { public String value() { return \"widget\"; } }\n", - ) - .expect("smoke dependency source should be written"); - let javac_status = std::process::Command::new( - java_home - .join("bin") - .join(format!("javac{executable_suffix}")), - ) - .arg("-d") - .arg(&dependency_classes) - .arg(&dependency_source) - .status() - .expect("smoke javac should start"); - assert!(javac_status.success(), "smoke dependency should compile"); - let jar_status = std::process::Command::new( - java_home - .join("bin") - .join(format!("jar{executable_suffix}")), - ) - .arg("--create") - .arg("--file") - .arg(&dependency_jar) - .arg("-C") - .arg(&dependency_classes) - .arg(".") - .status() - .expect("smoke jar should start"); - assert!( - jar_status.success(), - "smoke dependency JAR should be created" - ); - std::fs::write( - workspace.join("pom.xml"), - r#" - 4.0.0 - smoke - lithe-jdtls-smoke - 1.0.0 - 17 - - - smoke - dependency - 1.0.0 - system - ${project.basedir}/lib/smoke-dependency.jar - - - -"#, - ) - .expect("smoke pom should be written"); - let source = r#"package smoke; - -import dependency.Widget; - -public class Main { - private Widget widget; - public Widget read() { return widget; } - public void write(Widget replacement) { widget = replacement; } -} -"#; - let source_path = source_directory.join("Main.java"); - std::fs::write(&source_path, source).expect("smoke source should be written"); - - let canonical_workspace = workspace - .canonicalize() - .expect("smoke workspace should canonicalize"); - let canonical_source_path = source_path - .canonicalize() - .expect("smoke source should canonicalize"); - let root_uri = url::Url::from_directory_path(&canonical_workspace) - .expect("workspace should convert to a file URI") - .to_string(); - let source_uri = url::Url::from_file_path(&canonical_source_path) - .expect("source should convert to a file URI") + fn indexing_change_withdraws_open_working_copies_and_rejects_sync() { + let workspace = TemporaryWorkspace::recursive("indexing-working-copy"); + let root = workspace.root.canonicalize().unwrap(); + let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + let mut harness = Harness::start(|request| { + request.root_uri = root_uri.clone(); + request.working_directory = root.to_string_lossy().into_owned(); + }); + harness.server.complete_initialize(ready_capabilities()); + harness.await_state(LspLifecycleState::Ready); + let uri = url::Url::from_file_path(root.join("reactor/main.go")) + .unwrap() .to_string(); - let engine = LspEngine::new(); - let started = engine - .start_server(StartServerRequest { - provider_id: "java".to_string(), - role: SessionRole::LanguageServer, - log_subject: None, - plugin_id: None, - startup_operation: None, - host_services: Vec::new(), - host_options: Default::default(), - toolchain_providers: Vec::new(), - keymap_import_providers: Vec::new(), - session_policy: None, - executable_path, - arguments: Vec::new(), - environment: BTreeMap::from([( - "JAVA_HOME".to_string(), - java_home.to_string_lossy().into_owned(), - )]), - root_uri, - working_directory: workspace.to_string_lossy().into_owned(), - initialization_options: None, - workspace_configuration: None, - runtime_executable_path: Some(java_path), - jdtls_launch_resources: None, - cache_directory: Some(root.join("cache").to_string_lossy().into_owned()), - workspace_fingerprint: None, - maven_context: None, - java_runtimes: Vec::new(), - java_gradle: None, - initialize_timeout_milliseconds: 90_000, - service_ready_idle_timeout_milliseconds: 45_000, - service_ready_absolute_timeout_milliseconds: 600_000, - request_timeout_milliseconds: 30_000, - java_build_timeout_milliseconds: DEFAULT_JAVA_BUILD_TIMEOUT_MS, - shutdown_timeout_milliseconds: 10_000, - }) - .expect("real JDTLS should start"); - let _cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root, - }; - let session = engine - .session(&started.session_id) - .expect("real JDTLS session should be registered"); - let mut ready_events = - await_real_smoke_ready(&session).unwrap_or_else(|error| panic!("{error}")); - let capability_deadline = Instant::now() + Duration::from_secs(30); - let capabilities = loop { - if let Some(capabilities) = ready_events.iter().find_map(|event| { - event - .capabilities - .as_ref() - .filter(|capabilities| { - ["definition", "references", "executeCommand"] - .iter() - .all(|required| capabilities.iter().any(|feature| feature == required)) - }) - .cloned() - }) { - break capabilities; - } - assert!( - Instant::now() < capability_deadline, - "real JDTLS should dynamically publish capabilities: {ready_events:?}" - ); - ready_events.extend( - session - .poll_events() - .expect("real JDTLS capability events should poll"), - ); - thread::sleep(Duration::from_millis(20)); - }; - for required in ["definition", "references", "executeCommand"] { - assert!( - capabilities.iter().any(|feature| feature == required), - "real JDTLS did not negotiate {required}: {capabilities:?}" - ); - } - - session + harness.sync(&uri, "package main"); + let status = crate::project::indexing::configure( + serde_json::from_value(json!({ + "root":root,"manualExcludedDirectories":["reactor"], + "includedDirectories":[],"gitIgnoreEnabled":false + })) + .unwrap(), + ) + .unwrap(); + apply_indexing_to_sessions(&root, vec![harness.session()]).unwrap(); + assert!(!harness + .session() + .lock_state() + .unwrap() + .client + .open_documents + .contains_key(&uri)); + assert!(crate::project::indexing::uri_is_excluded(&root_uri, &uri).unwrap()); + let session = harness.session(); + assert!(session .sync_document(SyncDocumentRequest { - session_id: started.session_id.clone(), - uri: source_uri.clone(), - language_id: "java".to_string(), - text: source.to_string(), + session_id: harness.session_id.clone(), + uri: uri.clone(), + language_id: "go".into(), + text: "package main".into(), content_changes: Vec::new(), }) - .expect("smoke source should synchronize"); + .is_err()); + session.handle_server_message(json!({"jsonrpc":"2.0","method":"textDocument/publishDiagnostics", "params":{ + "uri":uri,"diagnostics":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"severity":1,"message":"late"}] + }}).to_string()).unwrap(); + assert!(!session + .lock_state() + .unwrap() + .client + .diagnostics + .contains_key(&uri)); - let field_position = real_smoke_token_position(source, "Widget widget", "Widget ".len()); - let physical_deadline = Instant::now() + Duration::from_secs(30); - let physical_references = loop { - let result = real_smoke_request( - &engine, - &session, - LspSemanticOperation::References, - Some(&source_uri), - None, - Some(field_position), - ) - .unwrap_or_else(|error| panic!("{error}")); - if real_smoke_locations(&result).len() >= 3 { - break result; - } - assert!( - Instant::now() < physical_deadline, - "real JDTLS did not index physical references: {result}" - ); - thread::sleep(Duration::from_millis(250)); - }; - assert!(real_smoke_locations(&physical_references).len() >= 3); - - let widget_position = real_smoke_token_position(source, "Widget widget", 1); - let definition = real_smoke_request( - &engine, - &session, - LspSemanticOperation::Definition, - Some(&source_uri), - None, - Some(widget_position), - ) - .unwrap_or_else(|error| panic!("{error}")); - let virtual_uri = real_smoke_locations(&definition) - .iter() - .find_map(|location| location.get("uri").and_then(Value::as_str)) - .filter(|uri| uri.starts_with("jdt://")) - .expect("Widget definition should resolve to a JDT virtual URI") - .to_string(); - let virtual_document = real_smoke_request( - &engine, - &session, - LspSemanticOperation::VirtualDocument, - None, - Some(&virtual_uri), - None, - ) - .unwrap_or_else(|error| panic!("{error}")); - let virtual_source = virtual_document - .get("text") - .and_then(Value::as_str) - .filter(|text| !text.is_empty()) - .expect("JDTLS should return decompiled Widget source"); - let virtual_position = - real_smoke_token_position(virtual_source, "class Widget", "class ".len()); - let virtual_references = real_smoke_request( - &engine, - &session, - LspSemanticOperation::References, - Some(&virtual_uri), - None, - Some(virtual_position), - ) - .unwrap_or_else(|error| panic!("{error}")); - assert!( - real_smoke_locations(&virtual_references).iter().any(|location| { - location.get("uri").and_then(Value::as_str) == Some(source_uri.as_str()) - }), - "virtual Widget references should include the synchronized project source: {virtual_references}" + assert_eq!( + harness.session().indexing_revision.load(Ordering::Acquire), + status.revision ); + crate::project::indexing::release(crate::project::indexing::ReleaseIndexingRequest { + owner_id: None, + root: root.to_string_lossy().into_owned(), + revision: status.revision, + }) + .unwrap(); } + /// Criterion 8: diagnostics for a stale document version are ignored. + /// Criterion 9: closing a document clears document and diagnostic state. #[test] - fn java_navigation_markers_resolve_only_implementation_lenses_and_omit_zero_targets() { - let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "codeLensProvider": { "resolveProvider": true } - })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/Service.java"; - harness.sync(uri, "public interface Service {}\n"); - let version = harness.snapshot().open_documents[uri].version; - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request_with_kind( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - Some(version), - ) - .expect("marker request should start"); + fn diagnostics_follow_the_current_document_version_and_clear_on_close() { + let mut harness = Harness::ready(); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + harness.sync(uri, "package main\nfunc main() {}"); - let code_lens_id = harness - .server - .await_request("textDocument/codeLens") - .expect("the marker operation should request CodeLens data"); harness.server.send(json!({ "jsonrpc": "2.0", - "id": code_lens_id, - "result": [ - { - "range": { - "start": { "line": 0, "character": 17 }, - "end": { "line": 0, "character": 24 } - }, - "data": [uri, { "line": 0, "character": 17 }, "implementations"] - }, - { + "method": "textDocument/publishDiagnostics", + "params": { + "uri": uri, + "version": 2, + "diagnostics": [{ "range": { - "start": { "line": 0, "character": 17 }, - "end": { "line": 0, "character": 24 } + "start": { "line": 1, "character": 0 }, + "end": { "line": 1, "character": 4 } }, - "data": [uri, { "line": 0, "character": 17 }, "references"] - } - ] + "severity": 1, + "message": "current" + }] + } })); - let resolve_id = harness - .server - .await_request("codeLens/resolve") - .expect("only the implementation lens should be resolved"); + harness.await_event(|event| { + event.kind == "diagnostics" + && event + .diagnostics + .as_ref() + .is_some_and(|list| list.len() == 1) + }); + assert_eq!(harness.snapshot().diagnostic_versions[uri], 2); + + // Version 1 is behind the open document, so it cannot replace version 2. harness.server.send(json!({ "jsonrpc": "2.0", - "id": resolve_id, - "result": { - "range": { - "start": { "line": 0, "character": 17 }, - "end": { "line": 0, "character": 24 } - }, - "command": { - "title": "0 implementations", - "command": "java.show.implementations", - "arguments": [] - } - } + "method": "textDocument/publishDiagnostics", + "params": { "uri": uri, "version": 1, "diagnostics": [] } })); + thread::sleep(Duration::from_millis(50)); + harness.poll(); + assert_eq!( + harness.snapshot().diagnostic_versions[uri], + 2, + "a stale version must not clear current diagnostics" + ); - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" - }); - assert_eq!(event.result.as_ref().unwrap()["documentVersion"], version); + harness.session().close_document(uri).unwrap(); + let snapshot = harness.snapshot(); + assert!(!snapshot.open_documents.contains_key(uri)); + assert!(!snapshot.diagnostic_versions.contains_key(uri)); + assert!( + harness.notification("textDocument/didClose").is_some(), + "the server must be told the document closed" + ); + // Clearing is published so the editor drops its markers, rather than + // leaving them until the next unrelated publish. + let cleared = harness + .poll() + .iter() + .rev() + .find(|event| event.kind == "diagnostics" && event.uri.as_deref() == Some(uri)); assert_eq!( - event.result.as_ref().unwrap()["markers"] - .as_array() + cleared + .and_then(|event| event.diagnostics.as_ref()) .map(Vec::len), Some(0) ); - assert_eq!( - harness - .server - .messages() - .iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) == Some("codeLens/resolve") - }) - .count(), - 1 - ); + } - let cached_operation_id = harness.engine.next_operation_id(); - assert!(harness - .session() - .complete_cached_java_navigation_markers(&cached_operation_id, uri, Some(version)) - .expect("the completed marker result should be cached")); - let logs = harness.session().poll_events().unwrap(); - let log = logs + /// A declarative plugin start handed off by the host ends in exactly one Core + /// result: `initialize` success, an exit before it, or nothing for a user stop. + /// Later exits belong to the session, not the start. A plugin API 1 server + /// starts host-owned, so the handoff alone names the plugin; a session owned + /// by a different plugin records nothing. + #[test] + fn declarative_plugin_start_records_one_host_operation_per_attempt() { + const PLUGIN: &str = "io.example.declarative-start"; + const OTHER: &str = "io.example.declarative-start-other"; + let handoff = |operation_id: &'static str, owner: Option<&'static str>| { + move |request: &mut StartServerRequest| { + request.plugin_id = owner.map(str::to_string); + request.startup_operation = Some(AttemptHandoff { + plugin_id: PLUGIN.to_string(), + operation_id: operation_id.to_string(), + elapsed_ms: 5, + }); + } + }; + + let mut ready = Harness::start(handoff("declarative-ready", Some(PLUGIN))); + ready.server.complete_initialize(ready_capabilities()); + ready.await_state(LspLifecycleState::Ready); + ready.server.exit(Some(1)); + ready.await_state(LspLifecycleState::Failed); + + let mut exited = Harness::start(handoff("declarative-exited", None)); + exited.server.exit(Some(2)); + exited.await_state(LspLifecycleState::Failed); + + let mut stopped = Harness::start(handoff("declarative-stopped", Some(PLUGIN))); + stopped.session().stop().unwrap(); + stopped.await_state(LspLifecycleState::Stopped); + + let mut foreign = Harness::start(handoff("declarative-foreign", Some(OTHER))); + foreign.server.exit(Some(3)); + foreign.await_state(LspLifecycleState::Failed); + assert!(plugin_operations::test_capture::take(OTHER).is_empty()); + + let facts = plugin_operations::test_capture::take(PLUGIN); + assert!(facts .iter() - .find(|event| event.event.as_deref() == Some("lsp.navigation.cache_hit")) - .unwrap(); - assert_eq!(log.detail.as_deref(), Some(format!("operationId={cached_operation_id}, uri={uri}, documentVersion={version}, markers=0").as_str())); - assert_eq!(log.fields.as_ref().unwrap()["document_version"], version); - assert_eq!(log.fields.as_ref().unwrap()["markers"], 0); - harness.events.extend(logs); - let cached_event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(cached_operation_id.as_str()) - && event.kind == "requestCompleted" - }); - assert_eq!( - cached_event.result.as_ref().unwrap()["documentVersion"], - version - ); + .all(|fact| std::ptr::eq(fact.contribution, &LANGUAGE_SERVER_START))); + let results: Vec<_> = facts + .into_iter() + .map(|fact| (fact.operation_id, fact.failure)) + .collect(); assert_eq!( - harness - .server - .messages() - .iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) == Some("textDocument/codeLens") - }) - .count(), - 1 + results, + [ + (Some("declarative-ready".to_string()), None), + ( + Some("declarative-exited".to_string()), + Some(AttemptStage::Exit) + ), + ] ); + } - harness.sync(uri, "public interface Service { void run(); }\n"); - let new_version = harness.snapshot().open_documents[uri].version; - assert_ne!(new_version, version); - assert!(!harness + /// startServer failing after spawn is a `launch` failure, and an initialize + /// timeout decided under the state lock is the only result even when the + /// response arrives afterwards. + #[test] + fn declarative_plugin_start_attributes_write_failure_and_timeout() { + const PLUGIN: &str = "io.example.declarative-start-failures"; + let handoff = |operation_id: &str, request: &mut StartServerRequest| { + request.plugin_id = Some(PLUGIN.to_string()); + request.startup_operation = Some(AttemptHandoff { + plugin_id: PLUGIN.to_string(), + operation_id: operation_id.to_string(), + elapsed_ms: 5, + }); + }; + + let broken = ScriptedServer::new(); + broken.break_input(); + let engine = LspEngine::with_launcher(broken.launcher()); + let mut request = start_request(&broken); + handoff("declarative-write-failed", &mut request); + assert!(engine.start_server(request).is_err()); + + let mut timed_out = Harness::start(|request| { + handoff("declarative-timed-out", request); + request.initialize_timeout_milliseconds = 60_000; + }); + timed_out .session() - .complete_cached_java_navigation_markers( - &harness.engine.next_operation_id(), - uri, - Some(new_version) - ) - .expect("editing the document should invalidate the marker cache")); + .expire_deadlines_at(Instant::now() + Duration::from_secs(61)); + timed_out.await_state(LspLifecycleState::Failed); + timed_out.server.complete_initialize(ready_capabilities()); + + let results: Vec<_> = plugin_operations::test_capture::take(PLUGIN) + .into_iter() + .map(|fact| (fact.operation_id, fact.failure)) + .collect(); + assert_eq!( + results, + [ + ( + Some("declarative-write-failed".to_string()), + Some(AttemptStage::Launch) + ), + ( + Some("declarative-timed-out".to_string()), + Some(AttemptStage::Timeout) + ), + ] + ); } + /// Criterion 10: shutdown sends exit after the response, and a shutdown that + /// is never answered force-terminates. #[test] - fn java_navigation_marker_batch_verifies_method_targets_and_keeps_both_directions() { - let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "codeLensProvider": { "resolveProvider": true }, - "implementationProvider": true - })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/Service.java"; - let source = concat!( - "interface Service { void run(); }\n", - "class ServiceImpl implements Service {\n", - " @Override public void run() {}\n", - "}\n" + fn shutdown_sends_exit_after_the_response_and_force_terminates_on_timeout() { + let mut harness = Harness::ready(); + harness.session().stop().unwrap(); + let shutdown_id = harness + .server + .await_request("shutdown") + .expect("stop should request shutdown"); + assert!( + harness.notification("exit").is_none(), + "exit must not precede the shutdown response" ); - harness.sync(uri, source); - let version = harness.snapshot().open_documents[uri].version; - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request_with_kind( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - Some(version), - ) - .expect("marker request should start"); - let code_lens_id = harness - .server - .await_request("textDocument/codeLens") - .expect("the marker operation should request CodeLens data"); harness.server.send(json!({ "jsonrpc": "2.0", - "id": code_lens_id, - "result": [] + "id": shutdown_id, + "result": null })); + assert!( + harness.server.await_notification("exit"), + "exit must follow the shutdown response" + ); + harness.server.exit(Some(0)); + harness.await_state(LspLifecycleState::Stopped); - let super_id = harness + let mut silent = Harness::start(|request| { + request.shutdown_timeout_milliseconds = 30; + }); + silent.server.complete_initialize(ready_capabilities()); + silent.await_state(LspLifecycleState::Ready); + silent.session().stop().unwrap(); + silent .server - .await_request("java/findLinks") - .expect("the override candidate should request its super implementation"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": super_id, - "result": [{ - "uri": uri, - "range": { - "start": { "line": 0, "character": 25 }, - "end": { "line": 0, "character": 28 } - } - }] - })); + .await_request("shutdown") + .expect("stop should request shutdown"); + // No response ever arrives, so the deadline must kill the process + // instead of leaving the session stuck in Stopping. + silent.await_state(LspLifecycleState::Stopped); + silent.await_event(|event| { + event.kind == "log" + && event.error.as_ref().is_some_and(|error| { + error.stage == "shutdown" && error.code == "shutdownTimeout" + }) + }); + } - let interface_implementation_id = harness - .server - .await_request_at("textDocument/implementation", 0) - .expect("the interface declaration should query implementations"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": interface_implementation_id, - "result": [{ - "uri": uri, - "range": { - "start": { "line": 2, "character": 26 }, - "end": { "line": 2, "character": 29 } - } - }] - })); + /// Criterion 11: a malformed `Content-Length` is a transport failure. + #[test] + fn a_malformed_content_length_header_fails_the_session_in_transport() { + let mut harness = Harness::ready(); + harness.server.send_raw(b"Content-Length: banana\r\n\r\n{}"); + harness.await_state(LspLifecycleState::Failed); - let overriding_implementation_id = harness - .server - .await_request_at("textDocument/implementation", 1) - .expect("the overriding method should query lower implementations"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": overriding_implementation_id, - "result": [{ - "uri": "file:///workspace/SpecialService.java", - "range": { - "start": { "line": 1, "character": 16 }, - "end": { "line": 1, "character": 19 } + let failure = harness + .events + .iter() + .find_map(|event| event.error.as_ref()) + .expect("bad framing should be reported as a runtime error"); + assert_eq!(failure.code, "transportFailed"); + assert_eq!(failure.stage, "transport"); + } + + /// Criterion 12: a partial frame is retained until it completes. + /// Criterion 13: consecutive frames are handled in order. + #[test] + fn partial_frames_are_buffered_and_consecutive_frames_arrive_in_order() { + let mut harness = Harness::ready(); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + + let split = |uri: &str, message: &str| { + let body = json!({ + "jsonrpc": "2.0", + "method": "textDocument/publishDiagnostics", + "params": { + "uri": uri, + "version": 1, + "diagnostics": [{ + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 0, "character": 1 } + }, + "severity": 1, + "message": message + }] } - }] - })); - - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" - }); - let markers = event.result.as_ref().unwrap()["markers"] - .as_array() - .expect("marker result should be an array"); - assert_eq!(markers.len(), 3); - assert!(markers.iter().any(|marker| { - marker["line"] == 0 - && marker["direction"] == "down" - && marker["relation"] == "interface" - })); - assert!(markers.iter().any(|marker| { - marker["line"] == 2 && marker["direction"] == "up" && marker["relation"] == "interface" - })); - assert!(markers.iter().any(|marker| { - marker["line"] == 2 - && marker["direction"] == "down" - && marker["relation"] == "inheritance" - })); - } + }) + .to_string(); + format!("Content-Length: {}\r\n\r\n{body}", body.len()) + }; - #[test] - fn java_navigation_marker_batch_is_cancelled_when_the_document_changes() { - let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "codeLensProvider": { "resolveProvider": true }, - "implementationProvider": true - })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/Service.java"; - harness.sync( - uri, - "class ServiceImpl implements Service { @Override public void run() {} }\n", + let first = split(uri, "first"); + let boundary = first.len() - 12; + harness.server.send_raw(first[..boundary].as_bytes()); + thread::sleep(Duration::from_millis(40)); + harness.poll(); + assert!( + !harness + .events + .iter() + .any(|event| event.kind == "diagnostics"), + "an incomplete frame must not be delivered" ); - let version = harness.snapshot().open_documents[uri].version; - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request_with_kind( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - Some(version), - ) - .expect("marker request should start"); - let code_lens_id = harness - .server - .await_request("textDocument/codeLens") - .expect("the marker operation should request CodeLens data"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": code_lens_id, - "result": [] - })); + // The tail of the first frame and a whole second frame arrive together, + // which is exactly how a stream coalesces writes. harness .server - .await_request("java/findLinks") - .expect("the first verification request should be in flight"); - - harness.sync( - uri, - "class ServiceImpl implements Service { @Override public void changed() {} }\n", - ); - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" + .send_raw(format!("{}{}", &first[boundary..], split(uri, "second")).as_bytes()); + harness.await_event(|event| { + event + .diagnostics + .as_ref() + .and_then(|list| list.first()) + .is_some_and(|diagnostic| diagnostic.message == "second") }); - assert_eq!( - event.error.as_ref().map(|error| error.code.as_str()), - Some("staleDocumentVersion") - ); - assert_eq!( - harness - .server - .messages() - .iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) - == Some("textDocument/implementation") - }) - .count(), - 0 - ); + let delivered: Vec<_> = harness + .events + .iter() + .filter(|event| event.kind == "diagnostics") + .filter_map(|event| event.diagnostics.as_ref()) + .filter_map(|list| list.first()) + .map(|diagnostic| diagnostic.message.clone()) + .collect(); + assert_eq!(delivered, vec!["first".to_string(), "second".to_string()]); + assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); } + /// Criterion 14: dynamic registration and unregistration change availability. #[test] - fn failed_java_marker_task_preserves_other_verified_markers() { + fn dynamic_capability_registration_and_unregistration_change_availability() { let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "codeLensProvider": { "resolveProvider": true }, - "implementationProvider": true - })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/Service.java"; - harness.sync(uri, "interface Service { void run(); }\n"); - let version = harness.snapshot().open_documents[uri].version; - let operation_id = harness.engine.next_operation_id(); + // Formatting is absent from the static capabilities, so it can only + // become available through dynamic registration. harness + .server + .complete_initialize(json!({ "hoverProvider": true })); + harness.await_state(LspLifecycleState::Ready); + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main"); + assert!(harness .session() - .request_with_kind( + .request( SemanticRequest { session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, + operation_id: Some("op-formatting".to_string()), + operation: LspSemanticOperation::Formatting, uri: Some(uri.to_string()), - virtual_uri: None, position: None, new_name: None, range: None, @@ -15359,707 +8076,493 @@ public class Main { code_action: None, command: None, }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - Some(version), + "op-formatting".to_string(), ) - .expect("marker request should start"); + .is_err()); - let code_lens_id = harness - .server - .await_request("textDocument/codeLens") - .expect("the marker operation should request CodeLens data"); harness.server.send(json!({ "jsonrpc": "2.0", - "id": code_lens_id, - "result": [{ - "range": { - "start": { "line": 0, "character": 25 }, - "end": { "line": 0, "character": 28 } - }, - "command": { "title": "1 implementation" } - }] + "id": "registration-1", + "method": "client/registerCapability", + "params": { + "registrations": [{ + "id": "formatting-1", + "method": "textDocument/formatting", + "registerOptions": {} + }] + } })); - let implementation_id = harness - .server - .await_request("textDocument/implementation") - .expect("the method candidate should be verified"); + let registered = harness + .await_event(|event| { + event + .capabilities + .as_ref() + .is_some_and(|names| names.iter().any(|name| name == "formatting")) + }) + .clone(); + assert_eq!(registered.kind, "featuresChanged"); + harness.server.send(json!({ "jsonrpc": "2.0", - "id": implementation_id, - "error": { "code": -32603, "message": "index temporarily unavailable" } + "id": "registration-2", + "method": "client/unregisterCapability", + "params": { + "unregisterations": [{ + "id": "formatting-1", + "method": "textDocument/formatting" + }] + } })); - - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" + // The initialize handshake also emitted a formatting-free feature set, so + // the withdrawal is only identifiable by coming after the registration. + let registered_at = registered.sequence; + harness.await_event(|event| { + event.kind == "featuresChanged" + && event.sequence > registered_at + && event + .capabilities + .as_ref() + .is_some_and(|names| !names.iter().any(|name| name == "formatting")) }); - assert!(event.error.is_none()); - assert_eq!( - event.result.as_ref().unwrap()["markers"] - .as_array() - .map(Vec::len), - Some(1) + assert!( + harness + .session() + .request( + SemanticRequest { + session_id: harness.session_id.clone(), + operation_id: Some("op-formatting-2".to_string()), + operation: LspSemanticOperation::Formatting, + uri: Some(uri.to_string()), + position: None, + new_name: None, + range: None, + diagnostics: Vec::new(), + completion_context: None, + completion_item: None, + code_action: None, + command: None, + }, + "op-formatting-2".to_string(), + ) + .is_err(), + "an unregistered capability must stop being offered" ); - assert!(harness.events.iter().any(|event| { - event.kind == "log" - && event.error.as_ref().is_some_and(|error| { - error.stage == "navigation" && error.code == "navigationMarkerFailed" - }) - })); } + /// Criterion 15: replacing the workspace stops the old root and clears it. #[test] - fn java_navigation_marker_batch_enforces_the_task_limit() { - let mut harness = Harness::start(|_| {}); - harness.server.complete_initialize(json!({ - "codeLensProvider": { "resolveProvider": true }, - "implementationProvider": true + fn replacing_the_workspace_stops_the_old_root_and_clears_its_state() { + let old_server = ScriptedServer::new(); + let engine = LspEngine::with_launcher(old_server.launcher()); + let old = engine.start_server(start_request(&old_server)).unwrap(); + old_server.complete_initialize(ready_capabilities()); + let old_session = engine.session(&old.session_id).unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline + && old_session.snapshot().unwrap().state != LspLifecycleState::Ready + { + thread::sleep(Duration::from_millis(2)); + } + let uri = "file:///workspace/main.go"; + old_session + .sync_document(SyncDocumentRequest { + session_id: old.session_id.clone(), + uri: uri.to_string(), + language_id: "go".to_string(), + text: "package main".to_string(), + content_changes: Vec::new(), + }) + .unwrap(); + old_server.send(json!({ + "jsonrpc": "2.0", + "method": "textDocument/publishDiagnostics", + "params": { + "uri": uri, + "version": 1, + "diagnostics": [{ + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 0, "character": 1 } + }, + "severity": 1, + "message": "old root" + }] + } })); - harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/LargeService.java"; - let methods = (0..(MAX_JAVA_NAVIGATION_TASKS + 1)) - .map(|index| format!(" void method{index}();")) - .collect::>() - .join("\n"); - let source = format!("interface LargeService {{\n{methods}\n}}\n"); - harness.sync(uri, &source); - let version = harness.snapshot().open_documents[uri].version; - let operation_id = harness.engine.next_operation_id(); - harness - .session() - .request_with_kind( - SemanticRequest { - session_id: harness.session_id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::CodeLens, - uri: Some(uri.to_string()), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - PendingKind::JavaNavigationMarkers, - Some(version), - ) - .expect("marker request should start"); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline + && !old_session + .snapshot() + .unwrap() + .diagnostic_versions + .contains_key(uri) + { + thread::sleep(Duration::from_millis(2)); + } - let code_lens_id = harness - .server - .await_request("textDocument/codeLens") - .expect("the marker operation should request CodeLens data"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": code_lens_id, - "result": [] - })); - for index in 0..MAX_JAVA_NAVIGATION_TASKS { - let request_id = harness - .server - .await_request_at("textDocument/implementation", index) - .expect("every task within the limit should be requested"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": request_id, - "result": [] - })); + old_session.stop().unwrap(); + let shutdown = old_server.await_request("shutdown").unwrap(); + old_server.send(json!({ "jsonrpc": "2.0", "id": shutdown, "result": null })); + old_server.exit(Some(0)); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline + && old_session.snapshot().unwrap().state != LspLifecycleState::Stopped + { + thread::sleep(Duration::from_millis(2)); } - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" - }); - assert_eq!( - event.result.as_ref().unwrap()["markers"] - .as_array() - .map(Vec::len), - Some(0) + let stopped = old_session.snapshot().unwrap(); + assert_eq!(stopped.root_uri, "file:///workspace"); + assert_eq!(stopped.state, LspLifecycleState::Stopped); + assert!(stopped.open_documents.is_empty()); + assert!(stopped.diagnostic_versions.is_empty()); + assert!(stopped.pending_operation_ids.is_empty()); + assert!( + old_server.input_was_closed(), + "the old root's stdin must be released" ); + + // Only a stopped session may be destroyed, and a destroyed one is + // unreachable, so the replacement cannot inherit any of its state. + engine.destroy(&old.session_id).unwrap(); + assert!(engine.session(&old.session_id).is_err()); + assert!(old_session + .sync_document(SyncDocumentRequest { + session_id: old.session_id.clone(), + uri: uri.to_string(), + language_id: "go".to_string(), + text: "package main".to_string(), + content_changes: Vec::new(), + }) + .is_err()); + } + + #[test] + fn semantic_operations_are_protocol_methods_but_never_expose_request_ids() { assert_eq!( - harness - .server - .messages() - .iter() - .filter(|message| { - message.get("method").and_then(Value::as_str) - == Some("textDocument/implementation") - }) - .count(), - MAX_JAVA_NAVIGATION_TASKS + semantic_method(LspSemanticOperation::Definition), + "textDocument/definition" ); - assert!(harness.events.iter().any(|event| { - event.kind == "log" - && event.error.as_ref().is_some_and(|error| { - error.stage == "navigation" && error.code == "navigationLimited" - }) - })); } #[test] - fn java_super_navigation_normalizes_find_links_locations() { + fn workspace_execute_command_does_not_require_an_open_document() { let mut harness = Harness::start(|_| {}); harness.server.complete_initialize(json!({ - "definitionProvider": true + "executeCommandProvider": { "commands": ["source.fix"] } })); harness.await_state(LspLifecycleState::Ready); - let uri = "file:///workspace/ServiceImpl.java"; - harness.sync( - uri, - "class ServiceImpl { @Override public void run() {} }\n", - ); - let version = harness.snapshot().open_documents[uri].version; let operation_id = harness.engine.next_operation_id(); + harness .session() - .request_with_kind( + .request( SemanticRequest { session_id: harness.session_id.clone(), operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaSuperImplementation, - uri: Some(uri.to_string()), - virtual_uri: None, - position: Some(LspPosition { - line: 0, - utf16_column: 42, - }), + operation: LspSemanticOperation::ExecuteCommand, + uri: None, + position: None, new_name: None, range: None, diagnostics: Vec::new(), completion_context: None, completion_item: None, code_action: None, - command: None, + command: Some(json!({ + "title": "Apply fix", + "command": "source.fix", + "arguments": [] + })), }, - operation_id.clone(), - PendingKind::JavaResolveNavigation, - Some(version), + operation_id, ) - .expect("super navigation should start"); + .expect("workspace commands should not be gated on an open document"); - let find_links_id = harness + let request = harness .server - .await_request("java/findLinks") - .expect("super navigation should use JDT LS findLinks"); - harness.server.send(json!({ - "jsonrpc": "2.0", - "id": find_links_id, - "result": [{ - "uri": "file:///workspace/Service.java", - "range": { - "start": { "line": 0, "character": 25 }, - "end": { "line": 0, "character": 28 } - } - }] - })); - - let event = harness.await_event(|event| { - event.operation_id.as_deref() == Some(operation_id.as_str()) - && event.kind == "requestCompleted" - }); - let locations = event.result.as_ref().unwrap()["locations"] - .as_array() - .expect("findLinks should be normalized to locations"); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0]["uri"], "file:///workspace/Service.java"); - assert_eq!(event.result.as_ref().unwrap()["documentVersion"], version); - } - - #[test] - fn java_runtime_is_derived_from_the_start_environment() { - let environment = BTreeMap::from([("JAVA_HOME".to_string(), "/jdk".to_string())]); - let path = java_executable_from_environment(&environment).unwrap(); - assert!(path.ends_with(if cfg!(windows) { - "bin/java.exe" - } else { - "bin/java" - })); - } - - #[test] - fn start_contract_rejects_missing_runtime_identity() { - let request = StartServerRequest { - provider_id: String::new(), - role: SessionRole::LanguageServer, - log_subject: None, - plugin_id: None, - startup_operation: None, - host_services: Vec::new(), - 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(), - root_uri: "file:///workspace".to_string(), - working_directory: "/workspace".to_string(), - initialization_options: None, - workspace_configuration: None, - runtime_executable_path: None, - jdtls_launch_resources: None, - cache_directory: None, - workspace_fingerprint: None, - maven_context: None, - java_runtimes: Vec::new(), - java_gradle: None, - initialize_timeout_milliseconds: 1, - service_ready_idle_timeout_milliseconds: 1, - service_ready_absolute_timeout_milliseconds: 1, - request_timeout_milliseconds: 1, - java_build_timeout_milliseconds: DEFAULT_JAVA_BUILD_TIMEOUT_MS, - shutdown_timeout_milliseconds: 1, - }; - assert!(validate_start_request(&request).is_err()); - } - - #[test] - fn direct_jdtls_contract_requires_a_java_provider_and_runtime() { - let server = ScriptedServer::new(); - let mut request = start_request(&server); - request.jdtls_launch_resources = Some(JdtlsLaunchResources { - launcher_jar_path: "/jdtls/plugins/equinox.jar".to_string(), - configuration_directory: "/jdtls/config_mac".to_string(), - lombok_agent_path: "/jdtls/lombok/lombok.jar".to_string(), - java_debug_bundle_path: None, - java_extension_bundle_paths: Vec::new(), - }); - - assert!(validate_start_request(&request).is_err()); - request.provider_id = "java".to_string(); - assert!(validate_start_request(&request).is_err()); - request.runtime_executable_path = Some("/jdk/bin/java".to_string()); - assert!(validate_start_request(&request).is_ok()); + .messages() + .into_iter() + .find(|message| message["method"] == "workspace/executeCommand") + .expect("the command should reach the language server"); + assert_eq!(request["params"]["command"], "source.fix"); + assert!(request["params"].get("textDocument").is_none()); } #[test] - fn direct_jdtls_start_request_matches_the_shared_contract_fixture() { + fn document_saves_honor_server_options_and_never_replace_newer_editor_text() { let fixture: Value = serde_json::from_str(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), - "/../../shared/fixtures/lsp/jdt-direct-launch-v1.json" + "/../../shared/fixtures/lsp/document-save-v1.json" ))) - .expect("direct JDTLS fixture should be valid JSON"); - let request: StartServerRequest = serde_json::from_value(fixture["request"].clone()) - .expect("fixture request should match the Core contract"); - - validate_start_request(&request).expect("fixture request should be valid"); - let resources = request - .jdtls_launch_resources - .expect("fixture should use structured direct launch"); - assert_eq!( - request.runtime_executable_path.as_deref(), - Some("/opt/lithe/jdk/bin/java") - ); - assert_eq!( - resources.configuration_directory, - "/opt/lithe/jdtls/config_mac" - ); - assert_eq!( - resources.java_extension_bundle_paths, - vec![ - "/opt/lithe/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar", - "/opt/lithe/jdtls/java-test/extensions/com.microsoft.java.test.plugin-0.42.0.jar", - ] - ); - assert_eq!(request.initialize_timeout_milliseconds, 30_000); - assert_eq!(request.service_ready_idle_timeout_milliseconds, 45_000); - assert_eq!(request.service_ready_absolute_timeout_milliseconds, 600_000); - } - - const JAVA_PROBE_COMMAND: &str = "java.probe"; - - fn java_build_command() -> Value { - json!({ - "title": "Build Java Workspace", - "command": "vscode.java.buildWorkspace", - "arguments": ["{\"mainClass\":\"demo.App\",\"isFullBuild\":false}"] - }) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let option = &case["saveOption"]; + let mut harness = Harness::start(|_| {}); + let mut capabilities = ready_capabilities(); + capabilities["textDocumentSync"] = json!({"change": 1, "save": option}); + harness.server.complete_initialize(capabilities); + harness.await_state(LspLifecycleState::Ready); + let uri = case["uri"].as_str().unwrap(); + let saved_text = case["savedText"].as_str().unwrap(); + harness.sync(uri, saved_text); + let saved = || SaveDocumentRequest { + session_id: harness.session_id.clone(), + uri: uri.to_string(), + text: saved_text.to_string(), + }; + let supported = case["sent"].as_bool().unwrap(); + assert_eq!(harness.session().save_document(saved()).unwrap(), supported); + if supported { + let notification = harness + .server + .await_notification_at("textDocument/didSave", 0) + .unwrap(); + assert_eq!(notification["params"]["textDocument"]["uri"], uri); + assert_eq!( + notification["params"].get("text"), + case["includeText"] + .as_bool() + .unwrap() + .then_some(&json!(saved_text)) + ); + } + harness.sync(uri, "newer unsaved edit"); + assert!(!harness.session().save_document(saved()).unwrap()); + let session = harness.session(); + let state = session.lock_state().unwrap(); + assert_eq!( + state.client.open_documents[uri].text.as_ref(), + "newer unsaved edit" + ); + assert_eq!(state.client.open_documents[uri].version, 2); + } } - fn java_probe_command() -> Value { - json!({ "command": JAVA_PROBE_COMMAND, "arguments": [] }) - } + /// Removes a scratch directory when the owning test ends or unwinds. + struct ScratchDirectory(PathBuf); - /// A ready JDT session whose Java builds use `java_build_timeout_milliseconds`. - fn java_build_harness(java_build_timeout_milliseconds: u64) -> Harness { - let mut harness = Harness::start(|request| { - request.provider_id = "java".to_string(); - request.cache_directory = Some( - std::env::temp_dir() - .join("lithe-lsp-engine-tests") - .to_string_lossy() - .into_owned(), - ); - request.java_build_timeout_milliseconds = java_build_timeout_milliseconds; - }); - harness.server.complete_java_initialize(json!({ - "executeCommandProvider": { - "commands": ["vscode.java.buildWorkspace", JAVA_PROBE_COMMAND] - } - })); - harness.await_state(LspLifecycleState::Ready); - harness + impl Drop for ScratchDirectory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } } + // Regression: JDT publishes diagnostics under the resolved path of a file + // the host opened through a symbolic link; matching the URIs textually + // dropped every Java error in such a workspace. + #[cfg(unix)] #[test] - fn java_preparation_reports_configuration_but_not_background_indexing() { - let mut harness = java_build_harness(60_000); - let session = harness.engine.session(&harness.session_id).unwrap(); - send_project_job_progress( - &mut harness, - "index", - json!({ "kind": "begin", "title": "Indexing" }), - ); - assert_eq!( - session - .lock_state() - .unwrap() - .preparation_snapshot - .as_ref() - .unwrap() - .phase, - "ready" - ); - send_project_job_progress( - &mut harness, - "config", - json!({ "kind": "begin", "message": "Update project sample" }), - ); - assert_eq!( - session - .lock_state() - .unwrap() - .preparation_snapshot - .as_ref() - .unwrap() - .phase, - "configuring" - ); - send_project_job_progress(&mut harness, "config", json!({ "kind": "end" })); - harness.poll(); - // The snapshot survives consuming all events, so a reconnect can render readiness. - assert_eq!( - session - .lock_state() - .unwrap() - .preparation_snapshot - .as_ref() - .unwrap() - .phase, - "ready" - ); - assert!(harness - .events - .iter() - .any(|event| event.kind == "projectPreparation" - && event - .result - .as_ref() - .is_some_and(|result| result["phase"] == "configuring"))); - } + fn diagnostics_published_under_the_resolved_path_reach_the_linked_document() { + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system clock should follow the Unix epoch") + .as_nanos(); + let scratch = ScratchDirectory(std::env::temp_dir().join(format!( + "lithe-linked-diagnostics-{}-{stamp}", + std::process::id() + ))); + let workspace = scratch.0.join("resolved"); + std::fs::create_dir_all(&workspace).expect("workspace should be creatable"); + std::fs::write(workspace.join("main.go"), "package main").expect("source file"); + let link = scratch.0.join("link"); + std::os::unix::fs::symlink(&workspace, &link).expect("link should be creatable"); + let opened_uri = url::Url::from_file_path(link.join("main.go")) + .expect("linked file converts to a URI") + .to_string(); + let published_uri = url::Url::from_file_path( + workspace + .canonicalize() + .expect("workspace canonicalizes") + .join("main.go"), + ) + .expect("resolved file converts to a URI") + .to_string(); + assert_ne!(opened_uri, published_uri); - fn send_project_job_progress(harness: &mut Harness, token: &str, value: Value) { + let mut harness = Harness::ready(); + harness.sync(&opened_uri, "package main"); harness.server.send(json!({ "jsonrpc": "2.0", - "method": "$/progress", - "params": { "token": token, "value": value } + "method": "textDocument/publishDiagnostics", + "params": { + "uri": published_uri, + "diagnostics": [{ + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 0, "character": 7 } + }, + "severity": 1, + "message": "reported at the resolved path" + }] + } })); - // Progress is logged and recorded under the same state lock, so the - // log proves the coordinator observed it. - let token = token.to_string(); - harness.await_event(move |event| { - event.message.as_deref() == Some("$/progress") - && event.detail.as_deref().is_some_and(|detail| { - detail.contains(&token) && detail.contains(value_kind(&value)) - }) - }); - } - - fn value_kind(value: &Value) -> &str { - value["kind"].as_str().unwrap_or_default() + let event = harness + .await_event(|event| event.kind == "diagnostics") + .clone(); + assert_eq!(event.uri.as_deref(), Some(opened_uri.as_str())); + assert_eq!(event.diagnostics.map(|list| list.len()), Some(1)); } - fn java_log_detail<'a>(harness: &'a mut Harness, message: &'static str) -> &'a str { - harness - .await_event(move |event| event.message.as_deref() == Some(message)) - .detail - .as_deref() - .unwrap_or_default() + fn open_document(uri: &str) -> (String, LspClientDocument) { + ( + uri.to_string(), + LspClientDocument { + uri: uri.to_string(), + language_id: "go".to_string(), + version: 1, + text: "".into(), + }, + ) } - /// Issue #692: Run built while JDT was still updating Maven projects and - /// repeated Run clicks started overlapping builds. Builds now wait for the - /// project job to end, run one at a time, and identical queued requests - /// share the next build. + // Servers publish for many files nobody has open. A session whose documents + // were not opened through a link must remember that and leave those + // messages untouched; closing a document must forget what was learned. + #[cfg(unix)] #[test] - fn java_builds_wait_for_project_updates_and_never_overlap() { - let mut harness = java_build_harness(60_000); - send_project_job_progress( - &mut harness, - "update-1", - json!({ "kind": "begin", "message": "Update project ruoyi-vue-plus" }), - ); - - let first = harness.execute_command(java_build_command()); - assert!( - java_log_detail(&mut harness, "Java project build is waiting") - .contains("waitingForProjectConfiguration") - ); - // An ordinary command is written immediately; being the first - // executeCommand on the wire proves the build was held back. - let probe = harness.execute_command(java_probe_command()); - let probe_id = harness - .server - .await_request_at("workspace/executeCommand", 0) - .expect("the probe should reach JDT LS"); - assert_eq!( - harness.written_request(&probe_id)["params"]["command"], - JAVA_PROBE_COMMAND - ); - - send_project_job_progress(&mut harness, "update-1", json!({ "kind": "end" })); - let first_build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("the build should start once the project update ends"); - assert_eq!( - harness.written_request(&first_build)["params"], - java_build_command() - ); + fn diagnostics_for_unlinked_documents_are_left_alone_and_forgotten_on_close() { + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system clock should follow the Unix epoch") + .as_nanos(); + let scratch = ScratchDirectory(std::env::temp_dir().join(format!( + "lithe-unlinked-diagnostics-{}-{stamp}", + std::process::id() + ))); + std::fs::create_dir_all(&scratch.0).expect("scratch should be creatable"); + let real = scratch.0.canonicalize().expect("scratch canonicalizes"); + std::fs::write(real.join("main.go"), "package main").expect("source file"); + std::fs::write(real.join("other.go"), "package main").expect("source file"); + let uri_of = |name: &str| { + url::Url::from_file_path(real.join(name)) + .expect("file converts to a URI") + .to_string() + }; + let message = |uri: &str| { + json!({ + "jsonrpc": "2.0", + "method": "textDocument/publishDiagnostics", + "params": { "uri": uri, "diagnostics": [] } + }) + }; - let second = harness.execute_command(java_build_command()); - let third = harness.execute_command(java_build_command()); - harness.execute_command(java_probe_command()); - let second_probe = harness - .server - .await_request_at("workspace/executeCommand", 2) - .expect("the second probe should reach JDT LS"); + let documents: BTreeMap<_, _> = [open_document(&uri_of("main.go"))].into(); + let mut linked = LinkedDocumentPaths::default(); assert_eq!( - harness.written_request(&second_probe)["params"]["command"], - JAVA_PROBE_COMMAND, - "no second build may start while the first is running" + diagnostics_addressed_to_open_document( + &documents, + &mut linked, + &message(&uri_of("other.go")) + ), + None ); + assert!(linked.resolved.is_empty()); + assert!(linked.examined.contains(&uri_of("main.go"))); - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": first_build, "result": 1 })); - let first_event = harness - .await_event(|event| event.operation_id.as_deref() == Some(first.as_str())) - .clone(); - assert!(first_event.error.is_none()); - assert_eq!(first_event.result, Some(json!({ "value": 1 }))); - - let shared_build = harness - .server - .await_request_at("workspace/executeCommand", 3) - .expect("the queued callers should start one shared build"); - assert_eq!( - harness.written_request(&shared_build)["params"], - java_build_command() + diagnostics_addressed_to_open_document( + &BTreeMap::new(), + &mut linked, + &message(&uri_of("other.go")), ); - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": shared_build, "result": 2 })); - for operation_id in [&second, &third] { - let event = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id.as_str())) - .clone(); - let error = event - .error - .as_ref() - .expect("WITH_ERROR must report build evidence"); - assert_eq!(error.code, "javaBuildCompilationErrors"); - assert_eq!(error.stage, "javaBuild"); - let report = error - .java_build_report - .as_ref() - .expect("a terminal build verdict must include its evidence"); - assert_eq!(report.marker_scope, JavaBuildMarkerScope::Workspace); - assert!(!report.builder_failed_earlier); - assert_eq!(report.recovery, JavaBuildRecovery::RebuildJavaIndex); - let serialized = serde_json::to_value(error).expect("runtime error should serialize"); - assert_eq!(serialized["javaBuildReport"]["markerScope"], "workspace"); - assert_eq!(serialized["javaBuildReport"]["builderFailedEarlier"], false); - assert!(serialized["javaBuildReport"]["elapsedMilliseconds"].is_u64()); - assert_eq!( - serialized["javaBuildReport"]["recovery"], - "rebuildJavaIndex" - ); - } - let builds_written = harness - .server - .messages() - .into_iter() - .filter(|message| message["params"]["command"] == "vscode.java.buildWorkspace") - .count(); - assert_eq!(builds_written, 2); - - for request_id in [probe_id, second_probe] { - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": request_id, "result": null })); - } - harness.await_event(|event| event.operation_id.as_deref() == Some(probe.as_str())); + assert!(linked.examined.is_empty()); } - /// A caller deadline sends advisory cancellation, but JDT may keep - /// building, so the next build waits for the old build's late answer. #[test] - fn a_timed_out_java_build_keeps_its_slot_until_jdt_answers() { - let mut harness = java_build_harness(100); - let first = harness.execute_command(java_build_command()); - let first_build = harness - .server - .await_request_at("workspace/executeCommand", 0) - .expect("an unblocked build should start immediately"); - - let timeout = harness - .await_event(|event| event.operation_id.as_deref() == Some(first.as_str())) - .clone() - .error - .expect("the caller deadline should fail the operation"); - assert_eq!(timeout.code, "requestTimeout"); - assert!(timeout - .underlying_message - .as_deref() - .is_some_and(|detail| detail.contains("phase=building"))); - assert!(harness.server.await_notification("$/cancelRequest")); - let cancellation = harness - .notification("$/cancelRequest") - .expect("the cancellation should be recorded"); - assert_eq!(cancellation["params"]["id"], first_build); - - let second = harness.execute_command(java_build_command()); - let queued_timeout = harness - .await_event(|event| event.operation_id.as_deref() == Some(second.as_str())) - .clone() - .error - .expect("the queued caller should time out"); - assert!(queued_timeout - .underlying_message - .as_deref() - .is_some_and(|detail| detail.contains("phase=waitingForPreviousBuild"))); - - harness - .server - .send(json!({ "jsonrpc": "2.0", "id": first_build, "result": 3 })); - assert!(java_log_detail(&mut harness, "Java project build finished") - .contains("\"waiterCount\":0")); - harness.execute_command(java_build_command()); - let next_build = harness - .server - .await_request_at("workspace/executeCommand", 1) - .expect("the answered build should release the slot"); - assert_ne!(next_build, first_build); - } - - /// A stalled maintenance write must not stop waiter deadlines or prevent - /// transport termination. Past timestamps drive each timeout without sleeps. - fn assert_blocked_maintenance_write_terminates(cancellation: bool) { - struct Cleanup(Arc); - impl Drop for Cleanup { - fn drop(&mut self) { - self.0.kill_process(); - } - } - - let mut harness = java_build_harness(60_000); - let session = harness.session(); - let _cleanup = Cleanup(session.clone()); - if cancellation { - let probe = harness.execute_command(java_probe_command()); - let request_id = harness - .server - .await_request("workspace/executeCommand") - .unwrap(); - harness.server.pause_input(); - session - .lock_state() - .unwrap() - .pending - .get_mut(&request_id) - .unwrap() - .deadline = Instant::now(); - harness.await_event(|event| event.operation_id.as_deref() == Some(probe.as_str())); - assert!(harness.server.await_input_pause()); - } else { - harness.server.pause_input(); - } - // Queue directly to exercise the maintenance writer, not the caller's - // immediate dispatch or the stdout reader's progress-triggered dispatch. - session.lock_state().unwrap().java_builds.enqueue( - "blocked-build".into(), - java_build_command(), - Instant::now(), - Duration::from_secs(60), + fn wait_events_returns_queued_events_without_waiting_the_timeout() { + let harness = Harness::start(|_| {}); + let started = Instant::now(); + let events = harness + .session() + .wait_events(Duration::from_secs(2)) + .expect("waiting should succeed"); + assert!( + !events.is_empty(), + "starting a session should enqueue at least one lifecycle event" + ); + assert!( + started.elapsed() < Duration::from_millis(500), + "queued events must not wait out the timeout" ); - if !cancellation { - assert!(harness.server.await_input_pause()); - } - - for operation_id in ["expired-one", "expired-two"] { - session.lock_state().unwrap().java_builds.enqueue( - operation_id.into(), - java_build_command(), - Instant::now() - Duration::from_secs(2), - Duration::from_secs(1), - ); - let error = harness - .await_event(|event| event.operation_id.as_deref() == Some(operation_id)) - .error - .as_ref() - .expect("the monitor must keep expiring callers"); - assert_eq!(error.code, "requestTimeout"); - } - - // Force the write's own deadline after proving the monitor remained live. - session.lock_state().unwrap().maintenance_write_deadline = Some(Instant::now()); - harness.await_state(LspLifecycleState::Failed); - let error = harness - .await_event(|event| event.operation_id.as_deref() == Some("blocked-build")) - .error - .as_ref() - .expect("the stalled transport must fail its remaining caller"); - assert_eq!(error.code, "transportFailed"); - assert!(harness.server.await_input_resumed()); - assert!(session.process.exit_status().is_some()); - assert!(harness.snapshot().pending_operation_ids.is_empty()); } #[test] - fn blocked_java_build_write_preserves_deadlines_and_terminates() { - assert_blocked_maintenance_write_terminates(false); + fn wait_events_times_out_with_an_empty_queue() { + let mut harness = Harness::ready(); + harness.poll(); + let started = Instant::now(); + let events = harness + .session() + .wait_events(Duration::from_millis(40)) + .expect("waiting should succeed"); + assert!(events.is_empty()); + assert!(started.elapsed() >= Duration::from_millis(30)); } #[test] - fn blocked_deadline_cancellation_preserves_deadlines_and_terminates() { - assert_blocked_maintenance_write_terminates(true); + fn wait_events_wakes_when_the_session_enqueues_a_lifecycle_event() { + let mut harness = Harness::ready(); + harness.poll(); + let session = harness.session(); + let waiter = thread::spawn({ + let session = Arc::clone(&session); + move || { + session + .wait_events(Duration::from_secs(2)) + .expect("waiting should succeed") + } + }); + thread::sleep(Duration::from_millis(30)); + session.stop().expect("the session should stop"); + let events = waiter.join().expect("the waiter thread should finish"); + assert!( + events.iter().any(|event| event.kind == "stateChanged"), + "stop should wake waiters with a lifecycle event, got {events:?}" + ); } #[test] - fn stopping_the_session_fails_queued_java_builds() { - let mut harness = java_build_harness(60_000); - send_project_job_progress( - &mut harness, - "update-1", - json!({ "kind": "begin", "message": "Updating project configurations" }), + fn wait_events_errors_after_terminal_state_events_are_drained() { + let mut harness = Harness::ready(); + harness.poll(); + harness.session().stop().unwrap(); + let shutdown_id = harness + .server + .await_request("shutdown") + .expect("stop should request shutdown"); + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": shutdown_id, + "result": null + })); + assert!( + harness.server.await_notification("exit"), + "exit must follow the shutdown response" ); - let queued = harness.execute_command(java_build_command()); - java_log_detail(&mut harness, "Java project build is waiting"); + harness.server.exit(Some(0)); + harness.await_state(LspLifecycleState::Stopped); + + // Drain any remaining lifecycle events from the stop transition. + loop { + let events = match harness.session().wait_events(Duration::from_millis(20)) { + Ok(events) => events, + Err(error) => { + assert!(matches!(error.code, ErrorCode::ProcessFailed)); + assert_eq!(error.details.as_deref(), Some("sessionStopped")); + return; + } + }; + if events.is_empty() { + break; + } + } - harness.session().stop().expect("stop should succeed"); let error = harness - .await_event(|event| event.operation_id.as_deref() == Some(queued.as_str())) - .clone() - .error - .expect("a stopping session cannot build"); - assert_eq!(error.code, "requestCancelled"); - assert!(harness.snapshot().pending_operation_ids.is_empty()); + .session() + .wait_events(Duration::from_millis(50)) + .expect_err("drained terminal sessions must not return empty Ok"); + assert!(matches!(error.code, ErrorCode::ProcessFailed)); + assert_eq!(error.details.as_deref(), Some("sessionStopped")); } /// Execution must not reach a model-only provider. diff --git a/rust/lithe-core/src/lsp/interface/engine_logging.rs b/rust/lithe-core/src/lsp/interface/engine_logging.rs index c9fac636a5..568b2d9e6d 100644 --- a/rust/lithe-core/src/lsp/interface/engine_logging.rs +++ b/rust/lithe-core/src/lsp/interface/engine_logging.rs @@ -2,7 +2,6 @@ use super::engine::LspRuntimeError; use crate::diagnostics::channel::{digest_segment, identity_segment, validate_segment}; -use crate::lsp::languages::jdt::MavenProfileProjectResult; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -132,30 +131,7 @@ pub(super) enum EngineLog { ProcessStarted, ProcessCleanupFailed, ProtocolInitialized, - ConfigurationCleaned, - ConfigurationCleanupFailed, - LegacyRemoved, - MavenSettingsForwarded, - MavenConfigurationUpdated, - MavenCancelled, - MavenProjectFinished, - MavenApplied, - MavenPartiallyApplied, - MavenApplicationStarted, - MavenStartFailed, - MavenTimedOut, - MavenTaskUpdated, - NavigationCacheHit, - NavigationLimited, - NavigationMarkerFailed, - NavigationResolved, ResponseSkipped, - WorkspaceProgressReceived, - WorkspaceWaiting, - WorkspaceImportFinished, - WorkspaceStalled, - BuildWaiting, - BuildExecution, ShutdownTimedOut, StderrReceived, StderrReadFailed, @@ -209,30 +185,7 @@ impl EngineLog { Self::ProcessCleanupFailed => "process.cleanup_failed", Self::ProcessStarted => "process.started", Self::ProtocolInitialized => "protocol.initialized", - Self::ConfigurationCleaned => "configuration.cleaned", - Self::ConfigurationCleanupFailed => "configuration.cleanup_failed", - Self::LegacyRemoved => "workspace.legacy_removed", - Self::MavenSettingsForwarded => "maven.settings_forwarded", - Self::MavenConfigurationUpdated => "maven.configuration_updated", - Self::MavenCancelled => "maven.cancelled", - Self::MavenProjectFinished => "maven.project_finished", - Self::MavenApplied => "maven.applied", - Self::MavenPartiallyApplied => "maven.partially_applied", - Self::MavenApplicationStarted => "maven.application_started", - Self::MavenStartFailed => "maven.start_failed", - Self::MavenTimedOut => "maven.timed_out", - Self::MavenTaskUpdated => "maven.task_updated", - Self::NavigationCacheHit => "navigation.cache_hit", - Self::NavigationLimited => "navigation.limited", - Self::NavigationMarkerFailed => "navigation.marker_failed", - Self::NavigationResolved => "navigation.resolved", Self::ResponseSkipped => "response.skipped", - Self::WorkspaceProgressReceived => "workspace.progress_received", - Self::WorkspaceWaiting => "workspace.waiting", - Self::WorkspaceImportFinished => "workspace.import_finished", - Self::WorkspaceStalled => "workspace.stalled", - Self::BuildWaiting => "build.waiting", - Self::BuildExecution => "build.execution", Self::ShutdownTimedOut => "shutdown.timed_out", Self::StderrReceived => "stderr.received", Self::StderrReadFailed => "stderr.read_failed", @@ -265,10 +218,7 @@ impl EngineLog { ); copy(&mut fields, "truncated", &input, "truncated"); } - Self::ProcessCleanupFailed - | Self::StderrReadFailed - | Self::ConfigurationCleanupFailed - | Self::MavenStartFailed => failure(&mut fields, code), + Self::ProcessCleanupFailed | Self::StderrReadFailed => failure(&mut fields, code), Self::MessageLogged | Self::MessageShown => { copy(&mut fields, "diagnostic", &input, "diagnostic"); copy(&mut fields, "severity", &input, "severity"); @@ -293,77 +243,13 @@ impl EngineLog { Self::NotificationReceived => { copy(&mut fields, "method", &input, "method"); } - Self::SessionUpdated | Self::MavenTaskUpdated => { + Self::SessionUpdated => { copy(&mut fields, "state", &input, "state"); - if matches!(self, Self::SessionUpdated) && input["state"] == "failed" { + if input["state"] == "failed" { id = identity.event("session.failed"); fields.insert("code".into(), json!(code)); } } - Self::ConfigurationCleaned => { - fields.insert( - "removed".into(), - json!(input["removedKeys"].as_array().map_or(0, Vec::len)), - ); - } - Self::LegacyRemoved => { - fields.insert( - "removed_files".into(), - json!(input["removedFiles"].as_array().map_or(0, Vec::len)), - ); - fields.insert( - "state_reset".into(), - json!(input["stateReset"].as_bool().unwrap_or(false)), - ); - } - Self::MavenSettingsForwarded => { - fields.insert("reason".into(), json!(code)); - } - Self::MavenConfigurationUpdated => { - for (target, source) in [ - ("settings_changed", "settingsChanged"), - ("projects_reloaded", "projectsReloaded"), - ("profiles_updating", "profilesUpdating"), - ] { - copy(&mut fields, target, &input, source); - } - } - Self::MavenApplicationStarted => { - copy(&mut fields, "projects", &input, "projectCount"); - } - Self::MavenProjectFinished => { - fields.insert( - "project".into(), - json!(input["projectUri"].as_str().unwrap_or("")), - ); - fields.insert( - "outcome".into(), - json!(input["status"].as_str().unwrap_or("unknown")), - ); - if error.is_some() { - id = identity.event("maven.project_failed"); - failure(&mut fields, code); - } - } - Self::NavigationCacheHit - | Self::NavigationLimited - | Self::NavigationMarkerFailed - | Self::NavigationResolved => { - for name in [ - "document", - "document_version", - "duration_ms", - "tasks", - "limit", - "code_lenses", - "markers", - ] { - copy(&mut fields, name, &input, name); - } - if matches!(self, Self::NavigationMarkerFailed) { - failure(&mut fields, code); - } - } Self::ResponseSkipped => { // JSON-RPC response IDs are opaque upstream strings. Only numeric // IDs are useful safe tokens; never record an arbitrary string ID. @@ -373,65 +259,6 @@ impl EngineLog { fields.insert("request".into(), json!(request)); } } - Self::WorkspaceProgressReceived => { - // The upstream progress phase is free text. Keep the observation - // structured rather than persisting status, project, or artifact text. - fields.insert("phase".into(), json!("import")); - copy(&mut fields, "completed", &input, "progressPercent"); - if fields.contains_key("completed") { - fields.insert("total".into(), json!(100)); - } - } - Self::WorkspaceImportFinished => { - copy(&mut fields, "duration_ms", &input, "importMilliseconds"); - } - Self::WorkspaceStalled => { - fields.insert( - "duration_ms".into(), - json!(input["idleMilliseconds"].as_u64().unwrap_or(0)), - ); - } - Self::BuildWaiting => { - copy(&mut fields, "reason", &input, "reason"); - } - Self::BuildExecution => { - id = identity.event(if input["errorCode"].as_str().is_some() { - "build.execution.failed" - } else if input.get("outcome").is_some() { - "build.execution.finished" - } else { - "build.execution.started" - }); - if let Some(code) = input["errorCode"].as_str() { - failure(&mut fields, code); - } - if input.get("outcome").is_some() { - fields.insert( - "duration_ms".into(), - json!(input["elapsedMilliseconds"].as_u64().unwrap_or(0)), - ); - } - fields.insert( - "waiters".into(), - json!(input["waiterCount"].as_u64().unwrap_or(0)), - ); - for (target, source) in [ - ("waited_ms", "waitedMilliseconds"), - ("outcome", "outcome"), - ("marker_scope", "markerScope"), - ("builder_failed_earlier", "builderFailedEarlier"), - ] { - copy(&mut fields, target, &input, source); - } - if let Some(recovery) = input.get("recovery").filter(|v| !v.is_null()) { - fields.insert( - "recovery".into(), - json!(recovery - .as_bool() - .unwrap_or_else(|| recovery.as_str().is_some_and(|v| v != "none"))), - ); - } - } Self::Dropped => { fields.clear(); fields.insert("count".into(), input["count"].clone()); @@ -442,16 +269,6 @@ impl EngineLog { (id, fields) } - pub(super) fn maven_project_fact( - identity: &SessionLogIdentity, - result: &MavenProfileProjectResult, - ) -> (String, Fields) { - let input = json!({"projectUri": result.project_uri, "status": result.status}); - // State updates carry no duplicate error payload; the explicit issue event - // owns the failure boundary, while this entry describes the project state. - Self::MavenProjectFinished.fact(identity, &input, None) - } - pub(super) fn notification(method: &str, params: &Value) -> (Self, Value) { match method { "window/logMessage" | "window/showMessage" => { @@ -736,7 +553,13 @@ mod tests { #[test] fn roles_route_opaque_provider_ids_without_parsing_prefixes() { for (role, provider, subject, plugin, expected) in [ - (SessionRole::LanguageServer, "java", None, None, "lsp/java"), + ( + SessionRole::LanguageServer, + "tool-a", + None, + None, + "lsp/tool-a", + ), ( SessionRole::Vcs, "vcsProvider:any:thing", @@ -795,7 +618,7 @@ mod tests { SessionRole::Vcs, SessionRole::Backend, ] { - let identity = SessionLogIdentity::new(role, "java", Some("io.plugin"), Some("git")); + let identity = SessionLogIdentity::new(role, "tool-a", Some("io.plugin"), Some("git")); let (id, fields) = EngineLog::ProcessCleanupFailed.fact(&identity, &Value::Null, None); crate::diagnostics::catalog::validate_fields(&id, &fields).unwrap(); assert_eq!(fields["error_code"], "operation_failed"); diff --git a/rust/lithe-core/src/lsp/interface/engine_real_jdt_maven_provider_tests.rs b/rust/lithe-core/src/lsp/interface/engine_real_jdt_maven_provider_tests.rs deleted file mode 100644 index 8ba9c5af1c..0000000000 --- a/rust/lithe-core/src/lsp/interface/engine_real_jdt_maven_provider_tests.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! Opt-in Maven Provider -> JDT -> project JVM integration, with installed -//! resources kept read-only and both workspace sessions owned by the test. - -use super::*; -use sha2::{Digest, Sha256}; - -fn command(name: &str, payload: Value) -> Value { - let response: Value = serde_json::from_str(&crate::execute_json( - &json!({"id":"java-provider-integration", "command":name, "payload":payload}).to_string(), - )) - .expect("Core JSON response"); - assert_eq!(response["ok"], true, "{response}"); - assert_eq!(response["data"]["status"], "ok", "{response}"); - response["data"].clone() -} - -fn build_command(manifest: &Value, name: &str, request: Value) -> Value { - command( - name, - json!({"manifest":manifest,"buildSystemID":"maven","request":request}), - ) -} - -fn provider_request(engine: &LspEngine, session: &Arc, plan: &Value) -> Value { - let operation = engine.next_operation_id(); - session - .build_request( - BuildProviderRequest { - session_id: session.id.clone(), - operation_id: Some(operation.clone()), - method: plan["provider"]["method"] - .as_str() - .expect("provider method") - .into(), - params: plan["provider"]["params"].clone(), - timeout_milliseconds: Some(120_000), - }, - operation.clone(), - ) - .expect("Core should admit the selected Provider request"); - await_operation(session, &operation, Duration::from_secs(120)) - .unwrap_or_else(|error| panic!("Provider request failed: {error}"))["value"] - .clone() -} - -fn write(root: &Path, path: &str, content: &str) { - let file = root.join(path); - std::fs::create_dir_all(file.parent().expect("fixture parent")).expect("fixture directory"); - std::fs::write(file, content).expect("fixture contents"); -} - -/// A byte-sensitive inventory, unlike a size-only listing, also detects an -/// upstream process rewriting an installed file without changing its length. -fn inventory(root: &Path) -> BTreeMap { - installation_listing(root) - .into_keys() - .map(|relative| { - let path = root.join(&relative); - let digest = if path.is_symlink() { - format!( - "link:{:?}", - std::fs::read_link(path).expect("installed symlink") - ) - } else { - format!( - "{:x}", - Sha256::digest(std::fs::read(path).expect("installed file")) - ) - }; - (relative, digest) - }) - .collect() -} - -#[test] -fn real_provider_resources_survive_jdt_build_and_reach_the_project_jvm() { - // This is an explicit tool integration, never an installed-tools dependency - // of the ordinary unit lane. A missing requested tool fails, not skips. - let Some(package) = std::env::var_os("LITHE_JDTLS_SMOKE_MAVEN_PACKAGE") else { - return; - }; - let toolchain = real_jdt_toolchain().expect("select the packaged JDT and both JDKs"); - let package = PathBuf::from(package); - let maven = toolchain - .maven - .as_ref() - .expect("select Maven for the integration"); - let manifest: Value = serde_json::from_slice( - &std::fs::read(package.join("plugin.json")).expect("Maven manifest"), - ) - .expect("Maven manifest JSON"); - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("Unix time") - .as_nanos(); - let scratch = std::env::temp_dir().join(format!( - "lithe-java-provider-{}-{stamp}", - std::process::id() - )); - let engine = LspEngine::new(); - // Own the tree before the first fixture write, including partial setup. - let _scratch_cleanup = RealSmokeCleanup { - engine: &engine, - session_id: "not-started".into(), - root: scratch.clone(), - }; - let workspace = scratch.join("workspace"); - // Keep a nested reactor and a nonstandard source/resource layout. No host - // filename convention can manufacture these project/source-role facts. - write( - &workspace, - "nested/pom.xml", - r#"4.0.0 - smokereactor1pom - libraryapp - 88 - UTF-8"#, - ); - write( - &workspace, - "nested/library/pom.xml", - r#"4.0.0 - smokereactor1 - library"#, - ); - write(&workspace, "nested/library/src/main/java/demo/Library.java", - "package demo; public class Library { public static String value() { return \"library\"; } }"); - write( - &workspace, - "nested/app/pom.xml", - r#"4.0.0 - smokereactor1app - smokelibrary1 - inactive-sourcesinactive-checks - ${selected.sources}${selected.checks} - runtime inputstrue - test inputstrue - launchprovidersourceschecks"#, - ); - write( - &workspace, - "nested/app/sources/demo/Main.java", - r#"package demo; - public class Main { public static void main(String[] args) throws Exception { - java.util.Properties p = new java.util.Properties(); - try (java.io.InputStream input = Main.class.getResourceAsStream("/runtime.properties")) { p.load(input); } - System.out.println(p.getProperty("selected") + ":" + Library.value()); - } }"#, - ); - write( - &workspace, - "nested/app/checks/demo/TestMain.java", - r#"package demo; - public class TestMain { public static void main(String[] args) throws Exception { - java.util.Properties p = new java.util.Properties(); - try (java.io.InputStream input = TestMain.class.getResourceAsStream("/test.properties")) { p.load(input); } - System.out.println(p.getProperty("selected") + ":" + Library.value()); - } }"#, - ); - write( - &workspace, - "nested/app/runtime inputs/runtime.properties", - "selected=${selected.value}:initial", - ); - write( - &workspace, - "nested/app/test inputs/test.properties", - "selected=${selected.value}:test-initial", - ); - let workspace = workspace.canonicalize().expect("canonical workspace"); - let root_uri = url::Url::from_directory_path(&workspace) - .expect("workspace URI") - .to_string(); - let before_package = inventory(&package); - let before_jdt = inventory(&toolchain.root); - let mut provider_start = real_start_request(&toolchain, &scratch, &workspace, &root_uri); - provider_start.provider_id = "test.maven".into(); - provider_start.executable_path = toolchain - .project_jdk - .join("bin") - .join(if cfg!(windows) { "java.exe" } else { "java" }) - .to_string_lossy() - .into(); - provider_start.arguments = vec![ - "-jar".into(), - package - .join("lib/lithe-maven-backend.jar") - .to_string_lossy() - .into(), - "--state".into(), - scratch.join("provider-state").to_string_lossy().into(), - ]; - provider_start.environment.insert( - "JAVA_HOME".into(), - toolchain.project_jdk.to_string_lossy().into(), - ); - provider_start.runtime_executable_path = None; - provider_start.jdtls_launch_resources = None; - provider_start.java_runtimes.clear(); - let started = engine - .start_server(provider_start) - .expect("start the real Maven Provider"); - let _provider_cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root: scratch.join("provider-state"), - }; - let provider = engine - .session(&started.session_id) - .expect("Provider session"); - await_real_smoke_ready(&provider).unwrap_or_else(|error| panic!("{error}")); - let options = json!({"profiles":["launch"]}); - let base = json!({"root":"nested","options":options,"pluginDirectory":package, - "workspaceStateDirectory":scratch.join("provider-state"),"tool":{"executable":maven, - "environment":{"JAVA_HOME":toolchain.project_jdk}}}); - let model_plan = build_command(&manifest, "build.modelPlan", base.clone()); - let raw = provider_request(&engine, &provider, &model_plan["plan"]); - let model = build_command( - &manifest, - "build.decodeModel", - json!({"workspaceRoot":workspace,"root":"nested","options":options,"result":raw}), - )["model"] - .clone(); - let project = model["projects"] - .as_array() - .expect("projects") - .iter() - .find(|p| p["name"] == "app") - .expect("app project"); - assert!( - model["contentRoots"] - .as_array() - .expect("source roles") - .iter() - .any(|r| r["path"] == "nested/app/checks" && r["kind"] == "testSource"), - "{model}" - ); - let import = build_command( - &manifest, - "build.languageImport", - json!({"workspaceRoot":workspace,"root":"nested","options":options,"executablePath":maven}), - ); - let mut java_start = real_start_request(&toolchain, &scratch, &workspace, &root_uri); - let requested_import: crate::project::MavenLaunchContextRequest = - serde_json::from_value(import["languageImport"]["mavenContext"].clone()) - .expect("public language import"); - let mut initial_import = requested_import.clone(); - initial_import.profiles.clear(); - java_start.maven_context = Some(initial_import); - let release = std::fs::read_to_string(toolchain.project_jdk.join("release")) - .expect("project JDK release"); - java_start.java_runtimes[0].version = - crate::execution::java_feature_version_from_release(&release) - .expect("JDK feature") - .to_string(); - let started = engine.start_server(java_start).expect("start packaged JDT"); - let _jdt_cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root: scratch.join("cache"), - }; - let jdt = engine.session(&started.session_id).expect("JDT session"); - await_real_smoke_ready(&jdt).unwrap_or_else(|error| panic!("{error}")); - // Start with a different profile whose source roots contain no entry points. - // A single immediate query after the hot update must await the new model; - // retrying an empty answer would conceal discovery/configuration races. - jdt.update_maven_configuration(requested_import, false) - .expect("apply the prepared Provider import"); - let entries = - request_real_entrypoints(&engine, &jdt).expect("discover after the profile update"); - assert_eq!( - entries["entries"].as_array().map(Vec::len), - Some(2), - "{entries}" - ); - // Change resources after import: startup copying cannot make the test pass. - write( - &workspace, - "nested/app/runtime inputs/runtime.properties", - "selected=${selected.value}:changed", - ); - write( - &workspace, - "nested/app/test inputs/test.properties", - "selected=${selected.value}:test-changed", - ); - for (class, role, expected) in [ - ("demo.Main", "source", "provider:changed:library"), - ( - "demo.TestMain", - "testSource", - "provider:test-changed:library", - ), - ] { - let tasks = manifest["buildSystems"][0]["tasks"] - .as_array() - .expect("tasks"); - let declared: Vec<_> = tasks - .iter() - .filter(|task| { - task["preparation"]["purpose"] == "run" - && task["preparation"]["sourceRoles"] - .as_array() - .is_some_and(|roles| roles.iter().any(|value| value == role)) - }) - .collect(); - assert_eq!(declared.len(), 1, "one declared preparation for {role}"); - let mut request = base.clone(); - request["task"] = declared[0]["id"].clone(); - request["project"] = project.clone(); - let plan = build_command(&manifest, "build.taskPlan", request); - let result = provider_request(&engine, &provider, &plan["plan"]); - assert_eq!(result["exitCode"], 0, "{result}"); - let entry = entries["entries"] - .as_array() - .expect("entry points") - .iter() - .find(|e| e["mainClass"] == class) - .expect("exact JDT entry"); - let built = execute_real_command(&engine, &jdt, json!({"command":"vscode.java.buildWorkspace","arguments":[json!({ - "mainClass":class,"projectName":entry["projectName"],"filePath":workspace.join(entry["sourcePath"].as_str().expect("source")),"isFullBuild":false}).to_string()]}), Duration::from_secs(120)) - .unwrap_or_else(|error| panic!("JDT build failed: {error}")); - assert_eq!(built["value"], 1, "{built}"); - let paths = execute_real_command(&engine, &jdt, json!({"command":"vscode.java.resolveClasspath","arguments":[class,entry["projectName"]]}), Duration::from_secs(60)) - .unwrap_or_else(|error| panic!("JDT paths failed: {error}")); - let classpath = paths["value"][1] - .as_array() - .expect("JDT classpaths") - .iter() - .map(|p| p.as_str().expect("classpath")) - .collect::>() - .join(if cfg!(windows) { ";" } else { ":" }); - let mut launch = - std::process::Command::new(toolchain.project_jdk.join("bin").join(if cfg!(windows) { - "java.exe" - } else { - "java" - })); - launch - .args(["-cp", &classpath, class]) - .current_dir(&workspace); - let deadline = Instant::now() + Duration::from_secs(15); - let output = lithe_git_host::run( - &mut launch, - None, - || Instant::now() >= deadline, - || {}, - |_, _| {}, - ); - assert!( - output.failure.is_none() && output.status.is_some_and(|s| s.success()), - "JVM failed: {:?} {}", - output.failure, - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected); - } - drop(_jdt_cleanup); - drop(_provider_cleanup); - assert_eq!( - inventory(&package), - before_package, - "Maven plugin package changed" - ); - assert_eq!( - inventory(&toolchain.root), - before_jdt, - "JDT installation changed" - ); -} 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 deleted file mode 100644 index 1dedf37c4e..0000000000 --- a/rust/lithe-core/src/lsp/interface/engine_real_jdt_tests.rs +++ /dev/null @@ -1,972 +0,0 @@ -//! Opt-in end-to-end checks against a real, packaged JDT LS. -//! -//! They run only when `LITHE_JDTLS_SMOKE_ROOT` names a directory prepared by -//! `scripts/macos/prepare/prepare-jdtls.sh` or -//! `scripts/windows/prepare/prepare-jdtls.ps1`, `LITHE_JDTLS_SMOKE_JAVA` names the Java -//! executable that runs JDT LS, and `LITHE_JDTLS_SMOKE_PROJECT_JDK` names a -//! JDK 25 home for the fixture project. Optional `LITHE_JDTLS_SMOKE_MAVEN` -//! names Maven so the discovered composed and inherited tests are also run. -//! They launch JDT LS exactly as the -//! product does (direct Java launch with the Debug and Test bundles) so that a -//! toolchain upgrade that breaks discovery, building, or launching fails here. - -use super::tests::{await_real_smoke_ready, RealSmokeCleanup}; -use super::*; - -#[path = "engine_real_jdt_maven_provider_tests.rs"] -mod maven_provider_tests; - -/// Paths an opt-in real JDT LS check needs, or `None` when not configured. -struct RealJdtToolchain { - root: PathBuf, - java: String, - project_jdk: PathBuf, - maven: Option, -} - -fn real_jdt_toolchain() -> Option { - let root = std::env::var_os("LITHE_JDTLS_SMOKE_ROOT")?; - let java = std::env::var("LITHE_JDTLS_SMOKE_JAVA") - .expect("LITHE_JDTLS_SMOKE_JAVA must accompany LITHE_JDTLS_SMOKE_ROOT"); - let project_jdk = std::env::var_os("LITHE_JDTLS_SMOKE_PROJECT_JDK") - .expect("LITHE_JDTLS_SMOKE_PROJECT_JDK must accompany LITHE_JDTLS_SMOKE_ROOT"); - let maven = std::env::var("LITHE_JDTLS_SMOKE_MAVEN").ok(); - Some(RealJdtToolchain { - root: PathBuf::from(root), - java, - project_jdk: PathBuf::from(project_jdk), - maven, - }) -} - -/// Size of every file below a JDT LS installation, keyed by relative path. -/// Symbolic links are recorded without being followed. -fn installation_listing(root: &Path) -> BTreeMap { - let mut listing = BTreeMap::new(); - let mut pending = vec![root.to_path_buf()]; - while let Some(directory) = pending.pop() { - for entry in std::fs::read_dir(&directory).expect("installation should be readable") { - let path = entry.expect("installation entry").path(); - let metadata = std::fs::symlink_metadata(&path).expect("installation metadata"); - if metadata.is_dir() { - pending.push(path); - } else { - let relative = path.strip_prefix(root).expect("entry inside root"); - listing.insert(relative.to_path_buf(), metadata.len()); - } - } - } - listing -} - -/// Direct-launch resources laid out by the prepare scripts. -fn packaged_launch_resources(root: &Path) -> JdtlsLaunchResources { - let plugins = std::fs::read_dir(root.join("plugins")).expect("JDTLS plugins directory"); - let mut launchers = plugins - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("org.eclipse.equinox.launcher_")) - }) - .collect::>(); - launchers.sort(); - let configuration = if cfg!(windows) { - "config_win" - } else if cfg!(target_os = "macos") { - if cfg!(target_arch = "aarch64") { - "config_mac_arm" - } else { - "config_mac" - } - } else { - "config_linux" - }; - let debug_bundle = std::fs::read_dir(root.join("java-debug")) - .expect("Java Debug directory") - .filter_map(Result::ok) - .map(|entry| entry.path()) - .find(|path| path.extension().is_some_and(|extension| extension == "jar")) - .expect("Java Debug bundle"); - let test_bundles = std::fs::read_to_string(root.join("java-test").join("extensions.txt")) - .expect("Java Test bundle list") - .lines() - .filter(|name| !name.trim().is_empty()) - .map(|name| { - root.join("java-test") - .join("extensions") - .join(name.trim()) - .to_string_lossy() - .into_owned() - }) - .collect::>(); - JdtlsLaunchResources { - launcher_jar_path: launchers - .first() - .expect("Equinox launcher") - .to_string_lossy() - .into_owned(), - configuration_directory: root.join(configuration).to_string_lossy().into_owned(), - lombok_agent_path: root - .join("lombok") - .join("lombok.jar") - .to_string_lossy() - .into_owned(), - java_debug_bundle_path: Some(debug_bundle.to_string_lossy().into_owned()), - java_extension_bundle_paths: test_bundles, - } -} - -/// Java 25 sources covering every entry-point form the JVM accepts, plus -/// declarations that only look like entry points. -const JAVA_25_ENTRYPOINT_SOURCES: &[(&str, &str)] = &[ - ( - "src/main/java/demo/ClassicMain.java", - "package demo;\npublic class ClassicMain { public static void main(String[] args) { System.out.println(\"classic\"); } }\n", - ), - ( - "src/main/java/demo/StaticNoArgs.java", - "package demo;\npublic class StaticNoArgs { static void main() { System.out.println(\"static-noargs\"); } }\n", - ), - ( - "src/main/java/demo/InstanceArgs.java", - "package demo;\npublic class InstanceArgs { void main(String[] args) { System.out.println(\"instance-args\"); } }\n", - ), - ( - "src/main/java/demo/InstanceNoArgs.java", - "package demo;\npublic class InstanceNoArgs { void main() { System.out.println(\"instance-noargs\"); } }\n", - ), - ( - "src/main/java/Compact.java", - "void main() {\n IO.println(\"compact\");\n}\n", - ), - ( - "src/main/java/demo/PrivateMain.java", - "package demo;\npublic class PrivateMain { private static void main(String[] args) { } }\n", - ), - ( - "src/main/java/demo/NotRunnable.java", - "package demo;\npublic class NotRunnable { public static int main(String[] args) { return 0; } }\n", - ), - ( - "src/main/java/demo/Samples.java", - "package demo;\nclass Samples { String sample = \"public static void main(String[] args) {}\"; }\n", - ), -]; - -/// Test sources whose membership cannot be decided by file names or direct -/// annotations alone. Java Test/JDT must resolve the composed annotation and -/// inherited method. -const JAVA_TEST_SOURCES: &[(&str, &str)] = &[ - ( - "src/test/java/MainTests.java", - "public class MainTests { public static void main(String[] args) { org.junit.jupiter.api.Assertions.assertTrue(true); System.out.println(\"test-main\"); } }\n", - ), - ( - "src/test/java/demo/FastTest.java", - "package demo;\nimport java.lang.annotation.*;\nimport org.junit.jupiter.api.Test;\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.METHOD)\n@Test\npublic @interface FastTest {}\n", - ), - ( - "src/test/java/demo/OddlyNamedSpec.java", - "package demo;\nimport java.nio.file.*;\nclass OddlyNamedSpec {\n @FastTest void composedAnnotation() throws Exception { Files.writeString(Path.of(\"target/composed-ran\"), \"yes\"); }\n}\n", - ), - ( - "src/test/java/demo/BaseBehavior.java", - "package demo;\nimport java.nio.file.*;\nimport org.junit.jupiter.api.Test;\nclass BaseBehavior {\n @Test void inheritedBehavior() throws Exception { Files.writeString(Path.of(\"target/inherited-ran\"), \"yes\"); }\n}\n", - ), - ( - "src/test/java/demo/InheritedSuite.java", - "package demo;\nclass InheritedSuite extends BaseBehavior {}\n", - ), -]; - -const JAVA_25_POM: &str = r#" - 4.0.0 - smoke - java25-entrypoints - 1.0.0 - - 25 - UTF-8 - - - - org.junit.jupiter - junit-jupiter - 5.14.0 - test - - - - ${project.basedir}/target/test-main-output - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.4 - - - - -"#; - -/// Sends one `workspace/executeCommand` and waits for its result event. -fn execute_real_command( - engine: &LspEngine, - session: &Arc, - command: Value, - timeout: Duration, -) -> Result { - let operation_id = engine.next_operation_id(); - session - .request( - SemanticRequest { - session_id: session.id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::ExecuteCommand, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: Some(command.clone()), - }, - operation_id.clone(), - ) - .map_err(|error| error.message)?; - await_operation(session, &operation_id, timeout).map_err(|error| format!("{command}: {error}")) -} - -fn await_operation( - session: &Arc, - operation_id: &str, - timeout: Duration, -) -> Result { - let deadline = Instant::now() + timeout; - loop { - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - return Err(format!("timed out after {timeout:?}")); - } - // Blocks until the engine publishes events rather than sleeping. - for event in session - .wait_events(remaining) - .map_err(|error| error.message)? - { - if event.operation_id.as_deref() != Some(operation_id) - || event.kind != "requestCompleted" - { - continue; - } - if let Some(error) = event.error { - return Err(format!("{error:?}")); - } - return Ok(event.result.unwrap_or(Value::Null)); - } - } -} - -fn request_real_entrypoints( - engine: &LspEngine, - session: &Arc, -) -> Result { - let operation_id = engine.next_operation_id(); - session - .request( - SemanticRequest { - session_id: session.id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaEntrypoints, - uri: None, - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .map_err(|error| error.message)?; - await_operation(session, &operation_id, Duration::from_secs(60)) -} - -fn request_real_test_items( - engine: &LspEngine, - session: &Arc, - uri: String, -) -> Result { - let operation_id = engine.next_operation_id(); - session - .request( - SemanticRequest { - session_id: session.id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaTestItems, - uri: Some(uri), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .map_err(|error| error.message)?; - await_operation(session, &operation_id, Duration::from_secs(60)) -} - -/// Launches JDT LS for `workspace` the way the product does, keeping every -/// cache below `root`. -fn real_start_request( - toolchain: &RealJdtToolchain, - root: &Path, - workspace: &Path, - root_uri: &str, -) -> StartServerRequest { - let java_home = PathBuf::from(&toolchain.java) - .parent() - .and_then(Path::parent) - .expect("JDT LS Java should be inside a JDK bin directory") - .to_path_buf(); - StartServerRequest { - provider_id: "java".to_string(), - role: SessionRole::LanguageServer, - log_subject: None, - plugin_id: None, - startup_operation: None, - host_services: Vec::new(), - host_options: Default::default(), - toolchain_providers: Vec::new(), - keymap_import_providers: Vec::new(), - session_policy: None, - executable_path: toolchain - .root - .join("bin") - .join("jdtls") - .to_string_lossy() - .into_owned(), - arguments: Vec::new(), - environment: BTreeMap::from([( - "JAVA_HOME".to_string(), - java_home.to_string_lossy().into_owned(), - )]), - root_uri: root_uri.to_string(), - working_directory: workspace.to_string_lossy().into_owned(), - initialization_options: None, - workspace_configuration: None, - runtime_executable_path: Some(toolchain.java.clone()), - jdtls_launch_resources: Some(packaged_launch_resources(&toolchain.root)), - cache_directory: Some(root.join("cache").to_string_lossy().into_owned()), - workspace_fingerprint: None, - maven_context: None, - // The project compiles for release 25 while JDT LS itself runs on - // an older JDK, as in the product. - java_runtimes: vec![JavaRuntimeCandidate { - is_default: true, - home_path: toolchain.project_jdk.to_string_lossy().into_owned(), - version: "25".to_string(), - }], - java_gradle: None, - initialize_timeout_milliseconds: 90_000, - service_ready_idle_timeout_milliseconds: 45_000, - service_ready_absolute_timeout_milliseconds: 600_000, - request_timeout_milliseconds: 60_000, - java_build_timeout_milliseconds: DEFAULT_JAVA_BUILD_TIMEOUT_MS, - shutdown_timeout_milliseconds: 10_000, - } -} - -/// Asks for entry points until JDT, which can finish importing shortly after -/// it reports ready, lists at least `minimum` of them. -fn await_real_entrypoints( - engine: &LspEngine, - session: &Arc, - minimum: usize, -) -> Value { - let import_deadline = Instant::now() + Duration::from_secs(120); - loop { - let result = request_real_entrypoints(engine, session) - .unwrap_or_else(|error| panic!("entry-point discovery failed: {error}")); - if result["entries"] - .as_array() - .is_some_and(|entries| entries.len() >= minimum) - { - return result; - } - assert!( - Instant::now() < import_deadline, - "JDT did not report the fixture entry points: {result}" - ); - // Import progress arrives as events; wait for the next one instead of - // sleeping, bounded so a silent server still reaches the deadline. - session - .wait_events( - import_deadline - .saturating_duration_since(Instant::now()) - .min(Duration::from_secs(5)), - ) - .expect("JDT events should be readable"); - } -} - -#[test] -fn real_jdtls_discovers_builds_and_launches_java_25_entrypoints() { - let Some(toolchain) = real_jdt_toolchain() else { - return; - }; - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-real-jdt-entrypoints-{}-{stamp}", - std::process::id() - )); - let workspace = root.join("workspace"); - for (relative, source) in JAVA_25_ENTRYPOINT_SOURCES { - let path = workspace.join(relative); - std::fs::create_dir_all(path.parent().expect("source parent")) - .expect("fixture source directory"); - std::fs::write(&path, source).expect("fixture source"); - } - for (relative, source) in JAVA_TEST_SOURCES { - let path = workspace.join(relative); - std::fs::create_dir_all(path.parent().expect("test source parent")) - .expect("fixture test source directory"); - std::fs::write(&path, source).expect("fixture test source"); - } - std::fs::write(workspace.join("pom.xml"), JAVA_25_POM).expect("fixture pom"); - let canonical_workspace = workspace.canonicalize().expect("workspace canonicalizes"); - let root_uri = url::Url::from_directory_path(&canonical_workspace) - .expect("workspace converts to a file URI") - .to_string(); - let installation_before = installation_listing(&toolchain.root); - - let engine = LspEngine::new(); - let started = engine - .start_server(real_start_request(&toolchain, &root, &workspace, &root_uri)) - .expect("real JDTLS should start"); - let _cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root: root.clone(), - }; - let session = engine - .session(&started.session_id) - .expect("real JDTLS session should be registered"); - await_real_smoke_ready(&session).unwrap_or_else(|error| panic!("{error}")); - - let entrypoints = await_real_entrypoints(&engine, &session, 6); - let discovered = entrypoints["entries"] - .as_array() - .expect("entries array") - .iter() - .map(|entry| { - ( - entry["mainClass"].as_str().unwrap_or_default().to_string(), - entry["sourcePath"].as_str().unwrap_or_default().to_string(), - ) - }) - .collect::>(); - assert_eq!( - discovered, - vec![ - ( - "Compact".to_string(), - "src/main/java/Compact.java".to_string() - ), - ( - "demo.ClassicMain".to_string(), - "src/main/java/demo/ClassicMain.java".to_string() - ), - ( - "demo.InstanceArgs".to_string(), - "src/main/java/demo/InstanceArgs.java".to_string() - ), - ( - "demo.InstanceNoArgs".to_string(), - "src/main/java/demo/InstanceNoArgs.java".to_string() - ), - ( - "demo.StaticNoArgs".to_string(), - "src/main/java/demo/StaticNoArgs.java".to_string() - ), - ( - "MainTests".to_string(), - "src/test/java/MainTests.java".to_string() - ), - ], - "JDT should list exactly the launchable forms: {entrypoints}" - ); - - // Editor Run markers ask the same JDT service per file. The Java 25 - // instance form must carry a marker on its `main` line, while a private - // `main` the JVM cannot launch must not. - let main_methods_for = |relative: &str| { - let uri = url::Url::from_file_path(canonical_workspace.join(relative)) - .expect("fixture file converts to a URI") - .to_string(); - let operation_id = engine.next_operation_id(); - session - .request( - SemanticRequest { - session_id: session.id.clone(), - operation_id: Some(operation_id.clone()), - operation: LspSemanticOperation::JavaMainMethods, - uri: Some(uri), - virtual_uri: None, - position: None, - new_name: None, - range: None, - diagnostics: Vec::new(), - completion_context: None, - completion_item: None, - code_action: None, - command: None, - }, - operation_id.clone(), - ) - .expect("main-method request is accepted"); - await_operation(&session, &operation_id, Duration::from_secs(60)) - .expect("JDT answers main-method discovery") - }; - let instance = main_methods_for("src/main/java/demo/InstanceArgs.java"); - assert_eq!( - instance["methods"][0]["mainClass"], - json!("demo.InstanceArgs"), - "{instance}" - ); - assert_eq!( - instance["methods"][0]["range"]["startLine"], - json!(1), - "{instance}" - ); - let private = main_methods_for("src/main/java/demo/PrivateMain.java"); - assert_eq!(private["methods"], json!([]), "{private}"); - - // Issue #769's form must also build and run, which requires JDT LS to - // compile against the project's JDK 25 rather than its own runtime. - let project_name = entrypoints["entries"] - .as_array() - .and_then(|entries| { - entries - .iter() - .find(|entry| entry["mainClass"] == "demo.StaticNoArgs") - }) - .and_then(|entry| entry["projectName"].as_str()) - .expect("the #769 entry should name its JDT project") - .to_string(); - let build = execute_real_command( - &engine, - &session, - json!({ - "command": "vscode.java.buildWorkspace", - "arguments": [json!({ - "mainClass": "demo.StaticNoArgs", - "projectName": project_name, - "filePath": canonical_workspace - .join("src/main/java/demo/StaticNoArgs.java") - .to_string_lossy(), - "isFullBuild": false - }).to_string()] - }), - Duration::from_secs(300), - ) - .unwrap_or_else(|error| panic!("the Java 25 project should build: {error}")); - assert_eq!(build["value"], json!(1), "unexpected build result: {build}"); - let paths = execute_real_command( - &engine, - &session, - json!({ - "command": "vscode.java.resolveClasspath", - "arguments": ["demo.StaticNoArgs", project_name] - }), - Duration::from_secs(60), - ) - .unwrap_or_else(|error| panic!("the runtime classpath should resolve: {error}")); - // Issue #379: scope omission must keep production launches free of test - // output, while a default-package test Main gets custom output and test-only - // dependencies from m2e/JDT instead of a guessed target/test-classes path. - let test_paths = execute_real_command( - &engine, - &session, - json!({ - "command": "vscode.java.resolveClasspath", - "arguments": ["MainTests", project_name] - }), - Duration::from_secs(60), - ) - .unwrap_or_else(|error| panic!("the test Main classpath should resolve: {error}")); - let test_entries = test_paths["value"][1].as_array().expect("test classpaths"); - let has_test_output = |entries: &[Value]| { - entries.iter().any(|entry| { - entry.as_str().is_some_and(|path| { - path.replace('\\', "/") - .ends_with("/target/test-main-output") - }) - }) - }; - assert!(has_test_output(test_entries), "{test_paths}"); - assert!( - test_entries.iter().any(|entry| entry - .as_str() - .is_some_and(|path| path.contains("junit-jupiter-api"))), - "{test_paths}" - ); - assert!( - !has_test_output(paths["value"][1].as_array().expect("main classpaths")), - "{paths}" - ); - assert!( - canonical_workspace - .join("target/test-main-output/MainTests.class") - .is_file(), - "the test Main should have been compiled" - ); - // `resolveClasspath` answers `[modulePaths, classPaths]`. - let class_path = paths["value"][1] - .as_array() - .map(|entries| { - entries - .iter() - .filter_map(Value::as_str) - .collect::>() - .join(if cfg!(windows) { ";" } else { ":" }) - }) - .filter(|class_path| !class_path.is_empty()) - .unwrap_or_else(|| panic!("no runtime classpath in {paths}")); - let executable = - toolchain - .project_jdk - .join("bin") - .join(if cfg!(windows) { "java.exe" } else { "java" }); - let test_class_path = test_entries - .iter() - .filter_map(Value::as_str) - .collect::>() - .join(if cfg!(windows) { ";" } else { ":" }); - for (main_class, paths, expected_output) in [ - ("demo.StaticNoArgs", class_path.as_str(), "static-noargs"), - ("MainTests", test_class_path.as_str(), "test-main"), - ] { - let output = std::process::Command::new(&executable) - .arg("-cp") - .arg(paths) - .arg(main_class) - .output() - .expect("the project JDK should start"); - assert!( - output.status.success(), - "{main_class} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!( - String::from_utf8_lossy(&output.stdout).trim(), - expected_output - ); - } - - // No local annotation or file-name rule can produce these answers: JDT - // resolves the custom meta-annotation and the inherited JUnit method. - for (relative, expected_class, expected_method) in [ - ( - "src/test/java/demo/OddlyNamedSpec.java", - "demo.OddlyNamedSpec", - Some("demo.OddlyNamedSpec#composedAnnotation()"), - ), - ( - "src/test/java/demo/InheritedSuite.java", - "demo.InheritedSuite", - None, - ), - ] { - let uri = url::Url::from_file_path(canonical_workspace.join(relative)) - .expect("test source converts to a file URI") - .to_string(); - let result = request_real_test_items(&engine, &session, uri) - .unwrap_or_else(|error| panic!("test discovery failed for {relative}: {error}")); - let classes = result["items"] - .as_array() - .unwrap_or_else(|| panic!("Java Test returned no item list for {relative}: {result}")); - let class = classes - .iter() - .find(|item| item["fullName"] == expected_class) - .unwrap_or_else(|| panic!("Java Test did not find {expected_class}: {result}")); - if let Some(expected_method) = expected_method { - let method = class["children"] - .as_array() - .and_then(|children| { - children - .iter() - .find(|item| item["fullName"] == expected_method) - }) - .unwrap_or_else(|| { - panic!("Java Test did not resolve the composed annotation: {result}") - }); - let range = &method["range"]; - assert!( - range["startLine"].as_i64().is_some_and(|line| line >= 0) - && range["startUtf16Column"] - .as_i64() - .is_some_and(|column| column >= 0) - && range["endLine"].as_i64().is_some_and(|line| line >= 0) - && range["endUtf16Column"] - .as_i64() - .is_some_and(|column| column >= 0), - "Java Test returned no usable method range: {result}" - ); - } - } - - // The packaged installation is the release baseline for delta updates: - // after import, build, and classpath resolution JDT LS must not have - // added, removed, or resized a single file in it. Equinox's framework - // state has to be in the cache's configuration area instead. - assert_eq!(installation_listing(&toolchain.root), installation_before); - let configuration_areas = std::fs::read_dir(root.join("cache").join("jdtls-configuration")) - .expect("the cache should hold the Equinox configuration area") - .filter_map(Result::ok) - .map(|entry| entry.path().join("configuration")) - .collect::>(); - assert!( - configuration_areas - .iter() - .any(|area| area.join("org.eclipse.osgi").is_dir()), - "Equinox did not write its state to the cache: {configuration_areas:?}" - ); - - let Some(maven_executable) = toolchain.maven.as_deref() else { - return; - }; - let mut maven = std::process::Command::new(maven_executable); - maven - .current_dir(&canonical_workspace) - .env("JAVA_HOME", &toolchain.project_jdk) - .args([ - "--batch-mode", - "--no-transfer-progress", - "-Dtest=OddlyNamedSpec,InheritedSuite", - "test", - ]); - let test_output = maven.output().expect("Maven should start"); - assert!( - test_output.status.success(), - "discovered Java tests failed:\n{}\n{}", - String::from_utf8_lossy(&test_output.stdout), - String::from_utf8_lossy(&test_output.stderr) - ); - assert!( - canonical_workspace.join("target/composed-ran").is_file(), - "the custom composed-annotation test did not run" - ); - assert!( - canonical_workspace.join("target/inherited-ran").is_file(), - "the inherited test did not run" - ); -} - -/// A plain folder becomes an invisible JDT project in its writable cache. -/// The Java Debug Server's path-scoped search omits that project, so discovery -/// must include its entries before Core applies workspace ownership checks. -#[test] -fn real_jdtls_lists_entrypoints_in_a_plain_java_folder() { - let Some(toolchain) = real_jdt_toolchain() else { - return; - }; - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-real-jdt-plain-{}-{stamp}", - std::process::id() - )); - let workspace = root.join("plain workspace"); - let source = "src/Main.java"; - std::fs::create_dir_all(workspace.join("src")).expect("fixture source directory"); - let text = "public class Main { public static void main(String[] args) { } }\n"; - std::fs::write(workspace.join(source), text).expect("fixture source"); - let root_uri = url::Url::from_directory_path(&workspace) - .expect("workspace converts to a file URI") - .to_string(); - let installation_before = installation_listing(&toolchain.root); - let engine = LspEngine::new(); - let mut request = real_start_request(&toolchain, &root, &workspace, &root_uri); - // This classic main needs no Java 25 features; use JDT's runtime JDK. - request.java_runtimes.clear(); - let started = engine - .start_server(request) - .expect("real JDTLS should start"); - let _cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root, - }; - let session = engine - .session(&started.session_id) - .expect("real JDTLS session should be registered"); - await_real_smoke_ready(&session).unwrap_or_else(|error| panic!("{error}")); - session - .sync_document(SyncDocumentRequest { - session_id: session.id.clone(), - uri: url::Url::from_file_path(workspace.join(source)) - .expect("source converts to a file URI") - .to_string(), - language_id: "java".to_string(), - text: text.to_string(), - content_changes: Vec::new(), - }) - .expect("plain source should open"); - let entrypoints = await_real_entrypoints(&engine, &session, 1); - let entries = entrypoints["entries"].as_array().expect("entry list"); - assert_eq!(entries.len(), 1, "{entrypoints}"); - assert_eq!(entries[0]["sourcePath"], source, "{entrypoints}"); - assert_eq!(entries[0]["mainClass"], "Main", "{entrypoints}"); - assert!(entries[0]["projectName"].is_string(), "{entrypoints}"); - assert_eq!(entrypoints["diagnostics"], json!([]), "{entrypoints}"); - assert_eq!(installation_listing(&toolchain.root), installation_before); -} - -/// Regression for a workspace opened through a symbolic link, which is how -/// macOS exposes `/tmp` and `/var`. JDT imports the project at its resolved -/// location, so an entry-point scope naming the link matched no project and -/// Run reported that the open file had no `main` method. -#[cfg(unix)] -#[test] -fn real_jdtls_lists_entrypoints_and_classpaths_behind_a_symbolic_link() { - let Some(toolchain) = real_jdt_toolchain() else { - return; - }; - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should follow the Unix epoch") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-real-jdt-symlink-{}-{stamp}", - std::process::id() - )); - let resolved_workspace = root.join("resolved"); - let source = "src/main/java/demo/ClassicMain.java"; - let source_path = resolved_workspace.join(source); - std::fs::create_dir_all(source_path.parent().expect("source parent")) - .expect("fixture source directory"); - std::fs::write( - &source_path, - "package demo;\npublic class ClassicMain { public static void main(String[] args) { } }\n", - ) - .expect("fixture source"); - std::fs::write(resolved_workspace.join("pom.xml"), JAVA_25_POM).expect("fixture pom"); - let workspace = root.join("link"); - std::os::unix::fs::symlink(&resolved_workspace, &workspace).expect("workspace link"); - let root_uri = url::Url::from_directory_path(&workspace) - .expect("workspace converts to a file URI") - .to_string(); - - let engine = LspEngine::new(); - let started = engine - .start_server(real_start_request(&toolchain, &root, &workspace, &root_uri)) - .expect("real JDTLS should start"); - let _cleanup = RealSmokeCleanup { - engine: &engine, - session_id: started.session_id.clone(), - root: root.clone(), - }; - let session = engine - .session(&started.session_id) - .expect("real JDTLS session should be registered"); - await_real_smoke_ready(&session).unwrap_or_else(|error| panic!("{error}")); - - let entrypoints = await_real_entrypoints(&engine, &session, 1); - assert_eq!( - entrypoints["entries"][0]["sourcePath"], - json!(source), - "{entrypoints}" - ); - assert_eq!(entrypoints["diagnostics"], json!([]), "{entrypoints}"); - - // JDT publishes diagnostics under the resolved path; they must still reach - // the document the host opened through the link. - let opened_uri = url::Url::from_file_path(workspace.join(source)) - .expect("linked source converts to a file URI") - .to_string(); - session - .sync_document(SyncDocumentRequest { - session_id: session.id.clone(), - uri: opened_uri.clone(), - language_id: "java".to_string(), - text: "package demo;\npublic class ClassicMain { public static void main(String[] args) { String broken = 1; } }\n".to_string(), - content_changes: Vec::new(), - }) - .expect("the linked source should open"); - let diagnostics_deadline = Instant::now() + Duration::from_secs(60); - let reported = loop { - let remaining = diagnostics_deadline.saturating_duration_since(Instant::now()); - assert!( - !remaining.is_zero(), - "JDT diagnostics did not reach the document opened through the link" - ); - let events = session - .wait_events(remaining) - .expect("JDT events should be readable"); - if let Some(event) = events.into_iter().find(|event| { - event.kind == "diagnostics" - && event - .diagnostics - .as_ref() - .is_some_and(|list| !list.is_empty()) - }) { - break event; - } - }; - assert_eq!(reported.uri.as_deref(), Some(opened_uri.as_str())); - - // The dependency projection reads each project's runtime classpath. JDT LS - // deserializes the options from JSON text only; a JSON object leaves them - // null and the command fails inside the server. - let projects = execute_real_command( - &engine, - &session, - json!({ "command": "java.project.getAll", "arguments": [] }), - Duration::from_secs(60), - ) - .unwrap_or_else(|error| panic!("JDT should list its projects: {error}")); - let project_uri = projects["value"] - .as_array() - .and_then(|projects| { - projects - .iter() - .filter_map(Value::as_str) - .find(|uri| !uri.contains("jdt.ls-java-project")) - }) - .unwrap_or_else(|| panic!("no imported project in {projects}")) - .to_string(); - let classpaths = execute_real_command( - &engine, - &session, - json!({ - "command": "java.project.getClasspaths", - "arguments": [project_uri, json!({ "scope": "runtime" }).to_string()] - }), - Duration::from_secs(60), - ) - .unwrap_or_else(|error| panic!("the runtime classpath should resolve: {error}")); - assert!( - classpaths["value"]["classpaths"] - .as_array() - .is_some_and(|paths| !paths.is_empty()), - "no runtime classpath in {classpaths}" - ); -} diff --git a/rust/lithe-core/src/lsp/interface/mod.rs b/rust/lithe-core/src/lsp/interface/mod.rs index 60c798ddf2..e86822b393 100644 --- a/rust/lithe-core/src/lsp/interface/mod.rs +++ b/rust/lithe-core/src/lsp/interface/mod.rs @@ -22,10 +22,7 @@ mod types; mod vcs_provider; pub(crate) use client::*; -pub(crate) use document_uri::{ - document_uri_command, resolve_field as resolve_uri_field, resolve_request_paths, - DocumentPathPlatform, -}; +pub(crate) use document_uri::{document_uri_command, resolve_request_paths, DocumentPathPlatform}; pub(crate) use engine::*; pub(crate) use engine_logging::{resolve_engine_log_subject, ResolveEngineLogSubjectRequest}; pub(crate) use function_relay::RelaySnapshot; diff --git a/rust/lithe-core/src/lsp/interface/scripted.rs b/rust/lithe-core/src/lsp/interface/scripted.rs index d08c796262..4982c79dcb 100644 --- a/rust/lithe-core/src/lsp/interface/scripted.rs +++ b/rust/lithe-core/src/lsp/interface/scripted.rs @@ -41,7 +41,8 @@ struct ScriptedShared { /// Deterministic write barrier used by concurrency-ordering tests. input_pause: Mutex, input_pause_changed: Condvar, - spec: Mutex>, + /// Set once the engine asked the launcher for a process. + launched: AtomicBool, } #[derive(Default)] @@ -51,15 +52,6 @@ struct ScriptedInputPause { release_requested: bool, } -/// What the engine asked the launcher for, so tests can assert provider -/// adaptation without reaching into the JDT module. -#[derive(Clone)] -pub struct LaunchedSpec { - pub executable: String, - pub arguments: Vec, - pub working_directory: String, -} - impl ScriptedServer { pub fn new() -> Self { Self { @@ -74,7 +66,7 @@ impl ScriptedServer { cleanup_blocked: AtomicBool::new(false), input_pause: Mutex::new(ScriptedInputPause::default()), input_pause_changed: Condvar::new(), - spec: Mutex::new(None), + launched: AtomicBool::new(false), }), } } @@ -87,8 +79,9 @@ impl ScriptedServer { }) } - pub fn launched_spec(&self) -> Option { - self.shared.spec.lock().unwrap().clone() + /// Whether the engine launched the process at all. + pub fn was_launched(&self) -> bool { + self.shared.launched.load(Ordering::SeqCst) } /// Sends one framed JSON-RPC message to the engine. @@ -123,16 +116,6 @@ impl ScriptedServer { })); } - /// Completes both the standard handshake and JDT LS project-import phase. - pub fn complete_java_initialize(&self, capabilities: Value) { - self.complete_initialize(capabilities); - self.send(serde_json::json!({ - "jsonrpc": "2.0", - "method": "language/status", - "params": { "type": "ServiceReady" } - })); - } - /// Blocks until the engine has written a request for `method`, returning its /// JSON-RPC id. Polling the written bytes is what lets a test stay in step /// with the engine's reader and monitor threads without fixed sleeps. @@ -302,13 +285,6 @@ impl ScriptedServer { .unwrap(); !pause.blocked } - - /// Releases a paused engine write and disables the pause barrier. - pub fn resume_input(&self) { - let mut pause = self.shared.input_pause.lock().unwrap(); - pause.release_requested = true; - self.shared.input_pause_changed.notify_all(); - } } fn parse_messages(written: &[u8]) -> Vec { @@ -341,12 +317,8 @@ struct ScriptedLauncher { } impl LspProcessLauncher for ScriptedLauncher { - fn launch(&self, spec: LspProcessSpec) -> Result { - *self.shared.spec.lock().unwrap() = Some(LaunchedSpec { - executable: spec.executable.to_string_lossy().into_owned(), - arguments: spec.arguments.clone(), - working_directory: spec.working_directory.to_string_lossy().into_owned(), - }); + fn launch(&self, _spec: LspProcessSpec) -> Result { + self.shared.launched.store(true, Ordering::SeqCst); Ok(LspProcessStreams { handle: Arc::new(ScriptedProcess { shared: self.shared.clone(), diff --git a/rust/lithe-core/src/lsp/languages/java_entrypoints.rs b/rust/lithe-core/src/lsp/languages/java_entrypoints.rs deleted file mode 100644 index 6515ce9f64..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_entrypoints.rs +++ /dev/null @@ -1,406 +0,0 @@ -//! Normalizes JDT's Java entry-point discovery into Lithe's shared contract. -//! -//! JDT LS, through the Java Debug Server's `vscode.java.resolveMainClass`, -//! decides which classes the JVM can launch. The rules change with the Java -//! language (instance and no-argument `main` in Java 25, compact source files), -//! so this module never reads Java source to add, drop, or second-guess an -//! entry. It only turns JDT's answer into workspace-relative, deterministic -//! facts and reports what it could not accept. -//! -//! Note: entry-point ownership is recorded in .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md - -use crate::lsp::percent_decode; -use serde::Serialize; -use serde_json::{json, Value}; - -/// Java Debug Server command that lists launchable classes in a scope. -pub(crate) const JAVA_RESOLVE_MAIN_CLASS_COMMAND: &str = "vscode.java.resolveMainClass"; - -/// Version of the serialized [`JavaEntrypoints`] shape. -pub(crate) const JAVA_ENTRYPOINTS_SCHEMA_VERSION: u32 = 1; - -/// `workspace/executeCommand` params that discover the session's Java entries. -/// -/// The bundled Java Debug Server's path-scoped search excludes invisible -/// projects, whose location is JDT's cache rather than their linked workspace. -/// Its unscoped command includes these projects. The normalizer below still -/// restricts every returned source to the opened workspace or its resolved root. -pub(crate) fn java_entrypoints_command() -> Value { - json!({ - "command": JAVA_RESOLVE_MAIN_CLASS_COMMAND, - "arguments": [], - }) -} - -/// Launchable Java classes JDT reported for one workspace. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaEntrypoints { - pub schema_version: u32, - /// Entries ordered by `sourcePath`, then `mainClass`, without duplicates. - pub entries: Vec, - /// JDT results that could not become entries, in JDT's order. - pub diagnostics: Vec, -} - -/// One class JDT confirmed the JVM can launch. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaEntrypoint { - /// Workspace-relative path with `/` separators; the stable identity of the - /// entry, because two modules may declare the same class name. - pub source_path: String, - /// Class name as JDT reports it, including a `module/` prefix for modular - /// projects; it is passed back to JDT and the JVM unchanged. - pub main_class: String, - /// JDT project that owns the class. It only helps JDT resolve the launch - /// again and is not part of any stable identifier. - #[serde(skip_serializing_if = "Option::is_none")] - pub project_name: Option, -} - -/// A JDT result that was dropped, with the reason. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaEntrypointDiagnostic { - /// `missingMainClass`, `missingSourcePath`, or `outsideWorkspace`. - pub code: &'static str, - #[serde(skip_serializing_if = "Option::is_none")] - pub main_class: Option, - /// Platform-owned detail, such as the absolute path JDT returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub detail: Option, -} - -/// Converts a `resolveMainClass` result into [`JavaEntrypoints`]. -/// -/// `canonical_root` is the workspace directory with symbolic links resolved, -/// when the platform could resolve it. JDT may report either spelling — a -/// workspace opened through `/var` on macOS comes back under `/private/var` — -/// so a file inside either one is inside the workspace. -/// -/// Returns `None` when the result is not a list, which means the server -/// answered something other than this command's contract. -pub(crate) fn normalize_java_entrypoints( - root_uri: &str, - canonical_root: Option<&str>, - result: &Value, -) -> Option { - let candidates = result.as_array()?; - let roots = workspace_root_path(root_uri) - .into_iter() - .chain(canonical_root.map(|root| root.replace('\\', "/").trim_end_matches('/').to_string())) - .collect::>(); - let mut entries = Vec::new(); - let mut diagnostics = Vec::new(); - for candidate in candidates { - let main_class = candidate - .get("mainClass") - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()); - let Some(main_class) = main_class else { - diagnostics.push(JavaEntrypointDiagnostic { - code: "missingMainClass", - main_class: None, - detail: None, - }); - continue; - }; - // A pathless entry cannot be told apart from a same-named class in - // another module, so it is reported instead of guessed at. - let Some(file_path) = candidate - .get("filePath") - .and_then(Value::as_str) - .filter(|value| !value.trim().is_empty()) - else { - diagnostics.push(JavaEntrypointDiagnostic { - code: "missingSourcePath", - main_class: Some(main_class.to_string()), - detail: None, - }); - continue; - }; - let Some(source_path) = roots - .iter() - .find_map(|root| workspace_relative_path(root, file_path)) - else { - diagnostics.push(JavaEntrypointDiagnostic { - code: "outsideWorkspace", - main_class: Some(main_class.to_string()), - detail: Some(file_path.to_string()), - }); - continue; - }; - let project_name = candidate - .get("projectName") - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string); - entries.push(JavaEntrypoint { - source_path, - main_class: main_class.to_string(), - project_name, - }); - } - entries.sort(); - entries.dedup(); - Some(JavaEntrypoints { - schema_version: JAVA_ENTRYPOINTS_SCHEMA_VERSION, - entries, - diagnostics, - }) -} - -/// Decodes a `file:` workspace URI into a `/`-separated absolute path. -/// -/// This is done textually rather than through the host OS so that a Windows -/// URI such as `file:///c%3A/work` normalizes identically on every platform. -pub(crate) fn workspace_root_path(root_uri: &str) -> Option { - let url = url::Url::parse(root_uri).ok()?; - if url.scheme() != "file" { - return None; - } - let decoded = percent_decode(url.path()); - let path = match decoded.as_bytes() { - // `/C:/work` is how a URI carries a Windows drive path. - [b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => decoded[1..].to_string(), - _ => decoded, - }; - let path = match url.host_str().filter(|host| !host.is_empty()) { - Some(host) => format!("//{host}{path}"), - None => path, - }; - Some(path.trim_end_matches('/').to_string()) -} - -/// Returns `file_path` relative to `root` with `/` separators, or `None` when -/// it is not strictly inside the workspace. -/// -/// Windows drive and UNC paths compare case-insensitively, matching the file -/// system; the returned relative path keeps JDT's casing. -pub(crate) fn workspace_relative_path(root: &str, file_path: &str) -> Option { - let file_path = file_path.replace('\\', "/"); - let case_insensitive = is_windows_path(root) || is_windows_path(&file_path); - let prefix_matches = file_path.len() > root.len() - && file_path.is_char_boundary(root.len()) - && if case_insensitive { - file_path[..root.len()].eq_ignore_ascii_case(root) - } else { - file_path[..root.len()] == *root - }; - if !prefix_matches { - return None; - } - let relative = file_path[root.len()..].strip_prefix('/')?; - let is_contained = !relative.is_empty() - && relative - .split('/') - .all(|component| !component.is_empty() && component != "." && component != ".."); - is_contained.then(|| relative.to_string()) -} - -pub(crate) fn is_windows_path(path: &str) -> bool { - path.starts_with("//") - || matches!(path.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn entry(source_path: &str, main_class: &str, project_name: Option<&str>) -> JavaEntrypoint { - JavaEntrypoint { - source_path: source_path.to_string(), - main_class: main_class.to_string(), - project_name: project_name.map(str::to_string), - } - } - - #[test] - fn the_command_includes_jdt_invisible_projects_before_workspace_filtering() { - assert_eq!( - java_entrypoints_command(), - json!({ "command": "vscode.java.resolveMainClass", "arguments": [] }) - ); - } - - #[test] - fn unscoped_results_keep_only_sources_owned_by_the_open_workspace() { - let result = json!([ - { "mainClass": "Main", "projectName": "invisible-cache-project", "filePath": "/resolved/app/src/Main.java" }, - { "mainClass": "Foreign", "projectName": "other-project", "filePath": "/resolved/app-other/src/Foreign.java" } - ]); - let normalized = - normalize_java_entrypoints("file:///linked/app/", Some("/resolved/app"), &result) - .expect("list result"); - assert_eq!( - normalized.entries, - vec![entry( - "src/Main.java", - "Main", - Some("invisible-cache-project") - )] - ); - assert_eq!(normalized.diagnostics.len(), 1); - assert_eq!(normalized.diagnostics[0].code, "outsideWorkspace"); - } - - #[test] - fn same_class_names_in_two_modules_stay_separate_entries() { - // Maven reactors often repeat `demo.App` per module; the source path, - // not the class name, keeps them apart. - let result = json!([ - { "mainClass": "demo.App", "projectName": "app-b", "filePath": "/work/app-b/src/main/java/demo/App.java" }, - { "mainClass": "demo.App", "projectName": "app-a", "filePath": "/work/app-a/src/main/java/demo/App.java" } - ]); - let normalized = - normalize_java_entrypoints("file:///work/", None, &result).expect("list result"); - assert_eq!( - normalized.entries, - vec![ - entry( - "app-a/src/main/java/demo/App.java", - "demo.App", - Some("app-a") - ), - entry( - "app-b/src/main/java/demo/App.java", - "demo.App", - Some("app-b") - ), - ] - ); - assert!(normalized.diagnostics.is_empty()); - } - - #[test] - fn windows_paths_match_the_workspace_uri_without_regard_to_case() { - let result = json!([ - { "mainClass": "demo.StaticNoArgs", "projectName": "app", "filePath": "c:\\Work\\App\\src\\main\\java\\demo\\StaticNoArgs.java" } - ]); - let normalized = normalize_java_entrypoints("file:///C%3A/work/app", None, &result) - .expect("list result"); - assert_eq!( - normalized.entries, - vec![entry( - "src/main/java/demo/StaticNoArgs.java", - "demo.StaticNoArgs", - Some("app") - )] - ); - } - - #[test] - fn unc_workspaces_keep_their_server_name() { - let result = json!([ - { "mainClass": "App", "filePath": "\\\\server\\share\\app\\App.java" } - ]); - let normalized = normalize_java_entrypoints("file://server/share/app/", None, &result) - .expect("list result"); - assert_eq!(normalized.entries, vec![entry("App.java", "App", None)]); - } - - #[test] - fn percent_encoded_workspace_uris_decode_before_matching() { - let result = json!([ - { "mainClass": "App", "filePath": "/home/dev/my project/App.java" } - ]); - let normalized = - normalize_java_entrypoints("file:///home/dev/my%20project/", None, &result) - .expect("list result"); - assert_eq!(normalized.entries, vec![entry("App.java", "App", None)]); - } - - #[test] - fn unusable_results_become_diagnostics_instead_of_guesses() { - let result = json!([ - { "projectName": "app", "filePath": "/work/app/A.java" }, - { "mainClass": " ", "filePath": "/work/app/B.java" }, - { "mainClass": "demo.Pathless", "projectName": "app" }, - { "mainClass": "demo.Elsewhere", "filePath": "/other/Elsewhere.java" }, - { "mainClass": "demo.Sibling", "filePath": "/work/app-sibling/Sibling.java" }, - { "mainClass": "demo.Escapes", "filePath": "/work/app/../secret/Escapes.java" }, - { "mainClass": "demo.Root", "filePath": "/work/app" } - ]); - let normalized = - normalize_java_entrypoints("file:///work/app/", None, &result).expect("list result"); - assert!(normalized.entries.is_empty(), "{normalized:?}"); - let codes = normalized - .diagnostics - .iter() - .map(|diagnostic| (diagnostic.code, diagnostic.main_class.as_deref())) - .collect::>(); - assert_eq!( - codes, - vec![ - ("missingMainClass", None), - ("missingMainClass", None), - ("missingSourcePath", Some("demo.Pathless")), - ("outsideWorkspace", Some("demo.Elsewhere")), - ("outsideWorkspace", Some("demo.Sibling")), - ("outsideWorkspace", Some("demo.Escapes")), - ("outsideWorkspace", Some("demo.Root")), - ] - ); - assert_eq!( - normalized.diagnostics[3].detail.as_deref(), - Some("/other/Elsewhere.java") - ); - } - - #[test] - fn repeated_results_collapse_and_blank_project_names_are_dropped() { - let result = json!([ - { "mainClass": "B", "projectName": " ", "filePath": "/work/B.java" }, - { "mainClass": "A", "projectName": "p", "filePath": "/work/A.java" }, - { "mainClass": "A", "projectName": "p", "filePath": "/work/A.java" } - ]); - let normalized = - normalize_java_entrypoints("file:///work", None, &result).expect("list result"); - assert_eq!( - normalized.entries, - vec![entry("A.java", "A", Some("p")), entry("B.java", "B", None)] - ); - } - - #[test] - fn files_under_the_resolved_workspace_path_are_inside_the_workspace() { - // macOS: a workspace opened as `/var/...` is reported by JDT under - // `/private/var/...`; both spellings name the same directory. - let result = json!([ - { "mainClass": "demo.App", "filePath": "/private/var/work/app/src/demo/App.java" } - ]); - let normalized = normalize_java_entrypoints( - "file:///var/work/app/", - Some("/private/var/work/app"), - &result, - ) - .expect("list result"); - assert_eq!( - normalized.entries, - vec![entry("src/demo/App.java", "demo.App", None)] - ); - assert!(normalized.diagnostics.is_empty()); - } - - #[test] - fn a_non_list_result_is_not_an_entry_list() { - assert!( - normalize_java_entrypoints("file:///work", None, &json!({ "mainClass": "A" })) - .is_none() - ); - assert!(normalize_java_entrypoints("file:///work", None, &Value::Null).is_none()); - } - - #[test] - fn an_empty_list_is_a_valid_answer() { - let normalized = - normalize_java_entrypoints("file:///work", None, &json!([])).expect("list result"); - assert_eq!( - serde_json::to_value(normalized).expect("serializes"), - json!({ "schemaVersion": 1, "entries": [], "diagnostics": [] }) - ); - } -} diff --git a/rust/lithe-core/src/lsp/languages/java_launch.rs b/rust/lithe-core/src/lsp/languages/java_launch.rs deleted file mode 100644 index b1314bb62a..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_launch.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Shared Java launch preparation, using JDT-owned entry points and runtime paths. -//! The session engine owns requests, build serialization, cancellation and deadlines. - -use super::java_entrypoints::{is_windows_path, workspace_relative_path, workspace_root_path}; -use crate::lsp::LspRuntimeError; -use serde_json::{json, Value}; - -const TARGET_ERROR: &str = - "The Java language service could not identify one launch target for this source file."; - -/// The next upstream request, or the completed product preparation result. -pub(crate) enum JavaLaunchAction { - Build(Value), - Classpath(Value), - Complete(Value), -} - -/// Preserves upstream failures; malformed successful replies have no upstream error. -pub(crate) enum JavaLaunchFailure { - Upstream(LspRuntimeError), - Invalid(&'static str), -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Phase { - Entrypoints, - Build, - Classpath, -} - -/// One launch attempt. No project model or launch facts survive its completion. -pub(crate) struct JavaLaunchPreparation { - source_path: String, - source_file: String, - configured_main_class: Option, - windows_paths: bool, - phase: Phase, - target: Value, - build_failure: Option, -} - -impl JavaLaunchPreparation { - /// Validates the selected source against the same roots as JDT entry normalization. - pub(crate) fn new( - root_uri: &str, - canonical_root: Option<&str>, - source_file: String, - configured_main_class: Option, - ) -> Result { - let root = workspace_root_path(root_uri).ok_or(TARGET_ERROR)?; - let source_path = workspace_relative_path(&root, &source_file) - .or_else(|| { - canonical_root.and_then(|root| { - workspace_relative_path( - root.replace('\\', "/").trim_end_matches('/'), - &source_file, - ) - }) - }) - .ok_or(TARGET_ERROR)?; - Ok(Self { - windows_paths: is_windows_path(&root), - source_path, - source_file, - configured_main_class: configured_main_class.filter(|value| !value.trim().is_empty()), - phase: Phase::Entrypoints, - target: Value::Null, - build_failure: None, - }) - } - - /// Advances only on a terminal upstream answer. Cancellation and unknown outcomes - /// never become a successful preparation, including after a failed build. - pub(crate) fn advance( - &mut self, - result: Option, - error: Option, - ) -> Result { - if let Some(error) = error { - if self.phase == Phase::Build - && matches!( - error.code.as_str(), - "javaBuildCompilationErrors" | "javaBuildFailed" - ) - { - self.build_failure = Some(json!({ - "code": error.code, - "message": error.message, - "report": error.java_build_report, - })); - } else { - return Err(JavaLaunchFailure::Upstream(error)); - } - } - let result = result.unwrap_or(Value::Null); - match self.phase { - Phase::Entrypoints => { - let entries = result["entries"] - .as_array() - .ok_or(JavaLaunchFailure::Invalid(TARGET_ERROR))?; - let exact: Vec<_> = entries - .iter() - .filter(|entry| { - entry["sourcePath"].as_str().is_some_and(|path| { - if self.windows_paths { - path.eq_ignore_ascii_case(&self.source_path) - } else { - path == self.source_path - } - }) - }) - .collect(); - let selected = if exact.len() == 1 { - exact.first().copied() - } else { - let matches: Vec<_> = exact - .into_iter() - .filter(|entry| { - let Some(configured) = self.configured_main_class.as_deref() else { - return false; - }; - entry["mainClass"].as_str().is_some_and(|main| { - main == configured || main.rsplit('/').next() == Some(configured) - }) - }) - .collect(); - (matches.len() == 1).then(|| matches[0]) - } - .ok_or(JavaLaunchFailure::Invalid(TARGET_ERROR))?; - self.target = json!({"mainClass": selected["mainClass"]}); - if let Some(project) = selected.get("projectName") { - self.target["projectName"] = project.clone(); - } - let mut build = json!({ - "mainClass": self.target["mainClass"], - "filePath": self.source_file, - "isFullBuild": false, - }); - if let Some(project) = self.target.get("projectName") { - build["projectName"] = project.clone(); - } - self.phase = Phase::Build; - Ok(JavaLaunchAction::Build(json!({ - "command": "vscode.java.buildWorkspace", - "arguments": [build.to_string()], - }))) - } - Phase::Build => { - if self.build_failure.is_none() - && result["value"] != json!(1) - && result["value"] != json!("1") - { - return Err(JavaLaunchFailure::Invalid( - "The Java language service returned an unexpected project build status.", - )); - } - self.phase = Phase::Classpath; - // Omitting scope lets Java Debug Server include test/custom roots - // for the selected main; never infer paths from source folder names. - Ok(JavaLaunchAction::Classpath(json!({ - "command": "vscode.java.resolveClasspath", - "arguments": [self.target["mainClass"], self.target["projectName"].as_str().unwrap_or("")], - }))) - } - Phase::Classpath => { - let groups = result["value"] - .as_array() - .filter(|groups| groups.len() == 2) - .ok_or(JavaLaunchFailure::Invalid( - "The Java language service returned an invalid runtime classpath.", - ))?; - let paths = |group: &Value| -> Option> { - group - .as_array()? - .iter() - .map(|value| { - value - .as_str() - .filter(|value| !value.trim().is_empty()) - .map(str::to_owned) - }) - .collect() - }; - let module_paths = paths(&groups[0]); - let class_paths = paths(&groups[1]); - let (Some(module_paths), Some(class_paths)) = (module_paths, class_paths) else { - return Err(JavaLaunchFailure::Invalid( - "The Java language service returned an invalid runtime classpath.", - )); - }; - if module_paths.is_empty() && class_paths.is_empty() { - return Err(JavaLaunchFailure::Invalid( - "The Java language service returned no runtime paths.", - )); - } - self.target["modulePaths"] = json!(module_paths); - self.target["classPaths"] = json!(class_paths); - Ok(JavaLaunchAction::Complete( - match self.build_failure.take() { - Some(failure) => { - json!({"kind": "buildFailed", "target": self.target, "failure": failure}) - } - None => json!({"kind": "ready", "target": self.target}), - }, - )) - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::lsp::languages::java_entrypoints::normalize_java_entrypoints; - - #[test] - fn shared_launch_fixtures_preserve_source_identity_and_upstream_paths() { - let fixture: Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/lsp/java-launch-preparation-v1.json" - )) - .unwrap(); - for case in fixture["cases"].as_array().unwrap() { - let root = case["rootUri"].as_str().unwrap(); - let mut preparation = JavaLaunchPreparation::new( - root, - None, - case["sourcePath"].as_str().unwrap().into(), - Some(case["mainClass"].as_str().unwrap().into()), - ) - .unwrap(); - let entries = normalize_java_entrypoints(root, None, &case["entries"]).unwrap(); - assert!( - matches!( - preparation.advance(Some(serde_json::to_value(entries).unwrap()), None), - Ok(JavaLaunchAction::Build(_)) - ), - "{}", - case["id"] - ); - assert!(matches!( - preparation.advance(Some(json!({"value": 1})), None), - Ok(JavaLaunchAction::Classpath(_)) - )); - let Ok(JavaLaunchAction::Complete(result)) = - preparation.advance(Some(json!({"value": case["paths"]})), None) - else { - panic!("fixture did not prepare: {}", case["id"]); - }; - assert_eq!(result, json!({"kind": "ready", "target": case["target"]})); - } - } - - #[test] - fn selection_never_borrows_another_file_or_guesses_an_ambiguous_module() { - for entries in [ - json!([{ "sourcePath": "other/Main.java", "mainClass": "demo.Main" }]), - json!([ - { "sourcePath": "app/Main.java", "mainClass": "one/demo.Main" }, - { "sourcePath": "app/Main.java", "mainClass": "two/demo.Main" } - ]), - ] { - let mut preparation = JavaLaunchPreparation::new( - "file:///workspace", - None, - "/workspace/app/Main.java".into(), - Some("demo.Main".into()), - ) - .unwrap(); - assert!(matches!( - preparation.advance(Some(json!({"entries": entries})), None), - Err(JavaLaunchFailure::Invalid(TARGET_ERROR)) - )); - } - assert!(JavaLaunchPreparation::new( - "file:///workspace", - None, - "/workspace-other/Main.java".into(), - None - ) - .is_err()); - } -} diff --git a/rust/lithe-core/src/lsp/languages/java_main_methods.rs b/rust/lithe-core/src/lsp/languages/java_main_methods.rs deleted file mode 100644 index 134f91f5b1..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_main_methods.rs +++ /dev/null @@ -1,235 +0,0 @@ -//! Normalizes JDT's per-file `main` method discovery into Lithe's shared contract. -//! -//! The Java Debug Server's `vscode.java.resolveMainMethod` reports, for one -//! source file, every `main` method the JVM can launch together with the -//! source range of its name. Editors use it to place Run markers beside the -//! declaration. As with workspace entry points, JDT alone decides which -//! methods qualify (Java 25 instance and no-argument `main`, compact source -//! files), so this module never reads Java source; it only validates JDT's -//! answer and orders it deterministically. -//! -//! Note: entry-point ownership is recorded in .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md - -use serde::Serialize; -use serde_json::{json, Value}; - -/// Java Debug Server command that lists launchable `main` methods in one file. -pub(crate) const JAVA_RESOLVE_MAIN_METHOD_COMMAND: &str = "vscode.java.resolveMainMethod"; - -/// Version of the serialized [`JavaMainMethods`] shape. -pub(crate) const JAVA_MAIN_METHODS_SCHEMA_VERSION: u32 = 1; - -/// `workspace/executeCommand` params that discover `main` methods in one document. -pub(crate) fn java_main_methods_command(uri: &str) -> Value { - json!({ - "command": JAVA_RESOLVE_MAIN_METHOD_COMMAND, - "arguments": [uri], - }) -} - -/// Launchable `main` methods JDT reported for one source file. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaMainMethods { - pub schema_version: u32, - /// Methods ordered by source position, then `mainClass`, without duplicates. - pub methods: Vec, - /// JDT results that could not become methods, in JDT's order. - pub diagnostics: Vec, -} - -/// One `main` method JDT confirmed the JVM can launch. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaMainMethod { - /// Range of the method name. Field order makes the derived ordering sort - /// by source position first. - pub range: JavaMainMethodRange, - /// Class name as JDT reports it; it matches the `mainClass` of the - /// workspace entry point generated for the same file. - pub main_class: String, - /// JDT project that owns the class; only used to resolve a launch again. - #[serde(skip_serializing_if = "Option::is_none")] - pub project_name: Option, -} - -/// Zero-based UTF-16 source range from JDT, matching `javaTestItems` ranges. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaMainMethodRange { - pub start_line: i64, - pub start_utf16_column: i64, - pub end_line: i64, - pub end_utf16_column: i64, -} - -/// A JDT result that was dropped, with the reason. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaMainMethodDiagnostic { - /// `invalidMethod`, `missingMainClass`, or `missingRange`. - pub code: &'static str, - #[serde(skip_serializing_if = "Option::is_none")] - pub main_class: Option, -} - -/// Converts a `resolveMainMethod` result into [`JavaMainMethods`]. -/// -/// An array is a valid answer, including an empty one. `null` — which the -/// command handler may return for a document outside any Java project — is -/// the same fact as "no launchable method here". Any other shape is a broken server -/// contract and returns `None` so callers keep their previous markers instead -/// of mistaking it for an empty file. -pub(crate) fn normalize_java_main_methods(result: &Value) -> Option { - let candidates: &[Value] = match result { - Value::Array(candidates) => candidates, - Value::Null => &[], - _ => return None, - }; - let mut methods = Vec::new(); - let mut diagnostics = Vec::new(); - for candidate in candidates { - let Some(object) = candidate.as_object() else { - diagnostics.push(JavaMainMethodDiagnostic { - code: "invalidMethod", - main_class: None, - }); - continue; - }; - let main_class = object - .get("mainClass") - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()); - let Some(main_class) = main_class else { - diagnostics.push(JavaMainMethodDiagnostic { - code: "missingMainClass", - main_class: None, - }); - continue; - }; - // Without a range the marker has no line to sit on; guessing one from - // source text would reintroduce Lithe-owned Java rules. - let Some(range) = object.get("range").and_then(normalize_range) else { - diagnostics.push(JavaMainMethodDiagnostic { - code: "missingRange", - main_class: Some(main_class.to_string()), - }); - continue; - }; - let project_name = object - .get("projectName") - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string); - methods.push(JavaMainMethod { - range, - main_class: main_class.to_string(), - project_name, - }); - } - methods.sort(); - methods.dedup(); - Some(JavaMainMethods { - schema_version: JAVA_MAIN_METHODS_SCHEMA_VERSION, - methods, - diagnostics, - }) -} - -fn integer_value(value: Option<&Value>) -> Option { - value.and_then(Value::as_i64).filter(|value| *value >= 0) -} - -fn normalize_range(value: &Value) -> Option { - let start = value.get("start")?; - let end = value.get("end")?; - Some(JavaMainMethodRange { - start_line: integer_value(start.get("line"))?, - start_utf16_column: integer_value(start.get("character"))?, - end_line: integer_value(end.get("line"))?, - end_utf16_column: integer_value(end.get("character"))?, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn range(line: i64, start: i64, end: i64) -> Value { - json!({ - "start": { "line": line, "character": start }, - "end": { "line": line, "character": end } - }) - } - - #[test] - fn command_passes_the_document_uri_to_java_debug() { - assert_eq!( - java_main_methods_command("file:///work/src/App.java"), - json!({ - "command": "vscode.java.resolveMainMethod", - "arguments": ["file:///work/src/App.java"] - }) - ); - } - - // Shape captured from JDT LS 1.61.0 with Java Debug 0.53.2 on a Java 25 - // project; the instance `main` must survive because JDT accepted it. - #[test] - fn keeps_every_method_jdt_accepted_in_source_order() { - let result = json!([ - { "range": range(9, 16, 20), "mainClass": "demo.Outer$Inner", "projectName": "app" }, - { "range": range(1, 33, 37), "mainClass": "demo.InstanceArgs", "projectName": "app" } - ]); - let normalized = normalize_java_main_methods(&result).expect("array result"); - assert!(normalized.diagnostics.is_empty()); - assert_eq!(normalized.schema_version, 1); - assert_eq!( - normalized - .methods - .iter() - .map(|method| (method.range.start_line, method.main_class.as_str())) - .collect::>(), - vec![(1, "demo.InstanceArgs"), (9, "demo.Outer$Inner")] - ); - assert_eq!(normalized.methods[0].project_name.as_deref(), Some("app")); - assert_eq!(normalized.methods[0].range.start_utf16_column, 33); - } - - #[test] - fn null_result_means_no_methods() { - let normalized = normalize_java_main_methods(&Value::Null).expect("null result"); - assert!(normalized.methods.is_empty()); - assert!(normalized.diagnostics.is_empty()); - } - - #[test] - fn malformed_entries_are_diagnosed_without_hiding_valid_peers() { - let result = json!([ - "not-a-method", - { "range": range(0, 0, 4) }, - { "mainClass": "demo.NoRange" }, - { "range": range(2, 4, 8), "mainClass": "demo.App", "projectName": " " }, - { "range": range(2, 4, 8), "mainClass": "demo.App" } - ]); - let normalized = normalize_java_main_methods(&result).expect("array result"); - assert_eq!(normalized.methods.len(), 1); - assert_eq!(normalized.methods[0].main_class, "demo.App"); - assert_eq!(normalized.methods[0].project_name, None); - assert_eq!( - normalized - .diagnostics - .iter() - .map(|diagnostic| diagnostic.code) - .collect::>(), - vec!["invalidMethod", "missingMainClass", "missingRange"] - ); - } - - #[test] - fn other_shapes_are_not_misreported_as_an_empty_file() { - assert_eq!(normalize_java_main_methods(&json!({ "methods": [] })), None); - } -} diff --git a/rust/lithe-core/src/lsp/languages/java_navigation_syntax.rs b/rust/lithe-core/src/lsp/languages/java_navigation_syntax.rs deleted file mode 100644 index 8f2f4214fe..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_navigation_syntax.rs +++ /dev/null @@ -1,264 +0,0 @@ -//! Java syntax candidates for semantic navigation-marker verification. - -use tree_sitter::{Node, Parser}; - -/// One declaration whose semantic parent or implementation relation must be verified by JDT LS. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) struct JavaNavigationCandidate { - pub line: i64, - pub utf16_column: i64, - pub direction: &'static str, - pub relation: &'static str, -} - -/// Extracts real Java method declarations without guessing across statement text. -/// -/// Syntax only selects bounded candidates. A candidate never becomes a visible -/// marker until JDT LS confirms at least one target, so incomplete or erroneous -/// source cannot create a false gutter icon by itself. -pub(crate) fn navigation_candidates(source: &str) -> Vec { - let mut parser = Parser::new(); - if parser - .set_language(&tree_sitter_java::LANGUAGE.into()) - .is_err() - { - return Vec::new(); - } - let Some(tree) = parser.parse(source, None) else { - return Vec::new(); - }; - let mut candidates = Vec::new(); - collect_candidates(tree.root_node(), source.as_bytes(), &mut candidates); - candidates.sort_by(|left, right| { - left.line - .cmp(&right.line) - .then_with(|| left.utf16_column.cmp(&right.utf16_column)) - .then_with(|| left.direction.cmp(right.direction)) - .then_with(|| left.relation.cmp(right.relation)) - }); - candidates.dedup(); - candidates -} - -fn collect_candidates( - node: Node<'_>, - source: &[u8], - candidates: &mut Vec, -) { - if node.kind() == "method_declaration" { - collect_method_candidates(node, source, candidates); - } - let mut cursor = node.walk(); - for child in node.children(&mut cursor) { - collect_candidates(child, source, candidates); - } -} - -fn collect_method_candidates( - method: Node<'_>, - source: &[u8], - candidates: &mut Vec, -) { - let Some(name) = method.child_by_field_name("name") else { - return; - }; - let modifiers = method - .children(&mut method.walk()) - .find(|child| child.kind() == "modifiers"); - let modifier_text = modifiers - .and_then(|value| value.utf8_text(source).ok()) - .unwrap_or_default(); - let enclosing_type = enclosing_type(method); - let relation = if enclosing_type.is_some_and(|value| value.kind() == "interface_declaration") { - "interface" - } else { - "inheritance" - }; - let point = name.start_position(); - let position = JavaNavigationCandidate { - line: i64::try_from(point.row).unwrap_or(i64::MAX), - utf16_column: utf16_column(source, point.row, point.column), - direction: "down", - relation, - }; - - if is_possible_override_target(modifier_text, enclosing_type, source) { - candidates.push(position.clone()); - } - if has_override_annotation(modifiers, source) { - candidates.push(JavaNavigationCandidate { - direction: "up", - relation: super_relation(enclosing_type, source), - ..position - }); - } -} - -fn enclosing_type(mut node: Node<'_>) -> Option> { - while let Some(parent) = node.parent() { - if matches!( - parent.kind(), - "class_declaration" - | "interface_declaration" - | "enum_declaration" - | "record_declaration" - ) { - return Some(parent); - } - node = parent; - } - None -} - -fn is_possible_override_target( - modifier_text: &str, - enclosing_type: Option>, - source: &[u8], -) -> bool { - if modifier_text - .split_whitespace() - .any(|modifier| matches!(modifier, "private" | "static" | "final")) - { - return false; - } - let Some(enclosing_type) = enclosing_type else { - return false; - }; - if enclosing_type.kind() == "interface_declaration" { - return true; - } - let type_modifiers = enclosing_type - .children(&mut enclosing_type.walk()) - .find(|child| child.kind() == "modifiers") - .and_then(|value| value.utf8_text(source).ok()) - .unwrap_or_default(); - !type_modifiers - .split_whitespace() - .any(|value| value == "final") -} - -fn has_override_annotation(modifiers: Option>, source: &[u8]) -> bool { - let Some(modifiers) = modifiers else { - return false; - }; - let mut cursor = modifiers.walk(); - let found = modifiers.children(&mut cursor).any(|child| { - matches!(child.kind(), "marker_annotation" | "annotation") - && child - .utf8_text(source) - .is_ok_and(|text| text.trim() == "@Override") - }); - found -} - -fn super_relation(enclosing_type: Option>, source: &[u8]) -> &'static str { - let Some(enclosing_type) = enclosing_type else { - return "inheritance"; - }; - if enclosing_type.kind() == "interface_declaration" { - return "interface"; - } - let header_end = enclosing_type - .child_by_field_name("body") - .map(|body| body.start_byte()) - .unwrap_or(enclosing_type.end_byte()); - let header = source - .get(enclosing_type.start_byte()..header_end) - .and_then(|value| std::str::from_utf8(value).ok()) - .unwrap_or_default(); - // JDT LS 1.38 findLinks identifies the parent method but does not report - // whether its declaring type is an interface. Prefer the interface visual - // for implementing classes; ordinary subclass overrides remain inheritance. - // A class that both extends and implements can be ambiguous until JDT LS - // exposes the declaring-type kind in this response. - if header - .split(|character: char| !character.is_ascii_alphanumeric() && character != '_') - .any(|word| word == "implements") - { - "interface" - } else { - "inheritance" - } -} - -fn utf16_column(source: &[u8], row: usize, byte_column: usize) -> i64 { - let line = source - .split(|value| *value == b'\n') - .nth(row) - .unwrap_or_default(); - let prefix = line.get(..byte_column).unwrap_or(line); - let units = String::from_utf8_lossy(prefix).encode_utf16().count(); - i64::try_from(units).unwrap_or(i64::MAX) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn multiline_declarations_are_candidates_but_constructor_calls_are_not() { - let source = r#" -interface UploadService { - UploadResponse createDirectUploadSession( - UploadRequest request, - String objectKey - ); -} - -class Response { - Response upload() { - return new Response( - ); - } -} -"#; - - let candidates = navigation_candidates(source); - - assert!(candidates.iter().any(|candidate| { - candidate.line == 2 - && candidate.direction == "down" - && candidate.relation == "interface" - })); - assert_eq!( - candidates - .iter() - .filter(|candidate| candidate.line >= 9) - .count(), - 1 - ); - } - - #[test] - fn override_methods_get_up_and_possible_down_candidates() { - let source = r#" -class ServiceImpl implements Service { - @Override - public void run() {} -} -"#; - - let candidates = navigation_candidates(source); - - assert!(candidates - .iter() - .any(|candidate| { candidate.direction == "up" && candidate.relation == "interface" })); - assert!(candidates - .iter() - .any(|candidate| candidate.direction == "down")); - } - - #[test] - fn private_static_final_and_final_class_methods_are_not_down_candidates() { - let source = r#" -final class Closed { - void ordinary() {} - private void hidden() {} - static void utility() {} - final void fixed() {} -} -"#; - - assert!(navigation_candidates(source).is_empty()); - } -} diff --git a/rust/lithe-core/src/lsp/languages/java_run_markers.rs b/rust/lithe-core/src/lsp/languages/java_run_markers.rs deleted file mode 100644 index a359bda1d2..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_run_markers.rs +++ /dev/null @@ -1,483 +0,0 @@ -//! Projects JDT facts and recorded test outcomes into editor Run markers. -//! -//! Both products show IDEA-style gutter markers: a Run marker beside each -//! launchable `main` method, a Run-all marker beside each test class, and a -//! Run marker beside each test method, the latter two switching to a passed or -//! failed icon once a run recorded an outcome. Which declarations qualify is -//! decided upstream by JDT (`javaMainMethods`) and the Java Test extension -//! (`javaTestItems`); outcomes come from canonical build-provider reports. This -//! module only combines those answers, so the two platforms cannot drift on -//! placement, labels, or how method outcomes roll up into a class outcome. -//! -//! Note: the design is recorded in .agents/notes/implemented/architecture/2026-09-22-editor-run-markers-and-test-outcomes.md - -use crate::protocol::{CoreError, ErrorCode}; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -/// Java Test extension level of a test class item. -const TEST_LEVEL_CLASS: i64 = 5; -/// Java Test extension level of a test method item. -const TEST_LEVEL_METHOD: i64 = 6; -/// Upper bound on markers returned for one file. -const MAX_MARKERS: usize = 5_000; - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Upstream answers for one open Java file. -pub struct JavaRunMarkersRequest { - /// `methods` from the file's `javaMainMethods` answer. - #[serde(default)] - pub main_methods: Vec, - /// `items` from the file's `javaTestItems` answer. Platforms pass an empty - /// list when they cannot run tests for this file. - #[serde(default)] - pub test_items: Vec, - /// Canonical report cases (`suite`, `case`, `status`); entries for other - /// classes are ignored. Legacy `className`/`method` remain accepted. - #[serde(default)] - pub test_cases: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// One `javaMainMethods` entry. -pub struct MainMethodInput { - pub main_class: String, - #[serde(default)] - pub project_name: Option, - pub range: RangeInput, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// One `javaTestItems` node, including its children. -pub struct TestItemInput { - pub id: String, - pub label: String, - pub full_name: String, - pub test_level: i64, - #[serde(default)] - pub range: Option, - #[serde(default)] - pub children: Vec, -} - -#[derive(Debug, Clone, Copy, Deserialize)] -#[serde(rename_all = "camelCase")] -/// Zero-based UTF-16 range as returned by the upstream operations. -pub struct RangeInput { - pub start_line: i64, - /// Java Test ranges run to the end of the declaration body; Java Debug - /// main-method ranges cover only the method name. - #[serde(default)] - pub end_line: Option, -} - -impl RangeInput { - fn end_line(self) -> i64 { - self.end_line - .filter(|end| *end >= self.start_line) - .unwrap_or(self.start_line) - } -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -/// One canonical test case, with legacy field aliases for older consumers. -pub struct TestCaseInput { - #[serde(alias = "suite")] - pub class_name: String, - #[serde(alias = "case")] - pub method: String, - pub status: String, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "camelCase")] -/// What a marker launches. The declaration order is the order of markers -/// sharing one line. -pub enum JavaRunMarkerKind { - /// A launchable `main` method. - Main, - /// A test class; running it runs every test the class contains. - TestClass, - /// One test method. - TestMethod, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Last recorded outcome shown by a marker. -pub enum JavaRunMarkerStatus { - /// Not run yet, or no outcome was recorded; shows the plain Run icon. - None, - Passed, - /// A failure or an error. - Failed, - /// Every recorded invocation was skipped. - Skipped, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -/// One gutter marker. -pub struct JavaRunMarker { - /// Zero-based line of the declaration name. - pub line: i64, - /// Last zero-based line of the declaration as JDT reports it: the end of - /// the body for test classes and methods, the name line for `main`. - pub end_line: i64, - pub kind: JavaRunMarkerKind, - /// Target named in menus, such as `App.main()`, `OrderTest`, or - /// `OrderTest.creates`; platforms wrap it in their localized verbs. - pub label: String, - /// `main` launch target, matching a `javaEntrypoints` entry. - #[serde(skip_serializing_if = "Option::is_none")] - pub main_class: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub project_name: Option, - /// Fully qualified test class for test markers, as the Java Test - /// extension names it. - #[serde(skip_serializing_if = "Option::is_none")] - pub test_class: Option, - /// Java method name for test method markers, without parameters. - #[serde(skip_serializing_if = "Option::is_none")] - pub test_method: Option, - /// Java Test extension item identity, for platforms that launch or debug - /// through the extension. - #[serde(skip_serializing_if = "Option::is_none")] - pub test_item_id: Option, - pub status: JavaRunMarkerStatus, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Markers for one file, ordered by line and then [`JavaRunMarkerKind`]. -pub struct JavaRunMarkersResponse { - pub markers: Vec, -} - -/// Builds the markers for one file (`java.runMarkers`). -pub fn java_run_markers( - request: JavaRunMarkersRequest, -) -> Result { - let outcomes = recorded_outcomes(&request.test_cases); - let mut markers = Vec::new(); - for method in &request.main_methods { - let main_class = method.main_class.trim(); - if main_class.is_empty() || method.range.start_line < 0 { - continue; - } - markers.push(JavaRunMarker { - line: method.range.start_line, - end_line: method.range.end_line(), - kind: JavaRunMarkerKind::Main, - label: format!("{}.main()", simple_class_name(main_class)), - main_class: Some(main_class.to_string()), - project_name: method - .project_name - .as_deref() - .map(str::trim) - .filter(|name| !name.is_empty()) - .map(str::to_string), - test_class: None, - test_method: None, - test_item_id: None, - status: JavaRunMarkerStatus::None, - }); - } - for item in &request.test_items { - collect_test_markers(item, None, &outcomes, &mut markers)?; - } - if markers.len() > MAX_MARKERS { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Too many Run markers for one file", - ) - .with_details(format!("maximumMarkers={MAX_MARKERS}"))); - } - markers.sort_by(|left, right| { - (left.line, left.kind, &left.label).cmp(&(right.line, right.kind, &right.label)) - }); - markers.dedup_by(|left, right| { - left.line == right.line && left.kind == right.kind && left.label == right.label - }); - Ok(JavaRunMarkersResponse { markers }) -} - -/// Outcomes keyed by `(class, method)`, with `$` nested-class separators -/// folded to `.` so report binary names match Java Test's source names. -fn recorded_outcomes(cases: &[TestCaseInput]) -> HashMap<(String, String), JavaRunMarkerStatus> { - let mut outcomes = HashMap::new(); - for case in cases { - let status = match case.status.as_str() { - "passed" => JavaRunMarkerStatus::Passed, - "failed" | "error" => JavaRunMarkerStatus::Failed, - "skipped" => JavaRunMarkerStatus::Skipped, - _ => continue, - }; - outcomes.insert( - ( - source_class_name(&case.class_name), - case.method.trim().to_string(), - ), - status, - ); - } - outcomes -} - -fn collect_test_markers( - item: &TestItemInput, - owning_class: Option<&str>, - outcomes: &HashMap<(String, String), JavaRunMarkerStatus>, - markers: &mut Vec, -) -> Result, CoreError> { - crate::protocol::cancellation::check()?; - match item.test_level { - TEST_LEVEL_CLASS => { - let class_name = item.full_name.trim(); - let mut statuses = Vec::new(); - for child in &item.children { - statuses.extend(collect_test_markers( - child, - Some(class_name), - outcomes, - markers, - )?); - } - if let Some(range) = item.range.filter(|range| range.start_line >= 0) { - markers.push(JavaRunMarker { - line: range.start_line, - end_line: range.end_line(), - kind: JavaRunMarkerKind::TestClass, - label: simple_class_name(class_name).to_string(), - main_class: None, - project_name: None, - test_class: Some(class_name.to_string()), - test_method: None, - test_item_id: Some(item.id.clone()), - status: class_status(&statuses), - }); - } - Ok(statuses) - } - TEST_LEVEL_METHOD => { - let Some(class_name) = owning_class.or_else(|| declaring_class(&item.full_name)) else { - return Ok(Vec::new()); - }; - let Some(method) = method_name(item) else { - return Ok(Vec::new()); - }; - let status = outcomes - .get(&(source_class_name(class_name), method.clone())) - .copied() - .unwrap_or(JavaRunMarkerStatus::None); - if let Some(range) = item.range.filter(|range| range.start_line >= 0) { - markers.push(JavaRunMarker { - line: range.start_line, - end_line: range.end_line(), - kind: JavaRunMarkerKind::TestMethod, - label: format!("{}.{}", simple_class_name(class_name), method), - main_class: None, - project_name: None, - test_class: Some(class_name.to_string()), - test_method: Some(method), - test_item_id: Some(item.id.clone()), - status, - }); - } - Ok(vec![status]) - } - // Package, project, and workspace levels only group classes. - _ => { - let mut statuses = Vec::new(); - for child in &item.children { - statuses.extend(collect_test_markers( - child, - owning_class, - outcomes, - markers, - )?); - } - Ok(statuses) - } - } -} - -/// A class shows failed when any recorded method failed and passed when at -/// least one passed and none failed; unrun methods do not hide a failure. -fn class_status(statuses: &[JavaRunMarkerStatus]) -> JavaRunMarkerStatus { - if statuses.contains(&JavaRunMarkerStatus::Failed) { - JavaRunMarkerStatus::Failed - } else if statuses.contains(&JavaRunMarkerStatus::Passed) { - JavaRunMarkerStatus::Passed - } else if statuses.contains(&JavaRunMarkerStatus::Skipped) { - JavaRunMarkerStatus::Skipped - } else { - JavaRunMarkerStatus::None - } -} - -/// Method name without its parameter list, from `Class#method(Args)` or the label. -fn method_name(item: &TestItemInput) -> Option { - let semantic = item - .full_name - .rsplit_once('#') - .map(|(_, method)| method) - .unwrap_or(&item.label); - let name = semantic.split('(').next().unwrap_or_default().trim(); - (!name.is_empty()).then(|| name.to_string()) -} - -fn declaring_class(full_name: &str) -> Option<&str> { - full_name - .split_once('#') - .map(|(class_name, _)| class_name.trim()) - .filter(|class_name| !class_name.is_empty()) -} - -fn source_class_name(class_name: &str) -> String { - class_name.trim().replace('$', ".") -} - -fn simple_class_name(class_name: &str) -> &str { - let without_module = class_name - .rsplit_once('/') - .map_or(class_name, |(_, name)| name); - without_module - .rsplit(['.', '$']) - .next() - .filter(|name| !name.is_empty()) - .unwrap_or(without_module) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn markers(request: serde_json::Value) -> Vec { - let request = serde_json::from_value(request).expect("valid request"); - let response = java_run_markers(request).expect("markers"); - serde_json::to_value(response).expect("encodes")["markers"] - .as_array() - .cloned() - .unwrap_or_default() - } - - fn range(line: i64) -> serde_json::Value { - json!({ "startLine": line, "startUtf16Column": 0, "endLine": line, "endUtf16Column": 4 }) - } - - #[test] - fn main_methods_become_run_markers_named_like_idea() { - let markers = markers(json!({ - "mainMethods": [ - { "mainClass": "demo.App", "projectName": "app", "range": range(4) }, - { "mainClass": "app/demo.Modular", "range": range(9) } - ] - })); - assert_eq!( - markers, - vec![ - json!({ "line": 4, "endLine": 4, "kind": "main", "label": "App.main()", "mainClass": "demo.App", "projectName": "app", "status": "none" }), - json!({ "line": 9, "endLine": 9, "kind": "main", "label": "Modular.main()", "mainClass": "app/demo.Modular", "status": "none" }), - ] - ); - } - - #[test] - fn test_classes_and_methods_carry_their_recorded_outcomes() { - let markers = markers(json!({ - "testItems": [{ - "id": "app@demo.OrderTest", "label": "OrderTest", "fullName": "demo.OrderTest", - "testLevel": 5, "range": range(3), - "children": [ - { "id": "m1", "label": "creates()", "fullName": "demo.OrderTest#creates()", "testLevel": 6, "range": range(5), "children": [] }, - { "id": "m2", "label": "priced(int)", "fullName": "demo.OrderTest#priced(int)", "testLevel": 6, "range": range(8), "children": [] }, - { "id": "m3", "label": "later()", "fullName": "demo.OrderTest#later()", "testLevel": 6, "range": range(11), "children": [] } - ] - }], - "testCases": [ - { "className": "demo.OrderTest", "method": "creates", "status": "passed" }, - { "className": "demo.OrderTest", "method": "priced", "status": "error" }, - { "className": "demo.OtherTest", "method": "later", "status": "passed" } - ] - })); - let summary = markers - .iter() - .map(|marker| { - ( - marker["line"].as_i64().unwrap(), - marker["kind"].as_str().unwrap().to_string(), - marker["label"].as_str().unwrap().to_string(), - marker["status"].as_str().unwrap().to_string(), - ) - }) - .collect::>(); - assert_eq!( - summary, - vec![ - (3, "testClass".into(), "OrderTest".into(), "failed".into()), - ( - 5, - "testMethod".into(), - "OrderTest.creates".into(), - "passed".into() - ), - ( - 8, - "testMethod".into(), - "OrderTest.priced".into(), - "failed".into() - ), - ( - 11, - "testMethod".into(), - "OrderTest.later".into(), - "none".into() - ), - ] - ); - assert_eq!(markers[2]["testMethod"], json!("priced")); - assert_eq!(markers[2]["testClass"], json!("demo.OrderTest")); - assert_eq!(markers[2]["testItemId"], json!("m2")); - } - - // Java Test nests inner test classes under their outer class and names - // them by binary name (`Outer$Inner`), as JDT LS 1.61.0 does for - // `@Nested`; source spelling (`Outer.Inner`) must match reports too. - #[test] - fn nested_class_outcomes_match_either_spelling() { - let markers = markers(json!({ - "testItems": [{ - "id": "outer", "label": "OrderTest", "fullName": "demo.OrderTest", "testLevel": 5, "range": range(2), - "children": [{ - "id": "inner", "label": "Refunds", "fullName": "demo.OrderTest$Refunds", "testLevel": 5, "range": range(4), - "children": [{ "id": "m", "label": "refunds()", "fullName": "demo.OrderTest$Refunds#refunds()", "testLevel": 6, "range": range(5), "children": [] }] - }] - }], - "testCases": [{ "className": "demo.OrderTest.Refunds", "method": "refunds", "status": "passed" }] - })); - assert_eq!( - markers - .iter() - .map(|marker| marker["status"].as_str().unwrap()) - .collect::>(), - vec!["passed", "passed", "passed"] - ); - assert_eq!(markers[1]["label"], json!("Refunds")); - } - - #[test] - fn items_without_a_source_range_get_no_marker() { - let markers = markers(json!({ - "testItems": [{ "id": "c", "label": "InheritedSuite", "fullName": "demo.InheritedSuite", "testLevel": 5, "children": [ - { "id": "m", "label": "inherited()", "fullName": "demo.BaseTests#inherited()", "testLevel": 6, "children": [] } - ] }] - })); - assert!(markers.is_empty()); - } -} diff --git a/rust/lithe-core/src/lsp/languages/java_tests.rs b/rust/lithe-core/src/lsp/languages/java_tests.rs deleted file mode 100644 index 37ac7303ba..0000000000 --- a/rust/lithe-core/src/lsp/languages/java_tests.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! Normalizes Java Test extension discovery into Lithe's shared contract. -//! -//! The Java Test extension and JDT decide which declarations are tests. This -//! module deliberately has no annotation or naming rules: it only validates -//! the extension result and exposes stable, typed fields to platform code. -//! -//! Note: semantic ownership is recorded in .agents/notes/implemented/architecture/2026-09-21-java-entrypoints-owned-by-jdt.md - -use serde::Serialize; -use serde_json::{json, Value}; - -/// Java Test extension command that discovers test types and methods in a file. -pub(crate) const JAVA_FIND_TEST_ITEMS_COMMAND: &str = "vscode.java.test.findTestTypesAndMethods"; - -/// Version of the serialized [`JavaTestItems`] shape. -pub(crate) const JAVA_TEST_ITEMS_SCHEMA_VERSION: u32 = 1; - -/// `workspace/executeCommand` params for semantic test discovery in one file. -pub(crate) fn java_test_items_command(uri: &str) -> Value { - json!({ - "command": JAVA_FIND_TEST_ITEMS_COMMAND, - "arguments": [uri], - }) -} - -/// Java test declarations reported for one source file. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaTestItems { - pub schema_version: u32, - pub items: Vec, - /// Invalid extension nodes that were ignored, in traversal order. - pub diagnostics: Vec, -} - -/// One test class or method identified by the Java Test extension. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaTestItem { - pub id: String, - pub label: String, - pub full_name: String, - pub project_name: String, - pub test_kind: i64, - pub test_level: i64, - #[serde(skip_serializing_if = "Option::is_none")] - pub jdt_handler: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub sort_text: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub range: Option, - pub children: Vec, -} - -/// Zero-based UTF-16 source range from JDT. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaTestRange { - pub start_line: i64, - pub start_utf16_column: i64, - pub end_line: i64, - pub end_utf16_column: i64, -} - -/// One raw extension node Core could not safely expose. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaTestItemDiagnostic { - pub code: &'static str, - #[serde(skip_serializing_if = "Option::is_none")] - pub detail: Option, -} - -/// Converts `findTestTypesAndMethods` output into the shared typed contract. -/// -/// An array is a valid answer, including an empty one. `null` is also “no -/// tests”: vscode-java-test returns its root's `children`, which stays `null` -/// until a first test is added. Any other shape is a broken server contract and -/// returns `None` so callers do not mistake it for “no tests”. Malformed child -/// nodes are diagnosed without discarding valid peers. -pub(crate) fn normalize_java_test_items(result: &Value) -> Option { - let candidates = match result { - Value::Null => &Vec::new(), - Value::Array(candidates) => candidates, - _ => return None, - }; - let mut diagnostics = Vec::new(); - let items = candidates - .iter() - .filter_map(|candidate| normalize_item(candidate, &mut diagnostics)) - .collect(); - Some(JavaTestItems { - schema_version: JAVA_TEST_ITEMS_SCHEMA_VERSION, - items, - diagnostics, - }) -} - -fn normalize_item( - candidate: &Value, - diagnostics: &mut Vec, -) -> Option { - let Some(object) = candidate.as_object() else { - diagnostics.push(JavaTestItemDiagnostic { - code: "invalidItem", - detail: Some("item is not an object".to_string()), - }); - return None; - }; - let required_string = |name: &str| { - object - .get(name) - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string) - }; - let id = required_string("id"); - let label = required_string("label"); - let full_name = required_string("fullName"); - let project_name = required_string("projectName"); - let test_kind = integer_value(object.get("testKind")); - let test_level = integer_value(object.get("testLevel")); - let ( - Some(id), - Some(label), - Some(full_name), - Some(project_name), - Some(test_kind), - Some(test_level), - ) = (id, label, full_name, project_name, test_kind, test_level) - else { - diagnostics.push(JavaTestItemDiagnostic { - code: "missingRequiredField", - detail: object - .get("label") - .and_then(Value::as_str) - .map(str::to_string), - }); - return None; - }; - let children = object - .get("children") - .and_then(Value::as_array) - .map(|children| { - children - .iter() - .filter_map(|child| normalize_item(child, diagnostics)) - .collect() - }) - .unwrap_or_default(); - Some(JavaTestItem { - id, - label, - full_name, - project_name, - test_kind, - test_level, - jdt_handler: optional_string(object.get("jdtHandler")), - sort_text: optional_string(object.get("sortText")), - range: object.get("range").and_then(normalize_range), - children, - }) -} - -fn optional_string(value: Option<&Value>) -> Option { - value - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string) -} - -fn integer_value(value: Option<&Value>) -> Option { - value.and_then(|value| { - value - .as_i64() - .or_else(|| value.as_str().and_then(|text| text.parse().ok())) - }) -} - -fn normalize_range(value: &Value) -> Option { - let start = value.get("start")?; - let end = value.get("end")?; - Some(JavaTestRange { - start_line: integer_value(start.get("line"))?, - start_utf16_column: integer_value(start.get("character"))?, - end_line: integer_value(end.get("line"))?, - end_utf16_column: integer_value(end.get("character"))?, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn command_passes_the_document_uri_to_java_test() { - assert_eq!( - java_test_items_command("file:///work/src/Composed.java"), - json!({ - "command": "vscode.java.test.findTestTypesAndMethods", - "arguments": ["file:///work/src/Composed.java"] - }) - ); - } - - #[test] - fn normalizes_classes_methods_and_utf16_ranges_without_semantic_guessing() { - let result = json!([{ - "id": "class-id", - "label": "OddlyNamedSpec", - "fullName": "demo.OddlyNamedSpec", - "projectName": "app", - "testKind": 0, - "testLevel": "5", - "jdtHandler": "=app/src, - /// Files added, changed, or removed since the previous observation. - #[serde(default)] - pub changed_paths: Vec, -} - -#[derive(Debug, Clone, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Shared Java workspace activation and change plan. -pub(crate) struct JavaWorkspacePolicyResponse { - /// Whether the workspace is a Java project that JDT LS should be started for. - /// - /// Requires a Java source *and* evidence that Java is what the workspace is - /// for: a build descriptor near the root, or a Java source near the root for - /// projects that have no build system at all. A lone Java file deep inside a - /// repository of another ecosystem does not qualify. - pub should_start: bool, - /// Deterministically selected Java source used only to attach the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub representative_java_path: Option, - /// Deterministically ordered classifications for the supplied changes. - pub changes: Vec, -} - -#[derive(Debug, Clone, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -/// One normalized changed path and the action category it belongs to. -pub(crate) struct JavaWorkspaceChange { - /// Normalized workspace-relative path with `/` separators. - pub path: String, - /// Shared semantic category consumed by platform workflow adapters. - pub kind: JavaWorkspaceChangeKind, -} - -#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Java workspace reaction required for one changed path. -pub(crate) enum JavaWorkspaceChangeKind { - /// An ignored output, dependency, metadata, or linked-worktree path. - Ignored, - /// A Java document synchronized through versioned LSP document events. - Source, - /// Maven or Gradle structure that requires a debounced project refresh. - BuildConfiguration, - /// A workspace file that does not affect the Java project model. - Other, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Filesystem metadata used to select expired JDT LS workspace directories. -pub(crate) struct JdtCacheRetentionRequest { - /// Unix timestamp supplied by the platform clock. - pub now_unix_seconds: u64, - /// Workspace key currently owned by a running session and never removable. - #[serde(default)] - pub active_workspace_key: Option, - /// Candidate directories discovered by the platform filesystem adapter. - #[serde(default)] - pub entries: Vec, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Modification metadata for one candidate JDT LS workspace directory. -pub(crate) struct JdtCacheEntry { - /// SHA-256 workspace directory name produced by `lsp.jdtWorkspaceKey`. - pub workspace_key: String, - /// Last modification time reported by the host filesystem. - pub last_modified_unix_seconds: u64, -} - -#[derive(Debug, Clone, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Deterministically ordered JDT LS directories that a platform may remove. -pub(crate) struct JdtCacheRetentionResponse { - /// Stable product retention period exposed for diagnostics and tests. - pub retention_days: u64, - /// Valid inactive workspace keys older than the retention period. - pub expired_workspace_keys: Vec, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Platform-observed inputs used to derive one portable JDT LS workspace fingerprint. -pub(crate) struct JdtWorkspaceFingerprintRequest { - /// Root build descriptors observed without recursive filesystem traversal. - #[serde(default)] - pub build_files: Vec, - /// Names of direct child directories that contain a Maven descriptor. - #[serde(default)] - pub direct_maven_modules: Vec, - /// `distributionUrl` of the root `gradle/wrapper/gradle-wrapper.properties`, - /// when present. Unlike edits to build scripts, which JDT LS notices on - /// restart, a Gradle version change is invisible to its import check, so - /// the version itself selects a fresh state directory. - #[serde(default)] - pub gradle_wrapper_distribution: Option, - /// JDT LS version resolved by the platform package adapter. - pub jdtls_version: String, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -/// One root-level Java build descriptor that exists in the workspace. -/// -/// Only its presence counts. Edits to a descriptor are JDT LS's to detect: on a -/// restart it compares each POM and Gradle file's timestamp with the state it -/// saved and updates only the projects that changed, and while running it -/// receives the change through `workspace/didChangeWatchedFiles`. Mixing the -/// timestamp into the state-directory name would discard the whole index after -/// any touch of the file, a `git checkout` included. -pub(crate) struct JdtBuildFileObservation { - /// Workspace-relative build descriptor path with `/` separators. - pub path: String, -} - -#[derive(Debug, Clone, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -/// Stable opaque fingerprint consumed by JDT LS workspace-key derivation. -pub(crate) struct JdtWorkspaceFingerprintResponse { - /// Opaque deterministic value that platforms pass back without parsing. - pub workspace_fingerprint: String, -} - -/// Builds the cross-platform Java activation and change-classification plan. -pub(crate) fn java_workspace_policy( - request: JavaWorkspacePolicyRequest, -) -> Result { - let workspace_paths = normalize_paths(request.workspace_paths)?; - let changed_paths = normalize_paths(request.changed_paths)?; - let representative_java_path = workspace_paths - .iter() - .find(|path| !is_ignored(path) && is_java_source(path)) - .cloned(); - // A stray `.java` file does not make a Java project. Fixtures, samples, and - // vendored snippets appear routinely in repositories of other ecosystems, and - // starting JDT LS for one costs a JVM, a full workspace import, and a cache - // directory retained for `JDT_CACHE_RETENTION_DAYS`. Require positive evidence - // instead. Opening a Java file in the editor stays extension-based on the host - // side, so an unrecognized project still gets language support on demand. - let describes_java_project = workspace_paths.iter().any(|path| { - is_activating_build_file(path) - || (!is_ignored(path) - && is_java_source(path) - && directory_depth(path) <= MAX_ACTIVATION_DEPTH) - }); - let changes = changed_paths - .into_iter() - .map(|path| JavaWorkspaceChange { - kind: classify_change(&path), - path, - }) - .collect(); - - Ok(JavaWorkspacePolicyResponse { - should_start: representative_java_path.is_some() && describes_java_project, - representative_java_path, - changes, - }) -} - -/// Reduces platform filesystem observations to the shared JDT LS fingerprint format. -pub(crate) fn jdt_workspace_fingerprint( - request: JdtWorkspaceFingerprintRequest, -) -> Result { - let version = request.jdtls_version.trim(); - if version.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The JDT LS version must not be empty.", - )); - } - - let build_files = request - .build_files - .into_iter() - .map(|observation| normalize_relative_path(&observation.path)) - .collect::, _>>()?; - let modules = request - .direct_maven_modules - .into_iter() - .map(|module| normalize_module_name(&module)) - .collect::, _>>()?; - let build_files = build_files.into_iter().collect::>().join(","); - let modules = modules.into_iter().collect::>().join(","); - let mut workspace_fingerprint = - format!("build={build_files}|modules={modules}|jdtls={version}"); - if let Some(distribution) = request.gradle_wrapper_distribution { - let distribution = distribution.trim(); - if distribution.is_empty() { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The Gradle wrapper distribution must not be empty.", - )); - } - // Appended only when present, so workspaces without a wrapper keep - // the state directory they already have. - workspace_fingerprint.push_str("|gradle="); - workspace_fingerprint.push_str(distribution); - } - - Ok(JdtWorkspaceFingerprintResponse { - workspace_fingerprint, - }) -} - -/// Selects inactive JDT LS workspace caches older than the shared retention period. -pub(crate) fn jdt_cache_retention( - request: JdtCacheRetentionRequest, -) -> Result { - if let Some(active_key) = request.active_workspace_key.as_deref() { - validate_workspace_key(active_key)?; - } - - // Duplicate observations are reduced to the newest timestamp so a stale - // filesystem event cannot delete a directory that was subsequently reused. - let mut newest_by_key = BTreeMap::new(); - for entry in request.entries { - if !is_workspace_key(&entry.workspace_key) { - continue; - } - newest_by_key - .entry(entry.workspace_key) - .and_modify(|timestamp: &mut u64| { - *timestamp = (*timestamp).max(entry.last_modified_unix_seconds) - }) - .or_insert(entry.last_modified_unix_seconds); - } - let retention_seconds = JDT_CACHE_RETENTION_DAYS * SECONDS_PER_DAY; - let expired_workspace_keys = newest_by_key - .into_iter() - .filter_map(|(workspace_key, last_modified)| { - let is_active = request.active_workspace_key.as_deref() == Some(workspace_key.as_str()); - let age = request.now_unix_seconds.saturating_sub(last_modified); - (!is_active && age > retention_seconds).then_some(workspace_key) - }) - .collect(); - - Ok(JdtCacheRetentionResponse { - retention_days: JDT_CACHE_RETENTION_DAYS, - expired_workspace_keys, - }) -} - -fn validate_workspace_key(value: &str) -> Result<(), CoreError> { - if is_workspace_key(value) { - Ok(()) - } else { - Err(CoreError::new( - ErrorCode::InvalidRequest, - "The active JDT LS workspace key must be a lowercase SHA-256 value.", - )) - } -} - -fn is_workspace_key(value: &str) -> bool { - value.len() == 64 - && value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) -} - -fn normalize_paths(paths: Vec) -> Result, CoreError> { - paths - .into_iter() - .map(|path| normalize_relative_path(&path)) - .collect::, _>>() - .map(BTreeSet::into_iter) - .map(Iterator::collect) -} - -fn normalize_relative_path(path: &str) -> Result { - let normalized = path.trim().replace('\\', "/"); - let normalized = normalized.trim_start_matches("./"); - let is_windows_absolute = normalized - .as_bytes() - .get(1) - .is_some_and(|separator| *separator == b':'); - if normalized.is_empty() - || normalized.starts_with('/') - || is_windows_absolute - || normalized - .split('/') - .any(|component| component.is_empty() || matches!(component, "." | "..")) - { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Java workspace paths must be workspace-relative.", - ) - .with_details(path.to_string())); - } - Ok(normalized.to_string()) -} - -fn normalize_module_name(value: &str) -> Result { - let normalized = value.trim(); - if normalized.is_empty() || normalized.contains(['/', '\\']) || matches!(normalized, "." | "..") - { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Direct Maven module names must be single path components.", - ) - .with_details(value.to_string())); - } - Ok(normalized.to_string()) -} - -fn classify_change(path: &str) -> JavaWorkspaceChangeKind { - if is_ignored(path) { - JavaWorkspaceChangeKind::Ignored - } else if is_java_source(path) { - JavaWorkspaceChangeKind::Source - } else if is_build_configuration(path) { - JavaWorkspaceChangeKind::BuildConfiguration - } else { - JavaWorkspaceChangeKind::Other - } -} - -fn is_ignored(path: &str) -> bool { - path.split('/').any(|component| { - let component = component.to_ascii_lowercase(); - IGNORED_DIRECTORIES.contains(&component.as_str()) - }) -} - -fn is_java_source(path: &str) -> bool { - path.rsplit_once('.') - .is_some_and(|(_, extension)| extension.eq_ignore_ascii_case("java")) -} - -/// Number of directories between the workspace root and `path`. -/// -/// Root-level files are depth zero, matching the workspace-relative path format -/// that every host normalizes to before calling in. -fn directory_depth(path: &str) -> usize { - path.matches('/').count() -} - -/// Whether `path` is a build descriptor close enough to the root to describe the -/// opened project. -/// -/// Only file names count. `is_build_configuration` additionally treats any `.mvn` -/// or `gradle` directory component as build configuration, which is correct for -/// invalidating a cached project model but too loose for activation: an unrelated -/// `docs/gradle/` directory would otherwise start JDT LS. -fn is_activating_build_file(path: &str) -> bool { - if is_ignored(path) || directory_depth(path) > MAX_ACTIVATION_DEPTH { - return false; - } - path.rsplit('/') - .next() - .map(|name| name.to_ascii_lowercase()) - .is_some_and(|name| BUILD_FILE_NAMES.contains(&name.as_str())) -} - -fn is_build_configuration(path: &str) -> bool { - let components: Vec<_> = path.split('/').collect(); - let file_name = components - .last() - .map(|component| component.to_ascii_lowercase()) - .unwrap_or_default(); - BUILD_FILE_NAMES.contains(&file_name.as_str()) - || components.iter().any(|component| { - component.eq_ignore_ascii_case(".mvn") || component.eq_ignore_ascii_case("gradle") - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn should_start(paths: &[&str]) -> bool { - java_workspace_policy(JavaWorkspacePolicyRequest { - workspace_paths: paths.iter().map(|path| path.to_string()).collect(), - changed_paths: Vec::new(), - }) - .expect("valid workspace paths must produce a policy") - .should_start - } - - #[test] - fn starts_for_projects_that_declare_a_java_build_near_the_root() { - // Conventional source layouts put sources well below MAX_ACTIVATION_DEPTH, - // so activation has to come from the descriptor rather than the sources. - assert!(should_start(&[ - "pom.xml", - "src/main/java/com/example/demo/DemoApplication.java", - ])); - assert!(should_start(&[ - "services/backend/build.gradle.kts", - "services/backend/src/main/java/com/example/App.java", - ])); - } - - #[test] - fn does_not_start_for_java_fixtures_checked_into_another_ecosystem() { - // Regression for this repository: a Swift, Rust, and TypeScript product - // that checks a sample Maven project into `shared/fixtures/`. Every such - // workspace used to start JDT LS and import the fixture as a real project. - assert!(!should_start(&[ - "Package.swift", - "Cargo.toml", - "shared/fixtures/projects/demo/pom.xml", - "shared/fixtures/projects/demo/src/main/java/com/example/demo/DemoApplication.java", - ])); - } - - #[test] - fn starts_for_java_sources_that_have_no_build_system() { - // Single-file programs and standalone `main` classes are supported by the - // run configuration layer, so language support must not require Maven or - // Gradle to be present. - assert!(should_start(&["Main.java"])); - assert!(should_start(&["src/Main.java"])); - } - - #[test] - fn ignores_build_descriptors_and_sources_under_ignored_directories() { - // Build output carries copies of both descriptors and sources. Treating - // them as evidence would reactivate on exactly the trees the ignore list - // exists to exclude. - assert!(!should_start(&[ - "target/pom.xml", - "target/classes/Main.java" - ])); - assert!(!should_start(&["node_modules/pkg/pom.xml"])); - } - - #[test] - fn requires_a_java_source_even_when_a_build_descriptor_exists() { - // A Gradle or Maven build in a Kotlin-only or resources-only repository - // has nothing for JDT LS to open. - assert!(!should_start(&["pom.xml", "src/main/kotlin/App.kt"])); - } - - #[test] - fn rejects_paths_that_escape_or_replace_the_workspace_root() { - for path in ["../Main.java", "/tmp/Main.java", "C:/work/Main.java"] { - let error = java_workspace_policy(JavaWorkspacePolicyRequest { - workspace_paths: vec![path.to_string()], - changed_paths: Vec::new(), - }) - .expect_err("absolute and escaping paths must be rejected"); - assert!(matches!(error.code, ErrorCode::InvalidRequest)); - } - } - - #[test] - fn rejects_invalid_workspace_fingerprint_observations() { - for request in [ - JdtWorkspaceFingerprintRequest { - build_files: vec![JdtBuildFileObservation { - path: "../pom.xml".to_string(), - }], - direct_maven_modules: Vec::new(), - gradle_wrapper_distribution: None, - jdtls_version: "1.38.0".to_string(), - }, - JdtWorkspaceFingerprintRequest { - build_files: Vec::new(), - direct_maven_modules: vec!["nested/core".to_string()], - gradle_wrapper_distribution: None, - jdtls_version: "1.38.0".to_string(), - }, - JdtWorkspaceFingerprintRequest { - build_files: Vec::new(), - direct_maven_modules: Vec::new(), - gradle_wrapper_distribution: None, - jdtls_version: " ".to_string(), - }, - JdtWorkspaceFingerprintRequest { - build_files: Vec::new(), - direct_maven_modules: Vec::new(), - gradle_wrapper_distribution: Some(" ".to_string()), - jdtls_version: "1.38.0".to_string(), - }, - ] { - let error = jdt_workspace_fingerprint(request) - .expect_err("invalid fingerprint observations must be rejected"); - assert!(matches!(error.code, ErrorCode::InvalidRequest)); - } - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt.rs b/rust/lithe-core/src/lsp/languages/jdt.rs deleted file mode 100644 index ac6f4a4ba7..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt.rs +++ /dev/null @@ -1,2753 +0,0 @@ -//! JDT LS-specific policy kept outside the generic LSP client and transport. -//! -//! The adapter is deliberately pure: it describes launch arguments, provider -//! notifications, configuration responses, and virtual-source requests. The -//! process engine remains responsible for creating directories and performing -//! all I/O. - -#![allow(dead_code)] // This module is an engine adapter seam; integration is intentionally separate. - -use crate::lsp::JavaRuntimeCandidate; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Map, Value}; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; -use url::Url; - -const JAVA_PROVIDER_ID: &str = "java"; -const JDT_URI_SCHEME: &str = "jdt"; -const JDTLS_DATA_DIRECTORY: &str = "jdtls"; -const JAVA_DECOMPILE_COMMAND: &str = "java.decompile"; -const DID_CHANGE_CONFIGURATION_METHOD: &str = "workspace/didChangeConfiguration"; -/// JDT LS extension that force-updates the listed projects' build configuration. -const PROJECT_CONFIGURATIONS_UPDATE_METHOD: &str = "java/projectConfigurationsUpdate"; -const LANGUAGE_STATUS_METHOD: &str = "language/status"; -const WORK_DONE_PROGRESS_METHOD: &str = "$/progress"; -const SERVICE_READY_STATUS: &str = "ServiceReady"; -const ERROR_STATUS: &str = "Error"; -/// JVM system property read by JDT LS's `org.eclipse.jdt.ls.filesystem` bundle. -/// -/// When the property is absent, JDT LS writes `.project`, `.classpath`, -/// `.factorypath`, and `.settings/*.prefs` into every imported module directory. -/// `false` redirects them to the `-data` metadata area, so opening a project -/// never adds Eclipse files to the user's tree. Files that already exist at a -/// module root still take precedence; `jdt_project_metadata` removes those. -const METADATA_AT_PROJECT_ROOT_PROPERTY: &str = "-Djava.import.generatesMetadataFilesAtProjectRoot"; -/// Heap ceiling passed to the JDT LS JVM on both launch paths. -/// -/// JDT LS switches to a batched, memory-frugal Maven import as soon as its -/// maximum heap is at most 1.5 GB. That path hands a `null` project to -/// `IProject.open` when several modules share `groupId` and `artifactId`, which -/// fails the whole Java service instead of the affected modules. Keep the -/// ceiling above that threshold, and at the 2 GB upstream documents for the -/// language server, so a normal multi-module workspace imports through the -/// regular path. -const JDTLS_MAX_HEAP_ARGUMENT: &str = "-Xmx2048m"; - -/// JDT LS readiness transition conveyed through its `language/status` -/// extension after the standard LSP initialize handshake. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) enum JdtReadinessSignal { - /// Project import and Java service initialization have completed. - Ready, - /// JDT LS reported that its Java service could not become usable. - Failed(String), -} - -/// Maven artifact transfer details extracted from JDT LS work-done progress. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) struct JdtDownloadProgress { - /// File name only; repository URLs can contain credentials or private hosts. - pub artifact: String, - /// Repository host without path, query, or credentials. - pub repository_host: Option, - /// Bytes transferred according to JDT LS, when its progress includes a size pair. - pub downloaded_bytes: Option, - /// Expected artifact size according to JDT LS, when the server reports it. - pub total_bytes: Option, -} - -/// Observable Java workspace-import activity derived from standard progress events. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) struct JdtImportProgress { - /// Stable signature used to ignore duplicate progress notifications. - pub activity_signature: String, - /// JDT LS work phase such as Maven import or classpath setup. - pub phase: Option, - /// Outer workspace-import percentage, which can stay fixed during downloads. - pub percentage: Option, - /// Current Maven project when JDT LS includes it in the progress message. - pub current_project: Option, - /// Current artifact transfer, if the progress message contains a repository URL. - pub download: Option, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JdtStartContext { - pub provider_id: String, - pub workspace_root: PathBuf, - /// Engine-owned cache/state root. The adapter only derives a child path. - pub data_root: PathBuf, - #[serde(default)] - pub selected_java_executable: Option, - #[serde(default)] - pub direct_launch_resources: Option, - #[serde(default)] - pub arguments: Vec, - /// Opaque platform-provided digest of the build-system inputs that decide - /// how JDT LS will import the workspace: root build files and the set of - /// module directories, plus the bundled JDT LS version. - /// - /// JDT LS never invalidates its own `-data` state, so a workspace that - /// gains or loses a module keeps resolving against a stale project model - /// and silently loses cross-module navigation. Mixing this digest into the - /// state-directory name gives structurally different workspaces different - /// directories while keeping the previous one intact for a later switch - /// back. `None` preserves the pre-fingerprint directory name so existing - /// caches stay valid. - #[serde(default)] - pub workspace_fingerprint: Option, -} - -/// Maven import settings already validated by the shared project domain. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) struct JdtMavenConfiguration { - /// Optional machine-local Maven settings file consumed by JDT LS. - pub settings_path: Option, - /// Optional `conf/settings.xml` of the Maven installation this workspace - /// runs. It carries the local repository and mirrors that the command line - /// already uses, so JDT LS must resolve artifacts through the same file. - pub global_settings_path: Option, - /// Sorted, de-duplicated Maven profile IDs selected for this workspace. - pub profiles: Vec, - /// Deterministically ordered reactor and recursive-module directory URIs. - pub project_uris: Vec, - /// Workspace-relative Java source directories discovered from Maven POMs. - pub source_paths: Vec, -} - -/// Gradle import settings Lithe owns in JDT LS's `settings.java`. -#[derive(Debug, Clone, Default, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub(crate) struct JdtGradleConfiguration { - /// The workspace root ships the wrapper descriptor Buildship reads - /// (`gradle/wrapper/gradle-wrapper.properties`). - /// - /// Telling Buildship a wrapper exists only restates its own default: the - /// distribution still comes from that descriptor. The wrapper is a property - /// of the workspace root and does not change for the lifetime of a session. - pub wrapper_present: bool, - /// The user turned on the build system's offline option, so Buildship - /// resolves from its caches as the user's own Gradle runs do. - #[serde(default)] - pub offline: bool, - /// The Gradle user home the user chose for the build system; `None` - /// keeps Buildship's default. - #[serde(default)] - pub user_home: Option, -} - -/// A JDK JDT LS may bind a project to, keyed by its execution environment. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) struct JdtJavaRuntime { - /// Selected project VM; at most one runtime is the default. - pub is_default: bool, - /// Execution-environment name such as `JavaSE-25` or `JavaSE-1.8`; JDT LS - /// matches it against the release a project compiles for. - pub name: String, - /// JDK home directory. - pub path: String, -} - -/// Values Lithe owns in JDT LS's `settings.java`, borrowed from one session. -#[derive(Debug, Clone, Copy, Default)] -pub(crate) struct JdtSettings<'a> { - /// Workspace indexing policy, when the host has installed one. - pub indexing_root_uri: Option<&'a str>, - /// Plugin-declared completion options from this session's initialization; - /// all leaves survive except the provider-owned guessMethodArguments. - pub completion: Option<&'a Value>, - /// Original plugin import exclusions, before Lithe overlays the workspace policy. - pub import_exclusions: Option<&'a Value>, - pub maven: Option<&'a JdtMavenConfiguration>, - /// Gradle import settings, present only for Gradle workspaces. - pub gradle: Option<&'a JdtGradleConfiguration>, - /// JDKs installed on this machine, at most one per execution environment. - pub java_runtimes: &'a [JdtJavaRuntime], -} - -/// Picks one JDK per Java major version for `java.configuration.runtimes`. -/// -/// Without these, JDT LS knows only the JDK it runs on, so a project that -/// compiles for a newer release fails with "release N is not found in the -/// system" even though that JDK is installed. The first valid default wins its -/// major; otherwise, the first JDK listed for that major wins. Platforms order -/// candidates by preference. Versions that do not parse are skipped, not guessed. -pub(crate) fn jdt_java_runtimes(candidates: &[JavaRuntimeCandidate]) -> Vec { - let selected = candidates.iter().find(|candidate| { - candidate.is_default - && !candidate.home_path.trim().is_empty() - && java_major_version(&candidate.version).is_some() - }); - let mut by_major = BTreeMap::new(); - // The explicit selection wins even over another installation of the same major. - for candidate in selected.into_iter().chain(candidates) { - let Some(major) = java_major_version(&candidate.version) else { - continue; - }; - if candidate.home_path.trim().is_empty() { - continue; - } - by_major.entry(major).or_insert(candidate); - } - by_major - .into_iter() - .map(|(major, candidate)| JdtJavaRuntime { - name: if major == 8 { - "JavaSE-1.8".to_string() - } else { - format!("JavaSE-{major}") - }, - path: candidate.home_path.trim().to_string(), - is_default: selected.is_some_and(|chosen| std::ptr::eq(chosen, candidate)), - }) - .collect() -} - -/// Major version of a `java -version` string: `25.0.4` → 25, `1.8.0_402` → 8. -/// Versions before 8 have no JDT execution environment Lithe supports. -fn java_major_version(version: &str) -> Option { - let mut parts = version - .trim() - .split(|character: char| !character.is_ascii_digit()); - let first = parts.next()?.parse::().ok()?; - let major = if first == 1 { - parts.next()?.parse::().ok()? - } else { - first - }; - (major >= 8).then_some(major) -} - -/// Lifecycle of the post-ServiceReady Maven profile task. -#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) enum MavenProfileTaskStatus { - Idle, - Running, - PartiallySucceeded, - Succeeded, - Failed, - TimedOut, - Cancelled, -} - -/// Stable result for one Maven project handled by the profile task. -#[derive(Debug, Clone, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct MavenProfileProjectResult { - pub project_uri: String, - pub status: MavenProfileTaskStatus, - #[serde(skip_serializing_if = "Option::is_none")] - pub error_details: Option, -} - -/// Produces a stable digest for the inputs that affect Maven profile updates. -/// The digest lets a warm session skip an identical update while retaining the -/// explicit retry path for failed or cancelled tasks. -pub(crate) fn maven_profile_fingerprint( - configuration: Option<&JdtMavenConfiguration>, -) -> Option { - let configuration = configuration?; - let payload = serde_json::to_vec(&json!({ - "settingsPath": configuration.settings_path, - "globalSettingsPath": configuration.global_settings_path, - "profiles": configuration.profiles, - "projectUris": configuration.project_uris, - "sourcePaths": configuration.source_paths, - })) - .ok()?; - Some(format!("{:x}", Sha256::digest(payload))) -} - -/// Platform-resolved files required to launch JDT LS without a shell wrapper. -#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JdtDirectLaunchResources { - pub launcher_jar_path: PathBuf, - /// Writable Equinox configuration area passed as `-configuration`. The - /// engine supplies the cache copy from `jdt_configuration`, never the - /// packaged directory, because Equinox writes its state here. - pub configuration_directory: PathBuf, - pub lombok_agent_path: PathBuf, - #[serde(default)] - pub java_debug_bundle_path: Option, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase")] -/// Request for the deterministic directory key used by JDT LS state. -pub(crate) struct JdtWorkspaceKeyRequest { - /// Absolute platform workspace path used only to derive a stable local key. - pub workspace_root: String, - /// Optional platform-computed build-structure digest mixed into the key. - #[serde(default)] - pub workspace_fingerprint: Option, -} - -#[derive(Debug, Clone, Serialize, Eq, PartialEq)] -#[serde(rename_all = "camelCase")] -/// Stable key returned to platform cache-maintenance adapters. -pub(crate) struct JdtWorkspaceKeyResponse { - /// Lowercase SHA-256 key naming the workspace's JDT LS state directory. - pub workspace_key: String, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JdtStartAdaptation { - #[serde(skip_serializing_if = "Option::is_none")] - pub executable: Option, - pub arguments: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub data_directory: Option, -} - -#[derive(Debug, Clone, Default, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct WorkspaceConfigurationItem { - #[serde(default)] - pub scope_uri: Option, - #[serde(default)] - pub section: Option, -} - -#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ProviderNotification { - pub method: String, - pub params: Value, -} - -#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ProviderLocation { - pub uri: String, - #[serde(default)] - pub is_read_only: bool, - #[serde(default)] - pub display_path: Option, -} - -#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ExecuteCommandParams { - pub command: String, - pub arguments: Vec, -} - -/// Applies the JDT LS-owned part of a provider start plan. -/// -/// `data_directory` is returned to the engine as a directory requirement; this -/// function never creates it. Arguments owned by this adapter are replaced so -/// repeated adaptation is deterministic and cannot leave two `-data` roots. -pub(crate) fn adapt_start(context: &JdtStartContext) -> JdtStartAdaptation { - if !is_java_provider(&context.provider_id) { - return JdtStartAdaptation { - executable: None, - arguments: context.arguments.clone(), - data_directory: None, - }; - } - - let data_directory = context - .data_root - .join(JDTLS_DATA_DIRECTORY) - .join(workspace_key( - &context.workspace_root, - context.workspace_fingerprint.as_deref(), - )); - let (executable, arguments) = match ( - &context.selected_java_executable, - &context.direct_launch_resources, - ) { - (Some(java_executable), Some(resources)) => ( - Some(java_executable.clone()), - direct_java_arguments(&context.arguments, resources, &data_directory), - ), - _ => ( - None, - wrapper_arguments( - &context.arguments, - context.selected_java_executable.as_deref(), - &data_directory, - ), - ), - }; - - JdtStartAdaptation { - executable, - arguments, - data_directory: Some(data_directory), - } -} - -/// Adds the JDT LS client extensions required for Java tooling. -/// -/// Catalog-provided options are preserved, while the provider-owned capability -/// is authoritative because virtual class files cannot be opened without it. -/// Extension bundles are appended in caller order without duplicating catalog -/// entries, which keeps Debug and Test plugin activation deterministic. -pub(crate) fn adapt_initialization_options( - provider_id: &str, - initialization_options: Option, - java_extension_bundle_paths: &[PathBuf], - settings: JdtSettings<'_>, -) -> Option { - if !is_java_provider(provider_id) { - return initialization_options; - } - - let mut options = match initialization_options { - Some(Value::Object(options)) => options, - _ => Map::new(), - }; - let extended = options - .entry("extendedClientCapabilities") - .or_insert_with(|| json!({})); - if !extended.is_object() { - *extended = json!({}); - } - extended - .as_object_mut() - .expect("the extended capabilities were normalized to an object") - .insert("classFileContentsSupport".to_string(), Value::Bool(true)); - - if !java_extension_bundle_paths.is_empty() { - let bundles = options - .entry("bundles") - .or_insert_with(|| Value::Array(Vec::new())); - if !bundles.is_array() { - *bundles = Value::Array(Vec::new()); - } - let bundles = bundles - .as_array_mut() - .expect("the Java extension bundles were normalized to an array"); - for bundle_path in java_extension_bundle_paths { - let bundle = Value::String(bundle_path.to_string_lossy().into_owned()); - if !bundles.contains(&bundle) { - bundles.push(bundle); - } - } - } - - // JDT LS configures its Maven embedder from `initializationOptions` while it - // handles `initialize`, and the project import starts immediately after. - // The same values sent later through `didChangeConfiguration` would arrive - // after that import already resolved every artifact against the embedded - // defaults, so the repository and mirrors must be present here as well. - merge_java_settings(&mut options, java_settings(settings)); - - Some(Value::Object(options)) -} - -/// Overlays the provider-owned `settings.java` values onto catalog-provided -/// initialization options. -/// -/// Catalog keys that the provider does not own are preserved, while the Maven, -/// build, completion, and code-lens values Lithe depends on stay authoritative. -fn merge_java_settings(options: &mut Map, provider_settings: Value) { - let settings = options.entry("settings").or_insert_with(|| json!({})); - if !settings.is_object() { - *settings = json!({}); - } - let settings = settings - .as_object_mut() - .expect("the settings value was normalized to an object"); - let java = settings.entry("java").or_insert_with(|| json!({})); - if !java.is_object() { - *java = json!({}); - } - let java = java - .as_object_mut() - .expect("the java settings were normalized to an object"); - let Some(provider_java) = provider_settings - .get("java") - .and_then(Value::as_object) - .cloned() - else { - return; - }; - for (key, value) in provider_java { - if key == "completion" { - let completion = java.entry(key).or_insert_with(|| json!({})); - if !completion.is_object() { - *completion = json!({}); - } - completion.as_object_mut().unwrap().extend( - value - .as_object() - .expect("completion settings are an object") - .clone(), - ); - continue; - } - // `java.import.gradle` is the only `import` leaf Lithe owns. The options - // Lithe deliberately never guesses (`java.home`, `version`, - // `offline.enabled`, ...) have to survive, so the owned leaves merge - // into the declared `import` object instead of replacing it. - if key == "import" { - if let Some(exclusions) = value.get("exclusions").and_then(Value::as_array) { - let import = java - .entry("import".to_string()) - .or_insert_with(|| json!({})); - if !import.is_object() { - *import = json!({}); - } - let mut combined = import - .get("exclusions") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - for exclusion in exclusions { - if !combined.contains(exclusion) { - combined.push(exclusion.clone()); - } - } - import["exclusions"] = json!(combined); - } - if let Some(gradle) = value.get("gradle").and_then(Value::as_object) { - let import = java - .entry("import".to_string()) - .or_insert_with(|| json!({})); - if !import.is_object() { - *import = json!({}); - } - let import = import - .as_object_mut() - .expect("the import value was normalized to an object"); - let declared_gradle = import - .entry("gradle".to_string()) - .or_insert_with(|| json!({})); - if !declared_gradle.is_object() { - *declared_gradle = json!({}); - } - let declared_gradle = declared_gradle - .as_object_mut() - .expect("the gradle value was normalized to an object"); - for (gradle_key, gradle_value) in gradle { - declared_gradle.insert(gradle_key.clone(), gradle_value.clone()); - } - continue; - } - } - if key == "import" && value.get("exclusions").is_some() { - continue; - } - java.insert(key, value); - } -} - -/// Returns JDT LS configuration values in the same order as the requested -/// `workspace/configuration` items. `None` delegates non-Java providers to the -/// generic engine behavior. -pub(crate) fn workspace_configuration( - provider_id: &str, - items: &[WorkspaceConfigurationItem], - settings: JdtSettings<'_>, -) -> Option> { - if !is_java_provider(provider_id) { - return None; - } - Some( - items - .iter() - .map(|item| java_configuration_for_section(item.section.as_deref(), settings)) - .collect(), - ) -} - -/// Notification the engine sends after the generic `initialized` handshake. -pub(crate) fn initialized_notification( - provider_id: &str, - settings: JdtSettings<'_>, -) -> Option { - is_java_provider(provider_id).then(|| settings_notification(settings)) -} - -/// `workspace/didChangeConfiguration` carrying every Java setting Lithe owns. -/// -/// When the Maven settings paths differ from the ones JDT LS holds, JDT LS -/// reloads them and force-updates every Maven project itself -/// (`StandardPreferenceManager.update`), including an import still in progress. -pub(crate) fn settings_notification(settings: JdtSettings<'_>) -> ProviderNotification { - ProviderNotification { - method: DID_CHANGE_CONFIGURATION_METHOD.to_string(), - params: json!({ - "settings": java_settings(settings) - }), - } -} - -/// Forces JDT LS to re-resolve the given Maven projects even though neither -/// their `pom.xml` nor the Maven settings changed. -/// -/// A JDT LS restart does not do this: its importer skips projects whose build -/// file is older than the saved workspace state, so dependencies that failed to -/// resolve stay missing. `java/projectConfigurationsUpdate` is the upstream -/// "update project" action and ignores that check. -pub(crate) fn project_update_notification( - configuration: &JdtMavenConfiguration, -) -> Option { - let mut seen = std::collections::BTreeSet::new(); - let identifiers = configuration - .project_uris - .iter() - .filter(|uri| seen.insert(uri.as_str())) - .map(|uri| json!({ "uri": uri })) - .collect::>(); - (!identifiers.is_empty()).then(|| ProviderNotification { - method: PROJECT_CONFIGURATIONS_UPDATE_METHOD.to_string(), - params: json!({ "identifiers": identifiers }), - }) -} - -/// Commands that apply the selected Maven profiles to every imported project. -pub(crate) fn maven_profile_update_requests( - configuration: Option<&JdtMavenConfiguration>, -) -> Vec { - let Some(configuration) = configuration else { - return Vec::new(); - }; - let profiles = configuration.profiles.join(","); - // Maven reactors can report the same project through both the root and a - // nested module scan. Preserve first-seen order while coalescing those - // duplicates so one project receives at most one update request. - let mut seen = std::collections::BTreeSet::new(); - configuration - .project_uris - .iter() - .filter(|uri| seen.insert(uri.as_str())) - .map(|uri| { - json!({ - "command": "java.project.updateSettings", - "arguments": [ - uri, - { "org.eclipse.m2e.core.selectedProfiles": profiles } - ] - }) - }) - .collect() -} - -/// Returns whether the provider has a readiness phase after standard LSP -/// initialization. JDT LS cannot safely serve semantic requests until its Java -/// project import publishes `ServiceReady`. -pub(crate) fn waits_for_service_ready(provider_id: &str) -> bool { - is_java_provider(provider_id) -} - -/// Reduces one JDT LS status notification to the readiness transition owned by -/// the generic process engine. Other providers and informational statuses do -/// not affect lifecycle state. -pub(crate) fn readiness_signal( - provider_id: &str, - method: Option<&str>, - params: Option<&Value>, -) -> Option { - if !is_java_provider(provider_id) || method != Some(LANGUAGE_STATUS_METHOD) { - return None; - } - let params = params?.as_object()?; - match params.get("type").and_then(Value::as_str) { - Some(SERVICE_READY_STATUS) => Some(JdtReadinessSignal::Ready), - Some(ERROR_STATUS) => Some(JdtReadinessSignal::Failed( - params - .get("message") - .and_then(Value::as_str) - .filter(|message| !message.trim().is_empty()) - .unwrap_or("JDT LS reported an unknown Java service error.") - .to_string(), - )), - _ => None, - } -} - -/// Extracts observability-only Maven import details from JDT LS `$/progress`. -/// -/// Lifecycle correctness must never depend on this parser because progress text -/// is owned by JDT LS and can change between releases. Readiness continues to -/// depend exclusively on `language/status: ServiceReady`. -pub(crate) fn import_progress( - provider_id: &str, - method: Option<&str>, - params: Option<&Value>, -) -> Option { - if !is_java_provider(provider_id) || method != Some(WORK_DONE_PROGRESS_METHOD) { - return None; - } - let value = params?.get("value")?; - let kind = value - .get("kind") - .and_then(Value::as_str) - .unwrap_or("report"); - let message = value - .get("message") - .and_then(Value::as_str) - .or_else(|| value.get("title").and_then(Value::as_str)) - .unwrap_or("") - .trim(); - let percentage = value.get("percentage").and_then(Value::as_u64); - if message.is_empty() && percentage.is_none() { - return None; - } - - Some(JdtImportProgress { - activity_signature: format!("{kind}|{}|{message}", percentage.unwrap_or(u64::MAX)), - phase: progress_phase(message), - percentage, - current_project: progress_project(message), - download: progress_download(message), - }) -} - -/// Returns whether a Java notification is replaced by structured import logs. -pub(crate) fn is_structured_import_notification(provider_id: &str, method: Option<&str>) -> bool { - is_java_provider(provider_id) - && matches!( - method, - Some(WORK_DONE_PROGRESS_METHOD | LANGUAGE_STATUS_METHOD) - ) -} - -fn progress_phase(message: &str) -> Option { - let phase = message - .split_once(" - ") - .map_or(message, |(phase, _)| phase) - .trim(); - (!phase.is_empty()).then(|| phase.to_string()) -} - -fn progress_project(message: &str) -> Option { - if let Some((_, project)) = message.split_once("Importing project ") { - let project = project.trim().trim_matches('\''); - return (!project.is_empty()).then(|| project.to_string()); - } - let (_, quoted) = message.split_once("Project '")?; - let (project, _) = quoted.split_once('\'')?; - let project = project.trim(); - (!project.is_empty()).then(|| project.to_string()) -} - -fn progress_download(message: &str) -> Option { - let url_text = message - .split_whitespace() - .find(|part| part.starts_with("https://") || part.starts_with("http://"))? - .trim_end_matches(|character: char| matches!(character, ',' | ';' | ')' | ']')); - let url = Url::parse(url_text).ok()?; - let artifact = url - .path_segments() - .and_then(|mut segments| segments.next_back()) - .filter(|segment| !segment.is_empty())? - .to_string(); - let sizes = message.split_whitespace().find_map(parse_size_pair); - Some(JdtDownloadProgress { - artifact, - repository_host: url.host_str().map(ToString::to_string), - downloaded_bytes: sizes.map(|(downloaded, _)| downloaded), - total_bytes: sizes.map(|(_, total)| total), - }) -} - -fn parse_size_pair(value: &str) -> Option<(u64, u64)> { - if value.starts_with("http://") || value.starts_with("https://") { - return None; - } - let value = value.trim_matches(|character: char| matches!(character, '(' | ')' | ',' | ';')); - let (downloaded, total) = value.split_once('/')?; - Some((parse_byte_count(downloaded)?, parse_byte_count(total)?)) -} - -fn parse_byte_count(value: &str) -> Option { - let number_end = value - .find(|character: char| !character.is_ascii_digit() && character != '.') - .unwrap_or(value.len()); - let number = value[..number_end].parse::().ok()?; - let multiplier = match value[number_end..].to_ascii_uppercase().as_str() { - "B" => 1_f64, - "KB" | "KIB" => 1024_f64, - "MB" | "MIB" => 1024_f64 * 1024_f64, - "GB" | "GIB" => 1024_f64 * 1024_f64 * 1024_f64, - _ => return None, - }; - Some((number * multiplier).round() as u64) -} - -/// Marks JDT virtual locations as read-only and gives them a source-like path. -/// File locations and locations from other providers pass through unchanged. -pub(crate) fn normalize_location( - provider_id: &str, - mut location: ProviderLocation, -) -> ProviderLocation { - if is_java_provider(provider_id) && has_uri_scheme(&location.uri, JDT_URI_SCHEME) { - location.is_read_only = true; - location.display_path = jdt_display_path(&location.uri); - } - location -} - -/// Converts a JDT virtual URI into `workspace/executeCommand` parameters. The -/// generic engine owns request IDs and JSON-RPC framing. -pub(crate) fn virtual_source_resolve_params( - provider_id: &str, - uri: &str, -) -> Option { - if !is_virtual_source_uri(provider_id, uri) { - return None; - } - Some(ExecuteCommandParams { - command: JAVA_DECOMPILE_COMMAND.to_string(), - arguments: vec![json!(uri)], - }) -} - -/// Returns whether a URI names a virtual source document owned by JDT LS. -pub(crate) fn is_virtual_source_uri(provider_id: &str, uri: &str) -> bool { - is_java_provider(provider_id) && has_uri_scheme(uri, JDT_URI_SCHEME) -} - -/// Extracts the text shape returned by JDT LS for `java.decompile`. -/// Different JDT LS versions return either the string directly or wrap it in -/// a `content` member. -pub(crate) fn virtual_source_content(provider_id: &str, result: &Value) -> Option { - if !is_java_provider(provider_id) { - return None; - } - result - .as_str() - .or_else(|| result.get("content").and_then(Value::as_str)) - .filter(|content| !content.is_empty()) - .map(str::to_string) -} - -fn is_java_provider(provider_id: &str) -> bool { - provider_id.trim().eq_ignore_ascii_case(JAVA_PROVIDER_ID) -} - -/// Maximum heap used when the plugin does not choose one, or chooses one the -/// host cannot accept. See `JDTLS_MAX_HEAP_ARGUMENT` for why it is 2 GB. -const DEFAULT_MAX_HEAP_ARGUMENT: &str = JDTLS_MAX_HEAP_ARGUMENT; -/// JDT LS runs its constrained-memory import at or below this heap, so no -/// plugin choice at or below it is accepted. -const CONSTRAINED_HEAP_MEBIBYTES: u64 = 1536; -const MAX_HEAP_PREFIX: &str = "-Xmx"; -/// Language-server log level used when the plugin does not choose one. -const DEFAULT_LOG_LEVEL_ARGUMENT: &str = "-Dlog.level=WARNING"; -const LOG_LEVEL_PREFIX: &str = "-Dlog.level="; -/// JVM defaults vscode-java and the JDT LS CI launch the language server with. -/// -/// The throughput collector with a 20% GC-time budget and a slowly adapting -/// size policy returns heap to the OS once an import settles, instead of -/// holding the 2 GB ceiling for the life of the session. `-Xlog:disable` keeps -/// JVM warnings off stdout, which carries the LSP stream. The installed-VM -/// scan is redundant because the host sends `java.configuration.runtimes`. -/// A plugin option with the same key replaces the default; see -/// `tuning_arguments`. -const JDTLS_TUNING_ARGUMENTS: [&str; 5] = [ - "-XX:+UseParallelGC", - "-XX:GCTimeRatio=4", - "-XX:AdaptiveSizePolicyWeight=90", - "-Xlog:disable", - "-DDetectVMInstallationsJob.disabled=true", -]; - -/// Removes every argument starting with `prefix` and returns the last one -/// that is acceptable. The JVM honors the last occurrence, so that is the one -/// the plugin meant; an unacceptable value is dropped so the host default -/// stays in force. -fn take_plugin_choice( - arguments: &mut Vec, - prefix: &str, - acceptable: fn(&str) -> bool, -) -> Option { - let choice = arguments - .iter() - .rev() - .find(|argument| { - argument - .strip_prefix(prefix) - .is_some_and(|value| acceptable(value)) - }) - .cloned(); - arguments.retain(|argument| !argument.starts_with(prefix)); - choice -} - -/// A JVM heap size (digits and an optional `k`, `m`, or `g` unit) above the -/// size at which JDT LS switches to its constrained-memory import. A smaller -/// choice is dropped so the host default stays in force. -fn is_heap_size(value: &str) -> bool { - let digits = value.trim_end_matches(['k', 'K', 'm', 'M', 'g', 'G']); - if digits.is_empty() - || value.len() - digits.len() > 1 - || !digits.chars().all(|character| character.is_ascii_digit()) - { - return false; - } - let Ok(amount) = digits.parse::() else { - return false; - }; - let mebibytes = match value[digits.len()..].to_ascii_lowercase().as_str() { - "k" => amount / 1024, - "m" => amount, - "g" => amount.saturating_mul(1024), - _ => amount / (1024 * 1024), - }; - mebibytes > CONSTRAINED_HEAP_MEBIBYTES -} - -/// Returns the tuning defaults the plugin's JVM options leave unset. An option -/// with the same key replaces a default, and any garbage-collector selection -/// replaces the default collector, since the JVM refuses two collectors. -fn tuning_arguments(custom_jvm_arguments: &[String]) -> Vec { - let chooses_collector = custom_jvm_arguments - .iter() - .any(|argument| is_collector_selection(argument)); - JDTLS_TUNING_ARGUMENTS - .iter() - .filter(|default| !(chooses_collector && is_collector_selection(default))) - .filter(|default| { - let key = jvm_option_key(default); - !custom_jvm_arguments - .iter() - .any(|argument| jvm_option_key(argument) == key) - }) - .map(|default| default.to_string()) - .collect() -} - -/// A tuning default exactly as the host writes it. It is host-owned, so a -/// relaunch rebuilds it instead of reading it back as a plugin choice. -fn is_tuning_default(argument: &str) -> bool { - JDTLS_TUNING_ARGUMENTS.contains(&argument) -} - -fn is_collector_selection(argument: &str) -> bool { - argument - .strip_prefix("-XX:") - .and_then(|option| option.strip_prefix(['+', '-'])) - .is_some_and(|option| option.starts_with("Use") && option.ends_with("GC")) -} - -/// The part of a JVM option that identifies it regardless of its value: -/// `-XX:` options by name without the `+`/`-` toggle, every `-Xlog` option as -/// one key because they combine into a single logging configuration, and other -/// options by the text before `=`. -fn jvm_option_key(argument: &str) -> String { - if let Some(option) = argument.strip_prefix("-XX:") { - let option = option.trim_start_matches(['+', '-']); - let name = option.split_once('=').map_or(option, |(name, _)| name); - return format!("-XX:{name}"); - } - if argument.starts_with("-Xlog") { - return "-Xlog".to_string(); - } - argument - .split_once('=') - .map_or(argument, |(name, _)| name) - .to_string() -} - -fn is_log_level(value: &str) -> bool { - !value.is_empty() - && value - .chars() - .all(|character| character.is_ascii_alphanumeric()) -} - -fn wrapper_arguments( - arguments: &[String], - java_executable: Option<&Path>, - data_directory: &Path, -) -> Vec { - let mut jvm_arguments: Vec = arguments - .iter() - .filter_map(|argument| argument.strip_prefix("--jvm-arg=")) - .map(str::to_string) - .collect(); - let max_heap = take_plugin_choice(&mut jvm_arguments, MAX_HEAP_PREFIX, is_heap_size) - .unwrap_or_else(|| DEFAULT_MAX_HEAP_ARGUMENT.to_string()); - jvm_arguments.retain(|argument| !is_tuning_default(argument)); - let tuning = tuning_arguments(&jvm_arguments); - let mut arguments = without_wrapper_owned_arguments(arguments); - if let Some(java_executable) = java_executable { - arguments.push("--java-executable".to_string()); - arguments.push(java_executable.to_string_lossy().into_owned()); - } - arguments.extend([ - "--jvm-arg=-Xms256m".to_string(), - format!("--jvm-arg={max_heap}"), - ]); - arguments.extend( - tuning - .into_iter() - .map(|argument| format!("--jvm-arg={argument}")), - ); - arguments.extend([ - format!("--jvm-arg={METADATA_AT_PROJECT_ROOT_PROPERTY}=false"), - "-data".to_string(), - data_directory.to_string_lossy().into_owned(), - ]); - arguments -} - -fn direct_java_arguments( - arguments: &[String], - resources: &JdtDirectLaunchResources, - data_directory: &Path, -) -> Vec { - let (mut custom_jvm_arguments, server_arguments) = - split_direct_launch_arguments(arguments, &resources.launcher_jar_path); - let max_heap = take_plugin_choice(&mut custom_jvm_arguments, MAX_HEAP_PREFIX, is_heap_size) - .unwrap_or_else(|| DEFAULT_MAX_HEAP_ARGUMENT.to_string()); - let log_level = take_plugin_choice(&mut custom_jvm_arguments, LOG_LEVEL_PREFIX, is_log_level) - .unwrap_or_else(|| DEFAULT_LOG_LEVEL_ARGUMENT.to_string()); - let mut adapted = vec![ - format!( - "-javaagent:{}", - resources.lombok_agent_path.to_string_lossy() - ), - "-Xms256m".to_string(), - max_heap, - ]; - adapted.extend(tuning_arguments(&custom_jvm_arguments)); - adapted.extend([ - "--add-modules=ALL-SYSTEM".to_string(), - "--add-opens=java.base/java.util=ALL-UNNAMED".to_string(), - "--add-opens=java.base/java.lang=ALL-UNNAMED".to_string(), - "-Declipse.application=org.eclipse.jdt.ls.core.id1".to_string(), - "-Declipse.product=org.eclipse.jdt.ls.core.product".to_string(), - "-Dosgi.bundles.defaultStartLevel=4".to_string(), - "-Dlog.protocol=true".to_string(), - log_level, - format!("{METADATA_AT_PROJECT_ROOT_PROPERTY}=false"), - ]); - adapted.extend(custom_jvm_arguments); - adapted.extend([ - "-jar".to_string(), - resources.launcher_jar_path.to_string_lossy().into_owned(), - "-configuration".to_string(), - resources - .configuration_directory - .to_string_lossy() - .into_owned(), - ]); - adapted.extend(server_arguments); - adapted.extend([ - "-data".to_string(), - data_directory.to_string_lossy().into_owned(), - ]); - adapted -} - -fn split_direct_launch_arguments( - arguments: &[String], - launcher_jar_path: &Path, -) -> (Vec, Vec) { - let launcher_jar_path = launcher_jar_path.to_string_lossy(); - let owned_launcher_index = arguments - .windows(2) - .position(|pair| pair[0] == "-jar" && pair[1] == launcher_jar_path.as_ref()); - let has_direct_layout = owned_launcher_index.is_some(); - let mut custom_jvm_arguments = Vec::new(); - let mut server_arguments = Vec::new(); - let mut after_launcher = false; - let mut index = 0; - while index < arguments.len() { - let argument = &arguments[index]; - if argument == "--java-executable" || argument == "-data" { - index += usize::from(index + 1 < arguments.len()) + 1; - continue; - } - if argument == "--jvm-arg" { - if let Some(value) = arguments.get(index + 1) { - if !is_jdt_owned_jvm_argument(value) { - custom_jvm_arguments.push(value.clone()); - } - } - index += usize::from(index + 1 < arguments.len()) + 1; - continue; - } - if let Some(value) = argument.strip_prefix("--jvm-arg=") { - if !is_jdt_owned_jvm_argument(value) { - custom_jvm_arguments.push(value.to_string()); - } - index += 1; - continue; - } - if owned_launcher_index == Some(index) { - after_launcher = true; - index += usize::from(index + 1 < arguments.len()) + 1; - continue; - } - if argument == "-configuration" && has_direct_layout && after_launcher { - index += usize::from(index + 1 < arguments.len()) + 1; - continue; - } - if has_direct_layout - && !after_launcher - && ((argument == "--add-modules" - && arguments - .get(index + 1) - .is_some_and(|value| value == "ALL-SYSTEM")) - || (argument == "--add-opens" - && arguments.get(index + 1).is_some_and(|value| { - value == "java.base/java.util=ALL-UNNAMED" - || value == "java.base/java.lang=ALL-UNNAMED" - }))) - { - index += 2; - continue; - } - if argument.starts_with("--java-executable=") || argument.starts_with("-data=") { - index += 1; - continue; - } - if has_direct_layout && !after_launcher { - if !is_jdt_owned_jvm_argument(argument) { - custom_jvm_arguments.push(argument.clone()); - } - } else if !is_jdt_owned_server_argument(argument) { - server_arguments.push(argument.clone()); - } - index += 1; - } - (custom_jvm_arguments, server_arguments) -} - -fn is_jdt_owned_jvm_argument(argument: &str) -> bool { - // `-Xmx` and `-Dlog.level=` are the plugin's to choose, so they stay in - // the custom arguments, where `direct_java_arguments` reads them. - argument.starts_with("-Xms") - || argument == "--add-modules=ALL-SYSTEM" - || argument == "--add-opens=java.base/java.util=ALL-UNNAMED" - || argument == "--add-opens=java.base/java.lang=ALL-UNNAMED" - || argument.starts_with("-Declipse.application=") - || argument.starts_with("-Declipse.product=") - || argument.starts_with("-Dosgi.bundles.defaultStartLevel=") - || argument.starts_with("-Dlog.protocol=") - || is_tuning_default(argument) - || is_metadata_location_argument(argument) - || is_lombok_agent_argument(argument) -} - -fn is_metadata_location_argument(argument: &str) -> bool { - argument - .strip_prefix(METADATA_AT_PROJECT_ROOT_PROPERTY) - .is_some_and(|rest| rest.starts_with('=')) -} - -fn is_lombok_agent_argument(argument: &str) -> bool { - let Some(path) = argument.strip_prefix("-javaagent:") else { - return false; - }; - path.split_once('=') - .map_or(path, |(path, _)| path) - .replace('\\', "/") - .rsplit('/') - .next() - .is_some_and(|name| name.eq_ignore_ascii_case("lombok.jar")) -} - -fn is_jdt_owned_server_argument(argument: &str) -> bool { - argument == "-data" || argument.starts_with("-data=") -} - -fn without_wrapper_owned_arguments(arguments: &[String]) -> Vec { - let mut retained = Vec::with_capacity(arguments.len()); - let mut index = 0; - while index < arguments.len() { - let argument = &arguments[index]; - let owns_following_value = argument == "--java-executable" || argument == "-data"; - let owns_inline_value = argument.starts_with("--java-executable=") - || argument.starts_with("-data=") - || argument.starts_with("--jvm-arg=-Xms") - || argument.starts_with("--jvm-arg=-Xmx") - || argument.strip_prefix("--jvm-arg=").is_some_and(|value| { - is_metadata_location_argument(value) || is_tuning_default(value) - }); - if owns_following_value { - index += usize::from(index + 1 < arguments.len()) + 1; - } else { - if !owns_inline_value { - retained.push(argument.clone()); - } - index += 1; - } - } - retained -} - -fn java_settings(settings: JdtSettings<'_>) -> Value { - let maven_configuration = settings.maven; - let gradle_configuration = settings.gradle; - let mut java = json!({ - "java": { - "eclipse": { - "downloadSources": false - }, - "maven": { - "downloadSources": false - }, - "configuration": { - "updateBuildConfiguration": "automatic" - }, - // JDT LS otherwise inserts parameter names into calls. Its "off" - // mode keeps the argument list empty and the snippet cursor inside. - "completion": java_completion_settings(settings.completion), - "inlayHints": { - "parameterNames": { - "enabled": "all" - } - }, - // Show "N implementations" code lens above interface methods and classes. - "implementationsCodeLens": { - "enabled": true - }, - // Show "N references" code lens above declarations. - "referencesCodeLens": { - "enabled": true - } - } - }); - if let Some(section) = maven_settings_section(maven_configuration) { - java["java"]["configuration"]["maven"] = section; - } - if let Some(section) = gradle_settings_section(gradle_configuration) { - java["java"]["import"]["gradle"] = section; - } - if settings.indexing_root_uri.is_some() || settings.import_exclusions.is_some() { - let mut exclusions = settings - .import_exclusions - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - if let Some(root_uri) = settings.indexing_root_uri { - for path in crate::project::indexing::java_import_exclusions(root_uri) { - let value = Value::String(path); - if !exclusions.contains(&value) { - exclusions.push(value); - } - } - } - java["java"]["import"]["exclusions"] = json!(exclusions); - } - if let Some(configuration) = maven_configuration { - java["java"]["project"]["sourcePaths"] = json!(configuration.source_paths); - } - if !settings.java_runtimes.is_empty() { - java["java"]["configuration"]["runtimes"] = java_runtimes_value(settings.java_runtimes); - } - java -} - -/// Retains the plugin's completion leaves while applying Lithe's argument policy. -/// Invalid section shapes are normalized without mutating the session input. -fn java_completion_settings(declared: Option<&Value>) -> Value { - let mut completion = declared - .and_then(Value::as_object) - .cloned() - .unwrap_or_default(); - completion.insert("guessMethodArguments".to_string(), json!("off")); - Value::Object(completion) -} - -fn java_runtimes_value(runtimes: &[JdtJavaRuntime]) -> Value { - Value::Array( - runtimes - .iter() - .map(|runtime| { - let mut value = json!({ "name": runtime.name, "path": runtime.path }); - if runtime.is_default { - value["default"] = json!(true); - } - value - }) - .collect(), - ) -} - -/// Builds the `java.configuration.maven` section for the resolved context. -/// -/// `globalSettings` carries the local repository and mirrors of the Maven -/// installation the workspace runs. Omitting it leaves JDT LS on its embedded -/// defaults, which resolves artifacts against a different repository than the -/// Maven command line uses for the same project. -fn maven_settings_section(maven_configuration: Option<&JdtMavenConfiguration>) -> Option { - let configuration = maven_configuration?; - let mut section = Map::new(); - if let Some(path) = &configuration.settings_path { - section.insert("userSettings".to_string(), json!(path)); - } - if let Some(path) = &configuration.global_settings_path { - section.insert("globalSettings".to_string(), json!(path)); - } - (!section.is_empty()).then_some(Value::Object(section)) -} - -/// Builds the `java.import.gradle` section for the resolved context. -/// -/// Both leaves state JDT LS's own defaults — `enabled` and `wrapper.enabled` are -/// `true` upstream — so the section declares the import behavior Lithe relies on -/// instead of changing today's import result. `wrapper.enabled` is sent only when -/// the root ships the descriptor Buildship reads, so Lithe never claims a wrapper -/// the workspace does not have. Settings that require reading the build script -/// (`java.home`, `version`, ...) are deliberately never sent: guessing them -/// would override the project's own declaration. `offline.enabled` and -/// `user.home` are sent only when the user chose them for the build system, -/// so the import uses what the user's Gradle runs use. -fn gradle_settings_section(gradle_configuration: Option<&JdtGradleConfiguration>) -> Option { - let configuration = gradle_configuration?; - let mut section = Map::new(); - section.insert("enabled".to_string(), json!(true)); - if configuration.wrapper_present { - section.insert("wrapper".to_string(), json!({ "enabled": true })); - } - if configuration.offline { - section.insert("offline".to_string(), json!({ "enabled": true })); - } - if let Some(home) = &configuration.user_home { - section.insert("user".to_string(), json!({ "home": home })); - } - Some(Value::Object(section)) -} - -fn java_configuration_for_section(section: Option<&str>, settings: JdtSettings<'_>) -> Value { - let maven_configuration = settings.maven; - let gradle_configuration = settings.gradle; - match section { - Some("java") => java_settings(settings)["java"].clone(), - Some("java.completion") => java_settings(settings)["java"]["completion"].clone(), - Some(section) if section.starts_with("java.completion.") => { - let completion = java_completion_settings(settings.completion); - section["java.completion.".len()..] - .split('.') - .try_fold(&completion, |value, key| value.get(key)) - .cloned() - .unwrap_or(Value::Null) - } - Some("java.inlayHints") => json!({ - "parameterNames": { - "enabled": "all" - } - }), - Some("java.inlayHints.parameterNames") => json!({ "enabled": "all" }), - Some("java.inlayHints.parameterNames.enabled") => json!("all"), - Some("java.eclipse") => json!({ "downloadSources": false }), - Some("java.eclipse.downloadSources") => json!(false), - Some("java.maven") => json!({ "downloadSources": false }), - Some("java.maven.downloadSources") => json!(false), - Some("java.configuration") => java_settings(settings)["java"]["configuration"].clone(), - Some("java.configuration.updateBuildConfiguration") => json!("automatic"), - Some("java.configuration.runtimes") => java_runtimes_value(settings.java_runtimes), - Some("java.configuration.maven") => { - maven_settings_section(maven_configuration).unwrap_or(Value::Null) - } - Some("java.configuration.maven.userSettings") => maven_configuration - .and_then(|value| value.settings_path.as_ref()) - .map_or(Value::Null, |path| json!(path)), - Some("java.configuration.maven.globalSettings") => maven_configuration - .and_then(|value| value.global_settings_path.as_ref()) - .map_or(Value::Null, |path| json!(path)), - Some("java.import") => java_settings(settings)["java"]["import"].clone(), - Some("java.import.exclusions") => { - java_settings(settings)["java"]["import"]["exclusions"].clone() - } - Some("java.import.gradle") => { - gradle_settings_section(gradle_configuration).unwrap_or(Value::Null) - } - Some("java.import.gradle.enabled") => { - gradle_configuration.map_or(Value::Null, |_| json!(true)) - } - Some("java.import.gradle.wrapper") => gradle_configuration - .filter(|value| value.wrapper_present) - .map_or(Value::Null, |_| json!({ "enabled": true })), - Some("java.import.gradle.wrapper.enabled") => gradle_configuration - .filter(|value| value.wrapper_present) - .map_or(Value::Null, |_| json!(true)), - Some("java.import.gradle.offline") => gradle_configuration - .filter(|value| value.offline) - .map_or(Value::Null, |_| json!({ "enabled": true })), - Some("java.import.gradle.offline.enabled") => gradle_configuration - .filter(|value| value.offline) - .map_or(Value::Null, |_| json!(true)), - Some("java.import.gradle.user") => gradle_configuration - .and_then(|value| value.user_home.as_ref()) - .map_or(Value::Null, |home| json!({ "home": home })), - Some("java.import.gradle.user.home") => gradle_configuration - .and_then(|value| value.user_home.as_ref()) - .map_or(Value::Null, |home| json!(home)), - Some("java.project") => maven_configuration - .map(|value| json!({ "sourcePaths": value.source_paths })) - .unwrap_or(Value::Null), - Some("java.project.sourcePaths") => maven_configuration - .map(|value| json!(value.source_paths)) - .unwrap_or(Value::Null), - Some("java.implementationsCodeLens") => json!({ "enabled": true }), - Some("java.implementationsCodeLens.enabled") => json!(true), - Some("java.referencesCodeLens") => json!({ "enabled": true }), - Some("java.referencesCodeLens.enabled") => json!(true), - _ => Value::Null, - } -} - -/// Resolves a platform request through the same key algorithm used at startup. -pub(crate) fn resolve_workspace_key(request: JdtWorkspaceKeyRequest) -> JdtWorkspaceKeyResponse { - JdtWorkspaceKeyResponse { - workspace_key: workspace_key( - Path::new(&request.workspace_root), - request.workspace_fingerprint.as_deref(), - ), - } -} - -/// Hashes the normalized workspace identity and optional structural fingerprint. -pub(crate) fn workspace_key(workspace_root: &Path, fingerprint: Option<&str>) -> String { - let mut identity = normalized_workspace_identity(workspace_root); - // Mix the structural fingerprint in as a null-delimited suffix so changes - // to build files or the module set produce a fresh state directory without - // touching the previous one. Absent fingerprint keeps the legacy key. - if let Some(fp) = fingerprint { - identity.push('\x00'); - identity.push_str(fp); - } - let digest = Sha256::digest(identity.as_bytes()); - let mut key = String::with_capacity(digest.len() * 2); - const HEX: &[u8; 16] = b"0123456789abcdef"; - for byte in digest { - key.push(HEX[(byte >> 4) as usize] as char); - key.push(HEX[(byte & 0x0f) as usize] as char); - } - key -} - -fn normalized_workspace_identity(workspace_root: &Path) -> String { - let raw = workspace_root.to_string_lossy().replace('\\', "/"); - let bytes = raw.as_bytes(); - let has_drive = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; - let is_unc = raw.starts_with("//"); - let (prefix, remainder, is_absolute, protected_components, fold_case) = if has_drive { - let drive = (bytes[0] as char).to_ascii_lowercase(); - let remainder = &raw[2..]; - ( - format!("{drive}:"), - remainder, - remainder.starts_with('/'), - 0, - true, - ) - } else if is_unc { - ("//".to_string(), raw.trim_start_matches('/'), true, 2, true) - } else if raw.starts_with('/') { - ("/".to_string(), raw.trim_start_matches('/'), true, 0, false) - } else { - (String::new(), raw.as_str(), false, 0, false) - }; - - let mut components: Vec = Vec::new(); - for component in remainder.split('/') { - match component { - "" | "." => {} - ".." => { - if components.len() > protected_components - && components.last().is_some_and(|value| value != "..") - { - components.pop(); - } else if !is_absolute { - components.push("..".to_string()); - } - } - value => components.push(if fold_case { - value.to_lowercase() - } else { - value.to_string() - }), - } - } - - let joined = components.join("/"); - match (prefix.as_str(), joined.is_empty(), is_absolute) { - ("", true, _) => ".".to_string(), - ("/", true, _) => "/".to_string(), - ("//", true, _) => "//".to_string(), - (prefix, true, _) => prefix.to_string(), - ("", false, _) => joined, - ("/", false, _) => format!("/{joined}"), - ("//", false, _) => format!("//{joined}"), - (prefix, false, true) => format!("{prefix}/{joined}"), - (prefix, false, false) => format!("{prefix}{joined}"), - } -} - -fn has_uri_scheme(uri: &str, expected: &str) -> bool { - uri.split_once(':') - .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case(expected)) -} - -fn jdt_display_path(uri: &str) -> Option { - let (_, remainder) = uri.split_once(':')?; - let path = if let Some(with_authority) = remainder.strip_prefix("//") { - with_authority - .find('/') - .map(|index| &with_authority[index + 1..])? - } else { - remainder.trim_start_matches('/') - }; - let path = path.split_once(['?', '#']).map_or(path, |(value, _)| value); - let decoded = percent_decode(path); - let mut components: Vec<_> = decoded - .split('/') - .filter(|component| !component.is_empty()) - .map(str::to_string) - .collect(); - let last = components.last_mut()?; - if let Some(class_name) = last.strip_suffix(".class") { - *last = format!("{class_name}.java"); - } - Some(components.join("/")) -} - -fn percent_decode(value: &str) -> String { - let bytes = value.as_bytes(); - let mut decoded = Vec::with_capacity(bytes.len()); - let mut index = 0; - while index < bytes.len() { - if bytes[index] == b'%' && index + 2 < bytes.len() { - if let (Some(high), Some(low)) = - (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) - { - decoded.push((high << 4) | low); - index += 3; - continue; - } - } - decoded.push(bytes[index]); - index += 1; - } - String::from_utf8_lossy(&decoded).into_owned() -} - -fn hex_value(value: u8) -> Option { - match value { - b'0'..=b'9' => Some(value - b'0'), - b'a'..=b'f' => Some(value - b'a' + 10), - b'A'..=b'F' => Some(value - b'A' + 10), - _ => None, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn runtime(home_path: &str, version: &str) -> JavaRuntimeCandidate { - JavaRuntimeCandidate { - is_default: false, - home_path: home_path.to_string(), - version: version.to_string(), - } - } - - #[test] - fn one_jdk_per_major_version_becomes_a_jdt_execution_environment() { - // A Java 25 project only builds when JDT LS knows a JavaSE-25 JDK; the - // bundled JDK 21 it runs on is not enough (#769). - let runtimes = jdt_java_runtimes(&[ - runtime("/jdks/temurin-25", "25.0.4.1"), - runtime("/jdks/corretto-25", "25.0.1"), - runtime("/jdks/jdk8", "1.8.0_402"), - runtime("/jdks/unknown", "not-a-version"), - runtime("", "17.0.9"), - runtime("/jdks/temurin-21", "21"), - ]); - assert_eq!( - runtimes, - vec![ - JdtJavaRuntime { - is_default: false, - name: "JavaSE-1.8".to_string(), - path: "/jdks/jdk8".to_string() - }, - JdtJavaRuntime { - is_default: false, - name: "JavaSE-21".to_string(), - path: "/jdks/temurin-21".to_string() - }, - JdtJavaRuntime { - is_default: false, - name: "JavaSE-25".to_string(), - path: "/jdks/temurin-25".to_string() - }, - ] - ); - } - - #[test] - fn selected_project_vm_wins_over_discovery_order_and_duplicate_majors() { - let fixture: Value = serde_json::from_str(include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../shared/fixtures/lsp/java-project-runtimes-v1.json" - ))) - .unwrap(); - for case in fixture["cases"].as_array().unwrap() { - let candidates: Vec = - serde_json::from_value(case["candidates"].clone()).unwrap(); - assert_eq!( - java_runtimes_value(&jdt_java_runtimes(&candidates)), - case["expected"], - "{}", - case["name"] - ); - } - } - - #[test] - fn java_runtimes_reach_jdt_at_initialize_and_on_configuration_requests() { - let runtimes = [JdtJavaRuntime { - is_default: true, - name: "JavaSE-25".to_string(), - path: "C:/Program Files/Java/jdk-25".to_string(), - }]; - let settings = JdtSettings { - maven: None, - gradle: None, - java_runtimes: &runtimes, - ..Default::default() - }; - let expected = json!([{ "name": "JavaSE-25", "path": "C:/Program Files/Java/jdk-25", "default": true }]); - let options = adapt_initialization_options("java", None, &[], settings).unwrap(); - assert_eq!( - options["settings"]["java"]["configuration"]["runtimes"], - expected - ); - let items = ["java", "java.configuration", "java.configuration.runtimes"].map(|section| { - WorkspaceConfigurationItem { - scope_uri: None, - section: Some(section.to_string()), - } - }); - let values = workspace_configuration("java", &items, settings).unwrap(); - assert_eq!(values[0]["configuration"]["runtimes"], expected); - assert_eq!(values[1]["runtimes"], expected); - assert_eq!(values[2], expected); - let notification = initialized_notification("java", settings).unwrap(); - assert_eq!( - notification.params["settings"]["java"]["configuration"]["runtimes"], - expected - ); - } - - #[test] - fn no_known_jdks_leaves_jdt_on_its_own_runtime() { - let options = - adapt_initialization_options("java", None, &[], JdtSettings::default()).unwrap(); - assert!(options["settings"]["java"]["configuration"] - .get("runtimes") - .is_none()); - } - - fn maven_settings(configuration: &JdtMavenConfiguration) -> JdtSettings<'_> { - JdtSettings { - maven: Some(configuration), - gradle: None, - java_runtimes: &[], - ..Default::default() - } - } - - fn gradle_settings(configuration: &JdtGradleConfiguration) -> JdtSettings<'_> { - JdtSettings { - maven: None, - gradle: Some(configuration), - java_runtimes: &[], - ..Default::default() - } - } - - #[test] - fn maven_profile_project_results_have_stable_wire_shape() { - let result = MavenProfileProjectResult { - project_uri: "file:///workspace/module-a/".to_string(), - status: MavenProfileTaskStatus::PartiallySucceeded, - error_details: Some("profile update failed".to_string()), - }; - assert_eq!( - serde_json::to_value(result).unwrap(), - json!({ - "projectUri": "file:///workspace/module-a/", - "status": "partiallySucceeded", - "errorDetails": "profile update failed" - }) - ); - assert_eq!( - serde_json::to_value(MavenProfileTaskStatus::TimedOut).unwrap(), - json!("timedOut") - ); - } - - fn java_start_context() -> JdtStartContext { - JdtStartContext { - provider_id: "java".to_string(), - workspace_root: PathBuf::from("/workspace/project"), - data_root: PathBuf::from("/cache/Lithe"), - selected_java_executable: Some(PathBuf::from("/jdk/bin/java")), - direct_launch_resources: None, - arguments: vec!["--stdio".to_string()], - workspace_fingerprint: None, - } - } - - #[test] - fn import_progress_extracts_module_and_download_diagnostics() { - let module = import_progress( - "java", - Some("$/progress"), - Some(&json!({ - "value": { - "kind": "report", - "message": "Importing Maven project(s) - Importing project module-a", - "percentage": 24 - } - })), - ) - .expect("Java work-done progress should be observed"); - assert_eq!(module.phase.as_deref(), Some("Importing Maven project(s)")); - assert_eq!(module.current_project.as_deref(), Some("module-a")); - assert_eq!(module.percentage, Some(24)); - - let download = import_progress( - "java", - Some("$/progress"), - Some(&json!({ - "value": { - "kind": "report", - "message": "Importing Maven project(s) - 117KB/7MB (1%) https://repo.maven.apache.org/maven2/org/apache/poi/poi.jar", - "percentage": 49 - } - })), - ) - .and_then(|progress| progress.download) - .expect("artifact transfer details should be parsed"); - assert_eq!(download.artifact, "poi.jar"); - assert_eq!( - download.repository_host.as_deref(), - Some("repo.maven.apache.org") - ); - assert_eq!(download.downloaded_bytes, Some(117 * 1024)); - assert_eq!(download.total_bytes, Some(7 * 1024 * 1024)); - } - - #[test] - fn import_progress_ignores_other_providers_and_status_text() { - let params = json!({ - "value": { - "kind": "report", - "message": "Importing Maven project(s) - 50%", - "percentage": 50 - } - }); - assert!(import_progress("gopls", Some("$/progress"), Some(¶ms)).is_none()); - assert!(import_progress("java", Some("language/status"), Some(¶ms)).is_none()); - } - - #[test] - fn java_start_adds_runtime_memory_and_unique_data_arguments() { - let context = java_start_context(); - let adapted = adapt_start(&context); - let data_directory = adapted.data_directory.as_ref().unwrap(); - - assert_eq!( - data_directory.parent().unwrap(), - Path::new("/cache/Lithe/jdtls") - ); - assert_eq!( - data_directory.file_name().unwrap().to_string_lossy().len(), - 64 - ); - assert_eq!( - adapted.arguments, - vec![ - "--stdio", - "--java-executable", - "/jdk/bin/java", - "--jvm-arg=-Xms256m", - "--jvm-arg=-Xmx2048m", - "--jvm-arg=-XX:+UseParallelGC", - "--jvm-arg=-XX:GCTimeRatio=4", - "--jvm-arg=-XX:AdaptiveSizePolicyWeight=90", - "--jvm-arg=-Xlog:disable", - "--jvm-arg=-DDetectVMInstallationsJob.disabled=true", - "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false", - "-data", - data_directory.to_string_lossy().as_ref() - ] - ); - } - - #[test] - fn java_start_lets_plugin_jvm_options_replace_the_tuning_defaults() { - let tuning_of = |arguments: &[String]| { - arguments - .iter() - .filter_map(|argument| argument.strip_prefix("--jvm-arg=")) - .filter(|argument| argument.starts_with("-XX:") || argument.starts_with("-Xlog")) - .map(str::to_string) - .collect::>() - }; - let mut context = java_start_context(); - context.arguments = vec![ - "--jvm-arg=-XX:+UseG1GC".to_string(), - "--jvm-arg=-XX:GCTimeRatio=9".to_string(), - "--jvm-arg=-Xlog:gc*:file=/tmp/gc.log".to_string(), - ]; - let first = adapt_start(&context); - context.arguments = first.arguments.clone(); - let second = adapt_start(&context); - - assert_eq!(first, second); - // The plugin's collector replaces ParallelGC, and its own GC-time - // ratio and logging replace the host's; the untouched default stays. - assert_eq!( - tuning_of(&first.arguments), - vec![ - "-XX:+UseG1GC", - "-XX:GCTimeRatio=9", - "-Xlog:gc*:file=/tmp/gc.log", - "-XX:AdaptiveSizePolicyWeight=90", - ] - ); - assert!(first - .arguments - .contains(&"--jvm-arg=-DDetectVMInstallationsJob.disabled=true".to_string())); - } - - #[test] - fn java_start_uses_the_plugins_heap_choice_and_is_stable() { - let mut context = java_start_context(); - context.arguments = vec![ - "--java-executable".to_string(), - "/old/java".to_string(), - "--jvm-arg=-Xms2g".to_string(), - "--jvm-arg=-Xmx4g".to_string(), - "--jvm-arg=-Duser.language=en".to_string(), - // A catalog or user override must not put metadata back into the project. - "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=true".to_string(), - "-data".to_string(), - "/old/data".to_string(), - ]; - let first = adapt_start(&context); - context.arguments = first.arguments.clone(); - let second = adapt_start(&context); - - assert_eq!(first, second); - assert!(first - .arguments - .contains(&"--jvm-arg=-Duser.language=en".to_string())); - // The plugin chooses the maximum heap; the initial heap stays the host's. - assert_eq!( - first - .arguments - .iter() - .filter(|argument| argument.starts_with("--jvm-arg=-Xm")) - .collect::>(), - vec!["--jvm-arg=-Xms256m", "--jvm-arg=-Xmx4g"] - ); - assert!(!first.arguments.contains(&"/old/java".to_string())); - assert!(!first.arguments.contains(&"/old/data".to_string())); - assert_eq!( - first - .arguments - .iter() - .filter(|argument| argument.contains("generatesMetadataFilesAtProjectRoot")) - .collect::>(), - vec!["--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false"] - ); - } - - #[test] - fn java_start_keeps_the_heap_above_the_jdtls_constrained_memory_threshold() { - // JDT LS switches to a batched Maven import whose `updateProjects` path - // dereferences a `null` project for modules that share a build - // coordinate (eclipse-jdtls/eclipse.jdt.ls#3893). Staying above 1.5 GB - // keeps a normal multi-module workspace on the regular import path. - const CONSTRAINED_MEMORY_THRESHOLD_MEBIBYTES: u64 = 1536; - - let mut direct_context = java_start_context(); - direct_context.direct_launch_resources = Some(JdtDirectLaunchResources { - launcher_jar_path: PathBuf::from("/jdtls/plugins/equinox.jar"), - configuration_directory: PathBuf::from("/jdtls/config_mac"), - lombok_agent_path: PathBuf::from("/jdtls/lombok/lombok.jar"), - java_debug_bundle_path: None, - }); - let wrapper = adapt_start(&java_start_context()); - let direct = adapt_start(&direct_context); - - for arguments in [&wrapper.arguments, &direct.arguments] { - let heap = arguments - .iter() - .find_map(|argument| { - argument - .strip_prefix("--jvm-arg=") - .unwrap_or(argument) - .strip_prefix("-Xmx") - }) - .expect("both JDT LS launch paths set a maximum heap"); - let mebibytes = heap - .strip_suffix('m') - .and_then(|value| value.parse::().ok()) - .expect("the JDT LS maximum heap uses a mebibyte suffix"); - assert!( - mebibytes > CONSTRAINED_MEMORY_THRESHOLD_MEBIBYTES, - "JDT LS needs more than {CONSTRAINED_MEMORY_THRESHOLD_MEBIBYTES} MiB of maximum heap, found {heap}" - ); - } - } - - #[test] - fn java_direct_start_builds_complete_shell_free_arguments_and_is_stable() { - let mut context = java_start_context(); - context.direct_launch_resources = Some(JdtDirectLaunchResources { - launcher_jar_path: PathBuf::from("/jdtls/plugins/equinox.jar"), - configuration_directory: PathBuf::from("/jdtls/config_mac"), - lombok_agent_path: PathBuf::from("/jdtls/lombok/lombok.jar"), - java_debug_bundle_path: Some(PathBuf::from( - "/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar", - )), - }); - context.arguments = vec![ - "--stdio".to_string(), - "-jar".to_string(), - "/server/extension.jar".to_string(), - "--java-executable=/old/java".to_string(), - "--jvm-arg=-Xmx4g".to_string(), - "--jvm-arg=-Dlog.level=INFO".to_string(), - "--jvm-arg=-Duser.language=en".to_string(), - "--jvm-arg=-Dosgi.logfile=/session/plugins/java/files/jdt.log".to_string(), - "--jvm-arg=-Declipse.log.include.commandline=false".to_string(), - "--jvm-arg=-Declipse.log.size.max=1024".to_string(), - "--jvm-arg=-Declipse.log.backup.max=2".to_string(), - "--jvm-arg=-Declipse.log.level=WARNING".to_string(), - "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=true".to_string(), - "-data=/old/data".to_string(), - ]; - - let first = adapt_start(&context); - context.arguments = first.arguments.clone(); - let second = adapt_start(&context); - let data_directory = first.data_directory.as_ref().unwrap(); - - assert_eq!(first, second); - assert_eq!(first.executable, Some(PathBuf::from("/jdk/bin/java"))); - assert_eq!( - first.arguments, - vec![ - "-javaagent:/jdtls/lombok/lombok.jar", - "-Xms256m", - "-Xmx4g", - "-XX:+UseParallelGC", - "-XX:GCTimeRatio=4", - "-XX:AdaptiveSizePolicyWeight=90", - "-Xlog:disable", - "-DDetectVMInstallationsJob.disabled=true", - "--add-modules=ALL-SYSTEM", - "--add-opens=java.base/java.util=ALL-UNNAMED", - "--add-opens=java.base/java.lang=ALL-UNNAMED", - "-Declipse.application=org.eclipse.jdt.ls.core.id1", - "-Declipse.product=org.eclipse.jdt.ls.core.product", - "-Dosgi.bundles.defaultStartLevel=4", - "-Dlog.protocol=true", - "-Dlog.level=INFO", - "-Djava.import.generatesMetadataFilesAtProjectRoot=false", - "-Duser.language=en", - "-Dosgi.logfile=/session/plugins/java/files/jdt.log", - "-Declipse.log.include.commandline=false", - "-Declipse.log.size.max=1024", - "-Declipse.log.backup.max=2", - "-Declipse.log.level=WARNING", - "-jar", - "/jdtls/plugins/equinox.jar", - "-configuration", - "/jdtls/config_mac", - "--stdio", - "-jar", - "/server/extension.jar", - "-data", - data_directory.to_string_lossy().as_ref(), - ] - ); - assert!(!first.arguments.contains(&"/old/java".to_string())); - assert!(!first.arguments.contains(&"/old/data".to_string())); - assert!(!first.arguments.contains(&"-Dlog.level=ALL".to_string())); - } - - #[test] - fn direct_start_keeps_host_defaults_without_a_choice_and_ignores_malformed_ones() { - let resources = JdtDirectLaunchResources { - launcher_jar_path: PathBuf::from("/jdtls/plugins/equinox.jar"), - configuration_directory: PathBuf::from("/jdtls/config_mac"), - lombok_agent_path: PathBuf::from("/jdtls/lombok/lombok.jar"), - java_debug_bundle_path: None, - }; - let data = Path::new("/data"); - let heap_and_level = |arguments: &[&str]| { - let arguments: Vec = arguments.iter().map(|value| value.to_string()).collect(); - let adapted = direct_java_arguments(&arguments, &resources, data); - ( - adapted - .iter() - .filter(|argument| argument.starts_with("-Xmx")) - .cloned() - .collect::>(), - adapted - .iter() - .filter(|argument| argument.starts_with("-Dlog.level=")) - .cloned() - .collect::>(), - ) - }; - - assert_eq!( - heap_and_level(&[]), - ( - vec!["-Xmx2048m".to_string()], - vec!["-Dlog.level=WARNING".to_string()] - ) - ); - // The last acceptable choice wins; a malformed one never reaches the JVM. - assert_eq!( - heap_and_level(&[ - "--jvm-arg=-Xmx2g", - "--jvm-arg=-Xmx3072m", - "--jvm-arg=-Dlog.level=WARNING", - "--jvm-arg=-Dlog.level=SEV ERE", - ]), - ( - vec!["-Xmx3072m".to_string()], - vec!["-Dlog.level=WARNING".to_string()] - ) - ); - assert_eq!( - heap_and_level(&[ - "--jvm-arg=-Xmx", - "--jvm-arg=-Xmxlots", - "--jvm-arg=-Xmx1024m", - "--jvm-arg=-Xmx1536m", - "--jvm-arg=-Dlog.level=", - ]), - ( - vec!["-Xmx2048m".to_string()], - vec!["-Dlog.level=WARNING".to_string()] - ) - ); - // A plugin that launches the server as `java -jar ` - // puts its choices before the launcher, where they are read the same way. - assert_eq!( - heap_and_level(&[ - "-Xmx2048m", - "-Dlog.level=SEVERE", - "-jar", - "/jdtls/plugins/equinox.jar", - ]), - ( - vec!["-Xmx2048m".to_string()], - vec!["-Dlog.level=SEVERE".to_string()] - ) - ); - } - - #[test] - fn workspace_identity_is_lexical_cross_platform_and_unique() { - assert_eq!( - workspace_key(Path::new(r"C:\Users\Ada\Project\.\src\.."), None), - workspace_key(Path::new("c:/users/ada/project"), None) - ); - assert_eq!( - workspace_key(Path::new("/workspace/project/./src/.."), None), - workspace_key(Path::new("/workspace/project"), None) - ); - assert_ne!( - workspace_key(Path::new("/workspace/project"), None), - workspace_key(Path::new("/workspace/other"), None) - ); - } - - #[test] - fn workspace_fingerprint_changes_data_directory() { - let mut context = java_start_context(); - let without = adapt_start(&context).data_directory.unwrap(); - context.workspace_fingerprint = Some("pom=111|modules=core,web|jdtls=1.38.0".to_string()); - let first = adapt_start(&context).data_directory.unwrap(); - context.workspace_fingerprint = Some("pom=222|modules=core,web|jdtls=1.38.0".to_string()); - let changed = adapt_start(&context).data_directory.unwrap(); - - assert_ne!(without, first); - assert_ne!(first, changed); - assert_eq!(without.parent(), first.parent()); - assert_eq!(first.parent(), changed.parent()); - assert_eq!(without.file_name().unwrap().to_string_lossy().len(), 64); - assert_eq!(first.file_name().unwrap().to_string_lossy().len(), 64); - assert_eq!(changed.file_name().unwrap().to_string_lossy().len(), 64); - - context.workspace_fingerprint = Some("pom=111|modules=core,web|jdtls=1.38.0".to_string()); - let repeated = adapt_start(&context).data_directory.unwrap(); - assert_eq!(first, repeated); - } - - #[test] - fn workspace_key_request_uses_the_same_compatibility_algorithm() { - let response = resolve_workspace_key(JdtWorkspaceKeyRequest { - workspace_root: "/workspace/project".to_string(), - workspace_fingerprint: Some("pom=111|jdtls=1.38.0".to_string()), - }); - - assert_eq!( - response.workspace_key, - workspace_key( - Path::new("/workspace/project"), - Some("pom=111|jdtls=1.38.0") - ) - ); - } - - #[test] - fn non_java_start_is_a_generic_noop() { - let mut context = java_start_context(); - context.provider_id = "rust".to_string(); - let adapted = adapt_start(&context); - - assert_eq!(adapted.arguments, context.arguments); - assert_eq!(adapted.data_directory, None); - assert!(workspace_configuration("rust", &[], JdtSettings::default()).is_none()); - assert!(initialized_notification("rust", JdtSettings::default()).is_none()); - assert!(virtual_source_resolve_params("rust", "jdt://contents/A.class").is_none()); - assert_eq!( - adapt_initialization_options( - "rust", - Some(json!({ "custom": true })), - &[], - JdtSettings::default() - ), - Some(json!({ "custom": true })) - ); - let location = ProviderLocation { - uri: "jdt://contents/A.class".to_string(), - is_read_only: false, - display_path: None, - }; - assert_eq!(normalize_location("rust", location.clone()), location); - } - - #[test] - fn java_initialization_enables_class_file_content_without_losing_catalog_options() { - let options = adapt_initialization_options( - "JAVA", - Some(json!({ - "workspace": { "custom": true }, - "bundles": ["/plugins/custom.jar"], - "extendedClientCapabilities": { - "customCapability": true, - "classFileContentsSupport": false - } - })), - &[ - PathBuf::from("/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar"), - PathBuf::from( - "/jdtls/java-test/extensions/com.microsoft.java.test.plugin-0.42.0.jar", - ), - ], - JdtSettings::default(), - ) - .unwrap(); - - assert_eq!(options["workspace"]["custom"], true); - assert_eq!( - options["extendedClientCapabilities"]["customCapability"], - true - ); - assert_eq!( - options["extendedClientCapabilities"]["classFileContentsSupport"], - true - ); - assert_eq!( - options["bundles"], - json!([ - "/plugins/custom.jar", - "/jdtls/java-debug/com.microsoft.java.debug.plugin-0.53.1.jar", - "/jdtls/java-test/extensions/com.microsoft.java.test.plugin-0.42.0.jar" - ]) - ); - } - - #[test] - fn java_initialization_options_carry_maven_settings_before_the_first_import() { - // JDT LS configures its Maven embedder while handling `initialize`, and - // the project import starts right after. A repository or mirror sent - // only through `didChangeConfiguration` would arrive once that import - // had already resolved every artifact against the embedded defaults. - let configuration = JdtMavenConfiguration { - settings_path: None, - global_settings_path: Some("/opt/maven/conf/settings.xml".to_string()), - profiles: Vec::new(), - project_uris: Vec::new(), - source_paths: vec!["src/main/java".to_string()], - }; - - let options = adapt_initialization_options( - "java", - Some(json!({ - "workspace": { "custom": true }, - "settings": { "java": { "custom": true } } - })), - &[], - maven_settings(&configuration), - ) - .unwrap(); - - assert_eq!( - options["settings"]["java"]["configuration"]["maven"]["globalSettings"], - "/opt/maven/conf/settings.xml" - ); - assert_eq!( - options["settings"]["java"]["project"]["sourcePaths"], - json!(["src/main/java"]) - ); - // Catalog values outside the provider-owned keys survive the overlay. - assert_eq!(options["settings"]["java"]["custom"], true); - assert_eq!(options["workspace"]["custom"], true); - } - - #[test] - fn java_completion_leaves_arguments_empty_across_configuration_channels() { - // Initialization, notifications and pull configuration must agree, or - // JDT LS can restore parameter placeholders after the first completion. - let fixture: Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/lsp/java-completion-v1.json" - )) - .expect("Java completion fixture should be valid"); - let expected = &fixture["javaSettings"]["completion"]; - let settings = JdtSettings { - completion: Some(&fixture["pluginCompletion"]), - ..Default::default() - }; - let options = adapt_initialization_options( - "java", - Some(json!({ "settings": { "java": { "completion": fixture["pluginCompletion"] } } })), - &[], - settings, - ) - .unwrap(); - assert_eq!( - options["settings"]["java"]["completion"]["guessMethodArguments"], - expected["guessMethodArguments"] - ); - assert_eq!( - options["settings"]["java"]["completion"]["favoriteStaticMembers"], - json!(["java.util.Objects.*"]) - ); - - assert_eq!(options["settings"]["java"]["completion"], *expected); - let notification = initialized_notification("java", settings).unwrap(); - assert_eq!( - notification.params["settings"]["java"]["completion"], - *expected - ); - let items = fixture["workspaceConfigurationSections"] - .as_array() - .unwrap() - .iter() - .map(|section| WorkspaceConfigurationItem { - scope_uri: None, - section: Some(section.as_str().unwrap().to_string()), - }) - .collect::>(); - let values = workspace_configuration("java", &items, settings).unwrap(); - assert_eq!(values[0]["completion"], *expected); - assert_eq!(values[1], *expected); - assert_eq!(values[2], expected["guessMethodArguments"]); - assert_eq!(values[3], expected["favoriteStaticMembers"]); - assert_eq!(values[4], expected["filteredTypes"]); - assert_eq!(values[5], Value::Null); - assert_eq!( - fixture["pluginCompletion"]["guessMethodArguments"], - "insertParameterNames" - ); - } - - #[test] - fn java_initialization_options_carry_settings_without_a_maven_context() { - let options = - adapt_initialization_options("java", None, &[], JdtSettings::default()).unwrap(); - - assert_eq!( - options["settings"]["java"]["maven"]["downloadSources"], - false - ); - // Without a resolved context JDT LS keeps its own Maven defaults rather - // than receiving an empty or null settings section. - assert!(options["settings"]["java"]["configuration"] - .get("maven") - .is_none()); - } - - #[test] - fn java_initialization_options_carry_gradle_settings_before_the_first_import() { - // Buildship imports the Gradle project while JDT LS handles `initialize`, - // so the import settings have to be present there and not only through - // the later `didChangeConfiguration` notification. - let configuration = JdtGradleConfiguration { - wrapper_present: true, - ..Default::default() - }; - - let options = adapt_initialization_options( - "java", - Some(json!({ - "workspace": { "custom": true }, - "settings": { "java": { "custom": true } } - })), - &[], - gradle_settings(&configuration), - ) - .unwrap(); - - assert_eq!( - options["settings"]["java"]["import"]["gradle"]["enabled"], - true - ); - assert_eq!( - options["settings"]["java"]["import"]["gradle"]["wrapper"]["enabled"], - true - ); - // Catalog values outside the provider-owned keys survive the overlay. - assert_eq!(options["settings"]["java"]["custom"], true); - assert_eq!(options["workspace"]["custom"], true); - } - - #[test] - fn gradle_import_settings_omit_the_wrapper_when_none_is_shipped() { - let configuration = JdtGradleConfiguration { - wrapper_present: false, - ..Default::default() - }; - - let options = - adapt_initialization_options("java", None, &[], gradle_settings(&configuration)) - .unwrap(); - let gradle = &options["settings"]["java"]["import"]["gradle"]; - - assert_eq!(gradle["enabled"], true); - // Pointing Buildship at a wrapper the workspace does not ship would be - // worse than leaving its own default in place. - assert!(gradle.get("wrapper").is_none()); - } - - #[test] - fn gradle_import_settings_keep_the_gradle_options_lithe_never_sends() { - // Without the user's own build options Lithe only states `enabled` - // and, when a wrapper is shipped, `wrapper.enabled`. Options that - // require reading the build script are never sent, so a declared - // `import.gradle` subtree has to survive the overlay instead of being - // replaced by those two leaves. - let configuration = JdtGradleConfiguration { - wrapper_present: true, - ..Default::default() - }; - - let options = adapt_initialization_options( - "java", - Some(json!({ - "settings": { - "java": { - "import": { - "gradle": { - "offline": { "enabled": true }, - "version": "8.10" - } - } - } - } - })), - &[], - gradle_settings(&configuration), - ) - .unwrap(); - - let gradle = &options["settings"]["java"]["import"]["gradle"]; - assert_eq!(gradle["enabled"], true); - assert_eq!(gradle["wrapper"]["enabled"], true); - assert_eq!(gradle["offline"]["enabled"], true); - assert_eq!(gradle["version"], "8.10"); - } - - #[test] - fn gradle_import_settings_carry_the_user_chosen_build_options() { - let configuration = JdtGradleConfiguration { - wrapper_present: false, - offline: true, - user_home: Some("/caches/gradle".to_string()), - }; - - let options = - adapt_initialization_options("java", None, &[], gradle_settings(&configuration)) - .unwrap(); - let gradle = &options["settings"]["java"]["import"]["gradle"]; - assert_eq!(gradle["offline"]["enabled"], true); - assert_eq!(gradle["user"]["home"], "/caches/gradle"); - - let items = [ - "java.import.gradle.offline.enabled", - "java.import.gradle.user.home", - ] - .map(|section| WorkspaceConfigurationItem { - scope_uri: None, - section: Some(section.to_string()), - }); - let values = - workspace_configuration("java", &items, gradle_settings(&configuration)).unwrap(); - assert_eq!(values, [json!(true), json!("/caches/gradle")]); - - // Without the user's choice Buildship keeps its own defaults. - let defaults = JdtGradleConfiguration::default(); - let options = - adapt_initialization_options("java", None, &[], gradle_settings(&defaults)).unwrap(); - let gradle = &options["settings"]["java"]["import"]["gradle"]; - assert!(gradle.get("offline").is_none() && gradle.get("user").is_none()); - } - - #[test] - fn java_initialization_options_omit_gradle_import_without_a_gradle_context() { - let options = - adapt_initialization_options("java", None, &[], JdtSettings::default()).unwrap(); - - assert!(options["settings"]["java"].get("import").is_none()); - } - - #[test] - fn java_workspace_configuration_answers_gradle_sections() { - let configuration = JdtGradleConfiguration { - wrapper_present: true, - ..Default::default() - }; - let items = [ - "java.import", - "java.import.gradle", - "java.import.gradle.enabled", - "java.import.gradle.wrapper", - "java.import.gradle.wrapper.enabled", - ] - .map(|section| WorkspaceConfigurationItem { - scope_uri: Some("file:///workspace/project".to_string()), - section: Some(section.to_string()), - }); - let values = - workspace_configuration("java", &items, gradle_settings(&configuration)).unwrap(); - - assert_eq!(values[0]["gradle"]["enabled"], true); - assert_eq!(values[0]["gradle"]["wrapper"]["enabled"], true); - assert_eq!(values[1]["enabled"], true); - assert_eq!(values[1]["wrapper"]["enabled"], true); - assert_eq!(values[2], true); - assert_eq!(values[3]["enabled"], true); - assert_eq!(values[4], true); - } - - #[test] - fn java_workspace_configuration_omits_gradle_wrapper_without_a_wrapper() { - let configuration = JdtGradleConfiguration { - wrapper_present: false, - ..Default::default() - }; - let items = [ - "java.import.gradle.wrapper", - "java.import.gradle.wrapper.enabled", - ] - .map(|section| WorkspaceConfigurationItem { - scope_uri: None, - section: Some(section.to_string()), - }); - let values = - workspace_configuration("java", &items, gradle_settings(&configuration)).unwrap(); - - assert_eq!(values[0], Value::Null); - assert_eq!(values[1], Value::Null); - } - - #[test] - fn java_workspace_configuration_matches_each_section_shape() { - let items = [ - "java", - "java.eclipse.downloadSources", - "java.maven.downloadSources", - "java.inlayHints", - "java.inlayHints.parameterNames", - "java.inlayHints.parameterNames.enabled", - "java.implementationsCodeLens", - "java.implementationsCodeLens.enabled", - "java.referencesCodeLens", - "java.referencesCodeLens.enabled", - "java.unknown", - ] - .map(|section| WorkspaceConfigurationItem { - scope_uri: Some("file:///workspace/project".to_string()), - section: Some(section.to_string()), - }); - let values = workspace_configuration("java", &items, JdtSettings::default()).unwrap(); - - assert_eq!(values[0]["inlayHints"]["parameterNames"]["enabled"], "all"); - assert_eq!(values[0]["eclipse"]["downloadSources"], false); - assert_eq!(values[0]["maven"]["downloadSources"], false); - assert_eq!(values[0]["implementationsCodeLens"]["enabled"], true); - assert_eq!(values[0]["referencesCodeLens"]["enabled"], true); - assert_eq!(values[1], false); // java.eclipse.downloadSources - assert_eq!(values[2], false); // java.maven.downloadSources - assert_eq!(values[3]["parameterNames"]["enabled"], "all"); // java.inlayHints - assert_eq!(values[4]["enabled"], "all"); // java.inlayHints.parameterNames - assert_eq!(values[5], "all"); // java.inlayHints.parameterNames.enabled - assert_eq!(values[6]["enabled"], true); // java.implementationsCodeLens - assert_eq!(values[7], true); // java.implementationsCodeLens.enabled - assert_eq!(values[8]["enabled"], true); // java.referencesCodeLens - assert_eq!(values[9], true); // java.referencesCodeLens.enabled - assert_eq!(values[10], Value::Null); // java.unknown - } - - #[test] - fn java_initialized_notification_publishes_inlay_settings() { - let notification = initialized_notification("JAVA", JdtSettings::default()).unwrap(); - - assert_eq!(notification.method, "workspace/didChangeConfiguration"); - assert_eq!( - notification.params["settings"]["java"]["inlayHints"]["parameterNames"]["enabled"], - "all" - ); - assert_eq!( - notification.params["settings"]["java"]["eclipse"]["downloadSources"], - false - ); - assert_eq!( - notification.params["settings"]["java"]["maven"]["downloadSources"], - false - ); - assert_eq!( - notification.params["settings"]["java"]["implementationsCodeLens"]["enabled"], - true - ); - assert_eq!( - notification.params["settings"]["java"]["referencesCodeLens"]["enabled"], - true - ); - } - - #[test] - fn java_configuration_and_profile_updates_consume_the_maven_context() { - let configuration = JdtMavenConfiguration { - settings_path: Some("/local/settings.xml".to_string()), - global_settings_path: Some("/opt/maven/conf/settings.xml".to_string()), - profiles: vec!["dev".to_string(), "enterprise".to_string()], - project_uris: vec![ - "file:///workspace/reactor/".to_string(), - "file:///workspace/reactor/module-a/".to_string(), - "file:///workspace/reactor/module-a/nested/".to_string(), - ], - source_paths: vec![ - "src/main/java".to_string(), - "module-a/src/main/java".to_string(), - ], - }; - let items = [ - "java", - "java.configuration", - "java.configuration.maven", - "java.configuration.maven.userSettings", - "java.configuration.maven.globalSettings", - ] - .map(|section| WorkspaceConfigurationItem { - scope_uri: Some("file:///workspace/reactor/".to_string()), - section: Some(section.to_string()), - }); - - let values = - workspace_configuration("java", &items, maven_settings(&configuration)).unwrap(); - assert_eq!( - values[0]["configuration"]["maven"]["userSettings"], - "/local/settings.xml" - ); - assert_eq!(values[1]["maven"]["userSettings"], "/local/settings.xml"); - assert_eq!(values[2]["userSettings"], "/local/settings.xml"); - assert_eq!(values[3], "/local/settings.xml"); - // The installation settings carry the local repository and mirrors that - // the Maven command line already uses for this workspace. - assert_eq!( - values[0]["configuration"]["maven"]["globalSettings"], - "/opt/maven/conf/settings.xml" - ); - assert_eq!( - values[1]["maven"]["globalSettings"], - "/opt/maven/conf/settings.xml" - ); - assert_eq!(values[2]["globalSettings"], "/opt/maven/conf/settings.xml"); - assert_eq!(values[4], "/opt/maven/conf/settings.xml"); - assert_eq!( - values[0]["project"]["sourcePaths"], - json!(["src/main/java", "module-a/src/main/java"]) - ); - let source_values = workspace_configuration( - "java", - &[ - WorkspaceConfigurationItem { - scope_uri: None, - section: Some("java.project".to_string()), - }, - WorkspaceConfigurationItem { - scope_uri: None, - section: Some("java.project.sourcePaths".to_string()), - }, - ], - maven_settings(&configuration), - ) - .unwrap(); - assert_eq!( - source_values, - vec![ - json!({ "sourcePaths": ["src/main/java", "module-a/src/main/java"] }), - json!(["src/main/java", "module-a/src/main/java"]), - ] - ); - - let notification = - initialized_notification("java", maven_settings(&configuration)).unwrap(); - assert_eq!( - notification.params["settings"]["java"]["configuration"]["maven"]["userSettings"], - "/local/settings.xml" - ); - assert_eq!( - notification.params["settings"]["java"]["configuration"]["maven"]["globalSettings"], - "/opt/maven/conf/settings.xml" - ); - assert_eq!( - notification.params["settings"]["java"]["project"]["sourcePaths"], - json!(["src/main/java", "module-a/src/main/java"]) - ); - assert_eq!( - maven_profile_update_requests(Some(&configuration)), - vec![ - json!({ - "command": "java.project.updateSettings", - "arguments": [ - "file:///workspace/reactor/", - { "org.eclipse.m2e.core.selectedProfiles": "dev,enterprise" } - ] - }), - json!({ - "command": "java.project.updateSettings", - "arguments": [ - "file:///workspace/reactor/module-a/", - { "org.eclipse.m2e.core.selectedProfiles": "dev,enterprise" } - ] - }), - json!({ - "command": "java.project.updateSettings", - "arguments": [ - "file:///workspace/reactor/module-a/nested/", - { "org.eclipse.m2e.core.selectedProfiles": "dev,enterprise" } - ] - }), - ] - ); - - let mut duplicated = configuration.clone(); - duplicated - .project_uris - .insert(1, duplicated.project_uris[0].clone()); - let requests = maven_profile_update_requests(Some(&duplicated)); - assert_eq!(requests.len(), 3); - assert_eq!(requests[0]["arguments"][0], "file:///workspace/reactor/"); - } - - #[test] - fn maven_profile_fingerprint_changes_when_selected_inputs_change() { - let mut configuration = JdtMavenConfiguration { - settings_path: Some("/settings.xml".to_string()), - global_settings_path: Some("/opt/maven/conf/settings.xml".to_string()), - profiles: vec!["dev".to_string()], - project_uris: vec!["file:///workspace".to_string()], - source_paths: vec!["src/main/java".to_string()], - }; - let first = maven_profile_fingerprint(Some(&configuration)); - configuration.profiles.push("test".to_string()); - let after_profiles = maven_profile_fingerprint(Some(&configuration)); - assert_ne!(first, after_profiles); - // Switching Maven installations changes the repository and mirrors the - // import resolves through, so a warm session must not skip the update. - configuration.global_settings_path = Some("/opt/other-maven/conf/settings.xml".to_string()); - assert_ne!( - after_profiles, - maven_profile_fingerprint(Some(&configuration)) - ); - } - - #[test] - fn jdt_location_is_read_only_with_a_source_display_path() { - let location = normalize_location( - "java", - ProviderLocation { - uri: "jdt://contents/java.base/java/util/Map%24Entry.class?=demo".to_string(), - is_read_only: false, - display_path: None, - }, - ); - - assert!(location.is_read_only); - assert_eq!( - location.display_path.as_deref(), - Some("java.base/java/util/Map$Entry.java") - ); - - let unchanged = normalize_location( - "java", - ProviderLocation { - uri: "file:///workspace/Main.java".to_string(), - is_read_only: false, - display_path: Some("Main.java".to_string()), - }, - ); - assert!(!unchanged.is_read_only); - assert_eq!(unchanged.display_path.as_deref(), Some("Main.java")); - } - - #[test] - fn virtual_source_uses_java_decompile_execute_command_params() { - let uri = "jdt://contents/java.base/java/lang/String.class"; - let params = virtual_source_resolve_params("java", uri).unwrap(); - let encoded = serde_json::to_value(params).unwrap(); - - assert_eq!(encoded["command"], "java.decompile"); - assert_eq!(encoded["arguments"], json!([uri])); - assert!(virtual_source_resolve_params("java", "file:///tmp/String.java").is_none()); - } - - #[test] - fn virtual_source_content_accepts_supported_jdt_result_shapes() { - assert_eq!( - virtual_source_content("java", &json!("class String {}")), - Some("class String {}".to_string()) - ); - assert_eq!( - virtual_source_content("java", &json!({ "content": "class Object {}" })), - Some("class Object {}".to_string()) - ); - assert!(virtual_source_content("go", &json!("class String {}")).is_none()); - assert!(virtual_source_content("java", &Value::Null).is_none()); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_build.rs b/rust/lithe-core/src/lsp/languages/jdt_build.rs deleted file mode 100644 index 0126cc7241..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_build.rs +++ /dev/null @@ -1,1235 +0,0 @@ -//! Coordination of JDT LS project builds requested by Run and Debug preparation. -//! -//! Java Debug Server's `vscode.java.buildWorkspace` builds every Java project in -//! the JDT workspace. Three upstream behaviors shape this coordinator: -//! -//! - Applying Maven profiles or changing build files schedules asynchronous JDT -//! project-update jobs, and the command that scheduled them returns before the -//! jobs finish. A build started meanwhile races JDT's own reconfiguration of -//! classpaths, annotation processing, and output folders, so builds wait until -//! those jobs report completion through work-done progress. -//! - Concurrent workspace builds in one JDT session contend for the same Eclipse -//! workspace rule and share builder state. Core therefore runs at most one build -//! per session and lets identical waiting requests share the next build. -//! - `$/cancelRequest` is advisory: JDT may keep building until an Eclipse job -//! observes cancellation. A build stays tracked until JDT answers, even after -//! every caller left, and the next build is not dispatched before that answer. -//! -//! The coordinator is a deterministic state machine. The engine supplies the -//! clock, allocates JSON-RPC IDs, and publishes the resulting events. - -use serde::Serialize; -use serde_json::Value; -use std::collections::{BTreeMap, VecDeque}; -use std::time::{Duration, Instant}; - -/// Java Debug Server command that builds the Java projects before a launch. -pub(crate) const JAVA_BUILD_WORKSPACE_COMMAND: &str = "vscode.java.buildWorkspace"; - -/// Default bound for one caller, covering the wait for project configuration, -/// the wait for an earlier build, and the build itself. Cold builds of large -/// multi-module projects with annotation processors take minutes, so the -/// ordinary 30-second semantic-request deadline does not apply. -pub(crate) const DEFAULT_JAVA_BUILD_TIMEOUT_MS: u64 = 10 * 60_000; - -/// A project-configuration job that reports no progress for this long no longer -/// blocks builds. JDT reports long update jobs every few seconds, but one -/// Maven step can stay silent for over a minute, so the bound stays generous -/// while still releasing builds if JDT never sends the matching `end`. -const PROJECT_CONFIGURATION_IDLE_TIMEOUT: Duration = Duration::from_secs(120); - -/// Job names JDT LS 1.38 reports while it rewrites project models. They come -/// from `ProjectsManager`: `updateProject`, `UpdateProjectsWorkspaceJob`, -/// `ImportProjectsFromSelectionJob`, and the workspace-folder update job. -const PROJECT_CONFIGURATION_JOB_PREFIXES: &[&str] = &[ - "Update project ", - "Updating project configurations", - "Applying the selected build files", - "Updating workspace folders", -]; - -const WORK_DONE_PROGRESS_METHOD: &str = "$/progress"; - -/// Why a queued build has not been sent to JDT LS yet. -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub(crate) enum JavaBuildBlock { - /// An earlier build has not received its terminal response. - PreviousBuild, - /// Core is still applying the selected Maven profiles. - MavenProfiles, - /// JDT reported a project-configuration job without its `end`. - ProjectConfiguration, -} - -impl JavaBuildBlock { - /// Stable identifier used in log details and timeout diagnostics. - pub(crate) fn as_str(self) -> &'static str { - match self { - Self::PreviousBuild => "waitingForPreviousBuild", - Self::MavenProfiles => "waitingForMavenProfiles", - Self::ProjectConfiguration => "waitingForProjectConfiguration", - } - } -} - -/// One work-done progress notification that may affect build gating. -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) enum ProjectJobProgress { - /// A job began; `label` is its task name or title. - Begin { token: String, label: String }, - /// A job reported progress, proving that it is still alive. - Report { token: String }, - /// A job finished. - End { token: String }, -} - -/// Parses a JDT work-done progress notification for build gating. -pub(crate) fn project_job_progress( - provider_id: &str, - method: Option<&str>, - params: Option<&Value>, -) -> Option { - if provider_id != "java" || method != Some(WORK_DONE_PROGRESS_METHOD) { - return None; - } - let params = params?; - let token = match params.get("token")? { - Value::String(token) => token.clone(), - Value::Number(token) => token.to_string(), - _ => return None, - }; - let value = params.get("value")?; - match value.get("kind").and_then(Value::as_str)? { - "begin" => { - // JDT puts the job name in `message` and may replace `title` with - // a subtask, so both are candidates for the job label. - let label = [value.get("message"), value.get("title")] - .into_iter() - .flatten() - .filter_map(Value::as_str) - .find(|label| is_project_configuration_job(label)) - .or_else(|| value.get("message").and_then(Value::as_str)) - .or_else(|| value.get("title").and_then(Value::as_str)) - .unwrap_or("") - .trim() - .to_string(); - Some(ProjectJobProgress::Begin { token, label }) - } - "report" => Some(ProjectJobProgress::Report { token }), - "end" => Some(ProjectJobProgress::End { token }), - _ => None, - } -} - -fn is_project_configuration_job(label: &str) -> bool { - let label = label.trim(); - PROJECT_CONFIGURATION_JOB_PREFIXES - .iter() - .any(|prefix| label.starts_with(prefix)) -} - -/// Returns whether an `executeCommand` payload asks Java Debug Server to build. -pub(crate) fn is_java_build_command(provider_id: &str, command: &Value) -> bool { - provider_id == "java" - && command.get("command").and_then(Value::as_str) == Some(JAVA_BUILD_WORKSPACE_COMMAND) -} - -/// Terminal result of one `vscode.java.buildWorkspace` call. -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub(crate) enum JavaBuildOutcome { - /// The build finished without error markers in the launched project. - Succeeded, - /// The build finished, but the launched project or a dependency has errors. - CompilationErrors, - /// JDT could not complete the build, for example after a builder exception. - Failed, - /// JDT observed cancellation before the build finished. - Cancelled, - /// The response did not contain a known build status. - Unrecognized, -} - -/// Which projects' error markers were requested for an unsuccessful build. -/// -/// Java Debug Server judges a build from the markers on the project owning the -/// main class plus the projects on its classpath. When it cannot identify that -/// owner it falls back to every project in the workspace, and an unrelated -/// module can then decide the verdict. Core cannot observe the project Java -/// Debug Server ultimately resolves, so this is evidence inferred from the -/// request rather than an authoritative account of the upstream marker query. -#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) enum JavaBuildMarkerScope { - /// The request named the owning project and asked upstream to scope to it. - LaunchTarget, - /// No owning project was named, so every project could decide the verdict. - Workspace, -} - -/// Recovery action a host should offer for an unsuccessful build. -#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) enum JavaBuildRecovery { - /// Nothing beyond fixing the reported code is indicated. - None, - /// The build reached a verdict about the code -- a builder failure or - /// error markers -- that may not describe the current sources: a failed - /// builder leaves markers that later builds neither refresh nor clear, and - /// error markers can also be decided by unrelated projects when the marker - /// scope widened. Resetting the Java index is the way back to a - /// trustworthy verdict, so it is offered alongside fixing the reported - /// errors. - RebuildJavaIndex, -} - -/// Evidence behind one unsuccessful Java launch build. -/// -/// A host must be able to explain a blocked launch and offer a way forward, so -/// this carries facts rather than a verdict: nothing here gates the launch by -/// itself, and the host decides what to show and which actions to enable. -#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct JavaBuildReport { - /// Marker scope inferred from the command arguments sent upstream. - pub marker_scope: JavaBuildMarkerScope, - /// An earlier build in this session ended with a builder failure, so the - /// markers behind this verdict may predate the current sources. - pub builder_failed_earlier: bool, - /// Wall-clock duration of this build, measured from dispatch to response. - /// A near-zero value can accompany an empty incremental build, but fast - /// successful builds and real stored errors are possible too; this value - /// is evidence only and never decides whether the verdict is trustworthy. - pub elapsed_milliseconds: u64, - /// Recovery action the host should offer alongside the reported errors. - pub recovery: JavaBuildRecovery, -} - -/// Derives the marker scope from the arguments sent to Java Debug Server. -/// -/// The command carries one JSON-encoded string argument. A missing, blank, or -/// unparsable `projectName` all reach Java Debug Server as blank, because it -/// applies `isNotBlank` before falling back to resolving the main class. -pub(crate) fn java_build_marker_scope(command: &Value) -> JavaBuildMarkerScope { - let named_project = command - .get("arguments") - .and_then(Value::as_array) - .and_then(|arguments| arguments.first()) - .and_then(Value::as_str) - .and_then(|encoded| serde_json::from_str::(encoded).ok()) - .as_ref() - .and_then(|payload| payload.get("projectName")) - .and_then(Value::as_str) - .is_some_and(|name| !name.trim().is_empty()); - if named_project { - JavaBuildMarkerScope::LaunchTarget - } else { - JavaBuildMarkerScope::Workspace - } -} - -/// Builds the report that accompanies an unsuccessful build. -/// -/// Any verdict about the code carries the rebuild option: a builder failure -/// leaves markers that later builds neither refresh nor clear, error markers -/// can be decided by unrelated projects when the marker scope widened, and a -/// project opened for the first time can still be mid-import while its -/// markers already read as errors. Cancellation and unrecognized results -/// reached no verdict about the code, so there the only useful action is a -/// retry. -pub(crate) fn java_build_report( - outcome: JavaBuildOutcome, - command: &Value, - builder_failed_earlier: bool, - elapsed: Duration, -) -> JavaBuildReport { - let recovery = if matches!( - outcome, - JavaBuildOutcome::Failed | JavaBuildOutcome::CompilationErrors - ) || builder_failed_earlier - { - JavaBuildRecovery::RebuildJavaIndex - } else { - JavaBuildRecovery::None - }; - JavaBuildReport { - marker_scope: java_build_marker_scope(command), - builder_failed_earlier, - elapsed_milliseconds: elapsed.as_millis() as u64, - recovery, - } -} - -/// Status returned by a Gradle build server when compilation fails. -const GRADLE_BUILD_SERVER_COMPILATION_ERROR: i64 = 100; - -/// Interprets the raw command result using JDT LS `BuildWorkspaceStatus` -/// (`FAILED`, `SUCCEED`, `WITH_ERROR`, `CANCELLED`, serialized by ordinal). -pub(crate) fn java_build_outcome(result: Option<&Value>) -> JavaBuildOutcome { - let numeric = match result { - Some(Value::Number(number)) => number.as_i64(), - Some(Value::String(text)) => match text.trim() { - "FAILED" => Some(0), - "SUCCEED" => Some(1), - "WITH_ERROR" => Some(2), - "CANCELLED" => Some(3), - other => other.parse().ok(), - }, - _ => None, - }; - match numeric { - Some(0) => JavaBuildOutcome::Failed, - Some(1) => JavaBuildOutcome::Succeeded, - Some(2) | Some(GRADLE_BUILD_SERVER_COMPILATION_ERROR) => { - JavaBuildOutcome::CompilationErrors - } - Some(3) => JavaBuildOutcome::Cancelled, - _ => JavaBuildOutcome::Unrecognized, - } -} - -/// Stable error code and user-facing message for an unsuccessful build. -pub(crate) fn java_build_failure( - outcome: JavaBuildOutcome, -) -> Option<(&'static str, &'static str)> { - match outcome { - JavaBuildOutcome::Succeeded => None, - JavaBuildOutcome::CompilationErrors => Some(( - "javaBuildCompilationErrors", - "The Java project build reported compilation errors.", - )), - JavaBuildOutcome::Failed => Some(( - "javaBuildFailed", - "The Java language service could not complete the project build. \ - Check the Java language server log for the build error.", - )), - JavaBuildOutcome::Cancelled => Some(( - "javaBuildCancelled", - "The Java project build was cancelled before it finished.", - )), - JavaBuildOutcome::Unrecognized => Some(( - "invalidServerResult", - "The Java language service returned an unknown project build status.", - )), - } -} - -#[derive(Debug, Clone)] -struct BuildWaiter { - operation_id: String, - created_at: Instant, - deadline: Instant, -} - -/// Callers that share one dispatch because they asked for the same build. -#[derive(Debug)] -struct BuildBatch { - /// Complete `workspace/executeCommand` params sent to JDT LS. - command: Value, - waiters: Vec, - queued_at: Instant, -} - -impl BuildBatch { - fn same_build(&self, command: &Value) -> bool { - self.command.get("command") == command.get("command") - && self.command.get("arguments") == command.get("arguments") - } - - fn remove_waiter(&mut self, operation_id: &str) -> bool { - let before = self.waiters.len(); - self.waiters - .retain(|waiter| waiter.operation_id != operation_id); - self.waiters.len() != before - } -} - -#[derive(Debug)] -struct InFlightBuild { - /// JSON-RPC ID of the request, retained until JDT answers. - request_id: String, - batch: BuildBatch, - started_at: Instant, - cancel_sent: bool, -} - -#[derive(Debug)] -struct ConfigurationJob { - last_activity: Instant, -} - -/// Result of trying to start the next queued build. -#[derive(Debug, Eq, PartialEq)] -pub(crate) enum JavaBuildDispatch { - /// No caller is waiting for a build. - Idle, - /// A caller is waiting; `newly` is true when the reason changed. - Blocked { block: JavaBuildBlock, newly: bool }, - /// The build was sent to JDT LS. - Started { - request_id: String, - waiter_count: usize, - waited: Duration, - }, -} - -/// Callers whose shared build received a terminal response. -#[derive(Debug, Eq, PartialEq)] -pub(crate) struct CompletedJavaBuild { - pub operation_ids: Vec, - pub elapsed: Duration, - /// The `executeCommand` params this build was dispatched with, so the - /// completion can report the marker scope requested upstream. - pub command: Value, -} - -/// Caller whose deadline elapsed before its build answered. -#[derive(Debug, Eq, PartialEq)] -pub(crate) struct ExpiredJavaBuildWaiter { - pub operation_id: String, - pub elapsed: Duration, - /// Stable phase reached before the deadline, for diagnostics. - pub phase: &'static str, -} - -/// Waiters that left because of cancellation, timeout, or session teardown. -#[derive(Debug, Default, Eq, PartialEq)] -pub(crate) struct JavaBuildDeparture { - pub expired: Vec, - /// Advisory cancellation to send when no caller still needs the running build. - pub cancel_request_id: Option, -} - -/// Per-session state that serializes and gates Java project builds. -#[derive(Debug, Default)] -pub(crate) struct JavaBuildCoordinator { - in_flight: Option, - queued: VecDeque, - configuration_jobs: BTreeMap, - /// Last block reason reported, so the monitor logs a reason once per change. - reported_block: Option, - /// A build in this session ended with a builder failure. JDT keeps the - /// error markers that failure left behind, and later incremental builds - /// neither refresh nor clear them, so every subsequent verdict is suspect - /// until the Java index is rebuilt. - builder_failed: bool, -} - -impl JavaBuildCoordinator { - /// Whether a builder failure was already observed in this session. - pub(crate) fn builder_failed_earlier(&self) -> bool { - self.builder_failed - } - - /// Records a terminal outcome so later builds can report that their markers - /// may predate the current sources. - pub(crate) fn observe_outcome(&mut self, outcome: JavaBuildOutcome) { - if outcome == JavaBuildOutcome::Failed { - self.builder_failed = true; - } - } - - /// Adds a caller. An identical queued build is shared; a running build - /// never is, because it may have started before the caller saved files. - pub(crate) fn enqueue( - &mut self, - operation_id: String, - command: Value, - now: Instant, - timeout: Duration, - ) { - let waiter = BuildWaiter { - operation_id, - created_at: now, - deadline: now + timeout, - }; - if let Some(batch) = self - .queued - .iter_mut() - .find(|batch| batch.same_build(&command)) - { - batch.waiters.push(waiter); - return; - } - self.queued.push_back(BuildBatch { - command, - waiters: vec![waiter], - queued_at: now, - }); - } - - /// Returns whether a caller is waiting for a build that has not started. - pub(crate) fn has_queued(&self) -> bool { - self.queued.iter().any(|batch| !batch.waiters.is_empty()) - } - - /// Returns whether `operation_id` is waiting for a build. - pub(crate) fn contains(&self, operation_id: &str) -> bool { - self.batches() - .flat_map(|batch| batch.waiters.iter()) - .any(|waiter| waiter.operation_id == operation_id) - } - - /// Operation IDs of every waiting caller, sorted for deterministic output. - #[cfg(test)] - pub(crate) fn operation_ids(&self) -> Vec { - let mut ids: Vec = self - .batches() - .flat_map(|batch| batch.waiters.iter()) - .map(|waiter| waiter.operation_id.clone()) - .collect(); - ids.sort(); - ids - } - - /// JSON-RPC ID of the build JDT is still running, if any. - pub(crate) fn in_flight_request_id(&self) -> Option<&str> { - self.in_flight - .as_ref() - .map(|build| build.request_id.as_str()) - } - - /// Reports the same bounded project-update gate used by build dispatch. - pub(crate) fn project_configuration_running(&mut self, now: Instant) -> bool { - self.configuration_jobs.retain(|_, job| { - now.saturating_duration_since(job.last_activity) < PROJECT_CONFIGURATION_IDLE_TIMEOUT - }); - !self.configuration_jobs.is_empty() - } - - /// Records a project-configuration job's lifecycle from work-done progress. - pub(crate) fn observe_progress(&mut self, progress: ProjectJobProgress, now: Instant) { - match progress { - ProjectJobProgress::Begin { token, label } => { - if is_project_configuration_job(&label) { - self.configuration_jobs - .insert(token, ConfigurationJob { last_activity: now }); - } - } - ProjectJobProgress::Report { token } => { - if let Some(job) = self.configuration_jobs.get_mut(&token) { - job.last_activity = now; - } - } - ProjectJobProgress::End { token } => { - self.configuration_jobs.remove(&token); - } - } - } - - /// Sends the next build when nothing blocks it. `allocate` writes the - /// JSON-RPC request for the command and returns its ID. If allocation - /// fails, the batch is discarded and its callers are returned with the - /// error so they fail once instead of being retried on every tick. - pub(crate) fn dispatch( - &mut self, - maven_profiles_running: bool, - now: Instant, - allocate: impl FnOnce(&Value) -> Result, - ) -> Result)> { - self.queued.retain(|batch| !batch.waiters.is_empty()); - if self.queued.is_empty() { - self.reported_block = None; - return Ok(JavaBuildDispatch::Idle); - } - if let Some(block) = self.block(maven_profiles_running, now) { - let newly = self.reported_block != Some(block); - self.reported_block = Some(block); - return Ok(JavaBuildDispatch::Blocked { block, newly }); - } - let Some(batch) = self.queued.pop_front() else { - return Ok(JavaBuildDispatch::Idle); - }; - let request_id = match allocate(&batch.command) { - Ok(request_id) => request_id, - Err(error) => { - self.reported_block = None; - let operation_ids = batch - .waiters - .into_iter() - .map(|waiter| waiter.operation_id) - .collect(); - return Err((error, operation_ids)); - } - }; - self.reported_block = None; - let waiter_count = batch.waiters.len(); - let waited = now.saturating_duration_since(batch.queued_at); - self.in_flight = Some(InFlightBuild { - request_id: request_id.clone(), - batch, - started_at: now, - cancel_sent: false, - }); - Ok(JavaBuildDispatch::Started { - request_id, - waiter_count, - waited, - }) - } - - /// Releases the running build after JDT answered `request_id`. - pub(crate) fn complete( - &mut self, - request_id: &str, - now: Instant, - ) -> Option { - if self.in_flight_request_id() != Some(request_id) { - return None; - } - let build = self.in_flight.take()?; - Some(CompletedJavaBuild { - operation_ids: build - .batch - .waiters - .into_iter() - .map(|waiter| waiter.operation_id) - .collect(), - elapsed: now.saturating_duration_since(build.started_at), - command: build.batch.command, - }) - } - - /// Removes one caller. Returns `None` when the operation is not a build. - pub(crate) fn cancel(&mut self, operation_id: &str) -> Option { - let removed = self - .in_flight - .as_mut() - .is_some_and(|build| build.batch.remove_waiter(operation_id)) - || self - .queued - .iter_mut() - .any(|batch| batch.remove_waiter(operation_id)); - if !removed { - return None; - } - self.queued.retain(|batch| !batch.waiters.is_empty()); - Some(JavaBuildDeparture { - expired: Vec::new(), - cancel_request_id: self.cancel_unneeded_build(), - }) - } - - /// Removes every caller whose deadline elapsed. - pub(crate) fn expire( - &mut self, - maven_profiles_running: bool, - now: Instant, - ) -> JavaBuildDeparture { - let queued_phase = self - .block(maven_profiles_running, now) - .map(JavaBuildBlock::as_str) - .unwrap_or("queued"); - let mut expired = Vec::new(); - let mut take_expired = |waiters: &mut Vec, phase: &'static str| { - waiters.retain(|waiter| { - if now < waiter.deadline { - return true; - } - expired.push(ExpiredJavaBuildWaiter { - operation_id: waiter.operation_id.clone(), - elapsed: now.saturating_duration_since(waiter.created_at), - phase, - }); - false - }); - }; - if let Some(build) = self.in_flight.as_mut() { - take_expired(&mut build.batch.waiters, "building"); - } - for batch in &mut self.queued { - take_expired(&mut batch.waiters, queued_phase); - } - if expired.is_empty() { - return JavaBuildDeparture::default(); - } - self.queued.retain(|batch| !batch.waiters.is_empty()); - JavaBuildDeparture { - expired, - cancel_request_id: self.cancel_unneeded_build(), - } - } - - /// Clears all state when the session stops or fails, returning the callers - /// to fail and the request ID of a build JDT had not answered. - pub(crate) fn drain(&mut self) -> (Vec, Option) { - let in_flight = self.in_flight.take(); - let request_id = in_flight.as_ref().map(|build| build.request_id.clone()); - let mut operation_ids: Vec = in_flight - .into_iter() - .map(|build| build.batch) - .chain(self.queued.drain(..)) - .flat_map(|batch| batch.waiters) - .map(|waiter| waiter.operation_id) - .collect(); - operation_ids.sort(); - self.configuration_jobs.clear(); - self.reported_block = None; - (operation_ids, request_id) - } - - fn batches(&self) -> impl Iterator { - self.in_flight - .iter() - .map(|build| &build.batch) - .chain(self.queued.iter()) - } - - fn block(&mut self, maven_profiles_running: bool, now: Instant) -> Option { - self.configuration_jobs.retain(|_, job| { - now.saturating_duration_since(job.last_activity) < PROJECT_CONFIGURATION_IDLE_TIMEOUT - }); - if self.in_flight.is_some() { - Some(JavaBuildBlock::PreviousBuild) - } else if maven_profiles_running { - Some(JavaBuildBlock::MavenProfiles) - } else if !self.configuration_jobs.is_empty() { - Some(JavaBuildBlock::ProjectConfiguration) - } else { - None - } - } - - /// Requests cancellation only when no running or queued caller still needs - /// a build: a queued caller benefits from the running build's output, and - /// interrupting JDT while it acquires workspace rules is itself risky. - fn cancel_unneeded_build(&mut self) -> Option { - let build = self.in_flight.as_mut()?; - if build.cancel_sent || !build.batch.waiters.is_empty() || !self.queued.is_empty() { - return None; - } - build.cancel_sent = true; - Some(build.request_id.clone()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - const TIMEOUT: Duration = Duration::from_secs(600); - - fn build_command(main_class: &str) -> Value { - json!({ - "title": "Build Java Workspace", - "command": JAVA_BUILD_WORKSPACE_COMMAND, - "arguments": [format!("{{\"mainClass\":\"{main_class}\",\"isFullBuild\":false}}")] - }) - } - - fn start_next( - coordinator: &mut JavaBuildCoordinator, - now: Instant, - request_id: &str, - ) -> JavaBuildDispatch { - coordinator - .dispatch(false, now, |_| Ok::<_, ()>(request_id.to_string())) - .unwrap_or_else(|_| panic!("allocation succeeds")) - } - - fn begin(token: &str, label: &str) -> ProjectJobProgress { - ProjectJobProgress::Begin { - token: token.to_string(), - label: label.to_string(), - } - } - - #[test] - fn marker_scope_follows_the_project_name_java_debug_would_use() { - let command = |arguments: Value| { - json!({ - "command": JAVA_BUILD_WORKSPACE_COMMAND, - "arguments": arguments, - }) - }; - let encoded = |payload: Value| json!([payload.to_string()]); - - assert_eq!( - java_build_marker_scope(&command(encoded( - json!({ "mainClass": "a.Main", "projectName": "service" }) - ))), - JavaBuildMarkerScope::LaunchTarget - ); - // Java Debug Server applies `isNotBlank`, so a missing field, an empty - // string, and whitespace all take the workspace-wide fallback. - assert_eq!( - java_build_marker_scope(&command(encoded(json!({ "mainClass": "a.Main" })))), - JavaBuildMarkerScope::Workspace - ); - assert_eq!( - java_build_marker_scope(&command(encoded( - json!({ "mainClass": "a.Main", "projectName": "" }) - ))), - JavaBuildMarkerScope::Workspace - ); - assert_eq!( - java_build_marker_scope(&command(encoded( - json!({ "mainClass": "a.Main", "projectName": " " }) - ))), - JavaBuildMarkerScope::Workspace - ); - // A payload Core cannot parse must not be reported as scoped. - assert_eq!( - java_build_marker_scope(&command(json!(["not json"]))), - JavaBuildMarkerScope::Workspace - ); - assert_eq!( - java_build_marker_scope(&command(json!([]))), - JavaBuildMarkerScope::Workspace - ); - } - - #[test] - fn a_builder_failure_marks_every_later_verdict_as_suspect() { - let mut coordinator = JavaBuildCoordinator::default(); - let command = json!({ - "command": JAVA_BUILD_WORKSPACE_COMMAND, - "arguments": [json!({ "projectName": "service" }).to_string()], - }); - - // The failure itself is the origin, not a casualty of an earlier one. - assert!(!coordinator.builder_failed_earlier()); - let failure = java_build_report( - JavaBuildOutcome::Failed, - &command, - coordinator.builder_failed_earlier(), - Duration::from_millis(5012), - ); - coordinator.observe_outcome(JavaBuildOutcome::Failed); - assert!(!failure.builder_failed_earlier); - assert_eq!(failure.recovery, JavaBuildRecovery::RebuildJavaIndex); - - // A later verdict stays suspect because the earlier builder failure may - // have left markers behind. Its short duration remains evidence only. - let leftover = java_build_report( - JavaBuildOutcome::CompilationErrors, - &command, - coordinator.builder_failed_earlier(), - Duration::from_millis(7), - ); - assert!(leftover.builder_failed_earlier); - assert_eq!(leftover.elapsed_milliseconds, 7); - assert_eq!(leftover.recovery, JavaBuildRecovery::RebuildJavaIndex); - assert_eq!(leftover.marker_scope, JavaBuildMarkerScope::LaunchTarget); - } - - #[test] - fn every_code_verdict_offers_the_workspace_reset() { - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.observe_outcome(JavaBuildOutcome::Succeeded); - coordinator.observe_outcome(JavaBuildOutcome::Cancelled); - assert!(!coordinator.builder_failed_earlier()); - - // Error markers can predate or misdescribe the current sources even - // without a builder failure -- a first import can still be running, - // and a widened marker scope lets unrelated projects decide the - // verdict -- so the rebuild option stays available for every verdict - // about the code. - let report = java_build_report( - JavaBuildOutcome::CompilationErrors, - &json!({ "command": JAVA_BUILD_WORKSPACE_COMMAND, "arguments": [] }), - coordinator.builder_failed_earlier(), - Duration::from_millis(12511), - ); - assert!(!report.builder_failed_earlier); - assert_eq!(report.recovery, JavaBuildRecovery::RebuildJavaIndex); - assert_eq!(report.marker_scope, JavaBuildMarkerScope::Workspace); - - // A cancelled build reached no verdict about the code, so resetting - // the workspace is not indicated. - let cancelled = java_build_report( - JavaBuildOutcome::Cancelled, - &json!({ "command": JAVA_BUILD_WORKSPACE_COMMAND, "arguments": [] }), - coordinator.builder_failed_earlier(), - Duration::from_millis(4), - ); - assert_eq!(cancelled.recovery, JavaBuildRecovery::None); - } - - #[test] - fn build_results_follow_jdt_build_workspace_status() { - assert_eq!( - java_build_outcome(Some(&json!(1))), - JavaBuildOutcome::Succeeded - ); - assert_eq!( - java_build_outcome(Some(&json!(0))), - JavaBuildOutcome::Failed - ); - assert_eq!( - java_build_outcome(Some(&json!(2))), - JavaBuildOutcome::CompilationErrors - ); - assert_eq!( - java_build_outcome(Some(&json!(3))), - JavaBuildOutcome::Cancelled - ); - assert_eq!( - java_build_outcome(Some(&json!(100))), - JavaBuildOutcome::CompilationErrors - ); - assert_eq!( - java_build_outcome(Some(&json!("WITH_ERROR"))), - JavaBuildOutcome::CompilationErrors - ); - assert_eq!( - java_build_outcome(Some(&json!("1"))), - JavaBuildOutcome::Succeeded - ); - assert_eq!(java_build_outcome(None), JavaBuildOutcome::Unrecognized); - assert_eq!(java_build_failure(JavaBuildOutcome::Succeeded), None); - let codes: Vec<_> = [ - JavaBuildOutcome::CompilationErrors, - JavaBuildOutcome::Failed, - JavaBuildOutcome::Cancelled, - JavaBuildOutcome::Unrecognized, - ] - .into_iter() - .filter_map(java_build_failure) - .map(|(code, _)| code) - .collect(); - // Each unsuccessful outcome keeps a distinct code so hosts never - // present an internal failure or cancellation as a source error. - assert_eq!( - codes, - [ - "javaBuildCompilationErrors", - "javaBuildFailed", - "javaBuildCancelled", - "invalidServerResult" - ] - ); - } - - #[test] - fn only_java_debug_build_commands_are_coordinated() { - assert!(is_java_build_command("java", &build_command("demo.App"))); - assert!(!is_java_build_command("gopls", &build_command("demo.App"))); - assert!(!is_java_build_command( - "java", - &json!({ "command": "vscode.java.resolveClasspath", "arguments": [] }) - )); - } - - #[test] - fn progress_parser_uses_job_names_and_numeric_tokens() { - let parsed = project_job_progress( - "java", - Some("$/progress"), - Some(&json!({ - "token": 7, - "value": { - "kind": "begin", - "message": "Update project ruoyi-vue-plus", - "title": "Refreshing '/ruoyi-vue-plus'." - } - })), - ); - assert_eq!(parsed, Some(begin("7", "Update project ruoyi-vue-plus"))); - assert_eq!( - project_job_progress( - "java", - Some("$/progress"), - Some(&json!({ "token": "a", "value": { "kind": "end" } })), - ), - Some(ProjectJobProgress::End { - token: "a".to_string() - }) - ); - assert_eq!( - project_job_progress( - "gopls", - Some("$/progress"), - Some(&json!({ "token": "a", "value": { "kind": "end" } })), - ), - None - ); - } - - #[test] - fn builds_wait_for_maven_profiles_and_project_updates() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.observe_progress(begin("update", "Update project ruoyi-vue-plus"), now); - coordinator.observe_progress(begin("build", "Building"), now); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - - let blocked = coordinator - .dispatch(true, now, |_| Ok::<_, ()>("never".to_string())) - .unwrap(); - assert_eq!( - blocked, - JavaBuildDispatch::Blocked { - block: JavaBuildBlock::MavenProfiles, - newly: true - } - ); - // Profiles finished, but the update job they scheduled is still running. - let blocked = coordinator - .dispatch(false, now, |_| Ok::<_, ()>("never".to_string())) - .unwrap(); - assert_eq!( - blocked, - JavaBuildDispatch::Blocked { - block: JavaBuildBlock::ProjectConfiguration, - newly: true - } - ); - let unchanged = coordinator - .dispatch(false, now, |_| Ok::<_, ()>("never".to_string())) - .unwrap(); - assert_eq!( - unchanged, - JavaBuildDispatch::Blocked { - block: JavaBuildBlock::ProjectConfiguration, - newly: false - } - ); - - coordinator.observe_progress( - ProjectJobProgress::End { - token: "update".into(), - }, - now, - ); - let later = now + Duration::from_secs(3); - assert_eq!( - start_next(&mut coordinator, later, "41"), - JavaBuildDispatch::Started { - request_id: "41".to_string(), - waiter_count: 1, - waited: Duration::from_secs(3), - } - ); - } - - #[test] - fn silent_configuration_jobs_stop_blocking_after_the_idle_bound() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.observe_progress(begin("update", "Updating project configurations"), now); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - - let reported = now + PROJECT_CONFIGURATION_IDLE_TIMEOUT - Duration::from_secs(1); - coordinator.observe_progress( - ProjectJobProgress::Report { - token: "update".into(), - }, - reported, - ); - assert!(matches!( - start_next( - &mut coordinator, - now + PROJECT_CONFIGURATION_IDLE_TIMEOUT, - "1" - ), - JavaBuildDispatch::Blocked { .. } - )); - assert!(matches!( - start_next( - &mut coordinator, - reported + PROJECT_CONFIGURATION_IDLE_TIMEOUT, - "1" - ), - JavaBuildDispatch::Started { .. } - )); - } - - #[test] - fn one_build_runs_at_a_time_and_identical_queued_requests_share_the_next() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - assert!(matches!( - start_next(&mut coordinator, now, "10"), - JavaBuildDispatch::Started { - waiter_count: 1, - .. - } - )); - // Repeated Run clicks while the first build is running: the running - // build is not shared because it may predate the latest save. - coordinator.enqueue("run-2".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.enqueue("run-3".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.enqueue("other".into(), build_command("demo.Other"), now, TIMEOUT); - assert_eq!( - start_next(&mut coordinator, now, "11"), - JavaBuildDispatch::Blocked { - block: JavaBuildBlock::PreviousBuild, - newly: true - } - ); - - let first = coordinator - .complete("10", now + Duration::from_secs(32)) - .unwrap(); - assert_eq!(first.operation_ids, ["run-1"]); - assert_eq!(first.elapsed, Duration::from_secs(32)); - assert!(matches!( - start_next(&mut coordinator, now, "11"), - JavaBuildDispatch::Started { - waiter_count: 2, - .. - } - )); - assert_eq!(coordinator.complete("unknown", now), None); - let second = coordinator.complete("11", now).unwrap(); - assert_eq!(second.operation_ids, ["run-2", "run-3"]); - assert!(matches!( - start_next(&mut coordinator, now, "12"), - JavaBuildDispatch::Started { - waiter_count: 1, - .. - } - )); - assert_eq!( - coordinator.complete("12", now).unwrap().operation_ids, - ["other"] - ); - assert_eq!( - start_next(&mut coordinator, now, "13"), - JavaBuildDispatch::Idle - ); - } - - #[test] - fn cancelling_the_only_caller_cancels_but_keeps_tracking_the_running_build() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - start_next(&mut coordinator, now, "10"); - - let departure = coordinator.cancel("run-1").unwrap(); - assert_eq!(departure.cancel_request_id.as_deref(), Some("10")); - assert_eq!(coordinator.cancel("run-1"), None); - // JDT may keep building after advisory cancellation, so a new caller - // waits for that build's response instead of overlapping it. - coordinator.enqueue("run-2".into(), build_command("demo.App"), now, TIMEOUT); - assert!(matches!( - start_next(&mut coordinator, now, "11"), - JavaBuildDispatch::Blocked { - block: JavaBuildBlock::PreviousBuild, - .. - } - )); - let abandoned = coordinator.complete("10", now).unwrap(); - assert!(abandoned.operation_ids.is_empty()); - assert!(matches!( - start_next(&mut coordinator, now, "11"), - JavaBuildDispatch::Started { .. } - )); - } - - #[test] - fn a_running_build_is_not_cancelled_while_another_caller_needs_a_build() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.enqueue("run-1b".into(), build_command("demo.App"), now, TIMEOUT); - start_next(&mut coordinator, now, "10"); - coordinator.enqueue("run-2".into(), build_command("demo.App"), now, TIMEOUT); - - assert_eq!(coordinator.cancel("run-1").unwrap().cancel_request_id, None); - assert_eq!( - coordinator.cancel("run-1b").unwrap().cancel_request_id, - None - ); - // The last caller leaving the queue makes the running build unneeded. - assert_eq!( - coordinator - .cancel("run-2") - .unwrap() - .cancel_request_id - .as_deref(), - Some("10") - ); - assert!(coordinator.operation_ids().is_empty()); - assert_eq!(coordinator.in_flight_request_id(), Some("10")); - } - - #[test] - fn deadlines_report_the_phase_each_caller_reached() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - let short = Duration::from_secs(30); - coordinator.enqueue("building".into(), build_command("demo.App"), now, short); - start_next(&mut coordinator, now, "10"); - coordinator.enqueue("queued".into(), build_command("demo.App"), now, short); - coordinator.enqueue("patient".into(), build_command("demo.App"), now, TIMEOUT); - - assert_eq!( - coordinator.expire(false, now + Duration::from_secs(29)), - JavaBuildDeparture::default() - ); - let departure = coordinator.expire(false, now + short); - assert_eq!( - departure.expired, - [ - ExpiredJavaBuildWaiter { - operation_id: "building".to_string(), - elapsed: short, - phase: "building", - }, - ExpiredJavaBuildWaiter { - operation_id: "queued".to_string(), - elapsed: short, - phase: "waitingForPreviousBuild", - }, - ] - ); - // `patient` still needs a build, so the running one is not cancelled. - assert_eq!(departure.cancel_request_id, None); - assert_eq!(coordinator.operation_ids(), ["patient"]); - } - - #[test] - fn draining_returns_every_caller_and_the_unanswered_build() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.observe_progress(begin("update", "Update project app"), now); - coordinator.enqueue("b".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.observe_progress( - ProjectJobProgress::End { - token: "update".into(), - }, - now, - ); - start_next(&mut coordinator, now, "10"); - coordinator.enqueue("a".into(), build_command("demo.Other"), now, TIMEOUT); - - let (operation_ids, request_id) = coordinator.drain(); - assert_eq!(operation_ids, ["a", "b"]); - assert_eq!(request_id.as_deref(), Some("10")); - assert!(!coordinator.contains("a")); - assert_eq!( - start_next(&mut coordinator, now, "11"), - JavaBuildDispatch::Idle - ); - } - - #[test] - fn allocation_failure_fails_the_batch_once_and_keeps_later_builds() { - let now = Instant::now(); - let mut coordinator = JavaBuildCoordinator::default(); - coordinator.enqueue("run-1".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.enqueue("run-1b".into(), build_command("demo.App"), now, TIMEOUT); - coordinator.enqueue("other".into(), build_command("demo.Other"), now, TIMEOUT); - let failed = coordinator.dispatch(false, now, |_| Err::("encode failed")); - assert_eq!( - failed, - Err(( - "encode failed", - vec!["run-1".to_string(), "run-1b".to_string()] - )) - ); - assert!(!coordinator.contains("run-1")); - assert_eq!(coordinator.in_flight_request_id(), None); - assert!(matches!( - start_next(&mut coordinator, now, "10"), - JavaBuildDispatch::Started { - waiter_count: 1, - .. - } - )); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_configuration.rs b/rust/lithe-core/src/lsp/languages/jdt_configuration.rs deleted file mode 100644 index fc3c8a9fed..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_configuration.rs +++ /dev/null @@ -1,453 +0,0 @@ -//! Writable Equinox configuration areas for packaged JDT LS installations. -//! -//! Equinox writes its framework state (bundle caches, resolver state, locks, -//! and p2 data) into the directory passed as `-configuration`. Packaged JDT LS -//! ships its `config_` directory inside the installed product: the -//! signed macOS app bundle, whose exact bytes are the base of Sparkle delta -//! updates, and the Windows installation directory. Handing that directory to -//! Equinox turns every launch into a modification of the release. -//! -//! As vscode-java does, the only shipped input, `config.ini`, is copied into -//! the host cache under a directory named by the file's SHA-256. The file lists -//! every bundle with its version, so a JDT LS upgrade receives a fresh area -//! instead of reusing framework state recorded for other bundles, and Equinox -//! never reads or writes the installation's configuration directory. - -use super::java_workspace::{jdt_cache_retention, JdtCacheEntry, JdtCacheRetentionRequest}; -use crate::protocol::{CoreError, ErrorCode}; -use sha2::{Digest, Sha256}; -use std::fs; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -/// Cache subdirectory holding one configuration area per `config.ini` digest. -/// -/// It is a sibling of the `-data` directories under `jdtls/` so that the -/// workspace retention adapters, which scan `jdtls/`, never treat an area in -/// use by another installation as an expired workspace. -pub(crate) const CONFIGURATION_AREAS_DIRECTORY: &str = "jdtls-configuration"; -/// The only file JDT LS ships in a platform configuration directory. -const CONFIG_INI: &str = "config.ini"; -/// Directory passed as `-configuration`, one level below the area root because -/// JDT LS's `config.ini` sets `eclipse.p2.data.area=@config.dir/../p2`, which -/// must resolve inside the same area. -const EQUINOX_CONFIGURATION_DIRECTORY: &str = "configuration"; -/// File in an area root recording the last launch that used it, as Unix seconds. -const LAST_USED_MARKER: &str = ".lithe-last-used"; - -static NEXT_TEMPORARY_FILE: AtomicU64 = AtomicU64::new(0); - -/// Configuration area selected for one JDT LS launch. -#[derive(Debug, Eq, PartialEq)] -pub(crate) struct PreparedConfigurationArea { - /// Writable directory passed to JDT LS as `-configuration`. - pub directory: PathBuf, - /// Digests of other areas removed because no launch used them within the - /// shared JDT cache retention period, in ascending order. - pub removed_keys: Vec, - /// Why expired areas could not be removed. Only disk space is at stake, - /// so the launch proceeds and the engine reports this as a warning. - pub cleanup_failure: Option, -} - -/// Returns the writable configuration area for the packaged configuration -/// directory `packaged_configuration`, creating or repairing it as needed. -/// -/// The area lives under `cache_directory`, which must resolve outside the JDT -/// LS installation; a cache inside it, including through a symbolic link, is -/// rejected before anything is written. Areas of other `config.ini` digests -/// that no launch used within the retention period are removed afterwards. -pub(crate) fn prepare_configuration_area( - cache_directory: &Path, - packaged_configuration: &Path, - now_unix_seconds: u64, -) -> Result { - let packaged_configuration = fs::canonicalize(packaged_configuration).map_err(|error| { - start_failure("The Java language-server configuration directory is unavailable.") - .with_details(error.to_string()) - })?; - let installation_root = packaged_configuration - .parent() - .unwrap_or(&packaged_configuration) - .to_path_buf(); - let config_ini = fs::read(packaged_configuration.join(CONFIG_INI)).map_err(|error| { - start_failure("The Java language-server configuration has no config.ini.") - .with_details(error.to_string()) - })?; - let key = format!("{:x}", Sha256::digest(&config_ini)); - let areas_root = cache_directory.join(CONFIGURATION_AREAS_DIRECTORY); - let area_root = areas_root.join(&key); - let directory = area_root.join(EQUINOX_CONFIGURATION_DIRECTORY); - - // Resolve through the deepest existing ancestor so that a symbolic link - // anywhere in the cache path is followed before the first write. - ensure_outside_installation(&directory, &installation_root)?; - fs::create_dir_all(&directory).map_err(|error| { - start_failure("Could not create the Java language-server configuration area.") - .with_details(error.to_string()) - })?; - ensure_outside_installation(&directory, &installation_root)?; - write_if_changed(&directory.join(CONFIG_INI), &config_ini)?; - fs::write( - area_root.join(LAST_USED_MARKER), - now_unix_seconds.to_string(), - ) - .map_err(|error| { - start_failure("Could not record the Java language-server configuration area use.") - .with_details(error.to_string()) - })?; - - let (removed_keys, cleanup_failure) = remove_expired_areas(&areas_root, &key, now_unix_seconds); - Ok(PreparedConfigurationArea { - directory, - removed_keys, - cleanup_failure, - }) -} - -fn start_failure(message: &str) -> CoreError { - CoreError::new(ErrorCode::ProcessStartFailed, message) -} - -fn ensure_outside_installation(path: &Path, installation_root: &Path) -> Result<(), CoreError> { - let resolved = resolve_existing_prefix(path).map_err(|error| { - start_failure("Could not resolve the Java language-server cache directory.") - .with_details(error.to_string()) - })?; - if resolved.starts_with(installation_root) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The Java language-server cache must be outside the JDT LS installation.", - )); - } - Ok(()) -} - -/// Canonicalizes the deepest existing ancestor of `path` and appends the -/// components that do not exist yet, which cannot be symbolic links. -fn resolve_existing_prefix(path: &Path) -> std::io::Result { - let mut missing = Vec::new(); - let mut current = path; - loop { - match fs::canonicalize(current) { - Ok(resolved) => { - return Ok(missing - .iter() - .rev() - .fold(resolved, |resolved, component| resolved.join(component))) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let (Some(parent), Some(name)) = (current.parent(), current.file_name()) else { - return Err(error); - }; - missing.push(name.to_os_string()); - current = parent; - } - Err(error) => return Err(error), - } - } -} - -/// Replaces `path` atomically unless it already holds `contents`, so a damaged -/// or truncated copy is repaired and concurrent launches never observe a -/// partially written file. -fn write_if_changed(path: &Path, contents: &[u8]) -> Result<(), CoreError> { - if fs::read(path).is_ok_and(|current| current == contents) { - return Ok(()); - } - let temporary = path.with_file_name(format!( - ".{CONFIG_INI}.{}-{}.tmp", - std::process::id(), - NEXT_TEMPORARY_FILE.fetch_add(1, Ordering::Relaxed) - )); - let result = fs::write(&temporary, contents).and_then(|()| fs::rename(&temporary, path)); - if result.is_err() { - // This boundary keeps the primary result; WARN exposes leftover staging. - let mut cleanup = crate::diagnostics::core_events::StorageCleanup::default(); - cleanup.observe(fs::remove_file(&temporary)); - cleanup.finish("jdt-configuration"); - } - result.map_err(|error| { - start_failure("Could not write the Java language-server configuration.") - .with_details(error.to_string()) - }) -} - -fn remove_expired_areas( - areas_root: &Path, - active_key: &str, - now_unix_seconds: u64, -) -> (Vec, Option) { - let entries = match fs::read_dir(areas_root) { - Ok(entries) => entries, - Err(error) => return (Vec::new(), Some(error.to_string())), - }; - let mut candidates = Vec::new(); - for entry in entries.flatten() { - let Ok(metadata) = fs::symlink_metadata(entry.path()) else { - continue; - }; - // A link is never followed: removing through it could delete data - // that does not belong to the cache. - if !metadata.is_dir() { - continue; - } - let Some(key) = entry.file_name().to_str().map(str::to_string) else { - continue; - }; - let last_used = fs::read_to_string(entry.path().join(LAST_USED_MARKER)) - .ok() - .and_then(|marker| marker.trim().parse::().ok()) - .or_else(|| { - metadata - .modified() - .ok() - .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()) - .map(|elapsed| elapsed.as_secs()) - }) - .unwrap_or(0); - candidates.push(JdtCacheEntry { - workspace_key: key, - last_modified_unix_seconds: last_used, - }); - } - // The workspace retention policy only accepts SHA-256 names and never - // selects the active one, which are exactly the rules for areas too. - let plan = match jdt_cache_retention(JdtCacheRetentionRequest { - now_unix_seconds, - active_workspace_key: Some(active_key.to_string()), - entries: candidates, - }) { - Ok(plan) => plan, - Err(error) => return (Vec::new(), Some(error.message)), - }; - let mut removed = Vec::new(); - let mut failures = Vec::new(); - for key in plan.expired_workspace_keys { - match fs::remove_dir_all(areas_root.join(&key)) { - Ok(()) => removed.push(key), - Err(error) => failures.push(format!("{key}: {error}")), - } - } - let failure = (!failures.is_empty()).then(|| failures.join("; ")); - (removed, failure) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::BTreeMap; - - static NEXT_SCRATCH: AtomicU64 = AtomicU64::new(0); - const DAY: u64 = 24 * 60 * 60; - const NOW: u64 = 1_800_000_000; - const CONFIG: &[u8] = - b"osgi.bundles=reference\\:file\\:org.eclipse.jdt.ls.core_1.61.0.jar@4\\:start\n"; - - /// A packaged JDT LS installation and a separate host cache, removed on - /// drop so a failed assertion does not leak them. - struct Scratch { - root: PathBuf, - } - - impl Scratch { - fn new() -> Self { - let root = std::env::temp_dir().join(format!( - "lithe-jdt-configuration-{}-{}", - std::process::id(), - NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed) - )); - let _ = fs::remove_dir_all(&root); - let configuration = root.join("installation/jdtls/config_mac"); - fs::create_dir_all(&configuration).expect("configuration should be created"); - fs::write(configuration.join(CONFIG_INI), CONFIG) - .expect("config.ini should be written"); - fs::create_dir_all(root.join("installation/jdtls/plugins")).expect("plugins"); - fs::write(root.join("installation/jdtls/plugins/equinox.jar"), b"jar").expect("jar"); - Self { root } - } - - fn installation(&self) -> PathBuf { - self.root.join("installation") - } - - fn packaged_configuration(&self) -> PathBuf { - self.installation().join("jdtls/config_mac") - } - - fn cache(&self) -> PathBuf { - self.root.join("cache") - } - - fn prepare(&self, now: u64) -> Result { - prepare_configuration_area(&self.cache(), &self.packaged_configuration(), now) - } - } - - impl Drop for Scratch { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.root); - } - } - - /// Relative path and contents of every file below `root`. - fn snapshot(root: &Path) -> BTreeMap> { - let mut files = BTreeMap::new(); - let mut pending = vec![root.to_path_buf()]; - while let Some(directory) = pending.pop() { - for entry in fs::read_dir(&directory).expect("directory should be readable") { - let path = entry.expect("entry should be readable").path(); - if path.is_dir() { - pending.push(path); - } else { - let contents = fs::read(&path).expect("file should be readable"); - files.insert(path.strip_prefix(root).unwrap().to_path_buf(), contents); - } - } - } - files - } - - fn key() -> String { - format!("{:x}", Sha256::digest(CONFIG)) - } - - #[test] - fn equinox_state_lands_in_the_cache_and_the_installation_stays_byte_identical() { - let scratch = Scratch::new(); - let before = snapshot(&scratch.installation()); - - let area = scratch.prepare(NOW).expect("the area should be prepared"); - // Equinox writes its framework state into the -configuration directory. - fs::create_dir_all(area.directory.join("org.eclipse.osgi")).expect("state directory"); - fs::write(area.directory.join("org.eclipse.osgi/.manager"), b"lock").expect("state"); - - assert_eq!( - area.directory, - scratch - .cache() - .join(CONFIGURATION_AREAS_DIRECTORY) - .join(key()) - .join(EQUINOX_CONFIGURATION_DIRECTORY) - ); - assert_eq!(fs::read(area.directory.join(CONFIG_INI)).unwrap(), CONFIG); - assert_eq!(snapshot(&scratch.installation()), before); - } - - #[test] - fn a_damaged_copy_is_repaired_and_equinox_state_is_kept() { - let scratch = Scratch::new(); - let first = scratch.prepare(NOW).expect("the area should be prepared"); - fs::create_dir_all(first.directory.join("org.eclipse.osgi")).expect("state directory"); - fs::write(first.directory.join(CONFIG_INI), b"truncat").expect("damage"); - - let second = scratch - .prepare(NOW) - .expect("a damaged copy should be repaired"); - assert_eq!(second.directory, first.directory); - assert_eq!(fs::read(second.directory.join(CONFIG_INI)).unwrap(), CONFIG); - assert!(second.directory.join("org.eclipse.osgi").is_dir()); - - fs::remove_file(second.directory.join(CONFIG_INI)).expect("delete the copy"); - let third = scratch - .prepare(NOW) - .expect("a missing copy should be restored"); - assert_eq!(fs::read(third.directory.join(CONFIG_INI)).unwrap(), CONFIG); - } - - #[test] - fn a_new_config_ini_selects_a_fresh_area() { - let scratch = Scratch::new(); - let first = scratch.prepare(NOW).expect("the area should be prepared"); - fs::write( - scratch.packaged_configuration().join(CONFIG_INI), - b"osgi.bundles=reference\\:file\\:org.eclipse.jdt.ls.core_1.62.0.jar@4\\:start\n", - ) - .expect("upgrade"); - - let upgraded = scratch - .prepare(NOW) - .expect("the upgraded area should be prepared"); - assert_ne!(upgraded.directory, first.directory); - assert!(first.directory.is_dir(), "a recently used area is retained"); - } - - #[test] - fn a_cache_inside_the_installation_is_rejected_before_anything_is_written() { - let scratch = Scratch::new(); - let before = snapshot(&scratch.installation()); - - let error = prepare_configuration_area( - &scratch.installation().join("jdtls/cache"), - &scratch.packaged_configuration(), - NOW, - ) - .expect_err("a cache inside the installation must be rejected"); - - assert!(matches!(error.code, ErrorCode::InvalidRequest)); - assert_eq!(snapshot(&scratch.installation()), before); - assert!(!scratch.installation().join("jdtls/cache").exists()); - } - - #[cfg(unix)] - #[test] - fn a_cache_linked_into_the_installation_is_rejected_before_anything_is_written() { - let scratch = Scratch::new(); - let before = snapshot(&scratch.installation()); - fs::create_dir_all(scratch.cache()).expect("cache"); - std::os::unix::fs::symlink( - scratch.installation().join("jdtls"), - scratch.cache().join(CONFIGURATION_AREAS_DIRECTORY), - ) - .expect("link"); - - let error = scratch - .prepare(NOW) - .expect_err("a cache linked into the installation must be rejected"); - - assert!(matches!(error.code, ErrorCode::InvalidRequest)); - assert_eq!(snapshot(&scratch.installation()), before); - } - - #[test] - fn a_missing_config_ini_fails_the_start() { - let scratch = Scratch::new(); - fs::remove_file(scratch.packaged_configuration().join(CONFIG_INI)).expect("remove"); - - let error = scratch.prepare(NOW).expect_err("config.ini is required"); - - assert!(matches!(error.code, ErrorCode::ProcessStartFailed)); - assert!(!scratch.cache().exists()); - } - - #[test] - fn areas_unused_for_the_retention_period_are_removed() { - let scratch = Scratch::new(); - let areas = scratch.cache().join(CONFIGURATION_AREAS_DIRECTORY); - let expired = "a".repeat(64); - let recent = "b".repeat(64); - for (name, last_used) in [(&expired, NOW - 31 * DAY), (&recent, NOW - 29 * DAY)] { - fs::create_dir_all(areas.join(name).join(EQUINOX_CONFIGURATION_DIRECTORY)) - .expect("area"); - fs::write( - areas.join(name).join(LAST_USED_MARKER), - last_used.to_string(), - ) - .expect("marker"); - } - // A directory that is not an area is never removed. - fs::create_dir_all(areas.join("p2")).expect("foreign directory"); - - let area = scratch.prepare(NOW).expect("the area should be prepared"); - - assert_eq!(area.removed_keys, vec![expired.clone()]); - assert_eq!(area.cleanup_failure, None); - assert!(!areas.join(&expired).exists()); - assert!(areas.join(&recent).is_dir()); - assert!(areas.join("p2").is_dir()); - assert_eq!( - fs::read_to_string(areas.join(key()).join(LAST_USED_MARKER)).unwrap(), - NOW.to_string() - ); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_maven_settings.rs b/rust/lithe-core/src/lsp/languages/jdt_maven_settings.rs deleted file mode 100644 index 89aca8eec2..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_maven_settings.rs +++ /dev/null @@ -1,559 +0,0 @@ -//! Content-addressed copies of the Maven settings documents JDT LS reads. -//! -//! JDT LS decides whether Maven settings changed by comparing the settings -//! *paths* it receives (`StandardPreferenceManager.update`). Only a changed path -//! makes it reload the settings and force-update every Maven project. A file -//! edited in place, or a generated file rewritten under a fixed name, therefore -//! leaves the running import on the old mirrors and local repository. -//! -//! Every settings document Lithe hands to JDT LS is copied into the session's -//! `-data` directory under a name derived from its contents. A content change is -//! then always a path change, which lets the upstream change detection do the -//! reload instead of Lithe re-implementing it. The copies live and die with the -//! JDT LS workspace state that uses them, and never touch the user's files or -//! the installed product. - -use crate::project::MavenJdtConfiguration; -use crate::protocol::{CoreError, ErrorCode}; -use sha2::{Digest, Sha256}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -/// Directory inside the JDT LS `-data` directory that holds the copies. -const SETTINGS_DIRECTORY: &[&str] = &[".lithe", "maven"]; -/// File-name prefix of the user-level copy (`java.configuration.maven.userSettings`). -const USER_SETTINGS_PREFIX: &str = "user-settings-"; -/// File-name prefix of the installation-level copy (`java.configuration.maven.globalSettings`). -const GLOBAL_SETTINGS_PREFIX: &str = "global-settings-"; -/// Hex digits of the content digest kept in a file name. -const DIGEST_LENGTH: usize = 16; - -/// Bare user-level settings used when Maven Settings overrides the local -/// repository without naming a settings file of its own. -const EMPTY_MAVEN_SETTINGS: &str = r#" - - -"#; - -/// Settings paths to send to JDT LS for one Maven configuration. -#[derive(Debug, Default, Eq, PartialEq)] -pub(crate) struct MaterializedMavenSettings { - /// Path sent as `userSettings`, or `None` to leave JDT LS on Maven's default. - pub user_settings_path: Option, - /// Path sent as `globalSettings`, or `None` when no installation is known. - pub global_settings_path: Option, - /// Problems that degraded a document to its original path. They are - /// reported to the session log rather than failing startup, because a - /// stale settings path must not cost every Java file its language service. - pub warnings: Vec, -} - -/// Directory holding the settings copies for one JDT LS `-data` directory. -pub(crate) fn settings_directory(data_directory: &Path) -> PathBuf { - SETTINGS_DIRECTORY - .iter() - .fold(data_directory.to_path_buf(), |path, part| path.join(part)) -} - -/// Maven's default user-level settings file, `${user.home}/.m2/settings.xml`. -/// -/// Maven reads it whenever no settings file is configured, so JDT LS must see -/// the same document through a content-addressed copy. The home directory -/// comes from the language server's launch environment first, because that is -/// the environment Maven inside JDT LS observes. -pub(crate) fn default_user_settings_path( - environment: &std::collections::BTreeMap, -) -> Option { - let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; - let home = environment - .get(variable) - .filter(|value| !value.trim().is_empty()) - .map(PathBuf::from) - .or_else(|| std::env::var_os(variable).map(PathBuf::from))?; - Some(home.join(".m2").join("settings.xml")) -} - -/// Writes the content-addressed settings copies for `configuration` into -/// `directory`. Copies remain valid until the owning JDT workspace is removed: -/// sending a notification does not acknowledge that JDT LS has read the file. -/// -/// The user-level source is the configured settings file, else Maven's default -/// user settings when they exist, else an empty document when only a local -/// repository override is configured. JDT LS has no repository preference, so -/// that override is written into the user-level copy. -pub(crate) fn materialize( - directory: &Path, - configuration: &MavenJdtConfiguration, - default_user_settings: Option<&Path>, -) -> Result { - let mut warnings = Vec::new(); - - let user_source = match configuration.settings_path.as_deref() { - Some(path) => Some(SettingsSource::Configured(path.to_string())), - None => default_user_settings - .filter(|path| path.is_file()) - .map(|path| SettingsSource::Configured(path.to_string_lossy().into_owned())) - .or_else(|| { - configuration - .local_repository_path - .as_ref() - .map(|_| SettingsSource::Empty) - }), - }; - let user_settings_path = match user_source { - None => None, - Some(source) => match source.read() { - Ok(document) => { - let document = match configuration.local_repository_path.as_deref() { - Some(repository) => { - crate::project::settings_with_local_repository(&document, repository)? - } - None => document, - }; - let path = write_copy(directory, USER_SETTINGS_PREFIX, &document)?; - Some(path.to_string_lossy().into_owned()) - } - Err((path, error)) => { - warnings.push(format!( - "Could not read the Maven settings file {path}, so the Java language service reads it directly and ignores the local repository override: {error}" - )); - Some(path) - } - }, - }; - - let global_settings_path = match configuration.global_settings_path.as_deref() { - None => None, - Some(path) => match std::fs::read_to_string(path) { - Ok(document) => { - let copy = write_copy(directory, GLOBAL_SETTINGS_PREFIX, &document)?; - Some(copy.to_string_lossy().into_owned()) - } - Err(error) => { - warnings.push(format!( - "Could not read the Maven installation settings file {path}, so the Java language service reads it directly: {error}" - )); - Some(path.to_string()) - } - }, - }; - - Ok(MaterializedMavenSettings { - user_settings_path, - global_settings_path, - warnings, - }) -} - -/// Where the user-level document comes from. -enum SettingsSource { - /// A settings file on disk, configured or Maven's default. - Configured(String), - /// No file exists, but a local repository override needs a document. - Empty, -} - -impl SettingsSource { - fn read(&self) -> Result { - match self { - Self::Configured(path) => { - std::fs::read_to_string(path).map_err(|error| (path.clone(), error)) - } - Self::Empty => Ok(EMPTY_MAVEN_SETTINGS.to_string()), - } - } -} - -/// Writes `document` under a name derived from its contents. -/// -/// An existing file with that name already holds the same bytes, so it is -/// reused. New files are written beside the target and renamed into place so -/// JDT LS never reads a partially written document. -fn write_copy(directory: &Path, prefix: &str, document: &str) -> Result { - let digest = Sha256::digest(document.as_bytes()); - let name = format!("{prefix}{}.xml", &hex(&digest)[..DIGEST_LENGTH]); - let target = directory.join(name); - if target.is_file() { - return Ok(target); - } - std::fs::create_dir_all(directory).map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not create the Maven settings directory.", - ) - .with_details(error.to_string()) - })?; - static NEXT_COPY: AtomicU64 = AtomicU64::new(0); - // Exclusive creation also avoids truncating a stale staging file after PID reuse. - let (staging, mut file) = loop { - let nonce = NEXT_COPY.fetch_add(1, Ordering::Relaxed); - let path = directory.join(format!(".{prefix}{}-{nonce}.tmp", std::process::id())); - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - match options.open(&path) { - Ok(file) => break (path, file), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => { - return Err(CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not create the generated Maven settings.", - ) - .with_details(error.to_string())) - } - } - }; - file.write_all(document.as_bytes()) - .and_then(|()| { - drop(file); - std::fs::rename(&staging, &target).or_else(|error| { - // Windows can reject replacing a copy another writer just published. - // Only accept that result when the full content matches. - if std::fs::read(&target).is_ok_and(|bytes| bytes == document.as_bytes()) { - std::fs::remove_file(&staging) - } else { - Err(error) - } - }) - }) - .map_err(|error| { - // This boundary keeps the primary result; WARN exposes leftover staging. - let mut cleanup = crate::diagnostics::core_events::StorageCleanup::default(); - cleanup.observe(std::fs::remove_file(&staging)); - cleanup.finish("maven-settings"); - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not write the generated Maven settings.", - ) - .with_details(error.to_string()) - })?; - Ok(target) -} - -fn hex(bytes: &[u8]) -> String { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - let mut value = String::with_capacity(bytes.len() * 2); - for byte in bytes { - value.push(DIGITS[(byte >> 4) as usize] as char); - value.push(DIGITS[(byte & 0x0f) as usize] as char); - } - value -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Temporary directory removed when the test ends, pass or fail. - struct Scratch(PathBuf); - - impl Scratch { - fn new(label: &str) -> Self { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock should be valid") - .as_nanos(); - let root = std::env::temp_dir().join(format!( - "lithe-maven-settings-{label}-{}-{nonce}", - std::process::id() - )); - std::fs::create_dir_all(&root).expect("scratch directory should be creatable"); - Self(root) - } - - fn write(&self, name: &str, contents: &str) -> String { - let path = self.0.join(name); - std::fs::write(&path, contents).expect("fixture should be writable"); - path.to_string_lossy().into_owned() - } - - fn copies(&self) -> PathBuf { - settings_directory(&self.0.join("data")) - } - } - - impl Drop for Scratch { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn configuration( - settings_path: Option, - global_settings_path: Option, - local_repository_path: Option<&str>, - ) -> MavenJdtConfiguration { - MavenJdtConfiguration { - profiles: Vec::new(), - settings_path, - global_settings_path, - local_repository_path: local_repository_path.map(ToString::to_string), - project_paths: Vec::new(), - source_paths: Vec::new(), - } - } - - fn read(path: &Option) -> String { - std::fs::read_to_string(path.as_deref().expect("a copy should be produced")) - .expect("copy should exist") - } - - #[test] - fn a_repository_override_keeps_the_configured_mirrors() { - // JDT LS has no repository preference, so the override travels inside a - // settings document. The copy must not drop the mirrors the workspace - // already resolves through. - let scratch = Scratch::new("repository-override"); - let configured = scratch.write( - "settings.xml", - r#"/oldaliyunmaven"#, - ); - - let materialized = materialize( - &scratch.copies(), - &configuration(Some(configured.clone()), None, Some("/opt/repository")), - None, - ) - .expect("settings should be materialized"); - - let document = read(&materialized.user_settings_path); - assert!(document.contains("/opt/repository")); - assert!(document.contains("aliyunmaven")); - assert!(!document.contains("/old")); - assert!(materialized.warnings.is_empty()); - let original = std::fs::read_to_string(configured).expect("source should still exist"); - assert!(original.contains("/old")); - } - - #[test] - fn a_repository_override_without_settings_uses_a_minimal_document() { - let scratch = Scratch::new("repository-only"); - - let materialized = materialize( - &scratch.copies(), - &configuration(None, None, Some("/opt/repository")), - None, - ) - .expect("settings should be materialized"); - - assert!(read(&materialized.user_settings_path) - .contains("/opt/repository")); - } - - #[test] - fn configured_settings_without_an_override_are_still_copied() { - // Passing the user's own path would let an in-place edit go unnoticed: - // JDT LS compares paths, so the copy is what makes the edit visible. - let scratch = Scratch::new("no-override"); - let configured = scratch.write("settings.xml", ""); - - let materialized = materialize( - &scratch.copies(), - &configuration(Some(configured.clone()), None, None), - None, - ) - .expect("settings should be materialized"); - - let copy = materialized.user_settings_path.clone().expect("copy"); - assert_ne!(copy, configured); - assert!(Path::new(©).starts_with(scratch.copies())); - assert_eq!( - read(&materialized.user_settings_path), - "" - ); - } - - #[test] - fn editing_a_settings_file_changes_the_path_jdt_ls_receives() { - // Regression for #970: a generated file under a fixed name made every - // later settings change invisible to JDT LS's path comparison. - let scratch = Scratch::new("content-change"); - let configured = scratch.write("settings.xml", ""); - let first = materialize( - &scratch.copies(), - &configuration(Some(configured.clone()), None, Some("/first")), - None, - ) - .expect("first materialization"); - let unchanged = materialize( - &scratch.copies(), - &configuration(Some(configured.clone()), None, Some("/first")), - None, - ) - .expect("repeated materialization"); - let repository_changed = materialize( - &scratch.copies(), - &configuration(Some(configured.clone()), None, Some("/second")), - None, - ) - .expect("repository change"); - scratch.write( - "settings.xml", - "", - ); - let file_edited = materialize( - &scratch.copies(), - &configuration(Some(configured), None, Some("/second")), - None, - ) - .expect("file edit"); - - assert_eq!(first.user_settings_path, unchanged.user_settings_path); - assert_ne!( - first.user_settings_path, - repository_changed.user_settings_path - ); - assert_ne!( - repository_changed.user_settings_path, - file_edited.user_settings_path - ); - } - - #[test] - fn installation_settings_are_copied_by_content() { - let scratch = Scratch::new("global"); - let global = scratch.write("global.xml", ""); - - let first = materialize( - &scratch.copies(), - &configuration(None, Some(global.clone()), None), - None, - ) - .expect("global settings"); - assert_eq!( - read(&first.global_settings_path), - "" - ); - assert_eq!(first.user_settings_path, None); - scratch.write("global.xml", ""); - let edited = materialize( - &scratch.copies(), - &configuration(None, Some(global), None), - None, - ) - .expect("edited global settings"); - - assert_ne!(first.global_settings_path, edited.global_settings_path); - assert_eq!( - read(&edited.global_settings_path), - "" - ); - } - - #[test] - fn maven_default_user_settings_are_used_when_none_are_configured() { - let scratch = Scratch::new("default-user"); - let default = - PathBuf::from(scratch.write("default.xml", "")); - - let materialized = materialize( - &scratch.copies(), - &configuration(None, None, None), - Some(&default), - ) - .expect("default settings"); - assert_eq!( - read(&materialized.user_settings_path), - "" - ); - let absent = materialize( - &scratch.copies(), - &configuration(None, None, None), - Some(&scratch.0.join("missing.xml")), - ) - .expect("absent default settings"); - - // Without a document JDT LS keeps Maven's own default, as the CLI does. - assert_eq!(absent.user_settings_path, None); - } - - #[test] - fn copies_remain_readable_until_the_workspace_is_removed() { - let scratch = Scratch::new("prune"); - let first = materialize( - &scratch.copies(), - &configuration(None, None, Some("/first")), - None, - ) - .expect("first"); - let second = materialize( - &scratch.copies(), - &configuration(None, None, Some("/second")), - None, - ) - .expect("second"); - - assert!(read(&first.user_settings_path).contains("/first")); - assert!(Path::new(second.user_settings_path.as_deref().unwrap()).exists()); - } - - #[test] - fn an_unowned_staging_file_is_never_truncated_or_removed() { - let scratch = Scratch::new("staging-owner"); - let copies = scratch.copies(); - std::fs::create_dir_all(&copies).unwrap(); - // The old PID-only name could belong to another update in this process. - let other = copies.join(format!(".{USER_SETTINGS_PREFIX}{}.tmp", std::process::id())); - std::fs::write(&other, "another writer's settings").unwrap(); - let result = materialize(&copies, &configuration(None, None, Some("/new")), None).unwrap(); - assert!(read(&result.user_settings_path).contains("/new")); - assert_eq!( - std::fs::read_to_string(other).unwrap(), - "another writer's settings" - ); - } - - #[test] - fn an_unreadable_settings_file_warns_instead_of_failing_the_java_session() { - // Losing the repository override costs one optional setting. Failing - // here would leave every Java file without completion, navigation, and - // diagnostics because of a stale path in Maven Settings. - let scratch = Scratch::new("unreadable"); - let missing = scratch.0.join("deleted.xml").to_string_lossy().into_owned(); - - let materialized = materialize( - &scratch.copies(), - &configuration( - Some(missing.clone()), - Some(missing.clone()), - Some("/opt/repository"), - ), - None, - ) - .expect("an unreadable settings file must not fail startup"); - - assert_eq!( - materialized.user_settings_path.as_deref(), - Some(missing.as_str()) - ); - assert_eq!( - materialized.global_settings_path.as_deref(), - Some(missing.as_str()) - ); - assert_eq!(materialized.warnings.len(), 2); - assert!(materialized.warnings[0].contains("local repository override")); - } - - #[test] - fn the_default_user_settings_follow_the_launch_environment() { - let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; - let environment = - std::collections::BTreeMap::from([(variable.to_string(), "/fixture/home".to_string())]); - - assert_eq!( - default_user_settings_path(&environment), - Some( - PathBuf::from("/fixture/home") - .join(".m2") - .join("settings.xml") - ) - ); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_navigation.rs b/rust/lithe-core/src/lsp/languages/jdt_navigation.rs deleted file mode 100644 index 49815ac43a..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_navigation.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! JDT LS navigation-marker planning and normalization shared by every platform frontend. - -use super::java_navigation_syntax::navigation_candidates; -use crate::protocol::JavaNavigationMarkerResponse; -use serde_json::json; -use serde_json::Value; -use std::collections::VecDeque; -use std::time::Instant; - -/// Maximum semantic verification work accepted for one document version. -pub(crate) const MAX_JAVA_NAVIGATION_TASKS: usize = 64; - -/// Bounded multi-request projection of JDT LS data into visible gutter markers. -pub(crate) struct JavaNavigationMarkerBatch { - tasks: VecDeque, - active_task: Option, - resolved_lenses: Vec, - semantic_markers: Vec, - total_tasks: usize, - created_at: Instant, - deadline: Instant, -} - -#[derive(Clone)] -/// One provider request needed to verify a possible Java navigation relation. -pub(crate) enum JavaNavigationMarkerTask { - ResolveCodeLens(Value), - FindImplementations(super::java_navigation_syntax::JavaNavigationCandidate), - FindSuperImplementation(super::java_navigation_syntax::JavaNavigationCandidate), -} - -impl JavaNavigationMarkerBatch { - /// Plans a deterministic, bounded batch from initial CodeLens data and synchronized source. - pub(crate) fn new( - raw_lenses: &[Value], - source: &str, - created_at: Instant, - deadline: Instant, - ) -> Self { - let mut implementation_lenses = implementation_code_lenses(raw_lenses); - let (resolved_lenses, unresolved_lenses): (Vec<_>, Vec<_>) = implementation_lenses - .drain(..) - .partition(is_resolved_implementation_lens); - let candidates = navigation_candidates(source); - let mut tasks = unresolved_lenses - .into_iter() - .map(JavaNavigationMarkerTask::ResolveCodeLens) - .collect::>(); - // Parent checks run before child checks so an override arrow can appear - // even when the fixed task budget is exhausted by a very large type. - tasks.extend( - candidates - .iter() - .filter(|candidate| candidate.direction == "up") - .cloned() - .map(JavaNavigationMarkerTask::FindSuperImplementation), - ); - tasks.extend( - candidates - .into_iter() - .filter(|candidate| candidate.direction == "down") - .map(JavaNavigationMarkerTask::FindImplementations), - ); - let total_tasks = tasks.len(); - tasks.truncate(MAX_JAVA_NAVIGATION_TASKS); - Self { - tasks, - active_task: None, - resolved_lenses, - semantic_markers: Vec::new(), - total_tasks, - created_at, - deadline, - } - } - - /// Removes and tracks the next semantic verification request. - pub(crate) fn take_next(&mut self) -> Option { - let task = self.tasks.pop_front()?; - self.active_task = Some(task.clone()); - Some(task) - } - - /// Merges a successful provider response into the partial projection. - pub(crate) fn record_active_result(&mut self, result: Option<&Value>) { - let Some(task) = self.active_task.take() else { - return; - }; - match task { - JavaNavigationMarkerTask::ResolveCodeLens(_) => { - if let Some(lens) = result.cloned().filter(is_resolved_implementation_lens) { - self.resolved_lenses.push(lens); - } - } - JavaNavigationMarkerTask::FindImplementations(candidate) - | JavaNavigationMarkerTask::FindSuperImplementation(candidate) => { - let count = raw_location_count(result); - if count > 0 { - self.semantic_markers.push(JavaNavigationMarkerResponse { - line: usize::try_from(candidate.line).unwrap_or_default(), - utf16_column: usize::try_from(candidate.utf16_column).unwrap_or_default(), - implementation_count: count, - direction: candidate.direction.to_string(), - relation: candidate.relation.to_string(), - }); - } - } - } - } - - /// Produces the deterministic final marker list, including partial successes. - pub(crate) fn finish(self, source: &str) -> Vec { - let mut markers = markers_from_resolved_code_lenses(&self.resolved_lenses, source); - markers.extend(self.semantic_markers); - normalized_markers(markers) - } - - pub(crate) fn total_tasks(&self) -> usize { - self.total_tasks - } - - pub(crate) fn resolved_lens_count(&self) -> usize { - self.resolved_lenses.len() - } - - pub(crate) fn created_at(&self) -> Instant { - self.created_at - } - - pub(crate) fn deadline(&self) -> Instant { - self.deadline - } -} - -impl JavaNavigationMarkerTask { - /// Returns the provider method and params for this verification step. - pub(crate) fn request(&self, uri: &str) -> (&'static str, Value) { - match self { - Self::ResolveCodeLens(lens) => ("codeLens/resolve", lens.clone()), - Self::FindImplementations(candidate) => ( - "textDocument/implementation", - json!({ - "textDocument": { "uri": uri }, - "position": { - "line": candidate.line, - "character": candidate.utf16_column - } - }), - ), - Self::FindSuperImplementation(candidate) => ( - "java/findLinks", - json!({ - "type": "superImplementation", - "position": { - "textDocument": { "uri": uri }, - "position": { - "line": candidate.line, - "character": candidate.utf16_column - } - } - }), - ), - } - } -} - -fn raw_location_count(result: Option<&Value>) -> usize { - match result { - Some(Value::Array(locations)) => locations.len(), - Some(Value::Object(_)) => 1, - _ => 0, - } -} - -/// Keeps only JDT LS implementation lenses; reference lenses never drive gutter icons. -pub(crate) fn implementation_code_lenses(values: &[Value]) -> Vec { - values - .iter() - .filter(|lens| { - resolved_implementation_title(lens).is_some() - || lens - .get("data") - .and_then(Value::as_array) - .and_then(|data| data.get(2)) - .and_then(Value::as_str) - == Some("implementations") - }) - .cloned() - .collect() -} - -/// Returns whether JDT LS has already attached the target count to a lens. -pub(crate) fn is_resolved_implementation_lens(lens: &Value) -> bool { - resolved_implementation_title(lens).is_some() -} - -/// Converts resolved JDT LS implementation CodeLens entries into gutter markers. -/// -/// JDT LS 1.38 only emits implementation lenses for interfaces and abstract -/// classes. It does not encode the declaration kind in the lens, so the -/// synchronized source is used solely to distinguish those two relationships. -/// Zero-target lenses are intentionally omitted to match IDEA gutter behavior. -pub(crate) fn markers_from_resolved_code_lenses( - code_lenses: &[Value], - source: &str, -) -> Vec { - let markers = code_lenses - .iter() - .filter_map(|lens| marker_from_resolved_code_lens(lens, source)) - .collect::>(); - normalized_markers(markers) -} - -/// Applies the deterministic ordering and identity used by the shared contract. -pub(crate) fn normalized_markers( - mut markers: Vec, -) -> Vec { - markers.sort_by(|left, right| { - left.line - .cmp(&right.line) - .then_with(|| left.utf16_column.cmp(&right.utf16_column)) - .then_with(|| left.relation.cmp(&right.relation)) - }); - markers.dedup_by(|left, right| { - left.line == right.line - && left.utf16_column == right.utf16_column - && left.direction == right.direction - && left.relation == right.relation - }); - markers -} - -fn marker_from_resolved_code_lens( - lens: &Value, - source: &str, -) -> Option { - let count = implementation_count(resolved_implementation_title(lens)?)?; - if count == 0 { - return None; - } - let start = lens.get("range")?.get("start")?; - let line = usize::try_from(start.get("line")?.as_i64()?).ok()?; - let utf16_column = start - .get("utf16Column") - .or_else(|| start.get("character")) - .and_then(Value::as_i64) - .and_then(|column| usize::try_from(column).ok())?; - let relation = if declaration_prefix(source, line, utf16_column) - .split(|character: char| !character.is_ascii_alphanumeric() && character != '_') - .any(|word| word == "interface") - { - "interface" - } else { - "inheritance" - }; - Some(JavaNavigationMarkerResponse { - line, - utf16_column, - implementation_count: count, - direction: "down".to_string(), - relation: relation.to_string(), - }) -} - -fn resolved_implementation_title(lens: &Value) -> Option<&str> { - let title = lens.get("command")?.get("title")?.as_str()?.trim(); - implementation_count(title).map(|_| title) -} - -fn implementation_count(title: &str) -> Option { - let mut parts = title.split_whitespace(); - let count = parts.next()?.parse::().ok()?; - let noun = parts.next()?; - if matches!(noun, "implementation" | "implementations") && parts.next().is_none() { - Some(count) - } else { - None - } -} - -fn declaration_prefix(source: &str, line: usize, utf16_column: usize) -> &str { - let Some(line_text) = source.lines().nth(line) else { - return ""; - }; - let byte_column = line_text - .char_indices() - .scan(0usize, |units, (offset, character)| { - let current = *units; - *units += character.len_utf16(); - Some((offset, current)) - }) - .find_map(|(offset, units)| (units >= utf16_column).then_some(offset)) - .unwrap_or(line_text.len()); - &line_text[..byte_column] -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn resolved_lenses_distinguish_interface_and_abstract_class_declarations() { - let source = "public interface Service {}\npublic abstract class Base {}\n"; - let lenses = vec![ - json!({ - "range": { "start": { "line": 0, "utf16Column": 17 } }, - "command": { "title": "2 implementations" } - }), - json!({ - "range": { "start": { "line": 1, "utf16Column": 22 } }, - "command": { "title": "1 implementation" } - }), - ]; - - let markers = markers_from_resolved_code_lenses(&lenses, source); - - assert_eq!(markers.len(), 2); - assert_eq!(markers[0].relation, "interface"); - assert_eq!(markers[0].implementation_count, 2); - assert_eq!(markers[1].relation, "inheritance"); - } - - #[test] - fn unresolved_zero_target_and_reference_lenses_do_not_create_markers() { - let lenses = vec![ - json!({ "range": { "start": { "line": 0, "utf16Column": 0 } } }), - json!({ - "range": { "start": { "line": 0, "utf16Column": 0 } }, - "command": { "title": "0 implementations" } - }), - json!({ - "range": { "start": { "line": 0, "utf16Column": 0 } }, - "command": { "title": "3 references" } - }), - ]; - - assert!(markers_from_resolved_code_lenses(&lenses, "interface Service {}").is_empty()); - } - - #[test] - fn implementation_filter_uses_jdt_data_before_lenses_are_resolved() { - let lenses = vec![ - json!({ "data": ["file:///Service.java", { "line": 0 }, "implementations"] }), - json!({ "data": ["file:///Service.java", { "line": 0 }, "references"] }), - json!({ "command": { "title": "1 implementation" } }), - ]; - - let filtered = implementation_code_lenses(&lenses); - - assert_eq!(filtered.len(), 2); - assert!(!is_resolved_implementation_lens(&filtered[0])); - assert!(is_resolved_implementation_lens(&filtered[1])); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_progress.rs b/rust/lithe-core/src/lsp/languages/jdt_progress.rs deleted file mode 100644 index 5a485596c8..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_progress.rs +++ /dev/null @@ -1,531 +0,0 @@ -//! Stateful, throttled diagnostics for JDT LS workspace-import progress. - -use super::jdt::JdtImportProgress; -use serde_json::json; -use std::collections::{BTreeMap, BTreeSet}; -use std::time::{Duration, Instant}; - -const JAVA_PROGRESS_LOG_INTERVAL_MS: u64 = 2_000; -const JAVA_PROGRESS_PERCENTAGE_STEP: u64 = 5; - -struct JavaDownloadDiagnostics { - artifact: String, - repository_host: Option, - started_at: Instant, - downloaded_bytes: Option, - total_bytes: Option, -} - -/// Java-only preparation observations retained until `ServiceReady` or timeout. -pub(crate) struct JavaPreparationDiagnostics { - startup_started_at: Instant, - process_start_elapsed: Duration, - cache_disposition: &'static str, - workspace_fingerprint_present: bool, - readiness_started_at: Option, - last_progress_at: Option, - absolute_deadline: Option, - idle_timeout: Duration, - idle_warning_reported: bool, - last_activity_signature: Option, - phase: Option, - progress_percentage: Option, - current_project: Option, - observed_projects: BTreeSet, - observed_downloads: BTreeMap, - active_download: Option, - last_log_at: Option, - last_logged_phase: Option, - last_logged_project: Option, - last_logged_percentage: Option, - last_logged_download_bytes: Option, - initialize_elapsed: Option, -} - -impl JavaPreparationDiagnostics { - /// Starts diagnostics with the process-launch and durable-cache observations. - pub(crate) fn new( - startup_started_at: Instant, - process_start_elapsed: Duration, - cache_disposition: &'static str, - workspace_fingerprint_present: bool, - ) -> Self { - Self { - startup_started_at, - process_start_elapsed, - cache_disposition, - workspace_fingerprint_present, - readiness_started_at: None, - last_progress_at: None, - absolute_deadline: None, - idle_timeout: Duration::ZERO, - idle_warning_reported: false, - last_activity_signature: None, - phase: None, - progress_percentage: None, - current_project: None, - observed_projects: BTreeSet::new(), - observed_downloads: BTreeMap::new(), - active_download: None, - last_log_at: None, - last_logged_phase: None, - last_logged_project: None, - last_logged_percentage: None, - last_logged_download_bytes: None, - initialize_elapsed: None, - } - } - - /// Serializes the process-start observation for platform log adapters. - pub(crate) fn startup_detail(&self) -> String { - json!({ - "stage": "processStart", - "processStartMilliseconds": self.process_start_elapsed.as_millis(), - "cacheDisposition": self.cache_disposition, - "workspaceFingerprintPresent": self.workspace_fingerprint_present, - }) - .to_string() - } - - /// Switches from the standard initialize handshake to post-initialize readiness. - pub(crate) fn begin_readiness( - &mut self, - now: Instant, - initialize_elapsed: Duration, - idle_timeout: Duration, - absolute_timeout: Duration, - ) -> String { - self.initialize_elapsed = Some(initialize_elapsed); - self.readiness_started_at = Some(now); - self.last_progress_at = Some(now); - self.absolute_deadline = Some(now + absolute_timeout); - self.idle_timeout = idle_timeout; - self.idle_warning_reported = false; - json!({ - "stage": "serviceReady", - "initializeMilliseconds": initialize_elapsed.as_millis(), - "idleTimeoutMilliseconds": idle_timeout.as_millis(), - "absoluteTimeoutMilliseconds": absolute_timeout.as_millis(), - "cacheDisposition": self.cache_disposition, - }) - .to_string() - } - - /// Records changed work-done progress and returns a throttled JSON log detail. - pub(crate) fn record_progress( - &mut self, - progress: JdtImportProgress, - now: Instant, - ) -> Option { - self.readiness_started_at?; - if self.last_activity_signature.as_deref() == Some(&progress.activity_signature) { - return None; - } - self.last_activity_signature = Some(progress.activity_signature); - self.last_progress_at = Some(now); - self.idle_warning_reported = false; - - let phase_changed = progress - .phase - .as_ref() - .is_some_and(|phase| self.last_logged_phase.as_deref() != Some(phase.as_str())); - let project_changed = progress - .current_project - .as_ref() - .is_some_and(|project| self.last_logged_project.as_deref() != Some(project.as_str())); - let percentage_advanced = progress.percentage.is_some_and(|percentage| { - self.last_logged_percentage.is_none_or(|logged| { - percentage >= logged.saturating_add(JAVA_PROGRESS_PERCENTAGE_STEP) - }) - }); - let download_finished = progress.download.is_none() && self.active_download.is_some(); - - if let Some(phase) = progress.phase { - self.phase = Some(phase); - } - if let Some(percentage) = progress.percentage { - self.progress_percentage = Some(percentage); - } - if let Some(project) = progress.current_project { - self.observed_projects.insert(project.clone()); - self.current_project = Some(project); - } - - let mut download_advanced = false; - if let Some(download) = progress.download { - let download_key = format!( - "{}/{}", - download.repository_host.as_deref().unwrap_or("unknown"), - download.artifact - ); - let observed = self.observed_downloads.entry(download_key).or_default(); - if let Some(downloaded_bytes) = download.downloaded_bytes { - *observed = (*observed).max(downloaded_bytes); - download_advanced = self - .last_logged_download_bytes - .is_none_or(|logged| downloaded_bytes > logged); - } - let same_download = self.active_download.as_ref().is_some_and(|active| { - active.artifact == download.artifact - && active.repository_host == download.repository_host - }); - if same_download { - if let Some(active) = self.active_download.as_mut() { - active.downloaded_bytes = download.downloaded_bytes; - active.total_bytes = download.total_bytes; - } - } else { - self.active_download = Some(JavaDownloadDiagnostics { - artifact: download.artifact, - repository_host: download.repository_host, - started_at: now, - downloaded_bytes: download.downloaded_bytes, - total_bytes: download.total_bytes, - }); - self.last_logged_download_bytes = None; - download_advanced = true; - } - } else { - self.active_download = None; - self.last_logged_download_bytes = None; - } - - let log_interval_elapsed = self.last_log_at.is_none_or(|logged_at| { - now.saturating_duration_since(logged_at) - >= Duration::from_millis(JAVA_PROGRESS_LOG_INTERVAL_MS) - }); - let should_log = phase_changed - || project_changed - || percentage_advanced - || download_finished - || (download_advanced && log_interval_elapsed); - if !should_log { - return None; - } - - self.last_log_at = Some(now); - self.last_logged_phase = self.phase.clone(); - self.last_logged_project = self.current_project.clone(); - self.last_logged_percentage = self.progress_percentage; - self.last_logged_download_bytes = self - .active_download - .as_ref() - .and_then(|download| download.downloaded_bytes); - Some(self.progress_detail(now)) - } - - fn progress_detail(&self, now: Instant) -> String { - let (artifact, repository_host, downloaded_bytes, total_bytes, bytes_per_second) = self - .active_download - .as_ref() - .map(|download| { - let elapsed = now.saturating_duration_since(download.started_at); - let throughput = download.downloaded_bytes.and_then(|bytes| { - (elapsed > Duration::ZERO) - .then(|| (bytes as f64 / elapsed.as_secs_f64()).round() as u64) - }); - ( - Some(download.artifact.clone()), - download.repository_host.clone(), - download.downloaded_bytes, - download.total_bytes, - throughput, - ) - }) - .unwrap_or((None, None, None, None, None)); - json!({ - "stage": "serviceReady", - "phase": self.phase, - "progressPercent": self.progress_percentage, - "currentProject": self.current_project, - "observedProjectCount": self.observed_projects.len(), - "downloadArtifact": artifact, - "repositoryHost": repository_host, - "downloadedBytes": downloaded_bytes, - "totalBytes": total_bytes, - "bytesPerSecond": bytes_per_second, - "elapsedMilliseconds": self.readiness_started_at - .map(|started| now.saturating_duration_since(started).as_millis()), - "idleMilliseconds": self.last_progress_at - .map(|progress| now.saturating_duration_since(progress).as_millis()), - "cacheDisposition": self.cache_disposition, - }) - .to_string() - } - - /// Scalar observation for catalog logging, separate from v1 JSON presentation. - pub(crate) fn log_progress(&self, now: Instant) -> serde_json::Value { - json!({"progressPercent": self.progress_percentage, "idleMilliseconds": self.last_progress_at.map(|at| now.saturating_duration_since(at).as_millis() as u64).unwrap_or(0)}) - } - - /// Elapsed import time before ready_detail consumes the readiness state. - pub(crate) fn log_import(&self, now: Instant) -> serde_json::Value { - json!({"importMilliseconds": self.readiness_started_at.map(|at| now.saturating_duration_since(at).as_millis() as u64)}) - } - - /// Finishes preparation and serializes one aggregate startup summary. - pub(crate) fn ready_detail(&mut self, now: Instant) -> String { - let import_elapsed = self - .readiness_started_at - .map(|started| now.saturating_duration_since(started)); - self.readiness_started_at = None; - self.absolute_deadline = None; - let downloaded_bytes: u64 = self.observed_downloads.values().copied().sum(); - json!({ - "stage": "serviceReady", - "outcome": "ready", - "totalMilliseconds": now.saturating_duration_since(self.startup_started_at).as_millis(), - "processStartMilliseconds": self.process_start_elapsed.as_millis(), - "initializeMilliseconds": self.initialize_elapsed.map(|elapsed| elapsed.as_millis()), - "importMilliseconds": import_elapsed.map(|elapsed| elapsed.as_millis()), - "progressPercent": self.progress_percentage, - "observedProjectCount": self.observed_projects.len(), - "downloadedArtifactCount": self.observed_downloads.len(), - "downloadedBytes": downloaded_bytes, - "cacheDisposition": self.cache_disposition, - }) - .to_string() - } - - /// Reports each quiet interval once without treating optional progress as a heartbeat. - pub(crate) fn take_idle_warning(&mut self, now: Instant) -> Option { - let started_at = self.readiness_started_at?; - let idle = now.saturating_duration_since(self.last_progress_at.unwrap_or(started_at)); - if self.idle_warning_reported || idle < self.idle_timeout { - return None; - } - self.idle_warning_reported = true; - Some(self.progress_detail(now)) - } - - /// Takes the absolute timeout once and returns its diagnostic snapshot. - pub(crate) fn take_timeout(&mut self, now: Instant) -> Option { - let started_at = self.readiness_started_at?; - if now < self.absolute_deadline? { - return None; - } - let last_progress_at = self.last_progress_at.unwrap_or(started_at); - let idle = now.saturating_duration_since(last_progress_at); - // JDT reports work milestones, not liveness. Silence is diagnostic only; - // even a quiet Maven import retains the full, bounded readiness budget. - let classification = match (idle >= self.idle_timeout, self.active_download.is_some()) { - (true, true) => "networkDownloadStalled", - (true, false) => "noProgressStall", - (false, true) => "networkTransferActive", - _ => "projectImportActive", - }; - self.readiness_started_at = None; - self.absolute_deadline = None; - Some( - json!({ - "stage": "serviceReady", - "timeoutKind": "absolute", - "classification": classification, - "elapsedMilliseconds": now.saturating_duration_since(started_at).as_millis(), - "idleMilliseconds": idle.as_millis(), - "progressPercent": self.progress_percentage, - "phase": self.phase, - "currentProject": self.current_project, - "observedProjectCount": self.observed_projects.len(), - "downloadArtifact": self.active_download.as_ref().map(|download| &download.artifact), - "downloadedBytes": self.active_download.as_ref().and_then(|download| download.downloaded_bytes), - "totalBytes": self.active_download.as_ref().and_then(|download| download.total_bytes), - "cacheDisposition": self.cache_disposition, - }) - .to_string(), - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn progress(signature: &str, percentage: u64) -> JdtImportProgress { - JdtImportProgress { - activity_signature: signature.to_string(), - phase: Some("Importing Maven project(s)".to_string()), - percentage: Some(percentage), - current_project: Some("module-a".to_string()), - download: None, - } - } - - #[test] - fn shared_readiness_examples_preserve_warnings_and_the_absolute_cap() { - let fixture: serde_json::Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/lsp/jdt-readiness-v1.json" - )) - .unwrap(); - for case in fixture["cases"].as_array().unwrap() { - let started = Instant::now(); - let mut diagnostics = - JavaPreparationDiagnostics::new(started, Duration::ZERO, "reused", true); - diagnostics.begin_readiness( - started, - Duration::ZERO, - Duration::from_millis(fixture["idleWarningMilliseconds"].as_u64().unwrap()), - Duration::from_millis(fixture["absoluteTimeoutMilliseconds"].as_u64().unwrap()), - ); - for step in case["steps"].as_array().unwrap() { - let now = started + Duration::from_millis(step["atMilliseconds"].as_u64().unwrap()); - match step["action"].as_str().unwrap() { - "progress" => { - diagnostics.record_progress( - progress( - &step["atMilliseconds"].to_string(), - step["percentage"].as_u64().unwrap(), - ), - now, - ); - } - "ready" => { - let result: serde_json::Value = - serde_json::from_str(&diagnostics.ready_detail(now)).unwrap(); - assert_eq!(result["outcome"], "ready"); - } - "poll" => { - let timeout = diagnostics.take_timeout(now); - assert_eq!( - timeout.is_some(), - step["timeout"].as_bool().unwrap(), - "{}", - case["name"] - ); - let warning = diagnostics.take_idle_warning(now); - assert_eq!( - warning.is_some(), - step["warning"].as_bool().unwrap(), - "{}", - case["name"] - ); - if let Some(timeout) = timeout { - let detail: serde_json::Value = serde_json::from_str(&timeout).unwrap(); - assert_eq!(detail["timeoutKind"], "absolute"); - assert_eq!(detail["classification"], step["classification"]); - } - } - action => panic!("unknown fixture action: {action}"), - } - } - } - } - - #[test] - fn quiet_import_warns_once_and_can_still_become_ready() { - let started = Instant::now(); - let mut diagnostics = - JavaPreparationDiagnostics::new(started, Duration::ZERO, "reused", true); - diagnostics.begin_readiness( - started, - Duration::ZERO, - Duration::from_secs(45), - Duration::from_secs(600), - ); - diagnostics.record_progress(progress("maven", 23), started); - let quiet = started + Duration::from_secs(46); - assert!(diagnostics.take_timeout(quiet).is_none()); - let warning = diagnostics - .take_idle_warning(quiet) - .expect("quiet import warning"); - let warning: serde_json::Value = serde_json::from_str(&warning).unwrap(); - assert_eq!(warning["idleMilliseconds"], 46_000); - assert_eq!(warning["progressPercent"], 23); - assert!(diagnostics - .take_idle_warning(quiet + Duration::from_secs(1)) - .is_none()); - - let ready: serde_json::Value = - serde_json::from_str(&diagnostics.ready_detail(started + Duration::from_secs(90))) - .unwrap(); - assert_eq!(ready["outcome"], "ready"); - assert!(diagnostics - .take_timeout(started + Duration::from_secs(601)) - .is_none()); - assert!(diagnostics - .take_idle_warning(started + Duration::from_secs(601)) - .is_none()); - } - - #[test] - fn meaningful_progress_refreshes_the_idle_warning() { - let started = Instant::now(); - let mut diagnostics = JavaPreparationDiagnostics::new(started, Duration::ZERO, "new", true); - diagnostics.begin_readiness( - started, - Duration::ZERO, - Duration::from_millis(100), - Duration::from_secs(1), - ); - diagnostics.record_progress(progress("first", 20), started + Duration::from_millis(80)); - assert!(diagnostics - .take_idle_warning(started + Duration::from_millis(150)) - .is_none()); - assert!(diagnostics - .take_idle_warning(started + Duration::from_millis(181)) - .is_some()); - diagnostics.record_progress(progress("second", 25), started + Duration::from_millis(200)); - assert!(diagnostics - .take_idle_warning(started + Duration::from_millis(250)) - .is_none()); - assert!(diagnostics - .take_idle_warning(started + Duration::from_millis(301)) - .is_some()); - assert!(diagnostics - .take_timeout(started + Duration::from_millis(301)) - .is_none()); - } - - #[test] - fn duplicate_progress_does_not_refresh_the_idle_warning() { - let started = Instant::now(); - let mut diagnostics = JavaPreparationDiagnostics::new(started, Duration::ZERO, "new", true); - diagnostics.begin_readiness( - started, - Duration::ZERO, - Duration::from_millis(45), - Duration::from_secs(10), - ); - diagnostics.record_progress(progress("same", 20), started + Duration::from_millis(10)); - diagnostics.record_progress(progress("same", 20), started + Duration::from_millis(30)); - let quiet = started + Duration::from_millis(56); - assert!(diagnostics.take_idle_warning(quiet).is_some()); - diagnostics.record_progress(progress("same", 20), started + Duration::from_millis(70)); - assert!(diagnostics - .take_idle_warning(started + Duration::from_millis(120)) - .is_none()); - assert!(diagnostics.take_timeout(quiet).is_none()); - let timeout: serde_json::Value = serde_json::from_str( - &diagnostics - .take_timeout(started + Duration::from_secs(10)) - .unwrap(), - ) - .unwrap(); - assert_eq!(timeout["timeoutKind"], "absolute"); - assert_eq!(timeout["classification"], "noProgressStall"); - assert!(diagnostics - .take_timeout(started + Duration::from_secs(11)) - .is_none()); - } - - #[test] - fn absolute_deadline_still_caps_continuously_active_imports() { - let started = Instant::now(); - let mut diagnostics = - JavaPreparationDiagnostics::new(started, Duration::from_millis(5), "reused", true); - diagnostics.begin_readiness( - started, - Duration::from_millis(10), - Duration::from_secs(1), - Duration::from_millis(100), - ); - diagnostics.record_progress(progress("first", 20), started + Duration::from_millis(40)); - diagnostics.record_progress(progress("second", 25), started + Duration::from_millis(90)); - - let timeout = diagnostics - .take_timeout(started + Duration::from_millis(100)) - .expect("the absolute deadline must remain a final safety cap"); - assert!(timeout.contains("\"timeoutKind\":\"absolute\"")); - assert!(timeout.contains("\"classification\":\"projectImportActive\"")); - } -} diff --git a/rust/lithe-core/src/lsp/languages/jdt_project_metadata.rs b/rust/lithe-core/src/lsp/languages/jdt_project_metadata.rs deleted file mode 100644 index 9318654e44..0000000000 --- a/rust/lithe-core/src/lsp/languages/jdt_project_metadata.rs +++ /dev/null @@ -1,429 +0,0 @@ -//! Removal of Eclipse project metadata that earlier JDT LS launches wrote into -//! the user's module directories. -//! -//! JDT LS now keeps `.project`, `.classpath`, `.factorypath`, and -//! `.settings/*.prefs` in its `-data` metadata area (see `jdt::adapt_start`). -//! A file that already exists at a module root still wins over that area, so -//! files written by earlier Lithe versions would otherwise stay in the project -//! forever. Only files Git does not track are removed: a tracked file is a -//! team decision, and outside a Git work tree ownership cannot be established. - -use crate::lsp::languages::java_workspace::IGNORED_DIRECTORIES; -use crate::protocol::{CoreError, ErrorCode}; -use std::collections::{BTreeMap, BTreeSet}; -use std::fs; -use std::path::{Path, PathBuf}; - -/// Build descriptors for which JDT LS's Maven and Gradle importers create an -/// Eclipse project, and therefore the only directories they write metadata to. -const MODULE_DESCRIPTOR_NAMES: &[&str] = &["pom.xml", "build.gradle", "build.gradle.kts"]; -/// Metadata files JDT LS writes directly into a module directory. -const METADATA_FILE_NAMES: &[&str] = &[".classpath", ".factorypath", ".project"]; -/// Directory holding the per-project Eclipse preference files. -const SETTINGS_DIRECTORY_NAME: &str = ".settings"; -/// Extension of the preference files JDT LS redirects together with the files above. -const PREFERENCES_EXTENSION: &str = "prefs"; - -/// Outcome of removing legacy metadata before one JDT LS launch. -#[derive(Debug, Default, Eq, PartialEq)] -pub(crate) struct LegacyMetadataCleanup { - /// Removed files as sorted workspace-relative paths with `/` separators. - pub removed_files: Vec, - /// Whether an existing JDT LS state directory was deleted so the launch - /// imports the workspace afresh. - pub state_reset: bool, -} - -/// Removes legacy metadata before JDT LS starts for `workspace_root`. -/// -/// When any file was removed, the JDT LS state in `data_directory` still -/// describes those projects at their old location, so it is deleted and the -/// launch imports the workspace afresh. -pub(crate) fn prepare_workspace( - workspace_root: &Path, - data_directory: &Path, -) -> Result { - let removed_files = remove_untracked_metadata(workspace_root); - let state_reset = !removed_files.is_empty() && data_directory.exists(); - if state_reset { - fs::remove_dir_all(data_directory).map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not reset the Java language-server state after moving its project files out of the workspace.", - ) - .with_details(error.to_string()) - })?; - } - Ok(LegacyMetadataCleanup { - removed_files, - state_reset, - }) -} - -/// One metadata file of one module, keyed for the repository that owns it. -struct Candidate { - module: PathBuf, - /// Path relative to `module` with `/` separators. - name: String, - /// Path relative to the owning repository root with `/` separators, the - /// form `git ls-files` reports. - repository_path: String, -} - -fn remove_untracked_metadata(workspace_root: &Path) -> Vec { - // Group candidates by repository so each repository answers with one Git - // query. The repository is located from its `.git` entry without starting a - // process, so modules outside Git — whose files are kept anyway — cost no - // Git invocation on any launch. - let mut repositories: BTreeMap> = BTreeMap::new(); - for module in module_directories(workspace_root) { - let names = metadata_candidates(&module); - if names.is_empty() { - continue; - } - let Some(repository) = enclosing_repository(&module) else { - continue; - }; - let module_path = relative_path(&repository, &module); - let candidates = repositories.entry(repository).or_default(); - for name in names { - let repository_path = if module_path.is_empty() { - name.clone() - } else { - format!("{module_path}/{name}") - }; - candidates.push(Candidate { - module: module.clone(), - name, - repository_path, - }); - } - } - - let mut removed = Vec::new(); - let mut emptied_settings = BTreeSet::new(); - for (repository, candidates) in repositories { - let paths = candidates - .iter() - .map(|candidate| candidate.repository_path.clone()) - .collect::>(); - // Removal is best effort: a file that cannot be queried or deleted keeps - // working for JDT LS exactly as before, so it never blocks the launch. - let Some(untracked) = crate::git::untracked_candidates(&repository, &paths) else { - continue; - }; - let untracked = untracked.into_iter().collect::>(); - for candidate in candidates { - if !untracked.contains(&candidate.repository_path) - || fs::remove_file(candidate.module.join(&candidate.name)).is_err() - { - continue; - } - if candidate.name.starts_with(SETTINGS_DIRECTORY_NAME) { - emptied_settings.insert(candidate.module.join(SETTINGS_DIRECTORY_NAME)); - } - let module_path = relative_path(workspace_root, &candidate.module); - removed.push(if module_path.is_empty() { - candidate.name - } else { - format!("{module_path}/{}", candidate.name) - }); - } - } - // Summarize cleanup at the launch boundary; retained settings are normal. - let mut cleanup = crate::diagnostics::core_events::StorageCleanup::default(); - for settings in emptied_settings { - cleanup.empty_directory(&settings); - } - cleanup.finish("jdt-settings"); - removed.sort(); - removed -} - -/// Nearest ancestor of `directory` (itself included) holding a `.git` entry. -/// -/// `.git` is a directory in a regular checkout and a file in linked worktrees -/// and submodules; both mark the repository whose index decides tracking, so a -/// module inside a nested repository is answered by that nested repository. -fn enclosing_repository(directory: &Path) -> Option { - directory - .ancestors() - .find(|ancestor| fs::symlink_metadata(ancestor.join(".git")).is_ok()) - .map(Path::to_path_buf) -} - -/// Directories below `workspace_root` that declare a Maven or Gradle module. -/// -/// Hidden, ignored, and symbolically linked directories are not entered, so the -/// walk stays inside the project's own sources and cannot leave the workspace. -fn module_directories(workspace_root: &Path) -> Vec { - let mut modules = Vec::new(); - let mut pending = vec![workspace_root.to_path_buf()]; - while let Some(directory) = pending.pop() { - let Ok(entries) = fs::read_dir(&directory) else { - continue; - }; - let mut is_module = false; - for entry in entries.flatten() { - let Ok(file_type) = entry.file_type() else { - continue; - }; - let name = entry.file_name(); - let name = name.to_string_lossy(); - if file_type.is_file() && MODULE_DESCRIPTOR_NAMES.contains(&name.as_ref()) { - is_module = true; - } else if file_type.is_dir() - && !name.starts_with('.') - && !IGNORED_DIRECTORIES.contains(&name.as_ref()) - { - pending.push(entry.path()); - } - } - if is_module { - modules.push(directory); - } - } - modules.sort(); - modules -} - -/// Existing metadata files of one module, relative to it with `/` separators. -fn metadata_candidates(module: &Path) -> Vec { - let mut candidates = METADATA_FILE_NAMES - .iter() - .filter(|name| is_regular_file(&module.join(name))) - .map(|name| name.to_string()) - .collect::>(); - let settings = module.join(SETTINGS_DIRECTORY_NAME); - let is_settings_directory = - fs::symlink_metadata(&settings).is_ok_and(|metadata| metadata.file_type().is_dir()); - if is_settings_directory { - if let Ok(entries) = fs::read_dir(&settings) { - let mut preferences = entries - .flatten() - .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) - .map(|entry| entry.file_name().to_string_lossy().into_owned()) - .filter(|name| { - Path::new(name) - .extension() - .is_some_and(|extension| extension == PREFERENCES_EXTENSION) - }) - .map(|name| format!("{SETTINGS_DIRECTORY_NAME}/{name}")) - .collect::>(); - preferences.sort(); - candidates.extend(preferences); - } - } - candidates -} - -fn is_regular_file(path: &Path) -> bool { - fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_file()) -} - -/// `path` relative to `base` with `/` separators; empty when they are equal. -fn relative_path(base: &Path, path: &Path) -> String { - path.strip_prefix(base) - .unwrap_or(path) - .to_string_lossy() - .replace('\\', "/") -} - -#[cfg(test)] -mod tests { - use super::*; - use std::process::Command; - use std::sync::atomic::{AtomicU64, Ordering}; - - static NEXT_WORKSPACE: AtomicU64 = AtomicU64::new(0); - - /// A scratch directory holding a workspace and a JDT data directory, removed - /// on drop so a failed assertion does not leak it. - struct Scratch { - root: PathBuf, - } - - impl Scratch { - fn new() -> Self { - let root = std::env::temp_dir().join(format!( - "lithe-jdt-metadata-{}-{}", - std::process::id(), - NEXT_WORKSPACE.fetch_add(1, Ordering::Relaxed) - )); - let _ = fs::remove_dir_all(&root); - fs::create_dir_all(root.join("workspace")).expect("workspace should be created"); - Self { root } - } - - fn workspace(&self) -> PathBuf { - self.root.join("workspace") - } - - fn data_directory(&self) -> PathBuf { - let directory = self.root.join("data"); - fs::create_dir_all(directory.join(".metadata")).expect("data should be created"); - directory - } - - fn write(&self, relative: &str) { - let path = self.workspace().join(relative); - fs::create_dir_all(path.parent().unwrap()).expect("parent should be created"); - fs::write(path, relative).expect("file should be written"); - } - - fn exists(&self, relative: &str) -> bool { - self.workspace().join(relative).exists() - } - - fn git(&self, arguments: &[&str]) { - let status = Command::new("git") - .args(arguments) - .current_dir(self.workspace()) - .status() - .expect("git should run"); - assert!(status.success(), "git {arguments:?} failed"); - } - } - - impl Drop for Scratch { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.root); - } - } - - /// The reported layout: a Maven reactor whose modules sit one and two - /// levels deep, each carrying the files JDT LS used to write in place. - fn write_reactor_with_legacy_metadata(scratch: &Scratch) { - for module in ["", "domain/", "infrastructure/sdk/"] { - scratch.write(&format!("{module}pom.xml")); - scratch.write(&format!("{module}.project")); - scratch.write(&format!("{module}.classpath")); - scratch.write(&format!("{module}.factorypath")); - scratch.write(&format!("{module}.settings/org.eclipse.jdt.core.prefs")); - scratch.write(&format!("{module}.settings/org.eclipse.m2e.core.prefs")); - } - } - - #[test] - fn removes_untracked_module_metadata_and_resets_the_jdt_state() { - let scratch = Scratch::new(); - write_reactor_with_legacy_metadata(&scratch); - scratch.git(&["init", "-q"]); - let data_directory = scratch.data_directory(); - - let cleanup = prepare_workspace(&scratch.workspace(), &data_directory) - .expect("preparation should succeed"); - let removed = &cleanup.removed_files; - - assert!(cleanup.state_reset); - assert_eq!(removed.len(), 15, "{removed:?}"); - assert_eq!(removed.first().map(String::as_str), Some(".classpath")); - assert!(removed - .contains(&"infrastructure/sdk/.settings/org.eclipse.m2e.core.prefs".to_string())); - for module in ["", "domain/", "infrastructure/sdk/"] { - assert!(scratch.exists(&format!("{module}pom.xml"))); - assert!(!scratch.exists(&format!("{module}.project"))); - assert!(!scratch.exists(&format!("{module}.settings"))); - } - assert!(!data_directory.exists(), "stale JDT state must not survive"); - } - - #[test] - fn keeps_tracked_metadata_and_user_files_in_settings() { - let scratch = Scratch::new(); - write_reactor_with_legacy_metadata(&scratch); - scratch.write("domain/.settings/team-notes.txt"); - scratch.git(&["init", "-q"]); - // A team that commits Eclipse files for its Eclipse users owns them. - scratch.git(&[ - "add", - "domain/.classpath", - "domain/.settings/org.eclipse.jdt.core.prefs", - ]); - - prepare_workspace(&scratch.workspace(), &scratch.data_directory()) - .expect("preparation should succeed"); - - assert!(scratch.exists("domain/.classpath")); - assert!(scratch.exists("domain/.settings/org.eclipse.jdt.core.prefs")); - assert!(!scratch.exists("domain/.settings/org.eclipse.m2e.core.prefs")); - assert!(scratch.exists("domain/.settings/team-notes.txt")); - assert!(!scratch.exists("domain/.project")); - } - - #[test] - fn asks_the_nested_repository_that_owns_a_module() { - let scratch = Scratch::new(); - scratch.write("pom.xml"); - scratch.write(".project"); - scratch.write("vendor-lib/pom.xml"); - scratch.write("vendor-lib/.classpath"); - scratch.write("vendor-lib/.project"); - scratch.git(&["init", "-q"]); - // The outer index never lists files of a nested repository, so asking the - // outer repository would report the inner tracked `.classpath` as untracked. - let status = Command::new("git") - .args(["init", "-q"]) - .current_dir(scratch.workspace().join("vendor-lib")) - .status() - .expect("git should run"); - assert!(status.success()); - let status = Command::new("git") - .args(["add", ".classpath"]) - .current_dir(scratch.workspace().join("vendor-lib")) - .status() - .expect("git should run"); - assert!(status.success()); - - let cleanup = prepare_workspace(&scratch.workspace(), &scratch.data_directory()) - .expect("preparation should succeed"); - - assert_eq!( - cleanup.removed_files, - vec![".project", "vendor-lib/.project"] - ); - assert!(scratch.exists("vendor-lib/.classpath")); - } - - #[test] - fn leaves_workspaces_outside_git_and_their_jdt_state_untouched() { - let scratch = Scratch::new(); - write_reactor_with_legacy_metadata(&scratch); - let data_directory = scratch.data_directory(); - - let cleanup = prepare_workspace(&scratch.workspace(), &data_directory) - .expect("preparation should succeed"); - - assert_eq!(cleanup, LegacyMetadataCleanup::default()); - assert!(scratch.exists(".project")); - assert!(scratch.exists("infrastructure/sdk/.settings/org.eclipse.m2e.core.prefs")); - assert!(data_directory.join(".metadata").is_dir()); - } - - #[test] - fn ignores_directories_that_are_not_modules_or_not_project_sources() { - let scratch = Scratch::new(); - scratch.write("pom.xml"); - // No build descriptor: an Eclipse project JDT LS did not generate. - scratch.write("tools/.project"); - // Vendored and build-output copies are not the opened project's modules. - scratch.write("node_modules/dep/pom.xml"); - scratch.write("node_modules/dep/.project"); - scratch.write("target/nested/pom.xml"); - scratch.write("target/nested/.classpath"); - scratch.git(&["init", "-q"]); - let data_directory = scratch.data_directory(); - - let cleanup = prepare_workspace(&scratch.workspace(), &data_directory) - .expect("preparation should succeed"); - - assert_eq!(cleanup, LegacyMetadataCleanup::default()); - assert!(scratch.exists("tools/.project")); - assert!(scratch.exists("node_modules/dep/.project")); - assert!(scratch.exists("target/nested/.classpath")); - assert!( - data_directory.join(".metadata").is_dir(), - "nothing moved, so the state is kept" - ); - } -} diff --git a/rust/lithe-core/src/lsp/languages/mod.rs b/rust/lithe-core/src/lsp/languages/mod.rs index 055fe39d0e..aed65c66d9 100644 --- a/rust/lithe-core/src/lsp/languages/mod.rs +++ b/rust/lithe-core/src/lsp/languages/mod.rs @@ -2,30 +2,7 @@ mod catalog; pub(crate) mod indexing; -pub(crate) mod java_entrypoints; -pub(crate) mod java_launch; -pub(crate) mod java_main_methods; -pub(crate) mod java_navigation_syntax; -mod java_run_markers; -pub(crate) mod java_tests; -mod java_workspace; -pub(crate) mod jdt; -pub(crate) mod jdt_build; -mod jdt_configuration; -pub(crate) mod jdt_maven_settings; -pub(crate) mod jdt_navigation; -pub(crate) mod jdt_progress; -mod jdt_project_metadata; -pub(crate) mod project_preparation; #[cfg(test)] pub(crate) mod swift; pub(crate) use catalog::*; -pub(crate) use java_run_markers::{java_run_markers, JavaRunMarkersRequest}; -pub(crate) use java_workspace::{ - java_workspace_policy, jdt_cache_retention, jdt_workspace_fingerprint, - JavaWorkspacePolicyRequest, JdtCacheRetentionRequest, JdtWorkspaceFingerprintRequest, -}; -pub(crate) use jdt::{resolve_workspace_key, JdtWorkspaceKeyRequest}; -pub(crate) use jdt_configuration::prepare_configuration_area as prepare_jdt_configuration_area; -pub(crate) use jdt_project_metadata::prepare_workspace as prepare_jdt_workspace; diff --git a/rust/lithe-core/src/lsp/languages/project_preparation.rs b/rust/lithe-core/src/lsp/languages/project_preparation.rs deleted file mode 100644 index 3e9f641e7f..0000000000 --- a/rust/lithe-core/src/lsp/languages/project_preparation.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! User-facing Java preparation state derived from the existing session and build owner. - -use super::jdt::MavenProfileTaskStatus; -use crate::lsp::LspLifecycleState; -use serde::Serialize; - -/// Stable presentation state. Ready means project preparation, not compilation, completed. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ProjectPreparation { - /// Current stage: starting, importing, configuring, building, ready, or stopped. - pub phase: &'static str, - /// Presentation outcome: idle, loading, ready, or failed. - pub status: &'static str, - /// Whether Java launch must wait for the session-wide preparation gate. - pub blocks_run: bool, -} - -/// Projects upstream lifecycle facts without starting work or treating indexing as a gate. -pub(crate) fn snapshot( - lifecycle: LspLifecycleState, - profiles: MavenProfileTaskStatus, - configuring: bool, - building: bool, -) -> ProjectPreparation { - use LspLifecycleState::*; - let (phase, status) = match lifecycle { - Created | ProcessStarting => ("starting", "loading"), - Initializing => ("importing", "loading"), - Failed => ("starting", "failed"), - Stopping | Stopped => ("stopped", "idle"), - Ready => match profiles { - MavenProfileTaskStatus::Running => ("configuring", "loading"), - _ if configuring => ("configuring", "loading"), - _ if building => ("building", "loading"), - - MavenProfileTaskStatus::Failed - | MavenProfileTaskStatus::TimedOut - | MavenProfileTaskStatus::PartiallySucceeded - | MavenProfileTaskStatus::Cancelled => ("configuring", "failed"), - _ => ("ready", "ready"), - }, - }; - ProjectPreparation { - phase, - status, - // Profile errors are per-project. Keep their failure visible, but let JDT - // validate the selected target rather than blocking unrelated modules. - blocks_run: lifecycle != LspLifecycleState::Ready || status == "loading", - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn serialized_snapshots_match_the_shared_fixture() { - let fixture: serde_json::Value = serde_json::from_str(include_str!( - "../../../../../shared/fixtures/lsp/project-preparation-v1.json" - )) - .unwrap(); - let cases = [ - ( - LspLifecycleState::Created, - MavenProfileTaskStatus::Idle, - false, - false, - ), - ( - LspLifecycleState::Initializing, - MavenProfileTaskStatus::Idle, - false, - false, - ), - ( - LspLifecycleState::Ready, - MavenProfileTaskStatus::Running, - false, - false, - ), - ( - LspLifecycleState::Ready, - MavenProfileTaskStatus::Succeeded, - false, - true, - ), - ( - LspLifecycleState::Ready, - MavenProfileTaskStatus::Succeeded, - false, - false, - ), - ( - LspLifecycleState::Ready, - MavenProfileTaskStatus::Failed, - false, - false, - ), - ( - LspLifecycleState::Stopped, - MavenProfileTaskStatus::Idle, - false, - false, - ), - ]; - for ((lifecycle, profiles, configuring, building), expected) in cases - .into_iter() - .zip(fixture["snapshots"].as_array().unwrap()) - { - assert_eq!( - &serde_json::to_value(snapshot(lifecycle, profiles, configuring, building)) - .unwrap(), - expected - ); - } - } - - #[test] - fn service_ready_does_not_bypass_project_configuration() { - let ready = LspLifecycleState::Ready; - assert_eq!( - snapshot(ready, MavenProfileTaskStatus::Running, false, false).phase, - "configuring" - ); - assert!(snapshot(ready, MavenProfileTaskStatus::Succeeded, true, false).blocks_run); - assert_eq!( - snapshot(ready, MavenProfileTaskStatus::Succeeded, false, true).phase, - "building" - ); - assert!(!snapshot(ready, MavenProfileTaskStatus::Succeeded, false, false).blocks_run); - } - - #[test] - fn failures_and_stopped_sessions_never_report_ready() { - for profiles in [ - MavenProfileTaskStatus::Failed, - MavenProfileTaskStatus::TimedOut, - MavenProfileTaskStatus::Cancelled, - MavenProfileTaskStatus::PartiallySucceeded, - ] { - assert!(snapshot(LspLifecycleState::Ready, profiles, true, false).blocks_run); - assert!(snapshot(LspLifecycleState::Ready, profiles, false, true).blocks_run); - assert_eq!( - snapshot(LspLifecycleState::Ready, profiles, false, false).status, - "failed" - ); - } - assert!( - snapshot( - LspLifecycleState::Stopped, - MavenProfileTaskStatus::Idle, - false, - false - ) - .blocks_run - ); - assert_eq!( - snapshot( - LspLifecycleState::Initializing, - MavenProfileTaskStatus::Idle, - false, - false - ) - .phase, - "importing" - ); - } -} diff --git a/rust/lithe-core/src/plugins/declarative.rs b/rust/lithe-core/src/plugins/declarative.rs index e7b7fc6665..8244094208 100644 --- a/rust/lithe-core/src/plugins/declarative.rs +++ b/rust/lithe-core/src/plugins/declarative.rs @@ -93,27 +93,25 @@ const KNOWN_PERMISSIONS: &[&str] = &[ /// Runtime tools the host knows how to discover and pass to a language /// server. The host exports each as `LITHE__PATH` and puts its /// directory on the server's `PATH`; gopls, for example, runs `go` itself. -const KNOWN_RUNTIME_TOOLS: &[&str] = &["go", "node"]; -/// Runtime tools available from API level 2 on. -pub(crate) const KNOWN_RUNTIME_TOOLS_V2: &[&str] = &["go", "java", "node"]; -/// Runtimes that can start a packaged entry file themselves (`java -jar`, -/// `node