From 36025af8f419c07e9f425244155c990e70bed490 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 17:24:41 +0800 Subject: [PATCH 1/4] fix(desktop): refresh build providers after toolchain saves --- ...-11-20-build-provider-toolchain-refresh.md | 38 +++++++++++++++ desktop/internal/workbench/app.go | 3 +- desktop/internal/workbench/build.go | 47 +++++++++--------- .../workbench/build_provider_restart_test.go | 48 +++++++++++++++++++ .../workbench/settings_publication.go | 12 +++++ .../workbench/settings_publication_test.go | 18 +++++++ .../internal/workbench/settings_toolchains.go | 15 +++++- .../features/build-system-plugins.json | 4 +- 8 files changed, 159 insertions(+), 26 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md new file mode 100644 index 0000000000..6263d24d12 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md @@ -0,0 +1,38 @@ +# Agent 笔记:保存工具链后刷新构建提供者 + +状态:已实现 + +## 先说结论 + +独立构建提供者(在后台常驻、执行插件构建或测试请求的进程)在启动时绑定工作环境。 +项目工具链或全局默认值保存后,下一次请求重新启动提供者,不要求用户重启桌面端。 +正在执行的请求仍交给旧进程,排空后再关闭;无变化的保存不会触发重启。 + +## 问题 + +原来进程复用只比较插件设置,不比较宿主保存的工具链。即使设置页已显示新程序, +仍可能由旧进程执行下一次测试任务。 + +## 决策 + +宿主在确认写入后推进工具链修订,现有进程复用键同时记录该修订。 +与语言服务器共享的提供者仍由语言服务器管理,不能通过这条路径另起一份。 + +## 考虑过的备选方案 + +没有选择保存时关闭所有构建会话,因为这会取消正在执行的任务;也没有在测试请求中特判具体语言, +因为同一个常驻进程也会为模型、依赖等其他请求服务。 + +## 后果 + +保存时没有额外的工具探测。代价是作用域内的独立提供者会在下次使用时重新解析并启动, +即使某个提供者不依赖刚变更的工具。 + +## 验证 + +在 `desktop/internal/workbench/build_provider_restart_test.go` 用合成提供者验证项目 pin 保存、已有请求排空 +和重复保存。在 Windows 的同一原生窗口中先用旧工具执行,再保存新工具并重跑,核对两次实际启动的路径。 + +## 适用范围 + +Viva 两端共用的宿主进程管理。Core 的选择规则、插件契约和界面文案不变。 diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 2877cf9474..5d2c42cbcc 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -760,7 +760,8 @@ type App struct { trustEveryWorkspace bool // toolchainRoot is the open project's root, read by the settings window from // its own thread. Nil means no project is open. - toolchainRoot atomic.Pointer[string] + toolchainRoot atomic.Pointer[string] + buildToolchainRevision atomic.Uint64 // toolchainResolve is the execution-side selector; tests replace it to keep // workspace file reads out of the window. Production leaves it nil. toolchainResolve func(ctx context.Context, root, directory, tool, minimumVersion string) (core.ToolchainSelection, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 259bdc6bdc..809f14bf92 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" @@ -367,13 +368,11 @@ func (a *App) attachProcess(p *project, op *buildOperation, process *buildproces // buildRuntime owns provider sessions for one project. A session is keyed by // plugin and build system, so two projects never share a process. type buildRuntime struct { - launches pluginLaunches - mu sync.Mutex - providers map[string]*buildprovider.Client - // settings is, for each running provider, the plugin settings it was started with - // (buildSettingsKey). The contract restarts a provider on the next request after they change. - settings map[string]string - // retired are providers a settings change replaced. Each closes once the requests it already + launches pluginLaunches + mu sync.Mutex + providers map[string]*buildprovider.Client + launchKeys map[string]buildProviderLaunchKey + // retired are providers a configuration change replaced. Each closes once the requests it already // had finished; a detach closes them at once with the others. retired map[*buildprovider.Client]struct{} // shared maps a plugin and language to the client attached to that @@ -385,28 +384,32 @@ type buildRuntime struct { detached uint64 } +type buildProviderLaunchKey struct { + settings string + toolchainRevision uint64 +} + // provider is the running provider of instance, started when there is none. The process starts // outside the lock, so detaching on the window thread never waits for a start; a start that lost // to another one or to a detach is stopped again. logDirectory gives the process's ${logDir}, and // is asked only when a process starts. // -// A provider started with other plugin settings than settings holds is replaced, as the contract -// says: a change of the plugin's settings restarts it on the next request, so its launch -// arguments reflect the current values. The replaced provider is returned as retired; the -// caller closes it with retire once the requests it already had finished. -func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (client, retired *buildprovider.Client, err error) { +// A provider started with other plugin settings or before a toolchain change is replaced on the +// next request. The caller retires the old provider once the requests it already had finish. +func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, toolchainRevision *atomic.Uint64, logDirectory func(context.Context, string) string) (client, retired *buildprovider.Client, err error) { key := instance.PluginID + "\x00" + instance.BuildSystemID errClosing := buildprovider.ErrClosed - launchedWith, err := buildSettingsKey(settings) + settingsKey, err := buildSettingsKey(settings) if err != nil { return nil, nil, err } r.mu.Lock() + launchedWith := buildProviderLaunchKey{settings: settingsKey, toolchainRevision: toolchainRevision.Load()} closed, client, detached := r.closed, r.providers[key], r.detached - if !closed && client != nil && !client.Closed() && r.settings[key] != launchedWith { + if !closed && client != nil && !client.Closed() && r.launchKeys[key] != launchedWith { retired = client delete(r.providers, key) - delete(r.settings, key) + delete(r.launchKeys, key) if r.retired == nil { r.retired = make(map[*buildprovider.Client]struct{}) } @@ -452,15 +455,15 @@ func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runne return nil, retired, err } r.mu.Lock() - current := !r.closed && r.detached == detached && ctx.Err() == nil + current := !r.closed && r.detached == detached && ctx.Err() == nil && launchedWith.toolchainRevision == toolchainRevision.Load() client = r.providers[key] if current && (client == nil || client.Closed()) { if r.providers == nil { r.providers = make(map[string]*buildprovider.Client) - r.settings = make(map[string]string) + r.launchKeys = make(map[string]buildProviderLaunchKey) } r.providers[key] = started - r.settings[key] = launchedWith + r.launchKeys[key] = launchedWith r.mu.Unlock() return started, retired, nil } @@ -533,7 +536,7 @@ func (r *buildRuntime) detach(closing bool) []*buildprovider.Client { for provider := range r.retired { clients = append(clients, provider) } - r.providers, r.settings, r.retired, r.shared = nil, nil, nil, nil + r.providers, r.launchKeys, r.retired, r.shared = nil, nil, nil, nil r.detached++ if closing { r.closed = true @@ -566,7 +569,7 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta if err != nil { return nil, err } - client, retired, err := p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, a.pluginLogDirectory) + client, retired, err := p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, &a.buildToolchainRevision, a.pluginLogDirectory) if retired != nil { a.retireBuildProvider(ctx, p, retired) } @@ -577,8 +580,8 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta return a.sharedBuildProvider(ctx, p, instance, shared.LanguageID) } -// retireBuildProvider closes, away from the window thread, a provider its plugin's changed -// settings replaced, after the requests it already had finished. A failure is logged under the +// retireBuildProvider closes, away from the window thread, a replaced provider after the requests +// it already had finished. A failure is logged under the // user action whose request (ctx) replaced it. func (a *App) retireBuildProvider(ctx context.Context, p *project, client *buildprovider.Client) { a.tasks.running.Add(1) diff --git a/desktop/internal/workbench/build_provider_restart_test.go b/desktop/internal/workbench/build_provider_restart_test.go index 6d26de6611..9534e5d196 100644 --- a/desktop/internal/workbench/build_provider_restart_test.go +++ b/desktop/internal/workbench/build_provider_restart_test.go @@ -14,6 +14,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) const restartFixtureID = "dev.lithe.test.provider-tests" @@ -180,6 +181,53 @@ func TestReplacedBuildProviderFinishesTheRequestItHas(t *testing.T) { awaitStateWithin(t, h, 30*time.Second, "the replaced provider's exit after its request", first.Closed) } +func TestBuildProviderRestartsAfterSavingProjectToolchain(t *testing.T) { + manifest := providerSettingsManifest(t) + h := providerTestsHarnessWith(t, manifest) + project := openProviderSettingsFixture(t, h, "block.marker") + instance := settingsFixtureInstance(h, manifest) + first := requestProvider(t, h, project, instance) + adapter := settingsToolchains{app: h.app} + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + operation, err := first.Execute(ctx, "lithe/build/test", json.RawMessage(`{"root":".","scope":"workspace","operationID":"before-toolchain-save"}`), 60_000) + if err != nil { + t.Fatal(err) + } + snapshot, err := adapter.Load(ctx) + if err != nil { + t.Fatal(err) + } + changes := []toolchain.Edit{{ + Tool: "dev.lithe.test.provider-tests:runtime", + Pin: &core.ToolchainPin{Home: filepath.ToSlash(t.TempDir()), Version: "1.0", Provider: "host:manual"}, + }} + snapshot, err = adapter.Save(ctx, snapshot, changes) + if err != nil { + t.Fatal(err) + } + second := requestProvider(t, h, project, instance) + if first == second { + t.Fatal("saving a project toolchain pin reused the old build provider") + } + if first.Closed() { + t.Fatal("saving a project toolchain pin stopped an active test") + } + if err := first.Cancel(ctx, operation); err != nil { + t.Fatal(err) + } + if _, err := operation.Wait(ctx); errors.Is(err, buildprovider.ErrClosed) || errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("replaced provider did not finish its test: %v", err) + } + awaitStateWithin(t, h, 30*time.Second, "the replaced provider's exit", first.Closed) + if _, err := adapter.Save(ctx, snapshot, changes); err != nil { + t.Fatal(err) + } + if again := requestProvider(t, h, project, instance); again != second { + t.Fatal("saving the same pin replaced the build provider again") + } +} + // Closing the project closes a replaced provider at once with the others, without waiting for // the request it still serves. func TestClosingTheProjectClosesAReplacedProvider(t *testing.T) { diff --git a/desktop/internal/workbench/settings_publication.go b/desktop/internal/workbench/settings_publication.go index 7da6926310..513445fc06 100644 --- a/desktop/internal/workbench/settings_publication.go +++ b/desktop/internal/workbench/settings_publication.go @@ -50,6 +50,18 @@ func (a *App) unsubscribeSettings() { } } +func (a *App) advanceGlobalBuildToolchainRevision() { + a.buildToolchainRevision.Add(1) + root := a.globalToolchainRoot() + settingsWindows.Lock() + defer settingsWindows.Unlock() + for target := range settingsWindows.live { + if target != a && target.globalToolchainRoot() == root { + target.buildToolchainRevision.Add(1) + } + } +} + // Publication has already committed. A page cancellation must not undo delivery; // an independent deadline bounds native identity reads and backpressure instead. func (a *App) publishSettings(editor pluginservice.SettingsEditor, scope string, effects []string) error { diff --git a/desktop/internal/workbench/settings_publication_test.go b/desktop/internal/workbench/settings_publication_test.go index 7c3d26b503..84ea4feb37 100644 --- a/desktop/internal/workbench/settings_publication_test.go +++ b/desktop/internal/workbench/settings_publication_test.go @@ -15,6 +15,24 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) +func TestGlobalBuildToolchainRevisionReachesOnlyMatchingSettingsWindows(t *testing.T) { + preferences := t.TempDir() + source := &App{store: store.At(preferences)} + matching := &App{store: store.At(preferences)} + unrelated := &App{store: store.At(t.TempDir())} + for _, window := range []*App{source, matching, unrelated} { + window.subscribeSettings() + t.Cleanup(window.unsubscribeSettings) + } + source.advanceGlobalBuildToolchainRevision() + if source.buildToolchainRevision.Load() != 1 || matching.buildToolchainRevision.Load() != 1 { + t.Fatal("global toolchain save did not invalidate both windows using the same settings") + } + if unrelated.buildToolchainRevision.Load() != 0 { + t.Fatal("global toolchain save invalidated a window using different settings") + } +} + func TestSettingsPublicationReachesMatchingWindowsAndKeepsProjectLayers(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index accafd8809..1db27ca108 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -1,6 +1,7 @@ package workbench import ( + "bytes" "context" "errors" @@ -115,7 +116,11 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapshot, edits []toolchain.Edit) (updated toolchain.Snapshot, err error) { defer func() { s.recordFailure(ctx, "toolchain_settings_save", err) }() if snapshot.Global { - if _, err := snapshot.SaveCatalog(ctx, s.app.kernel, edits); err != nil { + committed, err := snapshot.SaveCatalog(ctx, s.app.kernel, edits) + if committed { + s.app.advanceGlobalBuildToolchainRevision() + } + if err != nil { return snapshot, err } s.app.post(func(a *App) { a.retryFailedPluginServers() }) @@ -132,7 +137,13 @@ func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapsho if err := snapshot.CheckWorkspace(ctx, *root); err != nil { return snapshot, errors.Join(toolchain.ErrPinConflict, err) } - if _, _, err := snapshot.SavePins(ctx, s.app.kernel, edits); err != nil { + _, saved, err := snapshot.SavePins(ctx, s.app.kernel, edits) + if errors.Is(err, toolchain.ErrPinCommitted) || (err == nil && !bytes.Equal(snapshot.Baseline, saved)) { + if s.app.toolchainRoot.Load() == root { + s.app.buildToolchainRevision.Add(1) + } + } + if err != nil { return snapshot, err } s.app.post(func(a *App) { a.retryFailedPluginServers() }) diff --git a/shared/platform-feature-matrix/features/build-system-plugins.json b/shared/platform-feature-matrix/features/build-system-plugins.json index f42f5cb2fa..2222328f09 100644 --- a/shared/platform-feature-matrix/features/build-system-plugins.json +++ b/shared/platform-feature-matrix/features/build-system-plugins.json @@ -2,7 +2,7 @@ "id": "build-system-plugins", "area": "扩展", "group": "插件与主题", - "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。", + "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。保存项目工具链或全局默认后,独立构建提供者在下一次请求按最新配置启动,已有请求排空后关闭旧进程。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -22,6 +22,7 @@ "desktop/internal/workbench/tests_test.go", "desktop/internal/workbench/tests_provider_test.go", "desktop/internal/workbench/build_settings_test.go", + "desktop/internal/workbench/build_provider_restart_test.go", "desktop/internal/workbench/plugin_settings.go", "desktop/internal/workbench/build_tests.go", "desktop/internal/workbench/build_tests_test.go", @@ -61,6 +62,7 @@ "desktop/internal/workbench/tests_test.go", "desktop/internal/workbench/tests_provider_test.go", "desktop/internal/workbench/build_settings_test.go", + "desktop/internal/workbench/build_provider_restart_test.go", "desktop/internal/workbench/plugin_settings.go", "desktop/internal/workbench/build_tests.go", "desktop/internal/workbench/build_tests_test.go", From e67717de1a8cf2f139e459b80ce648804631d34c Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 19:00:23 +0800 Subject: [PATCH 2/4] fix(desktop): refresh build providers across clients and retries --- ...-11-20-build-provider-toolchain-refresh.md | 26 +- .../internal/buildprovider/buildprovider.go | 48 +++- desktop/internal/configfile/configfile.go | 69 +++-- desktop/internal/toolchain/catalog.go | 20 +- desktop/internal/toolchain/pins.go | 11 +- desktop/internal/toolchain/source_revision.go | 41 +++ .../toolchain/source_revision_test.go | 36 +++ desktop/internal/workbench/app.go | 8 +- desktop/internal/workbench/build.go | 238 ++++++++++-------- .../workbench/build_provider_cleanup.go | 69 +++++ .../workbench/build_provider_restart_test.go | 165 ++++++++++++ desktop/internal/workbench/notifications.go | 2 +- desktop/internal/workbench/plugin_programs.go | 23 +- .../workbench/settings_publication.go | 12 - .../workbench/settings_publication_test.go | 18 -- .../internal/workbench/settings_toolchains.go | 15 +- .../features/build-system-plugins.json | 2 +- 17 files changed, 593 insertions(+), 210 deletions(-) create mode 100644 desktop/internal/toolchain/source_revision.go create mode 100644 desktop/internal/toolchain/source_revision_test.go create mode 100644 desktop/internal/workbench/build_provider_cleanup.go diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md index 6263d24d12..3b375dda39 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md +++ b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md @@ -5,8 +5,8 @@ ## 先说结论 独立构建提供者(在后台常驻、执行插件构建或测试请求的进程)在启动时绑定工作环境。 -项目工具链或全局默认值保存后,下一次请求重新启动提供者,不要求用户重启桌面端。 -正在执行的请求仍交给旧进程,排空后再关闭;无变化的保存不会触发重启。 +项目工具链或全局默认值保存后,下一次请求重新启动提供者,独立窗口进程也能读取新值。 +已提交的请求由旧进程处理完。初始化期间发现配置已变更会在原请求期限内重新启动。 ## 问题 @@ -15,23 +15,31 @@ ## 决策 -宿主在确认写入后推进工具链修订,现有进程复用键同时记录该修订。 +宿主按实际来源文件的身份及内容判断进程能否复用。项目 pin 只影响读取该项目来源的实例, +全局目录里的工具链配置影响共用该目录的实例。复用前和初始化完成后均核对文件版本。 +无变化的保存不改文件。原子替换即使恢复相同的内容,也会因文件身份变化被识别。 与语言服务器共享的提供者仍由语言服务器管理,不能通过这条路径另起一份。 +旧进程在后台排空。退役进程和项目关闭时仍在清理的进程继续登记在工作台,直至完成原生销毁。 +例如卸载插件时先阻止新启动,等登记中的相关进程退出,再删除包及状态目录。切换项目时 +记录所属项目,避免关闭旧项目的任务影响新工作台的会话。 + ## 考虑过的备选方案 -没有选择保存时关闭所有构建会话,因为这会取消正在执行的任务;也没有在测试请求中特判具体语言, -因为同一个常驻进程也会为模型、依赖等其他请求服务。 +保存时主动停止所有会话会取消正在执行的任务。只递增进程内计数又无法覆盖使用相同配置目录 +的独立窗口。测试、模型和依赖查询共用提供者,所以在宿主复用入口检查来源。 ## 后果 -保存时没有额外的工具探测。代价是作用域内的独立提供者会在下次使用时重新解析并启动, -即使某个提供者不依赖刚变更的工具。 +按请求读取既有的有界配置文件,不启动探测或常驻轮询。作用域内的独立提供者下次使用时会重新 +解析并启动,即使某个提供者不依赖刚变更的工具。连续三次读取或启动均被来源变动打断时,返回 +工具链冲突供用户重试。 ## 验证 -在 `desktop/internal/workbench/build_provider_restart_test.go` 用合成提供者验证项目 pin 保存、已有请求排空 -和重复保存。在 Windows 的同一原生窗口中先用旧工具执行,再保存新工具并重跑,核对两次实际启动的路径。 +在 `desktop/internal/workbench/build_provider_restart_test.go` 用合成提供者验证项目 pin 保存和重复保存、 +未接收通知的另一个客户端写入、初始化期间保存、已有请求排空,以及卸载前等待退役进程销毁。 +原生窗口的验证动作是先用旧工具执行,再保存新工具并重跑,核对两次实际启动的路径。 ## 适用范围 diff --git a/desktop/internal/buildprovider/buildprovider.go b/desktop/internal/buildprovider/buildprovider.go index 7edf5e396f..395ee259e1 100644 --- a/desktop/internal/buildprovider/buildprovider.go +++ b/desktop/internal/buildprovider/buildprovider.go @@ -140,6 +140,8 @@ type Client struct { done chan struct{} doneOnce sync.Once closeOnce sync.Once + dispose chan struct{} + disposed bool // closeErr records why the session ended, for requests that arrive later. closeErr error @@ -160,19 +162,10 @@ type Client struct { // provider. The caller must run this away from the window thread. Close owns // the process and must be called when the workspace closes. func Start(ctx context.Context, runner *pluginbackend.Runner, request pluginbackend.StartRequest) (*Client, error) { - if runner == nil { - return nil, errors.New("buildprovider: no runner") - } - if request.Role == "" { - request.Role = "build" - } - session, err := runner.Start(ctx, request) + client, err := Launch(ctx, runner, request) if err != nil { return nil, err } - client := newClient(runner, session) - client.ctx, client.cancel = context.WithCancel(context.Background()) - go client.serve() if err := client.WaitReady(ctx); err != nil { // The session may have started but never negotiated the protocol. Stop // it instead of leaving an unusable process behind. @@ -186,6 +179,25 @@ func Start(ctx context.Context, runner *pluginbackend.Runner, request pluginback return client, nil } +// Launch gives the caller ownership immediately. The caller must wait for +// readiness and dispose the session even if initialization fails. +func Launch(ctx context.Context, runner *pluginbackend.Runner, request pluginbackend.StartRequest) (*Client, error) { + if runner == nil { + return nil, errors.New("buildprovider: no runner") + } + if request.Role == "" { + request.Role = "build" + } + session, err := runner.Start(ctx, request) + if err != nil { + return nil, err + } + client := newClient(runner, session) + client.ctx, client.cancel = context.WithCancel(context.Background()) + go client.serve() + return client, nil +} + // Attach returns a client over a session another owner started, such as a // language server of the same plugin. The owner must call Observe with every // event that session produces. Close detaches this client; it never stops the @@ -211,6 +223,7 @@ func newClient(runner *pluginbackend.Runner, session pluginbackend.Session) *Cli session: session, ready: make(chan struct{}), done: make(chan struct{}), + dispose: make(chan struct{}, 1), pending: make(map[string]*Operation), } } @@ -361,6 +374,19 @@ func (c *Client) Close(ctx context.Context) error { if c == nil { return nil } + if !c.shared { + // Retirement, project close and uninstall can all request the same stop. + // Claim native disposal before waking the requests that retirement awaits. + select { + case c.dispose <- struct{}{}: + defer func() { <-c.dispose }() + case <-ctx.Done(): + return ctx.Err() + } + if c.disposed { + return nil + } + } c.closeOnce.Do(func() { c.mu.Lock() c.closed = true @@ -380,7 +406,7 @@ func (c *Client) Close(ctx context.Context) error { } var err error if c.runner != nil { - err = c.runner.Stop(ctx, c.session) + c.disposed, err = c.runner.StopAndDispose(ctx, c.session) } c.end(ErrClosed) return err diff --git a/desktop/internal/configfile/configfile.go b/desktop/internal/configfile/configfile.go index e438c17d13..a65ea9b50f 100644 --- a/desktop/internal/configfile/configfile.go +++ b/desktop/internal/configfile/configfile.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "crypto/rand" + "crypto/sha256" "errors" "io" "os" @@ -32,19 +33,37 @@ type Snapshot struct { name string maximum int64 rootInfo os.FileInfo + fileInfo os.FileInfo content []byte - exists bool } // Path is a display-only source path. I/O always uses os.Root-relative methods. func (s Snapshot) Path() string { return filepath.Join(s.root, s.name) } -func (s Snapshot) Exists() bool { return s.exists } +func (s Snapshot) Exists() bool { return s.fileInfo != nil } func (s Snapshot) Bytes() []byte { return append([]byte(nil), s.content...) } +// Revision identifies the bounded bytes and the native file that supplied them. +// Atomic replacements can restore the same bytes while a consumer is starting. +type Revision struct { + file os.FileInfo + hash [sha256.Size]byte +} + +func (s Snapshot) Revision() Revision { + return Revision{file: s.fileInfo, hash: sha256.Sum256(s.content)} +} + +func (r Revision) Equal(other Revision) bool { + if r.file == nil || other.file == nil { + return r.file == nil && other.file == nil + } + return r.hash == other.hash && r.file.ModTime().Equal(other.file.ModTime()) && os.SameFile(r.file, other.file) +} + // Text rejects undecodable bytes before JSON string transport can replace them. // A nil string means a missing file; an empty existing file remains explicit. func (s Snapshot) Text() (*string, error) { - if !s.exists { + if !s.Exists() { return nil, nil } if !utf8.Valid(s.content) { @@ -76,66 +95,66 @@ func Capture(ctx context.Context, rootDirectory, relativeName string, maximumByt if err != nil { return snapshot, err } - snapshot.content, snapshot.exists, err = read(ctx, root, snapshot.name, maximumBytes, false) + snapshot.content, snapshot.fileInfo, err = read(ctx, root, snapshot.name, maximumBytes) return snapshot, err } -func read(ctx context.Context, root *os.Root, name string, maximum int64, writable bool) (data []byte, exists bool, err error) { +func read(ctx context.Context, root *os.Root, name string, maximum int64) (data []byte, info os.FileInfo, err error) { if err := ctx.Err(); err != nil { - return nil, false, err + return nil, nil, err } - info, err := root.Lstat(name) + info, err = root.Lstat(name) // log-exempt: 预期的缺失:缺失的配置文件是未覆盖的空来源。 if errors.Is(err, os.ErrNotExist) { - return nil, false, nil + return nil, nil, nil } if err != nil { - return nil, false, err + return nil, nil, err } if !info.Mode().IsRegular() { - return nil, false, ErrTarget + return nil, nil, ErrTarget } - file, err := openSource(root, name, writable) + file, err := openSource(root, name, false) if err != nil { - return nil, false, err + return nil, nil, err } defer func() { err = errors.Join(err, file.Close()) }() openedInfo, err := file.Stat() if err != nil { - return nil, false, err + return nil, nil, err } if !os.SameFile(info, openedInfo) { - return nil, false, ErrConflict + return nil, nil, ErrConflict } info = openedInfo if !info.Mode().IsRegular() { - return nil, false, ErrTarget + return nil, nil, ErrTarget } if info.Size() > maximum { - return nil, true, ErrTooLarge + return nil, nil, ErrTooLarge } data, err = io.ReadAll(io.LimitReader(file, maximum+1)) if err != nil { - return nil, true, err + return nil, nil, err } if int64(len(data)) > maximum { - return nil, true, ErrTooLarge + return nil, nil, ErrTooLarge } if err := ctx.Err(); err != nil { - return nil, true, err + return nil, nil, err } - return data, true, nil + return data, info, nil } func (s Snapshot) check(ctx context.Context, root *os.Root) error { - data, exists, err := read(ctx, root, s.name, s.maximum, false) + data, info, err := read(ctx, root, s.name, s.maximum) if errors.Is(err, ErrTooLarge) { return ErrConflict } if err != nil { return err } - if exists != s.exists || !bytes.Equal(data, s.content) { + if (info != nil) != s.Exists() || !bytes.Equal(data, s.content) { return ErrConflict } return nil @@ -255,16 +274,16 @@ func (s Snapshot) publish(ctx context.Context, content []byte, remove bool, chec return false, err } } - if remove && !s.exists { + if remove && !s.Exists() { return false, nil } - if !remove && s.exists && bytes.Equal(content, s.content) { + if !remove && s.Exists() && bytes.Equal(content, s.content) { return false, nil } // Prove native write access, and retain the original metadata by handle. var source *os.File - if s.exists { + if s.Exists() { source, err = openSource(root, s.name, true) if err != nil { return false, err diff --git a/desktop/internal/toolchain/catalog.go b/desktop/internal/toolchain/catalog.go index 671b813935..c3cf7b130e 100644 --- a/desktop/internal/toolchain/catalog.go +++ b/desktop/internal/toolchain/catalog.go @@ -10,8 +10,12 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) -type catalogKernel interface { +type catalogReader interface { ReadToolchainCatalogForWorkspace(context.Context, *string, string, string) (core.ToolchainCatalogState, error) +} + +type catalogKernel interface { + catalogReader EditToolchainCatalog(context.Context, *string, string, []core.ToolchainCatalogEdit) (core.ToolchainCatalogPublication, error) EditToolchainWorkspaceTrust(context.Context, *string, string, core.ToolchainWorkspaceTrustEdit) (core.ToolchainCatalogPublication, error) } @@ -40,11 +44,7 @@ func captureCatalog(ctx context.Context, kernel Kernel, root, workspaceRoot, pla if platform == "" { platform = PlatformName(runtime.GOOS) } - plan, err := native.ReadToolchainCatalogForWorkspace(ctx, nil, platform, "") - if err != nil { - return nil, err - } - file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + file, err := captureCatalogFile(ctx, native, root, platform) if err != nil { return nil, err } @@ -59,6 +59,14 @@ func captureCatalog(ctx context.Context, kernel Kernel, root, workspaceRoot, pla return &catalogSource{file: file, state: state, platform: platform}, nil } +func captureCatalogFile(ctx context.Context, kernel catalogReader, root, platform string) (configfile.Snapshot, error) { + plan, err := kernel.ReadToolchainCatalogForWorkspace(ctx, nil, platform, "") + if err != nil { + return configfile.Snapshot{}, err + } + return configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) +} + // SaveCatalog publishes only confirmed registrations/defaults. It never writes // a project pin or touches an SDK directory, and never treats a no-op as a file. func (s Snapshot) SaveCatalog(ctx context.Context, kernel Kernel, edits []Edit) (bool, error) { diff --git a/desktop/internal/toolchain/pins.go b/desktop/internal/toolchain/pins.go index 12ecc6b4bf..5d325652ea 100644 --- a/desktop/internal/toolchain/pins.go +++ b/desktop/internal/toolchain/pins.go @@ -21,14 +21,19 @@ type pinSource struct { document json.RawMessage } -func capturePinSource(ctx context.Context, kernel Kernel, root string) (pinSource, error) { +func capturePinFile(ctx context.Context, kernel Kernel, root string) (configfile.Snapshot, core.ToolchainPinStoragePlan, error) { plan, err := kernel.ToolchainPinStorage(ctx) if err != nil { - return pinSource{}, err + return configfile.Snapshot{}, plan, err } file, err := configfile.Capture(ctx, root, plan.DocumentRelativePath, plan.MaximumDocumentBytes) + return file, plan, pinSourceError(err) +} + +func capturePinSource(ctx context.Context, kernel Kernel, root string) (pinSource, error) { + file, plan, err := capturePinFile(ctx, kernel, root) if err != nil { - return pinSource{}, pinSourceError(err) + return pinSource{}, err } text, err := file.Text() if err != nil { diff --git a/desktop/internal/toolchain/source_revision.go b/desktop/internal/toolchain/source_revision.go new file mode 100644 index 0000000000..b4762a5607 --- /dev/null +++ b/desktop/internal/toolchain/source_revision.go @@ -0,0 +1,41 @@ +package toolchain + +import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" +) + +type sourceRevisionKernel interface { + Kernel + catalogReader +} + +// SourceRevision identifies the saved input files of one workspace's toolchain +// resolver. It holds no configuration bytes, tool selections or discovery state. +type SourceRevision struct { + project configfile.Revision + global configfile.Revision +} + +func (r SourceRevision) Equal(other SourceRevision) bool { + return r.project.Equal(other.project) && r.global.Equal(other.global) +} + +// ReadSourceRevision reads the same bounded files as Resolve, without decoding +// their content or probing tools. Separate clients therefore agree on whether +// a provider predates a committed settings change. +func ReadSourceRevision(ctx context.Context, kernel sourceRevisionKernel, root, globalRoot, platform string) (SourceRevision, error) { + project, _, err := capturePinFile(ctx, kernel, root) + if err != nil { + return SourceRevision{}, err + } + var global configfile.Snapshot + if globalRoot != "" { + global, err = captureCatalogFile(ctx, kernel, globalRoot, platform) + if err != nil { + return SourceRevision{}, err + } + } + return SourceRevision{project: project.Revision(), global: global.Revision()}, nil +} diff --git a/desktop/internal/toolchain/source_revision_test.go b/desktop/internal/toolchain/source_revision_test.go new file mode 100644 index 0000000000..312e3e696a --- /dev/null +++ b/desktop/internal/toolchain/source_revision_test.go @@ -0,0 +1,36 @@ +package toolchain + +import ( + "context" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestSourceRevisionKeepsProjectPinsLocal(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + kernel := core.NewClient() + project, unrelated, global := t.TempDir(), t.TempDir(), t.TempDir() + read := func(root string) SourceRevision { + t.Helper() + revision, err := ReadSourceRevision(ctx, kernel, root, global, PlatformName(runtime.GOOS)) + if err != nil { + t.Fatal(err) + } + return revision + } + beforeProject, beforeUnrelated := read(project), read(unrelated) + const tool = "dev.lithe.test.revision:runtime" + if _, _, err := SavePin(ctx, kernel, project, ".", tool, &core.ToolchainPin{ + Home: filepath.ToSlash(t.TempDir()), Provider: "host:manual", Version: "1.0", + }, nil); err != nil { + t.Fatal(err) + } + if beforeProject.Equal(read(project)) || !beforeUnrelated.Equal(read(unrelated)) { + t.Fatal("saving a pin must change only the owning project's source revision") + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 500dd06093..ee587e10f4 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -168,6 +168,7 @@ type Kernel interface { ResolveToolchainPins(ctx context.Context, document json.RawMessage, directory, tool string) (core.ToolchainPinResolution, error) EditToolchainPins(ctx context.Context, document json.RawMessage, directory string, edits []core.ToolchainPinEdit) (json.RawMessage, error) ToolchainPinStorage(ctx context.Context) (core.ToolchainPinStoragePlan, error) + ReadToolchainCatalogForWorkspace(ctx context.Context, document *string, platform, workspace string) (core.ToolchainCatalogState, error) DecodeToolchainPinDocument(ctx context.Context, document *string) (json.RawMessage, error) EditToolchainPinSources(ctx context.Context, request core.ToolchainPinSourcesRequest) (core.ToolchainPinSourcesEdit, error) CloseGitHistoryCursor(ctx context.Context, root, cursor string) (bool, error) @@ -707,6 +708,10 @@ type App struct { // Discovery remains registered until its report is cleaned up, even after // this workbench closes its project or leaves the tab strip. pluginDiscoveryLaunches pluginLaunches + // Provider launches can still be cleaning up after their project closes. + buildProviderLaunches pluginLaunches + // Providers remain owned here until native disposal succeeds. + closingBuildProviders closingBuildProviders // pluginServerMu guards the language-server maps because a build provider // may attach to a shared session from a background model load. pluginServerMu sync.Mutex @@ -773,8 +778,7 @@ type App struct { trustEveryWorkspace bool // toolchainRoot is the open project's root, read by the settings window from // its own thread. Nil means no project is open. - toolchainRoot atomic.Pointer[string] - buildToolchainRevision atomic.Uint64 + toolchainRoot atomic.Pointer[string] // toolchainResolve is the execution-side selector; tests replace it to keep // workspace file reads out of the window. Production leaves it nil. toolchainResolve func(ctx context.Context, root, directory, tool, minimumVersion string) (core.ToolchainSelection, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 71d7b1e5f0..88eb5449a5 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -16,11 +16,11 @@ import ( "strconv" "strings" "sync" - "sync/atomic" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" @@ -375,13 +375,9 @@ func (a *App) attachProcess(p *project, op *buildOperation, process *buildproces // buildRuntime owns provider sessions for one project. A session is keyed by // plugin and build system, so two projects never share a process. type buildRuntime struct { - launches pluginLaunches mu sync.Mutex providers map[string]*buildprovider.Client launchKeys map[string]buildProviderLaunchKey - // retired are providers a configuration change replaced. Each closes once the requests it already - // had finished; a detach closes them at once with the others. - retired map[*buildprovider.Client]struct{} // shared maps a plugin and language to the client attached to that // language server's session. shared map[string]*buildprovider.Client @@ -392,56 +388,56 @@ type buildRuntime struct { } type buildProviderLaunchKey struct { - settings string - toolchainRevision uint64 + settings string + toolchain toolchain.SourceRevision } -// provider is the running provider of instance, started when there is none. The process starts -// outside the lock, so detaching on the window thread never waits for a start; a start that lost -// to another one or to a detach is stopped again. logDirectory gives the process's ${logDir}, and -// is asked only when a process starts. -// -// A provider started with other plugin settings or before a toolchain change is replaced on the -// next request. The caller retires the old provider once the requests it already had finish. -func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, toolchainRevision *atomic.Uint64, logDirectory func(context.Context, string) string) (client, retired *buildprovider.Client, err error) { +func (key buildProviderLaunchKey) equal(other buildProviderLaunchKey) bool { + return key.settings == other.settings && key.toolchain.Equal(other.toolchain) +} + +var errBuildProviderSourceChanged = errors.New("build provider source changed during launch") + +// standaloneBuildProvider starts a process outside the session lock. Only a +// start from the current project and saved toolchain sources can be published. +func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance buildInstance, rootURI string, settings core.PluginSettingsState, launchKey buildProviderLaunchKey, detached uint64) (*buildprovider.Client, error) { + r := &p.buildSessions key := instance.PluginID + "\x00" + instance.BuildSystemID - errClosing := buildprovider.ErrClosed - settingsKey, err := buildSettingsKey(settings) - if err != nil { - return nil, nil, err - } r.mu.Lock() - launchedWith := buildProviderLaunchKey{settings: settingsKey, toolchainRevision: toolchainRevision.Load()} - closed, client, detached := r.closed, r.providers[key], r.detached - if !closed && client != nil && !client.Closed() && r.launchKeys[key] != launchedWith { - retired = client + if err := ctx.Err(); err != nil { + r.mu.Unlock() + return nil, err + } + if r.closed || r.detached != detached { + r.mu.Unlock() + return nil, buildprovider.ErrClosed + } + client := r.providers[key] + if client != nil { + if !client.Closed() && r.launchKeys[key].equal(launchKey) { + r.mu.Unlock() + return client, nil + } + // Register retirement before releasing the lock that uninstall uses to + // take active sessions. There must be no gap in native ownership. + a.closingBuildProviders.add(p.ctx, client) delete(r.providers, key) delete(r.launchKeys, key) - if r.retired == nil { - r.retired = make(map[*buildprovider.Client]struct{}) - } - r.retired[retired] = struct{}{} - client = nil } r.mu.Unlock() - if closed { - return nil, nil, errClosing - } - if client != nil && !client.Closed() { - return client, nil, nil - } - state := buildStateDirectory(pluginRoot, root, instance) - if err := os.MkdirAll(state, 0o700); err != nil { - return nil, retired, err + if client != nil { + a.retireBuildProvider(ctx, client) } + + state := buildStateDirectory(a.plugins.Root, p.root, instance) workspaceState := filepath.Join(state, "workspace") temporaryDirectory := filepath.Join(state, "tmp") for _, directory := range []string{workspaceState, temporaryDirectory} { if err := os.MkdirAll(directory, 0o700); err != nil { - return nil, retired, err + return nil, err } } - started, err := buildprovider.Start(ctx, runner, pluginbackend.StartRequest{ + started, startErr := buildprovider.Launch(ctx, a.plugins.Backend, pluginbackend.StartRequest{ Manifest: instance.Manifest, PackageDirectory: instance.PackageDirectory, PluginID: instance.PluginID, @@ -450,66 +446,73 @@ func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runne Role: "build", StateDirectory: state, WorkspaceStateDirectory: workspaceState, - LogDirectory: logDirectory(ctx, instance.PluginID), + LogDirectory: a.pluginLogDirectory(ctx, instance.PluginID), TemporaryDirectory: temporaryDirectory, Architecture: core.PluginArchitecture(), Settings: settings.Settings, ProjectSettings: settings.ProjectSettings, RootURI: rootURI, - WorkingDirectory: root, + WorkingDirectory: p.root, }) - if err != nil { - return nil, retired, err + var shared *pluginbackend.SharedProviderError + if errors.As(startErr, &shared) { + return nil, startErr } + if startErr == nil { + startErr = started.WaitReady(ctx) + } + latest, revisionErr := a.buildToolchainSource(ctx, p) r.mu.Lock() - current := !r.closed && r.detached == detached && ctx.Err() == nil && launchedWith.toolchainRevision == toolchainRevision.Load() + open := !r.closed && r.detached == detached && ctx.Err() == nil + current := open && revisionErr == nil && launchKey.toolchain.Equal(latest) client = r.providers[key] - if current && (client == nil || client.Closed()) { + if current && startErr == nil && client == nil { if r.providers == nil { r.providers = make(map[string]*buildprovider.Client) r.launchKeys = make(map[string]buildProviderLaunchKey) } r.providers[key] = started - r.launchKeys[key] = launchedWith + r.launchKeys[key] = launchKey r.mu.Unlock() - return started, retired, nil + return started, nil + } + matched := client != nil && !client.Closed() && r.launchKeys[key].equal(launchKey) + if started != nil { + a.closingBuildProviders.add(p.ctx, started) } r.mu.Unlock() - stopCtx, cancel := context.WithTimeout(context.Background(), buildStopTimeout) - defer cancel() - if err := started.Close(stopCtx); err != nil { - return nil, retired, err + if started != nil { + stopCtx, cancel := context.WithTimeout(context.Background(), buildStopTimeout) + defer cancel() + if err := a.closingBuildProviders.close(stopCtx, started); err != nil { + return nil, &trackedBuildProviderStopError{cause: errors.Join(startErr, revisionErr, err)} + } } - if !current { - return nil, retired, errClosing + if !open { + // log-exempt: teardown:关闭项目会撤销被替换的启动,进程清理错误已在上方返回。 + if err := ctx.Err(); err != nil { + return nil, err + } + return nil, buildprovider.ErrClosed } - return client, retired, nil -} - -// retire closes a provider that provider replaced, once the requests it already had finished or -// buildRequestTimeout passed; requests still running then end with the close. It leaves the -// client alone when a detach took it first and closes it itself. The error reports a provider -// that outlived the wait or failed to stop. -func (r *buildRuntime) retire(client *buildprovider.Client) error { - drainCtx, cancelDrain := context.WithTimeout(context.Background(), buildRequestTimeout) - defer cancelDrain() - var failures []error - if err := client.Drain(drainCtx); err != nil { - failures = append(failures, fmt.Errorf("the replaced build provider still served requests after %s: %w", buildRequestTimeout, err)) + if errors.Is(revisionErr, configfile.ErrConflict) { + return nil, errBuildProviderSourceChanged } - r.mu.Lock() - _, owned := r.retired[client] - delete(r.retired, client) - r.mu.Unlock() - if !owned { - return nil + if revisionErr != nil { + return nil, errors.Join(startErr, revisionErr) } - stopCtx, cancel := context.WithTimeout(context.Background(), buildStopTimeout) - defer cancel() - if err := client.Close(stopCtx); err != nil { - failures = append(failures, err) + if !current { + // log-exempt: 预期的缺失:过期启动结果随旧配置一起丢弃,调用方在同一期限内重试。 + return nil, errBuildProviderSourceChanged } - return errors.Join(failures...) + if matched { + // log-exempt: 预期的缺失:同一配置的并发启动已有可复用的进程。 + return client, nil + } + if startErr != nil { + return nil, startErr + } + return nil, errBuildProviderSourceChanged } // buildSettingsKey identifies the plugin settings a provider starts with: the global values and @@ -540,10 +543,7 @@ func (r *buildRuntime) detach(closing bool) []*buildprovider.Client { for _, provider := range r.shared { clients = append(clients, provider) } - for provider := range r.retired { - clients = append(clients, provider) - } - r.providers, r.launchKeys, r.retired, r.shared = nil, nil, nil, nil + r.providers, r.launchKeys, r.shared = nil, nil, nil r.detached++ if closing { r.closed = true @@ -563,23 +563,60 @@ func buildStateDirectory(pluginRoot, workspace string, instance buildInstance) s // buildProvider starts a provider process, or attaches to the language server // that shares it. The caller runs this away from the window thread. func (a *App) buildProvider(ctx context.Context, p *project, instance buildInstance) (client *buildprovider.Client, err error) { - ctx, finish, err := p.buildSessions.launches.begin(ctx, instance.PluginID) + ctx, finish, err := a.buildProviderLaunches.begin(ctx, instance.PluginID) if err != nil { return nil, err } - defer func() { finish(err) }() + defer func() { + var tracked *trackedBuildProviderStopError + if errors.As(err, &tracked) { + // The launch finished. Uninstall can retry disposal through the workbench. + finish(nil) + return + } + finish(err) + }() + p.buildSessions.mu.Lock() + detached := p.buildSessions.detached + p.buildSessions.mu.Unlock() + const maxSourceAttempts = 3 + for range maxSourceAttempts { + client, err = a.buildProviderWithSources(ctx, p, instance, detached) + // log-exempt: 预期的缺失:读取或启动期间工具链来源已更新,在原请求期限内重试。 + if err == errBuildProviderSourceChanged { + continue + } + return client, err + } + return nil, toolchain.ErrPinConflict +} + +func (a *App) buildToolchainSource(ctx context.Context, p *project) (toolchain.SourceRevision, error) { + return toolchain.ReadSourceRevision(ctx, a.kernel, p.root, a.globalToolchainRoot(), buildPlatform()) +} + +func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance buildInstance, detached uint64) (*buildprovider.Client, error) { settings, err := a.loadPluginPreferenceSources(ctx, instance.Manifest, p.root) if err != nil { return nil, err } + settingsKey, err := buildSettingsKey(settings.State) + if err != nil { + return nil, err + } rootURI, err := a.kernel.PluginDocumentURI(ctx, p.root, "auto") if err != nil { return nil, err } - client, retired, err := p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, &a.buildToolchainRevision, a.pluginLogDirectory) - if retired != nil { - a.retireBuildProvider(ctx, p, retired) + revision, err := a.buildToolchainSource(ctx, p) + if errors.Is(err, configfile.ErrConflict) { + return nil, errBuildProviderSourceChanged } + if err != nil { + return nil, err + } + launchKey := buildProviderLaunchKey{settings: settingsKey, toolchain: revision} + client, err := a.standaloneBuildProvider(ctx, p, instance, rootURI, settings.State, launchKey, detached) var shared *pluginbackend.SharedProviderError if !errors.As(err, &shared) { return client, err @@ -587,19 +624,6 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta return a.sharedBuildProvider(ctx, p, instance, shared.LanguageID) } -// retireBuildProvider closes, away from the window thread, a replaced provider after the requests -// it already had finished. A failure is logged under the -// user action whose request (ctx) replaced it. -func (a *App) retireBuildProvider(ctx context.Context, p *project, client *buildprovider.Client) { - a.tasks.running.Add(1) - go func() { - defer a.tasks.running.Done() - if err := p.buildSessions.retire(client); err != nil { - a.backgroundFailedIn(ctx, "build_provider_restart", err) - } - }() -} - // sharedBuildProvider attaches a build client to the language server of the // same plugin. If no server runs yet, it starts one and publishes it as the // window's language server so both build and editor requests reuse it. @@ -2300,11 +2324,17 @@ func (a *App) stopBuildSessions(p *project, closing bool) { a.endBuildSession(operation, "cancelled", a.text.Build.Cancelled) operation.ide.settle("cancelled", nil, operation.session.output.sequence, "") } - clients := p.buildSessions.detach(closing) + for _, client := range p.buildSessions.detach(closing) { + a.closingBuildProviders.add(p.ctx, client) + } + clients := a.closingBuildProviders.snapshot(func(_ *buildprovider.Client, owner context.Context) bool { + return owner == p.ctx + }) + origin := a.operationContext(context.Background()) a.tasks.running.Add(1) go func() { defer a.tasks.running.Done() - ctx, cancel := context.WithTimeout(context.Background(), buildStopTimeout) + ctx, cancel := context.WithTimeout(origin, buildStopTimeout) defer cancel() for _, operation := range operations { if operation.request != nil && operation.provider != nil { @@ -2313,7 +2343,9 @@ func (a *App) stopBuildSessions(p *project, closing bool) { } } for _, client := range clients { - _ = client.Close(ctx) + if err := a.closingBuildProviders.close(ctx, client); err != nil { + a.backgroundFailedIn(ctx, "build_provider_stop", err) + } } }() } diff --git a/desktop/internal/workbench/build_provider_cleanup.go b/desktop/internal/workbench/build_provider_cleanup.go new file mode 100644 index 0000000000..6675de41f5 --- /dev/null +++ b/desktop/internal/workbench/build_provider_cleanup.go @@ -0,0 +1,69 @@ +package workbench + +import ( + "context" + "errors" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" +) + +// closingBuildProviders retains native owners across project close. The +// project context is an identity, so reopening the same path has a new owner. +type closingBuildProviders struct { + mu sync.Mutex + clients map[*buildprovider.Client]context.Context +} + +// A failed disposal stays in closingBuildProviders. Uninstall can retry it +// after waiting for the launch that first attempted cleanup. +type trackedBuildProviderStopError struct{ cause error } + +func (e *trackedBuildProviderStopError) Error() string { return e.cause.Error() } +func (e *trackedBuildProviderStopError) Unwrap() error { return e.cause } + +func (r *closingBuildProviders) add(project context.Context, client *buildprovider.Client) { + r.mu.Lock() + defer r.mu.Unlock() + if r.clients == nil { + r.clients = make(map[*buildprovider.Client]context.Context) + } + r.clients[client] = project +} + +func (r *closingBuildProviders) snapshot(matches func(*buildprovider.Client, context.Context) bool) []*buildprovider.Client { + r.mu.Lock() + defer r.mu.Unlock() + var clients []*buildprovider.Client + for client, owner := range r.clients { + if matches(client, owner) { + clients = append(clients, client) + } + } + return clients +} + +func (r *closingBuildProviders) close(ctx context.Context, client *buildprovider.Client) error { + if err := client.Close(ctx); err != nil { + return err + } + r.mu.Lock() + delete(r.clients, client) + r.mu.Unlock() + return nil +} + +func (a *App) retireBuildProvider(ctx context.Context, client *buildprovider.Client) { + a.tasks.running.Add(1) + go func() { + defer a.tasks.running.Done() + drainCtx, cancelDrain := context.WithTimeout(context.Background(), buildRequestTimeout) + drainErr := client.Drain(drainCtx) + cancelDrain() + stopCtx, cancelStop := context.WithTimeout(context.Background(), buildStopTimeout) + defer cancelStop() + if err := errors.Join(drainErr, a.closingBuildProviders.close(stopCtx, client)); err != nil { + a.backgroundFailedIn(ctx, "build_provider_restart", err) + } + }() +} diff --git a/desktop/internal/workbench/build_provider_restart_test.go b/desktop/internal/workbench/build_provider_restart_test.go index 9534e5d196..ff693ebad5 100644 --- a/desktop/internal/workbench/build_provider_restart_test.go +++ b/desktop/internal/workbench/build_provider_restart_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" @@ -228,6 +229,170 @@ func TestBuildProviderRestartsAfterSavingProjectToolchain(t *testing.T) { } } +// A native window started as a separate process cannot receive an in-memory +// settings notification. Both clients still read the same catalog. +func TestBuildProviderObservesGlobalToolchainSavedByAnotherClient(t *testing.T) { + manifest := providerSettingsManifest(t) + h := providerTestsHarnessWith(t, manifest) + project := openProviderSettingsFixture(t, h) + instance := settingsFixtureInstance(h, manifest) + first := requestProvider(t, h, project, instance) + h.app.unsubscribeSettings() + + other := &App{kernel: h.app.kernel, store: h.store, plugins: h.app.plugins} + adapter := settingsToolchains{app: other} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + snapshot, err := adapter.LoadScope(ctx, "global") + if err != nil { + t.Fatal(err) + } + snapshot.Tools = append(snapshot.Tools, toolchain.Tool{ + ID: "dev.lithe.test.provider-tests:runtime", CustomHomes: []string{t.TempDir()}, + }) + tool := snapshot.Tools[len(snapshot.Tools)-1] + if _, err := adapter.Save(ctx, snapshot, []toolchain.Edit{{ + Tool: tool.ID, Pin: &core.ToolchainPin{Home: tool.CustomHomes[0]}, + }}); err != nil { + t.Fatal(err) + } + if second := requestProvider(t, h, project, instance); second == first { + t.Fatal("the next request reused a provider from before the global save") + } +} + +type toolchainStartupKernel struct { + *testKernel + starts atomic.Int32 + entered chan struct{} + release chan struct{} +} + +func (k *toolchainStartupKernel) StartPluginBackend(ctx context.Context, start core.PluginBackendStart) (core.PluginBackendStarted, error) { + if start.Role == "build" && k.starts.Add(1) == 1 { + close(k.entered) + select { + case <-k.release: + case <-ctx.Done(): + return core.PluginBackendStarted{}, ctx.Err() + } + } + return k.Client.StartPluginBackend(ctx, start) +} + +func TestBuildProviderRetriesAStartOvertakenByToolchainSave(t *testing.T) { + kernel := &toolchainStartupKernel{ + testKernel: &testKernel{Client: core.NewClient()}, + entered: make(chan struct{}), + release: make(chan struct{}), + } + manifest := providerSettingsManifest(t) + h := providerTestsHarnessWith(t, manifest, kernel) + project := openProviderSettingsFixture(t, h) + instance := settingsFixtureInstance(h, manifest) + ctx, cancel := context.WithTimeout(project.ctx, 40*time.Second) + defer cancel() + result := make(chan error, 1) + h.app.background(project, 0, func(context.Context) func(*App) { + _, err := h.app.buildProvider(ctx, project, instance) + result <- err + return nil + }) + select { + case <-kernel.entered: + case <-ctx.Done(): + t.Fatalf("provider did not reach its startup gate: %v", ctx.Err()) + } + saveFixtureToolchain(t, ctx, h.app) + close(kernel.release) + select { + case err := <-result: + if err != nil { + t.Fatalf("the original request failed after saving a toolchain: %v", err) + } + case <-ctx.Done(): + t.Fatalf("the original request did not finish: %v", ctx.Err()) + } + if got := kernel.starts.Load(); got != 2 { + t.Fatalf("provider starts = %d, want the superseded start followed by a retry", got) + } +} + +func saveFixtureToolchain(t *testing.T, ctx context.Context, app *App) { + t.Helper() + adapter := settingsToolchains{app: app} + snapshot, err := adapter.Load(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := adapter.Save(ctx, snapshot, []toolchain.Edit{{ + Tool: "dev.lithe.test.provider-tests:runtime", + Pin: &core.ToolchainPin{Home: filepath.ToSlash(t.TempDir()), Version: "1.0", Provider: "host:manual"}, + }}); err != nil { + t.Fatal(err) + } +} + +type toolchainRetirementKernel struct { + *uninstallOrderKernel + failOn atomic.Pointer[string] +} + +var errFixtureProviderStop = errors.New("injected provider stop failure") + +func (k *toolchainRetirementKernel) StopPluginBackend(ctx context.Context, id string) error { + err := k.Client.StopPluginBackend(ctx, id) + if target := k.failOn.Load(); target != nil && id == *target && k.failOn.CompareAndSwap(target, nil) { + return errors.Join(err, errFixtureProviderStop) + } + return err +} + +func TestUninstallStopsToolchainRetireesBeforeRemovingPackage(t *testing.T) { + kernel := &toolchainRetirementKernel{uninstallOrderKernel: &uninstallOrderKernel{ + testKernel: &testKernel{Client: core.NewClient()}, destroyed: make(chan bool, 4), + }} + manifest := providerSettingsManifest(t) + h := providerTestsHarnessWith(t, manifest, kernel) + project := openProviderSettingsFixture(t, h, "block.marker") + instance := settingsFixtureInstance(h, manifest) + kernel.directory = instance.PackageDirectory + first := requestProvider(t, h, project, instance) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) + defer cancel() + if _, err := first.Execute(ctx, "lithe/build/test", json.RawMessage(`{"root":".","scope":"workspace","operationID":"before-uninstall"}`), 60_000); err != nil { + t.Fatal(err) + } + saveFixtureToolchain(t, ctx, h.app) + second := requestProvider(t, h, project, instance) + if second == first || first.Closed() { + t.Fatal("expected an active provider and its draining predecessor") + } + oldSession := first.Session().ID + kernel.failOn.Store(&oldSession) + server, stop := h.app.detachPluginPrograms(instance.PluginID) + if err := h.app.plugins.Uninstall(ctx, instance.PluginID, server, stop); !errors.Is(err, errFixtureProviderStop) { + t.Fatalf("uninstall with a failed stop = %v, want the retired provider's failure", err) + } + if _, err := os.Stat(instance.PackageDirectory); err != nil { + t.Fatalf("uninstall removed the package while its retired provider's stop failed: %v", err) + } + server, stop = h.app.detachPluginPrograms(instance.PluginID) + if err := h.app.plugins.Uninstall(ctx, instance.PluginID, server, stop); err != nil { + t.Fatal(err) + } + for range 2 { + select { + case packagePresent := <-kernel.destroyed: + if !packagePresent { + t.Fatal("a provider was destroyed after package removal") + } + default: + t.Fatal("uninstall returned before both providers were destroyed") + } + } +} + // Closing the project closes a replaced provider at once with the others, without waiting for // the request it still serves. func TestClosingTheProjectClosesAReplacedProvider(t *testing.T) { diff --git a/desktop/internal/workbench/notifications.go b/desktop/internal/workbench/notifications.go index 109689d866..026eb818e3 100644 --- a/desktop/internal/workbench/notifications.go +++ b/desktop/internal/workbench/notifications.go @@ -28,7 +28,7 @@ type notification struct { text string detail string kind ui.ToastKind - count int + count int // at is when it came last. at time.Time // unread says it came after the history was last looked at. diff --git a/desktop/internal/workbench/plugin_programs.go b/desktop/internal/workbench/plugin_programs.go index 8f01644993..dd7734122e 100644 --- a/desktop/internal/workbench/plugin_programs.go +++ b/desktop/internal/workbench/plugin_programs.go @@ -105,7 +105,7 @@ func takePluginClients(clients map[string]*buildprovider.Client, id string) []pl return taken } -func stopPluginClients(ctx context.Context, mu *sync.Mutex, clients []pluginClient, pending func(context.Context) error) error { +func stopPluginClients(ctx context.Context, mu *sync.Mutex, clients []pluginClient) error { var failures []error for _, owned := range clients { if err := owned.client.Close(ctx); err != nil { @@ -118,16 +118,14 @@ func stopPluginClients(ctx context.Context, mu *sync.Mutex, clients []pluginClie } mu.Unlock() } - failures = append(failures, pending(ctx)) return errors.Join(failures...) } func (r *buildRuntime) detachPlugin(id string) func(context.Context) error { - wait := r.launches.stop(id) r.mu.Lock() clients := append(takePluginClients(r.providers, id), takePluginClients(r.shared, id)...) r.mu.Unlock() - return func(ctx context.Context) error { return stopPluginClients(ctx, &r.mu, clients, wait) } + return func(ctx context.Context) error { return stopPluginClients(ctx, &r.mu, clients) } } func (r *vcsRuntime) detachPlugin(id string) func(context.Context) error { @@ -135,7 +133,7 @@ func (r *vcsRuntime) detachPlugin(id string) func(context.Context) error { r.mu.Lock() clients := takePluginClients(r.clients, id) r.mu.Unlock() - return func(ctx context.Context) error { return stopPluginClients(ctx, &r.mu, clients, wait) } + return func(ctx context.Context) error { return errors.Join(stopPluginClients(ctx, &r.mu, clients), wait(ctx)) } } // detachPluginPrograms takes native handles on the UI thread, then returns the @@ -152,6 +150,7 @@ func (a *App) detachPluginPrograms(id string) (*pluginservice.LanguageSession, f } server := tab.detachPluginServer(id) stops = append(stops, tab.pluginDiscoveryLaunches.stop(id)) + stops = append(stops, tab.buildProviderLaunches.stop(id)) if p := tab.project; p != nil { p.revokePluginBuildTests(id) stops = append(stops, p.buildSessions.detachPlugin(id)) @@ -183,6 +182,18 @@ func (a *App) detachPluginPrograms(id string) (*pluginservice.LanguageSession, f return errors.Join(failures...) }) } + // A provider can still own native files after retirement or project close. + // Take these after the active starts and sessions above have stopped. + stops = append(stops, func(ctx context.Context) error { + clients := tab.closingBuildProviders.snapshot(func(client *buildprovider.Client, _ context.Context) bool { + return client.Session().PluginID == id + }) + var failures []error + for _, client := range clients { + failures = append(failures, tab.closingBuildProviders.close(ctx, client)) + } + return errors.Join(failures...) + }) if tab == a { currentServer = server } else { @@ -214,8 +225,8 @@ func (a *App) allowPluginPrograms(id string) { delete(tab.pluginServerSuppressed, id) tab.pluginServerMu.Unlock() tab.pluginDiscoveryLaunches.allow(id) + tab.buildProviderLaunches.allow(id) if p := tab.project; p != nil { - p.buildSessions.launches.allow(id) if p.vcs.launches != nil { p.vcs.launches.allow(id) } diff --git a/desktop/internal/workbench/settings_publication.go b/desktop/internal/workbench/settings_publication.go index 513445fc06..7da6926310 100644 --- a/desktop/internal/workbench/settings_publication.go +++ b/desktop/internal/workbench/settings_publication.go @@ -50,18 +50,6 @@ func (a *App) unsubscribeSettings() { } } -func (a *App) advanceGlobalBuildToolchainRevision() { - a.buildToolchainRevision.Add(1) - root := a.globalToolchainRoot() - settingsWindows.Lock() - defer settingsWindows.Unlock() - for target := range settingsWindows.live { - if target != a && target.globalToolchainRoot() == root { - target.buildToolchainRevision.Add(1) - } - } -} - // Publication has already committed. A page cancellation must not undo delivery; // an independent deadline bounds native identity reads and backpressure instead. func (a *App) publishSettings(editor pluginservice.SettingsEditor, scope string, effects []string) error { diff --git a/desktop/internal/workbench/settings_publication_test.go b/desktop/internal/workbench/settings_publication_test.go index 84ea4feb37..7c3d26b503 100644 --- a/desktop/internal/workbench/settings_publication_test.go +++ b/desktop/internal/workbench/settings_publication_test.go @@ -15,24 +15,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) -func TestGlobalBuildToolchainRevisionReachesOnlyMatchingSettingsWindows(t *testing.T) { - preferences := t.TempDir() - source := &App{store: store.At(preferences)} - matching := &App{store: store.At(preferences)} - unrelated := &App{store: store.At(t.TempDir())} - for _, window := range []*App{source, matching, unrelated} { - window.subscribeSettings() - t.Cleanup(window.unsubscribeSettings) - } - source.advanceGlobalBuildToolchainRevision() - if source.buildToolchainRevision.Load() != 1 || matching.buildToolchainRevision.Load() != 1 { - t.Fatal("global toolchain save did not invalidate both windows using the same settings") - } - if unrelated.buildToolchainRevision.Load() != 0 { - t.Fatal("global toolchain save invalidated a window using different settings") - } -} - func TestSettingsPublicationReachesMatchingWindowsAndKeepsProjectLayers(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index 1db27ca108..accafd8809 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -1,7 +1,6 @@ package workbench import ( - "bytes" "context" "errors" @@ -116,11 +115,7 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapshot, edits []toolchain.Edit) (updated toolchain.Snapshot, err error) { defer func() { s.recordFailure(ctx, "toolchain_settings_save", err) }() if snapshot.Global { - committed, err := snapshot.SaveCatalog(ctx, s.app.kernel, edits) - if committed { - s.app.advanceGlobalBuildToolchainRevision() - } - if err != nil { + if _, err := snapshot.SaveCatalog(ctx, s.app.kernel, edits); err != nil { return snapshot, err } s.app.post(func(a *App) { a.retryFailedPluginServers() }) @@ -137,13 +132,7 @@ func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapsho if err := snapshot.CheckWorkspace(ctx, *root); err != nil { return snapshot, errors.Join(toolchain.ErrPinConflict, err) } - _, saved, err := snapshot.SavePins(ctx, s.app.kernel, edits) - if errors.Is(err, toolchain.ErrPinCommitted) || (err == nil && !bytes.Equal(snapshot.Baseline, saved)) { - if s.app.toolchainRoot.Load() == root { - s.app.buildToolchainRevision.Add(1) - } - } - if err != nil { + if _, _, err := snapshot.SavePins(ctx, s.app.kernel, edits); err != nil { return snapshot, err } s.app.post(func(a *App) { a.retryFailedPluginServers() }) diff --git a/shared/platform-feature-matrix/features/build-system-plugins.json b/shared/platform-feature-matrix/features/build-system-plugins.json index 2222328f09..8e50a7c091 100644 --- a/shared/platform-feature-matrix/features/build-system-plugins.json +++ b/shared/platform-feature-matrix/features/build-system-plugins.json @@ -2,7 +2,7 @@ "id": "build-system-plugins", "area": "扩展", "group": "插件与主题", - "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。保存项目工具链或全局默认后,独立构建提供者在下一次请求按最新配置启动,已有请求排空后关闭旧进程。", + "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。保存项目工具链或全局默认后,独立构建提供者按已保存的配置来源判断是否重启,覆盖共用来源的独立窗口。初始化期间保存时,在原请求期限内重启。已有请求排空后关闭旧进程,卸载时等待退役进程退出再删包。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", From 3900193c85133fcfee547550f1458ff04395311b Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 19:29:56 +0800 Subject: [PATCH 3/4] fix(desktop): scope build refresh to host toolchain launches --- ...-11-20-build-provider-toolchain-refresh.md | 20 +- .../internal/pluginbackend/pluginbackend.go | 13 ++ .../pluginbackend/pluginbackend_test.go | 20 ++ desktop/internal/workbench/build.go | 70 +++++-- .../workbench/build_provider_restart_test.go | 196 +++++++++++++++--- .../features/build-system-plugins.json | 2 +- 6 files changed, 264 insertions(+), 57 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md index 3b375dda39..f941fdc6c8 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md +++ b/.agents/notes/implemented/bug-fix/2026-11-20-build-provider-toolchain-refresh.md @@ -5,7 +5,7 @@ ## 先说结论 独立构建提供者(在后台常驻、执行插件构建或测试请求的进程)在启动时绑定工作环境。 -项目工具链或全局默认值保存后,下一次请求重新启动提供者,独立窗口进程也能读取新值。 +通过宿主工具链启动的提供者会在项目 pin 或全局默认值保存后重新启动,独立窗口进程也能读取新值。 已提交的请求由旧进程处理完。初始化期间发现配置已变更会在原请求期限内重新启动。 ## 问题 @@ -15,10 +15,12 @@ ## 决策 -宿主按实际来源文件的身份及内容判断进程能否复用。项目 pin 只影响读取该项目来源的实例, +启动器先执行 Core 的启动计划。在实际解析宿主工具前,工作台才读取来源文件的身份和内容,并把 +这份版本记入会话复用键。项目 pin 只影响读取该项目来源的实例, 全局目录里的工具链配置影响共用该目录的实例。复用前和初始化完成后均核对文件版本。 无变化的保存不改文件。原子替换即使恢复相同的内容,也会因文件身份变化被识别。 -与语言服务器共享的提供者仍由语言服务器管理,不能通过这条路径另起一份。 +直接运行打包程序或打包运行时的提供者沿用插件设置复用键,工具链文件读取失败时仍可运行。 +与语言服务器共享的提供者继续走语言服务器的启动与复用机制。 旧进程在后台排空。退役进程和项目关闭时仍在清理的进程继续登记在工作台,直至完成原生销毁。 例如卸载插件时先阻止新启动,等登记中的相关进程退出,再删除包及状态目录。切换项目时 @@ -31,14 +33,16 @@ ## 后果 -按请求读取既有的有界配置文件,不启动探测或常驻轮询。作用域内的独立提供者下次使用时会重新 -解析并启动,即使某个提供者不依赖刚变更的工具。连续三次读取或启动均被来源变动打断时,返回 -工具链冲突供用户重试。 +依赖工具链的会话按请求读取既有的有界配置文件。读取版本本身只访问这两个文件。 +来源更新时会重新解析并启动,即使改动的是同一个来源中的另一个工具。连续三次读取或启动 +均被来源变动打断时,返回工具链冲突供用户重试。 ## 验证 -在 `desktop/internal/workbench/build_provider_restart_test.go` 用合成提供者验证项目 pin 保存和重复保存、 -未接收通知的另一个客户端写入、初始化期间保存、已有请求排空,以及卸载前等待退役进程销毁。 +在 `desktop/internal/workbench/build_provider_restart_test.go` 使用 Core 的运行时启动计划验证项目 pin +保存和重复保存、另一个客户端写入、初始化期间保存、已有请求排空,以及卸载前等待退役进程销毁。 +初始化重试用例检查两次启动的可执行文件路径。打包提供者用例覆盖项目和全局配置文件无法读取时的 +复用和重启。共享提供者选用语言服务器的行为见 `desktop/internal/pluginbackend/pluginbackend_test.go`。 原生窗口的验证动作是先用旧工具执行,再保存新工具并重跑,核对两次实际启动的路径。 ## 适用范围 diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index 2a964b3d87..baaa3508ad 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -142,6 +142,9 @@ type StartRequest struct { // ManagedTools are per-launch installations verified by the managed runtime resolver. // They are never stored as global defaults or used by a different plugin/session. ManagedTools map[string]ToolExecutable + // BeforeResolveTool lets a launch owner capture the sources that determine + // the selected installation. It runs only before host toolchain resolution. + BeforeResolveTool func(context.Context) error // Preparation starts a private resolver without workspace services or the // cross-plugin function relay. Only direct host invocations may reach it. Preparation bool @@ -382,6 +385,11 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if r.toolEntries == nil { return Session{}, fmt.Errorf("%w: this host cannot instantiate tool entries", ErrRequest) } + if executable == "" && request.BeforeResolveTool != nil { + if err := request.BeforeResolveTool(ctx); err != nil { + return Session{}, err + } + } tool, err := r.toolEntries(ctx, request.PluginID, request.WorkingDirectory, ToolEntryLaunch{ Tool: plan.Launch.Tool, Executable: executable, Entry: resolved.Entry, MinimumVersion: plan.Launch.MinimumVersion, RuntimeArguments: plan.Launch.RuntimeArguments, Arguments: plan.Arguments, @@ -398,6 +406,11 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if r.tools == nil { return Session{}, fmt.Errorf("%w: this host cannot resolve tool launches", ErrRequest) } + if request.BeforeResolveTool != nil { + if err := request.BeforeResolveTool(ctx); err != nil { + return Session{}, err + } + } var err error tool, err = r.tools(ctx, request.PluginID, request.WorkingDirectory, plan.Launch.Tool) if err != nil { diff --git a/desktop/internal/pluginbackend/pluginbackend_test.go b/desktop/internal/pluginbackend/pluginbackend_test.go index a403338ef8..78f3fc8910 100644 --- a/desktop/internal/pluginbackend/pluginbackend_test.go +++ b/desktop/internal/pluginbackend/pluginbackend_test.go @@ -745,6 +745,26 @@ func TestManagedToolSelectionBelongsOnlyToOneLaunch(t *testing.T) { } } +func TestSharedBuildProviderDoesNotResolveToolsInTheBuildRunner(t *testing.T) { + root := backendPackage(t) + plan := core.PluginBackendPlan{BuildProvider: &core.PluginBuildProviderPlan{ + BuildSystemID: "fixture-build", LanguageServer: "fixture-language", + }} + plan.Launch.Kind, plan.Launch.Tool = pluginhost.LaunchTool, "fixture-runtime" + kernel := &fakeKernel{plan: plan} + runner := New(kernel, echoServices(t)) + request := startRequest(root) + request.BuildSystemID = plan.BuildProvider.BuildSystemID + request.BeforeResolveTool = func(context.Context) error { + t.Fatal("a shared build provider tried to read a toolchain source") + return nil + } + var shared *SharedProviderError + if _, err := runner.Start(context.Background(), request); !errors.As(err, &shared) || shared.LanguageID != "fixture-language" { + t.Fatalf("start = %v, want the shared language server", err) + } +} + func TestToolEntryUsesCoreInstantiationAfterNativeVerification(t *testing.T) { root := backendPackage(t) entry := filepath.Join(root, "入口 with 空格.script") diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 88eb5449a5..cf2216385c 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -388,19 +388,20 @@ type buildRuntime struct { } type buildProviderLaunchKey struct { - settings string - toolchain toolchain.SourceRevision + settings string + usesToolchain bool + toolchain toolchain.SourceRevision } func (key buildProviderLaunchKey) equal(other buildProviderLaunchKey) bool { - return key.settings == other.settings && key.toolchain.Equal(other.toolchain) + return key.settings == other.settings && key.usesToolchain == other.usesToolchain && key.toolchain.Equal(other.toolchain) } var errBuildProviderSourceChanged = errors.New("build provider source changed during launch") // standaloneBuildProvider starts a process outside the session lock. Only a // start from the current project and saved toolchain sources can be published. -func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance buildInstance, rootURI string, settings core.PluginSettingsState, launchKey buildProviderLaunchKey, detached uint64) (*buildprovider.Client, error) { +func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance buildInstance, rootURI string, settings core.PluginSettingsState, settingsKey string, detached uint64) (*buildprovider.Client, error) { r := &p.buildSessions key := instance.PluginID + "\x00" + instance.BuildSystemID r.mu.Lock() @@ -413,11 +414,35 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance return nil, buildprovider.ErrClosed } client := r.providers[key] - if client != nil { - if !client.Closed() && r.launchKeys[key].equal(launchKey) { + if cached := r.launchKeys[key]; client != nil && !client.Closed() && cached.settings == settingsKey { + if !cached.usesToolchain { + r.mu.Unlock() + return client, nil + } + r.mu.Unlock() + revision, err := a.buildToolchainSource(ctx, p) + if err != nil { + return nil, err + } + r.mu.Lock() + if r.closed || r.detached != detached { + r.mu.Unlock() + return nil, buildprovider.ErrClosed + } + if err := ctx.Err(); err != nil { + r.mu.Unlock() + return nil, err + } + if r.providers[key] != client { + r.mu.Unlock() + return nil, errBuildProviderSourceChanged + } + if !client.Closed() && cached.toolchain.Equal(revision) { r.mu.Unlock() return client, nil } + } + if client != nil { // Register retirement before releasing the lock that uninstall uses to // take active sessions. There must be no gap in native ownership. a.closingBuildProviders.add(p.ctx, client) @@ -437,6 +462,7 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance return nil, err } } + launchKey := buildProviderLaunchKey{settings: settingsKey} started, startErr := buildprovider.Launch(ctx, a.plugins.Backend, pluginbackend.StartRequest{ Manifest: instance.Manifest, PackageDirectory: instance.PackageDirectory, @@ -453,6 +479,14 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance ProjectSettings: settings.ProjectSettings, RootURI: rootURI, WorkingDirectory: p.root, + BeforeResolveTool: func(ctx context.Context) error { + revision, err := a.buildToolchainSource(ctx, p) + if err != nil { + return err + } + launchKey.toolchain, launchKey.usesToolchain = revision, true + return nil + }, }) var shared *pluginbackend.SharedProviderError if errors.As(startErr, &shared) { @@ -461,7 +495,11 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance if startErr == nil { startErr = started.WaitReady(ctx) } - latest, revisionErr := a.buildToolchainSource(ctx, p) + var latest toolchain.SourceRevision + var revisionErr error + if launchKey.usesToolchain { + latest, revisionErr = a.buildToolchainSource(ctx, p) + } r.mu.Lock() open := !r.closed && r.detached == detached && ctx.Err() == nil current := open && revisionErr == nil && launchKey.toolchain.Equal(latest) @@ -495,7 +533,7 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance } return nil, buildprovider.ErrClosed } - if errors.Is(revisionErr, configfile.ErrConflict) { + if revisionErr == errBuildProviderSourceChanged { return nil, errBuildProviderSourceChanged } if revisionErr != nil { @@ -592,7 +630,11 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta } func (a *App) buildToolchainSource(ctx context.Context, p *project) (toolchain.SourceRevision, error) { - return toolchain.ReadSourceRevision(ctx, a.kernel, p.root, a.globalToolchainRoot(), buildPlatform()) + revision, err := toolchain.ReadSourceRevision(ctx, a.kernel, p.root, a.globalToolchainRoot(), buildPlatform()) + if errors.Is(err, configfile.ErrConflict) { + return revision, errBuildProviderSourceChanged + } + return revision, err } func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance buildInstance, detached uint64) (*buildprovider.Client, error) { @@ -608,15 +650,7 @@ func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance if err != nil { return nil, err } - revision, err := a.buildToolchainSource(ctx, p) - if errors.Is(err, configfile.ErrConflict) { - return nil, errBuildProviderSourceChanged - } - if err != nil { - return nil, err - } - launchKey := buildProviderLaunchKey{settings: settingsKey, toolchain: revision} - client, err := a.standaloneBuildProvider(ctx, p, instance, rootURI, settings.State, launchKey, detached) + client, err := a.standaloneBuildProvider(ctx, p, instance, rootURI, settings.State, settingsKey, detached) var shared *pluginbackend.SharedProviderError if !errors.As(err, &shared) { return client, err diff --git a/desktop/internal/workbench/build_provider_restart_test.go b/desktop/internal/workbench/build_provider_restart_test.go index ff693ebad5..c36c99b2ef 100644 --- a/desktop/internal/workbench/build_provider_restart_test.go +++ b/desktop/internal/workbench/build_provider_restart_test.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "strings" "sync/atomic" "testing" @@ -18,7 +19,10 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) -const restartFixtureID = "dev.lithe.test.provider-tests" +const ( + restartFixtureID = "dev.lithe.test.provider-tests" + restartFixtureTool = restartFixtureID + ":runtime" +) // providerSettingsManifest is the provider fixture with one global setting that its launch passes // in initializationOptions, so each process records the value it started with. @@ -42,6 +46,60 @@ func providerSettingsManifest(t *testing.T) string { return string(encoded) } +// These providers actually launch through Core's runtime plan and the host's +// toolchain resolver. The packaged fixture remains independent of this source. +func providerToolchainManifest(t *testing.T) string { + t.Helper() + t.Setenv(syntheticWorkbenchInterpMarkerEnv, filepath.Join(t.TempDir(), "version-probed")) + var manifest map[string]any + if err := json.Unmarshal([]byte(providerSettingsManifest(t)), &manifest); err != nil { + t.Fatal(err) + } + manifest["requires"].(map[string]any)["toolDefinitions"] = 0 + manifest["requiresTools"] = []string{restartFixtureTool} + manifest["toolDefinitions"] = []any{map[string]any{ + "id": restartFixtureTool, "displayName": "Fixture runtime", + "executableLayouts": []any{map[string]string{"path": fixtureRuntimePath()}}, + "executables": []any{ + map[string]string{"id": "shell", "kind": "command", "command": "lithe-test-provider-runtime"}, + map[string]string{"id": "installed", "kind": "toolchain", "scope": "installed"}, + }, + "commands": []string{"lithe-test-provider-runtime"}, + "version": map[string]any{ + "arguments": []string{"--version"}, + "pattern": `SyntheticInterp (\d+(?:\.\d+)*)`, + }, + "launch": []string{"${executable}", "${runtimeArguments}", "${arguments}", "${entry}"}, + }} + system := manifest["buildSystems"].([]any)[0].(map[string]any) + system["provider"].(map[string]any)["launch"] = map[string]string{ + "kind": "runtime", "tool": restartFixtureTool, "entry": "plugin.json", + } + encoded, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + return string(encoded) +} + +func fixtureRuntimePath() string { + if runtime.GOOS == "windows" { + return "bin/fixture-runtime.exe" + } + return "bin/fixture-runtime" +} + +func newFixtureRuntime(t *testing.T) string { + t.Helper() + home := t.TempDir() + path := filepath.Join(home, filepath.FromSlash(fixtureRuntimePath())) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + copyTestBinary(t, path) + return filepath.ToSlash(home) +} + // openProviderSettingsFixture opens a workspace the settings fixture provider serves. func openProviderSettingsFixture(t *testing.T, h *harness, markers ...string) *project { t.Helper() @@ -183,14 +241,15 @@ func TestReplacedBuildProviderFinishesTheRequestItHas(t *testing.T) { } func TestBuildProviderRestartsAfterSavingProjectToolchain(t *testing.T) { - manifest := providerSettingsManifest(t) + manifest := providerToolchainManifest(t) h := providerTestsHarnessWith(t, manifest) project := openProviderSettingsFixture(t, h, "block.marker") instance := settingsFixtureInstance(h, manifest) - first := requestProvider(t, h, project, instance) adapter := settingsToolchains{app: h.app} ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() + saveFixtureToolchain(t, ctx, h.app, newFixtureRuntime(t)) + first := requestProvider(t, h, project, instance) operation, err := first.Execute(ctx, "lithe/build/test", json.RawMessage(`{"root":".","scope":"workspace","operationID":"before-toolchain-save"}`), 60_000) if err != nil { t.Fatal(err) @@ -200,8 +259,8 @@ func TestBuildProviderRestartsAfterSavingProjectToolchain(t *testing.T) { t.Fatal(err) } changes := []toolchain.Edit{{ - Tool: "dev.lithe.test.provider-tests:runtime", - Pin: &core.ToolchainPin{Home: filepath.ToSlash(t.TempDir()), Version: "1.0", Provider: "host:manual"}, + Tool: restartFixtureTool, + Pin: &core.ToolchainPin{Home: newFixtureRuntime(t), Version: "3.12.4", Provider: "host:manual"}, }} snapshot, err = adapter.Save(ctx, snapshot, changes) if err != nil { @@ -229,33 +288,81 @@ func TestBuildProviderRestartsAfterSavingProjectToolchain(t *testing.T) { } } +func TestPackagedBuildProviderKeepsWorkingWithUnreadableToolchainSources(t *testing.T) { + for _, scope := range []string{"project", "global"} { + t.Run(scope, func(t *testing.T) { + manifest := providerSettingsManifest(t) + h := providerTestsHarnessWith(t, manifest) + project := openProviderSettingsFixture(t, h) + instance := settingsFixtureInstance(h, manifest) + first := requestProvider(t, h, project, instance) + + ctx, cancel := context.WithTimeout(project.ctx, 20*time.Second) + defer cancel() + var target string + if scope == "project" { + plan, err := h.app.kernel.ToolchainPinStorage(ctx) + if err != nil { + t.Fatal(err) + } + target = filepath.Join(project.root, filepath.FromSlash(plan.DocumentRelativePath)) + } else { + catalog, err := h.app.kernel.ReadToolchainCatalogForWorkspace(ctx, nil, buildPlatform(), "") + if err != nil { + t.Fatal(err) + } + target = filepath.Join(h.app.globalToolchainRoot(), filepath.FromSlash(catalog.Storage.RelativePath)) + } + if err := os.Remove(target); err != nil && !errors.Is(err, os.ErrNotExist) { + t.Fatal(err) + } + if err := os.MkdirAll(target, 0o700); err != nil { + t.Fatal(err) + } + if reused := requestProvider(t, h, project, instance); reused != first { + t.Fatal("reusing a packaged provider depended on an unrelated toolchain file") + } + saveProviderHeap(t, h, instance, 2048) + if restarted := requestProvider(t, h, project, instance); restarted == first { + t.Fatal("plugin settings did not restart the packaged provider") + } + }) + } +} + // A native window started as a separate process cannot receive an in-memory // settings notification. Both clients still read the same catalog. func TestBuildProviderObservesGlobalToolchainSavedByAnotherClient(t *testing.T) { - manifest := providerSettingsManifest(t) + manifest := providerToolchainManifest(t) h := providerTestsHarnessWith(t, manifest) project := openProviderSettingsFixture(t, h) instance := settingsFixtureInstance(h, manifest) - first := requestProvider(t, h, project, instance) h.app.unsubscribeSettings() other := &App{kernel: h.app.kernel, store: h.store, plugins: h.app.plugins} adapter := settingsToolchains{app: other} ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - snapshot, err := adapter.LoadScope(ctx, "global") - if err != nil { - t.Fatal(err) - } - snapshot.Tools = append(snapshot.Tools, toolchain.Tool{ - ID: "dev.lithe.test.provider-tests:runtime", CustomHomes: []string{t.TempDir()}, - }) - tool := snapshot.Tools[len(snapshot.Tools)-1] - if _, err := adapter.Save(ctx, snapshot, []toolchain.Edit{{ - Tool: tool.ID, Pin: &core.ToolchainPin{Home: tool.CustomHomes[0]}, - }}); err != nil { - t.Fatal(err) + save := func(home string) { + t.Helper() + snapshot, err := adapter.LoadScope(ctx, "global") + if err != nil { + t.Fatal(err) + } + for i := range snapshot.Tools { + if snapshot.Tools[i].ID == restartFixtureTool { + snapshot.Tools[i].CustomHomes = append(snapshot.Tools[i].CustomHomes, home) + } + } + if _, err := adapter.Save(ctx, snapshot, []toolchain.Edit{{ + Tool: restartFixtureTool, Pin: &core.ToolchainPin{Home: home}, + }}); err != nil { + t.Fatal(err) + } } + save(newFixtureRuntime(t)) + first := requestProvider(t, h, project, instance) + save(newFixtureRuntime(t)) if second := requestProvider(t, h, project, instance); second == first { t.Fatal("the next request reused a provider from before the global save") } @@ -266,16 +373,24 @@ type toolchainStartupKernel struct { starts atomic.Int32 entered chan struct{} release chan struct{} + paths chan string } func (k *toolchainStartupKernel) StartPluginBackend(ctx context.Context, start core.PluginBackendStart) (core.PluginBackendStarted, error) { - if start.Role == "build" && k.starts.Add(1) == 1 { - close(k.entered) + if start.Role == "build" { select { - case <-k.release: + case k.paths <- start.ExecutablePath: case <-ctx.Done(): return core.PluginBackendStarted{}, ctx.Err() } + if k.starts.Add(1) == 1 { + close(k.entered) + select { + case <-k.release: + case <-ctx.Done(): + return core.PluginBackendStarted{}, ctx.Err() + } + } } return k.Client.StartPluginBackend(ctx, start) } @@ -285,13 +400,16 @@ func TestBuildProviderRetriesAStartOvertakenByToolchainSave(t *testing.T) { testKernel: &testKernel{Client: core.NewClient()}, entered: make(chan struct{}), release: make(chan struct{}), + paths: make(chan string, 4), } - manifest := providerSettingsManifest(t) + manifest := providerToolchainManifest(t) h := providerTestsHarnessWith(t, manifest, kernel) project := openProviderSettingsFixture(t, h) instance := settingsFixtureInstance(h, manifest) ctx, cancel := context.WithTimeout(project.ctx, 40*time.Second) defer cancel() + oldHome, newHome := newFixtureRuntime(t), newFixtureRuntime(t) + saveFixtureToolchain(t, ctx, h.app, oldHome) result := make(chan error, 1) h.app.background(project, 0, func(context.Context) func(*App) { _, err := h.app.buildProvider(ctx, project, instance) @@ -300,10 +418,12 @@ func TestBuildProviderRetriesAStartOvertakenByToolchainSave(t *testing.T) { }) select { case <-kernel.entered: + case err := <-result: + t.Fatalf("provider exited before reaching its startup gate: %v", err) case <-ctx.Done(): t.Fatalf("provider did not reach its startup gate: %v", ctx.Err()) } - saveFixtureToolchain(t, ctx, h.app) + saveFixtureToolchain(t, ctx, h.app, newHome) close(kernel.release) select { case err := <-result: @@ -316,9 +436,24 @@ func TestBuildProviderRetriesAStartOvertakenByToolchainSave(t *testing.T) { if got := kernel.starts.Load(); got != 2 { t.Fatalf("provider starts = %d, want the superseded start followed by a retry", got) } + for _, home := range []string{oldHome, newHome} { + var path string + select { + case path = <-kernel.paths: + default: + t.Fatal("the startup did not report its executable") + } + want, err := filepath.EvalSymlinks(filepath.Join(home, filepath.FromSlash(fixtureRuntimePath()))) + if err != nil { + t.Fatal(err) + } + if !sameProjectRoot(path, want) { + t.Fatalf("provider executable = %q, want %q", path, want) + } + } } -func saveFixtureToolchain(t *testing.T, ctx context.Context, app *App) { +func saveFixtureToolchain(t *testing.T, ctx context.Context, app *App, home string) { t.Helper() adapter := settingsToolchains{app: app} snapshot, err := adapter.Load(ctx) @@ -326,8 +461,8 @@ func saveFixtureToolchain(t *testing.T, ctx context.Context, app *App) { t.Fatal(err) } if _, err := adapter.Save(ctx, snapshot, []toolchain.Edit{{ - Tool: "dev.lithe.test.provider-tests:runtime", - Pin: &core.ToolchainPin{Home: filepath.ToSlash(t.TempDir()), Version: "1.0", Provider: "host:manual"}, + Tool: restartFixtureTool, + Pin: &core.ToolchainPin{Home: home, Version: "3.12.4", Provider: "host:manual"}, }}); err != nil { t.Fatal(err) } @@ -352,18 +487,19 @@ func TestUninstallStopsToolchainRetireesBeforeRemovingPackage(t *testing.T) { kernel := &toolchainRetirementKernel{uninstallOrderKernel: &uninstallOrderKernel{ testKernel: &testKernel{Client: core.NewClient()}, destroyed: make(chan bool, 4), }} - manifest := providerSettingsManifest(t) + manifest := providerToolchainManifest(t) h := providerTestsHarnessWith(t, manifest, kernel) project := openProviderSettingsFixture(t, h, "block.marker") instance := settingsFixtureInstance(h, manifest) kernel.directory = instance.PackageDirectory - first := requestProvider(t, h, project, instance) ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) defer cancel() + saveFixtureToolchain(t, ctx, h.app, newFixtureRuntime(t)) + first := requestProvider(t, h, project, instance) if _, err := first.Execute(ctx, "lithe/build/test", json.RawMessage(`{"root":".","scope":"workspace","operationID":"before-uninstall"}`), 60_000); err != nil { t.Fatal(err) } - saveFixtureToolchain(t, ctx, h.app) + saveFixtureToolchain(t, ctx, h.app, newFixtureRuntime(t)) second := requestProvider(t, h, project, instance) if second == first || first.Closed() { t.Fatal("expected an active provider and its draining predecessor") diff --git a/shared/platform-feature-matrix/features/build-system-plugins.json b/shared/platform-feature-matrix/features/build-system-plugins.json index 8e50a7c091..d0ee3a0fb2 100644 --- a/shared/platform-feature-matrix/features/build-system-plugins.json +++ b/shared/platform-feature-matrix/features/build-system-plugins.json @@ -2,7 +2,7 @@ "id": "build-system-plugins", "area": "扩展", "group": "插件与主题", - "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。保存项目工具链或全局默认后,独立构建提供者按已保存的配置来源判断是否重启,覆盖共用来源的独立窗口。初始化期间保存时,在原请求期限内重启。已有请求排空后关闭旧进程,卸载时等待退役进程退出再删包。", + "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。通过宿主工具链启动的独立构建提供者按已保存的项目和全局来源判断是否重启,覆盖共用来源的独立窗口。直接运行打包程序的提供者可在工具链来源不可读时继续使用。初始化期间保存时,在原请求期限内重启。已有请求排空后关闭旧进程,卸载时等待退役进程退出再删包。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", From 4cdcb5580b879bfcc2372f2f563810be9ef4178f Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 20:11:17 +0800 Subject: [PATCH 4/4] Preserve project tree selection when focus clears --- .../2026-11-20-primary-click-selection.md | 3 +- .github/workflows/desktop-ci.yml | 19 +++++++ .../workbench/filetree_actions_test.go | 13 +++-- .../workbench/filetree_focus_visual_test.go | 49 +++++++++++++++++++ desktop/internal/workbench/filetree_test.go | 25 ++++++++++ desktop/internal/workbench/filetree_view.go | 7 ++- docs/ci-builds.md | 2 + .../features/workspace-tree-batch-files.json | 6 ++- 8 files changed, 116 insertions(+), 8 deletions(-) create mode 100644 desktop/internal/workbench/filetree_focus_visual_test.go diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-primary-click-selection.md b/.agents/notes/implemented/bug-fix/2026-11-20-primary-click-selection.md index 906d24d468..d23a257fd3 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-20-primary-click-selection.md +++ b/.agents/notes/implemented/bug-fix/2026-11-20-primary-click-selection.md @@ -16,7 +16,7 @@ Core 的第一次 toggle(增减一行选择)只把点击目标加入标记 - 没有批量标记和范围锚点时,Core 先把可见的、非根的当前行纳入,再切换点击行。已有批量继续只切换一行;隐藏旧行不因首次点击被意外加入。 - 文件树与 Git 分支列表有批量状态时只用批量标记呈现选中底色;取消选中的当前行不继续显示为已选。 -- 文件树记录已观察的焦点,指针焦点先交给点击处理,键盘焦点仍更新当前行。窗口失焦和恢复不清除批量。 +- 文件树记录已观察的焦点,指针焦点先交给点击处理,键盘焦点仍更新当前行。窗口失焦和恢复不清除批量。焦点清空时只记录焦点变化,行匹配要求焦点 ID 非空。目录列表刚加入的行在首次绘制前也使用空 ID,两者相等会把原选中项误移到新行。 - macOS Command 和 Windows Control 由 Viva 已有的主修饰键定义提供,不新增系统按键适配。 ## 考虑过的备选方案 @@ -33,6 +33,7 @@ Core 的第一次 toggle(增减一行选择)只把点击目标加入标记 - Core 共享 row-selection fixture 修改后先红后绿,覆盖首次追加保留、点击当前行取消、隐藏标记、范围选择和根保护。 - `desktop/internal/workbench/filetree_test.go` 的真实驱动点击先复现旧选择丢失,修复后覆盖追加、取消、全部选中底色、普通点击清除及键盘焦点回归。 +- `TestProjectTreeKeepsSelectionWhenFocusClearsBeforeNewRowsPaint` 控制焦点清空与目录行首次绘制的顺序,修复前选中新增行,修复后保留原选中行。`TestProjectTreeLocateGivesUpOnAFileThatIsGone` 覆盖删除活跃文件后定位的完整流程,`TestVisualProjectTreeMissingFile` 采集明暗主题的结果。 - `desktop/internal/workbench/branch_delete_test.go` 混合批量从普通点击开始,再用平台主修饰键追加,验证实际删除集合。 - 通过 `scripts/desktop/desktop-go.sh` 执行定向无头测试,`desktop/internal/workbench/branch_delete_visual_test.go` 生成中英文明暗主题的文件树多选截图。Windows 原生交互验证仍待目标平台执行。 diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index f0522286e1..e1ce9786a0 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -249,6 +249,25 @@ jobs: if-no-files-found: error retention-days: 14 + - name: Capture project tree focus regression + id: project-tree-visual + if: ${{ !cancelled() && steps.rust.outcome == 'success' }} + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/project-tree-visual + run: | + ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench \ + -run '^TestVisualProjectTreeMissingFile$' -count=1 -timeout=120s + + - name: Upload project tree screenshots + if: ${{ !cancelled() && steps.project-tree-visual.outcome == 'success' }} + uses: actions/upload-artifact@v7 + with: + name: project-tree-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/project-tree-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native verification reports if: always() uses: actions/upload-artifact@v7 diff --git a/desktop/internal/workbench/filetree_actions_test.go b/desktop/internal/workbench/filetree_actions_test.go index 9ca84451a4..600f09c935 100644 --- a/desktop/internal/workbench/filetree_actions_test.go +++ b/desktop/internal/workbench/filetree_actions_test.go @@ -89,19 +89,24 @@ func TestProjectTreeLocatesTheActiveFile(t *testing.T) { } func TestProjectTreeLocateGivesUpOnAFileThatIsGone(t *testing.T) { - root := t.TempDir() - writeTreeFiles(t, root, "a/gone.go", "a/kept.go") h := newHarness(t, &testKernel{Client: core.NewClient()}) + locateMissingTreeFile(t, h) +} + +func locateMissingTreeFile(t *testing.T, h *harness) { + t.Helper() + root := filepath.Join(t.TempDir(), "MissingFileProject") + writeTreeFiles(t, root, "a/gone.go", "a/kept.go") p := h.openTree(t, root) + p.tree.selected = p.tree.root h.app.openFile(p, filepath.Join(root, "a", "gone.go")) awaitDocumentState(t, h, func() bool { _, ok := activeTreePath(p); return ok }) if err := os.Remove(filepath.Join(root, "a", "gone.go")); err != nil { t.Fatal(err) } - selected := p.tree.selected h.app.revealActiveFile(p) awaitDocumentState(t, h, func() bool { return p.tree.reveal == "" && treeIdle(p) }) - if p.tree.selected != selected { + if p.tree.selected != p.tree.root { t.Fatalf("locating a file that is gone selected %+v", p.tree.selected) } if n := p.tree.find("a"); n == nil || !n.expanded || p.tree.find("a/kept.go") == nil { diff --git a/desktop/internal/workbench/filetree_focus_visual_test.go b/desktop/internal/workbench/filetree_focus_visual_test.go new file mode 100644 index 0000000000..67fa724918 --- /dev/null +++ b/desktop/internal/workbench/filetree_focus_visual_test.go @@ -0,0 +1,49 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualProjectTreeMissingFile(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"zh-Hans", "en-US"} { + t.Run(theme+"-"+language, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1000, 640 + var err error + session, err = headless.Open(config, nil, headless.Options{Scale: 1}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + locateMissingTreeFile(t, h) + h.settle() + if err := session.Screenshot(filepath.Join(out, "project-tree-missing-file-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/filetree_test.go b/desktop/internal/workbench/filetree_test.go index 6d36330efe..0c4ae5352d 100644 --- a/desktop/internal/workbench/filetree_test.go +++ b/desktop/internal/workbench/filetree_test.go @@ -1326,6 +1326,31 @@ func TestProjectTreeSelectionFollowsTheKeyboardFocus(t *testing.T) { } } +func TestProjectTreeKeepsSelectionWhenFocusClearsBeforeNewRowsPaint(t *testing.T) { + root := t.TempDir() + h := newHarness(t, &testKernel{Client: core.NewClient()}) + tree := &h.openTree(t, root).tree + tree.selected = tree.root + tree.focused = tree.view.RowID(0) + if tree.focused.IsZero() { + t.Fatal("the painted root has no row ID") + } + + // A directory listing has added a row to the model, but Viva has yet to paint it. + tree.rows = append(tree.rows, &treeNode{id: 1, name: "kept.go", path: "kept.go", depth: 1}) + if !tree.view.RowID(1).IsZero() { + t.Fatal("the new row already has a row ID") + } + + h.app.syncTreeSelection(new(gfx.Canvas), tree) + if tree.selected != tree.root || tree.view.Selected() != 0 { + t.Fatalf("clearing focus selected %+v (row %d), want the root", tree.selected, tree.view.Selected()) + } + if !tree.focused.IsZero() { + t.Fatal("cleared focus was not recorded") + } +} + // labelBounds is where the label that reads exactly value was painted in the last frame, or // an empty rectangle when no label reads so. func (h *harness) labelBounds(value string) gfx.Rect { diff --git a/desktop/internal/workbench/filetree_view.go b/desktop/internal/workbench/filetree_view.go index 41bb117bda..e0ccb3ef14 100644 --- a/desktop/internal/workbench/filetree_view.go +++ b/desktop/internal/workbench/filetree_view.go @@ -137,8 +137,11 @@ func (a *App) projectTree(c ui.C, p *project) { // scrolls a row to show to the middle of the view when it is out of view. The selection // follows the keyboard: the row the arrow keys moved the focus to is the selected one. func (a *App) syncTreeSelection(canvas *gfx.Canvas, t *fileTree) { - if focused := canvas.Focused(); focused != t.focused { - t.focused = focused + focused := canvas.Focused() + focusChanged := focused != t.focused + t.focused = focused + // A row added since the previous paint can also have a zero ID. + if focusChanged && !focused.IsZero() { if _, pointer := canvas.PointerOn(focused); !pointer { for i, n := range t.rows { if t.view.RowID(i) == focused { diff --git a/docs/ci-builds.md b/docs/ci-builds.md index cd64d48a90..74c74548c1 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -80,6 +80,8 @@ Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树 Desktop CI 的 Build 命令发现截图由 `TestVisualBuildCommandDiscovery` 写入当前工作树的 `.artifacts/build-command-discovery-visual/`。该结果绑定提交、平台、Go 工具链和固定的 Viva 与 Core 版本,上传后由 CI 清理,不跨工作树复制,也不进入安装包。 +项目树失焦后的选择由 `TestVisualProjectTreeMissingFile` 验证。Linux Desktop CI 将明暗主题和中英文截图写入当前工作树的 `.artifacts/project-tree-visual/`,上传后保留 14 天。截图对应本次提交、主题、语言、渲染平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复制。运行器清理本地输出,截图不进入安装包。 + 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 检出。这些文件都不进入安装包,也不会改变代码签名或增量更新。 Viva 的 Core 源码检出、Cargo 目标目录和暂存静态库位于当前工作树的 diff --git a/shared/platform-feature-matrix/features/workspace-tree-batch-files.json b/shared/platform-feature-matrix/features/workspace-tree-batch-files.json index b7ac4752c9..b5da4f21cc 100644 --- a/shared/platform-feature-matrix/features/workspace-tree-batch-files.json +++ b/shared/platform-feature-matrix/features/workspace-tree-batch-files.json @@ -12,6 +12,8 @@ "desktop/internal/workbench/filetree_batch.go", "desktop/internal/workbench/filetree_view.go", "desktop/internal/workbench/filetree_test.go", + "desktop/internal/workbench/filetree_actions_test.go", + "desktop/internal/workbench/filetree_focus_visual_test.go", "desktop/internal/workbench/branch_delete_visual_test.go" ] }, @@ -27,11 +29,13 @@ "desktop/internal/workbench/filetree_trash_windows_test.go", "desktop/internal/workbench/filetree_view.go", "desktop/internal/workbench/filetree_test.go", + "desktop/internal/workbench/filetree_actions_test.go", + "desktop/internal/workbench/filetree_focus_visual_test.go", "desktop/internal/workbench/branch_delete_visual_test.go" ] }, "owner": "Workspace", - "verification": "macOS:单击目录名称只选中本行,箭头展开/折叠,子项不继承高亮;⌘ 点击增减独立选择,Shift 正反向选择,Control 点击右键、右键未选中子项只作用于该行;⌘A 仍选择焦点项同级。拖动已选项携带整组,拖动未选项只携带该项,目录整体移动,父子去重;同窗口项目目录接收拖放,项目根不能移动,同目录无操作,同名整批拒绝,目录移入自身/后代和符号链接越界拒绝;中途失败报告已完成数量、保留剩余源项,切换工作区停止后续项。确认未保存文件保护、成功移动后打开文档路径/历史/目录标记更新;外部拖放仍提供文件 URL。大目录分别测量选择、展开和滚动,懒加载行应能滚动到末尾,折叠与定位保持正确。保留复制/粘贴/副本/废纸篓、快捷键焦点和双击可执行文件回归。Windows 尚无该多选入口;macOS 实机事件、性能及 Swift 测试需在目标平台验证。 Windows:TestTrashCommandStartsWithoutAConsoleAndKeepsItsDialogsVisible 检查回收站命令以 CREATE_NO_WINDOW 启动且不设 HideWindow;实机移到回收站不再闪出终端窗口,删除被其他程序占用的文件时系统错误框仍然可见(#2068)。 Viva 两端用平台主修饰键增减多选(macOS Command,Windows Control):先普通点击 A,再修饰键点击 B,A/B 都保留选中底色;再次点击 A 只取消 A,普通点击 C 恢复单选,Shift 范围与键盘方向导航保持正确。Core fixture 和 macOS 真实鼠标无头测试覆盖,明暗主题截图可检查;Windows 原生交互未执行,验证状态保持 pending。", + "verification": "macOS:单击目录名称只选中本行,箭头展开/折叠,子项不继承高亮;⌘ 点击增减独立选择,Shift 正反向选择,Control 点击右键、右键未选中子项只作用于该行;⌘A 仍选择焦点项同级。拖动已选项携带整组,拖动未选项只携带该项,目录整体移动,父子去重;同窗口项目目录接收拖放,项目根不能移动,同目录无操作,同名整批拒绝,目录移入自身/后代和符号链接越界拒绝;中途失败报告已完成数量、保留剩余源项,切换工作区停止后续项。确认未保存文件保护、成功移动后打开文档路径/历史/目录标记更新;外部拖放仍提供文件 URL。大目录分别测量选择、展开和滚动,懒加载行应能滚动到末尾,折叠与定位保持正确。保留复制/粘贴/副本/废纸篓、快捷键焦点和双击可执行文件回归。Windows 尚无该多选入口;macOS 实机事件、性能及 Swift 测试需在目标平台验证。 Windows:TestTrashCommandStartsWithoutAConsoleAndKeepsItsDialogsVisible 检查回收站命令以 CREATE_NO_WINDOW 启动且不设 HideWindow;实机移到回收站不再闪出终端窗口,删除被其他程序占用的文件时系统错误框仍然可见(#2068)。 Viva 两端用平台主修饰键增减多选(macOS Command,Windows Control):先普通点击 A,再修饰键点击 B,A/B 都保留选中底色;再次点击 A 只取消 A,普通点击 C 恢复单选,Shift 范围与键盘方向导航保持正确。Core fixture 和 macOS 真实鼠标无头测试覆盖,明暗主题截图可检查;项目树焦点清空且新行尚未绘制时保留当前选中项。打开项目中的文件,在外部删除后定位当前文件,祖先目录展开并保留原选中项。无头测试覆盖这两个场景。Windows 原生交互仍待验。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {