diff --git a/.agents/notes/implemented/architecture/2026-11-09-viva-plugin-preference-native-storage.md b/.agents/notes/implemented/architecture/2026-11-09-viva-plugin-preference-native-storage.md index d84f2c62d3..39f6951e4b 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-viva-plugin-preference-native-storage.md +++ b/.agents/notes/implemented/architecture/2026-11-09-viva-plugin-preference-native-storage.md @@ -92,6 +92,16 @@ Windows 全量回归发现,原 Go 适配器去掉 `file://` 后把 `/elsewhere 把发行目录作为默认写入根会改变安装基线,因此所有来源只由平台存储或用户工作区提供。乐观字节检查不会锁住不遵守协议的外部写入者,不宣称跨进程事务锁。 +### 工具原生配置使用独立的来源表单 + +插件偏好与工具配置分开处理。通用 `sourceSettings: 0` 由 Core PR [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) 定义,插件只返回非敏感字段和真实来源摘要;原始工具文档不跨 RPC。格式解析与编辑仍在所属插件,宿主不认识工具名称。 + +编译器页面归“构建、执行、部署”。打开页面只显示明确的读取按钮,点击后才使声明的语言/构建会话就绪并取得上游实际项目事实。工具读取可能运行项目代码和下载依赖,不以打开页面代替授权。读取、暂存和回读都在有界后台任务中执行。 + +Core 区分原始覆盖、当前有效值与移除覆盖后的继承值。界面保留草稿,模块表只增加用户选中的覆盖;不把查看继承值变成写入。外部更改在保存时通过原生基线拒绝,不以本地草稿覆盖新文件。 + +宿主在系统临时目录创建一次调用拥有的 0700 目录和已存在的 0600 文件,插件只能写暂存。所有替换先准备完成,再逐个经原生条件原子写入发布;每次发布前复查整批基线、工作区和包身份。多文件不能提供文件系统事务,部分提交被明确报告并要求重读。安装根和插件仓库只读,临时目录在成功、失败和取消时清理;可变状态不跨工作树复用,不影响签名或增量更新基线。 + ## 后果 保护逻辑只在后台读取或明确保存时运行,没有空闲轮询或帧内文件 I/O。批量非法输入、取消和外部修改不会覆盖旧来源;项目层清空只删除已经为空的目标文档,不删除其他插件配置。生成的用户状态和临时文件全部排除工作树复用。 @@ -134,3 +144,12 @@ Core 和 C ABI 共享同一份 `Lithe-core-rust/rust/fixtures/plugins/settings-d 桌面桥接、界面和工作台回归分别在 `desktop/internal/core/settings_surfaces_test.go`、 `desktop/internal/settingswindow/settings_surfaces_test.go` 和 `desktop/internal/workbench/settings_publication_test.go`。 + + +### 全局 SDK 登记不依赖项目 + +SDK 的安装目录和默认版本属于本机用户,不应要求先打开项目,更不应在每个项目复制一份安装列表。因此工具链页默认显示全局范围,允许自动识别与手动添加多个目录;项目范围只保留可选覆盖。两个范围共用同一解析器,项目覆盖优先于全局默认,清空全局默认只恢复自动选择,不删除手动登记。 + +Core 负责有界登记文档、目录身份规则与合并;原生适配器在平台用户设置目录读取 `toolchains/global.json`,保存前核对原始字节和文件身份,保存后重新探测。打开页面不创建目录;版本号不作为持久化事实;运行中进程保留启动时环境,新启动的 Build、Run、语言服务读取最新默认值。不要用当前工作目录冒充全局操作的项目,也不要写入 SDK、插件安装目录或 app bundle;该资源随用户设置存续,不影响签名和增量更新。 + +放弃把全局默认复制为每个项目 pin 的方案,因为这会阻断以后切换全局默认。验证覆盖无项目读取、多版本登记、保存冲突、两个项目的实时继承及显式项目覆盖;窗口测试覆盖多个添加草稿和确认保存。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-15-diagnostic-cell-projection-and-wave-paint.md b/.agents/notes/implemented/bug-fix/2026-11-15-diagnostic-cell-projection-and-wave-paint.md new file mode 100644 index 0000000000..7d116b4317 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-15-diagnostic-cell-projection-and-wave-paint.md @@ -0,0 +1,38 @@ +# Agent 笔记:诊断下划线按实际字符列定位并复用波浪网格 + +状态:已实现 + +## 先说结论 + +语言服务器给出的 UTF-16 位置不能直接当成屏幕字符列。诊断先绑定不可变文本修订,在后台换算 Tab、中文与表情的显示宽度;窗口只接收仍属于当前修订的结果。波浪线复用 Viva 的不可变图形网格,不能每帧重新生成整段笔画。 + +## 问题 + +UTF-16 用两个单位表示部分表情,中文通常占两个显示格,Tab 又取决于前面的列。直接把诊断偏移乘以字体宽度会让线条与标识符错位。把修正后的长波浪路径在每帧交给通用描边器,又会在密集诊断文件中反复计算同一几何形状。 + +## 决策 + +`ProjectMarkers` 只读取捕获的不可变文本,按行合并诊断端点,一行最多扫描到最后一个端点;结果仅含显示格范围。后台操作有取消与期限,回到窗口时核对文档、代数和文本修订;关闭文档会取消自己的投影。原生编辑器仍是文本和字体布局的所有者,Core 不保存第二份全文。 + +短线使用有界的视图内图形集合,最多 32 种、合计 8192 条路径指令,调用 Viva 既有的有界图形缓存。新形状超出额度或长于 512 点时,重复绘制同一个固定周期,并只裁剪两端。图形没有文件资源或后台进程,视图销毁时释放自己的集合。横向移动与换行沿用文档列的相位,线条靠近实际文本基线。 + +正确做法:文本改变后丢弃旧投影,稳态绘制只复用网格。不要这样做:绘制时扫描全文、在服务器线程修改视图、按每个文档或每个诊断无界缓存路径。 + +## 考虑过的备选方案 + +- 直接使用 UTF-16 偏移:无法对齐宽字符和 Tab,拒绝。 +- 每帧重新描整条波浪:实测显著增加密集诊断绘制耗时,拒绝。 +- 为全部宽度建立永久全局缓存:会随文档和缩放累积几何数据,拒绝。 +- 保留直矩形线:虽然开销低,但不满足诊断波浪线的视觉要求。 + +## 后果 + +投影到达前不展示过期标记;稳态绘制无堆分配。波浪比原直矩形包含更多绘制图元,必须在同机六次基线中报告实际代价,不得通过改预算或减少诊断来隐藏它。典型上限和所有权在代码中显式保持,不创建运行时磁盘资源。 + +## 验证 + +`desktop/internal/editorview/markers_test.go` 覆盖 Tab、中文、表情、混合字符、分数像素、取消与过期修订;原始错位和直线实现先失败,修正后通过。`desktop/internal/workbench/diagnostic_visual_test.go` 捕获中英、明暗主题的生产窗口。`scripts/desktop/perf/editor-bench.sh` 按原有完整场景和文档规模运行前后六次基线,密集标记继续要求零稳态分配。平台原生验证独立记录。 + +## 适用范围 + +Viva 编辑器的诊断投影、文本修订发布和下划线绘制,不改变上游诊断内容、严重级别或语言服务语义。 diff --git a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md index 7ace01e5f6..58ee9262c1 100644 --- a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md +++ b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md @@ -19,7 +19,7 @@ | 外观与行为 | 应用本身的外观、更新、编辑器显示与输入、快捷键,以及应用自身网络请求的代理设置 | | 插件 | 插件的安装、启用和插件自带的选项;一级页面,不属于任何分组 | | 版本控制 | Git、SVN 等版本控制系统的配置 | -| 构建、执行、部署 | 构建工具、项目 JDK、运行配置、服务运行,以及框架和构建工具注入的配置 | +| 构建、执行、部署 | 构建工具、项目 JDK、插件声明的编译器页与模块字节码、运行配置、服务运行,以及框架和构建工具注入的配置 | | 语言与框架 | 语言服务(LSP)的开关,以及 Spring Boot 等框架的配置 | | 工具 | 终端等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 | | AI | 与 AI 有关的全部配置:MCP、Skill、全局指令、AI 提交信息、Agents、AI 服务商 | diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 7cae926610..ca60a7b80e 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -218,6 +218,20 @@ jobs: - name: Vet and test run: ./scripts/desktop/check.sh + - name: Capture native settings and diagnostic screenshots + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/native-settings-visual + run: ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow ./internal/workbench -run '^(TestVisualNativeSettingsForm|TestVisualDiagnosticUnderline)$' -count=1 -timeout=120s + + - name: Upload native settings visual evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: native-settings-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/native-settings-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native cache regression report if: always() uses: actions/upload-artifact@v7 @@ -288,6 +302,20 @@ jobs: - name: Vet and test run: ./scripts/desktop/check.sh + - name: Capture native settings and diagnostic screenshots + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/native-settings-visual + run: ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow ./internal/workbench -run '^(TestVisualNativeSettingsForm|TestVisualDiagnosticUnderline)$' -count=1 -timeout=120s + + - name: Upload native settings visual evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: native-settings-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/native-settings-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native cache regression report if: always() uses: actions/upload-artifact@v7 diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 4e22984993..bdb77d5f72 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -2,7 +2,7 @@ name: Desktop Release # Releases the Viva desktop client (desktop/) for macOS, Windows and Linux. Its tags are # desktop-vMAJOR.MINOR.PATCH, apart from the v* tags of the SwiftUI and Tauri clients, and each -# release is a GitHub prerelease, so those clients' updaters continue to read their own latest release. +# release is stable. Keep the legacy clients' latest release unchanged; desktop updates select desktop-v tags. on: push: tags: @@ -175,7 +175,7 @@ jobs: if-no-files-found: error publish: - name: Publish the prerelease + name: Publish the release if: github.event_name != 'workflow_dispatch' || inputs.publish needs: - prepare @@ -201,7 +201,7 @@ jobs: DESKTOP_VERSION: ${{ needs.prepare.outputs.version }} run: node scripts/ci/common/desktop-packages.mjs verify "$DESKTOP_VERSION" dist - - name: Create or update the GitHub prerelease + - name: Create or update the GitHub release env: GH_TOKEN: ${{ github.token }} RELEASE_TAG: ${{ needs.prepare.outputs.tag }} @@ -211,7 +211,8 @@ jobs: --repo "$GITHUB_REPOSITORY" --title "Lithe Desktop $DESKTOP_VERSION" --notes-file "docs/releases/v$DESKTOP_VERSION.md" - --prerelease + --prerelease=false + --latest=false ) if ! gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then gh release create "$RELEASE_TAG" --target "$GITHUB_SHA" "${release_args[@]}" || \ diff --git a/desktop/go.mod b/desktop/go.mod index c336e4202b..04f19ebad8 100644 --- a/desktop/go.mod +++ b/desktop/go.mod @@ -9,7 +9,7 @@ toolchain go1.27.3 require ( github.com/creack/pty v1.1.24 github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f - github.com/vivaui/viva v0.6.5-0.20261115084025-ad3c812a43e2 + github.com/vivaui/viva v0.6.5-0.20261115140306-89ce846fe65c github.com/zalando/go-keyring v0.2.8 golang.org/x/sys v0.50.0 ) @@ -20,4 +20,4 @@ require ( github.com/godbus/dbus/v5 v5.2.2 // indirect ) -replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.5-0.20261115111929-3a274c3800ef +replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.5-0.20261115165622-97fdbdde326b diff --git a/desktop/go.sum b/desktop/go.sum index 7beaf865e1..bb6fd9d643 100644 --- a/desktop/go.sum +++ b/desktop/go.sum @@ -1,5 +1,5 @@ -github.com/Lithe-IDEA/viva v0.6.5-0.20261115111929-3a274c3800ef h1:p3n2Bsu2/gCcNmbVBJ5eu6NEW8JjUX7zf/uzgFAA9Mc= -github.com/Lithe-IDEA/viva v0.6.5-0.20261115111929-3a274c3800ef/go.mod h1:e9In6+J77G7B9ow4enZ2FSOFh7U3q4cQ5iJr3Qn/Olk= +github.com/Lithe-IDEA/viva v0.6.5-0.20261115165622-97fdbdde326b h1:JY0yXuRzZDlj6KHC712le49ISjGVrkFwm9KP5XlJFH8= +github.com/Lithe-IDEA/viva v0.6.5-0.20261115165622-97fdbdde326b/go.mod h1:e9In6+J77G7B9ow4enZ2FSOFh7U3q4cQ5iJr3Qn/Olk= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= diff --git a/desktop/internal/core/build.go b/desktop/internal/core/build.go index 05d34db787..ab307562b0 100644 --- a/desktop/internal/core/build.go +++ b/desktop/internal/core/build.go @@ -70,6 +70,7 @@ type BuildExecutableCandidate struct { // BuildRuntimeRequirement is a runtime the build tool needs, with the probe // Core expects the host to run when it must check the version. type BuildRuntimeRequirement struct { + PathVariable string `json:"pathVariable,omitempty"` ID string `json:"id"` DisplayName string `json:"displayName"` HostManaged bool `json:"hostManaged"` diff --git a/desktop/internal/core/plugin_setting_actions.go b/desktop/internal/core/plugin_setting_actions.go index 9b8cf00478..6b8f36d190 100644 --- a/desktop/internal/core/plugin_setting_actions.go +++ b/desktop/internal/core/plugin_setting_actions.go @@ -25,14 +25,18 @@ type PluginSettingsActionRequest struct { // Only an invoke plan contains Function and Params; runtime ownership is checked // again when the existing provider session receives that invocation. type PluginSettingsActionPlan struct { - Version string `json:"version"` - Kind string `json:"kind"` - PluginID string `json:"pluginID"` - ActionID string `json:"actionID"` - Title string `json:"title"` - Reason string `json:"reason,omitempty"` - Function string `json:"function,omitempty"` - Params json.RawMessage `json:"params,omitempty"` + Version string `json:"version"` + Kind string `json:"kind"` + PluginID string `json:"pluginID"` + ActionID string `json:"actionID"` + Title string `json:"title"` + Reason string `json:"reason,omitempty"` + Function string `json:"function,omitempty"` + Params json.RawMessage `json:"params,omitempty"` + SourceEditor bool `json:"sourceEditor,omitempty"` + BuildSystemID string `json:"buildSystemID,omitempty"` + LanguageID string `json:"languageID,omitempty"` + EditFunction string `json:"editFunction,omitempty"` } // PlanPluginSettingsAction resolves a manifest action without opening a backend diff --git a/desktop/internal/core/plugin_settings.go b/desktop/internal/core/plugin_settings.go index ddb8f78cb9..c2af1bb79e 100644 --- a/desktop/internal/core/plugin_settings.go +++ b/desktop/internal/core/plugin_settings.go @@ -9,6 +9,7 @@ import ( type PluginSettingPage struct { LanguageID string `json:"languageID,omitempty"` BuildSystemID string `json:"buildSystemID,omitempty"` + CompilerID string `json:"compilerID,omitempty"` } // PluginSettingOption is one value and its plugin-provided display title. @@ -56,13 +57,20 @@ type PluginSettingRow struct { // PluginSettingAction invokes a declared function only after a user action. type PluginSettingAction struct { - ID string `json:"id"` - Title string `json:"title"` - Description string `json:"description,omitempty"` - Page *PluginSettingPage `json:"page,omitempty"` - Section string `json:"section,omitempty"` - Function string `json:"function"` - Confirm bool `json:"confirm"` + ID string `json:"id"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + Page *PluginSettingPage `json:"page,omitempty"` + Section string `json:"section,omitempty"` + Function string `json:"function"` + Confirm bool `json:"confirm"` + SourceEditor *PluginSourceEditorDeclaration `json:"sourceEditor,omitempty"` +} + +type PluginSourceEditorDeclaration struct { + BuildSystemID string `json:"buildSystemID,omitempty"` + LanguageID string `json:"languageID,omitempty"` + EditFunction string `json:"editFunction"` } // PluginSettingsStorage is Core's bounded read plan under native-owned roots. diff --git a/desktop/internal/core/source_settings.go b/desktop/internal/core/source_settings.go new file mode 100644 index 0000000000..3ff050b505 --- /dev/null +++ b/desktop/internal/core/source_settings.go @@ -0,0 +1,120 @@ +package core + +import ( + "context" + "encoding/json" +) + +// SourceSettingsSnapshot is a plugin's bounded projection of native workspace +// files. The host never interprets a tool's configuration format. +type SourceSettingsSnapshot struct { + Format string `json:"format"` + Version int `json:"version"` + Title string `json:"title"` + Groups []SourceSettingsGroup `json:"groups"` + Sources []SettingsSource `json:"sources"` +} + +type SourceSettingsGroup struct { + ID string `json:"id"` + Title string `json:"title"` + Layout string `json:"layout"` + RowTitle string `json:"rowTitle,omitempty"` +} + +type SettingsSource struct { + ID string `json:"id"` + Group string `json:"group"` + Title string `json:"title"` + Path string `json:"path"` + Revision string `json:"revision"` + Writable bool `json:"writable"` + Fields []SourceSettingField `json:"fields"` +} + +type SourceSettingField struct { + ID string `json:"id"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + Kind string `json:"kind"` + Value json.RawMessage `json:"value"` + InheritedValue json.RawMessage `json:"inheritedValue,omitempty"` + EffectiveValue json.RawMessage `json:"effectiveValue"` + EffectiveSource string `json:"effectiveSource"` + Options []PluginSettingOption `json:"options,omitempty"` +} + +// SourceSettingInput is the unparsed view draft projected by Core. Inherit +// retains absence of an override; displaying an effective value cannot save it. +type SourceSettingInput struct { + Text string `json:"text"` + Choice string `json:"choice"` + On bool `json:"on"` + Inherit bool `json:"inherit"` +} + +type SourceSettingsLimits struct { + MaximumSourceBytes int64 `json:"maximumSourceBytes"` + MaximumTotalBytes int64 `json:"maximumTotalBytes"` +} + +type SourceSettingsEffectiveDisplay struct { + Inherited bool `json:"inherited"` + Kind string `json:"kind"` + Text string `json:"text"` + On bool `json:"on"` + Count int `json:"count"` +} + +type SourceSettingsState struct { + EffectiveDisplays map[string]map[string]SourceSettingsEffectiveDisplay `json:"effectiveDisplays"` + Snapshot SourceSettingsSnapshot `json:"snapshot"` + InheritedInputs map[string]map[string]SourceSettingInput `json:"inheritedInputs"` + Inputs map[string]map[string]SourceSettingInput `json:"inputs"` + Limits SourceSettingsLimits `json:"limits"` + Layout []SourceSettingsLayout `json:"layout"` +} + +type SourceSettingsLayout struct { + Group int `json:"group"` + Sources []int `json:"sources"` +} + +type SourceSettingsEdits struct { + SourceID string `json:"sourceID"` + Values map[string]SourceSettingInput `json:"values"` +} + +type SourceSettingsWrite struct { + SourceID string `json:"sourceID"` + Path string `json:"path"` + Revision string `json:"revision"` + Values map[string]json.RawMessage `json:"values"` +} + +type SourceSettingsReceipt struct { + SourceID string `json:"sourceID"` + Revision string `json:"revision"` + Changed bool `json:"changed"` +} + +func (c *Client) ReadSourceSettings(ctx context.Context, result json.RawMessage) (SourceSettingsState, error) { + return settingsSurfaceResult[SourceSettingsState](ctx, c, "plugins.settings.sourceState", "state", struct { + Result json.RawMessage `json:"result"` + }{result}) +} + +func (c *Client) PlanSourceSettingsEdits(ctx context.Context, snapshot SourceSettingsSnapshot, edits []SourceSettingsEdits, confirmed bool) ([]SourceSettingsWrite, error) { + return settingsSurfaceResult[[]SourceSettingsWrite](ctx, c, "plugins.settings.sourceEdit", "writes", struct { + Snapshot SourceSettingsSnapshot `json:"snapshot"` + Edits []SourceSettingsEdits `json:"edits"` + Confirmed bool `json:"confirmed"` + }{snapshot, edits, confirmed}) +} + +func (c *Client) DecodeSourceSettingsReceipt(ctx context.Context, write SourceSettingsWrite, result json.RawMessage) (SourceSettingsReceipt, error) { + return settingsSurfaceResult[SourceSettingsReceipt](ctx, c, "plugins.settings.sourceReceipt", "receipt", struct { + Write SourceSettingsWrite `json:"write"` + Result json.RawMessage `json:"result"` + }{write, result}) +} diff --git a/desktop/internal/core/toolchain.go b/desktop/internal/core/toolchain.go index c57fb736c6..538b52125f 100644 --- a/desktop/internal/core/toolchain.go +++ b/desktop/internal/core/toolchain.go @@ -194,6 +194,7 @@ type ToolchainFixed struct { // ToolchainCandidatesRequest is one toolchains.candidates input. type ToolchainCandidatesRequest struct { + Global bool `json:"global,omitempty"` Registry json.RawMessage `json:"registry"` Tool string `json:"tool"` Platform string `json:"platform"` @@ -262,6 +263,7 @@ type ToolchainQuery struct { // ToolchainResolveRequest is one toolchains.resolve input. type ToolchainResolveRequest struct { + Global bool `json:"global,omitempty"` Registry json.RawMessage `json:"registry"` Tool string `json:"tool"` Directory string `json:"directory"` diff --git a/desktop/internal/core/toolchain_catalog.go b/desktop/internal/core/toolchain_catalog.go new file mode 100644 index 0000000000..694557971f --- /dev/null +++ b/desktop/internal/core/toolchain_catalog.go @@ -0,0 +1,51 @@ +package core + +import ( + "context" +) + +// ToolchainCatalog contains registrations owned by this machine, independent of project pins. +type ToolchainCatalog struct { + Version int `json:"version"` + Tools map[string]ToolchainCatalogEntry `json:"tools"` +} + +type ToolchainCatalogEntry struct { + Homes []string `json:"homes"` + DefaultHome *string `json:"defaultHome,omitempty"` +} + +type ToolchainCatalogState struct { + Document ToolchainCatalog `json:"document"` + Storage struct { + RelativePath string `json:"relativePath"` + MaximumBytes int64 `json:"maximumBytes"` + } `json:"storage"` +} + +type ToolchainCatalogEdit struct { + Tool string `json:"tool"` + Homes []string `json:"homes"` + DefaultHome *string `json:"defaultHome"` +} + +type ToolchainCatalogPublication struct { + Changed bool `json:"changed"` + Document *string `json:"document"` + Catalog ToolchainCatalog `json:"catalog"` +} + +func (c *Client) ReadToolchainCatalog(ctx context.Context, document *string, platform string) (ToolchainCatalogState, error) { + return settingsSurfaceResult[ToolchainCatalogState](ctx, c, "toolchains.catalogState", "state", struct { + Document *string `json:"document"` + Platform string `json:"platform"` + }{document, platform}) +} + +func (c *Client) EditToolchainCatalog(ctx context.Context, document *string, platform string, edits []ToolchainCatalogEdit) (ToolchainCatalogPublication, error) { + return settingsSurfaceResult[ToolchainCatalogPublication](ctx, c, "toolchains.editCatalog", "edit", struct { + Document *string `json:"document"` + Platform string `json:"platform"` + Edits []ToolchainCatalogEdit `json:"edits"` + }{document, platform, edits}) +} diff --git a/desktop/internal/editorview/markers.go b/desktop/internal/editorview/markers.go new file mode 100644 index 0000000000..87e3b8359f --- /dev/null +++ b/desktop/internal/editorview/markers.go @@ -0,0 +1,98 @@ +package editorview + +import ( + "context" + "slices" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" +) + +// ProjectedMarkers is immutable display-cell geometry for one text revision. +// Its internals cannot be changed by callers after worker preparation. +type ProjectedMarkers struct{ lines map[int][]Marker } + +// ProjectMarkers runs off the UI thread over a persistent rope. Each affected +// line is traversed once, only as far as its last diagnostic, with cancellation +// checked for every rope chunk. It never materializes a long line. +func ProjectMarkers(ctx context.Context, text rope.Rope, markers []Marker) (ProjectedMarkers, error) { + if err := ctx.Err(); err != nil { + return ProjectedMarkers{}, err + } + result := ProjectedMarkers{lines: make(map[int][]Marker)} + for _, marker := range markers { + if marker.Line < 0 || marker.Line >= text.LineCount() || marker.Start < 0 || marker.End <= marker.Start { + continue + } + result.lines[marker.Line] = append(result.lines[marker.Line], marker) + } + for line, items := range result.lines { + if err := ctx.Err(); err != nil { + return ProjectedMarkers{}, err + } + positions := make([]int, 0, len(items)*2) + for _, item := range items { + positions = append(positions, item.Start, item.End) + } + slices.Sort(positions) + positions = slices.Compact(positions) + cellsAt := make(map[int]int, len(positions)) + index, units, cells := 0, 0, 0 + text.Chunks(text.LineStart(line), text.LineEnd(line), func(chunk string) bool { + if ctx.Err() != nil { + return false + } + for len(chunk) > 0 && index < len(positions) { + r, size := utf8.DecodeRuneInString(chunk) + width := 1 + if r > 0xffff { + width = 2 + } + // A malformed UTF-16 endpoint inside a surrogate pair rounds down, + // matching ByteOffset. Out-of-line endpoints clamp to the line end. + for index < len(positions) && positions[index] < units+width { + cellsAt[positions[index]] = cells + index++ + } + if index == len(positions) { + return false + } + units += width + cells += runeCells(r, cells) + chunk = chunk[size:] + } + return index < len(positions) + }) + if err := ctx.Err(); err != nil { + return ProjectedMarkers{}, err + } + for ; index < len(positions); index++ { + cellsAt[positions[index]] = cells + } + projected := items[:0] + for _, item := range items { + item.Start, item.End = cellsAt[item.Start], cellsAt[item.End] + if item.End > item.Start { + projected = append(projected, item) + } + } + if len(projected) == 0 { + delete(result.lines, line) + } else { + result.lines[line] = projected + } + } + if len(result.lines) == 0 { + result.lines = nil + } + return result, nil +} + +// SetProjectedMarkers publishes worker geometry only for the captured revision. +func (v *View) SetProjectedMarkers(markers ProjectedMarkers, revision int) bool { + if v.revision != revision { + return false + } + v.markers = markers.lines + return true +} diff --git a/desktop/internal/editorview/markers_test.go b/desktop/internal/editorview/markers_test.go index d50f700aaa..dede55a5b4 100644 --- a/desktop/internal/editorview/markers_test.go +++ b/desktop/internal/editorview/markers_test.go @@ -1,9 +1,73 @@ package editorview -import "testing" +import ( + "context" + "errors" + "math" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// The language server counts UTF-16 units; tabs and wide glyphs occupy a +// different number of screen cells. Measure the actual painted geometry. +func TestDiagnosticUnderlineFollowsTextCells(t *testing.T) { + for _, test := range []struct { + name, text string + start, end, cell int + cellWidth float32 + }{ + {"tab", "\tMissing", 1, 8, tabSize, 10}, + {"wide", "中Missing", 1, 8, 2, 10}, + {"supplementary", "😀Missing", 2, 9, 2, 10}, + {"combined", "\t中😀Missing", 4, 11, tabSize + 4, 10}, + {"fractional-phase", "\t中😀Missing", 4, 11, tabSize + 4, 7.3}, + } { + t.Run(test.name, func(t *testing.T) { + v := newTestView(t, test.text) + v.cellW, v.cellH, v.lineH, v.textLeft = test.cellWidth, 16, 24, 70 + v.SetMarkers([]Marker{{Line: 0, Start: test.start, End: test.end, Severity: MarkerError}}) + var canvas gfx.Canvas + v.paintMarkers(&canvas, 0, 0, 100, 0, 0) + left, right := float32(math.Inf(1)), float32(math.Inf(-1)) + for _, rectangle := range canvas.Rectangles() { + left = min(left, rectangle.Bounds.X) + right = max(right, rectangle.Bounds.X+rectangle.Bounds.Width) + } + for _, triangle := range canvas.Triangles() { + for _, point := range triangle.Points { + left, right = min(left, point.X), max(right, point.X) + } + } + want := v.textLeft + float32(test.cell)*v.cellW + if math.Abs(float64(left-want)) > 0.6 || math.Abs(float64(right-(want+7*v.cellW))) > 0.6 { + t.Fatalf("underline spans %v..%v, want %v..%v under Missing", left, right, want, want+7*v.cellW) + } + }) + } +} + +func TestDiagnosticUnderlineIsAWaveNearTheText(t *testing.T) { + v := newTestView(t, "Missing") + v.cellW, v.cellH, v.lineH = 10, 16, 36 + v.SetMarkers([]Marker{{Line: 0, Start: 0, End: 7, Severity: MarkerError}}) + var canvas gfx.Canvas + v.paintMarkers(&canvas, 0, 0, 100, 0, 0) + if len(canvas.Triangles()) < 4 || len(canvas.Rectangles()) != 0 { + t.Fatal("diagnostics must draw a thin wave instead of a filled rectangle") + } + for _, triangle := range canvas.Triangles() { + for _, point := range triangle.Points { + if point.Y < 24 || point.Y > 29 { + t.Fatalf("wave at y=%v is detached from the centered 16-point text", point.Y) + } + } + } +} func TestSetMarkersGroupsByLine(t *testing.T) { - var v View + v := newTestView(t, "abcdef\nsecond\n0123456789") v.SetMarkers([]Marker{ {Line: 2, Start: 4, End: 9, Severity: MarkerError}, {Line: 0, Start: 0, End: 3, Severity: MarkerWarning}, @@ -18,7 +82,7 @@ func TestSetMarkersGroupsByLine(t *testing.T) { } func TestSetMarkersDropsInvisibleOnes(t *testing.T) { - var v View + v := newTestView(t, "abcdef") v.SetMarkers([]Marker{ {Line: -1, Start: 0, End: 1}, {Line: 0, Start: -1, End: 2}, @@ -32,7 +96,7 @@ func TestSetMarkersDropsInvisibleOnes(t *testing.T) { } func TestSetMarkersReplacesThePreviousSet(t *testing.T) { - var v View + v := newTestView(t, "first\nsecond\nthird\nfourth") v.SetMarkers([]Marker{{Line: 1, Start: 0, End: 2}}) v.SetMarkers([]Marker{{Line: 3, Start: 1, End: 4}}) if len(v.markers) != 1 { @@ -63,3 +127,24 @@ func TestMarkerColorDistinguishesSeverities(t *testing.T) { t.Fatal("an unknown severity did not fall back to info") } } + +func TestDiagnosticProjectionCancelsAndRefusesAnEditedRevision(t *testing.T) { + v := newTestView(t, strings.Repeat("\t中😀", 2048)+"Missing") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := ProjectMarkers(ctx, v.TextSnapshot(), []Marker{{Line: 0, Start: 1, End: 8}}); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled projection: %v", err) + } + revision := v.Revision() + projected, err := ProjectMarkers(context.Background(), v.TextSnapshot(), []Marker{{Line: 0, Start: 4 * 2048, End: 4*2048 + 7}}) + if err != nil { + t.Fatal(err) + } + if got := projected.lines[0][0]; got.Start != 8*2048 || got.End != 8*2048+7 { + t.Fatalf("chunk-spanning cells: %+v", got) + } + v.typeText("changed") + if v.SetProjectedMarkers(projected, revision) { + t.Fatal("stale worker geometry reached edited text") + } +} diff --git a/desktop/internal/editorview/paint.go b/desktop/internal/editorview/paint.go index e6b7450397..5b5c6fa6f5 100644 --- a/desktop/internal/editorview/paint.go +++ b/desktop/internal/editorview/paint.go @@ -507,8 +507,56 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, // replacementChar is what a byte that is not UTF-8 shows, as range over a string reads it. const replacementChar = "\uFFFD" -// markerThickness is how tall an underline is, in pixels. Two is the thinnest line -// that survives a device pixel ratio above one. +// Diagnostic waves stay close to the text even when line spacing is enlarged. +const markerWaveHeight = float32(3) + +// One period is immutable, so both geometry and paint reuse Viva's bounded +// glyph cache. Its filled strip is a thin wave, with no per-document path cache. +var markerWave = gfx.Icon{ViewBox: 4, ViewHeight: markerWaveHeight, Commands: []gfx.PathCommand{ + gfx.MoveTo(0, 0), gfx.LineTo(2, 2), gfx.LineTo(4, 0), gfx.LineTo(4, 1), gfx.LineTo(2, 3), gfx.LineTo(0, 1), gfx.ClosePath(), +}} + +type markerWaveKey struct{ width, phase float32 } + +// Cache only a small working set of short underlines. Unique or very long +// diagnostics fall back to the one shared period, keeping retained geometry bounded. +func (v *View) markerWaveGlyph(width, phase float32) (gfx.Icon, bool) { + key := markerWaveKey{width, phase} + if icon, ok := v.markerWaves[key]; ok { + return icon, true + } + count := int(width) + 8 + if width > 512 || len(v.markerWaves) >= 32 || v.markerWaveCommands+count > 8192 { + return gfx.Icon{}, false + } + points := make([]gfx.PathCommand, 0, count) + height := func(x float32) float32 { + p := float32(math.Mod(float64(x+phase), 4)) + if p > 2 { + p = 4 - p + } + return p + } + points = append(points, gfx.MoveTo(0, height(0))) + for x := 2 - float32(math.Mod(float64(phase), 2)); x < width; x += 2 { + points = append(points, gfx.LineTo(x, height(x))) + } + points = append(points, gfx.LineTo(width, height(width)), gfx.LineTo(width, height(width)+1)) + for i := len(points) - 3; i >= 0; i-- { + point := points[i].Point + points = append(points, gfx.LineTo(point.X, point.Y+1)) + } + points = append(points, gfx.ClosePath()) + icon := gfx.Icon{ViewBox: width, ViewHeight: markerWaveHeight, Commands: points} + if v.markerWaves == nil { + v.markerWaves = make(map[markerWaveKey]gfx.Icon) + } + v.markerWaves[key] = icon + v.markerWaveCommands += len(points) + return icon, true +} + +// Hovered document links retain their straight two-point underline. const markerThickness = 2 // paintMarkers underlines the diagnostics that fall inside one wrapped row. @@ -525,12 +573,26 @@ func (v *View) paintMarkers(canvas *gfx.Canvas, line, from, to, shift int, y flo continue } left := v.textLeft + float32(start-shift)*v.cellW - v.scrollX - canvas.Fill(gfx.Rect{ - X: left, - Y: y + v.lineH - markerThickness, - Width: float32(end-start) * v.cellW, - Height: markerThickness, - }, markerColor(marker.Severity)) + width := float32(end-start) * v.cellW + top := y + min((v.lineH+v.cellH)/2-0.5, v.lineH-markerWaveHeight) + // Phase belongs to document cells, so sideways scrolling and wrapping + // clip the same wave instead of making it crawl under the characters. + phase := float32(math.Mod(float64(float32(start)*v.cellW), 4)) + if glyph, ok := v.markerWaveGlyph(width, phase); ok { + canvas.DrawIcon(glyph, gfx.Rect{X: left, Y: top, Width: width, Height: markerWaveHeight}, markerColor(marker.Severity)) + continue + } + for x := -phase; x < width; x += 4 { + bounds := gfx.Rect{X: left + x, Y: top, Width: 4, Height: markerWaveHeight} + if x >= 0 && x+4 <= width { + canvas.DrawIcon(markerWave, bounds, markerColor(marker.Severity)) + } else { + // Only the two edge tiles need geometric clipping. Interior tiles + // reuse Viva's immutable glyph mesh instead of retessellating paths. + clip := gfx.IconClip{Bounds: gfx.Rect{X: max(-x, 0), Width: min(4, width-x) - max(-x, 0), Height: markerWaveHeight}} + canvas.DrawIconTransformed(markerWave, bounds, markerColor(marker.Severity), gfx.IconTransform{Clip: &clip}) + } + } } } diff --git a/desktop/internal/editorview/view.go b/desktop/internal/editorview/view.go index f813fd8b9f..db46808079 100644 --- a/desktop/internal/editorview/view.go +++ b/desktop/internal/editorview/view.go @@ -8,6 +8,7 @@ package editorview import ( + "context" "slices" "strings" "sync/atomic" @@ -184,9 +185,12 @@ type View struct { // caretLine is the cells of the line the last edit left the caret on, while that line has no // tab; see lineCells. caretLine lineCells - // markers are the diagnostics to underline, grouped by line. They are the view's only + // markers are diagnostics projected into display cells and grouped by line. They are the view's only // knowledge of a language server: the text and the caret never depend on them. markers map[int][]Marker + // Diagnostic glyphs are view-local and bounded; Viva reuses their immutable meshes. + markerWaves map[markerWaveKey]gfx.Icon + markerWaveCommands int // links are the document links the view can underline on hover; hovered is the one the pointer is // over while the link modifier is held, or nil. links []Link @@ -372,18 +376,8 @@ func (v *View) SetMarkers(markers []Marker) { v.markers = nil return } - grouped := make(map[int][]Marker, len(markers)) - for _, marker := range markers { - if marker.Line < 0 || marker.Start < 0 || marker.End <= marker.Start { - continue - } - grouped[marker.Line] = append(grouped[marker.Line], marker) - } - if len(grouped) == 0 { - v.markers = nil - return - } - v.markers = grouped + projected, _ := ProjectMarkers(context.Background(), v.text, markers) + v.markers = projected.lines } // Close stops the view's background highlighter. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index c3f88d900d..990873542b 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1465,6 +1465,15 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.updates.title": "Updates", "desktop.settings.updates.upToDate": "Lithe {version} is up to date.", "desktop.settings.updates.update": "Update", + "desktop.sourceSettings.add": "Add override", + "desktop.sourceSettings.allEntriesShown": "All available entries are shown.", + "desktop.sourceSettings.close": "Back", + "desktop.sourceSettings.compilerTitle": "{compiler} Compiler", + "desktop.sourceSettings.effective": "Effective: {value}", + "desktop.sourceSettings.fileCount": "{count} entries", + "desktop.sourceSettings.inherit": "Inherit ({value})", + "desktop.sourceSettings.noValue": "Not determined", + "desktop.sourceSettings.remove": "Inherit project defaults", "desktop.startupSweep.body": "{arg1} processes started by an earlier run of Lithe are still running. Ending them stops them.", "desktop.startupSweep.end": "End them", "desktop.startupSweep.item": "{arg1} PID {arg2} {arg3}", @@ -1626,13 +1635,19 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.chooseHelp": "Selecting a row only changes the draft. Save writes the choice to this project's .lithe/toolchains/local.json; Cancel leaves the file unchanged.", "desktop.toolchains.conflict": "{tool} is defined by {plugins}; disable all but one of those plugins.", "desktop.toolchains.description": "Tools declared by enabled plugins. The effective value and its source come from the shared Core resolver; nothing is written until Save.", + "desktop.toolchains.directory": "Installation directory", + "desktop.toolchains.directoryHelp": "Choose the installation root containing the tool executable, such as a JDK directory rather than its bin folder. Checking the version only updates the draft; Save writes the project selection.", "desktop.toolchains.effective": "Effective: {value}", + "desktop.toolchains.global": "Global defaults", + "desktop.toolchains.globalHelp": "Manage detected and manually added SDKs for all projects. Save writes to the application’s user settings; projects can override the default. Existing processes use the new SDK after restarting.", "desktop.toolchains.installation": "{home} · {version} · {provider}", + "desktop.toolchains.invalidDirectory": "The selected directory does not contain a usable installation. Check the directory and try again.", "desktop.toolchains.loadFailed": "Could not read toolchains: {reason}", "desktop.toolchains.loading": "Reading toolchains…", "desktop.toolchains.noInstallations": "No installations found.", "desktop.toolchains.noProject": "Open a project to read its toolchains.", "desktop.toolchains.pinSource": "Pinned in {directory}", + "desktop.toolchains.project": "Current project", "desktop.toolchains.providerUnsupported": "This build cannot query plugin backends yet; provider-reported installations are not shown.", "desktop.toolchains.reload": "Reload", "desktop.toolchains.reloadAfterSave": "The save step completed, but its source could not be reloaded or closed cleanly. Reload before saving again; your draft has been kept.", @@ -1645,6 +1660,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.sourceInvalid": "The toolchain or ignore configuration is invalid, too large, or cannot be accessed safely. Check the source files, then reload.", "desktop.toolchains.title": "Toolchains", "desktop.toolchains.unavailable": "Unavailable: {reason}", + "desktop.toolchains.useDirectory": "Use directory", "desktop.tools.background": "Background", "desktop.tools.dragHint": "Drag to move elsewhere", "desktop.tools.moveTo": "Move to", @@ -4079,6 +4095,15 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.updates.title": "更新", "desktop.settings.updates.upToDate": "Lithe {version} 已是最新版本。", "desktop.settings.updates.update": "更新", + "desktop.sourceSettings.add": "添加覆盖", + "desktop.sourceSettings.allEntriesShown": "所有可用条目已列出。", + "desktop.sourceSettings.close": "返回", + "desktop.sourceSettings.compilerTitle": "{compiler} 编译器", + "desktop.sourceSettings.effective": "当前生效:{value}", + "desktop.sourceSettings.fileCount": "{count} 项", + "desktop.sourceSettings.inherit": "继承({value})", + "desktop.sourceSettings.noValue": "未确定", + "desktop.sourceSettings.remove": "继承项目设置", "desktop.startupSweep.body": "上次运行 Lithe 启动的 {arg1} 个进程仍在运行。结束它们会停止这些进程。", "desktop.startupSweep.end": "结束这些进程", "desktop.startupSweep.item": "{arg1} PID {arg2} {arg3}", @@ -4240,13 +4265,19 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.chooseHelp": "选择一行只修改草稿。保存会写入本项目的 .lithe/toolchains/local.json;取消不会改动文件。", "desktop.toolchains.conflict": "{tool} 同时由 {plugins} 定义;请只保留其中一个插件。", "desktop.toolchains.description": "已启用插件声明的工具。生效值与来源由共享 Core 解析得出;点击保存前不会写入任何文件。", + "desktop.toolchains.directory": "安装目录", + "desktop.toolchains.directoryHelp": "选择包含工具程序的安装根目录,例如 JDK 目录,而不是 bin 目录。验证版本只修改草稿;点击保存后才写入项目选择。", "desktop.toolchains.effective": "生效:{value}", + "desktop.toolchains.global": "全局默认", + "desktop.toolchains.globalHelp": "统一管理自动识别和手动添加的 SDK,保存到应用的用户设置。项目可单独覆盖默认版本;已启动的进程需重启后使用新版本。", "desktop.toolchains.installation": "{home} · {version} · {provider}", + "desktop.toolchains.invalidDirectory": "所选目录中未找到可用的工具安装,请检查目录后重试。", "desktop.toolchains.loadFailed": "无法读取工具链:{reason}", "desktop.toolchains.loading": "正在读取工具链…", "desktop.toolchains.noInstallations": "没有找到安装。", "desktop.toolchains.noProject": "打开项目后才能读取其工具链。", "desktop.toolchains.pinSource": "固定在 {directory}", + "desktop.toolchains.project": "当前项目", "desktop.toolchains.providerUnsupported": "当前版本还不能查询插件后端;由提供方报告的安装不会显示。", "desktop.toolchains.reload": "重新读取", "desktop.toolchains.reloadAfterSave": "保存步骤已完成,但未能重新读取或正常关闭配置来源。再次保存前请重新加载;草稿已保留。", @@ -4259,6 +4290,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.sourceInvalid": "工具链或忽略配置无效、过大或无法安全访问。请检查来源文件后重新加载。", "desktop.toolchains.title": "工具链", "desktop.toolchains.unavailable": "不可用:{reason}", + "desktop.toolchains.useDirectory": "使用此目录", "desktop.tools.background": "背景", "desktop.tools.dragHint": "可拖动到其他位置", "desktop.tools.moveTo": "移动到", diff --git a/desktop/internal/installedpackage/installedpackage.go b/desktop/internal/installedpackage/installedpackage.go index f4bfb4cf54..30e287cd1f 100644 --- a/desktop/internal/installedpackage/installedpackage.go +++ b/desktop/internal/installedpackage/installedpackage.go @@ -12,10 +12,37 @@ // package and fails if it ever writes to the file system. package installedpackage -import "os" +import ( + "os" + "path/filepath" + "runtime" + "strings" +) // Executable returns the path of the running client executable. Its only use is starting another -// client of the same build; nothing is written beside it. +// client of the same build or protecting its installation; nothing is written beside it. func Executable() (string, error) { return os.Executable() } + +// Root returns the read-only installation boundary, including all macOS bundle +// resources or the Windows executable's installation directory. Callers use it +// only to refuse writes; mutable state never derives a destination from it. +func Root() (string, error) { + executable, err := Executable() + if err != nil { + return "", err + } + return rootForExecutable(executable), nil +} +func rootForExecutable(executable string) string { + directory := filepath.Dir(executable) + if runtime.GOOS == "darwin" { + for parent := directory; filepath.Dir(parent) != parent; parent = filepath.Dir(parent) { + if strings.EqualFold(filepath.Ext(parent), ".app") { + return parent + } + } + } + return directory +} diff --git a/desktop/internal/installedpackage/installedpackage_test.go b/desktop/internal/installedpackage/installedpackage_test.go index 4639ec6290..8004625b47 100644 --- a/desktop/internal/installedpackage/installedpackage_test.go +++ b/desktop/internal/installedpackage/installedpackage_test.go @@ -2,6 +2,8 @@ package installedpackage import ( "os" + "path/filepath" + "runtime" "testing" ) @@ -18,3 +20,19 @@ func TestExecutableIsTheRunningProgram(t *testing.T) { t.Fatalf("Executable = %q, want %q", got, want) } } + +func TestRootIncludesEveryProductionResourceDirectory(t *testing.T) { + base := filepath.Join(t.TempDir(), "Lithe.app") + executable := filepath.Join(base, "Contents", "MacOS", "lithe") + want := filepath.Dir(executable) + if runtime.GOOS == "darwin" { + want = base + } + if got := rootForExecutable(executable); got != want { + t.Fatalf("installation root = %q; want %q", got, want) + } + windowsStyle := filepath.Join(t.TempDir(), "Lithe", "lithe.exe") + if got := rootForExecutable(windowsStyle); got != filepath.Dir(windowsStyle) { + t.Fatalf("executable resources escaped installation: %q", got) + } +} diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 2c4e181cd7..4b9d746812 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -155,6 +155,7 @@ func Declared() Capabilities { "pluginFunctions", "projectGenerators", "settings", + "sourceSettings", "toolDefinitions", "ui", "vcsProviders", diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 2d140989ab..ea4dd715a7 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -60,7 +60,7 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { want := []string{ "backend", "buildProviders", "buildSystems", "commandInstallers", "debugAdapters", "languageServers", "languages", "outputLinkMatchers", "pluginFunctions", - "projectGenerators", "settings", "toolDefinitions", "ui", "vcsProviders", + "projectGenerators", "settings", "sourceSettings", "toolDefinitions", "ui", "vcsProviders", } if len(declared) != len(want) { t.Fatalf("declared = %v", declared) diff --git a/desktop/internal/pluginservice/settings_editor.go b/desktop/internal/pluginservice/settings_editor.go index f49851f240..d28ebfe91f 100644 --- a/desktop/internal/pluginservice/settings_editor.go +++ b/desktop/internal/pluginservice/settings_editor.go @@ -213,6 +213,7 @@ func settingsPackageDirectoryInfo(ctx context.Context, path string) (info os.Fil type SettingsActionResult struct { Plan core.PluginSettingsActionPlan Completed bool + Sources *pluginsettings.SourceEditor } // SettingsOwner returns the private registration identity captured on load. diff --git a/desktop/internal/pluginsettings/sources.go b/desktop/internal/pluginsettings/sources.go new file mode 100644 index 0000000000..390d5ba0e4 --- /dev/null +++ b/desktop/internal/pluginsettings/sources.go @@ -0,0 +1,252 @@ +package pluginsettings + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// ErrSourcesCommitted means a source was published before a later failure. +// The editor must retain its draft and require a fresh read before retrying. +var ErrSourcesCommitted = errors.New("native settings sources were published; reload before retrying") + +type SourceKernel interface { + PlanSourceSettingsEdits(context.Context, core.SourceSettingsSnapshot, []core.SourceSettingsEdits, bool) ([]core.SourceSettingsWrite, error) + DecodeSourceSettingsReceipt(context.Context, core.SourceSettingsWrite, json.RawMessage) (core.SourceSettingsReceipt, error) +} + +// SourceEditor exposes only Core's non-sensitive projection. Native source +// bytes and read identities are private, as in the preference Snapshot. +type SourceEditor struct { + State core.SourceSettingsState + root string + files map[string]configfile.Snapshot + paths map[string]string + limits core.SourceSettingsLimits + protectedRoots []string +} + +func sourceRevision(file configfile.Snapshot) string { + if !file.Exists() { + return "missing" + } + digest := sha256.Sum256(file.Bytes()) + return "sha256:" + hex.EncodeToString(digest[:]) +} + +// CaptureSources is read-only. Package/installation roots come from the native +// owner, not a plugin's projection; native aliases are rejected before editing. +func CaptureSources(ctx context.Context, workspace string, state core.SourceSettingsState, protectedRoots []string) (SourceEditor, error) { + editor := SourceEditor{State: state, root: workspace, limits: state.Limits, files: make(map[string]configfile.Snapshot), paths: make(map[string]string), protectedRoots: append([]string(nil), protectedRoots...)} + if editor.limits.MaximumSourceBytes <= 0 || editor.limits.MaximumTotalBytes <= 0 { + return editor, configfile.ErrTooLarge + } + var bytes int64 + var identities []os.FileInfo + for _, source := range state.Snapshot.Sources { + if err := ctx.Err(); err != nil { + return editor, err + } + file, err := configfile.Capture(ctx, workspace, source.Path, editor.limits.MaximumSourceBytes) + if err != nil { + return editor, err + } + if sourceRevision(file) != source.Revision { + return editor, configfile.ErrConflict + } + if err := allowSourcePath(file.Path(), protectedRoots); err != nil { + return editor, err + } + if file.Exists() { + info, err := os.Stat(file.Path()) + if err != nil { + return editor, err + } + for _, previous := range identities { + if os.SameFile(previous, info) { + return editor, configfile.ErrTarget + } + } + identities = append(identities, info) + } + bytes += int64(len(file.Bytes())) + if bytes > editor.limits.MaximumTotalBytes { + return editor, configfile.ErrTooLarge + } + editor.files[source.ID], editor.paths[source.ID] = file, source.Path + } + return editor, nil +} + +// Resolve the nearest existing parent as well as the leaf, so missing files +// under an installed bundle cannot bypass the read-only ownership boundary. +func allowSourcePath(path string, roots []string) error { + canonical := path + var tail []string + for { + resolved, err := filepath.EvalSymlinks(canonical) + if err == nil { + canonical = resolved + break + } + if !errors.Is(err, os.ErrNotExist) { + return err + } + parent := filepath.Dir(canonical) + if parent == canonical { + return configfile.ErrTarget + } + tail = append(tail, filepath.Base(canonical)) + canonical = parent + } + for index := len(tail) - 1; index >= 0; index-- { + canonical = filepath.Join(canonical, tail[index]) + } + for _, root := range roots { + if root == "" { + continue + } + resolved, err := filepath.EvalSymlinks(root) + // log-exempt: 预期的缺失:尚未创建的插件安装根不含发行资源。 + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return err + } + relative, err := filepath.Rel(resolved, canonical) + if err == nil && (relative == "." || filepath.IsLocal(relative)) { + return configfile.ErrTarget + } + } + return nil +} + +type stagedSource struct { + write core.SourceSettingsWrite + before configfile.Snapshot + content []byte + revision string +} + +// Apply prepares every replacement before publishing any source. Each commit +// retains the captured bytes and metadata guard. A partial failure is explicit. +// The caller owns workspace/package checks and must perform a fresh read-back. +func (s SourceEditor) Apply(ctx context.Context, kernel SourceKernel, edits []core.SourceSettingsEdits, call func(context.Context, json.RawMessage) (json.RawMessage, error), check func() error) (published map[string]string, err error) { + published = make(map[string]string) + defer func() { + if err != nil && len(published) > 0 { + err = errors.Join(ErrSourcesCommitted, err) + } + }() + writes, err := kernel.PlanSourceSettingsEdits(ctx, s.State.Snapshot, edits, true) + if err != nil || len(writes) == 0 { + return published, err + } + if err := check(); err != nil { + return published, err + } + staging, err := os.MkdirTemp("", "lithe-source-settings-") + if err != nil { + return published, err + } + defer func() { err = errors.Join(err, os.RemoveAll(staging)) }() + var staged []stagedSource + var total int64 + for _, write := range writes { + before, ok := s.files[write.SourceID] + if !ok || write.Path != s.paths[write.SourceID] || sourceRevision(before) != write.Revision { + return published, configfile.ErrConflict + } + if err := before.Verify(ctx); err != nil { + return published, err + } + if err := check(); err != nil { + return published, err + } + file, err := os.CreateTemp(staging, "source-*") + if err != nil { + return published, err + } + name := file.Name() + if err := file.Close(); err != nil { + return published, err + } + params, err := json.Marshal(struct { + Operation string `json:"operation"` + SourceID string `json:"sourceID"` + Revision string `json:"revision"` + Values map[string]json.RawMessage `json:"values"` + OutputFile string `json:"outputFile"` + }{"editSource", write.SourceID, write.Revision, write.Values, name}) + if err != nil { + return published, err + } + result, err := call(ctx, params) + if err != nil { + return published, err + } + receipt, err := kernel.DecodeSourceSettingsReceipt(ctx, write, result) + if err != nil { + return published, err + } + if !receipt.Changed { + continue + } + stagedFile, err := configfile.Capture(ctx, staging, filepath.Base(name), s.limits.MaximumSourceBytes) + if err != nil { + return published, err + } + if sourceRevision(stagedFile) != receipt.Revision { + return published, configfile.ErrConflict + } + content := stagedFile.Bytes() + total += int64(len(content)) + if total > s.limits.MaximumTotalBytes { + return published, configfile.ErrTooLarge + } + staged = append(staged, stagedSource{write: write, before: before, content: content, revision: receipt.Revision}) + } + current := make([]configfile.Snapshot, len(staged)) + for index := range staged { + current[index] = staged[index].before + } + verify := func() error { + if err := check(); err != nil { + return err + } + for _, file := range current { + if err := allowSourcePath(file.Path(), s.protectedRoots); err != nil { + return err + } + if err := file.Verify(ctx); err != nil { + return err + } + } + return nil + } + for index, replacement := range staged { + committed, err := replacement.before.Replace(ctx, replacement.content, verify) + if committed { + published[replacement.write.SourceID] = replacement.revision + } + if err != nil { + return published, err + } + current[index], err = configfile.Capture(ctx, s.root, replacement.write.Path, s.limits.MaximumSourceBytes) + if err != nil { + return published, err + } + if sourceRevision(current[index]) != replacement.revision { + return published, configfile.ErrConflict + } + } + return published, nil +} diff --git a/desktop/internal/pluginsettings/sources_test.go b/desktop/internal/pluginsettings/sources_test.go new file mode 100644 index 0000000000..f63779e5c1 --- /dev/null +++ b/desktop/internal/pluginsettings/sources_test.go @@ -0,0 +1,280 @@ +package pluginsettings + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type sourceFixture struct { + root string + editor SourceEditor + ctx context.Context + calls int + staging []string +} + +func sourceDigest(data []byte) string { + digest := sha256.Sum256(data) + return "sha256:" + hex.EncodeToString(digest[:]) +} + +func newSourceFixture(t *testing.T) *sourceFixture { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "child"), 0700); err != nil { + t.Fatal(err) + } + data := []byte(`{"target":"two","unrelated":"keep","credential":"private-canary"}`) + if err := os.WriteFile(filepath.Join(root, "child/tool.json"), data, 0600); err != nil { + t.Fatal(err) + } + fixture, err := os.ReadFile(contractfixture.CoreFixture("plugins/settings-sources.json")) + if err != nil { + t.Fatal(err) + } + var payload struct { + Snapshot core.SourceSettingsSnapshot `json:"snapshot"` + } + if err := json.Unmarshal(fixture, &payload); err != nil { + t.Fatal(err) + } + payload.Snapshot.Sources[1].Revision = sourceDigest(data) + raw, err := json.Marshal(payload.Snapshot) + if err != nil { + t.Fatal(err) + } + state, err := core.NewClient().ReadSourceSettings(ctx, raw) + if err != nil { + t.Fatal(err) + } + editor, err := CaptureSources(ctx, root, state, nil) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte("private-canary")) { + t.Fatal("private source content entered the projection") + } + return &sourceFixture{root: root, editor: editor, ctx: ctx} +} + +// This synthetic backend edits inert JSON fixtures only. It deliberately opens +// the existing staging file without CREATE, as the public protocol requires. +func (f *sourceFixture) call(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + var request struct { + SourceID string `json:"sourceID"` + Values map[string]json.RawMessage `json:"values"` + OutputFile string `json:"outputFile"` + } + if err := json.Unmarshal(params, &request); err != nil { + return nil, err + } + f.calls++ + f.staging = append(f.staging, request.OutputFile) + path := f.editor.paths[request.SourceID] + document := make(map[string]json.RawMessage) + data, err := os.ReadFile(filepath.Join(f.root, path)) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + if err == nil { + if err := json.Unmarshal(data, &document); err != nil { + return nil, err + } + } + for id, value := range request.Values { + if string(value) == "null" { + delete(document, id) + } else { + document[id] = value + } + } + data, err = json.Marshal(document) + if err != nil { + return nil, err + } + file, err := os.OpenFile(request.OutputFile, os.O_WRONLY, 0) + if err != nil { + return nil, err + } + _, writeErr := file.Write(data) + if err := errors.Join(writeErr, file.Close()); err != nil { + return nil, err + } + return json.Marshal(map[string]any{"format": "litheSettingsSourceEdit", "version": 0, "sourceID": request.SourceID, "revision": sourceDigest(data), "changed": true}) +} + +func (f *sourceFixture) edit(source, choice string) core.SourceSettingsEdits { + input := f.editor.State.Inputs[source]["target"] + input.Inherit, input.Choice = false, choice + return core.SourceSettingsEdits{SourceID: source, Values: map[string]core.SourceSettingInput{"target": input}} +} + +func assertSourceStagingRemoved(t *testing.T, f *sourceFixture) { + t.Helper() + for _, path := range f.staging { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Errorf("staging remains after operation: %v", err) + } + } +} + +func TestNativeSourcesReadAndUnchangedInheritanceWriteNothing(t *testing.T) { + f := newSourceFixture(t) + var edits []core.SourceSettingsEdits + for id, inputs := range f.editor.State.Inputs { + edits = append(edits, core.SourceSettingsEdits{SourceID: id, Values: inputs}) + } + published, err := f.editor.Apply(f.ctx, core.NewClient(), edits, f.call, func() error { return nil }) + if err != nil || len(published) != 0 || f.calls != 0 { + t.Fatalf("no-op = %v, %v, calls %d", published, err, f.calls) + } + if _, err := os.Stat(filepath.Join(f.root, "tool.json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("opening/saving unchanged inheritance created a source") + } +} + +func TestNativeSourcesPublishOnlyTheEditedModuleAndPreservePrivateFields(t *testing.T) { + f := newSourceFixture(t) + published, err := f.editor.Apply(f.ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("child", "one")}, f.call, func() error { return nil }) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(f.root, "child/tool.json")) + if err != nil { + t.Fatal(err) + } + if len(published) != 1 || published["child"] != sourceDigest(data) { + t.Fatalf("published = %v", published) + } + var document map[string]string + if err := json.Unmarshal(data, &document); err != nil { + t.Fatal(err) + } + if document["target"] != "one" || document["credential"] != "private-canary" || document["unrelated"] != "keep" { + t.Fatal("native edit lost unrelated/private content") + } + if _, err := os.Stat(filepath.Join(f.root, "tool.json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("module edit created project defaults") + } + assertSourceStagingRemoved(t, f) +} + +func TestNativeSourcesRejectAnExternalEditBeforeCallingThePlugin(t *testing.T) { + f := newSourceFixture(t) + if err := os.WriteFile(filepath.Join(f.root, "child/tool.json"), []byte(`{"target":"external"}`), 0600); err != nil { + t.Fatal(err) + } + _, err := f.editor.Apply(f.ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("child", "one")}, f.call, func() error { return nil }) + if !errors.Is(err, configfile.ErrConflict) || f.calls != 0 { + t.Fatalf("conflict = %v, calls %d", err, f.calls) + } +} + +func TestNativeSourcesPrepareAllReplacementsBeforePublishingAny(t *testing.T) { + f := newSourceFixture(t) + rejected := errors.New("synthetic staging rejection") + call := func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + if f.calls > 0 { + return nil, rejected + } + return f.call(ctx, params) + } + published, err := f.editor.Apply(f.ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("root", "one"), f.edit("child", "one")}, call, func() error { return nil }) + if !errors.Is(err, rejected) || len(published) != 0 { + t.Fatalf("preparation = %v, %v", published, err) + } + if _, err := os.Stat(filepath.Join(f.root, "tool.json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("first source was published before all staging succeeded") + } + assertSourceStagingRemoved(t, f) +} + +func TestNativeSourcesRejectAFalseStagingDigestAndCleanUp(t *testing.T) { + f := newSourceFixture(t) + call := func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + result, err := f.call(ctx, params) + if err != nil { + return nil, err + } + if err := os.WriteFile(f.staging[len(f.staging)-1], []byte("different bytes"), 0600); err != nil { + return nil, err + } + return result, nil + } + published, err := f.editor.Apply(f.ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("child", "one")}, call, func() error { return nil }) + if !errors.Is(err, configfile.ErrConflict) || len(published) != 0 { + t.Fatalf("digest mismatch = %v, %v", published, err) + } + assertSourceStagingRemoved(t, f) +} + +func TestNativeSourcesReportPartialPublicationAndKeepTheRemainingSource(t *testing.T) { + f := newSourceFixture(t) + revoked := errors.New("synthetic owner revocation") + check := func() error { + if _, err := os.Stat(filepath.Join(f.root, "tool.json")); err == nil { + return revoked + } + return nil + } + published, err := f.editor.Apply(f.ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("root", "one"), f.edit("child", "one")}, f.call, check) + if !errors.Is(err, ErrSourcesCommitted) || !errors.Is(err, revoked) || len(published) != 1 { + t.Fatalf("partial outcome = %v, %v", published, err) + } + data, readErr := os.ReadFile(filepath.Join(f.root, "child/tool.json")) + if readErr != nil { + t.Fatal(readErr) + } + if !bytes.Contains(data, []byte(`"target":"two"`)) { + t.Fatal("revoked operation changed the remaining source") + } + assertSourceStagingRemoved(t, f) +} + +func TestNativeSourcesCannotEditAnInstallationRoot(t *testing.T) { + f := newSourceFixture(t) + _, err := CaptureSources(f.ctx, f.root, f.editor.State, []string{f.root}) + if !errors.Is(err, configfile.ErrTarget) { + t.Fatalf("installation source = %v", err) + } +} + +func TestNativeSourcesCancellationAfterStagingNeverPublishes(t *testing.T) { + f := newSourceFixture(t) + ctx, cancel := context.WithCancel(f.ctx) + defer cancel() + call := func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + result, err := f.call(ctx, params) + cancel() + return result, err + } + published, err := f.editor.Apply(ctx, core.NewClient(), []core.SourceSettingsEdits{f.edit("child", "one")}, call, func() error { return nil }) + if !errors.Is(err, context.Canceled) || len(published) != 0 { + t.Fatalf("cancel outcome = %v, %v", published, err) + } + data, readErr := os.ReadFile(filepath.Join(f.root, "child/tool.json")) + if readErr != nil { + t.Fatal(readErr) + } + if !bytes.Contains(data, []byte(`"target":"two"`)) { + t.Fatal("canceled operation published a source") + } + assertSourceStagingRemoved(t, f) +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 85bd3a3a1b..ee783b4eba 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -186,6 +186,17 @@ type ToolchainLoader interface { Save(context.Context, toolchain.Snapshot, []toolchain.Edit) (toolchain.Snapshot, error) } +// ToolchainInspector validates an explicit installation with the runtime's +// resolver. Inspection reads facts and probes a version without saving a pin. +// ToolchainScopedLoader supplies machine registrations and optional project overrides. +type ToolchainScopedLoader interface { + LoadScope(context.Context, string) (toolchain.Snapshot, error) +} + +type ToolchainInspector interface { + Inspect(context.Context, toolchain.Snapshot, string, string) (core.ToolchainSelection, error) +} + // PluginSettingsLoader reads and publishes captured native sources off the UI thread. // Load translates the plugin's own text for the language; a save's readback keeps the // language its editor was loaded in. @@ -199,6 +210,11 @@ type PluginSettingsActionLoader interface { Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) } +// PluginSourceSettingsLoader publishes only explicitly saved native-source drafts. +type PluginSourceSettingsLoader interface { + SaveSources(context.Context, pluginservice.SettingsEditor, string, pluginsettings.SourceEditor, []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) +} + // CommandInstaller finds the commands installed plugins run from the user's system and // installs a missing one through the installer its plugin declares (commandInstallers[], // API-23). Every call runs off the window thread and returns once ctx ends. diff --git a/desktop/internal/settingswindow/installed_view.go b/desktop/internal/settingswindow/installed_view.go index 981219bbe6..9b5f81f280 100644 --- a/desktop/internal/settingswindow/installed_view.go +++ b/desktop/internal/settingswindow/installed_view.go @@ -803,7 +803,7 @@ func (w *window) openContributedPage(key, pluginID string) { return } parent := pageLanguages - if page.Kind == "buildSystem" { + if page.Kind == "buildSystem" || page.Kind == "compiler" { parent = pageBuild } w.selectSettingsPage(parent, key) diff --git a/desktop/internal/settingswindow/plugin_settings_model.go b/desktop/internal/settingswindow/plugin_settings_model.go index 7e5f2e0a3b..c675d06774 100644 --- a/desktop/internal/settingswindow/plugin_settings_model.go +++ b/desktop/internal/settingswindow/plugin_settings_model.go @@ -63,6 +63,7 @@ type pluginSettingsOp struct { } type pluginSettingsForm struct { + sources *sourceSettingsForm pageKey string stale bool staleReported bool @@ -129,7 +130,16 @@ func newPluginSettingsForm(loader PluginSettingsLoader) *pluginSettingsForm { // runOp is the save or the action. The stop button cancels its context through // cancelOp. func (p *pluginSettingsForm) runOp(parent context.Context) (pluginSettingsResult, error) { - ctx, cancel := context.WithTimeout(parent, 30*time.Second) + timeout := 30 * time.Second + p.mu.Lock() + for _, action := range p.op.editor.Snapshot.State.Actions { + if p.op.isAction && action.ID == p.op.action && action.SourceEditor != nil { + timeout = 120 * time.Second + break + } + } + p.mu.Unlock() + ctx, cancel := context.WithTimeout(parent, timeout) p.mu.Lock() op := p.op p.cancelOp = cancel @@ -163,6 +173,7 @@ func (p *pluginSettingsForm) stop() { } func (p *pluginSettingsForm) load(id string) { + p.sources = nil p.stale = false p.staleReported = false p.actionConfirmation = nil @@ -196,6 +207,9 @@ func (p *pluginSettingsForm) take() { p.running = false p.applyOp(result) } + if p.sources != nil { + p.sources.take() + } } // declare keeps the form's requests alive. The window declares every form it holds in @@ -210,10 +224,18 @@ func (p *pluginSettingsForm) declare(c ui.C) { if p.opKey != 0 { ui.Effect(c, p.opEffect, p.opKey) } + if p.sources != nil && p.sources.key != 0 { + ui.Effect(c.Part("source-editor"), p.sources.effect, p.sources.key) + } } func (p *pluginSettingsForm) applyOp(result pluginSettingsResult) { if result.action != nil { + if result.err == nil && result.action.Sources != nil { + if _, ok := p.loader.(PluginSourceSettingsLoader); ok { + p.sources = newSourceSettingsForm(p.loader, p.editor, result.action.Plan.ActionID, *result.action.Sources) + } + } p.acting = false p.failed = result.err p.actionComplete = result.action.Completed diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index b6784ef539..100ca53654 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -57,22 +57,30 @@ func (w *window) pluginSettingsPanel(c ui.C, id string) { p.load(id) } p.follow(language) + if p.sources != nil { + w.sourceSettingsPanel(c, p.sources) + return + } + page := w.dynamic.selected(w.dynamicPage) + compiler := page != nil && page.Kind == "compiler" ui.Column(c).FillWidth().Grow(1).Gap(10).Children(func() { - ui.Row(c).FillWidth().Height(1).Background(w.pal.line) - ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { - ui.Text(c, i18n.Shared(language, "desktop.pluginSettings.title")).FontSize(14).Weight(gfx.WeightSemibold).Color(w.pal.text) - ui.Spacer(c) - reloadLabel := i18n.Shared(language, "desktop.pluginSettings.reload") - if p.hasDraft() { - reloadLabel = i18n.Shared(language, "desktop.pluginSettings.discardReload") - } - if ui.Button(c, reloadLabel).Outline().Disabled(p.running).Clicked() { - p.load(id) - } - if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.save")).Disabled(p.running || p.stale || !p.loaded || !p.hasDraft()).Clicked() { - p.save() - } - }) + if !compiler { + ui.Row(c).FillWidth().Height(1).Background(w.pal.line) + ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.pluginSettings.title")).FontSize(14).Weight(gfx.WeightSemibold).Color(w.pal.text) + ui.Spacer(c) + reloadLabel := i18n.Shared(language, "desktop.pluginSettings.reload") + if p.hasDraft() { + reloadLabel = i18n.Shared(language, "desktop.pluginSettings.discardReload") + } + if ui.Button(c, reloadLabel).Outline().Disabled(p.running).Clicked() { + p.load(id) + } + if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.save")).Disabled(p.running || p.stale || !p.loaded || !p.hasDraft()).Clicked() { + p.save() + } + }) + } if p.stale { ui.Wrap(c, i18n.Shared(language, "desktop.pluginSettings.sourceChanged")).Color(w.pal.danger) } @@ -119,6 +127,15 @@ func (w *window) pluginSettingsPanel(c ui.C, id string) { if p.editor.Snapshot.State.PluginID != id || (!p.loaded && len(p.controls[p.scope]) == 0) { return } + if compiler { + w.pluginSettingActions(c) + for _, item := range p.layout { + if item.action { + w.pluginSettingActionRow(c, item.row) + } + } + return + } ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { if p.running || p.hasDraft() { // A scope change would drop the draft of the other scope's rows, so the list is diff --git a/desktop/internal/settingswindow/settings_surfaces.go b/desktop/internal/settingswindow/settings_surfaces.go index 4e77fa1ccf..7015f31b80 100644 --- a/desktop/internal/settingswindow/settings_surfaces.go +++ b/desktop/internal/settingswindow/settings_surfaces.go @@ -31,9 +31,10 @@ type surfacesKey struct { // surfacesJob is what one run works from. The window thread publishes a new one when the // key changes and the run takes it once, so nothing the run reads is written again. type surfacesJob struct { - key rowsKey - pages []core.SettingsPage - loaded bool + language i18n.Language + key rowsKey + pages []core.SettingsPage + loaded bool } // One page Effect owns catalog I/O and Core search. Rendering retains only the immutable @@ -82,7 +83,11 @@ func (s *settingsSurfaces) request(key rowsKey) { s.want = want s.requested = true s.jobMu.Lock() - s.job = surfacesJob{key: key, pages: s.pages, loaded: s.loaded} + language := i18n.English + if s.opts.Language != nil { + language = s.opts.Language() + } + s.job = surfacesJob{key: key, pages: s.pages, loaded: s.loaded, language: language} s.jobMu.Unlock() } @@ -99,6 +104,12 @@ func (s *settingsSurfaces) run(parent context.Context) (surfacesResult, error) { if !job.loaded && opts.SettingsPages != nil { var err error result.pages, err = opts.SettingsPages(ctx) + for index := range result.pages { + page := &result.pages[index] + if page.Kind == "compiler" { + page.Title = i18n.SharedFormat(job.language, "desktop.sourceSettings.compilerTitle", map[string]string{"compiler": page.Title}) + } + } if err != nil { result.err = err // log-exempt: 用户取消:快速搜索或关闭窗口取代旧请求。 @@ -135,7 +146,7 @@ func (s *settingsSurfaces) run(parent context.Context) (surfacesResult, error) { } for index, page := range result.pages { parent := pageLanguages - if page.Kind == "buildSystem" { + if page.Kind == "buildSystem" || page.Kind == "compiler" { parent = pageBuild } parentID := "static:" + strconv.Itoa(int(parent)) diff --git a/desktop/internal/settingswindow/source_settings_view.go b/desktop/internal/settingswindow/source_settings_view.go new file mode 100644 index 0000000000..fbd7a01fec --- /dev/null +++ b/desktop/internal/settingswindow/source_settings_view.go @@ -0,0 +1,442 @@ +package settingswindow + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +type sourceSettingControl struct { + input core.SourceSettingInput + base core.SourceSettingInput + inherited core.SourceSettingInput + choices []int + selected int +} + +type sourceSettingsRow struct { + group int + source int + field int +} + +// A source form owns only presentation drafts. The worker receives a captured +// native editor and sends all parsing, normalization and edit planning to Core. +type sourceSettingsForm struct { + owner pluginservice.SettingsEditor + action string + editor pluginsettings.SourceEditor + controls map[string]map[string]*sourceSettingControl + rows []sourceSettingsRow + list ui.ListState + add map[string]*int + available map[string][]int + pending map[string]map[string]core.SourceSettingInput + tableSources map[string]bool + layoutDirty bool + loader PluginSettingsLoader + effect *ui.EffectState[pluginsettings.SourceEditor, int] + key int + jobEdits []core.SourceSettingsEdits + jobEditor pluginsettings.SourceEditor + reload bool + busy, stale, saved bool + failed error +} + +func newSourceSettingsForm(loader PluginSettingsLoader, owner pluginservice.SettingsEditor, action string, editor pluginsettings.SourceEditor) *sourceSettingsForm { + p := &sourceSettingsForm{loader: loader, owner: owner, action: action} + p.effect = ui.NewEffect[pluginsettings.SourceEditor, int](func(parent context.Context) (pluginsettings.SourceEditor, error) { + ctx, cancel := context.WithTimeout(parent, 120*time.Second) + defer cancel() + if p.reload { + result, err := p.loader.(PluginSettingsActionLoader).Action(ctx, p.owner, p.action, false) + if err != nil { + return p.jobEditor, err + } + if result.Sources == nil { + return p.jobEditor, configfile.ErrConflict + } + return *result.Sources, nil + } + return p.loader.(PluginSourceSettingsLoader).SaveSources(ctx, p.owner, p.action, p.jobEditor, p.jobEdits) + }) + p.apply(editor) + return p +} + +func (p *sourceSettingsForm) apply(editor pluginsettings.SourceEditor) { + p.editor = editor + p.controls = make(map[string]map[string]*sourceSettingControl) + p.add = make(map[string]*int) + p.pending = make(map[string]map[string]core.SourceSettingInput) + p.tableSources = make(map[string]bool) + for _, section := range editor.State.Layout { + if editor.State.Snapshot.Groups[section.Group].Layout == "table" { + for _, index := range section.Sources { + p.tableSources[editor.State.Snapshot.Sources[index].ID] = true + } + } + } + for _, source := range editor.State.Snapshot.Sources { + fields := make(map[string]*sourceSettingControl) + for _, field := range source.Fields { + input := editor.State.Inputs[source.ID][field.ID] + control := &sourceSettingControl{input: input, base: input, inherited: editor.State.InheritedInputs[source.ID][field.ID]} + control.choices = make([]int, len(field.Options)+1) + for index := range control.choices { + control.choices[index] = index + if index > 0 && field.Options[index-1].Value == input.Choice && !input.Inherit { + control.selected = index + } + } + fields[field.ID] = control + } + p.controls[source.ID] = fields + } + p.stale, p.failed = false, nil + p.layout() +} + +func (p *sourceSettingsForm) layout() { + p.rows = p.rows[:0] + p.available = make(map[string][]int) + p.layoutDirty = false + for _, section := range p.editor.State.Layout { + groupIndex := section.Group + group := p.editor.State.Snapshot.Groups[groupIndex] + p.rows = append(p.rows, sourceSettingsRow{group: groupIndex, source: -1, field: -1}) + if p.add[group.ID] == nil { + p.add[group.ID] = new(int) + } + for _, sourceIndex := range section.Sources { + source := p.editor.State.Snapshot.Sources[sourceIndex] + if group.Layout == "table" { + visible := false + for _, control := range p.controls[source.ID] { + visible = visible || !control.input.Inherit + } + if visible { + p.rows = append(p.rows, sourceSettingsRow{group: groupIndex, source: sourceIndex, field: -1}) + } + if !visible && source.Writable { + p.available[group.ID] = append(p.available[group.ID], sourceIndex) + } + } else { + for fieldIndex := range source.Fields { + p.rows = append(p.rows, sourceSettingsRow{group: groupIndex, source: sourceIndex, field: fieldIndex}) + } + } + } + if available := p.available[group.ID]; len(available) > 0 { + selected := p.add[group.ID] + valid := false + for _, index := range available { + valid = valid || index == *selected + } + if !valid { + *selected = available[0] + } + } + } +} + +func (p *sourceSettingsForm) edits() []core.SourceSettingsEdits { + var edits []core.SourceSettingsEdits + for id, inputs := range p.pending { + values := make(map[string]core.SourceSettingInput, len(inputs)) + for field, input := range inputs { + values[field] = input + } + edits = append(edits, core.SourceSettingsEdits{SourceID: id, Values: values}) + } + return edits +} + +func (p *sourceSettingsForm) changed(source, field string) { + control := p.controls[source][field] + if control.input == control.base { + delete(p.pending[source], field) + if len(p.pending[source]) == 0 { + delete(p.pending, source) + } + } else { + if p.pending[source] == nil { + p.pending[source] = make(map[string]core.SourceSettingInput) + } + p.pending[source][field] = control.input + } + p.saved = false + if p.tableSources[source] { + p.layoutDirty = true + } +} + +func (p *sourceSettingsForm) start(reload bool) { + if p.busy { + return + } + p.jobEditor, p.jobEdits = p.editor, p.edits() + p.reload, p.busy, p.saved, p.failed = reload, true, false, nil + p.key++ +} + +func (p *sourceSettingsForm) take() { + if editor, err, ok := p.effect.Take(); ok { + p.busy, p.failed = false, err + if err == nil { + p.apply(editor) + p.saved = !p.reload + } else if errors.Is(err, pluginsettings.ErrSourcesCommitted) || errors.Is(err, configfile.ErrConflict) { + p.stale = true + } + } + if p.layoutDirty { + p.layout() + } +} + +func (w *window) sourceSettingsPanel(c ui.C, p *sourceSettingsForm) { + language := w.marketLanguage() + ui.Column(c).FillWidth().Grow(1).Gap(10).Children(func() { + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + ui.Text(c, p.editor.State.Snapshot.Title).FontSize(14).Weight(gfx.WeightSemibold).Color(w.pal.text) + ui.Spacer(c) + if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.reload")).Outline().Disabled(p.busy).Clicked() { + p.start(true) + } + if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.save")).Disabled(p.busy || p.stale || len(p.pending) == 0).Clicked() { + p.start(false) + } + if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.close")).Outline().Disabled(p.busy).Clicked() { + w.pluginSettings.sources = nil + } + }) + if p.busy { + ui.Text(c, i18n.Shared(language, "native.loading")).FontSize(12).Color(w.pal.muted) + } + if p.failed != nil { + message := i18n.Shared(language, "desktop.pluginSettings.failed") + if p.stale { + message = i18n.Shared(language, "desktop.pluginSettings.sourceChanged") + } + ui.Wrap(c, message).FontSize(12).Color(w.pal.danger) + } + if p.saved { + ui.Text(c, i18n.Shared(language, "desktop.pluginSettings.saved")).FontSize(12).Color(w.pal.muted) + } + ui.List(c, &p.list, len(p.rows), func(row ui.ListRow) { + item := p.rows[row.Index] + group := p.editor.State.Snapshot.Groups[item.group] + row.Element.FillWidth().Children(func() { + if item.source < 0 { + w.sourceSettingsGroup(row.C, p, group) + return + } + source := p.editor.State.Snapshot.Sources[item.source] + if item.field >= 0 { + field := source.Fields[item.field] + ui.Column(row.C).FillWidth().Gap(5).PadY(6).Children(func() { + ui.Row(row.C).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if field.Kind == "boolean" { + w.sourceSettingsControl(row.C, p, source, field) + } else { + ui.Text(row.C, field.Title).FontSize(12).Weight(gfx.WeightSemibold).Color(w.pal.text) + } + if field.Description != "" { + w.infoButton(row.C, field.Description) + } + ui.Spacer(row.C) + if item.field == 0 { + ui.Text(row.C, source.Path).FontSize(11).Color(w.pal.muted).Ellipsis() + } + }) + if field.Kind != "boolean" { + w.sourceSettingsControl(row.C, p, source, field) + } + if field.EffectiveSource != "" { + ui.Text(row.C, field.EffectiveSource).FontSize(11).Color(w.pal.muted) + } + if field.Kind != "enum" && !controlInherits(p, source.ID, field.ID) && ui.Button(row.C, i18n.Shared(language, "desktop.pluginSettings.reset")).Link().Disabled(p.busy || p.stale || !source.Writable || controlInherits(p, source.ID, field.ID)).Clicked() { + control := p.controls[source.ID][field.ID] + control.input = control.inherited + p.changed(source.ID, field.ID) + } + }) + } else { + ui.Row(row.C).FillWidth().MinHeight(36).Items(ui.Center).Gap(8).Children(func() { + ui.Text(row.C, source.Title).FontSize(12).Color(w.pal.text).Grow(1).Ellipsis() + w.infoButton(row.C, source.Path) + for _, field := range source.Fields { + w.sourceSettingsControl(row.C.Key(field.ID), p, source, field) + } + if ui.Button(row.C, i18n.Shared(language, "desktop.sourceSettings.remove")).Outline().Disabled(p.busy || !source.Writable).Clicked() { + for id, control := range p.controls[source.ID] { + control.input = control.inherited + control.selected = 0 + p.changed(source.ID, id) + } + } + }) + } + }) + }).Scrollbars().FillWidth().Grow(1).MinHeight(settingsListMinHeight).Label(p.editor.State.Snapshot.Title) + }) +} + +func (w *window) sourceSettingsGroup(c ui.C, p *sourceSettingsForm, group core.SourceSettingsGroup) { + language := w.marketLanguage() + ui.Column(c).FillWidth().Gap(6).PadY(8).Children(func() { + ui.Text(c, group.Title).FontSize(13).Weight(gfx.WeightSemibold).Color(w.pal.text) + if group.Layout != "table" { + return + } + available := p.available[group.ID] + ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { + if len(available) > 0 { + selected := p.add[group.ID] + label := func(index int) string { return p.editor.State.Snapshot.Sources[index].Title } + ui.Select(c, selected, available, label).Width(230).Label(group.Title).Disabled(p.busy) + if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.add")).Outline().Disabled(p.busy).Clicked() { + source := p.editor.State.Snapshot.Sources[*selected] + for _, field := range source.Fields { + control := p.controls[source.ID][field.ID] + control.input.Inherit = false + for index, option := range field.Options { + if option.Value == control.input.Choice { + control.selected = index + 1 + } + } + p.changed(source.ID, field.ID) + } + } + } else { + ui.Text(c, i18n.Shared(language, "desktop.sourceSettings.allEntriesShown")).FontSize(11).Color(w.pal.muted) + } + }) + if group.RowTitle != "" { + ui.Text(c, group.RowTitle).FontSize(11).Color(w.pal.muted) + } + }) +} + +func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source core.SettingsSource, field core.SourceSettingField) { + language := w.marketLanguage() + control := p.controls[source.ID][field.ID] + disabled := p.busy || p.stale || !source.Writable + accessibleTitle := field.Title + if p.tableSources[source.ID] { + accessibleTitle = source.Title + " " + field.Title + } + switch field.Kind { + case "enum": + label := func(index int) string { + if index > 0 { + return field.Options[index-1].Title + } + value := control.inherited.Choice + if value == "" { + value = i18n.Shared(language, "desktop.sourceSettings.noValue") + } + for _, option := range field.Options { + if option.Value == value { + value = option.Title + break + } + } + return i18n.SharedFormat(language, "desktop.sourceSettings.inherit", map[string]string{"value": value}) + } + if disabled { + w.readOnlyField(c, field.Title, label(control.selected)) + return + } + if ui.Select(c, &control.selected, control.choices, label).Width(190).Label(accessibleTitle).Changed() { + control.input.Inherit = control.selected == 0 + if control.selected > 0 { + control.input.Choice = field.Options[control.selected-1].Value + } + p.changed(source.ID, field.ID) + } + case "boolean": + if ui.Checkbox(c, &control.input.On, field.Title).Disabled(disabled).Changed() { + control.input.Inherit = false + p.changed(source.ID, field.ID) + } + default: + if disabled { + w.readOnlyField(c, field.Title, control.input.Text) + } else if field.Kind == "stringList" || field.Kind == "fileList" { + if ui.TextArea(c, &control.input.Text, field.Title, "").FillWidth().Height(100).Changed() { + control.input.Inherit = false + p.changed(source.ID, field.ID) + } + } else { + if ui.TextField(c, &control.input.Text, field.Title, "").FillWidth().Height(30).Changed() { + control.input.Inherit = false + p.changed(source.ID, field.ID) + } + } + if field.Kind == "fileList" && ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.browse")).Outline().Disabled(disabled).Clicked() { + c.After(func() { + paths, err := app.OpenFiles(app.OpenFileOptions{Title: field.Title}) + // log-exempt: 用户取消:文件选择器取消不修改依赖草稿。 + if errors.Is(err, app.ErrCanceled) { + return + } + if err != nil { + p.failed = err + if w.ctrl.opts.MarketplaceError != nil { + w.ctrl.opts.MarketplaceError(err) + } + return + } + if w.pluginSettings.sources != p || p.controls[source.ID][field.ID] != control { + return + } + if len(paths) > 0 { + if control.input.Text != "" && !strings.HasSuffix(control.input.Text, "\n") { + control.input.Text += "\n" + } + control.input.Text += strings.Join(paths, "\n") + control.input.Inherit = false + p.changed(source.ID, field.ID) + } + }) + } + } + if display, ok := p.editor.State.EffectiveDisplays[source.ID][field.ID]; ok { + value := display.Text + switch display.Kind { + case "unknown": + value = i18n.Shared(language, "desktop.sourceSettings.noValue") + case "boolean": + value = i18n.Shared(language, "native.disabled.variant2") + if display.On { + value = i18n.Shared(language, "native.enabled.variant2") + } + case "list": + value = i18n.SharedFormat(language, "desktop.sourceSettings.fileCount", map[string]string{"count": strconv.Itoa(display.Count)}) + } + hint := i18n.SharedFormat(language, "desktop.sourceSettings.effective", map[string]string{"value": value}) + if display.Inherited { + hint = i18n.SharedFormat(language, "desktop.sourceSettings.inherit", map[string]string{"value": value}) + } + ui.Text(c, hint).FontSize(11).Color(w.pal.muted).Ellipsis() + } + +} + +func controlInherits(p *sourceSettingsForm, source, field string) bool { + return p.controls[source][field].input.Inherit +} diff --git a/desktop/internal/settingswindow/source_settings_view_test.go b/desktop/internal/settingswindow/source_settings_view_test.go new file mode 100644 index 0000000000..77f6686c8e --- /dev/null +++ b/desktop/internal/settingswindow/source_settings_view_test.go @@ -0,0 +1,163 @@ +package settingswindow + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/app" +) + +type nativeFormFixture struct { + reads atomic.Int32 + settingsFormSource + native pluginsettings.SourceEditor + saves chan []core.SourceSettingsEdits + failure error +} + +func (s *nativeFormFixture) Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) { + s.reads.Add(1) + return pluginservice.SettingsActionResult{Plan: core.PluginSettingsActionPlan{Kind: "invoke", ActionID: "compiler", SourceEditor: true}, Sources: &s.native}, nil +} +func (s *nativeFormFixture) SaveSources(ctx context.Context, _ pluginservice.SettingsEditor, _ string, editor pluginsettings.SourceEditor, edits []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) { + s.saves <- edits + return editor, s.failure +} +func nativeFormSource(t *testing.T) *nativeFormFixture { + t.Helper() + manifest, err := os.ReadFile(contractfixture.Path("fixtures/settings/source-editor.plugin.json")) + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "child"), 0700); err != nil { + t.Fatal(err) + } + contents := []byte(`{"target":"two"}`) + if err := os.WriteFile(filepath.Join(root, "child/tool.json"), contents, 0600); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(contractfixture.CoreFixture("plugins/settings-sources.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Snapshot core.SourceSettingsSnapshot `json:"snapshot"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + fixture.Snapshot.Sources[1].Revision = fmt.Sprintf("sha256:%x", sha256.Sum256(contents)) + raw, err := json.Marshal(fixture.Snapshot) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + state, err := core.NewClient().ReadSourceSettings(ctx, raw) + if err != nil { + t.Fatal(err) + } + native, err := pluginsettings.CaptureSources(ctx, root, state, nil) + if err != nil { + t.Fatal(err) + } + return &nativeFormFixture{settingsFormSource: settingsFormSource{store: pluginsettings.New(core.NewClient(), t.TempDir()), manifest: manifest, workspace: root}, native: native, saves: make(chan []core.SourceSettingsEdits, 2)} +} +func nativeFormWindow(t *testing.T, source *nativeFormFixture, language i18n.Language, theme string) *window { + t.Helper() + fetch := func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: []core.MarketplacePlugin{{ID: "dev.lithe.test.source-settings", Name: "Fictional Compiler", LatestVersion: "1.0.0"}}}}, nil + } + w := newWindow(NewController(Options{Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, PluginSettings: source, + SettingsNavigation: core.NewClient().SettingsNavigation, + SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { + return core.NewClient().SettingsPages(ctx, []core.SettingsContribution{{Manifest: source.manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.test.source-settings", Version: "1.0.0"}, Enabled: true}}) + }, Marketplace: fetch, MarketplaceInstalled: fetch, PluginState: func(string) PluginState { return PluginState{Installed: true, Enabled: true, Version: "1.0.0"} }, InstalledPlugins: func() []PluginFacts { + return []PluginFacts{{ID: "dev.lithe.test.source-settings", Name: "Fictional Compiler", Version: "1.0.0", Settings: 1}} + }}), Values{Theme: theme, Language: language.Code()}) + w.sess.page = pagePlugins + w.installed.tab = installedSettings + return w +} +func openNativeForm(t *testing.T, w *window, d *windowDriver) { + t.Helper() + d.until("source action", func() bool { return w.pluginSettings.loaded }) + d.click("Compiler settings") + d.until("native form", func() bool { return w.pluginSettings.sources != nil }) +} +func TestNativeSettingsFormKeepsInheritanceAndSavesOnlyAnExplicitModuleEdit(t *testing.T) { + source := nativeFormSource(t) + source.failure = configfile.ErrConflict + w := nativeFormWindow(t, source, i18n.English, "dark") + d := openWindow(t, w, func(config *app.Config) { config.Height = 1100 }) + openNativeForm(t, w, d) + p := w.pluginSettings.sources + if len(p.pending) != 0 || !d.hit(i18n.Shared(i18n.English, "desktop.pluginSettings.save")).Disabled { + t.Fatal("displaying inherited values created a draft") + } + select { + case <-source.saves: + t.Fatal("opening the form wrote a source") + default: + } + // Target is also the first form control; choose the module's last matching + // accessible control, whose current explicit value is Version 2. + d.click("Child module Target") + d.click("Version 1") + d.pump() + if len(p.pending) != 1 || len(p.pending["child"]) != 1 || p.pending["child"]["target"].Choice != "one" { + t.Fatalf("module draft: %+v", p.pending) + } + d.click(i18n.Shared(i18n.English, "desktop.pluginSettings.save")) + d.until("native conflict", func() bool { return p.stale }) + select { + case edits := <-source.saves: + if len(edits) != 1 || edits[0].SourceID != "child" || len(edits[0].Values) != 1 { + t.Fatalf("save changed unrelated sources: %+v", edits) + } + default: + t.Fatal("explicit save did not reach the native adapter") + } + if p.controls["child"]["target"].input.Choice != "one" { + t.Fatal("a conflict discarded the user's draft") + } + data, err := os.ReadFile(filepath.Join(source.workspace, "child/tool.json")) + if err != nil { + t.Fatal(err) + } + if string(data) != `{"target":"two"}` { + t.Fatal("a rejected draft changed its native file") + } +} + +func TestNativeCompilerPageRequiresAnExplicitRead(t *testing.T) { + source := nativeFormSource(t) + w := nativeFormWindow(t, source, i18n.English, "dark") + d := openWindow(t, w) + d.until("compiler page", func() bool { return len(w.dynamic.pages) == 1 }) + w.selectSettingsPage(pageBuild, "compiler:fictional") + d.until("compiler action", func() bool { return w.pluginSettings.pageKey == w.dynamicPage && w.pluginSettings.loaded }) + if source.reads.Load() != 0 { + t.Fatal("opening a compiler page executed the project tool") + } + d.click("Compiler settings") + d.until("native compiler form", func() bool { return w.pluginSettings.sources != nil }) + if source.reads.Load() != 1 { + t.Fatal("the explicit read did not query exactly once") + } +} diff --git a/desktop/internal/settingswindow/source_settings_visual_test.go b/desktop/internal/settingswindow/source_settings_visual_test.go new file mode 100644 index 0000000000..25d903e58e --- /dev/null +++ b/desktop/internal/settingswindow/source_settings_visual_test.go @@ -0,0 +1,48 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/headless" + "os" + "path/filepath" + "testing" +) + +func TestVisualNativeSettingsForm(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"-"+theme, func(t *testing.T) { + source := nativeFormSource(t) + w := nativeFormWindow(t, source, language, theme) + config := w.config() + config.Width, config.Height = 1120, 900 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.until("compiler page", func() bool { return len(w.dynamic.pages) == 1 }) + w.selectSettingsPage(pageBuild, "compiler:fictional") + d.until("compiler settings action", func() bool { + return w.pluginSettings.pageKey == w.dynamicPage && w.pluginSettings.loaded && len(w.pluginSettings.layout) > 0 + }) + d.click("Compiler settings") + d.until("native compiler form", func() bool { return w.pluginSettings.sources != nil }) + d.pump() + if err := session.Screenshot(filepath.Join(out, "native-settings-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/settingswindow/toolchains_view.go b/desktop/internal/settingswindow/toolchains_view.go index 943852017b..bdeb8214d3 100644 --- a/desktop/internal/settingswindow/toolchains_view.go +++ b/desktop/internal/settingswindow/toolchains_view.go @@ -4,11 +4,13 @@ import ( "context" "errors" "strings" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/ui" ) @@ -17,9 +19,18 @@ import ( // before it, so a result of a replaced request never reaches the draft, and the window // takes what finished with take at the start of a paint. type toolchainState struct { - loader ToolchainLoader - loadEffect *ui.EffectState[toolchain.Snapshot, int] - saveEffect *ui.EffectState[toolchain.Snapshot, int] + loader ToolchainLoader + loadEffect *ui.EffectState[toolchain.Snapshot, int] + saveEffect *ui.EffectState[toolchain.Snapshot, int] + inspectEffect *ui.EffectState[core.ToolchainSelection, int] + inspectKey int + inspectSnapshot toolchain.Snapshot + inspectTool, inspectHome string + inspecting bool + inputs map[string]*string + custom map[string]core.ToolchainPin + scope, loadScope string + registrations map[string]bool // loadKey and saveKey name the requests; zero means none was made. The save's inputs // are written before its key changes and are read by that one run only. loadKey, saveKey int @@ -41,19 +52,45 @@ type toolchainState struct { } func newToolchainState(loader ToolchainLoader) *toolchainState { - t := &toolchainState{loader: loader, draft: make(map[string]string), picks: make(map[string]*string)} + t := &toolchainState{loader: loader, scope: "project", draft: make(map[string]string), picks: make(map[string]*string), inputs: make(map[string]*string), custom: make(map[string]core.ToolchainPin), registrations: make(map[string]bool)} + if _, ok := loader.(ToolchainScopedLoader); ok { + t.scope = "global" + } if loader != nil { t.loadEffect = ui.NewEffect[toolchain.Snapshot, int](func(ctx context.Context) (toolchain.Snapshot, error) { + if scoped, ok := loader.(ToolchainScopedLoader); ok { + return scoped.LoadScope(ctx, t.loadScope) + } return loader.Load(ctx) }) t.saveEffect = ui.NewEffect[toolchain.Snapshot, int](func(ctx context.Context) (toolchain.Snapshot, error) { return loader.Save(ctx, t.saveSnapshot, t.saveEdits) }) } + if inspector, ok := loader.(ToolchainInspector); ok { + t.inspectEffect = ui.NewEffect[core.ToolchainSelection, int](func(ctx context.Context) (core.ToolchainSelection, error) { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + return inspector.Inspect(ctx, t.inspectSnapshot, t.inspectTool, t.inspectHome) + }) + } return t } +func (t *toolchainState) beginInspect(tool, home string) { + if t.inspectEffect == nil || t.loading || t.saving || t.inspecting || !t.loaded || home == "" { + return + } + t.inspectSnapshot, t.inspectTool, t.inspectHome = t.snapshot, tool, home + t.inspectKey++ + t.inspecting, t.saved, t.failed = true, false, nil +} + func toolchainFailureMessage(language i18n.Language, err error) string { + var unavailable *toolchain.UnavailableError + if errors.As(err, &unavailable) { + return i18n.Shared(language, "desktop.toolchains.invalidDirectory") + } if errors.Is(err, toolchain.ErrPinCommitted) { return i18n.Shared(language, "desktop.toolchains.reloadAfterSave") } @@ -70,9 +107,10 @@ func toolchainFailureMessage(language i18n.Language, err error) string { // beginLoad reads the project's toolchains off the window thread. func (t *toolchainState) beginLoad() { - if t.loader == nil || t.loading || t.saving { + if t.loader == nil || t.loading || t.saving || t.inspecting { return } + t.loadScope = t.scope t.loadKey++ t.loading = true t.failed = nil @@ -81,7 +119,7 @@ func (t *toolchainState) beginLoad() { // beginSave writes the draft's changed pins. Every edit goes through the same // Core-validated document merge; a conflict keeps the draft. func (t *toolchainState) beginSave() { - if t.loader == nil || !t.loaded || t.loading || t.saving || !t.hasDraft() { + if t.loader == nil || !t.loaded || t.loading || t.saving || t.inspecting || !t.hasDraft() { return } edits := t.edits() @@ -105,6 +143,46 @@ func (t *toolchainState) take() { if snapshot, err, ok := t.saveEffect.Take(); ok { t.finish(snapshot, err, true) } + if t.inspectEffect != nil { + if selection, err, ok := t.inspectEffect.Take(); ok { + t.inspecting, t.failed = false, err + if err == nil && selection.Home != nil { + t.acceptInspection(t.inspectTool, selection) + } + } + } +} + +func (t *toolchainState) acceptInspection(id string, selection core.ToolchainSelection) { + if selection.Home == nil { + return + } + pin := core.ToolchainPin{Home: *selection.Home, Version: selection.Version, Provider: "host:manual"} + if t.snapshot.Global { + for index := range t.snapshot.Tools { + tool := &t.snapshot.Tools[index] + if tool.ID != id { + continue + } + registered, installed := false, false + for _, home := range tool.CustomHomes { + registered = registered || home == pin.Home + } + if !registered { + tool.CustomHomes = append(tool.CustomHomes, pin.Home) + t.registrations[id] = true + } + for _, installation := range tool.Installations { + installed = installed || installation.Home == pin.Home + } + if !installed { + tool.Installations = append(tool.Installations, core.ToolchainInstallation{Home: pin.Home, Version: pin.Version, Provider: pin.Provider}) + } + } + } else { + t.custom[id] = pin + } + t.choose(id, pin.Home) } func (t *toolchainState) finish(snapshot toolchain.Snapshot, err error, saved bool) { @@ -132,6 +210,9 @@ func (t *toolchainState) declare(c ui.C) { if t.saveKey != 0 { ui.Effect(c, t.saveEffect, t.saveKey) } + if t.inspectKey != 0 { + ui.Effect(c, t.inspectEffect, t.inspectKey) + } } func (t *toolchainState) apply(snapshot toolchain.Snapshot, saved bool) { @@ -139,7 +220,10 @@ func (t *toolchainState) apply(snapshot toolchain.Snapshot, saved bool) { t.loaded = true t.saved = saved t.failed = nil - if !saved { + { + t.custom = make(map[string]core.ToolchainPin) + t.registrations = make(map[string]bool) + t.inputs = make(map[string]*string) t.draft = make(map[string]string, len(snapshot.Tools)) for _, tool := range snapshot.Tools { if tool.Pin != nil { @@ -168,6 +252,9 @@ func (t *toolchainState) resetDrafts() { } func (t *toolchainState) hasDraft() bool { + if len(t.registrations) != 0 { + return true + } for _, tool := range t.snapshot.Tools { current := "" if tool.Pin != nil { @@ -190,13 +277,17 @@ func (t *toolchainState) edits() []toolchain.Edit { current = tool.Pin.Home } wanted := t.draft[tool.ID] - if wanted == current { + if wanted == current && !t.registrations[tool.ID] { continue } if wanted == "" { edits = append(edits, toolchain.Edit{Tool: tool.ID}) continue } + if pin, ok := t.custom[tool.ID]; ok && pin.Home == wanted { + edits = append(edits, toolchain.Edit{Tool: tool.ID, Pin: &pin}) + continue + } for _, installation := range tool.Installations { if installation.Home != wanted || installation.Version == "" { continue @@ -234,21 +325,36 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { } w.card(c, i18n.Shared(language, "desktop.toolchains.title"), i18n.Shared(language, "desktop.toolchains.description"), func() { ui.Column(c).FillWidth().Gap(8).Children(func() { - ui.Wrap(c, i18n.Shared(language, "desktop.toolchains.chooseHelp")).FontSize(12).Color(w.pal.muted) + if _, ok := t.loader.(ToolchainScopedLoader); ok { + previous := t.scope + ui.Row(c.Part("scope")).FillWidth().Gap(16).Children(func() { + disabled := t.loading || t.saving || t.inspecting || t.hasDraft() + w.radio(c.Part("global"), &t.scope, "global", i18n.Shared(language, "desktop.toolchains.global"), disabled) + w.radio(c.Part("project"), &t.scope, "project", i18n.Shared(language, "desktop.toolchains.project"), disabled) + }) + if t.scope != previous { + t.beginLoad() + } + } + help := i18n.Shared(language, "desktop.toolchains.chooseHelp") + if t.scope == "global" { + help = i18n.Shared(language, "desktop.toolchains.globalHelp") + } + ui.Wrap(c, help).FontSize(12).Color(w.pal.muted) ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reload")).Outline().Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reload")).Outline().Disabled(t.loading || t.saving || t.inspecting).Clicked() { t.beginLoad() } - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reset")).Outline().Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reset")).Outline().Disabled(t.loading || t.saving || t.inspecting).Clicked() { t.resetDrafts() } ui.Spacer(c) - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.save")).Disabled(!t.loaded || !t.hasDraft() || t.saving || t.loading).Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.save")).Disabled(!t.loaded || !t.hasDraft() || t.saving || t.loading || t.inspecting).Clicked() { t.beginSave() } }) switch { - case t.loading: + case t.loading || t.inspecting: ui.Text(c, i18n.Shared(language, "desktop.toolchains.loading")).FontSize(12).Color(w.pal.muted) case t.saving: ui.Text(c, i18n.Shared(language, "desktop.toolchains.saving")).FontSize(12).Color(w.pal.muted) @@ -259,7 +365,7 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { } }) }) - if t.snapshot.Root == "" && t.loaded { + if t.snapshot.Root == "" && !t.snapshot.Global && t.loaded { w.card(c.Part("no-project"), i18n.Shared(language, "desktop.toolchains.title"), "", func() { ui.Text(c, i18n.Shared(language, "desktop.toolchains.noProject")).FontSize(12).Color(w.pal.muted) }) @@ -280,6 +386,7 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.Tool) { t := w.toolchains + busy := t.loading || t.saving || t.inspecting ui.Column(c).FillWidth().Gap(6).Children(func() { ui.Text(c, tool.PluginID).FontSize(11).Color(w.pal.muted) switch { @@ -304,7 +411,7 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To } else { automatic = i18n.Shared(language, "desktop.toolchains.noInstallations") } - w.radio(c.Part("automatic"), pick, "", i18n.SharedFormat(language, "desktop.toolchains.automatic", map[string]string{"value": automatic}), false) + w.radio(c.Part("automatic"), pick, "", i18n.SharedFormat(language, "desktop.toolchains.automatic", map[string]string{"value": automatic}), busy) pinShown := false for _, installation := range tool.Installations { home := installation.Home @@ -314,15 +421,42 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To label := i18n.SharedFormat(language, "desktop.toolchains.installation", map[string]string{ "home": home, "version": installation.Version, "provider": installation.Provider, }) - w.radio(c.Key(home), pick, home, label, installation.Version == "") + w.radio(c.Key(home), pick, home, label, installation.Version == "" || busy) } if tool.Pin != nil && !pinShown { label := i18n.SharedFormat(language, "desktop.toolchains.pinSource", map[string]string{"directory": tool.PinSource}) - w.radio(c.Part("pin"), pick, tool.Pin.Home, tool.Pin.Home+" · "+label, false) + w.radio(c.Part("pin"), pick, tool.Pin.Home, tool.Pin.Home+" · "+label, busy) + } + if pin, ok := t.custom[tool.ID]; ok { + label := i18n.SharedFormat(language, "desktop.toolchains.installation", map[string]string{"home": pin.Home, "version": pin.Version, "provider": pin.Provider}) + w.radio(c.Part("custom"), pick, pin.Home, label, t.inspecting || t.saving) } if *pick != t.draft[tool.ID] { t.choose(tool.ID, *pick) } + if t.inspectEffect != nil { + input := t.inputs[tool.ID] + if input == nil { + input = new(string) + t.inputs[tool.ID] = input + } + label := i18n.Shared(language, "desktop.toolchains.directory") + busy := t.loading || t.saving || t.inspecting + ui.Row(c.Part("manual")).FillWidth().Gap(8).Items(ui.Center).Children(func() { + if busy { + w.readOnlyField(c, label, *input) + } else { + ui.TextField(c, input, label, "").Grow(1).MinWidth(0).Height(30) + } + w.infoButton(c, i18n.Shared(language, "desktop.toolchains.directoryHelp")) + if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.browse")).Outline().Disabled(busy).Clicked() { + c.After(func() { w.pickToolchainDirectory(tool.ID, input, label) }) + } + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.useDirectory")).Outline().Disabled(busy || *input == "").Clicked() { + t.beginInspect(tool.ID, *input) + } + }) + } for _, shell := range tool.Shell { version := shell.Variable if shell.Version != nil { @@ -340,6 +474,25 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To }) } +func (w *window) pickToolchainDirectory(tool string, input *string, title string) { + path, err := app.OpenDirectory(app.OpenDirectoryOptions{Title: title}) + // log-exempt: 用户取消:关闭目录选择器不修改工具链草稿。 + if errors.Is(err, app.ErrCanceled) { + return + } + if err != nil { + w.toolchains.failed = err + if w.ctrl.opts.MarketplaceError != nil { + w.ctrl.opts.MarketplaceError(err) + } + return + } + if path != "" && w.toolchains.inputs[tool] == input { + *input = path + w.toolchains.beginInspect(tool, path) + } +} + func toolchainReason(tool toolchain.Tool) string { for _, trace := range tool.Trace { if trace.Reason != nil && trace.Reason.Code != "" { diff --git a/desktop/internal/settingswindow/toolchains_view_test.go b/desktop/internal/settingswindow/toolchains_view_test.go index 018855e2b8..6394b159eb 100644 --- a/desktop/internal/settingswindow/toolchains_view_test.go +++ b/desktop/internal/settingswindow/toolchains_view_test.go @@ -12,10 +12,15 @@ import ( ) type fakeToolchainLoader struct { - snapshot toolchain.Snapshot - loaded chan struct{} - saved chan []toolchain.Edit - saveErr error + snapshot toolchain.Snapshot + loaded chan struct{} + saved chan []toolchain.Edit + saveErr error + inspectErr error +} + +func (f *fakeToolchainLoader) Inspect(_ context.Context, _ toolchain.Snapshot, _ string, home string) (core.ToolchainSelection, error) { + return core.ToolchainSelection{Home: &home, Executable: home + "/bin/compiler", Version: "9.1"}, f.inspectErr } func (f *fakeToolchainLoader) Load(context.Context) (toolchain.Snapshot, error) { @@ -119,6 +124,78 @@ func TestToolchainDraftSavesOnlyExplicitChanges(t *testing.T) { } } +func TestToolchainManualDirectoryIsValidatedBeforeAnExplicitSave(t *testing.T) { + loader := &fakeToolchainLoader{snapshot: fixtureSnapshot(), saved: make(chan []toolchain.Edit, 1)} + w, d := toolchainWindow(t, loader) + d.click("Installation directory") + d.typeText("/fixture/custom") + d.click("Use directory") + d.until("the checked directory", func() bool { return w.toolchains.draft["dev.example:compiler"] == "/fixture/custom" }) + select { + case edits := <-loader.saved: + t.Fatalf("validating a directory wrote %+v", edits) + default: + } + d.click(i18n.Shared(i18n.English, "desktop.toolchains.save")) + d.until("the manual directory to save", func() bool { return w.toolchains.saved }) + select { + case edits := <-loader.saved: + if len(edits) != 1 || edits[0].Pin == nil || edits[0].Pin.Home != "/fixture/custom" || edits[0].Pin.Version != "9.1" { + t.Fatalf("manual directory pin = %+v", edits) + } + default: + t.Fatal("manual directory was not saved") + } +} + +type scopedToolchainLoader struct{ fakeToolchainLoader } + +func (f *scopedToolchainLoader) LoadScope(ctx context.Context, scope string) (toolchain.Snapshot, error) { + result, err := f.Load(ctx) + result.Global = scope == "global" + return result, err +} + +func TestGlobalToolchainsKeepMultipleManualSDKsWithoutAProject(t *testing.T) { + fixture := fixtureSnapshot() + fixture.Root = "" + loader := &scopedToolchainLoader{fakeToolchainLoader{snapshot: fixture, saved: make(chan []toolchain.Edit, 1)}} + w := newWindow(NewController(Options{Toolchains: loader}), Values{}) + w.sess.page = pageBuild + d := openWindow(t, w) + d.until("global toolchains without a project", func() bool { return w.toolchains.loaded }) + if !w.toolchains.snapshot.Global || !d.text("Global defaults") || !d.text("Compiler") { + t.Fatal("the toolchain page requires a project or does not default to global") + } + for _, home := range []string{"/fixture/sdk8", "/fixture/sdk21"} { + d.click("Installation directory") + d.typeText(home) + d.click("Use directory") + d.until("the checked SDK", func() bool { return w.toolchains.draft["dev.example:compiler"] == home }) + // Clear the input for the next native text entry without changing its draft. + *w.toolchains.inputs["dev.example:compiler"] = "" + } + if got := w.toolchains.snapshot.Tools[0].CustomHomes; !slices.Equal(got, []string{"/fixture/sdk8", "/fixture/sdk21"}) { + t.Fatalf("manual SDK registrations = %v", got) + } + if !d.hit("Current project").Disabled { + t.Fatal("switching scopes could discard an unsaved registration") + } + select { + case <-loader.saved: + t.Fatal("directory validation published settings") + default: + } + d.click(i18n.Shared(i18n.English, "desktop.toolchains.save")) + d.until("global SDKs saved", func() bool { return w.toolchains.saved }) + if w.toolchains.hasDraft() { + t.Fatal("saved registrations remain dirty") + } + if len(w.toolchains.snapshot.Tools[0].CustomHomes) != 2 { + t.Fatal("saving lost a registered SDK") + } +} + func TestToolchainDraftCancelWritesNothing(t *testing.T) { loader := &fakeToolchainLoader{snapshot: fixtureSnapshot(), saved: make(chan []toolchain.Edit, 1)} w, d := toolchainWindow(t, loader) diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index d55d9743f4..b403053a41 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -8,9 +8,11 @@ import ( "path/filepath" "testing" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" ) @@ -71,7 +73,7 @@ func TestVisualSettings(t *testing.T) { MonospaceFamilies: func() []string { return []string{"JetBrains Mono", "Menlo"} }, Marketplace: func(context.Context) (marketplace.Snapshot, error) { return marketplace.Snapshot{}, nil }, UpdateStatus: func() UpdateStatus { return UpdateStatus{Configured: true} }, - Toolchains: &fakeToolchainLoader{snapshot: fixtureSnapshot()}, + Toolchains: &scopedToolchainLoader{fakeToolchainLoader{snapshot: globalVisualToolchains()}}, } w := newWindow(NewController(opts), Values{Theme: theme, Language: language.Code(), TerminalScrollback: 2000}) w.sess.page = scenario.page @@ -134,3 +136,19 @@ func TestVisualSettings(t *testing.T) { } } } + +func globalVisualToolchains() toolchain.Snapshot { + snapshot := fixtureSnapshot() + snapshot.Root = "" + tool := &snapshot.Tools[0] + tool.AutomaticHome = "/fixture/compiler" + tool.CustomHomes = []string{"/fixture/sdk8", "/fixture/sdk21"} + for index, home := range tool.CustomHomes { + version := []string{"8.0.1", "21.0.4"}[index] + tool.Installations = append(tool.Installations, core.ToolchainInstallation{Home: home, Version: version, Provider: "host:manual"}) + } + tool.Pin = &core.ToolchainPin{Home: "/fixture/sdk21", Provider: "host:default"} + selected := "/fixture/sdk21" + tool.Effective = &core.ToolchainSelection{Home: &selected, Executable: selected + "/bin/compiler", Version: "21.0.4", Layer: "global"} + return snapshot +} diff --git a/desktop/internal/toolchain/catalog.go b/desktop/internal/toolchain/catalog.go new file mode 100644 index 0000000000..2d217dcd90 --- /dev/null +++ b/desktop/internal/toolchain/catalog.go @@ -0,0 +1,103 @@ +package toolchain + +import ( + "context" + "errors" + "runtime" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type catalogKernel interface { + ReadToolchainCatalog(context.Context, *string, string) (core.ToolchainCatalogState, error) + EditToolchainCatalog(context.Context, *string, string, []core.ToolchainCatalogEdit) (core.ToolchainCatalogPublication, error) +} + +type catalogSource struct { + file configfile.Snapshot + state core.ToolchainCatalogState + platform string +} + +// Global registrations live in the platform preference root. Reads do not create +// that root; source bytes and native identity remain private to this adapter. +func captureCatalog(ctx context.Context, kernel Kernel, root, platform string) (*catalogSource, error) { + if root == "" { + return nil, nil + } + native, ok := kernel.(catalogKernel) + if !ok { + return nil, errors.New("toolchain: the Core client has no global catalog support") + } + if platform == "" { + platform = PlatformName(runtime.GOOS) + } + plan, err := native.ReadToolchainCatalog(ctx, nil, platform) + if err != nil { + return nil, err + } + file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + if err != nil { + return nil, err + } + document, err := file.Text() + if err != nil { + return nil, err + } + state, err := native.ReadToolchainCatalog(ctx, document, platform) + if err != nil { + return nil, err + } + return &catalogSource{file: file, state: state, platform: platform}, nil +} + +// SaveCatalog publishes only confirmed registrations/defaults. It never writes +// a project pin or touches an SDK directory, and never treats a no-op as a file. +func (s Snapshot) SaveCatalog(ctx context.Context, kernel Kernel, edits []Edit) (bool, error) { + if !s.Global || s.catalog == nil { + return false, ErrPinConflict + } + native, ok := kernel.(catalogKernel) + if !ok { + return false, ErrPinConflict + } + text, err := s.catalog.file.Text() + if err != nil { + return false, err + } + entries := make([]core.ToolchainCatalogEdit, 0, len(edits)) + for _, edit := range edits { + homes := []string{} + for _, tool := range s.Tools { + if tool.ID == edit.Tool { + homes = append(homes, tool.CustomHomes...) + break + } + } + entry := core.ToolchainCatalogEdit{Tool: edit.Tool, Homes: homes} + if edit.Pin != nil { + home := edit.Pin.Home + entry.DefaultHome = &home + } + entries = append(entries, entry) + } + change, err := native.EditToolchainCatalog(ctx, text, s.catalog.platform, entries) + if err != nil { + return false, err + } + if !change.Changed { + return false, nil + } + if change.Document == nil { + return false, errors.New("toolchain: changed catalog has no source") + } + committed, err := s.catalog.file.Replace(ctx, []byte(*change.Document), func() error { return s.catalog.file.Verify(ctx) }) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrPinConflict, err) + } + if err != nil && committed { + err = errors.Join(ErrPinCommitted, err) + } + return committed, err +} diff --git a/desktop/internal/toolchain/catalog_test.go b/desktop/internal/toolchain/catalog_test.go new file mode 100644 index 0000000000..26ad9b9304 --- /dev/null +++ b/desktop/internal/toolchain/catalog_test.go @@ -0,0 +1,77 @@ +package toolchain + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestGlobalCatalogWithoutProjectPersistsSDKsAndAllowsProjectOverrides(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + kernel := core.NewClient() + settings := filepath.Join(t.TempDir(), "user-settings") + home := t.TempDir() + first, second := filepath.Join(t.TempDir(), "sdk8"), filepath.Join(t.TempDir(), "sdk21") + outputs := map[string]string{} + for _, sdk := range []string{first, second} { + exe := filepath.Join(sdk, "bin", "cc") + writeExecutable(t, exe) + outputs[canonical(t, exe)] = "Compiler 3.2.1\n" + } + first, second = canonical(t, first), canonical(t, second) + options := fixtureOptions(home, "", outputs) + options.Global, options.GlobalRoot = true, settings + manifests := []json.RawMessage{readManifest(t, "compiler.plugin.json")} + snapshot, err := Load(ctx, kernel, "", ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(settings); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reading global settings created the root: %v", err) + } + const tool = "dev.example.toolsmith:compiler" + snapshot.Tools[0].CustomHomes = []string{first, second} + edits := []Edit{{Tool: tool, Pin: &core.ToolchainPin{Home: second, Version: "3.2.1", Provider: "host:manual"}}} + if changed, err := snapshot.SaveCatalog(ctx, kernel, edits); err != nil || !changed { + t.Fatalf("save global catalog = %v, %v", changed, err) + } + loaded, err := Load(ctx, kernel, "", ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if len(loaded.Tools) != 1 || len(loaded.Tools[0].CustomHomes) != 2 || loaded.Tools[0].Effective == nil || loaded.Tools[0].Effective.Home == nil || filepath.Clean(*loaded.Tools[0].Effective.Home) != filepath.Clean(second) { + t.Fatalf("global SDK readback = %+v", loaded.Tools) + } + if _, err := snapshot.SaveCatalog(ctx, kernel, edits); !errors.Is(err, ErrPinConflict) { + t.Fatalf("stale global source was reused: %v", err) + } + options.Global = false + for range 2 { + root := t.TempDir() + selected, err := Resolve(ctx, kernel, root, ".", tool, "", nil, manifests, options) + if err != nil || selected.Home == nil || filepath.Clean(*selected.Home) != filepath.Clean(second) { + t.Fatalf("a different project did not inherit the global default: %+v, %v", selected, err) + } + if _, err := os.Stat(filepath.Join(root, ".lithe")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("inheriting a global SDK wrote project state: %v", err) + } + project, err := Load(ctx, kernel, root, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if _, _, err := project.SavePins(ctx, kernel, []Edit{{Tool: tool, Pin: &core.ToolchainPin{Home: first, Version: "3.2.1", Provider: "host:manual"}}}); err != nil { + t.Fatal(err) + } + selected, err = Resolve(ctx, kernel, root, ".", tool, "", nil, manifests, options) + if err != nil || selected.Home == nil || filepath.Clean(*selected.Home) != filepath.Clean(first) || selected.Layer != "pinned" { + t.Fatalf("the explicit project SDK did not override the default: %+v, %v", selected, err) + } + } +} diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index caf402144b..121cf8b046 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "os" "path/filepath" "strings" "sync/atomic" @@ -18,8 +19,10 @@ var loadSequence atomic.Uint64 // UnavailableError reports that Core refused to select an installation. Code is // a stable Core reason; callers localize it rather than parsing the text. type UnavailableError struct { - Tool string - Code string + // Terminal preserves Core's refusal of a fixed or pinned installation. + Terminal bool + Tool string + Code string } func (e *UnavailableError) Error() string { @@ -45,6 +48,14 @@ func RegistryInput(manifests []json.RawMessage) (json.RawMessage, error) { // probes, Core's candidate report and the effective layer for every definition. // It writes nothing. func Load(ctx context.Context, kernel Kernel, root, directory string, manifests []json.RawMessage, options Options) (Snapshot, error) { + catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, options.Platform) + if catalogErr != nil { + return Snapshot{}, catalogErr + } + if catalog != nil { + options.catalog = &catalog.state.Document + } + if kernel == nil { return Snapshot{}, fmt.Errorf("toolchain: no Core client") } @@ -52,7 +63,10 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if err != nil { return Snapshot{}, err } - rootIdentity, err := directoryIdentity(ctx, workspace.root) + var rootIdentity os.FileInfo + if !options.Global { + rootIdentity, err = directoryIdentity(ctx, workspace.root) + } if err != nil { return Snapshot{}, err } @@ -72,11 +86,15 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests for _, entry := range registry.Definitions { definitions[entry.Definition.ID] = entry.Definition } - captured, err := capturePinSource(ctx, kernel, workspace.root) + captured := pinSource{document: json.RawMessage(`{"version":1,"toolchains":{}}`)} + if !options.Global { + captured, err = capturePinSource(ctx, kernel, workspace.root) + } if err != nil { return Snapshot{}, err } snapshot := Snapshot{ + Global: options.Global, catalog: catalog, Root: workspace.root, rootIdentity: rootIdentity, Directory: directory, @@ -119,8 +137,41 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests tool.Pin = pin tool.PinSource = source } - if prepared.candidates.Selected != nil { - tool.AutomaticHome = *prepared.candidates.Selected + if options.catalog != nil { + tool.CustomHomes = append([]string(nil), options.catalog.Tools[planned.Tool].Homes...) + } + if options.Global && prepared.globalDefault != nil { + home := prepared.globalDefault.Home + tool.Pin = &core.ToolchainPin{Home: home, Provider: "host:default"} + tool.PinSource = "global" + } + // Automatic uses the runtime resolver too: the discovery report's + // selected installation omits environment and command candidates. + automatic := resolution + if options.Global && prepared.globalDefault != nil { + automaticPrepared := prepared + automaticPrepared.globalDefault = nil + automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, automaticPrepared, captured.document, directory, options.MinimumVersion, fmt.Sprintf("settings-auto-global-%d-%d", sequence, index)) + if err != nil { + return Snapshot{}, err + } + } + if pin != nil { + document, err := kernel.EditToolchainPins(ctx, captured.document, directory, []core.ToolchainPinEdit{{Tool: planned.Tool}}) + if err != nil { + return Snapshot{}, err + } + automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, prepared, document, directory, + options.MinimumVersion, fmt.Sprintf("settings-auto-%d-%d", sequence, index)) + if err != nil { + return Snapshot{}, err + } + } + if automatic.Outcome.Kind == "resolved" && automatic.Outcome.Selection != nil { + tool.AutomaticHome = automatic.Outcome.Selection.Executable + if automatic.Outcome.Selection.Home != nil { + tool.AutomaticHome = *automatic.Outcome.Selection.Home + } } if resolution.Outcome.Kind == "resolved" { tool.Effective = resolution.Outcome.Selection @@ -134,6 +185,14 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests // facts and Core entry points as the settings page, so a displayed value and a // launched executable cannot come from two rule sets. func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumVersion string, fixed *Fixed, manifests []json.RawMessage, options Options) (Selection, error) { + catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, options.Platform) + if catalogErr != nil { + return Selection{}, catalogErr + } + if catalog != nil { + options.catalog = &catalog.state.Document + } + if kernel == nil { return Selection{}, fmt.Errorf("toolchain: no Core client") } @@ -157,7 +216,10 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV for _, entry := range registry.Definitions { definitions[entry.Definition.ID] = entry.Definition } - captured, err := capturePinSource(ctx, kernel, workspace.root) + captured := pinSource{document: json.RawMessage(`{"version":1,"toolchains":{}}`)} + if !options.Global { + captured, err = capturePinSource(ctx, kernel, workspace.root) + } if err != nil { return Selection{}, err } @@ -183,7 +245,7 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if resolution.Outcome.Reason != nil && resolution.Outcome.Reason.Code != "" { code = resolution.Outcome.Reason.Code } - return Selection{}, &UnavailableError{Tool: tool, Code: code} + return Selection{}, &UnavailableError{Tool: tool, Code: code, Terminal: resolution.Outcome.Kind == "terminalFailure"} } return *resolution.Outcome.Selection, nil } @@ -191,6 +253,7 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV } type preparedTool struct { + globalDefault *core.ToolchainGlobalDefault definition core.ToolchainToolDefinition candidates core.ToolchainCandidates facts []core.ToolchainFileFact @@ -206,6 +269,12 @@ type preparedTool struct { // otherwise consider. func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, document json.RawMessage, planned core.ToolchainDiscoveryPlanTool, definition core.ToolchainToolDefinition, directory string, options Options, fixed *Fixed) (preparedTool, *core.ToolchainPin, string, error) { prepared := preparedTool{definition: definition, fixed: fixed} + if options.catalog != nil { + entry := options.catalog.Tools[planned.Tool] + if entry.DefaultHome != nil { + prepared.globalDefault = &core.ToolchainGlobalDefault{Home: *entry.DefaultHome} + } + } pinResolution, err := kernel.ResolveToolchainPins(ctx, document, directory, planned.Tool) if err != nil { return prepared, nil, "", err @@ -214,6 +283,9 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis if err != nil { return prepared, nil, "", err } + if options.catalog != nil { + homes = append(homes, options.catalog.Tools[planned.Tool].Homes...) + } for _, home := range homes { prepared.installations = append(prepared.installations, core.ToolchainSystemInstallation{Tool: planned.Tool, Home: home}) } @@ -285,6 +357,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis prepared.facts = workspace.all() request := core.ToolchainCandidatesRequest{ + Global: options.Global, Registry: registry, Tool: planned.Tool, Platform: workspace.platform, @@ -345,6 +418,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis // resolveTool runs Core's four-layer resolution over the prepared evidence. func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, prepared preparedTool, document json.RawMessage, directory, minimumVersion, operationID string) (core.ToolchainResolution, error) { request := core.ToolchainResolveRequest{ + Global: workspace.root == "", GlobalDefault: prepared.globalDefault, Registry: registry, Tool: prepared.definition.ID, Directory: directory, diff --git a/desktop/internal/toolchain/scan.go b/desktop/internal/toolchain/scan.go index 42705d8192..6926b91905 100644 --- a/desktop/internal/toolchain/scan.go +++ b/desktop/internal/toolchain/scan.go @@ -35,15 +35,19 @@ func newWorkspace(root string, options Options) (*workspace, error) { if options.Platform == "" { options.Platform = PlatformName(runtime.GOOS) } - if root == "" || !filepath.IsAbs(root) { - return nil, errors.New("toolchain: the workspace root must be absolute") - } - canonicalRoot, err := canonicalPath(root) - if err != nil { - return nil, err - } - if info, err := os.Stat(canonicalRoot); err != nil || !info.IsDir() { - return nil, errors.New("toolchain: the workspace root is not a directory") + canonicalRoot := "" + var err error + if !options.Global { + if root == "" || !filepath.IsAbs(root) { + return nil, errors.New("toolchain: the workspace root must be absolute") + } + canonicalRoot, err = canonicalPath(root) + if err != nil { + return nil, err + } + if info, err := os.Stat(canonicalRoot); err != nil || !info.IsDir() { + return nil, errors.New("toolchain: the workspace root is not a directory") + } } home := options.Home if home == "" { @@ -121,6 +125,9 @@ func canonicalPath(name string) (string, error) { } func (w *workspace) insideRoot(name string) bool { + if w.root == "" { + return false + } root := w.root candidate := name if !w.caseSensitive { @@ -137,6 +144,9 @@ func (w *workspace) insideRoot(name string) bool { // observe records one native fact. Every fact is deduplicated by native identity // so Core never sees two contradictory rows for one path. func (w *workspace) observe(name string) core.ToolchainFileFact { + if name == "" { + return core.ToolchainFileFact{} + } absolute, err := filepath.Abs(name) if err != nil { return core.ToolchainFileFact{} diff --git a/desktop/internal/toolchain/toolchain.go b/desktop/internal/toolchain/toolchain.go index bb33899f4a..f48ee9d5bc 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -22,6 +22,7 @@ type Kernel interface { ToolchainCandidatesOf(ctx context.Context, request core.ToolchainCandidatesRequest) (core.ToolchainCandidates, error) ResolveToolchain(ctx context.Context, request core.ToolchainResolveRequest) (core.ToolchainResolution, error) ResolveToolchainPins(ctx context.Context, document json.RawMessage, directory, tool string) (core.ToolchainPinResolution, error) + EditToolchainPins(ctx context.Context, document json.RawMessage, directory string, edits []core.ToolchainPinEdit) (json.RawMessage, error) ToolchainPinStorage(ctx context.Context) (core.ToolchainPinStoragePlan, error) DecodeToolchainPinDocument(ctx context.Context, document *string) (json.RawMessage, error) EditToolchainPinSources(ctx context.Context, request core.ToolchainPinSourcesRequest) (core.ToolchainPinSourcesEdit, error) @@ -52,9 +53,10 @@ func PlatformName(goos string) string { // Tool is one definition the settings view presents. type Tool struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - PluginID string `json:"pluginID"` + CustomHomes []string `json:"customHomes,omitempty"` + ID string `json:"id"` + DisplayName string `json:"displayName"` + PluginID string `json:"pluginID"` // Providers are the qualified provider IDs that declared this tool. Their // answers are not queried by this client yet, so the view states it. Providers []string `json:"providers"` @@ -78,6 +80,8 @@ type Tool struct { // Snapshot is everything one settings load read for one project directory. type Snapshot struct { + Global bool `json:"global,omitempty"` + catalog *catalogSource Root string `json:"root"` Directory string `json:"directory"` Tools []Tool `json:"tools"` @@ -93,6 +97,10 @@ type Snapshot struct { // Options configure one load. The zero value uses the host platform, the user's // home, the process environment and a bounded native probe. type Options struct { + // Global permits discovery without any project; GlobalRoot owns the native SDK registry. + Global bool + GlobalRoot string + catalog *core.ToolchainCatalog Platform string Home string Environment map[string]string diff --git a/desktop/internal/toolchain/toolchain_test.go b/desktop/internal/toolchain/toolchain_test.go index 214660fc4c..3803dfcfae 100644 --- a/desktop/internal/toolchain/toolchain_test.go +++ b/desktop/internal/toolchain/toolchain_test.go @@ -60,6 +60,31 @@ func fixtureOptions(home, vmHome string, outputs map[string]string) Options { } } +// An environment installation is an automatic choice even when no discovery +// scan found it. The page must describe the same selection the runtime uses. +func TestAutomaticHomeIncludesTheResolvedEnvironment(t *testing.T) { + root, home, vmHome := t.TempDir(), t.TempDir(), t.TempDir() + vm := filepath.Join(vmHome, "jre", "bin", "vm") + writeExecutable(t, vm) + vm = canonical(t, vm) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + snapshot, err := Load(ctx, core.NewClient(), root, ".", []json.RawMessage{readManifest(t, "runtime.plugin.json")}, + fixtureOptions(home, vmHome, map[string]string{vm: "vm 7.1\n"})) + if err != nil { + t.Fatal(err) + } + if len(snapshot.Tools) != 1 || snapshot.Tools[0].Effective == nil { + t.Fatalf("no effective runtime: %+v", snapshot.Tools) + } + if snapshot.Tools[0].Effective.Home == nil { + t.Fatal("the resolved installation has no home") + } + if got, want := snapshot.Tools[0].AutomaticHome, *snapshot.Tools[0].Effective.Home; got != want { + t.Fatalf("automatic home = %q, runtime home = %q", got, want) + } +} + func TestLoadDiscoversTwoSemanticallyDifferentTools(t *testing.T) { root := t.TempDir() home := t.TempDir() diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index d05887c9ef..750d6f849a 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -51,6 +51,9 @@ import ( // the calls that read the disk or run Git, so a screen can be checked against answers the // test chooses. type Kernel interface { + ReadSourceSettings(context.Context, json.RawMessage) (core.SourceSettingsState, error) + PlanSourceSettingsEdits(context.Context, core.SourceSettingsSnapshot, []core.SourceSettingsEdits, bool) ([]core.SourceSettingsWrite, error) + DecodeSourceSettingsReceipt(context.Context, core.SourceSettingsWrite, json.RawMessage) (core.SourceSettingsReceipt, error) SelectPluginFunctionProvider(context.Context, string, string, string, string, []core.PluginFunctionProviderCandidate) (string, error) ReduceRecentProjects(ctx context.Context, entries []core.RecentProject, action core.RecentAction, capacity int) (core.RecentProjectsResult, error) GitCheckoutBranch(ctx context.Context, text string) (string, error) @@ -128,6 +131,7 @@ type Kernel interface { ToolchainCandidatesOf(ctx context.Context, request core.ToolchainCandidatesRequest) (core.ToolchainCandidates, error) ResolveToolchain(ctx context.Context, request core.ToolchainResolveRequest) (core.ToolchainResolution, error) ResolveToolchainPins(ctx context.Context, document json.RawMessage, directory, tool string) (core.ToolchainPinResolution, error) + EditToolchainPins(ctx context.Context, document json.RawMessage, directory string, edits []core.ToolchainPinEdit) (json.RawMessage, error) ToolchainPinStorage(ctx context.Context) (core.ToolchainPinStoragePlan, error) DecodeToolchainPinDocument(ctx context.Context, document *string) (json.RawMessage, error) EditToolchainPinSources(ctx context.Context, request core.ToolchainPinSourcesRequest) (core.ToolchainPinSourcesEdit, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index cf5154516c..fc8deaca68 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -624,7 +624,7 @@ func (a *App) reloadBuildModel(p *project, index int) { // writable state and removed after decoding. No plugin process runs the command, so the // host records the load as the plugin's lithe/build/model operation, at the stage // buildCommandStage describes. -func (a *App) commandModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, messages i18n.BuildMessages) (core.BuildModel, error) { +func (a *App) commandModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, messages i18n.BuildMessages, resolved ...buildExecution) (core.BuildModel, error) { attempt := core.StartPluginAttempt(instance.PluginID, core.OperationBuildModel, core.OriginOf(ctx).Operation) fail := func(stage core.PluginStage, err error) (core.BuildModel, error) { a.plugins.EndAttempt(ctx, attempt, stage, err) @@ -659,7 +659,12 @@ func (a *App) commandModel(ctx context.Context, p *project, instance buildInstan if plan.Provider != nil { return fail(core.StagePlan, errors.New("the build system answered with a provider model")) } - execution, err := a.resolveBuildExecutable(ctx, p, instance, messages) + var execution buildExecution + if len(resolved) > 0 { + execution = resolved[0] + } else { + execution, err = a.resolveBuildExecutable(ctx, p, instance, messages) + } if err != nil { return fail(core.StageResolve, err) } @@ -706,11 +711,17 @@ type buildLaunchError struct{ cause error } func (e *buildLaunchError) Error() string { return e.cause.Error() } func (e *buildLaunchError) Unwrap() error { return e.cause } -func (a *App) providerModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, refresh bool) (core.BuildModel, error) { +func (a *App) providerModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, refresh bool, resolved ...buildExecution) (core.BuildModel, error) { // The host resolves the build tool the provider runs with, so the provider never searches // for it; an explicit tool setting that does not exist fails here, as it does for commands. var tool *core.BuildTool - execution, err := a.resolveBuildExecutable(ctx, p, instance, a.text.Build) + var execution buildExecution + var err error + if len(resolved) > 0 { + execution = resolved[0] + } else { + execution, err = a.resolveBuildExecutable(ctx, p, instance, a.text.Build) + } if err != nil { return core.BuildModel{}, err } @@ -1010,8 +1021,62 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b if err != nil { return buildExecution{}, err } + runtimes := make(map[string]buildExecution, len(invocation.RuntimeDependencies)) + var runtimeEnvironment map[string]string + for _, requirement := range invocation.RuntimeDependencies { + resolved, err := a.resolveBuildCandidates(ctx, p, instance.Root, requirement.Executables, requirement.MinimumVersion, messages, runtimes) + if err != nil { + return buildExecution{}, err + } + resolved.Environment = applyToolchainSelection(resolved.Environment, core.ToolchainSelection{Environment: runtimeEnvironment}) + if requirement.MinimumVersion != "" && requirement.Version != nil { + output, err := probeBuildTool(ctx, resolved.Executable, requirement.Version.Arguments, p.root, applyToolchainSelection(nil, resolved.selection())) + if err != nil { + return buildExecution{}, err + } + version, err := a.kernel.CheckBuildToolVersion(ctx, instance.Manifest, instance.BuildSystemID, requirement.ID, output) + if err != nil { + return buildExecution{}, err + } + if !version.Satisfied { + return buildExecution{}, errors.New(messages.VersionTooOld(requirement.MinimumVersion, version.Version)) + } + } + if requirement.PathVariable != "" { + if resolved.Environment == nil { + resolved.Environment = make(map[string]string) + } + resolved.Environment[requirement.PathVariable] = resolved.Executable + } + runtimeEnvironment = applyToolchainSelection(runtimeEnvironment, resolved.selection()) + runtimes[requirement.ID] = resolved + } + execution, err := a.resolveBuildCandidates(ctx, p, instance.Root, invocation.Executables, invocation.MinimumVersion, messages, runtimes) + if err != nil { + return buildExecution{}, err + } + execution.Environment = applyToolchainSelection(execution.Environment, core.ToolchainSelection{Environment: runtimeEnvironment}) + if invocation.MinimumVersion != "" && invocation.Version != nil { + output, probeErr := probeBuildTool(ctx, execution.Executable, invocation.Version.Arguments, p.root, applyToolchainSelection(nil, execution.selection())) + if probeErr != nil { + return buildExecution{}, probeErr + } + version, checkErr := a.kernel.CheckBuildToolVersion(ctx, instance.Manifest, instance.BuildSystemID, "", output) + if checkErr != nil { + return buildExecution{}, checkErr + } + if !version.Satisfied { + return buildExecution{}, errors.New(messages.VersionTooOld(invocation.MinimumVersion, version.Version)) + } + } + return execution, nil +} + +// Native candidate lookup consumes Core's order and runtime bindings. Runtime +// exports and version probes are applied before the build tool itself starts. +func (a *App) resolveBuildCandidates(ctx context.Context, p *project, directory string, candidates []core.BuildExecutableCandidate, minimum string, messages i18n.BuildMessages, runtimes map[string]buildExecution) (buildExecution, error) { execution := buildExecution{} - for _, candidate := range invocation.Executables { + for _, candidate := range candidates { switch candidate.Kind { case "projectFile": path := filepath.Join(p.root, filepath.FromSlash(candidate.Path)) @@ -1047,14 +1112,27 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b execution.Executable = path } case "runtime": + if resolved, ok := runtimes[candidate.Runtime]; ok { + execution = resolved + break + } + selection, selectErr := a.resolveToolchainSelection(ctx, p.root, directory, candidate.Runtime, minimum) + if selectErr == nil { + execution = buildExecution{Executable: selection.Executable, Environment: selection.Environment, PathPrepend: selection.PathPrepend} + break + } + var unavailable *toolchain.UnavailableError + if !errors.As(selectErr, &unavailable) || unavailable.Code != "definitionUnavailable" { + return buildExecution{}, selectErr + } if path, lookupErr := exec.LookPath(candidate.Runtime); lookupErr == nil { execution.Executable = path } case "toolchain": - selection, selectErr := a.resolveToolchainSelection(ctx, p.root, instance.Root, candidate.ToolchainID, invocation.MinimumVersion) + selection, selectErr := a.resolveToolchainSelection(ctx, p.root, directory, candidate.ToolchainID, minimum) if selectErr != nil { var unavailable *toolchain.UnavailableError - if errors.As(selectErr, &unavailable) { + if errors.As(selectErr, &unavailable) && !unavailable.Terminal { continue } return buildExecution{}, selectErr @@ -1070,19 +1148,6 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b if execution.Executable == "" { return buildExecution{}, errors.New(messages.ExecutableMissing) } - if invocation.MinimumVersion != "" && invocation.Version != nil { - output, probeErr := probeBuildTool(ctx, execution.Executable, invocation.Version.Arguments, p.root, applyToolchainSelection(nil, execution.selection())) - if probeErr != nil { - return buildExecution{}, probeErr - } - version, checkErr := a.kernel.CheckBuildToolVersion(ctx, instance.Manifest, instance.BuildSystemID, "", output) - if checkErr != nil { - return buildExecution{}, checkErr - } - if !version.Satisfied { - return buildExecution{}, errors.New(messages.VersionTooOld(invocation.MinimumVersion, version.Version)) - } - } return execution, nil } diff --git a/desktop/internal/workbench/diagnostic_visual_test.go b/desktop/internal/workbench/diagnostic_visual_test.go new file mode 100644 index 0000000000..10df9fca1c --- /dev/null +++ b/desktop/internal/workbench/diagnostic_visual_test.go @@ -0,0 +1,65 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualDiagnosticUnderline(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []string{"en", "zh-Hans"} { + for _, theme := range []string{"dark", "light"} { + t.Run(language+"-"+theme, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + path := filepath.Join(root, "Diagnostics.txt") + text := "MissingType variable;\n\tMissingType variable;\n中MissingType variable;\n😀MissingType variable;\n\t中😀MissingType variable;\n\nWarningType variable;\n" + if err := os.WriteFile(path, []byte(text), 0600); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1100, 700 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settleChain() + d := p.docs.byPath(path) + if d == nil { + t.Fatal("editor missing") + } + d.view.SetMarkers([]editorview.Marker{{Line: 0, Start: 0, End: 11, Severity: editorview.MarkerError}, {Line: 1, Start: 1, End: 12, Severity: editorview.MarkerError}, {Line: 2, Start: 1, End: 12, Severity: editorview.MarkerError}, {Line: 3, Start: 2, End: 13, Severity: editorview.MarkerError}, {Line: 4, Start: 4, End: 15, Severity: editorview.MarkerError}, {Line: 6, Start: 0, End: 11, Severity: editorview.MarkerWarning}}) + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "diagnostic-"+language+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 62d67c03a1..9dfa892c43 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -48,6 +48,9 @@ var ( // document is a file open in a tab of the editor area. type document struct { + // Each replacement cancels diagnostic geometry still being prepared. + markerCancel context.CancelFunc + markerGeneration uint64 find editorFind scratch bool recoveredConflict bool @@ -815,7 +818,7 @@ func (a *App) removeDocument(p *project, d *document) { // A document without a tab is released with nothing to close, once it is saved. if d.tabless && !d.dirty() { a.semanticTokensDropped(d) - d.view.Close() + d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) } return @@ -825,7 +828,7 @@ func (a *App) removeDocument(p *project, d *document) { return } a.semanticTokensDropped(d) - d.view.Close() + d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) a.unwatchDocument(p, d) a.closeDocumentInSession(p, d) @@ -912,7 +915,7 @@ func (a *App) closeDocuments(p *project) { a.flushCheckpoint(p, d, false) d.find.dispose() d.cancelAutoSave() - d.view.Close() + d.closeEditorView() } p.docs = documentSet{} } @@ -991,3 +994,11 @@ func (a *App) focusedDocument(id gfx.ID) *editorview.View { } return nil } + +func (d *document) closeEditorView() { + if d.markerCancel != nil { + d.markerCancel() + d.markerCancel = nil + } + d.view.Close() +} diff --git a/desktop/internal/workbench/plugindiagnostics.go b/desktop/internal/workbench/plugindiagnostics.go index d671a9ee49..b20e3e3d9f 100644 --- a/desktop/internal/workbench/plugindiagnostics.go +++ b/desktop/internal/workbench/plugindiagnostics.go @@ -4,6 +4,7 @@ import ( "context" "errors" "sort" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" @@ -87,7 +88,7 @@ func (a *App) refreshDocumentMarkers(path string) { if document == nil { return } - document.view.SetMarkers(a.documentMarkers(path)) + a.projectDocumentMarkers(document) } // documentMarkers turns every server's stored diagnostics of one file into view @@ -183,7 +184,7 @@ func (a *App) refreshOpenDocumentMarkers() { return } for _, document := range a.project.docs.list { - document.view.SetMarkers(a.documentMarkers(document.path)) + a.projectDocumentMarkers(document) } } @@ -253,3 +254,41 @@ func (a *App) pluginProblemCount() int { } return total } + +// Capture immutable text and diagnostics on the owner thread. Geometry that +// scans a long line belongs to a cancellable worker, never painting or input. +func (a *App) projectDocumentMarkers(document *document) { + if document.markerCancel != nil { + document.markerCancel() + document.markerCancel = nil + } + document.markerGeneration++ + generation, revision := document.markerGeneration, document.view.Revision() + text, markers := document.view.TextSnapshot(), a.documentMarkers(document.path) + if len(markers) == 0 { + document.view.SetMarkers(nil) + return + } + parent, cancel := context.WithCancel(a.project.ctx) + document.markerCancel = cancel + a.background(a.project, 10*time.Second, func(ctx context.Context) func(*App) { + stop := context.AfterFunc(ctx, cancel) + defer stop() + defer cancel() + projected, err := editorview.ProjectMarkers(parent, text, markers) + return func(a *App) { + if document.markerGeneration != generation { + return + } + document.markerCancel = nil + if err != nil { + // log-exempt: 用户取消:替换诊断或关闭文档取消旧几何准备。 + if !errors.Is(err, context.Canceled) { + a.backgroundFailed("diagnostic_geometry", err) + } + return + } + document.view.SetProjectedMarkers(projected, revision) + } + }) +} diff --git a/desktop/internal/workbench/settings_plugin_actions.go b/desktop/internal/workbench/settings_plugin_actions.go index f2b94f6359..9369c95943 100644 --- a/desktop/internal/workbench/settings_plugin_actions.go +++ b/desktop/internal/workbench/settings_plugin_actions.go @@ -63,6 +63,14 @@ func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice. } return result, nil } + if result.Plan.SourceEditor { + editor, readErr := s.readSourceSettings(ctx, editor, id, nil) + if readErr != nil { + return result, readErr + } + result.Sources = &editor + return result, nil + } // Capture the project on its owning window thread. The buffered reply lets a // cancelled settings page leave without blocking a later window callback. projectReply := make(chan *project, 1) diff --git a/desktop/internal/workbench/settings_plugin_sources.go b/desktop/internal/workbench/settings_plugin_sources.go new file mode 100644 index 0000000000..c06cb882c4 --- /dev/null +++ b/desktop/internal/workbench/settings_plugin_sources.go @@ -0,0 +1,234 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackage" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" +) + +func (s pluginSettingsSources) sourceSettingsCall(ctx context.Context, editor pluginservice.SettingsEditor, action string, params json.RawMessage, editing bool) (json.RawMessage, error) { + check := s.actionWorkspaceCheck(editor) + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, check) + if err != nil { + return nil, err + } + if plan.Kind != "invoke" || !plan.SourceEditor { + return nil, configfile.ErrConflict + } + if params == nil { + params = plan.Params + } + function := plan.Function + if editing { + function = plan.EditFunction + } + result, err := s.app.plugins.CallFromPage(ctx, plan.PluginID, function, params, editor.Snapshot.Workspace(), nil) + if err != nil { + return nil, err + } + current, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, check) + if err != nil { + return nil, err + } + if current.Kind != "invoke" || current.Function != plan.Function || current.EditFunction != plan.EditFunction || !current.SourceEditor { + return nil, configfile.ErrConflict + } + return result, nil +} + +func (s pluginSettingsSources) readSourceSettings(ctx context.Context, editor pluginservice.SettingsEditor, action string, published map[string]string) (pluginsettings.SourceEditor, error) { + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, s.actionWorkspaceCheck(editor)) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + environment, err := s.sourceSettingsContext(ctx, editor, plan, len(published) > 0) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + request := struct { + Operation string `json:"operation,omitempty"` + Context sourceEditorContext `json:"context"` + }{Context: environment} + if len(published) > 0 { + request.Operation = "readAfterSave" + } + params, err := json.Marshal(request) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + raw, err := s.sourceSettingsCall(ctx, editor, action, params, false) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + state, err := s.app.kernel.ReadSourceSettings(ctx, raw) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + for id, revision := range published { + found := false + for _, source := range state.Snapshot.Sources { + if source.ID == id && source.Revision == revision { + found = true + break + } + } + if !found { + return pluginsettings.SourceEditor{}, configfile.ErrConflict + } + } + // The plugin store and the running application's installation are immutable. + // macOS resources are siblings of MacOS inside the enclosing .app bundle; + // Windows resources live beside the executable in the installation directory. + installation, err := installedpackage.Root() + if err != nil { + return pluginsettings.SourceEditor{}, err + } + return pluginsettings.CaptureSources(ctx, editor.Snapshot.Workspace(), state, []string{s.app.plugins.Root, installation}) +} + +// SaveSources runs entirely on the settings worker. The source editor retains +// its private baseline, and every publication rechecks package and workspace. +func (s pluginSettingsSources) SaveSources(ctx context.Context, editor pluginservice.SettingsEditor, action string, sources pluginsettings.SourceEditor, edits []core.SourceSettingsEdits) (updated pluginsettings.SourceEditor, err error) { + ctx = s.app.performedIn(ctx, "plugin.saveNativeSettings", surfaceButton) + defer func() { + if errors.Is(err, pluginsettings.ErrSourcesCommitted) { + s.app.operationFailedIn(ctx, "plugin_settings_source_save", err) + } else { + (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_source_save", err) + } + }() + check := func() error { + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, s.actionWorkspaceCheck(editor)) + if err != nil { + return err + } + if plan.Kind != "invoke" || !plan.SourceEditor { + return configfile.ErrConflict + } + return nil + } + published, err := sources.Apply(ctx, s.app.kernel, edits, func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + return s.sourceSettingsCall(ctx, editor, action, params, true) + }, check) + if err != nil { + return sources, err + } + updated, err = s.readSourceSettings(ctx, editor, action, published) + if err != nil && len(published) > 0 { + err = errors.Join(pluginsettings.ErrSourcesCommitted, err) + } + return updated, err +} + +// Only native session handles are selected here. Source semantics, grouping and +// declaration validation belong to Core; project facts come from the build engine. +type sourceEditorBuild struct { + Root string `json:"root"` + Options map[string]json.RawMessage `json:"options"` + Tool core.BuildTool `json:"tool"` + Model sourceEditorProjectModel `json:"model"` +} + +// Source queries receive only the upstream project's normalized facts. Task, +// run and content-root arrays do not cross this separate settings wire. +type sourceEditorProjectModel struct { + Projects []core.BuildProject `json:"projects"` +} +type sourceEditorContext struct { + Language string `json:"language"` + Builds []sourceEditorBuild `json:"builds"` +} + +func (s pluginSettingsSources) sourceSettingsContext(ctx context.Context, editor pluginservice.SettingsEditor, plan core.PluginSettingsActionPlan, refresh bool) (sourceEditorContext, error) { + result := sourceEditorContext{Builds: []sourceEditorBuild{}} + if editor.Snapshot.State.Localization != nil { + result.Language = editor.Snapshot.State.Localization.Language + } + if plan.LanguageID == "" && plan.BuildSystemID == "" { + return result, nil + } + type captured struct { + messages i18n.BuildMessages + project *project + instances []buildInstance + loading bool + failure string + } + timer := time.NewTicker(100 * time.Millisecond) + defer timer.Stop() + var current captured + for { + reply := make(chan captured, 1) + s.app.post(func(a *App) { + p := a.project + if p == nil { + reply <- captured{} + return + } + if plan.LanguageID != "" { + a.startPluginServer(plan.LanguageID) + } + if plan.BuildSystemID != "" && !p.build.loaded && !p.build.loading { + a.loadBuildSystems(p) + } + // Copy native handles on their owning thread. Their tool/options identities + // remain bound to this captured workspace generation. + reply <- captured{a.text.Build, p, append([]buildInstance(nil), p.build.instances...), p.build.loading, p.build.failed} + }) + select { + case current = <-reply: + case <-ctx.Done(): + return result, ctx.Err() + } + if err := s.actionWorkspaceCheck(editor)(); err != nil { + return result, err + } + if current.project == nil { + return result, configfile.ErrConflict + } + if !current.loading { + break + } + select { + case <-timer.C: + case <-ctx.Done(): + return result, ctx.Err() + } + } + if current.failure != "" { + return result, errors.New(current.failure) + } + if plan.LanguageID != "" { + if _, err := s.app.waitReadyPluginServer(ctx, current.project, plan.PluginID, plan.LanguageID); err != nil { + return result, err + } + } + for _, instance := range current.instances { + if instance.PluginID != plan.PluginID || instance.BuildSystemID != plan.BuildSystemID { + continue + } + execution, err := s.app.resolveBuildExecutable(ctx, current.project, instance, current.messages) + if err != nil { + return result, err + } + var model core.BuildModel + if instance.System.Provider { + model, err = s.app.providerModel(ctx, current.project, instance, s.app.kernel, refresh, execution) + } else { + model, err = s.app.commandModel(ctx, current.project, instance, s.app.kernel, current.messages, execution) + } + if err != nil { + return result, err + } + result.Builds = append(result.Builds, sourceEditorBuild{instance.Root, instance.Options, core.BuildTool{Executable: execution.Executable}, sourceEditorProjectModel{Projects: model.Projects}}) + } + return result, nil +} diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index 819cf35c3b..735b06d871 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -4,9 +4,42 @@ import ( "context" "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) +func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snapshot, tool, home string) (selection core.ToolchainSelection, err error) { + ctx = s.app.performedIn(ctx, "toolchain.inspectDirectory", surfaceButton) + defer func() { s.recordFailure(ctx, "toolchain_settings_inspect", err) }() + if snapshot.Global { + manifests, readErr := s.app.toolchainManifests(ctx) + if readErr != nil { + return selection, readErr + } + return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Global: true, GlobalRoot: s.app.store.Dir(), Platform: buildPlatform()}) + } + root := s.app.toolchainRoot.Load() + if root == nil || snapshot.Root == "" { + return selection, toolchain.ErrPinConflict + } + if err := snapshot.CheckWorkspace(ctx, *root); err != nil { + return selection, errors.Join(toolchain.ErrPinConflict, err) + } + manifests, err := s.app.toolchainManifests(ctx) + if err != nil { + return selection, err + } + selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.store.Dir()}) + if err != nil { + return selection, err + } + if current := s.app.toolchainRoot.Load(); current != root { + return selection, toolchain.ErrPinConflict + } + return selection, snapshot.CheckWorkspace(ctx, *root) +} + // settingsToolchains is the settings window's adapter onto the workbench: it // reads the open project's enabled plugin manifests and writes explicit // directory pins. All calls run on the settings window's background worker. @@ -25,18 +58,41 @@ func (s settingsToolchains) Load(ctx context.Context) (snapshot toolchain.Snapsh return s.loadAt(ctx, *root) } +// LoadScope keeps machine SDK management available before any project is open. +func (s settingsToolchains) LoadScope(ctx context.Context, scope string) (snapshot toolchain.Snapshot, err error) { + if scope != "global" { + return s.Load(ctx) + } + defer func() { s.recordFailure(ctx, "toolchain_settings_load", err) }() + manifests, err := s.app.toolchainManifests(ctx) + if err != nil { + return snapshot, err + } + return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, toolchain.Options{Global: true, GlobalRoot: s.app.store.Dir(), Platform: buildPlatform()}) +} + func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain.Snapshot, error) { manifests, err := s.app.toolchainManifests(ctx) if err != nil && len(manifests) == 0 { return toolchain.Snapshot{}, err } - return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform()}) + return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.store.Dir()}) } // Save applies all draft changes in one Core edit, against the exact // bytes the snapshot was read from, then re-reads the effective values. func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapshot, edits []toolchain.Edit) (updated toolchain.Snapshot, err error) { defer func() { s.recordFailure(ctx, "toolchain_settings_save", err) }() + if snapshot.Global { + if _, err := snapshot.SaveCatalog(ctx, s.app.kernel, edits); err != nil { + return snapshot, err + } + updated, err = s.LoadScope(ctx, "global") + if err != nil { + return snapshot, errors.Join(toolchain.ErrPinCommitted, err) + } + return updated, nil + } root := s.app.toolchainRoot.Load() if root == nil || *root == "" || snapshot.Root == "" { return snapshot, toolchain.ErrPinConflict diff --git a/desktop/internal/workbench/settings_toolchains_test.go b/desktop/internal/workbench/settings_toolchains_test.go index e4b347c25c..24976ff588 100644 --- a/desktop/internal/workbench/settings_toolchains_test.go +++ b/desktop/internal/workbench/settings_toolchains_test.go @@ -11,11 +11,74 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) +// Discovery is inert here: the test owns source failures, never the user's SDKs. +type catalogSourceKernel struct{ *testKernel } + +func (*catalogSourceKernel) ToolchainDiscoveryPlanOf(context.Context, json.RawMessage, string) (core.ToolchainDiscoveryPlan, error) { + return core.ToolchainDiscoveryPlan{}, nil +} + +func TestGlobalToolchainsDoNotHideAnUnreadableEnabledPlugin(t *testing.T) { + preferences, root := store.At(t.TempDir()), t.TempDir() + service, err := pluginservice.Open(core.NewClient(), preferences, root) + if err != nil { + t.Fatal(err) + } + for _, id := range []string{"dev.example.catalog-readable", "dev.example.catalog-unreadable"} { + staging, err := pluginpkg.NewStaging(root) + if err != nil { + t.Fatal(err) + } + fixture, err := os.ReadFile("../toolchain/testdata/compiler.plugin.json") + if err != nil { + t.Fatal(err) + } + var document map[string]any + if err := json.Unmarshal(fixture, &document); err != nil { + t.Fatal(err) + } + document["id"] = id + definition := document["toolDefinitions"].([]any)[0].(map[string]any) + definition["id"] = id + ":compiler" + manifest, err := json.Marshal(document) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(staging, pluginpkg.ManifestFile), manifest, 0600); err != nil { + t.Fatal(err) + } + installed, err := pluginpkg.Install(root, id, "1.0.0", staging) + if err != nil { + t.Fatal(err) + } + if err := pluginstate.New(preferences).SetEnabled(id, true); err != nil { + t.Fatal(err) + } + if id == "dev.example.catalog-unreadable" { + if err := os.Remove(filepath.Join(installed.Path, pluginpkg.ManifestFile)); err != nil { + t.Fatal(err) + } + } + } + app := &App{kernel: &catalogSourceKernel{&testKernel{Client: core.NewClient()}}, store: preferences, plugins: service} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err = (settingsToolchains{app: app}).LoadScope(ctx, "global") + if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("global SDK settings discarded the native read failure: %v", err) + } + if _, err := os.Stat(filepath.Join(preferences.Dir(), "toolchains", "global.json")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a failed read wrote a global catalog: %v", err) + } +} + func TestToolchainSettingsRejectSaveForAnotherOrClosedProject(t *testing.T) { for _, closed := range []bool{false, true} { name := "another-project" @@ -59,7 +122,7 @@ func (k *settingsScopeKernel) EditToolchainPinSources(ctx context.Context, reque func TestToolchainSettingsSaveRereadsItsCapturedProject(t *testing.T) { original, current := t.TempDir(), t.TempDir() kernel := &settingsScopeKernel{testKernel: &testKernel{Client: core.NewClient()}} - app := &App{kernel: kernel} + app := &App{kernel: kernel, store: store.At(t.TempDir())} app.toolchainRoot.Store(&original) kernel.onEdit = func() { app.toolchainRoot.Store(¤t) } plugins, err := pluginservice.Open(core.NewClient(), store.At(t.TempDir()), t.TempDir()) @@ -107,7 +170,7 @@ func testToolchainSettingsWorkspaceReplacement(t *testing.T, duringEdit bool) { t.Fatal(err) } kernel := &settingsScopeKernel{testKernel: &testKernel{Client: core.NewClient()}, onEdit: func() {}} - app := &App{kernel: kernel} + app := &App{kernel: kernel, store: store.At(t.TempDir())} app.toolchainRoot.Store(&original) plugins, err := pluginservice.Open(core.NewClient(), store.At(t.TempDir()), t.TempDir()) if err != nil { @@ -168,7 +231,7 @@ func (k *pinReadbackFailureKernel) DecodeToolchainPinDocument(ctx context.Contex func TestToolchainSettingsReadbackFailureReportsCommittedSource(t *testing.T) { root := t.TempDir() kernel := &pinReadbackFailureKernel{testKernel: &testKernel{Client: core.NewClient()}} - app := &App{kernel: kernel} + app := &App{kernel: kernel, store: store.At(t.TempDir())} app.toolchainRoot.Store(&root) plugins, err := pluginservice.Open(core.NewClient(), store.At(t.TempDir()), t.TempDir()) if err != nil { diff --git a/desktop/internal/workbench/toolchains.go b/desktop/internal/workbench/toolchains.go index c77ea245c1..80c311d151 100644 --- a/desktop/internal/workbench/toolchains.go +++ b/desktop/internal/workbench/toolchains.go @@ -58,7 +58,8 @@ func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, to directory = "." } return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, toolchain.Options{ - Platform: buildPlatform(), + Platform: buildPlatform(), + GlobalRoot: a.store.Dir(), }) } diff --git a/desktop/internal/workbench/toolchains_test.go b/desktop/internal/workbench/toolchains_test.go index 866df6b866..d83e2197e1 100644 --- a/desktop/internal/workbench/toolchains_test.go +++ b/desktop/internal/workbench/toolchains_test.go @@ -3,6 +3,7 @@ package workbench import ( "context" "encoding/json" + "errors" "os" "path/filepath" "runtime" @@ -138,3 +139,54 @@ func writeFakeExecutable(name string) error { } return os.WriteFile(name, []byte("#!/bin/sh\n"), 0o755) } + +func TestBuildRuntimeDependenciesUseTheSelectedInstallation(t *testing.T) { + kernel := &invocationKernel{testKernel: &testKernel{Client: core.NewClient()}, invocation: core.BuildInvocation{ + Executables: []core.BuildExecutableCandidate{{Kind: "toolchain", ToolchainID: "builder"}}, + RuntimeDependencies: []core.BuildRuntimeRequirement{{ID: "vm", MinimumVersion: "9", Executables: []core.BuildExecutableCandidate{{Kind: "toolchain", ToolchainID: "vm"}}}}, + }} + h := newHarness(t, kernel) + h.open(t.TempDir()) + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + var calls []string + h.app.toolchainResolve = func(_ context.Context, _, directory, tool, minimum string) (core.ToolchainSelection, error) { + calls = append(calls, tool) + if tool == "vm" { + if directory != "." || minimum != "9" { + t.Fatalf("runtime selection retargeted: %s %s", directory, minimum) + } + return core.ToolchainSelection{Executable: executable, Environment: map[string]string{"FICTIONAL_VM_HOME": "/selected/vm"}, PathPrepend: []string{"/selected/vm/bin"}}, nil + } + return core.ToolchainSelection{Executable: executable}, nil + } + execution, err := h.app.resolveBuildExecutable(context.Background(), h.app.project, buildInstance{BuildInstance: core.BuildInstance{Root: "."}}, h.app.text.Build) + if err != nil { + t.Fatal(err) + } + if execution.Environment["FICTIONAL_VM_HOME"] != "/selected/vm" { + t.Fatalf("selected runtime was ignored: %+v; resolutions %v", execution, calls) + } + if len(calls) != 2 || calls[0] != "vm" || calls[1] != "builder" { + t.Fatalf("runtime must be resolved before the build tool: %v", calls) + } +} + +func TestBuildRuntimeRefusesAnInvalidPinBeforeFallback(t *testing.T) { + kernel := &invocationKernel{testKernel: &testKernel{Client: core.NewClient()}, invocation: core.BuildInvocation{ + Executables: []core.BuildExecutableCandidate{{Kind: "command", Command: "unused"}}, + RuntimeDependencies: []core.BuildRuntimeRequirement{{ID: "vm", Executables: []core.BuildExecutableCandidate{{Kind: "toolchain", ToolchainID: "vm"}, {Kind: "command", Command: "go"}}}}, + }} + h := newHarness(t, kernel) + h.open(t.TempDir()) + refusal := &toolchain.UnavailableError{Tool: "vm", Code: "notFound", Terminal: true} + h.app.toolchainResolve = func(context.Context, string, string, string, string) (core.ToolchainSelection, error) { + return core.ToolchainSelection{}, refusal + } + _, err := h.app.resolveBuildExecutable(context.Background(), h.app.project, buildInstance{BuildInstance: core.BuildInstance{Root: "."}}, h.app.text.Build) + if !errors.Is(err, refusal) { + t.Fatalf("invalid pin fell through to another installation: %v", err) + } +} diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 2bd7e2b062..ab70654d05 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -127,6 +127,16 @@ SDK 的构建输出,以及对当前工作树的 Core 运行的端到端测试 (`node shared/plugins/scripts/sdk-e2e.mjs`)都属于 Core 仓库, 本仓库不构建 SDK,也不把这些目录登记为可复用资源。 +全局 SDK 登记 `/toolchains/global.json` 登记为 `global-toolchain-catalog` 不可复用项。它属于本机用户设置,最多 256 KiB、64 个工具、每个工具 32 个目录;读取不创建来源,确认保存才条件原子写入并重新解析。没有可复用的构建身份,不允许跨工作树复制,不进入安装包,也不写入 SDK 或签名及增量更新基线。 + +原生插件设置的暂存目录登记为 `plugin-native-settings-staging`: +`/lithe-source-settings-/` 只属于一次确认后的保存操作。 +目录权限为 0700,已有的暂存文件为 0600;原生适配器在写回前校验来源版本、 +工作区与插件身份和 SHA-256,再按原文件元数据进行条件原子替换,并重新读取。 +私有来源快照每个文件最多 2 MiB、总计 8 MiB;所有结束路径均清理暂存。 +这些数据没有可复用的版本、平台、架构或工具链身份,资源复用入口在任何复制阶段均拒绝。 +来源只限用户工作区;应用安装目录和插件安装目录受只读边界保护,不影响代码签名或 Sparkle delta。 + 模块日志和诊断包暂存目录登记为 `application-log-state`,不允许跨工作树复用。日志会话位于 `desktop/internal/logstore` 按平台选择的用户日志目录(`dir_darwin.go`、`dir_other.go`、`dir_windows.go`)下的 `sessions//`。没有可验证的版本、平台、架构或工具链 identity stamp,复用脚本在解析工作树与复制之前拒绝这些位置,不存在允许复制的阶段。测试必须注入各自的临时日志根目录,不要复用真实用户日志。这些数据不进入安装包或签名基线。 #### 日志窗口的视觉截图检查 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 4c44076853..e5cc4ce620 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,7 @@ native_path() { fi } +# Core #57/#58 add sourceSettings 0 and native compiler/runtime plans; #59 adds the project-free SDK catalog. PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Lithe-core-rust #56, squash-merged into main as 9425469: targetBindings.cwd may read # target.directory, so a debugged program runs in its source file's directory rather than in the @@ -117,7 +118,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="9425469bdaa5a8195d9cdf5e9f440165c9e79810" +PINNED_CORE_REVISION="5802c42b5766df7375bd427c54203db415ff72d7" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/scripts/resources/reuse-worktree-resources.mjs b/scripts/resources/reuse-worktree-resources.mjs index d9c36ab77a..936f994e7c 100644 --- a/scripts/resources/reuse-worktree-resources.mjs +++ b/scripts/resources/reuse-worktree-resources.mjs @@ -409,7 +409,7 @@ async function main() { // Identical bytes do not establish transferable execution ownership. // SwiftPM scratch-local compiler stamps only invalidate local products; // swiftpm-build-state is not a sealed download cache and has no copy stage. - // Includes application-log-state: v2 sessions, plugin files (0700/no-follow), + // Includes global-toolchain-catalog (mutable user SDK defaults), plugin-native-settings-staging (private confirmed transactions) and application-log-state: v2 sessions, plugin files (0700/no-follow), // confirmation snapshots and export ZIP // staging belong to one runtime session; no validator or copy stage applies. // Localized logging probes also reject their temporary SwiftPM UI hosts; diff --git a/scripts/resources/test-reuse-worktree-resources.mjs b/scripts/resources/test-reuse-worktree-resources.mjs index b0c05870db..066a3d8510 100644 --- a/scripts/resources/test-reuse-worktree-resources.mjs +++ b/scripts/resources/test-reuse-worktree-resources.mjs @@ -542,12 +542,20 @@ try { assert.notEqual(result.status, 0); assert.match(result.stderr, /language-tools is isolated/); - for (const id of ["windows-worker-plugins", "installed-worker-plugins", "viva-editor-user-state"]) { + for (const id of ["windows-worker-plugins", "installed-worker-plugins", "viva-editor-user-state", "global-toolchain-catalog"]) { const result = run(process.execPath, [reuseScript, "--source", sourceRoot, "--resource", id]); assert.notEqual(result.status, 0); assert.match(diagnostics(result), /isolated/); } + await test("native settings staging belongs to its confirmed operation", {timeout:15000}, async()=>{ + const registry=JSON.parse(await fs.readFile(path.join(scriptDirectory,"worktree-resources.json"),"utf8")); + const entry=registry.excludedResources.find(item=>item.id==="plugin-native-settings-staging"); + assert.equal(entry.reusable,false);assert.match(entry.identity,/2 MiB.*8 MiB/); + assert.match(entry.reason,/0700.*0600/);assert.match(entry.reason,/Every terminal path removes staging/); + const listed=run(process.execPath,[reuseScript,"--list"]);assertSucceeded(listed);assert.ok(!listed.stdout.includes(entry.id)); + const refused=reuse(["--resource",entry.id]);assert.notEqual(refused.status,0);assert.match(diagnostics(refused),/plugin-native-settings-staging is isolated/); + }); process.stdout.write("Worktree resource reuse tests passed.\n"); } finally { await fs.rm(testRoot, { force: true, recursive: true }); diff --git a/scripts/resources/worktree-resources.json b/scripts/resources/worktree-resources.json index 7cc9078e9c..6041949410 100644 --- a/scripts/resources/worktree-resources.json +++ b/scripts/resources/worktree-resources.json @@ -559,6 +559,24 @@ ], "identity": "Mutable user-authored source snapshots, caret/history and personal keymap settings. Owned by the preference installation and document, with no reusable version/platform/architecture/toolchain stamp.", "reason": "Native adapters read only when an editor or list needs them, and atomically replace private files after edits or explicit settings changes. Core owns limits and recovery conflict decisions; saved/discarded normal documents remove recovery copies, scratch files persist until Save As or discard. Never share, copy, package or run a build resource validator at any worktree reuse stage. These paths are outside installed resources and cannot affect code signatures or Sparkle delta baselines." + }, + { + "id": "plugin-native-settings-staging", + "reusable": false, + "locations": [ + "/lithe-source-settings-/" + ], + "identity": "One confirmed editor operation and its native source/package/workspace identities. Private source snapshots are limited to 2 MiB per file and 8 MiB in aggregate; they have no reusable toolchain or build identity.", + "reason": "The native adapter creates a private 0700 transaction directory with existing 0600 staging files, verifies exact source revisions and staged SHA-256 receipts, then conditionally publishes to user-owned workspace files. Every terminal path removes staging. Never copy or share at any worktree reuse stage. Installation/package roots are protected and never used for mutable output, preserving signatures and Sparkle delta baselines." + }, + { + "id": "global-toolchain-catalog", + "reusable": false, + "locations": [ + "/toolchains/global.json" + ], + "identity": "Mutable machine-local SDK registrations and defaults, bounded to 256 KiB, 64 tool IDs and 32 homes per tool. No reusable build or toolchain identity.", + "reason": "Read only on demand without creating missing sources; explicit Save verifies native identity and bytes before atomic publication and fresh resolution. Owned by the user preference installation, not a workspace. Never copy at any worktree reuse stage, never package, and never write into SDKs or installed resources; signatures and Sparkle delta baselines are unchanged." } ] } diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 6fff88a7ec..693ded3402 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1476,6 +1476,13 @@ "desktop.settings.tabsSqueeze": "Squeeze tabs", "desktop.settings.terminalShellHelp": "The shell a new terminal runs, including the one the Terminal tool window opens by itself. The ⌄ menu beside + opens a terminal in another installed shell.", "desktop.settings.terminalShellMissing": "{path} (not found)", + "desktop.sourceSettings.add": "Add override", + "desktop.sourceSettings.allEntriesShown": "All available entries are shown.", + "desktop.sourceSettings.close": "Back", + "desktop.sourceSettings.compilerTitle": "{compiler} Compiler", + "desktop.sourceSettings.inherit": "Inherit ({value})", + "desktop.sourceSettings.noValue": "Not determined", + "desktop.sourceSettings.remove": "Inherit project defaults", "desktop.status.caret": "Caret position", "desktop.status.encoding": "Text encoding", "desktop.status.fPS": "Frame rate", @@ -1586,8 +1593,11 @@ "desktop.toolchains.chooseHelp": "Selecting a row only changes the draft. Save writes the choice to this project's .lithe/toolchains/local.json; Cancel leaves the file unchanged.", "desktop.toolchains.conflict": "{tool} is defined by {plugins}; disable all but one of those plugins.", "desktop.toolchains.description": "Tools declared by enabled plugins. The effective value and its source come from the shared Core resolver; nothing is written until Save.", + "desktop.toolchains.directory": "Installation directory", + "desktop.toolchains.directoryHelp": "Choose the installation root containing the tool executable, such as a JDK directory rather than its bin folder. Checking the version only updates the draft; Save writes the project selection.", "desktop.toolchains.effective": "Effective: {value}", "desktop.toolchains.installation": "{home} · {version} · {provider}", + "desktop.toolchains.invalidDirectory": "The selected directory does not contain a usable installation. Check the directory and try again.", "desktop.toolchains.loadFailed": "Could not read toolchains: {reason}", "desktop.toolchains.loading": "Reading toolchains…", "desktop.toolchains.noInstallations": "No installations found.", @@ -1605,6 +1615,7 @@ "desktop.toolchains.sourceInvalid": "The toolchain or ignore configuration is invalid, too large, or cannot be accessed safely. Check the source files, then reload.", "desktop.toolchains.title": "Toolchains", "desktop.toolchains.unavailable": "Unavailable: {reason}", + "desktop.toolchains.useDirectory": "Use directory", "desktop.tools.background": "Background", "desktop.tools.dragHint": "Drag to move elsewhere", "desktop.tools.withShortcut": "{name} {keys}", @@ -11240,7 +11251,12 @@ "desktop.marketplace.failureChecksum": "The downloaded package failed integrity verification. Retry to download a fresh copy.", "desktop.marketplace.failureNetwork": "Could not download the package. Check your network and proxy settings, then retry.", "desktop.marketplace.failurePermission": "Lithe could not access the required files. Check folder permissions, then retry.", - "desktop.marketplace.failureHelp": "The package could not be downloaded, verified or installed. Retry; if it fails again, open Diagnostics to view the error details." + "desktop.marketplace.failureHelp": "The package could not be downloaded, verified or installed. Retry; if it fails again, open Diagnostics to view the error details.", + "desktop.sourceSettings.effective": "Effective: {value}", + "desktop.sourceSettings.fileCount": "{count} entries", + "desktop.toolchains.global": "Global defaults", + "desktop.toolchains.globalHelp": "Manage detected and manually added SDKs for all projects. Save writes to the application’s user settings; projects can override the default. Existing processes use the new SDK after restarting.", + "desktop.toolchains.project": "Current project" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 202277ec8b..7249746297 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1476,6 +1476,13 @@ "desktop.settings.tabsSqueeze": "挤压标签页", "desktop.settings.terminalShellHelp": "新建终端时运行的 Shell,也包括终端工具窗口自动打开的那个。+ 旁边的 ⌄ 菜单可以用其他已安装的 Shell 新建终端。", "desktop.settings.terminalShellMissing": "{path}(未找到)", + "desktop.sourceSettings.add": "添加覆盖", + "desktop.sourceSettings.allEntriesShown": "所有可用条目已列出。", + "desktop.sourceSettings.close": "返回", + "desktop.sourceSettings.compilerTitle": "{compiler} 编译器", + "desktop.sourceSettings.inherit": "继承({value})", + "desktop.sourceSettings.noValue": "未确定", + "desktop.sourceSettings.remove": "继承项目设置", "desktop.status.caret": "光标位置", "desktop.status.encoding": "文本编码", "desktop.status.fPS": "帧率", @@ -1586,8 +1593,11 @@ "desktop.toolchains.chooseHelp": "选择一行只修改草稿。保存会写入本项目的 .lithe/toolchains/local.json;取消不会改动文件。", "desktop.toolchains.conflict": "{tool} 同时由 {plugins} 定义;请只保留其中一个插件。", "desktop.toolchains.description": "已启用插件声明的工具。生效值与来源由共享 Core 解析得出;点击保存前不会写入任何文件。", + "desktop.toolchains.directory": "安装目录", + "desktop.toolchains.directoryHelp": "选择包含工具程序的安装根目录,例如 JDK 目录,而不是 bin 目录。验证版本只修改草稿;点击保存后才写入项目选择。", "desktop.toolchains.effective": "生效:{value}", "desktop.toolchains.installation": "{home} · {version} · {provider}", + "desktop.toolchains.invalidDirectory": "所选目录中未找到可用的工具安装,请检查目录后重试。", "desktop.toolchains.loadFailed": "无法读取工具链:{reason}", "desktop.toolchains.loading": "正在读取工具链…", "desktop.toolchains.noInstallations": "没有找到安装。", @@ -1605,6 +1615,7 @@ "desktop.toolchains.sourceInvalid": "工具链或忽略配置无效、过大或无法安全访问。请检查来源文件后重新加载。", "desktop.toolchains.title": "工具链", "desktop.toolchains.unavailable": "不可用:{reason}", + "desktop.toolchains.useDirectory": "使用此目录", "desktop.tools.background": "背景", "desktop.tools.dragHint": "可拖动到其他位置", "desktop.tools.withShortcut": "{name} {keys}", @@ -11240,7 +11251,12 @@ "desktop.marketplace.failureChecksum": "下载的插件包未通过完整性校验,请重试以重新下载。", "desktop.marketplace.failureNetwork": "无法下载插件包,请检查网络和代理设置后重试。", "desktop.marketplace.failurePermission": "无法访问所需文件,请检查目录权限后重试。", - "desktop.marketplace.failureHelp": "插件包下载、校验或安装失败。请重试;若仍失败,可打开诊断查看错误详情。" + "desktop.marketplace.failureHelp": "插件包下载、校验或安装失败。请重试;若仍失败,可打开诊断查看错误详情。", + "desktop.sourceSettings.effective": "当前生效:{value}", + "desktop.sourceSettings.fileCount": "{count} 项", + "desktop.toolchains.global": "全局默认", + "desktop.toolchains.globalHelp": "统一管理自动识别和手动添加的 SDK,保存到应用的用户设置。项目可单独覆盖默认版本;已启动的进程需重启后使用新版本。", + "desktop.toolchains.project": "当前项目" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index c82564a01a..7fe78271b5 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -16318,6 +16318,61 @@ "desktop" ] }, + { + "id": "desktop.sourceSettings.add", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.allEntriesShown", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.close", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.compilerTitle", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ], + "parameters": { + "compiler": "string" + } + }, + { + "id": "desktop.sourceSettings.inherit", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.sourceSettings.noValue", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.remove", + "description": "Generic source-backed settings form controls and status.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.startupSweep.body", "description": "Start-up dialog text: {arg1} processes started by an earlier run of Lithe are still running", @@ -17563,6 +17618,20 @@ "desktop" ] }, + { + "id": "desktop.toolchains.directory", + "description": "Desktop toolchain directory selection and validation.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.directoryHelp", + "description": "Desktop toolchain directory selection and validation.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.toolchains.effective", "description": "The value and layer the shared resolver selected. {value} is the formatted selection.", @@ -17585,6 +17654,13 @@ "provider": "string" } }, + { + "id": "desktop.toolchains.invalidDirectory", + "description": "Desktop toolchain directory selection and validation.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.toolchains.loadFailed", "description": "Toolchain discovery failed. {reason} is the diagnostic.", @@ -17716,6 +17792,13 @@ "reason": "string" } }, + { + "id": "desktop.toolchains.useDirectory", + "description": "Desktop toolchain directory selection and validation.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.tools.background", "description": "Desktop tools: Background", @@ -106721,6 +106804,47 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.sourceSettings.effective", + "description": "Generic native settings effective value presentation.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.sourceSettings.fileCount", + "description": "Generic native settings effective value presentation.", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.toolchains.global", + "description": "Machine-wide toolchain scope selector.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.globalHelp", + "description": "Explains global SDK registrations, project overrides and process restart requirements.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.project", + "description": "Current-project toolchain scope selector.", + "platforms": [ + "desktop" + ] } ] } diff --git a/shared/platform-feature-matrix/features/declarative-plugin-settings.json b/shared/platform-feature-matrix/features/declarative-plugin-settings.json index ae01bb243e..1a9059e25d 100644 --- a/shared/platform-feature-matrix/features/declarative-plugin-settings.json +++ b/shared/platform-feature-matrix/features/declarative-plugin-settings.json @@ -2,7 +2,7 @@ "id": "declarative-plugin-settings", "area": "插件", "group": "插件管理", - "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。 插件包可自带 l10n/<语言>.json 翻译设置文字,Core 按界面语言挑选文件并逐条回退到清单原文;切换界面语言后重读文字,但保留未保存草稿。", + "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。 插件包可自带 l10n/<语言>.json 翻译设置文字,Core 按界面语言挑选文件并逐条回退到清单原文;切换界面语言后重读文字,但保留未保存草稿。 支持 Core 来源表单、编译器页面、有效/继承值和显式条件原子保存;读取项目工具须点击读取按钮。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -42,7 +42,13 @@ "desktop/internal/settingswindow/plugin_settings_language_test.go", "desktop/internal/workbench/settings_plugins.go", "desktop/internal/workbench/startup_test.go", - ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md" + ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md", + "desktop/internal/core/source_settings.go", + "desktop/internal/pluginsettings/sources.go", + "desktop/internal/pluginsettings/sources_test.go", + "desktop/internal/settingswindow/source_settings_view.go", + "desktop/internal/settingswindow/source_settings_view_test.go", + "desktop/internal/workbench/settings_plugin_sources.go" ] }, "windows": { @@ -84,7 +90,13 @@ "desktop/internal/settingswindow/plugin_settings_language_test.go", "desktop/internal/workbench/settings_plugins.go", "desktop/internal/workbench/startup_test.go", - ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md" + ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md", + "desktop/internal/core/source_settings.go", + "desktop/internal/pluginsettings/sources.go", + "desktop/internal/pluginsettings/sources_test.go", + "desktop/internal/settingswindow/source_settings_view.go", + "desktop/internal/settingswindow/source_settings_view_test.go", + "desktop/internal/workbench/settings_plugin_sources.go" ] }, "owner": "Plugin Platform", diff --git a/shared/platform-feature-matrix/features/lsp-diagnostics.json b/shared/platform-feature-matrix/features/lsp-diagnostics.json index 8bc43f84a4..037478d8a9 100644 --- a/shared/platform-feature-matrix/features/lsp-diagnostics.json +++ b/shared/platform-feature-matrix/features/lsp-diagnostics.json @@ -2,7 +2,7 @@ "id": "lsp-diagnostics", "area": "编辑器", "group": "语言服务", - "capability": "诊断与编译错误定位", + "capability": "诊断与编译错误定位 UTF-16 诊断位置在后台按制表符、宽字符和补充平面字符转换为显示列,版本变化拒绝旧结果;以细波浪线呈现。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -22,7 +22,10 @@ "desktop/internal/core/plugin_documents.go", "desktop/internal/editorview/view.go", "desktop/internal/pluginbackend/pluginbackend.go", - "desktop/internal/workbench/pluginsync_test.go" + "desktop/internal/workbench/pluginsync_test.go", + "desktop/internal/editorview/markers.go", + "desktop/internal/editorview/markers_test.go", + "desktop/internal/workbench/diagnostic_visual_test.go" ] }, "windows": { @@ -44,7 +47,10 @@ "desktop/internal/core/plugin_documents.go", "desktop/internal/editorview/view.go", "desktop/internal/pluginbackend/pluginbackend.go", - "desktop/internal/workbench/pluginsync_test.go" + "desktop/internal/workbench/pluginsync_test.go", + "desktop/internal/editorview/markers.go", + "desktop/internal/editorview/markers_test.go", + "desktop/internal/workbench/diagnostic_visual_test.go" ] }, "owner": "Language Tooling", diff --git a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json index d1a27b8e0e..9fa4f76c63 100644 --- a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json +++ b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json @@ -2,7 +2,7 @@ "id": "plugin-injected-toolchains", "area": "扩展", "group": "插件与主题", - "capability": "Viva 从已启用插件的 toolDefinitions 声明发现工具链,将文件事实与有界版本探测交给原 Rust Core 的 candidates/resolve;Build 设置显示实际生效值与来源,草稿经显式 Save/Reset/Cancel 和受保护来源快照写入本机目录 pin,Core 统一提供读预算、严格来源解析与 Git 忽略编辑计划,无变化重置不创建文件,Build/Run/命令型 Tests 使用解析出的程序与环境。提供方 toolchains/query、完整配置来源编辑与原生 GUI 验收仍未完成。", + "capability": "Viva 从已启用插件的 toolDefinitions 声明发现工具链,将文件事实与有界版本探测交给原 Rust Core 的 candidates/resolve;Build 设置显示实际生效值与来源,草稿经显式 Save/Reset/Cancel 和受保护来源快照写入本机目录 pin,Core 统一提供读预算、严格来源解析与 Git 忽略编辑计划,无变化重置不创建文件,Build/Run/命令型 Tests 使用解析出的程序与环境。提供方 toolchains/query、完整配置来源编辑与原生 GUI 验收仍未完成。 支持手动目录验证、自动值回显及构建运行时依赖先解析再执行。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -22,7 +22,10 @@ "desktop/internal/core/toolchain_sources.go", "desktop/internal/toolchain/storage_test.go", "desktop/internal/configfile/", - "desktop/internal/settingswindow/toolchains_view_test.go" + "desktop/internal/settingswindow/toolchains_view_test.go", + "desktop/internal/workbench/toolchains_test.go", + "desktop/internal/toolchain/catalog.go", + "desktop/internal/toolchain/catalog_test.go" ] }, "windows": { @@ -38,12 +41,15 @@ "desktop/internal/core/toolchain_sources.go", "desktop/internal/toolchain/storage_test.go", "desktop/internal/configfile/", - "desktop/internal/settingswindow/toolchains_view_test.go" + "desktop/internal/settingswindow/toolchains_view_test.go", + "desktop/internal/workbench/toolchains_test.go", + "desktop/internal/toolchain/catalog.go", + "desktop/internal/toolchain/catalog_test.go" ] }, "owner": "Plugin Platform", "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib toolchain,核对定义独占与官方短 ID、第二种通用工具、旧候选边界、答案身份/代次、Windows 路径大小写、工作区排除、固定值失效不回落、最近项目要求、冲突选择、最低版本、环境隔离和纯声明扫描;按逐项计时工具生成 HTML/JUnit。macOS 继续补齐下列消费者与保存验收,Windows 须先实现对应 adapter:启动提供方并协商、取消/超时和过期结果隔离、输入新建/删除后整体重查、目录固定保存/取消/冲突回读、插件停用撤回、真实 Build/LSP/Run 消费者取得同一选择、发行目录哈希不变与子进程清理。未完成原生流程前保持 pending,不以 Core 测试代替实机验证。 提供方查询:cargo test -p lithe-core --lib toolchain(含 lsp 引擎脚本后端:只有插件后端被提供 litheToolchains、未协商的提供方不写请求、错误回复原样返回;别名链接只有链接路径事实时仍选中规范 home);MacToolchainDiscoveryTests 用真实临时目录与注入的查询验证全局与目录查询各带独立 operationID/代次、链接 home 规范化、工作区内 home 整份拒绝;ToolchainSettingsFeatureTests 验证监视文件连续变化只重载一次、外部输入观察随关闭释放。真实 mise 插件端到端尚未在应用内验证。 原生布局回归 ToolchainSettingsLayoutTests:同一设置宿主按900/1180/1400/900重复缩放,真实分隔条拖动;来源页按500/666/946/500缩放,检查AX控件边界、卡片不重叠、选择和快照不改变。此几何验证不代表提供方查询或保存功能已完成。 声明式扫描 MacToolchainDiscoveryTests:真实临时目录、注入的用户目录与探测,覆盖 homeLayouts 首个匹配、隐藏与未匹配条目、链接到工作区的条目不探测、只探测 Core 返回的可执行文件、同版本冲突、被拒声明不扫描,以及隔离预览样例清单通过 Core 准入;不运行本机安装的工具。 固定集成新增 MacToolchainDiscoveryTests 的运行前解析回归和 MacBuildToolResolverTests,验证两个目录使用各自 pin、最低版本、独立环境与失败不回落;RunLaunchEnvironmentTests 证明操作返回值不会留下共享执行许可槽。该测试不是完整应用 UI 验收。 生产准入回归 installedToolDeclarationsPassTheProductionHostAdmission 经 RustDeclarativePluginOperations 验证工具定义和提供者。Build PATH 保留声明的附加目录,拒绝空目录项。 Windows 原生解析基础:lithe-project::defined_toolchain 逐项计时覆盖两个工具、声明式扫描、固定目录、最近继承、同版本冲突、最低版本、显式 Wrapper、输入撤销及宿主秘密不进入 RPC。真实 Windows 命令包装和进程清理继续由现有 CI 验证;准入仍关闭。 本次回归另核对同目录两个 Run 独立选择、团队/本机逐项合并和显式清空、私有环境隔离、失效固定值不回落、工作区启动器被动零探测,以及未知默认值迁移失败保留源文件。 本批显式 LITHE_TEST_NODE 驱动真实 Core/Node 会话,逐项计时覆盖单次协商、多次查询、原始错误、无协商拒绝、静默超时、后端意外退出与撤销清理;原生解析验证查询与当前事实、来源在探测中变化及稳定模型摘要。安装状态按 plugin/operation/workspace 隔离且不可跨工作树复制。 #1581 最终合入回归包含固定值与未扫描目录、同轮次/上下文、冲突及提供方超时和不可用的来源展示。 通用默认增量:更改工作区工具 home 后,消费者继承读取新值,按 Run 固定值保持独立;失效明确路径不回落,来源在探测期间改变或越出工作区时拒绝。旧编辑保存保留通用偏好,显式空 v1 文档清除。矩阵保持 pending,未把手写测试文档当成设置页或旧配置迁移验收。 macOS Build 偏好编辑:ToolchainPreferencesTests 验证打开/草稿/取消/空重置不建文件、明确保存/回读与权限保留、外部冲突保留原始草稿基线、仅偏好文档不阻断旧默认迁移、缺失子目录的父链接/最终链接/只读安装目录拒绝及主动取消;原生 Save/Reset 按钮在深浅主题通过实际存储执行。ToolchainSettingsLoaderTests 验证使用方来自当前 Core invocation 并随停用撤回。运行全量 Core 与相关 macOS 逐项计时;完整产品、全局默认、旧消费者和 Windows 设置页仍待验收。 tool 引用验证:共享 fixture/Core 覆盖最近通用目录、根目录、跳过父消费者、目录与工作区默认变化、显式 Run 优先和禁止通用工具反向引用;MacToolchainDiscoveryTests 与 lithe-project::defined_toolchain 的真实临时安装/注入探测验证运行前重读,不冻结安装路径。 本机目录/重载回归覆盖仅消费者偏好、父目录连接、重置撤回、链接/非法层级拒绝、单次重试与可刷新错误、未修改表单更新、冲突草稿保留及自身保存通知不等待/撤销保存。该集成不代替完整 GUI。 运行前来源审计 missingPreferenceLeafBehindAParentAliasIsRejectedBeforeToolWork 覆盖两级父目录及存在/悬空链接,四种情况均在工具探测前拒绝。 ToolchainPluginAdmissionTests 使用正式契约 fixture 与真实 Core 验证市场可安装、完整安装审查、清单加载,以及无后端纯工具定义插件的启用模块和工厂登记;本地编译验证不代替真实 mise 与 Windows 工作流验收。 2026-11-02 本机 Swift 6.4.2:准入、后端、发现和加载器 42 项通过,新增两个准入用例分别 4/6 ms;Swift 6.3.3 在本机 Xcode 27.2 SDK 下编译依赖清单崩溃,不能作为固定工具链通过。真实 mise 0.2.1 发布包 SHA-256 与市场一致,Core 证明修复前 unsupported、修复后 available;真实后端完成协商、查询并停止销毁,当前环境未安装 mise,查询真实返回 miseNotFound,未验证安装列表和应用内工作流。 增补来源保存验收:不存在的 pin 重置不创建状态;拒绝逃出工作区的符号链接/junction;有界 UTF-8 与重复键、未知字段和 dormant pin 校验;Git 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。", - "notes": "Viva:共享 Core toolchain 命令已接入 desktop/internal/core/toolchain.go;声明式扫描、文件事实、有界版本探测、toolchains.candidates/resolve 与目录 pin 保存位于 desktop/internal/toolchain/ 并有真实 Core 测试;设置窗口 Build 页可按插件声明展示工具、生效值与来源,显式 Save/Reset 写 .lithe/toolchains/local.json,Cancel 不写;Build 命令和 Provider Run 的 toolchain 候选使用 Core 解析出的可执行文件、环境导出和 PATH。提供方后端查询(toolchainProviders)未接入,因此未声明该能力;Windows 与完整 GUI/原生工作流未验收,状态保持 pending,legacy 证据不代表 Viva。 本轮通过外部 Core Draft PR #3 的精确提交接入 toolchains.editPins:平台不再编辑 pin schema;Core/Go 共用 fixture、批量保存和取消/外部并发修改回归通过。命令型 Tests 同样消费解析后的工具链环境。原生 Windows、提供方工具查询、完整 GUI 与发行验收仍 pending。 Windows 原生回归确认保存前后的文件模式以及真实访问控制描述符(所有者、组、DACL/继承保护)保留;元数据先准备到临时文件,再核对取消/冲突并原子发布。此证据不代表提供方查询或 GUI 已验收。 Viva 设置保存前核对读取项目的原生目录身份;项目关闭或切换后旧草稿拒绝写入,已确认保存的发布与回读固定捕获来源。冲突通过共享 i18n 显示并保留草稿,加载/保存失败进入目录日志;macOS 先失败后通过的回归已有计时,新增作用域行为的 Windows 验收尚未执行。 Windows 原生探测统一 Core 正斜杠路径与本机反斜杠/大小写别名,防止重复事实使目录 pin 解析遭拒绝;选择与校验规则仍由原有 Core 决定。", + "notes": "Viva:共享 Core toolchain 命令已接入 desktop/internal/core/toolchain.go;声明式扫描、文件事实、有界版本探测、toolchains.candidates/resolve 与目录 pin 保存位于 desktop/internal/toolchain/ 并有真实 Core 测试;设置窗口 Build 页可按插件声明展示工具、生效值与来源,显式 Save/Reset 写 .lithe/toolchains/local.json,Cancel 不写;Build 命令和 Provider Run 的 toolchain 候选使用 Core 解析出的可执行文件、环境导出和 PATH。提供方后端查询(toolchainProviders)未接入,因此未声明该能力;Windows 与完整 GUI/原生工作流未验收,状态保持 pending,legacy 证据不代表 Viva。 本轮通过外部 Core Draft PR #3 的精确提交接入 toolchains.editPins:平台不再编辑 pin schema;Core/Go 共用 fixture、批量保存和取消/外部并发修改回归通过。命令型 Tests 同样消费解析后的工具链环境。原生 Windows、提供方工具查询、完整 GUI 与发行验收仍 pending。 Windows 原生回归确认保存前后的文件模式以及真实访问控制描述符(所有者、组、DACL/继承保护)保留;元数据先准备到临时文件,再核对取消/冲突并原子发布。此证据不代表提供方查询或 GUI 已验收。 Viva 设置保存前核对读取项目的原生目录身份;项目关闭或切换后旧草稿拒绝写入,已确认保存的发布与回读固定捕获来源。冲突通过共享 i18n 显示并保留草稿,加载/保存失败进入目录日志;macOS 先失败后通过的回归已有计时,新增作用域行为的 Windows 验收尚未执行。 Windows 原生探测统一 Core 正斜杠路径与本机反斜杠/大小写别名,防止重复事实使目录 pin 解析遭拒绝;选择与校验规则仍由原有 Core 决定。 全局 SDK 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {