From f62230cfc73b258adf26ae12009f7c2f6e41cdca Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:24:24 +0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(toolchains):=20=E6=8E=A5=E5=85=A5?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=B7=A5=E5=85=B7=E9=93=BE=E6=8F=90=E4=BE=9B?= =?UTF-8?q?=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...toolchain-settings-and-build-resolution.md | 19 +- desktop/internal/core/plugin_session.go | 19 +- desktop/internal/core/toolchain_provider.go | 101 +++++ .../internal/pluginbackend/pluginbackend.go | 3 + desktop/internal/pluginhost/pluginhost.go | 10 +- .../internal/pluginhost/pluginhost_test.go | 4 +- desktop/internal/pluginservice/activation.go | 14 +- desktop/internal/pluginservice/backendhost.go | 95 ++++- .../internal/pluginservice/pluginservice.go | 17 + .../pluginservice/toolchain_provider.go | 151 +++++++ .../pluginservice/toolchain_provider_test.go | 375 ++++++++++++++++++ desktop/internal/toolchain/load.go | 129 +++--- desktop/internal/toolchain/provider.go | 363 +++++++++++++++++ .../toolchain/provider_observation.go | 165 ++++++++ desktop/internal/toolchain/toolchain.go | 10 +- desktop/internal/workbench/app.go | 4 + desktop/internal/workbench/new_project.go | 12 +- .../internal/workbench/settings_toolchains.go | 8 +- desktop/internal/workbench/toolchains.go | 9 +- docs/ci-builds.md | 2 + scripts/desktop/build-desktop-core.sh | 3 +- .../features/plugin-injected-toolchains.json | 2 +- .../features/plugin-toolchain-providers.json | 32 ++ 23 files changed, 1432 insertions(+), 115 deletions(-) create mode 100644 desktop/internal/core/toolchain_provider.go create mode 100644 desktop/internal/pluginservice/toolchain_provider.go create mode 100644 desktop/internal/pluginservice/toolchain_provider_test.go create mode 100644 desktop/internal/toolchain/provider.go create mode 100644 desktop/internal/toolchain/provider_observation.go create mode 100644 shared/platform-feature-matrix/features/plugin-toolchain-providers.json 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 3af8e7d285..5fe0936cdb 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,19 @@ Viva 桌面端现在把插件声明的工具链接进了设置和构建执行: - Core 返回的可执行路径可用正斜杠,Windows 原生扫描和 pin 可能使用反斜杠或不同大小写。执行探测前按原生路径身份合并别名,并把本机路径交给进程适配器;不把同一程序的多个拼写当作多份探测事实。Windows 回归已先复现同一程序被探测三次及 pin 解析因重复证据遭拒绝,修复保留 Core 的严格证据校验。 - 扫描不到安装、版本不满足或工具被两个插件争用时,界面显示 Core 的稳定原因,不伪造默认安装。争用工具不注册,宿主不按插件 ID 替用户选择。 +### 按需发现提供方安装 + +共享插件后端在首次查询时启动,查询与函数调用都用 Core 的会话及取消入口。一个工作区查询带打开时的上下文 ID 和代次。工作区关闭或重开后,旧上下文不能继续发布结果。用户固定的运行目标可以独立解析。 + +每个工具的同一轮回包共用一个代次。桌面收集声明布局、要求来源和观察路径的原生事实,Core 负责校验身份、路径范围、安装与版本要求。为设置和运行缓存的是有界原始回包,每次使用仍按当前文件事实校验。缺失的输入由最近的现存父目录负责观察,文件变化会使整轮重新查询,已有进程保持自己的启动参数。关闭项目、停用或重新加载插件时,释放观察器并结束相应会话。 + +例如用户创建原本缺失的版本要求文件时,下次解析应重新调用提供方并使用完整的新回包。仅重新探测上轮已发现的程序无法反映新文件。沿用原生目录事件避免空闲轮询,且让替换写不会留下指向旧文件的监听。 + ### 读取真实来源,明确保存 工具链快照另保存从已打开目录句柄立即读取的工作区身份。保存前同时核对读取时来源和活动项目的身份,不能只比较两个当前路径;原路径被改名并重建时,即使本地文档仍缺失或字节相同,也要拒绝。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 +79,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 +112,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/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index 9b4869a1fa..c33ced10fe 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 0000000000..23743f257a --- /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 c12d02430d..2a964b3d87 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 4edeef3c85..b1538846b5 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -116,6 +116,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 @@ -155,9 +158,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", @@ -176,6 +179,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 b43c8c2647..0438251e2c 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) { @@ -94,7 +94,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 588896f213..ca7fecb660 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 e87e3a5eaa..0b5229ec16 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. @@ -132,23 +145,35 @@ func (h *BackendHost) EnsureBackend(ctx context.Context, pluginID string) (*Back 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 + 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) + 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 } } @@ -178,6 +203,18 @@ func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSessi if !declaresBackend(manifest) { return nil, fmt.Errorf("%w: %s declares no backend", ErrBackendUnavailable, pluginID) } + 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 +226,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 +266,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 +294,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() } diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index f5c7f40818..dee8aef2eb 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,18 @@ 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, + 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 0000000000..0f34835fa4 --- /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 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) + 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 0000000000..0ab0e90102 --- /dev/null +++ b/desktop/internal/pluginservice/toolchain_provider_test.go @@ -0,0 +1,375 @@ +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) + } + image, err := os.ReadFile(binary) + if err != nil { + t.Fatal(err) + } + write(filepath.Join(installed, pluginpkg.ManifestFile), manifest, 0o600) + write(filepath.Join(installed, "provider.exe"), 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) + } +} + +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/toolchain/load.go b/desktop/internal/toolchain/load.go index 24a62cf98d..d765e3aa2e 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -3,6 +3,7 @@ package toolchain import ( "context" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -65,6 +66,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") } @@ -124,6 +133,7 @@ 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 ctx.Err() != nil { return Snapshot{}, ctx.Err() @@ -142,20 +152,19 @@ 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, - 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, + 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 @@ -220,6 +229,14 @@ 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 + } } return snapshot, nil } @@ -228,6 +245,14 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests // facts and Core entry points as the settings page, so a displayed value and a // launched executable cannot come from two rule sets. func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumVersion string, fixed *Fixed, manifests []json.RawMessage, options Options) (Selection, error) { + 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") } @@ -275,6 +300,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 @@ -284,6 +312,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 != "" { @@ -297,6 +330,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 @@ -374,32 +409,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) @@ -407,22 +420,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) + 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 { @@ -503,6 +524,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 @@ -539,7 +565,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 0000000000..e2aa3a26bc --- /dev/null +++ b/desktop/internal/toolchain/provider.go @@ -0,0 +1,363 @@ +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(context.Context, string, core.ToolchainQueryParams) (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, +) (*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} + } + reply, err := p.Request(queryCtx, pluginID, params) + 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 +} + +// 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, +) (*providerRound, []core.ToolchainQuery, []core.ToolchainProviderInstallation, error) { + round, key, err := p.round(ctx, w, registry, planned, directory, scope) + 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 0000000000..b850eb4b6d --- /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/toolchain.go b/desktop/internal/toolchain/toolchain.go index 3567ce882d..7d0920a1ce 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -67,8 +67,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"` @@ -91,7 +90,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. @@ -114,6 +112,12 @@ 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 + skipPinnedProviders bool + // 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 5c60b237c0..bfb53a86fc 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -962,6 +962,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 519d56d871..745ebade2e 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,7 @@ 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()}) + snapshot, loadErr := toolchain.Load(ctx, a.kernel, "", ".", manifests, a.toolchainOptions("")) if loadErr != nil { return nil, loadErr } diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index c7d80291bc..379dc3ca13 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -17,7 +17,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if readErr != nil { return selection, readErr } - return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Global: true, GlobalRoot: s.app.globalToolchainRoot(), Platform: buildPlatform()}) + return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, s.app.toolchainOptions("")) } root := s.app.toolchainRoot.Load() if root == nil || snapshot.Root == "" { @@ -30,7 +30,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if err != nil { return selection, err } - selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.globalToolchainRoot()}) + selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, s.app.toolchainOptions(snapshot.Root)) if err != nil { return selection, err } @@ -95,7 +95,7 @@ func (s settingsToolchains) LoadScope(ctx context.Context, scope string) (snapsh if err != nil { return snapshot, err } - return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, toolchain.Options{Global: true, GlobalRoot: s.app.globalToolchainRoot(), Platform: buildPlatform()}) + return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, s.app.toolchainOptions("")) } func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain.Snapshot, error) { @@ -103,7 +103,7 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. if err != nil && len(manifests) == 0 { return toolchain.Snapshot{}, err } - return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.globalToolchainRoot()}) + return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, s.app.toolchainOptions(root)) } // 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 a7dd88e103..2d07affb49 100644 --- a/desktop/internal/workbench/toolchains.go +++ b/desktop/internal/workbench/toolchains.go @@ -64,9 +64,12 @@ func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, to if directory == "" { directory = "." } - return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, toolchain.Options{ - Platform: buildPlatform(), - GlobalRoot: a.globalToolchainRoot(), + return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, a.toolchainOptions(root)) +} + +func (a *App) toolchainOptions(root string) toolchain.Options { + return a.plugins.ToolchainOptions(root, toolchain.Options{ + Global: root == "", GlobalRoot: a.globalToolchainRoot(), Platform: buildPlatform(), }) } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 26227cfd7d..d328cc3d8a 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -68,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +工具链提供方回包只在窗口进程内短期缓存。缓存由当前插件版本、工作区上下文和工具输入决定,关闭项目或停用插件时清理。原生文件观察器随缓存释放。该状态没有可复制的编译身份,不跨工作树复用,也不写入插件包或发行目录。 + Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 Viva 编辑器性能基线 `scripts/desktop/perf/editor-bench.sh` 把每次运行的原始输出和 Markdown 预算报告写入当前工作树的 `.artifacts/editor-perf/`(`run-.txt`、`record-.txt` 及同名 `.md`,以及开发者用 `--out` 指定在该目录下的文件)。它们只属于这一次运行,受源码修订、机器、CPU、运行时负载、Go 工具链和大文档大小(默认 10 MiB,可用 `LITHE_EDITOR_PERF_LARGE_BYTES` 或 `--large-bytes` 修改)影响;没有可验证的跨树身份 stamp,不跨工作树复制,由开发者在本地清理;该基线不是 CI 必跑项,CI 不运行基准,也没有 artifact。随仓库提交的历史记录 `desktop/benchmarks/history/*.jsonl` 由 Git 跟踪,属于源码而不是下载或生成资源,各工作树从 Git 检出。这些文件都不进入安装包,也不会改变代码签名或增量更新。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index c7cae60bab..754419172e 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -266,7 +266,8 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="9dea6aa6eaaf830c3568b647aa7daae5018b9727" +# Global toolchain provider replies can be resolved without a workspace scope (Core #111). +PINNED_CORE_REVISION="db27c70e4927ad02a789bb0b635fa02cab9e8d94" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json index 97507832f3..58213b9347 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 0000000000..68a0f92530 --- /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 核对取消与迟到回复。原生设置工作流还需核对打开项目、改写版本要求、重新加载和关闭窗口。", + "notes": "Core 从提供方回包与本机文件事实得出候选和有效安装。桌面首次使用时启动插件的共享后端,并为短期缓存观察输入变化。安装与工作区目录保持原有信任检查。" +} From 8b80afb5031f55daad5a769bca7126f9e632cf59 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:28:06 +0800 Subject: [PATCH 2/8] test(toolchains): reuse the fixture executable image --- .../pluginservice/toolchain_provider_test.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/desktop/internal/pluginservice/toolchain_provider_test.go b/desktop/internal/pluginservice/toolchain_provider_test.go index 0ab0e90102..6b8294805f 100644 --- a/desktop/internal/pluginservice/toolchain_provider_test.go +++ b/desktop/internal/pluginservice/toolchain_provider_test.go @@ -205,12 +205,17 @@ func TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources(t *tes if err != nil { t.Fatal(err) } - image, err := os.ReadFile(binary) - if err != nil { - t.Fatal(err) - } write(filepath.Join(installed, pluginpkg.ManifestFile), manifest, 0o600) - write(filepath.Join(installed, "provider.exe"), image, 0o700) + // 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 { From d0fae42c4352c0396527690e8a054d39dd6fa184 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 17:08:04 +0800 Subject: [PATCH 3/8] build(core): use the shared Python integration revision --- scripts/desktop/build-desktop-core.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 1d49ec8bcd..6b0c1ca1e9 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -271,8 +271,8 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -# Global toolchain provider replies can be resolved without a workspace scope (Core #111). -PINNED_CORE_REVISION="c481227084deead11b5171a1db4fb711401af49c" +# Includes global toolchain provider replies and command-based test discovery (Core #111 and #112). +PINNED_CORE_REVISION="44d62e4ec9b9bdc2b61fa19e4da474b8c6483c40" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From 693f944ae95ac4e6bbc5e6e39d72fc5ea999b907 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 19:05:30 +0800 Subject: [PATCH 4/8] fix(toolchains): query the selected plugin version and form tools --- ...toolchain-settings-and-build-resolution.md | 2 + desktop/internal/pluginservice/backendhost.go | 63 ++++++++--- .../pluginservice/toolchain_provider.go | 4 +- .../pluginservice/toolchain_provider_test.go | 100 ++++++++++++++++++ desktop/internal/toolchain/load.go | 23 +++- desktop/internal/toolchain/provider.go | 29 ++++- desktop/internal/toolchain/provider_test.go | 11 +- desktop/internal/toolchain/toolchain.go | 5 + desktop/internal/workbench/new_project.go | 4 +- .../internal/workbench/new_project_test.go | 92 ++++++++++++++++ .../features/plugin-toolchain-providers.json | 4 +- 11 files changed, 310 insertions(+), 27 deletions(-) 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 91036ede95..672a95f61a 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 @@ -26,6 +26,8 @@ Viva 桌面端现在把插件声明的工具链接进了设置和构建执行: 共享插件后端在首次查询时启动,查询与函数调用都用 Core 的会话及取消入口。一个工作区查询带打开时的上下文 ID 和代次。工作区关闭或重开后,旧上下文不能继续发布结果。用户固定的运行目标可以独立解析。 +查询使用注册表清单中的插件版本,缓存键也含同一份清单。升级后的首次查询先确认新版本仍是当前启用版本,再结束旧后端并启动新后端。旧版迟到查询不能替换现用会话。新建项目只对表单需要的工具运行发现与探测,未选工具的提供方故障不会阻断表单。 + 每个工具的同一轮回包共用一个代次。桌面收集声明布局、要求来源和观察路径的原生事实,Core 负责校验身份、路径范围、安装与版本要求。为设置和运行缓存的是有界原始回包,每次使用仍按当前文件事实校验。缺失的输入由最近的现存父目录负责观察,文件变化会使整轮重新查询,已有进程保持自己的启动参数。关闭项目、停用或重新加载插件时,释放观察器并结束相应会话。 例如用户创建原本缺失的版本要求文件时,下次解析应重新调用提供方并使用完整的新回包。仅重新探测上轮已发现的程序无法反映新文件。沿用原生目录事件避免空闲轮询,且让替换写不会留下指向旧文件的监听。 diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index 0b5229ec16..ad094c8420 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -136,12 +136,14 @@ 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 { @@ -151,11 +153,16 @@ func (h *BackendHost) EnsureBackend(ctx context.Context, pluginID string) (*Back return nil, ctx.Err() } } + 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(startCtx, pluginID) + session, err := h.start(startCtx, pluginID, version, previous) cancel() h.mu.Lock() detached := h.starting[pluginID] != start @@ -178,7 +185,7 @@ func (h *BackendHost) EnsureBackend(ctx context.Context, pluginID string) (*Back } } -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 { @@ -193,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) @@ -203,6 +210,29 @@ 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"` @@ -538,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/toolchain_provider.go b/desktop/internal/pluginservice/toolchain_provider.go index 0f34835fa4..f6fc90df8c 100644 --- a/desktop/internal/pluginservice/toolchain_provider.go +++ b/desktop/internal/pluginservice/toolchain_provider.go @@ -61,7 +61,7 @@ func (s *Service) ToolchainOptions(root string, options toolchain.Options) toolc const toolchainQueryTimeout = 10 * time.Second -func (s *Service) queryToolchain(ctx context.Context, pluginID string, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { +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 { @@ -74,7 +74,7 @@ func (s *Service) queryToolchain(ctx context.Context, pluginID string, params co if err := verify(); err != nil { return core.ToolchainProviderReply{}, err } - session, err := s.Host.EnsureBackend(queryCtx, pluginID) + session, err := s.Host.ensureBackend(queryCtx, pluginID, version) if err == nil { if err := verify(); err != nil { return core.ToolchainProviderReply{}, err diff --git a/desktop/internal/pluginservice/toolchain_provider_test.go b/desktop/internal/pluginservice/toolchain_provider_test.go index 6b8294805f..a23ac055db 100644 --- a/desktop/internal/pluginservice/toolchain_provider_test.go +++ b/desktop/internal/pluginservice/toolchain_provider_test.go @@ -287,6 +287,106 @@ func TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources(t *tes } } +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 || 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 diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index 08854fd320..c592c5fc2c 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -9,6 +9,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "sync/atomic" @@ -107,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 @@ -137,6 +144,10 @@ func load(ctx context.Context, kernel Kernel, root, directory string, manifests 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() } @@ -242,7 +253,9 @@ func load(ctx context.Context, kernel Kernel, root, directory string, manifests return Snapshot{}, err } } - appendManagedDependencies(&snapshot, pluginNames, options.ManagedDependencies) + if len(options.DiscoveryTools) == 0 { + appendManagedDependencies(&snapshot, pluginNames, options.ManagedDependencies) + } return snapshot, nil } @@ -363,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 @@ -518,7 +537,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } 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) + 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 } diff --git a/desktop/internal/toolchain/provider.go b/desktop/internal/toolchain/provider.go index c95663fc77..32b78300bc 100644 --- a/desktop/internal/toolchain/provider.go +++ b/desktop/internal/toolchain/provider.go @@ -26,7 +26,7 @@ type ProviderScope struct { // never authority to execute a tool. Every use captures fresh evidence and // validates the reply again in Core. type ProviderClient struct { - Request func(context.Context, string, core.ToolchainQueryParams) (core.ToolchainProviderReply, error) + 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) @@ -93,6 +93,7 @@ func (p *ProviderClient) Invalidate() func() { 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, @@ -144,7 +145,11 @@ func (p *ProviderClient) round( var reply core.ToolchainProviderReply err := queryCtx.Err() if err == nil { - reply, err = p.Request(queryCtx, pluginID, params) + 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. @@ -172,6 +177,23 @@ func (p *ProviderClient) round( 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) { @@ -244,8 +266,9 @@ func (w *workspace) observeToolHome(home string, definition core.ToolchainToolDe 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) + round, key, err := p.round(ctx, w, registry, planned, directory, scope, versions) if err != nil || round == nil { return nil, nil, nil, err } diff --git a/desktop/internal/toolchain/provider_test.go b/desktop/internal/toolchain/provider_test.go index 6d282bc471..c6972e7b21 100644 --- a/desktop/internal/toolchain/provider_test.go +++ b/desktop/internal/toolchain/provider_test.go @@ -20,7 +20,10 @@ func TestToolchainProviderRoundPreservesAnswersAtItsDeadline(t *testing.T) { 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, _ string, params core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { + 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 @@ -37,7 +40,7 @@ func TestToolchainProviderRoundPreservesAnswersAtItsDeadline(t *testing.T) { }, } planned := core.ToolchainDiscoveryPlanTool{Tool: "fixture", Providers: []string{"test:ready", "test:slow", "test:queued"}} - round, _, err := client.round(ctx, &workspace{platform: "macos"}, nil, planned, ".", nil) + round, _, err := client.round(ctx, &workspace{platform: "macos"}, nil, planned, ".", nil, map[string]string{"test": "1.0.0"}) if err != nil { t.Fatal(err) } @@ -56,7 +59,7 @@ func TestToolchainProviderRoundHonorsCallerDeadline(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) { + Request: func(query context.Context, _, _ string, _ core.ToolchainQueryParams) (core.ToolchainProviderReply, error) { <-query.Done() return core.ToolchainProviderReply{}, query.Err() }, @@ -66,7 +69,7 @@ func TestToolchainProviderRoundHonorsCallerDeadline(t *testing.T) { }, } planned := core.ToolchainDiscoveryPlanTool{Tool: "fixture", Providers: []string{"test:slow"}} - round, _, err := client.round(ctx, &workspace{platform: "macos"}, nil, planned, ".", nil) + 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 de6920c191..59126e02e1 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -125,8 +125,13 @@ type Options struct { // 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/new_project.go b/desktop/internal/workbench/new_project.go index db2446d1a5..ad66317705 100644 --- a/desktop/internal/workbench/new_project.go +++ b/desktop/internal/workbench/new_project.go @@ -323,7 +323,9 @@ func (a *App) loadProjectTools(ctx context.Context, tools []string) (map[string] if err != nil && len(manifests) == 0 { return nil, err } - snapshot, loadErr := toolchain.Load(ctx, a.kernel, "", ".", manifests, a.toolchainOptions(ctx, "", manifests)) + 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 8aa1ec0ff5..8e3f96884b 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/shared/platform-feature-matrix/features/plugin-toolchain-providers.json b/shared/platform-feature-matrix/features/plugin-toolchain-providers.json index 06666044cd..6138026497 100644 --- a/shared/platform-feature-matrix/features/plugin-toolchain-providers.json +++ b/shared/platform-feature-matrix/features/plugin-toolchain-providers.json @@ -27,6 +27,6 @@ ] }, "owner": "Plugins", - "verification": "使用 TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources 核对合成插件协商、安装与项目版本要求、生效层、全局发现、源文件变化、复用和关闭清理。使用 TestToolchainProviderCancellationDoesNotCompleteTheNextQuery 核对取消与迟到回复。原生设置工作流还需核对打开项目、改写版本要求、重新加载和关闭窗口。", - "notes": "Core 从提供方回包与本机文件事实得出候选和有效安装。桌面首次使用时启动插件的共享后端,并为短期缓存观察输入变化。查询期限耗尽时保留已完成的答复和本机候选,由 TestToolchainProviderRoundPreservesAnswersAtItsDeadline 覆盖。安装与工作区目录沿用原有信任检查。" + "verification": "使用 TestToolchainProviderQueriesThroughSharedBackendAndReobservesSources 核对合成插件协商、安装与项目版本要求、生效层、全局发现、源文件变化、复用和关闭清理。使用 TestToolchainProviderCancellationDoesNotCompleteTheNextQuery 核对取消与迟到回复。使用 TestToolchainProviderQueriesTheInstalledVersionAfterUpgrade 核对升级后的版本和路径,使用 TestNewProjectOnlyDiscoversToolsRequestedByTheForm 核对表单工具范围。原生设置工作流还需核对打开项目、改写版本要求、重新加载和关闭窗口。", + "notes": "Core 从提供方回包与本机文件事实得出候选和有效安装。桌面按选定清单版本启动共享后端,并为短期缓存观察输入变化。查询期限耗尽时保留已完成的答复和本机候选,由 TestToolchainProviderRoundPreservesAnswersAtItsDeadline 覆盖。安装与工作区目录沿用原有信任检查。" } From 0dd2ca50872b4ede325778840a034f451e289fa0 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 20:15:30 +0800 Subject: [PATCH 5/8] test(toolchains): compare provider upgrade paths in native form --- desktop/internal/pluginservice/toolchain_provider_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/desktop/internal/pluginservice/toolchain_provider_test.go b/desktop/internal/pluginservice/toolchain_provider_test.go index a23ac055db..ae53e48d61 100644 --- a/desktop/internal/pluginservice/toolchain_provider_test.go +++ b/desktop/internal/pluginservice/toolchain_provider_test.go @@ -361,7 +361,7 @@ func TestToolchainProviderQueriesTheInstalledVersionAfterUpgrade(t *testing.T) { } selection, err := toolchain.Resolve(ctx, client, "", ".", toolchainFixtureTool, "", nil, []json.RawMessage{selected[0].Manifest}, options) session := service.Host.Running(toolchainFixturePlugin) - if err != nil || selection.Executable != executable { + 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 { From ca71cf569bf5fb006d286a6748b2e3ab01c8891d Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 20:15:13 +0800 Subject: [PATCH 6/8] fix(terminal): wait for shell hangup before closing the PTY --- ...2026-11-16-local-shell-integration-shim.md | 4 +- desktop/internal/localshell/shell.go | 50 +++++++--------- .../internal/localshell/shell_unix_test.go | 59 +++++++++++++++++++ .../features/terminal-shell-integration.json | 2 +- 4 files changed, 84 insertions(+), 31 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md index 59190b93fc..3e40bf7d4c 100644 --- a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md +++ b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md @@ -106,7 +106,8 @@ Motty 有开关。没有采用:只在命令行输入区、单击且未拖动 - 收益:本地 bash/zsh、WSL 和带 PSReadLine 的 PowerShell 里,提示符处调整大小不再留下重复提示符;单击命令行可以移动光标。Windows PowerShell/cmd 的提示符上报首次真正启用。 - 代价:每次启动本地 bash/zsh 多运行一次 `sh`(随即变成 Shell,不常驻);`TMPDIR` 下会短暂出现一个私有目录;第一个提示符上点击不生效。 -- 关闭时等 Shell 回到提示符再挂断(#2005):bash 只在“算作交互状态”时把挂断转给后台任务,它运行 `PROMPT_COMMAND`(集成也用它)期间不算。挂断如果落在这段时间里,bash 会退出,但后台任务留了下来。因此 `localshell.Shell` 在读输出时跟踪本会话带令牌的 A–D 标记(`prompt_marks.go`)。Shell 显示过提示符后,如果关闭时它正处在“命令结束到下一个提示符出现”之间(上一个标记不是 B,也不是“C 之后前台还有程序在跑”),挂断就推迟到它打出 B 标记、自己结束,或者最多等 1 秒(`promptGrace`),然后照常挂断,0.5 秒后强制结束。到 B 时 bash 已经回到交互状态,会把挂断转给后台任务。还没出过第一个提示符、或者没有集成的 Shell,照旧立即挂断。关闭后读端继续读输出但直接丢弃,这样内存不会增长,也能看到 B 标记。窗口退出要等每个 Shell 结束,所以最多多等约 1 秒。 +- 关闭集成终端时等 Shell 回到提示符再挂断(#2005、[#2054](https://github.com/1lck/Lithe-IDEA/issues/2054))。Bash 运行 `PROMPT_COMMAND` 时可能无法把挂断转给后台任务。提示符钩子也能启动前台程序,所以前台进程组无法区分正在运行的用户命令和提示符钩子。显示过提示符的 Shell 如还未打出下一个 B 标记,就继续读取并丢弃输出,最多等原有的 1 秒宽限再发送 SIGHUP。未经集成或还没有提示符的 Shell 立即挂断。 +- 伪终端主端(PTY master)留到 Shell 退出并完成有界输出排空。Unix 上关闭主端会让 Shell 的读端看到 EOF 或 EIO,与 Bash 处理 SIGHUP 的顺序产生竞争。保留主端使 Bash 有机会把信号转给自己的任务。原有 0.5 秒强制结束仍为不响应的 Shell 兜底。 - 不要这样做:给会话里所有进程组都发挂断。用户 `disown` 掉的任务会被一起结束;挂断交给 Shell 转发,`disown`/`disown -h` 的语义才能保留。其他终端(如 Ghostty)也只挂断 Shell 自己的进程组。 - 仍然存在的限制:没有集成、但用户自己配了 `PROMPT_COMMAND` 的 bash 不变。zsh 只有在后台任务刚 fork、还没 exec 的约 1 毫秒里被挂断时才会留下任务,这个窗口没有标记可以等,不处理。一直不回提示符的 Shell(例如在 `PROMPT_COMMAND` 里死循环)在 1 秒后照常挂断。 - 没有消费方的回调和目录上报已由 #1984 删除,见“只上报有消费方的内容”。 @@ -116,6 +117,7 @@ Motty 有开关。没有采用:只在命令行输入区、单击且未拖动 ## 验证 - `./scripts/desktop/desktop-go.sh test ./internal/localshell/... ./internal/term/... ./internal/termview/... -count=1`:真实 bash/zsh 经垫片启动并上报提示符和命令,第一个提示符出现时启动目录已删除;挂断能结束 Shell 和后台任务;命令刚结束、bash 还在运行 `PROMPT_COMMAND`(包括慢的 `PROMPT_COMMAND`)时关闭,后台任务也会结束(`TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs`,关掉推迟后 bash 的三个用例都会失败);一直不回提示符的 Shell 在宽限期后结束(`TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt`);标记识别跨分片、只认本会话令牌(`TestPromptMarks*`、`TestPromptMarksAcrossEverySplit`);命令结束只在退出码有效时收回输入模式(`TestACommandEndReclaimsOnlyWithAValidStatus`);WSL 脚本在起始目录启动登录 Shell(`TestWSLScriptStartsTheLoginShellInTheStartFolder`);启动文件还在运行时关闭,Shell 被结束、目录被删除(`TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory`);令牌每次启动更换;提示符处尺寸保持后只发一次;点击按条件发送方向键。 +- `TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY` 用可控后端验证关闭顺序。即使提示符钩子占用前台进程组,也先等 B 标记,发出挂断后再等 Shell 退出,最后关闭主端。 - 运行 `./internal/workbench/` 测试前后统计 `TMPDIR` 下的 `motty-shell.*` 目录,数量不变。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认运行时没有写入发行目录。 - 在 Windows 上运行 `TestWindowsShellsMarkTheirPromptsUnderTheToken`(PowerShell 在下一个提示符前标记命令开始、屏幕开启两项功能,cmd 不标记)、`TestPowerShellReadLineIntegrationMarksTheCommandStart`、`TestPowerShellPromptIntegrationPreservesCustomPromptAndExitStatus`,它们只在 Windows 编译。 diff --git a/desktop/internal/localshell/shell.go b/desktop/internal/localshell/shell.go index 33441be9ad..353ab1b595 100644 --- a/desktop/internal/localshell/shell.go +++ b/desktop/internal/localshell/shell.go @@ -281,6 +281,9 @@ func (shell *Shell) wait() { case <-shell.readDone: case <-time.After(readDrainGrace): } + // Closing a Unix PTY early can make Bash read EOF before it handles SIGHUP. + // By now the shell has had its chance to forward SIGHUP to its jobs. + _ = shell.b.io.Close() shell.mu.Lock() shell.exitErr = err shell.finished = true @@ -398,10 +401,9 @@ func (shell *Shell) ExitStatus() int { // The shell passes the hangup on to the jobs it would end, and leaves those the user // disowned. Bash does so only while it is interactive, and running PROMPT_COMMAND, // which the integration uses, it is not; a job Zsh is still starting misses it too. -// So an integrated shell that has shown a prompt but is not at one now and runs no -// program in the foreground, that is one between a command and its next prompt, is -// hung up when it shows the prompt, or after promptGrace. Without integration the -// shell is hung up at once. +// A foreground program can also be part of PROMPT_COMMAND. Wait for the next +// prompt of an integrated shell that has already shown one, bounded by +// promptGrace. A shell without prompt information is hung up at once. func (shell *Shell) Close() { shell.mu.Lock() if shell.closed { @@ -414,35 +416,20 @@ func (shell *Shell) Close() { if shell.resizeWake != nil { close(shell.resizeWake) } - settling := shell.prompted && shell.lastMark != 'B' && !shell.finished - mark := shell.lastMark + var shown chan struct{} + if shell.prompted && shell.lastMark != 'B' && !shell.finished { + shown = make(chan struct{}) + shell.promptShown = shown + } + shell.finished = true shell.mu.Unlock() // A reader waiting for room drops what it holds and reads on. shell.space.Broadcast() - // A command in the foreground keeps the shell waiting for it, interactive. - if settling && mark == 'C' && shell.b.busy != nil && shell.b.busy() { - settling = false - } - var shown chan struct{} - if settling { - shell.mu.Lock() - if shell.lastMark == 'B' { - settling = false - } else { - shown = make(chan struct{}) - shell.promptShown = shown - } - shell.mu.Unlock() - } - if settling { + if shown != nil { go shell.hangUpAtPrompt(shown) } else { shell.hangUp() } - shell.mu.Lock() - shell.finished = true - shell.mu.Unlock() - shell.space.Broadcast() } // hangUpAtPrompt hangs up a closed shell once it shows its prompt, ends, or has had @@ -453,21 +440,26 @@ func (shell *Shell) hangUpAtPrompt(shown <-chan struct{}) { select { case <-shown: case <-shell.done: + return case <-timer.C: } shell.hangUp() } -// hangUp asks the shell to end, kills it when it outlives killGrace and lets go of -// the terminal. +// hangUp asks the shell to end and kills it if it outlives killGrace. The +// waiter releases the terminal after the process exits and output is drained. func (shell *Shell) hangUp() { + select { + case <-shell.done: + return + default: + } shell.b.hangup() timer := time.AfterFunc(killGrace, shell.b.kill) go func() { <-shell.done timer.Stop() }() - _ = shell.b.io.Close() } // sawMark records a prompt mark the reader found in the output. diff --git a/desktop/internal/localshell/shell_unix_test.go b/desktop/internal/localshell/shell_unix_test.go index 4d152f47e8..0ae1c7e005 100644 --- a/desktop/internal/localshell/shell_unix_test.go +++ b/desktop/internal/localshell/shell_unix_test.go @@ -7,7 +7,9 @@ import ( "path/filepath" "slices" "strings" + "sync" "testing" + "testing/synctest" "time" ) @@ -200,6 +202,63 @@ func TestCloseHangsUpARunningProgramAndReleasesIt(t *testing.T) { shell.Close() // idempotent } +type hangupTestPTY struct { + resizeTestIO + onClose func() +} + +func (pty hangupTestPTY) Close() error { + pty.onClose() + return nil +} + +func TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + exited := make(chan struct{}) + var calls []string + shell := resizeTestShell(backend{ + io: hangupTestPTY{onClose: func() { calls = append(calls, "close PTY") }}, + wait: func() (int, error) { + <-exited + return 0, nil + }, + hangup: func() { calls = append(calls, "hangup") }, + kill: func() { calls = append(calls, "kill") }, + busy: func() bool { return true }, + }) + shell.space = sync.NewCond(&shell.mu) + shell.readDone = make(chan struct{}) + shell.prompted, shell.lastMark = true, 'C' + liveShells.Acquire() + go shell.wait() + + // A foreground process can belong to a slow PROMPT_COMMAND. Its + // presence doesn't mean the shell can already propagate a hangup. + shell.Close() + synctest.Wait() + if len(calls) != 0 { + t.Errorf("while the prompt hook runs: %v, want no backend calls", calls) + } + shell.sawMark('B') + synctest.Wait() + if !slices.Equal(calls, []string{"hangup"}) { + t.Errorf("before the shell handles hangup: %v, want only hangup", calls) + } + + close(exited) + close(shell.readDone) + select { + case <-shell.Done(): + case <-time.After(time.Second): + t.Fatal("the shell never released its terminal") + } + synctest.Wait() + if !slices.Equal(calls, []string{"hangup", "close PTY"}) { + t.Fatalf("shutdown order = %v, want hangup followed by PTY close", calls) + } + }) +} + func TestOutputIsBoundedAndNothingIsLost(t *testing.T) { shell, wakes := start(t, Config{}) // 3 MiB of output against a 1 MiB buffer: the program is held back, not diff --git a/shared/platform-feature-matrix/features/terminal-shell-integration.json b/shared/platform-feature-matrix/features/terminal-shell-integration.json index 6681512a4b..5f8bc44942 100644 --- a/shared/platform-feature-matrix/features/terminal-shell-integration.json +++ b/shared/platform-feature-matrix/features/terminal-shell-integration.json @@ -62,6 +62,6 @@ ] }, "owner": "Terminal", - "verification": "macOS/Linux 打开默认的 zsh 或 bash 终端:Lithe 经 /bin/sh 小脚本启动用户 Shell,用户自己的启动文件、历史记录和提示符照常生效(TestIntegratedBashStartupMatchesALoginShell、TestIntegratedZshHistorySurvivesSessions)。执行一条命令后,Shell 带着本次启动新生成的令牌上报提示符、命令开始与结束和退出码(OSC 133 A/B/C/D);其他程序打印的同样序列、嵌套 Shell 和重启前旧 Shell 的令牌都不被采信(TestIntegratedShellReportsPromptsAndCommands、TestTheUsersShellReportsItsPromptsUnderATokenNewToEachStart)。bash 的登录配置把 PROMPT_COMMAND 设成数组、在 PS0 前放命令替换(systemd 257 起的 /etc/profile.d/80-systemd-osc-context.sh 就这样做,Ubuntu 26.04 默认带),或用户自己的 DEBUG trap 回显 BASH_COMMAND 时,每条命令行仍只上报一次命令开始,用户的 PROMPT_COMMAND、PS0 和 DEBUG trap 照常运行;Bash 4.4 起的 PS0 路径和更早 Bash 的 DEBUG trap 路径都覆盖(TestIntegratedBashReportsEachCommandLineOnce、TestIntegratedBashDebugTrapReportsEachCommandLineOnce、TestIntegratedSystemBashReportsEachCommandLineOnce)。带参数启动的程序、插件终端、Git Bash 和未识别的 Shell 不带令牌,照原样启动(TestAProgramWithArgumentsOfItsOwnGetsNoToken、TestShellsTheIntegrationDoesNotCoverStartAsThemselves)。启动文件写在 Lithe 于 TMPDIR 下新建、仅本人可读的临时目录,sh 写完后直接变成用户 Shell(exec),Shell 读完启动文件即删除目录;Shell 结束后 Lithe 再删一次,所以启动中途被关闭、挂断被忽略而被强制结束时也不留目录、不留 Shell 进程(TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory),应用包字节不变(verify-runtime-bundle-immutability.sh)。终端启动的进程仍是用户 Shell,关闭确认的忙碌判断、挂断与退出码都和不集成时一样;关闭终端时 Shell 与它的后台任务都收到挂断(TestClosingAnIntegratedShellHangsUpTheShellAndItsJobs)。命令刚结束、Shell 还没回到提示符(bash 正在运行 PROMPT_COMMAND)时关闭终端,Lithe 等 Shell 打出提示符标记再挂断,最多等 1 秒,后台任务同样结束;一直不回提示符的 Shell 在 1 秒后照常挂断(TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs、TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt、TestPromptMarksFindTheSessionsMarksInPiecesOfOutput)。 在提示符处拖动窗口或分隔条改变终端宽度:屏幕跟随每一步,提示符行留给 Shell 自己重绘,Shell 在尺寸保持 100 毫秒后只收到一次新尺寸,回到原尺寸则不发送;结束后只有一份提示符,没有重复或被截断的提示符行(TestAShellAtItsPromptIsToldItsSizeOnceItHolds、TestASizeThatComesBackIsNotSentToAShellAtItsPrompt、TestResizeLeavesTheShellPromptForTheShellToRedraw、TestResizeBackToItsWidthRestoresThePrompt)。运行命令或全屏程序时尺寸立即发送(TestAProgramIsToldItsSizeAtOnce)。 在正在输入的命令行上单击或 Option+单击:Shell 光标移到点击处(按程序要求的光标键编码发送左右方向键,宽字符、软换行按显示计算);拖动仍是选择,点在提示符上、输入行以外、命令运行中或备用屏时不发送按键(TestOptionClickMovesTheShellCursorWithinTheInputLine、TestPlainClickMovesTheCursorButADragDoesNot、TestAClickLeavesTheKeyboardAloneWhereItCannotPlaceTheCursor、TestInputMoveAcrossSoftWrap)。与 Motty 一致,Shell 至少执行过一条命令后点击移动才生效。 Windows:PowerShell 5.1 与 7 在 PSReadLine 交回用户确认的命令行后、命令运行前上报命令开始(包住 PSConsoleHostReadLine,行内容和上一条命令的成败状态不变,没有 PSReadLine 时不包;TestPowerShellReadLineIntegrationMarksTheCommandStart),之后提示符处延迟调整大小和点击移动光标对 PowerShell 生效(TestWindowsShellsMarkTheirPromptsUnderTheToken)。cmd 读完一行就直接运行,没有可插入的时机,只上报提示符,这两项对它不生效,尺寸立即发送、点击只是点击。WSL 发行版里的 bash/zsh 走同一脚本,三项都生效。Windows 运行时测试与 PowerShell、cmd、WSL 实机验收 pending;macOS 真实产品交互验收 pending。", + "verification": "macOS/Linux 打开默认的 zsh 或 bash 终端:Lithe 经 /bin/sh 小脚本启动用户 Shell,用户自己的启动文件、历史记录和提示符照常生效(TestIntegratedBashStartupMatchesALoginShell、TestIntegratedZshHistorySurvivesSessions)。执行一条命令后,Shell 带着本次启动新生成的令牌上报提示符、命令开始与结束和退出码(OSC 133 A/B/C/D);其他程序打印的同样序列、嵌套 Shell 和重启前旧 Shell 的令牌都不被采信(TestIntegratedShellReportsPromptsAndCommands、TestTheUsersShellReportsItsPromptsUnderATokenNewToEachStart)。bash 的登录配置把 PROMPT_COMMAND 设成数组、在 PS0 前放命令替换(systemd 257 起的 /etc/profile.d/80-systemd-osc-context.sh 就这样做,Ubuntu 26.04 默认带),或用户自己的 DEBUG trap 回显 BASH_COMMAND 时,每条命令行仍只上报一次命令开始,用户的 PROMPT_COMMAND、PS0 和 DEBUG trap 照常运行;Bash 4.4 起的 PS0 路径和更早 Bash 的 DEBUG trap 路径都覆盖(TestIntegratedBashReportsEachCommandLineOnce、TestIntegratedBashDebugTrapReportsEachCommandLineOnce、TestIntegratedSystemBashReportsEachCommandLineOnce)。带参数启动的程序、插件终端、Git Bash 和未识别的 Shell 不带令牌,照原样启动(TestAProgramWithArgumentsOfItsOwnGetsNoToken、TestShellsTheIntegrationDoesNotCoverStartAsThemselves)。启动文件写在 Lithe 于 TMPDIR 下新建、仅本人可读的临时目录,sh 写完后直接变成用户 Shell(exec),Shell 读完启动文件即删除目录;Shell 结束后 Lithe 再删一次,所以启动中途被关闭、挂断被忽略而被强制结束时也不留目录、不留 Shell 进程(TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory),应用包字节不变(verify-runtime-bundle-immutability.sh)。终端启动的进程仍是用户 Shell,关闭确认的忙碌判断、挂断与退出码都和不集成时一样;关闭终端时 Shell 与它的后台任务都收到挂断(TestClosingAnIntegratedShellHangsUpTheShellAndItsJobs)。Shell 退出后再关闭伪终端主端,避免读取 EOF 抢在挂断处理之前(TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY)。命令刚结束、Shell 还没回到提示符(bash 正在运行 PROMPT_COMMAND)时关闭终端,Lithe 等 Shell 打出提示符标记再挂断,最多等 1 秒,后台任务同样结束;一直不回提示符的 Shell 在 1 秒后照常挂断(TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs、TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt、TestPromptMarksFindTheSessionsMarksInPiecesOfOutput)。 在提示符处拖动窗口或分隔条改变终端宽度:屏幕跟随每一步,提示符行留给 Shell 自己重绘,Shell 在尺寸保持 100 毫秒后只收到一次新尺寸,回到原尺寸则不发送;结束后只有一份提示符,没有重复或被截断的提示符行(TestAShellAtItsPromptIsToldItsSizeOnceItHolds、TestASizeThatComesBackIsNotSentToAShellAtItsPrompt、TestResizeLeavesTheShellPromptForTheShellToRedraw、TestResizeBackToItsWidthRestoresThePrompt)。运行命令或全屏程序时尺寸立即发送(TestAProgramIsToldItsSizeAtOnce)。 在正在输入的命令行上单击或 Option+单击:Shell 光标移到点击处(按程序要求的光标键编码发送左右方向键,宽字符、软换行按显示计算);拖动仍是选择,点在提示符上、输入行以外、命令运行中或备用屏时不发送按键(TestOptionClickMovesTheShellCursorWithinTheInputLine、TestPlainClickMovesTheCursorButADragDoesNot、TestAClickLeavesTheKeyboardAloneWhereItCannotPlaceTheCursor、TestInputMoveAcrossSoftWrap)。与 Motty 一致,Shell 至少执行过一条命令后点击移动才生效。 Windows:PowerShell 5.1 与 7 在 PSReadLine 交回用户确认的命令行后、命令运行前上报命令开始(包住 PSConsoleHostReadLine,行内容和上一条命令的成败状态不变,没有 PSReadLine 时不包;TestPowerShellReadLineIntegrationMarksTheCommandStart),之后提示符处延迟调整大小和点击移动光标对 PowerShell 生效(TestWindowsShellsMarkTheirPromptsUnderTheToken)。cmd 读完一行就直接运行,没有可插入的时机,只上报提示符,这两项对它不生效,尺寸立即发送、点击只是点击。WSL 发行版里的 bash/zsh 走同一脚本,三项都生效。Windows 运行时测试与 PowerShell、cmd、WSL 实机验收 pending;macOS 真实产品交互验收 pending。", "notes": "2026-11-16:同步 Motty 203857c9(调整大小只保留一份提示符)与 b2357d69(点击命令行移动光标),并把 Motty internal/sshconn/integration.go(0ae3ba59)的 bash/zsh 集成脚本用于本地 Shell 与 WSL,见 termview/NOTICE。#1984 留下的令牌链路(localshell.Config.PromptToken,原名 DirectoryToken;term.SetPromptToken)由 termview 接通,每次启动生成新令牌;Windows 的 PowerShell/cmd 集成因此首次真正启用。#1984 随后删除了没有消费方的部分:term 的目录、提示符、命令与输入环境回调和 OSC 7、OSC 9;9 目录解析,以及集成脚本里的目录上报(Unix OSC 7,WSL、PowerShell、cmd 的 OSC 9;9);OSC 133 标记照常上报并被使用(TestPromptMarksAcrossEverySplit、TestACommandEndReclaimsOnlyWithAValidStatus),WSL 起始目录(MOTTY_WSL_CD)保留(TestWSLScriptStartsTheLoginShellInTheStartFolder)。与 Motty 的差异:不提供点击移动的设置开关;调整大小不等待鼠标松开,只等尺寸保持 100 毫秒;见 .agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md。Windows 为 partial:cmd 不上报命令开始,后两项在 cmd 中不生效;PowerShell 自 #2008 起经 PSReadLine 上报命令开始(与 VS Code 的 PowerShell 集成做法相同)。 2026-11-16:#2005 关闭时把挂断推迟到 Shell 回到提示符(最多 1 秒),修复 bash 在 PROMPT_COMMAND 期间被关闭时留下后台任务;Windows 后端不跟踪提示符标记,行为不变。 2026-11-16:bash 的 PS0 改用提示符转义写命令开始标记,赋值语句的文本里不再带标记字节,用户 DEBUG trap 回显 BASH_COMMAND 时不会伪造一次命令开始;DEBUG trap 路径遇到数组形式的 PROMPT_COMMAND 也在首尾加入钩子,不再整段跳过而一次命令开始都不报。这两处与 Motty 的脚本不同。" } From 3b625f68383a4a6ce1a769a67e2a2967f162b0e7 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 20:36:40 +0800 Subject: [PATCH 7/8] fix(workspace): display trust locations with native path separators --- .../feature/2026-11-19-workspace-trust-and-safe-mode.md | 2 +- desktop/internal/workbench/workspace_trust.go | 2 +- desktop/internal/workbench/workspace_trust_test.go | 4 +++- shared/platform-feature-matrix/features/workspace-trust.json | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md index e54ed0a2f1..a1732f0564 100644 --- a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md +++ b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md @@ -12,7 +12,7 @@ Maven 这类命令来源的模型会运行 `mvn`,pom 里的扩展和插件就 ## 决策 -- **三种状态由 Core 判定。** Core 的工具链目录记着信任过的工作区、明确不信任的工作区和信任的位置(父文件夹)。`toolchains.catalogState` 返回 `workspaceTrust`(`trusted`、`distrusted`、`unknown`,以及可以提供的父文件夹);显式决定优先于位置,和 IDEA 的 `TrustedPaths` 一致。根目录、盘符和网络共享根不作为可信位置提供。 +- **三种状态由 Core 判定。** Core 的工具链目录记着信任过的工作区、明确不信任的工作区和信任的位置(父文件夹)。`toolchains.catalogState` 返回 `workspaceTrust`(`trusted`、`distrusted`、`unknown`,以及可以提供的父文件夹);显式决定优先于位置,和 IDEA 的 `TrustedPaths` 一致。根目录、盘符和网络共享根不作为可信位置提供。Core 返回的父文件夹路径在生成复选框标签时转换为当前平台的显示格式,再缩写主目录或长路径。 - **Core 拒绝会运行项目代码的计划。** 计划请求带 `projectCodeAllowed`;为假时,命令模型(清单标了 `executesProjectCode`)、执行类提供者计划和声明了运行项目代码的提供者都会被拒绝,错误码 `plugin.build.untrustedWorkspace`。宿主只负责把项目当前的信任带进请求(`desktop/internal/workbench` 中 11 处请求都填 `p.trust.allowed()`),不自己判断哪些计划危险。 - **先问再打开。** `openProjectHere` 先读信任(`toolchain.ReadWorkspaceTrust`),再决定直接打开、以安全模式打开或提问;选“不打开”时当前项目原样保留,新开的项目页签直接关掉。“以安全模式预览”记成不信任,下次打开不再问,和 IDEA 的 `setProjectTrusted(false)` 相同。 - **安全模式下的动作先问。** `startRun`、`runBuildTask`、`startTests`、运行当前文件和重新加载模型前,安全模式会弹出“信任项目?/ 保持安全模式”。信任保存成功后才执行原动作;保存失败按未信任处理。自动加载的模型不运行,构建窗口在模型位置显示安全模式说明。 diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index 050bb3ec34..5bc2d5e7b9 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -112,7 +112,7 @@ const trustFolderMaxRunes = 48 // trustFolderLabel is how the checkbox names folder: under home as "~" plus the rest, as IDEA // writes it, and a longer one with its middle left out, so its start and its own name stay. func trustFolderLabel(folder, home string) string { - label := []rune(welcomeShorten(folder, home)) + label := []rune(welcomeShorten(filepath.FromSlash(folder), home)) if len(label) <= trustFolderMaxRunes { return string(label) } diff --git a/desktop/internal/workbench/workspace_trust_test.go b/desktop/internal/workbench/workspace_trust_test.go index ecab664161..c87aa01d93 100644 --- a/desktop/internal/workbench/workspace_trust_test.go +++ b/desktop/internal/workbench/workspace_trust_test.go @@ -186,7 +186,9 @@ func TestSafeModeKeepsProjectCodeFromRunningUntilTrusted(t *testing.T) { func TestTrustFolderLabelShortensHomeAndLongPaths(t *testing.T) { home := filepath.Join(string(filepath.Separator)+"Users", "ann") - if got, want := trustFolderLabel(filepath.Join(home, "IdeaProjects"), home), "~"+string(filepath.Separator)+"IdeaProjects"; got != want { + // Core returns a slash-separated location even on Windows. + folder := filepath.ToSlash(filepath.Join(home, "IdeaProjects")) + if got, want := trustFolderLabel(folder, home), "~"+string(filepath.Separator)+"IdeaProjects"; got != want { t.Fatalf("label = %q, want %q", got, want) } long := filepath.Join(string(filepath.Separator)+"srv", "builds", "a-very-long-folder-name-for-every-checkout", "of-the-team", "projects") diff --git a/shared/platform-feature-matrix/features/workspace-trust.json b/shared/platform-feature-matrix/features/workspace-trust.json index e9ade6db16..f15acf0ec5 100644 --- a/shared/platform-feature-matrix/features/workspace-trust.json +++ b/shared/platform-feature-matrix/features/workspace-trust.json @@ -22,6 +22,6 @@ ] }, "owner": "Workspace", - "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", + "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹,父文件夹标签使用当前平台的路径分隔符;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。语言服务器和 Git 在安全模式下仍启动、可信位置没有独立设置页,分别由 #2208、#2207 跟进。" } From 4c9be5a08071ced200bbe0782760d35c8ea78708 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 20:44:55 +0800 Subject: [PATCH 8/8] fix(terminal): retry a missed hangup at the Bash prompt --- ...2026-11-16-local-shell-integration-shim.md | 2 +- desktop/internal/localshell/backend_unix.go | 4 +- desktop/internal/localshell/shell.go | 23 +++++++++- .../internal/localshell/shell_unix_test.go | 43 +++++++++++++++++-- 4 files changed, 65 insertions(+), 7 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md index 3e40bf7d4c..c5cc53dc7b 100644 --- a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md +++ b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md @@ -107,7 +107,7 @@ Motty 有开关。没有采用:只在命令行输入区、单击且未拖动 - 收益:本地 bash/zsh、WSL 和带 PSReadLine 的 PowerShell 里,提示符处调整大小不再留下重复提示符;单击命令行可以移动光标。Windows PowerShell/cmd 的提示符上报首次真正启用。 - 代价:每次启动本地 bash/zsh 多运行一次 `sh`(随即变成 Shell,不常驻);`TMPDIR` 下会短暂出现一个私有目录;第一个提示符上点击不生效。 - 关闭集成终端时等 Shell 回到提示符再挂断(#2005、[#2054](https://github.com/1lck/Lithe-IDEA/issues/2054))。Bash 运行 `PROMPT_COMMAND` 时可能无法把挂断转给后台任务。提示符钩子也能启动前台程序,所以前台进程组无法区分正在运行的用户命令和提示符钩子。显示过提示符的 Shell 如还未打出下一个 B 标记,就继续读取并丢弃输出,最多等原有的 1 秒宽限再发送 SIGHUP。未经集成或还没有提示符的 Shell 立即挂断。 -- 伪终端主端(PTY master)留到 Shell 退出并完成有界输出排空。Unix 上关闭主端会让 Shell 的读端看到 EOF 或 EIO,与 Bash 处理 SIGHUP 的顺序产生竞争。保留主端使 Bash 有机会把信号转给自己的任务。原有 0.5 秒强制结束仍为不响应的 Shell 兜底。 +- 伪终端主端(PTY master)留到 Shell 退出并完成有界输出排空。Unix 上关闭主端会让 Shell 的读端看到 EOF 或 EIO,与 Bash 处理 SIGHUP 的顺序产生竞争。保留主端使 Bash 有机会把信号转给自己的任务。Linux 并发复现显示,Bash 打出 B 标记后仍可能错过第一次 SIGHUP,0.5 秒后被强制结束而后台任务仍在运行。集成 Bash 在提示符处挂断后,若 100 毫秒内仍未完成关闭,再给 Shell 发一次 SIGHUP,让进入输入循环的 Bash 转发;0.5 秒强制结束宽限不变。 - 不要这样做:给会话里所有进程组都发挂断。用户 `disown` 掉的任务会被一起结束;挂断交给 Shell 转发,`disown`/`disown -h` 的语义才能保留。其他终端(如 Ghostty)也只挂断 Shell 自己的进程组。 - 仍然存在的限制:没有集成、但用户自己配了 `PROMPT_COMMAND` 的 bash 不变。zsh 只有在后台任务刚 fork、还没 exec 的约 1 毫秒里被挂断时才会留下任务,这个窗口没有标记可以等,不处理。一直不回提示符的 Shell(例如在 `PROMPT_COMMAND` 里死循环)在 1 秒后照常挂断。 - 没有消费方的回调和目录上报已由 #1984 删除,见“只上报有消费方的内容”。 diff --git a/desktop/internal/localshell/backend_unix.go b/desktop/internal/localshell/backend_unix.go index 8f8c7069a7..f6687fe8a8 100644 --- a/desktop/internal/localshell/backend_unix.go +++ b/desktop/internal/localshell/backend_unix.go @@ -41,6 +41,7 @@ func startBackend(config Config) (backend, error) { } env := append(withoutVariables(inherited, config.Unset), "TERM=xterm-256color", "COLORTERM=truecolor") env = withUTF8Locale(append(env, config.Env...)) + bash := filepath.Base(program) == "bash" args := config.Args // runtime is the private directory of an integrated shell's startup files: // it is made here and removed once the shell has ended, however it ended, @@ -117,7 +118,8 @@ func startBackend(config Config) (backend, error) { }) return readErr == nil && err == nil && group > 0 && group != cmd.Process.Pid }, - promptToken: promptToken, + promptToken: promptToken, + retryHangupAtPrompt: bash && promptToken != "", }, nil } diff --git a/desktop/internal/localshell/shell.go b/desktop/internal/localshell/shell.go index 353ab1b595..52af1f3a56 100644 --- a/desktop/internal/localshell/shell.go +++ b/desktop/internal/localshell/shell.go @@ -91,6 +91,8 @@ type backend struct { // promptToken is the token of the prompt marks the shell prints when it was // started with integration (see integration_scripts.go), else empty. promptToken string + // retryHangupAtPrompt is set by the Unix backend for integrated Bash. + retryHangupAtPrompt bool } // ExitError is why a shell ended with a nonzero status. It has the same @@ -455,10 +457,24 @@ func (shell *Shell) hangUp() { default: } shell.b.hangup() - timer := time.AfterFunc(killGrace, shell.b.kill) + kill := time.AfterFunc(killGrace, shell.b.kill) + var retry *time.Timer + if shell.b.retryHangupAtPrompt { + shell.mu.Lock() + atPrompt := shell.lastMark == 'B' + shell.mu.Unlock() + if atPrompt { + // Bash can print the prompt before Readline is ready to handle + // SIGHUP. Give the shell another chance to forward it to its jobs. + retry = time.AfterFunc(hangupRetryDelay, shell.b.hangup) + } + } go func() { <-shell.done - timer.Stop() + kill.Stop() + if retry != nil { + retry.Stop() + } }() } @@ -477,6 +493,9 @@ func (shell *Shell) sawMark(kind byte) { } } +// hangupRetryDelay lets Readline finish entering its input loop after the prompt. +const hangupRetryDelay = 100 * time.Millisecond + // killGrace is how long a shell gets to leave after a hangup before it is killed. const killGrace = 500 * time.Millisecond diff --git a/desktop/internal/localshell/shell_unix_test.go b/desktop/internal/localshell/shell_unix_test.go index 0ae1c7e005..aba75a53d2 100644 --- a/desktop/internal/localshell/shell_unix_test.go +++ b/desktop/internal/localshell/shell_unix_test.go @@ -222,9 +222,10 @@ func TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY(t *testing.T) { <-exited return 0, nil }, - hangup: func() { calls = append(calls, "hangup") }, - kill: func() { calls = append(calls, "kill") }, - busy: func() bool { return true }, + hangup: func() { calls = append(calls, "hangup") }, + kill: func() { calls = append(calls, "kill") }, + busy: func() bool { return true }, + retryHangupAtPrompt: true, }) shell.space = sync.NewCond(&shell.mu) shell.readDone = make(chan struct{}) @@ -259,6 +260,42 @@ func TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY(t *testing.T) { }) } +func TestHangupRetriesAtTheBashPromptBeforeForcingExit(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + signals := make(chan string, 3) + shell := resizeTestShell(backend{ + hangup: func() { signals <- "hangup" }, + retryHangupAtPrompt: true, + }) + shell.b.kill = func() { + signals <- "kill" + close(shell.done) + } + shell.lastMark = 'B' + shell.hangUp() + synctest.Wait() + if len(signals) != 1 { + t.Errorf("initial signal count = %d, want one hangup", len(signals)) + } + + select { + case <-shell.done: + case <-time.After(killGrace + time.Millisecond): + t.Fatal("the fallback did not end the shell within its original grace period") + } + for _, want := range []string{"hangup", "hangup", "kill"} { + select { + case got := <-signals: + if got != want { + t.Fatalf("signal = %q, want %q", got, want) + } + default: + t.Fatalf("missing signal %q", want) + } + } + }) +} + func TestOutputIsBoundedAndNothingIsLost(t *testing.T) { shell, wakes := start(t, Config{}) // 3 MiB of output against a 1 MiB buffer: the program is held back, not