diff --git a/.agents/notes/implemented/architecture/2026-11-09-viva-toolchain-settings-and-build-resolution.md b/.agents/notes/implemented/architecture/2026-11-09-viva-toolchain-settings-and-build-resolution.md index 3af8e7d28..672a95f61 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-viva-toolchain-settings-and-build-resolution.md +++ b/.agents/notes/implemented/architecture/2026-11-09-viva-toolchain-settings-and-build-resolution.md @@ -6,7 +6,7 @@ Viva 桌面端现在把插件声明的工具链接进了设置和构建执行:Core 仍是唯一决定“哪个安装生效”的地方,Go 只做声明式扫描、文件事实读取、有界版本探测和原子保存。设置页的 Build 页按插件声明的工具显示当前生效值与来源;用户选择只改草稿,明确 Save 才写 `.lithe/toolchains/local.json`,Cancel 不写。Build 命令任务、Build 模型和 Provider 应用的 `toolchain` 候选都复用同一次解析,启动时使用 Core 返回的可执行文件、导出环境和 PATH。 -这一批没有接入提供方后端查询(`toolchainProviders`),也没有因此声明该能力;Windows 原生保存与相关组件已在 Lithe-dev 验证,完整 GUI 流程仍未验收。 +工具链提供方(`toolchainProviders`)在设置、运行或新建项目需要发现结果时,复用插件的共享后端。工作区与全局查询采用同一套文件事实校验和 Core 解析。原生窗口的完整流程仍待验收。 ## 问题 @@ -22,11 +22,23 @@ Viva 桌面端现在把插件声明的工具链接进了设置和构建执行: - Core 返回的可执行路径可用正斜杠,Windows 原生扫描和 pin 可能使用反斜杠或不同大小写。执行探测前按原生路径身份合并别名,并把本机路径交给进程适配器;不把同一程序的多个拼写当作多份探测事实。Windows 回归已先复现同一程序被探测三次及 pin 解析因重复证据遭拒绝,修复保留 Core 的严格证据校验。 - 扫描不到安装、版本不满足或工具被两个插件争用时,界面显示 Core 的稳定原因,不伪造默认安装。争用工具不注册,宿主不按插件 ID 替用户选择。 +### 按需发现提供方安装 + +共享插件后端在首次查询时启动,查询与函数调用都用 Core 的会话及取消入口。一个工作区查询带打开时的上下文 ID 和代次。工作区关闭或重开后,旧上下文不能继续发布结果。用户固定的运行目标可以独立解析。 + +查询使用注册表清单中的插件版本,缓存键也含同一份清单。升级后的首次查询先确认新版本仍是当前启用版本,再结束旧后端并启动新后端。旧版迟到查询不能替换现用会话。新建项目只对表单需要的工具运行发现与探测,未选工具的提供方故障不会阻断表单。 + +每个工具的同一轮回包共用一个代次。桌面收集声明布局、要求来源和观察路径的原生事实,Core 负责校验身份、路径范围、安装与版本要求。为设置和运行缓存的是有界原始回包,每次使用仍按当前文件事实校验。缺失的输入由最近的现存父目录负责观察,文件变化会使整轮重新查询,已有进程保持自己的启动参数。关闭项目、停用或重新加载插件时,释放观察器并结束相应会话。 + +例如用户创建原本缺失的版本要求文件时,下次解析应重新调用提供方并使用完整的新回包。仅重新探测上轮已发现的程序无法反映新文件。沿用原生目录事件避免空闲轮询,且让替换写不会留下指向旧文件的监听。 + +整轮提供方查询有独立的期限。到期时保留已完成的回包,并请 Core 为剩余提供方生成超时回包,以便同一次解析仍能使用本机候选;用户取消或工作区关闭则终止解析。用 `TestToolchainProviderRoundPreservesAnswersAtItsDeadline` 检查已收到的回包和未发出的查询。 + ### 读取真实来源,明确保存 工具链快照另保存从已打开目录句柄立即读取的工作区身份。保存前同时核对读取时来源和活动项目的身份,不能只比较两个当前路径;原路径被改名并重建时,即使本地文档仍缺失或字节相同,也要拒绝。Core 编辑期间和最终发布前再次核对,防止校验期间替换根目录。已有确认后切换到另一个项目仍只写捕获的原目录并回读原目录;这与替换原目录是不同情况。 -- 设置页 Build 页显示每个工具的有效安装、版本、层级和 pin 来源;登录 Shell 的 home 候选单列显示,并说明提供方安装尚未查询。 +- 设置页 Build 页显示每个工具的有效安装、版本、层级和 pin 来源;登录 Shell 的 home 候选单列显示,提供方安装进入同一安装列表。 - 选择只修改窗口草稿;Save 才把整批变化交给 Core。来源文件的路径、字节预算、缺失时默认值、完整 schema 与重复 JSON 键检查都由 Core 给出;没有已安装工具也必须校验 dormant pin。Go 使用已有 `configfile` 适配器按预算读取 UTF-8,不先解析或补默认文档。原生选项未指定平台时采用当前宿主,不能把空平台字符串交给 Core。 - `toolchains.editPinSources` 同时返回本地文档与忽略文件的编辑计划。没有语义变化时保留原字节和缺失状态;例如对不存在的 pin 执行重置,不能创建 `.lithe`。旧 `editPins` 的选择与合并规则继续复用,不重写内核。 - 忽略规则使用 Core 固定版本 `ignore` 的完整匹配器。只调用 `GitignoreBuilder` 的内存行解析和匹配,不启用目录遍历、全局规则发现或线程池;许可证为 MIT/Unlicense,资源开销仅发生在明确保存时。已经生效的通配规则保持原样;后续否定规则取消忽略时,在末尾追加明确规则,保留评论、已有行与换行风格。不在 Go 用“是否包含一行”代替 Git 规则。输入与输出都检查字节和行数预算,避免发布下次无法读取的来源。 @@ -71,13 +83,13 @@ Windows 的工具发现和构建模型测试要保留两条真实本机边界: - **在 Go 里扫描目录并维护 Maven/JDK 优先规则。** 能最快让界面有内容,但会重造 Core 已校验的四层选择和工具知识,第二个工具就要再改宿主,因此不采用。 - **只做设置页,不接 Build。** 页面可展示但用户仍无法使用所选路径;无法验证“探测结果与启动目标一致”,因此先接执行。 -- **声明 `toolchainProviders` 后再补查询。** 会让市场允许带后端的工具链插件安装,但本客户端无法发 `toolchains/query`,首次使用才失败;所以本批不声明该能力。 -- **用文件监听做实时刷新。** 会新增常驻监听和失效规则;本批在打开页面和显式 Reload 时读取,避免未验收的 watcher 生命周期。 +- **单独为每次查询启动一份提供方进程。** 同一插件同时提供语言配置和工具链时,进程启动与初始化会重复。共享后端可在同一连接中区分操作,并由同一个插件生命周期释放。 +- **每次都重新向提供方请求。** 工具选择会在设置和多个运行入口反复执行。采用短期有界缓存和原生观察,输入变动时重查,空闲时无需轮询。 - **在宿主 CI 下载真实插件和工具做 Windows 回归。** 会引入具体插件依赖、网络与安装布局,不能稳定控制失败形态;宿主只测试合成工具的通用流程,真实工具在插件仓库验收。 ## 后果 -收益是设置显示与 Build/Run 启动共享同一份 Core 结果,新增工具只需插件声明,不需改宿主工具表。代价是提供方查询、目录树多来源合并、手动“添加安装”和输入文件监听仍未实现;保存的 JSON 编辑规则由 Core 持有,平台仅负责有冲突检查的原生写入。 +收益是设置显示与 Build/Run 启动共享同一份 Core 结果,新增工具只需插件声明,不需改宿主工具表。提供方查询需要临时后端和有限的观察器注册。达到观察范围上限后只保留当次结果;保存的 JSON 编辑规则由 Core 持有,平台负责有冲突检查的原生写入。 Windows 已运行真实 Core 的工具链与工作台组件测试,并以受保护的用户专属访问控制列表验证原子保存保留原权限。原生程序识别与权限发布的取舍见 `../bug-fix/2026-11-09-viva-windows-native-file-validation.md`;路径大小写的完整工作流、GUI 和发行包验收仍待补。 @@ -104,6 +116,7 @@ Windows 运行 `./.agents/skills/write-stable-tests/scripts/test-stability-windo - `desktop/internal/core/toolchain.go` - `desktop/internal/toolchain/` +- `desktop/internal/pluginservice/toolchain_provider.go` - `desktop/internal/settingswindow/toolchains_view.go` - `desktop/internal/workbench/toolchains.go`、`settings_toolchains.go`、`build.go` - `desktop/internal/toolchain/path_windows_test.go`、`desktop/internal/workbench/build_command_windows_test.go` diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index a5de9ea1c..df52b29e2 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -227,6 +227,28 @@ jobs: if-no-files-found: error retention-days: 14 + - name: Capture toolchain provider settings + id: toolchain-provider-visual + if: ${{ !cancelled() && steps.rust.outcome == 'success' }} + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/toolchain-provider-visual + run: | + for language in en zh-Hans; do + LITHE_VISUAL_LANGUAGE="$language" LITHE_VISUAL_OUTPUT_DIR="$LITHE_VISUAL_OUTPUT_DIR/$language" \ + ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow \ + -run '^TestVisualSettings$/^m51-toolchain-provider-installation' -count=1 -timeout=120s + done + + - name: Upload toolchain provider settings screenshots + if: ${{ !cancelled() && steps.toolchain-provider-visual.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: toolchain-provider-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/toolchain-provider-visual/**/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native verification reports if: always() uses: actions/upload-artifact@v7 @@ -281,6 +303,7 @@ jobs: run: ./scripts/desktop/check.sh - name: Capture native settings and diagnostic screenshots + id: native-settings-visual env: LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/native-settings-visual run: | @@ -302,7 +325,7 @@ jobs: done - name: Upload native settings visual evidence - if: always() + if: ${{ !cancelled() && steps.native-settings-visual.outcome != 'skipped' }} uses: actions/upload-artifact@v7 with: name: native-settings-visual-${{ runner.os }}-${{ runner.arch }} @@ -381,6 +404,7 @@ jobs: run: ./scripts/desktop/check.sh - name: Capture native settings and diagnostic screenshots + id: native-settings-visual env: LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/native-settings-visual run: | @@ -402,7 +426,7 @@ jobs: done - name: Upload native settings visual evidence - if: always() + if: ${{ !cancelled() && steps.native-settings-visual.outcome != 'skipped' }} uses: actions/upload-artifact@v7 with: name: native-settings-visual-${{ runner.os }}-${{ runner.arch }} diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index 9b4869a1f..c33ced10f 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -9,15 +9,16 @@ import ( // PluginBackendStart is the host-resolved process and workspace. The host must // only supply programs and grants from an approved, verified plugin package. type PluginBackendStart struct { - ProviderID string `json:"providerId"` - PluginID string `json:"pluginId"` - Role string `json:"role,omitempty"` - ExecutablePath string `json:"executablePath"` - Arguments []string `json:"arguments,omitempty"` - Environment map[string]string `json:"environment,omitempty"` - RootURI any `json:"rootUri"` - WorkingDirectory string `json:"workingDirectory"` - HostServices []string `json:"hostServices,omitempty"` + ProviderID string `json:"providerId"` + PluginID string `json:"pluginId"` + Role string `json:"role,omitempty"` + ExecutablePath string `json:"executablePath"` + Arguments []string `json:"arguments,omitempty"` + Environment map[string]string `json:"environment,omitempty"` + RootURI any `json:"rootUri"` + WorkingDirectory string `json:"workingDirectory"` + HostServices []string `json:"hostServices,omitempty"` + ToolchainProviders []string `json:"toolchainProviders,omitempty"` // FunctionRelayEnabled isolates preparation sessions from both incoming and // outgoing cross-plugin calls. Omitted preserves ordinary backend behavior. FunctionRelayEnabled *bool `json:"functionRelayEnabled,omitempty"` diff --git a/desktop/internal/core/toolchain_provider.go b/desktop/internal/core/toolchain_provider.go new file mode 100644 index 000000000..23743f257 --- /dev/null +++ b/desktop/internal/core/toolchain_provider.go @@ -0,0 +1,101 @@ +package core + +import ( + "context" + "encoding/json" +) + +// ToolchainQueryContext is the captured identity of the open workspace. +type ToolchainQueryContext struct { + ID string `json:"contextID"` + Generation uint64 `json:"generation"` +} + +// ToolchainQueryWorkspace identifies the directory for one provider query. +type ToolchainQueryWorkspace struct { + RootID string `json:"rootID"` + Root string `json:"root"` + Directory string `json:"directory"` +} + +// ToolchainQueryParams remain the same from submission to reply validation. +type ToolchainQueryParams struct { + OperationID string `json:"operationID"` + Generation uint64 `json:"generation"` + ProviderID string `json:"providerID"` + Authority map[string]string `json:"authority"` + Context *ToolchainQueryContext `json:"context"` + Workspace *ToolchainQueryWorkspace `json:"workspace"` + Tools []string `json:"tools"` +} + +// ToolchainProviderReply preserves the real wire identity and raw response. +type ToolchainProviderReply struct { + ID json.RawMessage `json:"id"` + Response json.RawMessage `json:"response"` +} + +// ToolchainProviderSnapshot contains the reply facts validated by Core. +type ToolchainProviderSnapshot struct { + Installations []ToolchainProviderInstallation `json:"installations"` + Watch []string `json:"watch"` +} + +const ( + ToolchainProviderUnavailable = "plugin.toolchain.providerUnavailable" + ToolchainProviderTimeout = "plugin.toolchain.timeout" +) + +// RequestPluginToolchain queues a query on the plugin's initialized backend. +func (c *Client) RequestPluginToolchain(ctx context.Context, sessionID string, params ToolchainQueryParams, timeoutMS int) error { + return c.Execute(ctx, "lsp.toolchainRequest", struct { + SessionID string `json:"sessionId"` + OperationID string `json:"operationId"` + Params ToolchainQueryParams `json:"params"` + TimeoutMS int `json:"timeoutMilliseconds"` + }{sessionID, params.OperationID, params, timeoutMS}, nil) +} + +// ToolchainFailureReply asks Core to encode a missing transport reply. +func (c *Client) ToolchainFailureReply(ctx context.Context, params ToolchainQueryParams, code string) (ToolchainProviderReply, error) { + const command = "toolchains.failureReply" + var result struct { + Status string `json:"status"` + Reply *ToolchainProviderReply `json:"reply"` + Error *MarketplaceRejection `json:"error"` + } + request := struct { + Params ToolchainQueryParams `json:"params"` + Code string `json:"code"` + }{params, code} + if err := c.Execute(ctx, command, request, &result); err != nil { + return ToolchainProviderReply{}, err + } + if result.Error != nil { + return ToolchainProviderReply{}, result.Error + } + if result.Status != "ok" || result.Reply == nil { + return ToolchainProviderReply{}, newParseError(command, "toolchains.failureReply returned no reply", "") + } + return *result.Reply, nil +} + +// DecodeToolchainReply verifies the raw reply against authority-local facts. +func (c *Client) DecodeToolchainReply(ctx context.Context, query ToolchainQuery) (ToolchainProviderSnapshot, error) { + const command = "toolchains.decodeReply" + var result struct { + Status string `json:"status"` + Snapshot *ToolchainProviderSnapshot `json:"snapshot"` + Error *MarketplaceRejection `json:"error"` + } + if err := c.Execute(ctx, command, query, &result); err != nil { + return ToolchainProviderSnapshot{}, err + } + if result.Error != nil { + return ToolchainProviderSnapshot{}, result.Error + } + if result.Status != "ok" || result.Snapshot == nil { + return ToolchainProviderSnapshot{}, newParseError(command, "toolchains.decodeReply returned no snapshot", "") + } + return *result.Snapshot, nil +} diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index c12d02430..2a964b3d8 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -119,6 +119,8 @@ type StartRequest struct { // VcsProviderID selects a VCS provider the same way. It is empty for the // other roles. VcsProviderID string + // ToolchainProviders are the provider IDs from the approved backend manifest. + ToolchainProviders []string // Role is the Core session role. Empty keeps the historical backend role; // a build provider names "build" and a VCS provider "vcs". Role string @@ -422,6 +424,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro RootURI: request.RootURI, WorkingDirectory: request.WorkingDirectory, HostServices: granted, + ToolchainProviders: request.ToolchainProviders, HostOptions: hostOptions(granted), InitializationOptions: plan.InitializationOptions, WorkspaceConfiguration: plan.WorkspaceConfiguration, diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 8999b5a52..7fa38f2f1 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -119,6 +119,9 @@ type Capabilities map[string][]int // launches use the shared Core resolver. Version 1 adds a definition's // category and audience, which group the tool on the Toolchains settings // page. +// - toolchainProviders: the shared plugin backend discovers global and project +// installations and requirements on demand. Core validates each answer with +// native filesystem facts before the toolchain resolver can use it. // - commandInstallers: plugin management reports the commands a // systemCommand launch names but the machine lacks, and installs them with // the plugin's tool after the user confirms the command line, the network @@ -157,9 +160,9 @@ type Capabilities map[string][]int // watching, authentication, history entry diffs, status in the project tree // and the editor gutter, and lithe/vcs/execution console output. // -// buildModelInputs, executionProviders, keymapImportProviders, packageTrust and -// toolchainProviders are not declared: nothing here serves -// them, so a plugin that needs one is not offered for installation. +// buildModelInputs, executionProviders, keymapImportProviders and packageTrust +// are not declared: nothing here serves them, so plugins requiring them are +// not offered for installation. func Declared() Capabilities { baseline := []string{ "backend", @@ -178,6 +181,7 @@ func Declared() Capabilities { "settings", "sourceSettings", "toolDefinitions", + "toolchainProviders", "ui", "vcsProviders", } diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 19306b36c..362a6d34b 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -61,7 +61,7 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { want := []string{ "backend", "beforeLaunchTasks", "buildProviders", "buildSystems", "commandInstallers", "debugAdapters", "languageServers", "languages", "managedRuntimes", "outputLinkMatchers", "pluginFunctions", - "projectGenerators", "runConfigurationTypes", "settings", "sourceSettings", "toolDefinitions", "ui", + "projectGenerators", "runConfigurationTypes", "settings", "sourceSettings", "toolDefinitions", "toolchainProviders", "ui", "vcsProviders", } if len(declared) != len(want) { @@ -98,7 +98,7 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { // Capabilities nothing here serves stay absent so their plugins are not // offered for installation. for _, name := range []string{ - "buildModelInputs", "executionProviders", "keymapImportProviders", "packageTrust", "toolchainProviders", + "buildModelInputs", "executionProviders", "keymapImportProviders", "packageTrust", } { if _, ok := declared[name]; ok { t.Fatalf("%s was declared", name) diff --git a/desktop/internal/pluginservice/activation.go b/desktop/internal/pluginservice/activation.go index 588896f21..ca7fecb66 100644 --- a/desktop/internal/pluginservice/activation.go +++ b/desktop/internal/pluginservice/activation.go @@ -124,8 +124,13 @@ func (s *Service) DetachWorkspaces() func() { if s == nil || s.Contexts == nil || s.Host == nil { return func() {} } + stopObserving := s.toolchainProviders.Invalidate() s.Contexts.CloseAll() - return s.Host.DetachAll() + stopBackend := s.Host.DetachAll() + return func() { + stopObserving() + stopBackend() + } } // DetachBackend removes one plugin's backend from the host, as DetachWorkspaces @@ -134,7 +139,12 @@ func (s *Service) DetachBackend(pluginID string) func() { if s == nil || s.Host == nil { return func() {} } - return s.Host.Detach(pluginID) + stopObserving := s.toolchainProviders.Invalidate() + stopBackend := s.Host.Detach(pluginID) + return func() { + stopObserving() + stopBackend() + } } // contextsChanged tells running backends the contexts changed and refreshes the diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index e87e3a5ea..ad094c842 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -65,12 +65,25 @@ type BackendHost struct { // sessions are the running backends by plugin ID. sessions map[string]*BackendSession // starting makes concurrent EnsureBackend calls for one plugin share a start. - starting map[string]chan struct{} + starting map[string]*backendStart nextOp atomic.Uint64 } +type backendStart struct { + done chan struct{} + cancel context.CancelFunc +} + +func (s *backendStart) stop() { + s.cancel() + select { + case <-s.done: + case <-time.After(backendStopTimeout): + } +} + func newBackendHost(service *Service) *BackendHost { - return &BackendHost{service: service, sessions: make(map[string]*BackendSession), starting: make(map[string]chan struct{})} + return &BackendHost{service: service, sessions: make(map[string]*BackendSession), starting: make(map[string]*backendStart)} } // BackendSession is one running plugin backend and its serve loop. @@ -123,37 +136,56 @@ func (h *BackendHost) RunningPlugins() []string { // EnsureBackend starts the plugin's backend when it is not running and returns // its session. It does not wait for the backend to finish initialize; Call does. func (h *BackendHost) EnsureBackend(ctx context.Context, pluginID string) (*BackendSession, error) { + return h.ensureBackend(ctx, pluginID, "") +} + +// A toolchain query names the version from its registry snapshot. Updating the +// package can change the provider's response without changing its provider ID. +func (h *BackendHost) ensureBackend(ctx context.Context, pluginID, version string) (*BackendSession, error) { for { h.mu.Lock() - if session := h.sessions[pluginID]; session != nil && !session.isEnded() { - h.mu.Unlock() - return session, nil - } if wait, busy := h.starting[pluginID]; busy { h.mu.Unlock() select { - case <-wait: + case <-wait.done: continue case <-ctx.Done(): return nil, ctx.Err() } } - done := make(chan struct{}) - h.starting[pluginID] = done + previous := h.sessions[pluginID] + if previous != nil && !previous.isEnded() && (version == "" || previous.Version == version) { + h.mu.Unlock() + return previous, nil + } + startCtx, cancel := context.WithCancel(ctx) + start := &backendStart{done: make(chan struct{}), cancel: cancel} + h.starting[pluginID] = start h.mu.Unlock() - session, err := h.start(ctx, pluginID) + session, err := h.start(startCtx, pluginID, version, previous) + cancel() h.mu.Lock() - delete(h.starting, pluginID) - if err == nil { - h.sessions[pluginID] = session + detached := h.starting[pluginID] != start + if !detached { + delete(h.starting, pluginID) + if err == nil { + h.sessions[pluginID] = session + } } h.mu.Unlock() - close(done) + if detached { + if session != nil { + session.stop() + } + err = context.Canceled + session = nil + } + close(start.done) return session, err } } -func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSession, error) { +func (h *BackendHost) start(ctx context.Context, pluginID, version string, previous *BackendSession) (*BackendSession, error) { s := h.service entries, err := s.Manager.Installed() if err != nil { @@ -168,7 +200,7 @@ func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSessi break } } - if !found { + if !found || (version != "" && entry.Installed.Version != version) { return nil, errors.Join(ErrBackendUnavailable, selectionErr) } manifest, err := readBounded(filepath.Join(entry.Installed.Path, pluginpkg.ManifestFile), MaxManifestBytes) @@ -178,6 +210,41 @@ func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSessi if !declaresBackend(manifest) { return nil, fmt.Errorf("%w: %s declares no backend", ErrBackendUnavailable, pluginID) } + // Validate the current package before ending the old session. A delayed + // query for a superseded version must leave the new session alone. + if previous != nil { + if err := ctx.Err(); err != nil { + return nil, err + } + previous.cancel() + select { + case <-previous.done: + case <-ctx.Done(): + return nil, ctx.Err() + } + disposed, stopErr := previous.disposed, previous.stopErr + if !disposed { + disposed, stopErr = s.Backend.StopAndDispose(ctx, previous.Session) + if disposed { + h.forget(previous) + } + } + if err := s.runtimeStopFailure(ctx, disposed, stopErr); err != nil { + return nil, err + } + } + var declaration struct { + ToolchainProviders []struct { + ID string `json:"id"` + } `json:"toolchainProviders"` + } + if err := json.Unmarshal(manifest, &declaration); err != nil { + return nil, err + } + providerIDs := make([]string, 0, len(declaration.ToolchainProviders)) + for _, provider := range declaration.ToolchainProviders { + providerIDs = append(providerIDs, provider.ID) + } settings, err := s.Settings.Load(ctx, manifest, "") if err != nil { return nil, err @@ -189,15 +256,16 @@ func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSessi startCtx, cancelStart := context.WithTimeout(ctx, backendStartTimeout) defer cancelStart() started, err := s.Backend.Start(startCtx, pluginbackend.StartRequest{ - Manifest: manifest, - PackageDirectory: entry.Installed.Path, - PluginID: entry.Installed.ID, - ProviderID: entry.Installed.ID + "/backend", - StateDirectory: directories.state, - LogDirectory: directories.log, - Architecture: core.PluginArchitecture(), - Settings: settings.State.Settings, - ProjectSettings: settings.State.ProjectSettings, + Manifest: manifest, + PackageDirectory: entry.Installed.Path, + PluginID: entry.Installed.ID, + ProviderID: entry.Installed.ID + "/backend", + ToolchainProviders: providerIDs, + StateDirectory: directories.state, + LogDirectory: directories.log, + Architecture: core.PluginArchitecture(), + Settings: settings.State.Settings, + ProjectSettings: settings.State.ProjectSettings, // A backend belongs to no workspace: it starts with its plugin-wide state // directory as root and working directory. RootURI: fileURI(directories.state), @@ -228,8 +296,16 @@ func (h *BackendHost) Detach(pluginID string) func() { h.mu.Lock() session := h.sessions[pluginID] delete(h.sessions, pluginID) + start := h.starting[pluginID] + delete(h.starting, pluginID) h.mu.Unlock() + if start != nil { + start.cancel() + } return func() { + if start != nil { + start.stop() + } if session != nil { session.stop() } @@ -248,12 +324,19 @@ func (h *BackendHost) DetachAll() func() { sessions = append(sessions, session) } h.sessions = make(map[string]*BackendSession) + starts := h.starting + h.starting = make(map[string]*backendStart) h.mu.Unlock() + for _, start := range starts { + start.cancel() + } return func() { var group sync.WaitGroup for _, session := range sessions { - group.Add(1) - go func() { defer group.Done(); session.stop() }() + group.Go(session.stop) + } + for _, start := range starts { + group.Go(start.stop) } group.Wait() } @@ -485,15 +568,22 @@ func (b *BackendSession) serve(ctx context.Context) { _ = err // Everything the session created in the host goes with it. b.host.service.resources.releaseSession(b.Session.ID) - // A backend that exited on its own leaves the Core session to dispose. - b.host.mu.Lock() - if b.host.sessions[b.PluginID] == b { - delete(b.host.sessions, b.PluginID) - } - b.host.mu.Unlock() + // Keep the session registered until its process is disposed so the next + // start can wait for it, even if the event loop has already ended. stopCtx, cancel := context.WithTimeout(context.Background(), backendStopTimeout) defer cancel() b.disposed, b.stopErr = b.host.service.Backend.StopAndDispose(stopCtx, b.Session) + if b.disposed { + b.host.forget(b) + } +} + +func (h *BackendHost) forget(session *BackendSession) { + h.mu.Lock() + if h.sessions[session.PluginID] == session { + delete(h.sessions, session.PluginID) + } + h.mu.Unlock() } // observe records the lifecycle facts calls depend on and routes completions. diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index f5c7f4081..440e175a3 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -31,6 +31,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) // ErrAssembly reports a stack that cannot be built. @@ -64,6 +65,10 @@ type Kernel interface { // Service is the assembled plugin stack. type Service struct { + toolchainProviders *toolchain.ProviderClient + toolchainKernel toolchainProviderKernel + // ToolchainIssue records discovery failures that left declared fallback sources usable. + ToolchainIssue func(context.Context, error) // providers2 holds the editor provider registrations of the window (hostproviders.go). providers2 *editorProviderBindings // actions holds the editor action registrations of the window (hostactions.go). @@ -198,6 +203,19 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se } service.Backend.SetCommandStore(service.Commands) service.Host = newBackendHost(service) + if providerKernel, ok := kernel.(toolchainProviderKernel); ok { + service.toolchainKernel = providerKernel + service.toolchainProviders = &toolchain.ProviderClient{ + Request: service.queryToolchain, + FailureReply: providerKernel.ToolchainFailureReply, + Decode: providerKernel.DecodeToolchainReply, + Failed: func(ctx context.Context, err error) { + if service.ToolchainIssue != nil { + service.ToolchainIssue(ctx, err) + } + }, + } + } service.Runs = newRuns(service) service.Contexts = newWorkspaceContexts(filepath.Join(root, pluginpkg.StateDirectory)) service.Contexts.SetObserver(service.contextsChanged) diff --git a/desktop/internal/pluginservice/toolchain_provider.go b/desktop/internal/pluginservice/toolchain_provider.go new file mode 100644 index 000000000..f6fc90df8 --- /dev/null +++ b/desktop/internal/pluginservice/toolchain_provider.go @@ -0,0 +1,151 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "os" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +type toolchainProviderKernel interface { + RequestPluginToolchain(context.Context, string, core.ToolchainQueryParams, int) error + ToolchainFailureReply(context.Context, core.ToolchainQueryParams, string) (core.ToolchainProviderReply, error) + DecodeToolchainReply(context.Context, core.ToolchainQuery) (core.ToolchainProviderSnapshot, error) +} + +// ToolchainOptions binds discovery to the window's existing project identity +// and the native roots that provider answers must never authorize. +func (s *Service) ToolchainOptions(root string, options toolchain.Options) toolchain.Options { + if s == nil || s.Contexts == nil { + return options + } + options.WorkspaceRoots = s.Contexts.workspaceRoots() + options.Providers = s.toolchainProviders + if root == "" { + return options + } + workspace, present := s.Contexts.ByPath(root) + if !present { + // A pin reread uses the captured canonical path while Open can receive an + // alias from the chooser. Compare native identities only on this worker. + if expected, err := os.Stat(root); err == nil { + _, contexts := s.Contexts.List() + for _, candidate := range contexts { + if info, err := os.Stat(candidate.Path); err == nil && os.SameFile(info, expected) { + workspace, present = candidate, true + break + } + } + } + } + if !present { + // No project context is available for paths that a consumer is inspecting + // without opening. Such paths remain eligible for declarative discovery. + options.Providers = nil + return options + } + options.ProviderScope = &toolchain.ProviderScope{ + Context: core.ToolchainQueryContext{ID: workspace.ContextID, Generation: workspace.Generation}, + RootID: func(pluginID string) string { return s.Contexts.RootID(pluginID, workspace.Path) }, + Validate: func() error { + _, err := s.Contexts.Lookup(workspace.ContextRef) + return err + }, + } + return options +} + +const toolchainQueryTimeout = 10 * time.Second + +func (s *Service) queryToolchain(ctx context.Context, pluginID, version string, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { + queryCtx, cancel := context.WithTimeout(ctx, toolchainQueryTimeout) + defer cancel() + verify := func() error { + if params.Context == nil { + return nil + } + _, err := s.Contexts.Lookup(ContextRef{ContextID: params.Context.ID, Generation: params.Context.Generation}) + return err + } + if err := verify(); err != nil { + return core.ToolchainProviderReply{}, err + } + session, err := s.Host.ensureBackend(queryCtx, pluginID, version) + if err == nil { + if err := verify(); err != nil { + return core.ToolchainProviderReply{}, err + } + var reply core.ToolchainProviderReply + reply, err = session.queryToolchain(queryCtx, params) + if err == nil { + if err := verify(); err != nil { + return core.ToolchainProviderReply{}, err + } + return reply, nil + } + } + if err := ctx.Err(); err != nil { + return core.ToolchainProviderReply{}, err + } + code := core.ToolchainProviderUnavailable + var failure *eventFailure + var bridge *core.Error + switch { + case errors.Is(err, context.Canceled): + return core.ToolchainProviderReply{}, err + case errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &failure) && failure.Code == "requestTimeout"): + code = core.ToolchainProviderTimeout + case session == nil, errors.Is(err, ErrBackendUnavailable): + case errors.As(err, &bridge) && (bridge.Code == core.CodeConnectionClosed || + (bridge.Code == core.CodeNotSupported && bridge.Details == core.ToolchainProviderUnavailable)): + default: + return core.ToolchainProviderReply{}, err + } + return s.toolchainKernel.ToolchainFailureReply(ctx, params, code) +} + +func (b *BackendSession) queryToolchain(ctx context.Context, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { + if err := b.waitFor(ctx, func() bool { return b.ready && !b.ended }); err != nil { + return core.ToolchainProviderReply{}, err + } + completed := make(chan core.BackendEvent, 1) + b.mu.Lock() + if b.ended { + b.mu.Unlock() + return core.ToolchainProviderReply{}, ErrBackendUnavailable + } + b.waiters[params.OperationID] = completed + b.mu.Unlock() + defer func() { + b.mu.Lock() + delete(b.waiters, params.OperationID) + b.mu.Unlock() + }() + kernel := b.host.service.kernel + if err := b.host.service.toolchainKernel.RequestPluginToolchain(ctx, b.Session.ID, params, int(toolchainQueryTimeout/time.Millisecond)); err != nil { + return core.ToolchainProviderReply{}, err + } + select { + case event := <-completed: + value, err := decodeCompletion(event) + if err != nil { + return core.ToolchainProviderReply{}, err + } + var reply core.ToolchainProviderReply + if err := json.Unmarshal(value, &reply); err != nil { + return core.ToolchainProviderReply{}, err + } + return reply, nil + case <-ctx.Done(): + cancelCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if err := kernel.CancelPluginOperation(cancelCtx, b.Session.ID, params.OperationID); err != nil && b.host.service.RecordFailed != nil { + b.host.service.RecordFailed(cancelCtx, err) + } + return core.ToolchainProviderReply{}, ctx.Err() + } +} diff --git a/desktop/internal/pluginservice/toolchain_provider_test.go b/desktop/internal/pluginservice/toolchain_provider_test.go new file mode 100644 index 000000000..ae53e48d6 --- /dev/null +++ b/desktop/internal/pluginservice/toolchain_provider_test.go @@ -0,0 +1,480 @@ +package pluginservice + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +const ( + toolchainFixturePlugin = "dev.lithe.test.toolchain" + toolchainFixtureTool = "dev.lithe.test.toolchain:tool" + providerFixtureSource = ".fixture-version" +) + +const toolchainProviderFixtureManifest = `{ + "schemaVersion": 0, + "id": "dev.lithe.test.toolchain", + "displayName": "Toolchain fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"backend": 0, "toolDefinitions": 0, "toolchainProviders": 0}, + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch", "toolchains.provide"], + "backend": { + "launch": {"kind": "packaged", "path": "provider.exe"}, + "arguments": ["-test.run=^TestToolchainProviderFixtureProcess$"] + }, + "toolchainProviders": [{"id": "fixture", "displayName": "Fixture provider", "tools": ["dev.lithe.test.toolchain:tool"], + "watchFiles": [{"reader": "native", "pattern": ".fixture-version"}]}], + "toolDefinitions": [{ + "id": "dev.lithe.test.toolchain:tool", + "displayName": "Fixture tool", + "executableLayouts": [{"path": "bin/fixture"}], + "executables": [ + {"id": "provider", "kind": "toolchain", "scope": "project"}, + {"id": "shell", "kind": "command", "command": "fixture-tool"}, + {"id": "installed", "kind": "toolchain", "scope": "installed"} + ], + "version": {"arguments": ["--version"], "pattern": "Fixture (\\d+(?:\\.\\d+)*)"}, + "commands": ["fixture-tool"], + "launch": ["${executable}", "${arguments}"] + }] +}` + +type toolchainProviderFixtureConfig struct { + Home string +} + +func TestToolchainProviderFixtureProcess(t *testing.T) { + data, err := os.ReadFile("toolchain-fixture.json") + if errors.Is(err, os.ErrNotExist) { + t.Skip("only the configured backend process serves the fixture") + } + var config toolchainProviderFixtureConfig + if err != nil || json.Unmarshal(data, &config) != nil { + os.Exit(2) + } + reader := bufio.NewReader(os.Stdin) + count := 0 + for { + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + if err := readToolchainFixtureFrame(reader, &request); err != nil { + os.Exit(3) + } + if len(request.ID) == 0 { + if request.Method == "exit" { + os.Exit(0) + } + continue + } + var result any + switch request.Method { + case "initialize": + var params struct { + Capabilities struct { + Experimental struct { + Toolchains struct { + Providers []string `json:"providers"` + } `json:"litheToolchains"` + } `json:"experimental"` + } `json:"capabilities"` + } + if json.Unmarshal(request.Params, ¶ms) != nil || + len(params.Capabilities.Experimental.Toolchains.Providers) != 1 || + params.Capabilities.Experimental.Toolchains.Providers[0] != "fixture" { + os.Exit(4) + } + result = map[string]any{"capabilities": map[string]any{"experimental": map[string]any{ + "litheToolchains": map[string]any{"version": 0, "providers": []string{"fixture"}}, + }}} + case "toolchains/query": + var query core.ToolchainQueryParams + if json.Unmarshal(request.Params, &query) != nil || query.ProviderID != "fixture" || + len(query.Tools) != 1 || query.Tools[0] != toolchainFixtureTool { + os.Exit(5) + } + count++ + if err := os.WriteFile("query-count", []byte(strconv.Itoa(count)), 0o600); err != nil { + os.Exit(6) + } + watch, statements := []string{}, []any{} + if query.Workspace != nil { + source := filepath.Join(query.Workspace.Root, providerFixtureSource) + watch = append(watch, source) + if data, err := os.ReadFile(source); err == nil { + statements = append(statements, map[string]any{ + "tool": toolchainFixtureTool, "kind": "declaration", "scope": "project", + "source": source, "request": string(data), "installation": config.Home, "reader": "native", + }) + } + } + result = map[string]any{ + "operationID": query.OperationID, "generation": query.Generation, "providerID": query.ProviderID, + "installations": []any{map[string]any{"tool": toolchainFixtureTool, "home": config.Home, "version": "7.1"}}, + "statements": statements, "watch": watch, + } + case "shutdown": + default: + os.Exit(7) + } + body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result}) + if err != nil { + os.Exit(8) + } + if _, err := fmt.Fprintf(os.Stdout, "Content-Length: %d\r\n\r\n%s", len(body), body); err != nil { + os.Exit(9) + } + } +} + +func readToolchainFixtureFrame(reader *bufio.Reader, request any) error { + length := -1 + for { + line, err := reader.ReadString('\n') + if err != nil { + return err + } + line = strings.TrimSpace(line) + if line == "" { + break + } + if key, value, ok := strings.Cut(line, ":"); ok && strings.EqualFold(key, "Content-Length") { + length, err = strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return err + } + } + } + if length < 0 || length > 1<<20 { + return errors.New("invalid fixture frame length") + } + body := make([]byte, length) + if _, err := io.ReadFull(reader, body); err != nil { + return err + } + return json.Unmarshal(body, request) +} + +func TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources(t *testing.T) { + client, preferences, plugins := core.NewClient(), store.At(t.TempDir()), t.TempDir() + service, err := Open(client, preferences, plugins) + if err != nil { + t.Fatal(err) + } + service.Contexts.SetObserver(nil) + t.Cleanup(func() { service.DetachWorkspaces()() }) + + manifest := json.RawMessage(toolchainProviderFixtureManifest) + installed := filepath.Join(plugins, toolchainFixturePlugin, "1.0.0") + state := pluginpkg.VersionStateRoot(plugins, toolchainFixturePlugin, "1.0.0") + home := t.TempDir() + for _, directory := range []string{installed, state, filepath.Join(home, "bin")} { + if err := os.MkdirAll(directory, 0o700); err != nil { + t.Fatal(err) + } + } + write := func(path string, bytes []byte, mode os.FileMode) { + t.Helper() + if err := os.WriteFile(path, bytes, mode); err != nil { + t.Fatal(err) + } + } + binary, err := os.Executable() + if err != nil { + t.Fatal(err) + } + write(filepath.Join(installed, pluginpkg.ManifestFile), manifest, 0o600) + // The fixture never changes its executable. A hard link lets the platform + // reuse validation of the test binary instead of validating a second image. + program := filepath.Join(installed, "provider.exe") + if err := os.Link(binary, program); err != nil { + image, readErr := os.ReadFile(binary) + if readErr != nil { + t.Fatal(readErr) + } + write(program, image, 0o700) + } + write(filepath.Join(home, "bin", "fixture"), nil, 0o700) + config, err := json.Marshal(toolchainProviderFixtureConfig{Home: home}) + if err != nil { + t.Fatal(err) + } + write(filepath.Join(state, "toolchain-fixture.json"), config, 0o600) + if err := pluginstate.New(preferences).SetEnabled(toolchainFixturePlugin, true); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + workspace := t.TempDir() + service.Contexts.Open(workspace) + options := service.ToolchainOptions(workspace, toolchain.Options{ + Home: t.TempDir(), Platform: toolchain.PlatformName(runtime.GOOS), Environment: map[string]string{}, + Probe: func(context.Context, string, []string) (string, int, error) { return "Fixture 7.1", 0, nil }, + Lookup: func(string) (string, error) { return "", os.ErrNotExist }, + }) + if service.Host.Running(toolchainFixturePlugin) != nil { + t.Fatal("opening a workspace started a provider before discovery was needed") + } + load := func(layer string, counts ...int) { + t.Helper() + snapshot, err := toolchain.Load(ctx, client, workspace, ".", []json.RawMessage{manifest}, options) + if err != nil { + var rejection *core.MarketplaceRejection + if errors.As(err, &rejection) { + t.Fatalf("%s: %v", rejection.Field, err) + } + t.Fatal(err) + } + if len(snapshot.Tools) != 1 || snapshot.Tools[0].Effective == nil || snapshot.Tools[0].Effective.Layer != layer || + snapshot.Tools[0].Effective.Provider != toolchainFixturePlugin+":fixture" || len(snapshot.Tools[0].Installations) != 1 { + t.Fatalf("toolchain selection = %+v, want %s resolution and a provider installation", snapshot.Tools, layer) + } + got, err := os.ReadFile(filepath.Join(state, "query-count")) + count, parseErr := strconv.Atoi(string(got)) + if err != nil || parseErr != nil || !slices.Contains(counts, count) { + t.Fatalf("provider ran %q queries, want one of %v (read: %v, parse: %v)", got, counts, err, parseErr) + } + } + load("automatic", 1) + backend := service.Host.Running(toolchainFixturePlugin) + if backend == nil { + t.Fatal("provider ran outside the shared plugin backend") + } + load("automatic", 1) + write(filepath.Join(workspace, providerFixtureSource), []byte("7.1"), 0o600) + // The native watcher can deliver the create event during registration of + // the refreshed generation. A retry is allowed once, under the same deadline. + load("project", 2, 3) + global := service.ToolchainOptions("", toolchain.Options{ + Global: true, Home: options.Home, Environment: options.Environment, Probe: options.Probe, Lookup: options.Lookup, + }) + selection, err := toolchain.Resolve(ctx, client, "", ".", toolchainFixtureTool, "", nil, []json.RawMessage{manifest}, global) + if err != nil || selection.Layer != "automatic" || selection.Provider != toolchainFixturePlugin+":fixture" { + t.Fatalf("global selection = %+v, %v", selection, err) + } + if service.Host.Running(toolchainFixturePlugin) != backend { + t.Fatal("an observation change started a second copy of the plugin backend") + } + stop := service.DetachWorkspaces() + stop() + if service.Host.Running(toolchainFixturePlugin) != nil { + t.Fatal("closing the project left a provider backend registered") + } + if _, err := toolchain.Load(ctx, client, workspace, ".", []json.RawMessage{manifest}, options); !errors.Is(err, ErrContextExpired) { + t.Fatalf("closed workspace query error = %v, want context expiration", err) + } +} + +func TestToolchainProviderQueriesTheInstalledVersionAfterUpgrade(t *testing.T) { + client, preferences, plugins := core.NewClient(), store.At(t.TempDir()), t.TempDir() + service, err := Open(client, preferences, plugins) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { service.DetachWorkspaces()() }) + if err := pluginstate.New(preferences).SetEnabled(toolchainFixturePlugin, true); err != nil { + t.Fatal(err) + } + binary, err := os.Executable() + if err != nil { + t.Fatal(err) + } + install := func(version string) string { + t.Helper() + packageDir := filepath.Join(plugins, toolchainFixturePlugin, version) + stateDir := pluginpkg.VersionStateRoot(plugins, toolchainFixturePlugin, version) + home := t.TempDir() + for _, path := range []string{packageDir, stateDir, filepath.Join(home, "bin")} { + if err := os.MkdirAll(path, 0o700); err != nil { + t.Fatal(err) + } + } + program := filepath.Join(packageDir, "provider.exe") + if err := os.Link(binary, program); err != nil { + image, readErr := os.ReadFile(binary) + if readErr != nil { + t.Fatal(readErr) + } + if err := os.WriteFile(program, image, 0o700); err != nil { + t.Fatal(err) + } + } + config, err := json.Marshal(toolchainProviderFixtureConfig{Home: home}) + if err != nil { + t.Fatal(err) + } + manifest := strings.Replace(toolchainProviderFixtureManifest, `"version": "1.0.0"`, `"version": "`+version+`"`, 1) + executable := filepath.Join(home, "bin", "fixture") + for path, data := range map[string][]byte{ + filepath.Join(packageDir, pluginpkg.ManifestFile): []byte(manifest), + filepath.Join(stateDir, "toolchain-fixture.json"): config, + executable: nil, + } { + if err := os.WriteFile(path, data, 0o700); err != nil { + t.Fatal(err) + } + } + canonical, err := filepath.EvalSymlinks(executable) + if err != nil { + t.Fatal(err) + } + return canonical + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + options := service.ToolchainOptions("", toolchain.Options{ + Global: true, Home: t.TempDir(), Environment: map[string]string{}, + Probe: func(context.Context, string, []string) (string, int, error) { return "Fixture 7.1", 0, nil }, + Lookup: func(string) (string, error) { return "", os.ErrNotExist }, + }) + resolve := func(version, executable string) *BackendSession { + t.Helper() + entries, err := service.Manager.Installed() + if err != nil { + t.Fatal(err) + } + selected, err := service.ToolchainPlugins(ctx, entries) + if err != nil || len(selected) != 1 || selected[0].Version != version { + t.Fatalf("current toolchain manifest = %+v, error = %v, want %s", selected, err, version) + } + selection, err := toolchain.Resolve(ctx, client, "", ".", toolchainFixtureTool, "", nil, []json.RawMessage{selected[0].Manifest}, options) + session := service.Host.Running(toolchainFixturePlugin) + if err != nil || filepath.FromSlash(selection.Executable) != executable { + t.Fatalf("installed %s, executable %q, want %q (error %v)", version, selection.Executable, executable, err) + } + if session == nil || session.Version != version { + t.Fatalf("the backend for installed version %s did not own the query", version) + } + return session + } + old := resolve("1.0.0", install("1.0.0")) + current := resolve("1.1.0", install("1.1.0")) + if current == old { + t.Fatal("the upgrade reused the old backend") + } + select { + case <-old.done: + default: + t.Fatal("the replacement published before the old backend stopped") + } + if _, err := service.Host.ensureBackend(ctx, toolchainFixturePlugin, old.Version); !errors.Is(err, ErrBackendUnavailable) { + t.Fatalf("a late query for the superseded version returned %v", err) + } + if service.Host.Running(toolchainFixturePlugin) != current { + t.Fatal("a late query displaced the current backend") + } +} + +type toolchainCancellationKernel struct { + *core.Client + submitted chan string + cancelled chan string +} + +func (k *toolchainCancellationKernel) RequestPluginToolchain(ctx context.Context, _ string, params core.ToolchainQueryParams, _ int) error { + select { + case k.submitted <- params.OperationID: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (k *toolchainCancellationKernel) CancelPluginOperation(ctx context.Context, _, operation string) error { + select { + case k.cancelled <- operation: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func TestToolchainProviderCancellationDoesNotCompleteTheNextQuery(t *testing.T) { + kernel := &toolchainCancellationKernel{ + Client: core.NewClient(), submitted: make(chan string, 2), cancelled: make(chan string, 1), + } + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + session := &BackendSession{ + host: service.Host, ready: true, waiters: make(map[string]chan core.BackendEvent), changed: make(chan struct{}), + } + type outcome struct { + reply core.ToolchainProviderReply + err error + } + ctx, finish := context.WithTimeout(context.Background(), 5*time.Second) + defer finish() + query := func(queryCtx context.Context, id string) <-chan outcome { + done := make(chan outcome, 1) + go func() { + reply, err := session.queryToolchain(queryCtx, core.ToolchainQueryParams{OperationID: id}) + done <- outcome{reply, err} + }() + return done + } + await := func(events <-chan string, want string) { + t.Helper() + select { + case got := <-events: + if got != want { + t.Fatalf("observed operation %q, want %q", got, want) + } + case <-ctx.Done(): + t.Fatalf("operation %q was not observed: %v", want, ctx.Err()) + } + } + complete := func(id, wire string) { + data := json.RawMessage(fmt.Sprintf(`{"value":{"id":%q,"response":{}}}`, wire)) + session.observe(core.BackendEvent{Type: "requestCompleted", OperationID: id, Result: data}) + } + cancellable, cancel := context.WithCancel(ctx) + defer cancel() + first := query(cancellable, "first") + await(kernel.submitted, "first") + cancel() + await(kernel.cancelled, "first") + select { + case got := <-first: + if !errors.Is(got.err, context.Canceled) { + t.Fatalf("cancelled query outcome = %+v", got) + } + case <-ctx.Done(): + t.Fatal("cancelled query did not return") + } + next := query(ctx, "second") + await(kernel.submitted, "second") + complete("first", "expired") + complete("second", "current") + select { + case got := <-next: + if got.err != nil || string(got.reply.ID) != `"current"` { + t.Fatalf("second query = %+v, want the current wire reply", got) + } + case <-ctx.Done(): + t.Fatal("second query did not return") + } +} diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index 08e83352a..e8847618c 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -51,6 +51,7 @@ func TestVisualSettings(t *testing.T) { {"33-settings-toolchains", pageToolchains}, {"m44-toolchain-directory-menu", pageToolchains}, {"m45-toolchain-custom-directory", pageToolchains}, {"m47-toolchain-project-untrusted", pageToolchains}, {"m48-toolchain-project-trusted", pageToolchains}, {"m49-toolchain-project-trust-click", pageToolchains}, {"m50-toolchain-project-trust-tip", pageToolchains}, + {"m51-toolchain-provider-installation", pageToolchains}, {"fonts", pageFonts}, {"21-settings-language-popup", pageGeneral}, {"30-settings-history", pageGeneral}, {"m46-history-default-rules-help", pageGeneral}, {"35-settings-search", pageEditor}, {"m35-editor-tab-layout", pageEditor}, {"m25-project-open-mode", pageGeneral}, {"m29-editor-font-menu", pageFonts}, {"m38-plugin-management-menu", pagePlugins}, {"m42-plugin-auto-update-on", pagePlugins}, @@ -215,6 +216,8 @@ func TestVisualSettings(t *testing.T) { case "m45-toolchain-custom-directory": d.click(text("desktop.buildSettings.addDirectory")) d.pump() + case "m51-toolchain-provider-installation": + d.until("the provider installation", func() bool { return d.has("/fixture/provider/compiler") }) case "m47-toolchain-project-untrusted", "m48-toolchain-project-trusted", "m49-toolchain-project-trust-click", "m50-toolchain-project-trust-tip": d.until("the project scope", func() bool { return w.toolchains.projectName() != "" }) d.pump() @@ -335,6 +338,19 @@ func visualToolchainLoader(scenarioID string) ToolchainLoader { }}, } switch scenarioID { + case "m51-toolchain-provider-installation": + snapshot := fixtureSnapshot() + snapshot.Root = "" + tool := &snapshot.Tools[0] + const provider = "dev.example:discovery" + home := "/fixture/provider/compiler" + tool.PluginName = "Example Toolchain" + tool.Providers = []string{provider} + tool.AutomaticHome = home + tool.Automatic = &core.ToolchainSelection{Home: &home, Executable: home + "/bin/compiler", Version: "2.0.0", Provider: provider, Layer: "global"} + tool.Effective = tool.Automatic + tool.Installations = []core.ToolchainInstallation{{Home: home, Version: "2.0.0", Provider: provider}} + return &scopedToolchainLoader{fakeToolchainLoader{snapshot: snapshot}} case "m47-toolchain-project-untrusted", "m49-toolchain-project-trust-click", "m50-toolchain-project-trust-tip": return &trustToolchainLoader{globalSnapshot: global, untrusted: untrusted, trustedSnapshot: trusted} case "m48-toolchain-project-trusted": diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index 3581eadf1..c592c5fc2 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -5,9 +5,11 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "path/filepath" + "slices" "strings" "sync/atomic" @@ -67,6 +69,14 @@ func PluginNames(manifests []json.RawMessage) map[string]string { // 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) { + snapshot, err := load(ctx, kernel, root, directory, manifests, options) + if errors.Is(err, errProviderGenerationChanged) { + return load(ctx, kernel, root, directory, manifests, options) + } + return snapshot, err +} + +func load(ctx context.Context, kernel Kernel, root, directory string, manifests []json.RawMessage, options Options) (Snapshot, error) { if kernel == nil { return Snapshot{}, fmt.Errorf("toolchain: no Core client") } @@ -98,6 +108,12 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if err != nil { return Snapshot{}, err } + if options.Providers != nil { + options.providerVersions, err = providerVersions(manifests) + if err != nil { + return Snapshot{}, err + } + } plan, err := kernel.ToolchainDiscoveryPlanOf(ctx, registryRequest, workspace.platform) if err != nil { return Snapshot{}, err @@ -126,7 +142,12 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests source: captured, } sequence := loadSequence.Add(1) + var rounds []*providerRound for index, planned := range plan.Tools { + if len(options.DiscoveryTools) > 0 && !slices.Contains(options.DiscoveryTools, planned.Tool) && + !slices.Contains(options.DiscoveryTools, planned.PluginID+":"+planned.Tool) { + continue + } if ctx.Err() != nil { return Snapshot{}, ctx.Err() } @@ -144,22 +165,21 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests return Snapshot{}, err } tool := Tool{ - ID: planned.Tool, - DisplayName: definition.DisplayName, - PluginID: planned.PluginID, - PluginName: pluginNames[planned.PluginID], - Category: definition.Category, - Audience: definition.Audience, - ManagedRuntime: options.ManagedTools[planned.Tool] != "" && options.ManagedTools[planned.Tool] == planned.PluginID, - ManagedRuntimeHomes: uniqueSorted(prepared.managedHomes), - Providers: planned.Providers, - Shell: prepared.candidates.Shell, - Installations: prepared.candidates.Installations, - Skipped: prepared.candidates.Skipped, - Trace: resolution.Trace, - Unmet: resolution.Unmet, - Conflicts: resolution.Conflicts, - ProviderQueriesUnsupported: len(planned.Providers) > 0, + ID: planned.Tool, + DisplayName: definition.DisplayName, + PluginID: planned.PluginID, + PluginName: pluginNames[planned.PluginID], + Category: definition.Category, + Audience: definition.Audience, + ManagedRuntime: options.ManagedTools[planned.Tool] != "" && options.ManagedTools[planned.Tool] == planned.PluginID, + ManagedRuntimeHomes: uniqueSorted(prepared.managedHomes), + Providers: planned.Providers, + Shell: prepared.candidates.Shell, + Installations: prepared.candidates.Installations, + Skipped: prepared.candidates.Skipped, + Trace: resolution.Trace, + Unmet: resolution.Unmet, + Conflicts: resolution.Conflicts, } if pin != nil { tool.Pin = pin @@ -224,8 +244,18 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests } } snapshot.Tools = append(snapshot.Tools, tool) + if prepared.providerRound != nil { + rounds = append(rounds, prepared.providerRound) + } + } + for _, round := range rounds { + if err := options.Providers.check(ctx, round, options.ProviderScope); err != nil { + return Snapshot{}, err + } + } + if len(options.DiscoveryTools) == 0 { + appendManagedDependencies(&snapshot, pluginNames, options.ManagedDependencies) } - appendManagedDependencies(&snapshot, pluginNames, options.ManagedDependencies) return snapshot, nil } @@ -314,6 +344,14 @@ func managedDependencyToolID(pluginID, depID string) string { // 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) { + selection, err := resolve(ctx, kernel, root, directory, tool, minimumVersion, fixed, manifests, options) + if errors.Is(err, errProviderGenerationChanged) { + return resolve(ctx, kernel, root, directory, tool, minimumVersion, fixed, manifests, options) + } + return selection, err +} + +func resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumVersion string, fixed *Fixed, manifests []json.RawMessage, options Options) (Selection, error) { if kernel == nil { return Selection{}, fmt.Errorf("toolchain: no Core client") } @@ -338,6 +376,12 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if err != nil { return Selection{}, err } + if options.Providers != nil { + options.providerVersions, err = providerVersions(manifests) + if err != nil { + return Selection{}, err + } + } plan, err := kernel.ToolchainDiscoveryPlanOf(ctx, registryRequest, workspace.platform) if err != nil { return Selection{}, err @@ -361,6 +405,9 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if !ok { continue } + // A runtime operation with an explicit pin or fixed choice does not query + // providers that cannot affect the choice. + options.skipPinnedProviders = true prepared, _, _, err := prepareTool(ctx, kernel, workspace, registryRequest, captured.document, planned, definition, directory, plan.Limits.Ancestors, projectCodeAllowed, options, fixed) if err != nil { return Selection{}, err @@ -370,6 +417,11 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if err != nil { return Selection{}, err } + if prepared.providerRound != nil { + if err := options.Providers.check(ctx, prepared.providerRound, options.ProviderScope); err != nil { + return Selection{}, err + } + } if resolution.Outcome.Kind != "resolved" || resolution.Outcome.Selection == nil { code := "notFound" if resolution.Outcome.Reason != nil && resolution.Outcome.Reason.Code != "" { @@ -383,6 +435,8 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV } type preparedTool struct { + providerRound *providerRound + queries []core.ToolchainQuery globalDefault *core.ToolchainGlobalDefault definition core.ToolchainToolDefinition candidates core.ToolchainCandidates @@ -470,32 +524,10 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } prepared.commandHomes = commandHomes(workspace, definition) for _, home := range uniqueSorted(evidenceHomes) { - workspace.observe(home) - for _, layout := range definition.ExecutableLayouts { - if !platformMatches(layout.Platforms, workspace.platform) { - continue - } - workspace.observe(filepath.Join(home, filepath.FromSlash(layout.Path))) - } - for _, template := range definition.PathPrepend { - if name, ok := prependPath(home, template); ok { - workspace.observe(name) - } - } + workspace.observeToolHome(home, definition) } for _, home := range uniqueSorted(valuesOf(prepared.commandHomes)) { - workspace.observe(home) - for _, layout := range definition.ExecutableLayouts { - if !platformMatches(layout.Platforms, workspace.platform) { - continue - } - workspace.observe(filepath.Join(home, filepath.FromSlash(layout.Path))) - } - for _, template := range definition.PathPrepend { - if name, ok := prependPath(home, template); ok { - workspace.observe(name) - } - } + workspace.observeToolHome(home, definition) } if prepared.fixed != nil && prepared.fixed.Executable != "" { fact := workspace.observe(prepared.fixed.Executable) @@ -503,22 +535,30 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis workspace.observe(fact.CanonicalPath) } } + var providerInstallations []core.ToolchainProviderInstallation + if options.Providers != nil && len(planned.Providers) > 0 && fixed == nil && !(pin != nil && options.skipPinnedProviders) { + prepared.providerRound, prepared.queries, providerInstallations, err = options.Providers.capture(ctx, workspace, registry, directory, planned, definition, options.ProviderScope, options.providerVersions) + if err != nil { + return prepared, nil, "", err + } + } prepared.facts = workspace.all() request := core.ToolchainCandidatesRequest{ - Global: options.Global, - Registry: registry, - Tool: planned.Tool, - Platform: workspace.platform, - WorkspaceRoot: workspace.root, - WorkspaceRoots: workspace.workspaceRoots, - Filesystem: prepared.facts, - MinimumVersion: options.MinimumVersion, - SystemInstallations: prepared.installations, - Environment: prepared.environment, - CommandHomes: prepared.commandHomes, - Fixed: prepared.fixed, - ProjectCodeAllowed: projectCodeAllowed, + Global: options.Global, + Registry: registry, + Tool: planned.Tool, + Platform: workspace.platform, + WorkspaceRoot: workspace.root, + WorkspaceRoots: workspace.workspaceRoots, + Filesystem: prepared.facts, + MinimumVersion: options.MinimumVersion, + SystemInstallations: prepared.installations, + ProviderInstallations: providerInstallations, + Environment: prepared.environment, + CommandHomes: prepared.commandHomes, + Fixed: prepared.fixed, + ProjectCodeAllowed: projectCodeAllowed, } candidates, err := kernel.ToolchainCandidatesOf(ctx, request) if err != nil { @@ -599,6 +639,11 @@ func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, regis Generation: loadSequence.Add(1), Fixed: prepared.fixed, } + if prepared.providerRound != nil { + request.Generation = prepared.providerRound.generation + request.Context = prepared.providerRound.context + request.Queries = prepared.queries + } resolution, err := kernel.ResolveToolchain(ctx, request) if err != nil || !projectCodeAllowed { return resolution, err @@ -635,7 +680,6 @@ func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } } request.Probes = prepared.probes - request.Generation = loadSequence.Add(1) request.OperationID = operationID + "-project" return kernel.ResolveToolchain(ctx, request) } diff --git a/desktop/internal/toolchain/provider.go b/desktop/internal/toolchain/provider.go new file mode 100644 index 000000000..32b78300b --- /dev/null +++ b/desktop/internal/toolchain/provider.go @@ -0,0 +1,396 @@ +package toolchain + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// ProviderScope binds a query to the host's open project context. A nil scope +// is only usable for discovery in global mode. +type ProviderScope struct { + Context core.ToolchainQueryContext + RootID func(pluginID string) string + Validate func() error +} + +// ProviderClient owns a window's provider reply cache. It stores raw replies, +// never authority to execute a tool. Every use captures fresh evidence and +// validates the reply again in Core. +type ProviderClient struct { + Request func(ctx context.Context, pluginID, version string, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) + FailureReply func(context.Context, core.ToolchainQueryParams, string) (core.ToolchainProviderReply, error) + Decode func(context.Context, core.ToolchainQuery) (core.ToolchainProviderSnapshot, error) + Failed func(context.Context, error) + + mu sync.Mutex + revision uint64 + cache map[providerCacheKey]*providerRound +} + +const ( + providerCacheEntries = 8 + providerCacheBytes = 1 << 20 + providerReplyBytes = 1 << 20 + providerRoundBytes = 2 << 20 + providerFactsLimit = 16384 + providerRoundTimeout = 15 * time.Second +) + +type providerCacheKey struct { + registry [sha256.Size]byte + platform string + root string + roots [sha256.Size]byte + context core.ToolchainQueryContext + directory string + tool string +} + +type providerAnswer struct { + pluginID string + request json.RawMessage + response json.RawMessage +} + +type providerRound struct { + generation uint64 + revision uint64 + started time.Time + context json.RawMessage + answers []providerAnswer + observed *providerObservation +} + +var errProviderGenerationChanged = errors.New("toolchain: provider generation changed during discovery") + +// Invalidate clears every provider round when the workspace or plugin roster +// changes. Detached observers are released by the returned cleanup function. +func (p *ProviderClient) Invalidate() func() { + if p == nil { + return func() {} + } + p.mu.Lock() + p.revision++ + retired := p.cache + p.cache = nil + p.mu.Unlock() + return func() { + for _, round := range retired { + round.observed.close() + } + } +} + +func (p *ProviderClient) round( + ctx context.Context, w *workspace, registry json.RawMessage, + planned core.ToolchainDiscoveryPlanTool, directory string, scope *ProviderScope, + versions map[string]string, +) (*providerRound, providerCacheKey, error) { + key := providerCacheKey{ + registry: sha256.Sum256(registry), platform: w.platform, root: w.root, + roots: sha256.Sum256([]byte(strings.Join(w.workspaceRoots, "\x00"))), directory: directory, tool: planned.Tool, + } + contextJSON := json.RawMessage("null") + if w.root != "" { + if scope == nil { + return nil, key, nil + } + if err := scope.Validate(); err != nil { + return nil, key, err + } + key.context = scope.Context + data, err := json.Marshal(scope.Context) + if err != nil { + return nil, key, err + } + contextJSON = data + } + p.mu.Lock() + cached := p.cache[key] + revision := p.revision + p.mu.Unlock() + if cached != nil && time.Since(cached.started) < time.Minute && cached.observed.current() { + return cached, key, nil + } + + round := &providerRound{ + generation: loadSequence.Add(1), revision: revision, started: time.Now(), context: contextJSON, + } + queryCtx, cancel := context.WithTimeout(ctx, providerRoundTimeout) + defer cancel() + roundBytes := 0 + for index, qualified := range planned.Providers { + pluginID, providerID, ok := strings.Cut(qualified, ":") + if !ok || pluginID == "" || providerID == "" { + return nil, key, errors.New("toolchain: Core returned an invalid provider identity") + } + params := core.ToolchainQueryParams{ + OperationID: fmt.Sprintf("toolchain-query-%d-%d", round.generation, index), + Generation: round.generation, ProviderID: providerID, Authority: map[string]string{"kind": "local"}, + Tools: []string{planned.Tool}, + } + if w.root != "" { + params.Context = &scope.Context + params.Workspace = &core.ToolchainQueryWorkspace{RootID: scope.RootID(pluginID), Root: w.root, Directory: directory} + } + var reply core.ToolchainProviderReply + err := queryCtx.Err() + if err == nil { + version := versions[pluginID] + if version == "" { + return nil, key, errors.New("toolchain: Core returned a provider outside the manifest snapshot") + } + reply, err = p.Request(queryCtx, pluginID, version, params) + } + // The round's budget is separate from the caller's lifetime. Core + // can still resolve completed replies and local candidates. + if errors.Is(err, context.DeadlineExceeded) && queryCtx.Err() == context.DeadlineExceeded && ctx.Err() == nil { + reply, err = p.FailureReply(ctx, params, core.ToolchainProviderTimeout) + } + if err != nil { + return nil, key, err + } + roundBytes += len(reply.Response) + if len(reply.Response) > providerReplyBytes || roundBytes > providerRoundBytes { + return nil, key, errors.New("toolchain: provider reply exceeds the native observation budget") + } + request, err := json.Marshal(struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params core.ToolchainQueryParams `json:"params"` + }{"2.0", reply.ID, "toolchains/query", params}) + if err != nil { + return nil, key, err + } + round.answers = append(round.answers, providerAnswer{pluginID, request, reply.Response}) + } + return round, key, nil +} + +// The registry digest includes these same manifest versions, so a response can +// only be cached under the package snapshot used to obtain it. +func providerVersions(manifests []json.RawMessage) (map[string]string, error) { + versions := make(map[string]string, len(manifests)) + for _, manifest := range manifests { + var identity struct { + ID string `json:"id"` + Version string `json:"version"` + } + if err := json.Unmarshal(manifest, &identity); err != nil { + return nil, err + } + versions[identity.ID] = identity.Version + } + return versions, nil +} + +// Observe only the inert paths required by the contract. Core still verifies +// each path and type, each installation and statement, and the reply envelope. +func (a providerAnswer) observe(w *workspace, definition core.ToolchainToolDefinition) ([]string, error) { + var envelope struct { + Result struct { + Installations []struct { + Tool string `json:"tool"` + Home string `json:"home"` + } `json:"installations"` + Statements []struct { + Tool string `json:"tool"` + Source string `json:"source"` + } `json:"statements"` + Watch []string `json:"watch"` + } `json:"result"` + } + if err := json.Unmarshal(a.response, &envelope); err != nil { + return nil, err + } + result := envelope.Result + if len(result.Installations) > 512 || len(result.Statements) > 256 || len(result.Watch) > 256 { + return nil, errors.New("toolchain: provider reply exceeds native path observation limits") + } + paths := make([]string, 0, len(result.Watch)+len(result.Statements)) + for _, value := range result.Installations { + if value.Tool == definition.ID && providerAbsolutePath(value.Home) { + w.observeToolHome(value.Home, definition) + if len(w.facts) > providerFactsLimit { + return nil, errors.New("toolchain: provider reply exceeds native filesystem fact limits") + } + } + } + for _, value := range result.Statements { + if value.Tool == definition.ID && providerAbsolutePath(value.Source) { + w.observe(value.Source) + paths = append(paths, value.Source) + } + } + for _, name := range result.Watch { + if providerAbsolutePath(name) { + w.observe(name) + paths = append(paths, name) + } + } + if len(w.facts) > providerFactsLimit { + return nil, errors.New("toolchain: provider reply exceeds native filesystem fact limits") + } + return paths, nil +} + +func providerAbsolutePath(path string) bool { + return len(path) <= 4096 && !strings.ContainsRune(path, 0) && + filepath.IsAbs(path) && filepath.Clean(path) == filepath.FromSlash(path) +} + +func (w *workspace) observeToolHome(home string, definition core.ToolchainToolDefinition) { + w.observe(home) + for _, layout := range definition.ExecutableLayouts { + if platformMatches(layout.Platforms, w.platform) { + w.observe(filepath.Join(home, filepath.FromSlash(layout.Path))) + } + } + for _, template := range definition.PathPrepend { + if name, ok := prependPath(home, template); ok { + w.observe(name) + } + } +} + +func (p *ProviderClient) capture( + ctx context.Context, w *workspace, registry json.RawMessage, directory string, + planned core.ToolchainDiscoveryPlanTool, definition core.ToolchainToolDefinition, scope *ProviderScope, + versions map[string]string, +) (*providerRound, []core.ToolchainQuery, []core.ToolchainProviderInstallation, error) { + round, key, err := p.round(ctx, w, registry, planned, directory, scope, versions) + if err != nil || round == nil { + return nil, nil, nil, err + } + if w.root != "" && directory != "." { + w.observe(filepath.Join(w.root, filepath.FromSlash(directory))) + } + var paths []string + for _, answer := range round.answers { + observed, err := answer.observe(w, definition) + if err != nil { + return nil, nil, nil, err + } + paths = append(paths, observed...) + } + facts := w.all() + var queries []core.ToolchainQuery + var installations []core.ToolchainProviderInstallation + cacheable := true + for _, answer := range round.answers { + query := core.ToolchainQuery{ + Registry: registry, PluginID: answer.pluginID, + Request: answer.request, Response: answer.response, + CurrentGeneration: round.generation, Filesystem: facts, + Platform: w.platform, WorkspaceRoots: w.workspaceRoots, + } + snapshot, err := p.Decode(ctx, query) + if err != nil { + var rejection *core.MarketplaceRejection + if !errors.As(err, &rejection) || (rejection.Code != core.ToolchainProviderUnavailable && rejection.Code != core.ToolchainProviderTimeout) { + return nil, nil, nil, err + } + if p.Failed != nil { + p.Failed(ctx, err) + } + cacheable = false + } + paths = append(paths, snapshot.Watch...) + installations = append(installations, snapshot.Installations...) + queries = append(queries, query) + } + if err := p.check(ctx, round, scope); err != nil { + return nil, nil, nil, err + } + if cacheable && round.observed == nil { + if err := p.remember(ctx, key, round, paths); err != nil { + return nil, nil, nil, err + } + } + return round, queries, installations, nil +} + +func (p *ProviderClient) check(ctx context.Context, round *providerRound, scope *ProviderScope) error { + if err := ctx.Err(); err != nil { + return err + } + if scope != nil { + if err := scope.Validate(); err != nil { + return err + } + } + if round == nil { + return nil + } + p.mu.Lock() + current := p.revision == round.revision + p.mu.Unlock() + if !current || (round.observed != nil && !round.observed.current()) { + return errProviderGenerationChanged + } + return nil +} + +func (p *ProviderClient) remember(ctx context.Context, key providerCacheKey, round *providerRound, paths []string) error { + bytes := 0 + for _, answer := range round.answers { + bytes += len(answer.request) + len(answer.response) + } + if bytes > providerCacheBytes { + return nil + } + observed, err := observeProviderInputs(paths, round.started) + if errors.Is(err, errProviderGenerationChanged) { + return err + } + if err != nil { + if p.Failed != nil { + p.Failed(ctx, err) + } + return nil + } + if observed == nil { + return nil + } + round.observed = observed + p.mu.Lock() + if p.revision != round.revision { + p.mu.Unlock() + observed.close() + return nil + } + if p.cache == nil { + p.cache = make(map[providerCacheKey]*providerRound) + } + retired := p.cache[key] + if retired != nil && retired.generation > round.generation { + p.mu.Unlock() + observed.close() + return nil + } + if retired == nil && len(p.cache) >= providerCacheEntries { + var oldest providerCacheKey + for key, cached := range p.cache { + if retired == nil || cached.generation < retired.generation { + oldest, retired = key, cached + } + } + delete(p.cache, oldest) + } + p.cache[key] = round + p.mu.Unlock() + if retired != nil { + retired.observed.close() + } + return nil +} diff --git a/desktop/internal/toolchain/provider_observation.go b/desktop/internal/toolchain/provider_observation.go new file mode 100644 index 000000000..b850eb4b6 --- /dev/null +++ b/desktop/internal/toolchain/provider_observation.go @@ -0,0 +1,165 @@ +package toolchain + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "time" + + "github.com/vivaui/viva/app" +) + +// Each round uses at most this many native registrations, including parent +// directories used to follow atomic replacements and missing inputs. +const providerWatchDirectories = 32 + +type providerObservation struct { + mu sync.Mutex + invalid bool + watches []providerDirectory + facts map[string]os.FileInfo +} + +type providerDirectory struct { + watch *app.DirectoryWatch + names map[string]bool + all bool +} + +type providerWatchTarget struct { + names map[string]bool + all bool +} + +// Observe existing directories and the nearest existing ancestors of missing +// paths. The latter watches the next path component being created. +func observeProviderInputs(paths []string, queryStarted time.Time) (*providerObservation, error) { + targets := make(map[string]providerWatchTarget) + facts := make(map[string]os.FileInfo) + for _, name := range uniqueSorted(paths) { + name = filepath.FromSlash(name) + if !filepath.IsAbs(name) { + continue + } + path := name + var prior os.FileInfo + for { + info, err := os.Stat(path) + if err == nil { + if path == name && !info.ModTime().Before(queryStarted) { + return nil, errProviderGenerationChanged + } + prior = info + break + } + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + parent := filepath.Dir(path) + if parent == path { + return nil, nil + } + path = parent + } + facts[path] = prior + if path != name { + facts[name] = nil + } + if path == name && prior.IsDir() { + target := targets[path] + target.all = true + targets[path] = target + } + if path == name { + path = filepath.Dir(name) + } + if name != path { + relative, err := filepath.Rel(path, name) + if err != nil { + return nil, err + } + next, _, _ := strings.Cut(relative, string(filepath.Separator)) + target := targets[path] + if target.names == nil { + target.names = make(map[string]bool) + } + target.names[nativeFileKey(next)] = true + targets[path] = target + } + if len(targets) > providerWatchDirectories { + return nil, nil + } + } + observation := &providerObservation{facts: facts} + for name, target := range targets { + // The watcher queues input changes. Consumers drain on demand off the + // window thread; the notification callback never blocks or closes it. + watch, err := app.WatchDirectory(name, func() {}) + if err != nil { + observation.close() + return nil, err + } + observation.watches = append(observation.watches, providerDirectory{watch: watch, names: target.names, all: target.all}) + } + if !observation.current() { + observation.close() + return nil, errProviderGenerationChanged + } + return observation, nil +} + +func (o *providerObservation) current() bool { + o.mu.Lock() + defer o.mu.Unlock() + for path, previous := range o.facts { + current, err := os.Stat(path) + // log-exempt: 预期的缺失:不存在的输入也是可观察状态。 + if previous == nil && errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil || previous == nil || !os.SameFile(previous, current) || previous.Mode() != current.Mode() || + previous.Size() != current.Size() || !previous.ModTime().Equal(current.ModTime()) { + o.invalid = true + break + } + } + return !o.invalid && o.drainLocked() +} + +func (o *providerObservation) drainLocked() bool { + for _, entry := range o.watches { + changes := entry.watch.Changes(nil) + if changes.Resync || (entry.all && len(changes.Names) != 0) { + o.invalid = true + return false + } + for _, name := range changes.Names { + if entry.names[nativeFileKey(name)] { + o.invalid = true + return false + } + } + } + return true +} + +func (o *providerObservation) close() { + o.mu.Lock() + o.drainLocked() + watches := o.watches + o.watches = nil + o.mu.Unlock() + for _, entry := range watches { + entry.watch.Close() + } +} + +func nativeFileKey(name string) string { + if runtime.GOOS == "windows" { + return strings.ToLower(name) + } + return name +} diff --git a/desktop/internal/toolchain/provider_test.go b/desktop/internal/toolchain/provider_test.go new file mode 100644 index 000000000..c6972e7b2 --- /dev/null +++ b/desktop/internal/toolchain/provider_test.go @@ -0,0 +1,77 @@ +package toolchain + +import ( + "context" + "encoding/json" + "errors" + "slices" + "testing" + "testing/synctest" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestToolchainProviderRoundPreservesAnswersAtItsDeadline(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + var contacted, timedOut []string + success := core.ToolchainProviderReply{ID: json.RawMessage(`"ready"`), Response: json.RawMessage(`{"result":{}}`)} + timeout := core.ToolchainProviderReply{ID: json.RawMessage(`"timeout"`), Response: json.RawMessage(`{"error":{}}`)} + client := ProviderClient{ + Request: func(query context.Context, _, version string, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { + if version != "1.0.0" { + t.Fatalf("queried provider version %q", version) + } + contacted = append(contacted, params.ProviderID) + if params.ProviderID == "ready" { + return success, nil + } + <-query.Done() + return core.ToolchainProviderReply{}, query.Err() + }, + FailureReply: func(replyContext context.Context, params core.ToolchainQueryParams, code string) (core.ToolchainProviderReply, error) { + if replyContext.Err() != nil || code != core.ToolchainProviderTimeout { + t.Fatalf("failure reply context = %v, code = %q", replyContext.Err(), code) + } + timedOut = append(timedOut, params.ProviderID) + return timeout, nil + }, + } + planned := core.ToolchainDiscoveryPlanTool{Tool: "fixture", Providers: []string{"test:ready", "test:slow", "test:queued"}} + round, _, err := client.round(ctx, &workspace{platform: "macos"}, nil, planned, ".", nil, map[string]string{"test": "1.0.0"}) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(contacted, []string{"ready", "slow"}) || !slices.Equal(timedOut, []string{"slow", "queued"}) { + t.Fatalf("contacted %v, timed out %v", contacted, timedOut) + } + if len(round.answers) != 3 || !slices.Equal(round.answers[0].response, success.Response) || + !slices.Equal(round.answers[1].response, timeout.Response) || !slices.Equal(round.answers[2].response, timeout.Response) { + t.Fatalf("round answers = %+v", round.answers) + } + }) +} + +func TestToolchainProviderRoundHonorsCallerDeadline(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + client := ProviderClient{ + Request: func(query context.Context, _, _ string, _ core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { + <-query.Done() + return core.ToolchainProviderReply{}, query.Err() + }, + FailureReply: func(context.Context, core.ToolchainQueryParams, string) (core.ToolchainProviderReply, error) { + t.Fatal("the caller's deadline was converted into a provider failure") + return core.ToolchainProviderReply{}, nil + }, + } + planned := core.ToolchainDiscoveryPlanTool{Tool: "fixture", Providers: []string{"test:slow"}} + round, _, err := client.round(ctx, &workspace{platform: "macos"}, nil, planned, ".", nil, map[string]string{"test": "1.0.0"}) + if round != nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("round = %+v, error = %v", round, err) + } + }) +} diff --git a/desktop/internal/toolchain/toolchain.go b/desktop/internal/toolchain/toolchain.go index cc38bf9c0..59126e02e 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -76,8 +76,7 @@ type Tool struct { // Reason is Core's stable code when no installation applies, empty when the // tool resolved. Reason string `json:"reason,omitempty"` - // 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 are the qualified provider IDs that declared this tool. Providers []string `json:"providers"` Pin *core.ToolchainPin `json:"pin,omitempty"` @@ -100,7 +99,6 @@ type Tool struct { Conflicts []json.RawMessage `json:"conflicts"` // Hidden lists provider declarations the host cannot query yet, so the // settings page says the tool may have more installations than shown. - ProviderQueriesUnsupported bool `json:"providerQueriesUnsupported"` } // Snapshot is everything one settings load read for one project directory. @@ -123,6 +121,17 @@ 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 { + // Providers are the enabled plugins' on-demand query transport and cache. + // ProviderScope is required when Providers queries an open project. + Providers *ProviderClient + ProviderScope *ProviderScope + providerVersions map[string]string + skipPinnedProviders bool + + // DiscoveryTools restricts Load to the consumer's requested tool IDs. An + // empty list loads the complete settings catalog. + DiscoveryTools []string + // Global permits discovery without any project; GlobalRoot owns the native SDK // registry and per-workspace toolchain trust in user application settings. Global bool diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f49c50bb3..43da31d25 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -981,6 +981,10 @@ func (a *App) openPlugins(options Options) { service.LanguageTool = a.resolveLanguageTool service.LogDirectory = a.pluginLogDirectory service.RecordFailed = a.pluginOperationRecordFailed + service.ToolchainIssue = func(ctx context.Context, err error) { + a.backgroundFailedIn(ctx, "toolchain_provider_discovery", err) + } + service.RuntimeIssue = a.recordPluginRuntimeIssue service.SetRuntimeLanguage(a.language().Code()) if err := service.AttachWorkbench(pluginWorkbench{app: a}); err != nil { diff --git a/desktop/internal/workbench/new_project.go b/desktop/internal/workbench/new_project.go index 519d56d87..ad6631770 100644 --- a/desktop/internal/workbench/new_project.go +++ b/desktop/internal/workbench/new_project.go @@ -313,9 +313,8 @@ func (a *App) loadProjectCatalog(ctx context.Context, _ struct{}) (catalogResult } // loadProjectTools lists the installations of each tool a generator's fields -// pick. New Project has no workspace, so discovery runs in an empty temporary -// directory: no project pin applies, exactly as the settings page shows a tool -// before a project chooses one. +// pick. New Project has no workspace, so discovery uses the same global +// scope as the settings page shows before a project opens. func (a *App) loadProjectTools(ctx context.Context, tools []string) (map[string]toolList, error) { if a.projectToolLists != nil { return a.projectToolLists(ctx, tools) @@ -324,12 +323,9 @@ func (a *App) loadProjectTools(ctx context.Context, tools []string) (map[string] if err != nil && len(manifests) == 0 { return nil, err } - root, mkErr := os.MkdirTemp("", "lithe-new-project-tools-*") - if mkErr != nil { - return nil, mkErr - } - defer os.RemoveAll(root) - snapshot, loadErr := toolchain.Load(ctx, a.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform()}) + options := a.toolchainOptions(ctx, "", manifests) + options.DiscoveryTools = tools + snapshot, loadErr := toolchain.Load(ctx, a.kernel, "", ".", manifests, options) if loadErr != nil { return nil, loadErr } diff --git a/desktop/internal/workbench/new_project_test.go b/desktop/internal/workbench/new_project_test.go index 8aa1ec0ff..8e3f96884 100644 --- a/desktop/internal/workbench/new_project_test.go +++ b/desktop/internal/workbench/new_project_test.go @@ -15,8 +15,11 @@ import ( "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/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/projectgen" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -71,6 +74,95 @@ func (h *harness) openNewProjectSheet() { var generatorFixtures = contractfixture.Path("fixtures/project-generators") +const ( + generatorToolPlugin = "dev.lithe.test.generator-tools" + generatorToolWanted = "fixture-wanted" + generatorToolUnrelated = "fixture-unrelated" +) + +type generatorToolKernel struct{ *testKernel } + +func (k generatorToolKernel) ToolchainCandidatesOf(_ context.Context, request core.ToolchainCandidatesRequest) (core.ToolchainCandidates, error) { + if request.Tool == generatorToolUnrelated { + return core.ToolchainCandidates{}, errors.New("unrelated tool discovery failed") + } + return core.ToolchainCandidates{Installations: []core.ToolchainInstallation{{Home: "fixture-home", Version: "1.0"}}}, nil +} + +func TestNewProjectOnlyDiscoversToolsRequestedByTheForm(t *testing.T) { + client := core.NewClient() + preferences, pluginRoot := store.At(t.TempDir()), t.TempDir() + service, err := pluginservice.Open(client, preferences, pluginRoot) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { service.DetachWorkspaces()() }) + fixture, err := os.ReadFile("../toolchain/testdata/compiler.plugin.json") + if err != nil { + t.Fatal(err) + } + var manifest map[string]json.RawMessage + if err := json.Unmarshal(fixture, &manifest); err != nil { + t.Fatal(err) + } + manifest["id"], err = json.Marshal(generatorToolPlugin) + if err != nil { + t.Fatal(err) + } + var tools []json.RawMessage + if err := json.Unmarshal(manifest["toolDefinitions"], &tools); err != nil { + t.Fatal(err) + } + var template map[string]json.RawMessage + if err := json.Unmarshal(tools[0], &template); err != nil { + t.Fatal(err) + } + delete(template, "discovery") + delete(template, "homeLayouts") + tools = nil + for _, id := range []string{generatorToolWanted, generatorToolUnrelated} { + template["id"], err = json.Marshal(id) + if err != nil { + t.Fatal(err) + } + definition, err := json.Marshal(template) + if err != nil { + t.Fatal(err) + } + tools = append(tools, definition) + } + manifest["toolDefinitions"], err = json.Marshal(tools) + if err != nil { + t.Fatal(err) + } + data, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + dir := filepath.Join(pluginRoot, generatorToolPlugin, "1.0.0") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, pluginpkg.ManifestFile), data, 0o600); err != nil { + t.Fatal(err) + } + if err := pluginstate.New(preferences).SetEnabled(generatorToolPlugin, true); err != nil { + t.Fatal(err) + } + a := &App{kernel: generatorToolKernel{&testKernel{Client: client}}, store: preferences, plugins: service} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for _, name := range []string{generatorToolWanted, generatorToolPlugin + ":" + generatorToolWanted} { + lists, err := a.loadProjectTools(ctx, []string{name}) + if err != nil { + t.Fatal(err) + } + if installations := lists[name].Installations; len(installations) != 1 || installations[0].Home != "fixture-home" { + t.Errorf("tool %s installations = %+v", name, installations) + } + } +} + func fixtureGeneratorPlugin(t *testing.T) pluginservice.GeneratorPlugin { t.Helper() data, err := os.ReadFile(filepath.Join(generatorFixtures, "project-generator.plugin.json")) diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index 6507fd8b6..accafd880 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -17,14 +17,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if readErr != nil { return selection, readErr } - managedHomes, managedTools, _ := s.app.managedToolchainOptions(ctx, manifests) - return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{ - Global: true, - GlobalRoot: s.app.globalToolchainRoot(), - Platform: buildPlatform(), - ManagedHomes: managedHomes, - ManagedTools: managedTools, - }) + return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, s.app.toolchainOptions(ctx, "", manifests)) } root := s.app.toolchainRoot.Load() if root == nil || snapshot.Root == "" { @@ -37,13 +30,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if err != nil { return selection, err } - managedHomes, managedTools, _ := s.app.managedToolchainOptions(ctx, manifests) - 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.globalToolchainRoot(), - ManagedHomes: managedHomes, - ManagedTools: managedTools, - }) + selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, s.app.toolchainOptions(ctx, snapshot.Root, manifests)) if err != nil { return selection, err } @@ -112,15 +99,7 @@ func (s settingsToolchains) LoadScope(ctx context.Context, scope string) (snapsh if err != nil { return snapshot, err } - managedHomes, managedTools, managedDeps := s.app.managedToolchainOptions(ctx, manifests) - return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, toolchain.Options{ - Global: true, - GlobalRoot: s.app.globalToolchainRoot(), - Platform: buildPlatform(), - ManagedHomes: managedHomes, - ManagedTools: managedTools, - ManagedDependencies: managedDeps, - }) + return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, s.app.toolchainOptions(ctx, "", manifests)) } func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain.Snapshot, error) { @@ -128,14 +107,7 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. if err != nil && len(manifests) == 0 { return toolchain.Snapshot{}, err } - managedHomes, managedTools, managedDeps := s.app.managedToolchainOptions(ctx, manifests) - return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{ - Platform: buildPlatform(), - GlobalRoot: s.app.globalToolchainRoot(), - ManagedHomes: managedHomes, - ManagedTools: managedTools, - ManagedDependencies: managedDeps, - }) + return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, s.app.toolchainOptions(ctx, root, manifests)) } // Save applies all draft changes in one Core edit, against the exact diff --git a/desktop/internal/workbench/toolchains.go b/desktop/internal/workbench/toolchains.go index 762add598..35163ae23 100644 --- a/desktop/internal/workbench/toolchains.go +++ b/desktop/internal/workbench/toolchains.go @@ -81,12 +81,14 @@ func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, to if directory == "" { directory = "." } - managedHomes, managedTools, _ := a.managedToolchainOptions(ctx, manifests) - return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, toolchain.Options{ - Platform: buildPlatform(), - GlobalRoot: a.globalToolchainRoot(), - ManagedHomes: managedHomes, - ManagedTools: managedTools, + return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, a.toolchainOptions(ctx, root, manifests)) +} + +func (a *App) toolchainOptions(ctx context.Context, root string, manifests []json.RawMessage) toolchain.Options { + homes, tools, dependencies := a.managedToolchainOptions(ctx, manifests) + return a.plugins.ToolchainOptions(root, toolchain.Options{ + Global: root == "", GlobalRoot: a.globalToolchainRoot(), Platform: buildPlatform(), + ManagedHomes: homes, ManagedTools: tools, ManagedDependencies: dependencies, }) } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 3de94534a..0ce7726a4 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -70,6 +70,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 搜索偏好 `/search.json` 由桌面原生存储适配器持有,最多64 KiB;只在用户应用/恢复默认时条件原子写回,打开页面不创建文件。它是用户状态,没有源码、版本、平台、架构或工具链复用身份,不跨工作树复制。搜索索引和未保存快照仅在当前进程内,绑定工作区、可见性与读取预算,关闭项目后释放,不写入安装目录。它们不改变代码签名或增量更新基线。`TestVisualSearchResults` 和 `TestVisualSearchPreferences` 的截图写入当前检出的 `.artifacts/search-visual/`,绑定本次源码、语言、主题和渲染环境,不跨工作树复制;Linux Desktop CI上传后由runner清理,不进入发行包。 +工具链提供方回包只在窗口进程内短期缓存。缓存由当前插件版本、工作区上下文和工具输入决定,关闭项目或停用插件时清理。原生文件观察器随缓存释放。该状态没有可复制的编译身份,不跨工作树复用,也不写入插件包或发行目录。 Linux Desktop CI 的工具链提供方截图写入当前检出的 `.artifacts/toolchain-provider-visual/`,按语言分目录,绑定本次源码、Go 工具链与固定的 Viva 和 Core 版本。截图上传后由运行器清理,不跨工作树复制,也不进入安装包。 + Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 Desktop CI 的 Build 命令发现截图由 `TestVisualBuildCommandDiscovery` 写入当前工作树的 `.artifacts/build-command-discovery-visual/`。该结果绑定提交、平台、Go 工具链和固定的 Viva 与 Core 版本,上传后由 CI 清理,不跨工作树复制,也不进入安装包。 diff --git a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json index 97507832f..58213b934 100644 --- a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json +++ b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json @@ -63,7 +63,7 @@ }, "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 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。 Viva 全局 SDK 页:运行 TestVisualSettings/33-settings-toolchains,使用 en、zh-Hans 和 dark/light 的生产无头窗口,核对无项目模式、自动实际值、多版本登记与全局默认选择。通过 run-go-tests-with-timing.mjs 记录单测试 HTML/JUnit;desktop-ci 的 macOS/Windows 每次上传四张图和计时报告。2026-11-15 本机 macOS 与 Windows 11 ARM64 来宾的 GNU x64 系统仿真均通过两个语言各 3 个计时结果,Windows 49 个 SDK/来源/诊断/资源定向用例通过;该证据不替代工具提供方与完整产品工作流验收,整体保持 partial/pending。 Windows #2042:TestToolchainCandidatesUseNativeShellPathsInUserProfiles 以真实 PATH 查找、真实有界版本进程和 Core 候选规则,覆盖 PATH-only/环境变量-only 及空格/中文用户目录;合成工具位于扫描目录之外,全局登记使用私有根。 通过现有 Windows CI 的 scripts/desktop/check.sh 运行;本机逐项计时报告覆盖这些合成场景,完整原生界面验收仍保持 pending。 2026-11-18(#2122):使用 dev.lithe.test.* 合成工具清单运行 TestUntrustedProjectEnvironmentNeverProbesWorkspaceExecutables、TestTrustedWorkspacePersistsInLocalSettingsOnlyAndResolvesSymlinkedVenv、TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories、TestProjectToolchainTrustSwitchGrantsAndRevokesImmediately 与 TestWorkbenchToolchainTrustPersistsLocallyLogsActionAndEnablesRuntimeResolution,验证未授权零探测、两跳符号链接虚拟环境字面路径保留、macOS 目录符号链接与 Windows 目录联接点指向外部时在探测前拒绝、本机 toolchains/global.json 原子保存与撤销(绝不写工作区 .lithe/)、performedIn 操作轨迹以及中英明暗无头截图 m47/m48;Windows 实机与完整原生 GUI 工作流保持 pending。", - "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 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。 Viva 2026-11-16:Build 页每个工具改为一个下拉框,默认回显当前选择(未固定时为“自动(实际目录)”),列出识别到的其他安装、已保存固定值和已校验目录;选“自定义…”才显示目录输入、浏览和“使用此目录”,校验通过后该目录成为列表项并被选中。无版本的安装不可选,在列表下以说明文字列出。自动化:TestToolchainListShowsAutomaticAndHidesTheDirectoryUntilCustom 及原有草稿/保存/冲突用例;截图 TestVisualSettings/33-settings-toolchains、m44-toolchain-directory-menu、m45-toolchain-custom-directory。原生验收仍 pending。 Viva 2026-11-16(#2032):toolchains.candidates 改为同时接收宿主找到的 PATH 命令所在目录(commandHomes),JAVA_HOME 等声明变量和 PATH 上的安装校验通过后以 host:shell 并入安装列表并按规范目录去重,新建项目的工具选择、设置页和运行配置因此能选到只配置在 PATH 或环境变量上的 JDK;自动层的选择不变。Core 回归 toolchain_candidates_offer_shell_homes_that_no_discovery_scan_covers(Lithe-core-rust#67),宿主回归 TestShellHomesAreInstallationsWithoutADiscoveryScan;两者都确认修复前失败。Windows 0.8.0 实机复现了缺陷,修复后的完整 Windows 客户端尚未实机验收,状态保持 pending。 Viva 2026-11-18(#2122):prepareTool 沿工作区祖先链观测 discoveryPlan 返回的 projectFiles、requires、home、中间父目录、pathPrepend 及软链目标;probeAll 在 ProjectCodeAllowed 为 false 时拒绝探测任何工作区内可执行文件;本机信任记录经 Core catalogState/editCatalog 保存在应用用户设置目录 toolchains/global.json,设置页项目作用域提供带 ⓘ 说明的显式信任开关并立即回读生效值,工作台 resolveToolchainSelection 同步读取同一本机信任状态。 Viva 2026-11-18(构建设置重构):工具链页按 docs/design/build-execution-settings.html 重做为“全局默认 / 当前项目”两个作用域、按类别或插件分组、需处理与已手动指定过滤,列表与详情两栏;详情显示当前生效的程序、版本与来源标签和安装列表(自动、发现的安装、手动目录),项目作用域在未信任时显示信任提示。筛选、分组和计数由 Core 设置投影(Lithe-core-rust#99)给出,一个插件可以注册多个 SDK。固定值本身不再算一个来源标签,只有其目录不在其他来源中时才标出提供方。自动化:toolchains_view_test.go、TestVisualSettings 的 33、m44–m49 场景。原生与 Windows 验收仍 pending。", + "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。提供方后端查询的现行证据见 plugin-toolchain-providers;本条 Windows 与完整 GUI/原生工作流仍保持 pending。 本轮通过外部 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 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。 Viva 2026-11-16:Build 页每个工具改为一个下拉框,默认回显当前选择(未固定时为“自动(实际目录)”),列出识别到的其他安装、已保存固定值和已校验目录;选“自定义…”才显示目录输入、浏览和“使用此目录”,校验通过后该目录成为列表项并被选中。无版本的安装不可选,在列表下以说明文字列出。自动化:TestToolchainListShowsAutomaticAndHidesTheDirectoryUntilCustom 及原有草稿/保存/冲突用例;截图 TestVisualSettings/33-settings-toolchains、m44-toolchain-directory-menu、m45-toolchain-custom-directory。原生验收仍 pending。 Viva 2026-11-16(#2032):toolchains.candidates 改为同时接收宿主找到的 PATH 命令所在目录(commandHomes),JAVA_HOME 等声明变量和 PATH 上的安装校验通过后以 host:shell 并入安装列表并按规范目录去重,新建项目的工具选择、设置页和运行配置因此能选到只配置在 PATH 或环境变量上的 JDK;自动层的选择不变。Core 回归 toolchain_candidates_offer_shell_homes_that_no_discovery_scan_covers(Lithe-core-rust#67),宿主回归 TestShellHomesAreInstallationsWithoutADiscoveryScan;两者都确认修复前失败。Windows 0.8.0 实机复现了缺陷,修复后的完整 Windows 客户端尚未实机验收,状态保持 pending。 Viva 2026-11-18(#2122):prepareTool 沿工作区祖先链观测 discoveryPlan 返回的 projectFiles、requires、home、中间父目录、pathPrepend 及软链目标;probeAll 在 ProjectCodeAllowed 为 false 时拒绝探测任何工作区内可执行文件;本机信任记录经 Core catalogState/editCatalog 保存在应用用户设置目录 toolchains/global.json,设置页项目作用域提供带 ⓘ 说明的显式信任开关并立即回读生效值,工作台 resolveToolchainSelection 同步读取同一本机信任状态。 Viva 2026-11-18(构建设置重构):工具链页按 docs/design/build-execution-settings.html 重做为“全局默认 / 当前项目”两个作用域、按类别或插件分组、需处理与已手动指定过滤,列表与详情两栏;详情显示当前生效的程序、版本与来源标签和安装列表(自动、发现的安装、手动目录),项目作用域在未信任时显示信任提示。筛选、分组和计数由 Core 设置投影(Lithe-core-rust#99)给出,一个插件可以注册多个 SDK。固定值本身不再算一个来源标签,只有其目录不在其他来源中时才标出提供方。自动化:toolchains_view_test.go、TestVisualSettings 的 33、m44–m49 场景。原生与 Windows 验收仍 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-toolchain-providers.json b/shared/platform-feature-matrix/features/plugin-toolchain-providers.json new file mode 100644 index 000000000..613802649 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-toolchain-providers.json @@ -0,0 +1,32 @@ +{ + "id": "plugin-toolchain-providers", + "area": "扩展", + "group": "插件与主题", + "capability": "从启用插件的工具链提供方发现安装和版本要求", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/pluginservice/toolchain_provider.go", + "desktop/internal/pluginservice/toolchain_provider_test.go", + "desktop/internal/toolchain/provider.go", + "desktop/internal/toolchain/provider_observation.go", + "desktop/internal/workbench/settings_toolchains.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/pluginservice/toolchain_provider.go", + "desktop/internal/pluginservice/toolchain_provider_test.go", + "desktop/internal/toolchain/provider.go", + "desktop/internal/toolchain/provider_observation.go", + "desktop/internal/toolchain/native_path_windows.go", + "desktop/internal/workbench/settings_toolchains.go" + ] + }, + "owner": "Plugins", + "verification": "使用 TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources 核对合成插件协商、安装与项目版本要求、生效层、全局发现、源文件变化、复用和关闭清理。使用 TestToolchainProviderCancellationDoesNotCompleteTheNextQuery 核对取消与迟到回复。使用 TestToolchainProviderQueriesTheInstalledVersionAfterUpgrade 核对升级后的版本和路径,使用 TestNewProjectOnlyDiscoversToolsRequestedByTheForm 核对表单工具范围。原生设置工作流还需核对打开项目、改写版本要求、重新加载和关闭窗口。", + "notes": "Core 从提供方回包与本机文件事实得出候选和有效安装。桌面按选定清单版本启动共享后端,并为短期缓存观察输入变化。查询期限耗尽时保留已完成的答复和本机候选,由 TestToolchainProviderRoundPreservesAnswersAtItsDeadline 覆盖。安装与工作区目录沿用原有信任检查。" +}