From 536378b31f76763a72be407db64b2ded51e1f848 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 16:29:56 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(desktop):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E7=BC=BA=E5=B0=91=E7=9A=84=E5=91=BD=E4=BB=A4=E5=8F=AF=E5=9C=A8?= =?UTF-8?q?=E8=83=BD=E5=8A=9B=E5=8D=A1=E7=89=87=E4=B8=8A=E4=B8=80=E9=94=AE?= =?UTF-8?q?=E5=AE=89=E8=A3=85=EF=BC=88API-23=20commandInstallers=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 插件用 commandInstallers 声明用哪个已注入的工具安装 systemCommand 启动缺的命令。 宿主经 Core 校验并展开安装计划;插件详情“功能”页的能力卡片检测命令是否存在,缺失时显示 “未找到”和安装按钮,没有卡片的后端命令显示在横幅里。用户在对话框里选择 Lithe 管理的目录 或工具默认位置,看清要运行的命令、环境和是否联网后确认;安装输出实时显示,可取消,超时停止, 确认命令落地后记录目录,之后的启动在那里找到命令。命令缺失导致的调试、构建、版本控制启动 失败改为本地化提示。卡片上“本机已安装:xxx”改为“使用本机程序:xxx”,不再与“未找到”矛盾。 --- .../2026-11-15-plugin-command-installers.md | 74 +++ desktop/internal/core/command_installers.go | 158 ++++++ .../internal/core/command_installers_test.go | 242 ++++++++ desktop/internal/core/plugin_operation.go | 3 + desktop/internal/i18n/shared.generated.go | 50 +- .../internal/pluginbackend/pluginbackend.go | 20 +- .../pluginbackend/pluginbackend_test.go | 3 +- desktop/internal/pluginhost/commands.go | 278 ++++++++++ desktop/internal/pluginhost/commands_test.go | 188 +++++++ desktop/internal/pluginhost/launch.go | 32 +- desktop/internal/pluginhost/launch_test.go | 5 +- desktop/internal/pluginhost/pluginhost.go | 11 +- .../internal/pluginhost/pluginhost_test.go | 2 +- desktop/internal/pluginpkg/install.go | 15 +- .../internal/pluginservice/pluginservice.go | 6 + .../settingswindow/command_install.go | 518 ++++++++++++++++++ .../settingswindow/command_install_test.go | 194 +++++++ .../command_install_visual_test.go | 72 +++ desktop/internal/settingswindow/controller.go | 65 +++ .../internal/settingswindow/installed_view.go | 11 +- desktop/internal/settingswindow/window.go | 7 + .../internal/settingswindow/window_view.go | 1 + desktop/internal/workbench/app.go | 7 + desktop/internal/workbench/build.go | 8 +- .../internal/workbench/command_installers.go | 515 +++++++++++++++++ .../workbench/command_installers_test.go | 448 +++++++++++++++ desktop/internal/workbench/debug.go | 2 +- desktop/internal/workbench/debug_child.go | 2 +- desktop/internal/workbench/debug_launch.go | 12 +- desktop/internal/workbench/settings.go | 1 + desktop/internal/workbench/vcs.go | 5 +- docs/development/macos-plugin-api-plan.md | 2 +- shared/i18n/locales/en-US.json | 25 +- shared/i18n/locales/zh-CN.json | 25 +- shared/i18n/messages.json | 204 ++++++- .../features/plugin-command-installers.json | 40 ++ 36 files changed, 3214 insertions(+), 37 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md create mode 100644 desktop/internal/core/command_installers.go create mode 100644 desktop/internal/core/command_installers_test.go create mode 100644 desktop/internal/pluginhost/commands.go create mode 100644 desktop/internal/pluginhost/commands_test.go create mode 100644 desktop/internal/settingswindow/command_install.go create mode 100644 desktop/internal/settingswindow/command_install_test.go create mode 100644 desktop/internal/settingswindow/command_install_visual_test.go create mode 100644 desktop/internal/workbench/command_installers.go create mode 100644 desktop/internal/workbench/command_installers_test.go create mode 100644 shared/platform-feature-matrix/features/plugin-command-installers.json diff --git a/.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md b/.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md new file mode 100644 index 0000000000..f5fb781967 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md @@ -0,0 +1,74 @@ +# Agent 笔记:插件声明的命令缺失时由宿主安装 + +状态:已实现 + +## 先说结论 + +很多插件不打包自己要运行的程序,而是用本机已有的命令:Go 插件的语言服务器是 `gopls`,调试器是 `dlv`。以前这些命令不在时,用户只看到“plugin package path is not usable: none of the plan's commands is available”这类原始错误,也不知道怎么装。现在插件可以在清单里用 `commandInstallers` 声明“用哪个工具、跑什么参数来安装哪些命令”。宿主在插件详情“功能”页的能力卡片上显示“未找到 xxx”和安装按钮,用户在对话框里选择安装位置、看清要运行的命令后确认,宿主运行安装并记录命令所在目录,之后该插件的启动都能找到它们。宿主里没有任何针对具体插件或具体工具的代码。 + +## 问题 + +- 插件的 `systemCommand` 启动(语言服务器、构建、版本控制、调试适配器、后端)只在 PATH 和工具默认目录里找命令。找不到时,启动失败的原因是英文原始错误,用户不知道缺什么、该装到哪。 +- 安装命令的方式因工具而异(`go install`、`npm install -g`、`cargo install`……),装到哪里也因工具而异(`GOBIN`、`GOPATH/bin`)。宿主如果按工具写死安装逻辑,就违反了“宿主对具体插件和工具零依赖”。 +- 安装会运行下载代码的程序,必须让用户看清要运行什么、会不会联网,并且可以取消。 +- 发行包在运行时只读,装好的命令不能写进 app bundle 或安装目录。 + +## 决策 + +对应计划编号 API-23(工具链与受管进程)。 + +**谁负责什么** + +- **插件声明**:清单 `commandInstallers[]`(`requires.commandInstallers: 0`,权限 `commands.install`),每项写明安装哪些命令(必须是本清单某个 `systemCommand` 启动用到的命令,且每个命令只归一个安装器)、用哪个已注入的工具(`tool`,必须同时列在 `requiresTools`)、参数、环境、超时(1–3600 秒,默认 600)、是否可能联网,以及支持哪些目标: + - `managed`:装进 Lithe 管理的目录。参数或环境里必须出现 `${installDirectory}`,可用 `commandDirectory` 指出命令在安装目录下的哪个相对子目录。 + - `toolDefault`:装进工具自己的默认位置。用最多 4 个只含字面参数的探测命令(例如 `go env GOBIN`,再退到 `go env GOPATH` 的第一项加 `bin`)找出那个目录。 +- **Core 校验与展开**(Lithe-core-rust#53):`plugins.commandInstallers.requirements` 列出每个 `systemCommand` 启动和它的命令、能安装它的安装器;`plugins.commandInstallers.plan` 把一个目标展开成参数、环境和命令目录;`plugins.commandInstallers.defaultDirectory` 从探测输出里取出目录。宿主不自己解释清单字段。 +- **宿主执行**(`desktop/internal/workbench/command_installers.go`): + - 缺失检测:按启动自己的查找方式找命令。调试适配器用调试的查找(macOS 上还会问 `xcrun --find`),其他用插件运行器的查找。两者都会加上已记录的安装目录。只有“找不到命令”算缺失,别的失败不提示安装。 + - 解析工具:在打开的项目里解析,项目固定的工具版本就是安装用的版本。 + - 运行:经 `buildprocess` 直接启动工具,不经过 shell。工作目录是项目目录,输出逐行送到对话框(每行有上限),到超时就停止,用户取消就停止。 + - 核对:工具退出码为 0 之后,再确认每个命令确实落在目标目录里,才写记录。 +- **记录与查找**(`desktop/internal/pluginhost/commands.go` 的 `CommandStore`): + - 受管目录是 `<插件根目录>/.state/<插件 ID>/commands/<安装器 ID>`。 + - 记录文件是 `<插件根目录>/.state/<插件 ID>/commands.json`,读取上限 64 KiB,先写临时文件再改名替换。 + - 之后的启动通过 `CommandStore.Lookup` 和 `Backend.ResolveCommand` 先在记录的目录里找,再按原来的方式找。 +- **界面**(`desktop/internal/settingswindow/command_install.go`): + - 能力卡片显示“未找到 xxx”和安装按钮。没有卡片的后端命令显示在横幅里。 + - 对话框列出两个位置。工具默认位置探测不到时,该选项不可选并说明原因。 + - 对话框还显示要运行的命令和环境、是否可能联网。 + - 安装输出实时显示,失败原因全部本地化。命令缺失导致的启动失败(调试、构建、版本控制)也改用本地化提示。 + +**运行时写入位置**:只写插件根目录下的 `.state`。它属于平台存储目录,不在 app bundle 或安装目录里,所以不影响代码签名,也不影响 Sparkle 增量包的源基线。卸载插件时,Core 的卸载计划包含删除状态目录的步骤(`core.PluginRemoveState`),受管目录和记录随之删除。`toolDefault` 只记录目录,工具装进默认位置的文件归用户和工具所有,卸载不删除。 + +正确做法:新插件需要本机命令时,在清单里声明 `commandInstallers`,安装方式写成该工具自己的参数;需要知道工具把命令装到哪,就用 `directory` 探测,不在宿主里加分支。 + +不要这样做:在宿主里写“缺 gopls 就运行 `go install golang.org/x/tools/gopls@latest`”;也不要让插件后端自己下载并解压命令到插件包目录,插件包和发行包一样,运行时只读。 + +## 考虑过的备选方案 + +1. **宿主为常见工具内置安装方式**(Go、Node、Rust 各写一套):最快,但每支持一个工具就要改宿主,违反宿主对工具零依赖;第三方插件也用不上。否决。 +2. **插件后端自己下载并安装**:插件可以完全控制,但用户看不到将要运行什么,宿主也无法统一提供取消、超时、位置选择和本地化失败原因;后端还没启动时(缺的正是后端命令)就无从安装。否决。 +3. **只提示“请手动运行 xxx”**:安全但麻烦,用户要自己找终端并设对 `GOBIN`;用户明确要求提供自动安装按钮。作为退路仍然可用:对话框始终显示要运行的命令和环境,安装失败后用户可以照着手动运行。 +4. **只支持装进 Lithe 管理的目录**:最可控,但用户已有 `GOPATH/bin` 习惯时会装出第二份。按用户选择,两种位置都提供,由用户在对话框里选。 +5. **把装好的命令写进插件包目录**:卸载时自然删除,但插件包要保持签名后的原样,运行时写入会破坏校验。否决,改为 `.state`。 + +## 后果 + +- 收益:插件作者只写声明就能获得安装按钮、位置选择、取消和超时、本地化失败原因;宿主对 Go、Node 等工具没有任何特判。 +- 收益:命令缺失导致的启动失败不再显示原始英文错误。 +- 代价:打开“功能”页时,要为每个 `systemCommand` 启动查找一次命令。这一步在后台运行,有超时限制,不阻塞界面线程。 +- 代价:安装会运行插件指定的工具和参数,所以需要 `commands.install` 权限,并在对话框里显示完整命令,由用户确认。 +- 代价:`toolDefault` 装的文件不随插件卸载删除,用户需要自己清理。 +- 尚未在原生窗口真机和 Windows 真机验证;`verificationStatus` 保持 pending。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./internal/workbench -run 'CommandInstall|CommandMissing|CommandOutput' -count=1`:合成插件 `dev.lithe.test.command-installers` 用复制出来的测试二进制当安装工具(不联网),覆盖缺失检测、两个目标的展开、受管安装后启动能找到命令、工具默认位置的探测与记录、非零退出/命令没落地/超时、取消停止工具且不留记录、拒绝插件没声明的目标、启动失败的本地化。 +- `scripts/desktop/desktop-go.sh test ./internal/settingswindow -run 'CommandInstall|CapabilityCard' -count=1`:卡片状态、横幅、对话框内容、安装输出、完成后卡片清除、取消、失败文案。 +- `scripts/desktop/desktop-go.sh test ./internal/pluginhost ./internal/core -count=1`:记录文件的读写边界和 Core 封装。 +- `LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualCommandInstall ./internal/settingswindow -count=1`:深浅主题的卡片与对话框截图。 +- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:安装与启动后 app bundle 文件清单不变。 + +## 适用范围 + +Viva 客户端(`desktop/`)中插件 `systemCommand` 启动的命令查找与安装:`desktop/internal/core/command_installers.go`、`desktop/internal/pluginhost/commands.go`、`desktop/internal/pluginhost/launch.go`、`desktop/internal/pluginbackend/`、`desktop/internal/workbench/command_installers.go`、`desktop/internal/settingswindow/command_install.go`。契约与展开规则以 Lithe-core-rust 的 `shared/plugins/contract/v1/` 为准。插件包内自带的程序(`packaged` 启动)不走这里。 diff --git a/desktop/internal/core/command_installers.go b/desktop/internal/core/command_installers.go new file mode 100644 index 0000000000..80e8133bb2 --- /dev/null +++ b/desktop/internal/core/command_installers.go @@ -0,0 +1,158 @@ +package core + +import ( + "context" + "encoding/json" +) + +// Command installer targets, written as the contract's tokens. +const ( + // CommandInstallManaged installs into a directory the host owns for the plugin. + CommandInstallManaged = "managed" + // CommandInstallToolDefault installs wherever the tool puts commands when told nothing. + CommandInstallToolDefault = "toolDefault" +) + +// CommandRequirements is Core's answer to plugins.commandInstallers.requirements: every +// systemCommand launch of a manifest with the bare commands it names, and the installers that +// provide them. +type CommandRequirements struct { + Consumers []CommandConsumer `json:"consumers"` + Installers []CommandInstaller `json:"installers"` +} + +// CommandConsumer is one systemCommand launch. +type CommandConsumer struct { + // Kind is languageServer, buildProvider, vcsProvider, debugAdapter or backend. + Kind string `json:"kind"` + // ID is the language, build system, VCS or adapter ID; nil for the backend. + ID *string `json:"id"` + Commands []RequiredCommand `json:"commands"` +} + +// RequiredCommand is one command a launch names, in the launch's order. +type RequiredCommand struct { + Command string `json:"command"` + // Installer is the ID of the installer that provides it; nil when none does. + Installer *string `json:"installer"` +} + +// CommandInstaller is the summary of one commandInstallers[] entry. +type CommandInstaller struct { + ID string `json:"id"` + Commands []string `json:"commands"` + Tool string `json:"tool"` + MinimumVersion *string `json:"minimumVersion"` + MayUseNetwork bool `json:"mayUseNetwork"` + // Targets lists the declared targets, managed before toolDefault. + Targets []string `json:"targets"` +} + +// CommandInstallPlan is one installer expanded for the target the user chose. The host runs +// Tool's resolved executable with Arguments and Environment set over the tool's environment. +type CommandInstallPlan struct { + Installer string `json:"installer"` + Target string `json:"target"` + Commands []string `json:"commands"` + Tool string `json:"tool"` + MinimumVersion *string `json:"minimumVersion"` + MayUseNetwork bool `json:"mayUseNetwork"` + TimeoutMilliseconds int64 `json:"timeoutMilliseconds"` + Arguments []string `json:"arguments"` + Environment map[string]string `json:"environment"` + // CommandDirectory is where a managed installation's commands land; nil for toolDefault, + // whose directory the probes find. + CommandDirectory *string `json:"commandDirectory"` + DirectoryProbes []CommandDirectoryProbe `json:"directoryProbes"` +} + +// CommandDirectoryProbe is one run of the plan's tool whose output names the directory a +// toolDefault installation puts its commands in. +type CommandDirectoryProbe struct { + Arguments []string `json:"arguments"` +} + +// CommandInstallerRequirements lists the systemCommand launches of manifest and the installer +// of each command. It reads nothing and starts nothing. +func (c *Client) CommandInstallerRequirements(ctx context.Context, manifest json.RawMessage) (CommandRequirements, error) { + const command = "plugins.commandInstallers.requirements" + var result struct { + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Requirements *CommandRequirements `json:"requirements"` + } + if err := c.Execute(ctx, command, struct { + Manifest json.RawMessage `json:"manifest"` + }{manifest}, &result); err != nil { + return CommandRequirements{}, err + } + if result.Status == "rejected" && result.Error != nil { + return CommandRequirements{}, result.Error + } + if result.Status != "ok" || result.Requirements == nil { + return CommandRequirements{}, newParseError(command, "command requirements returned an invalid outcome", "") + } + return *result.Requirements, nil +} + +// PlanCommandInstaller expands installerID for target. installDirectory is the absolute +// directory the host made for a managed installation and must be empty for toolDefault. +func (c *Client) PlanCommandInstaller(ctx context.Context, manifest json.RawMessage, installerID, target, installDirectory string) (CommandInstallPlan, error) { + const command = "plugins.commandInstallers.plan" + var result struct { + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Plan *CommandInstallPlan `json:"plan"` + } + if err := c.Execute(ctx, command, struct { + Manifest json.RawMessage `json:"manifest"` + InstallerID string `json:"installerID"` + Target string `json:"target"` + InstallDirectory string `json:"installDirectory,omitempty"` + }{manifest, installerID, target, installDirectory}, &result); err != nil { + return CommandInstallPlan{}, err + } + if result.Status == "rejected" && result.Error != nil { + return CommandInstallPlan{}, result.Error + } + if result.Status != "ok" || result.Plan == nil || result.Plan.Installer != installerID || result.Plan.Target != target || len(result.Plan.Commands) == 0 || result.Plan.TimeoutMilliseconds <= 0 { + return CommandInstallPlan{}, newParseError(command, "command installer plan returned an invalid outcome", "") + } + if (target == CommandInstallManaged) != (result.Plan.CommandDirectory != nil) { + return CommandInstallPlan{}, newParseError(command, "command installer plan returned an invalid outcome", "") + } + return *result.Plan, nil +} + +// CommandInstallerDefaultDirectory reads where a toolDefault installation of installerID puts +// its commands from the output of its directory probes, one per probe in plan order and nil +// for a probe that failed. ok is false when no probe named an absolute directory. +func (c *Client) CommandInstallerDefaultDirectory(ctx context.Context, manifest json.RawMessage, installerID string, outputs []*string) (directory string, ok bool, err error) { + const command = "plugins.commandInstallers.defaultDirectory" + if outputs == nil { + // Core reads an absent or null list as malformed; no probes is an empty list. + outputs = []*string{} + } + var result struct { + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Directory *string `json:"directory"` + } + if err := c.Execute(ctx, command, struct { + Manifest json.RawMessage `json:"manifest"` + InstallerID string `json:"installerID"` + Outputs []*string `json:"outputs"` + }{manifest, installerID, outputs}, &result); err != nil { + return "", false, err + } + if result.Status == "rejected" && result.Error != nil { + return "", false, result.Error + } + if result.Status != "ok" { + return "", false, newParseError(command, "command installer default directory returned an invalid outcome", "") + } + if result.Directory == nil || *result.Directory == "" { + return "", false, nil + } + return *result.Directory, true, nil +} diff --git a/desktop/internal/core/command_installers_test.go b/desktop/internal/core/command_installers_test.go new file mode 100644 index 0000000000..15efed6e52 --- /dev/null +++ b/desktop/internal/core/command_installers_test.go @@ -0,0 +1,242 @@ +package core + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +type commandInstallerCase struct { + Name string `json:"name"` + Operation string `json:"operation"` + Payload json.RawMessage `json:"payload"` + ManifestEdits []struct { + Path string `json:"path"` + Value json.RawMessage `json:"value"` + } `json:"manifestEdits"` + Expected json.RawMessage `json:"expected"` + Platforms map[string]struct { + Payload json.RawMessage `json:"payload"` + Expected json.RawMessage `json:"expected"` + } `json:"platforms"` +} + +// The wrappers answer every golden case of the shared fixture the way Core's own test reads +// it: a result matches field for field, a rejection by its code and field. +func TestCommandInstallersSharedFixture(t *testing.T) { + directory := contractfixture.Path("fixtures/command-installers") + data, err := os.ReadFile(filepath.Join(directory, "command-installer-plans.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Plugin string `json:"plugin"` + Cases []commandInstallerCase `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + plugin, err := os.ReadFile(filepath.Join(directory, fixture.Plugin)) + if err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("fixture has no cases") + } + platform := "unix" + if runtime.GOOS == "windows" { + platform = "windows" + } + client := NewClient() + for _, c := range fixture.Cases { + t.Run(c.Name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + payload, expected := c.Payload, c.Expected + if specific, ok := c.Platforms[platform]; ok { + payload = mergeObjects(t, payload, specific.Payload) + expected = specific.Expected + } + manifest := editManifest(t, plugin, c) + var fields struct { + InstallerID string `json:"installerID"` + Target string `json:"target"` + InstallDirectory string `json:"installDirectory"` + Outputs []*string `json:"outputs"` + } + if err := json.Unmarshal(payload, &fields); err != nil { + t.Fatal(err) + } + var got any + switch c.Operation { + case "requirements": + got, err = client.CommandInstallerRequirements(ctx, manifest) + case "plan": + got, err = client.PlanCommandInstaller(ctx, manifest, fields.InstallerID, fields.Target, fields.InstallDirectory) + case "defaultDirectory": + var directory string + var ok bool + directory, ok, err = client.CommandInstallerDefaultDirectory(ctx, manifest, fields.InstallerID, fields.Outputs) + if ok { + got = directory + } + default: + t.Fatalf("unknown operation %q", c.Operation) + } + var want struct { + Status string `json:"status"` + Code string `json:"code"` + Field string `json:"field"` + Requirements json.RawMessage `json:"requirements"` + Plan json.RawMessage `json:"plan"` + Directory json.RawMessage `json:"directory"` + } + if err := json.Unmarshal(expected, &want); err != nil { + t.Fatal(err) + } + if want.Status == "rejected" { + var rejection *MarketplaceRejection + if !errors.As(err, &rejection) || rejection.Code != want.Code || rejection.Field != want.Field { + t.Fatalf("err = %v, want %s (%s)", err, want.Code, want.Field) + } + return + } + if err != nil { + t.Fatal(err) + } + wantValue := want.Requirements + switch c.Operation { + case "plan": + wantValue = want.Plan + case "defaultDirectory": + wantValue = want.Directory + } + sameJSON(t, got, wantValue) + }) + } +} + +// A plan whose target does not match the directory it carries is not one the host can run. +func TestPlanCommandInstallerRefusesAnInconsistentOutcome(t *testing.T) { + directory := contractfixture.Path("fixtures/command-installers") + manifest, err := os.ReadFile(filepath.Join(directory, "command-installer.plugin.json")) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := NewClient() + if _, err := client.PlanCommandInstaller(ctx, manifest, "sample-ls", "unknown", ""); err == nil { + t.Fatal("an unknown target was planned") + } + if directory, ok, err := client.CommandInstallerDefaultDirectory(ctx, manifest, "sample-ls", []*string{nil, nil}); err != nil || ok || directory != "" { + t.Fatalf("failed probes gave %q, %v, %v", directory, ok, err) + } +} + +func mergeObjects(t *testing.T, base, overlay json.RawMessage) json.RawMessage { + t.Helper() + merged := map[string]json.RawMessage{} + for _, part := range []json.RawMessage{base, overlay} { + if len(part) == 0 { + continue + } + var object map[string]json.RawMessage + if err := json.Unmarshal(part, &object); err != nil { + t.Fatal(err) + } + for key, value := range object { + merged[key] = value + } + } + out, err := json.Marshal(merged) + if err != nil { + t.Fatal(err) + } + return out +} + +// editManifest replaces the value at each of the case's JSON pointers. +func editManifest(t *testing.T, plugin []byte, c commandInstallerCase) json.RawMessage { + t.Helper() + if len(c.ManifestEdits) == 0 { + return plugin + } + var document any + if err := json.Unmarshal(plugin, &document); err != nil { + t.Fatal(err) + } + for _, edit := range c.ManifestEdits { + var value any + if err := json.Unmarshal(edit.Value, &value); err != nil { + t.Fatal(err) + } + segments := strings.Split(strings.TrimPrefix(edit.Path, "/"), "/") + parent := document + for _, segment := range segments[:len(segments)-1] { + parent = child(t, parent, segment) + } + last := segments[len(segments)-1] + switch node := parent.(type) { + case map[string]any: + node[last] = value + case []any: + index, err := strconv.Atoi(last) + if err != nil || index < 0 || index >= len(node) { + t.Fatalf("bad pointer %s", edit.Path) + } + node[index] = value + default: + t.Fatalf("bad pointer %s", edit.Path) + } + } + out, err := json.Marshal(document) + if err != nil { + t.Fatal(err) + } + return out +} + +func child(t *testing.T, node any, segment string) any { + t.Helper() + switch value := node.(type) { + case map[string]any: + return value[segment] + case []any: + index, err := strconv.Atoi(segment) + if err != nil || index < 0 || index >= len(value) { + t.Fatalf("bad pointer segment %s", segment) + } + return value[index] + } + t.Fatalf("bad pointer segment %s", segment) + return nil +} + +func sameJSON(t *testing.T, got any, want json.RawMessage) { + t.Helper() + encoded, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + var gotValue, wantValue any + if err := json.Unmarshal(encoded, &gotValue); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(want, &wantValue); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(gotValue, wantValue) { + t.Fatalf("got %s\nwant %s", encoded, want) + } +} diff --git a/desktop/internal/core/plugin_operation.go b/desktop/internal/core/plugin_operation.go index 2eb65f5c33..3bc1923983 100644 --- a/desktop/internal/core/plugin_operation.go +++ b/desktop/internal/core/plugin_operation.go @@ -24,6 +24,9 @@ const ( OperationBuildModel PluginOperationName = "lithe/build/model" // OperationBuildDependencies is one dependency tree load of a command source. OperationBuildDependencies PluginOperationName = "lithe/build/dependencies" + // OperationCommandInstallerInstall is one commandInstallers[] installation the user + // confirmed, from planning it to finding its commands. A cancelled one is not recorded. + OperationCommandInstallerInstall PluginOperationName = "commandInstaller/install" ) // PluginStage is where an attempt failed. Core turns it into a code through the contribution's diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 2ac03fe6f9..c3f88d900d 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -927,6 +927,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.packageFilter": "Plugin package", "desktop.marketplace.permissionBackend": "Start the plugin’s background service", "desktop.marketplace.permissionBuild": "Run build tools for your projects", + "desktop.marketplace.permissionCommandsInstall": "Install the command-line tools the plugin needs (asks you before each installation)", "desktop.marketplace.permissionDebug": "Start a debugger for your programs", "desktop.marketplace.permissionGenerate": "Create project files in the location you choose", "desktop.marketplace.programDetails": "Program declarations ({count}) — show / hide details", @@ -1105,7 +1106,29 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginWeb.openFileTitle": "Choose a File for {plugin}", "desktop.pluginWeb.saveFileTitle": "Save a File for {plugin}", "desktop.pluginWeb.unavailable": "This window cannot be shown: {reason}", - "desktop.plugins.installedOnThisComputer": "Installed on this computer: {arg1}", + "desktop.plugins.commandInstallCommand": "Command to run", + "desktop.plugins.commandInstallCommandsMissing": "The installation finished, but {commands} was not found in {directory}.", + "desktop.plugins.commandInstallError": "Could not install: {reason}", + "desktop.plugins.commandInstallFailed": "The installation failed with exit code {code}. See the output below.", + "desktop.plugins.commandInstallLocation": "Install location", + "desktop.plugins.commandInstallManaged": "A directory Lithe manages", + "desktop.plugins.commandInstallManagedHelp": "Used by Lithe only and removed with the plugin.", + "desktop.plugins.commandInstallNetwork": "The installation may download from the network.", + "desktop.plugins.commandInstallNoDirectory": "Could not find where {tool} installs by default.", + "desktop.plugins.commandInstallOutput": "Output", + "desktop.plugins.commandInstallPrompt": "{commands} will be installed with {tool}.", + "desktop.plugins.commandInstallStopped": "The installation ended unexpectedly. See the output below.", + "desktop.plugins.commandInstallTimedOut": "The installation did not finish within {seconds} seconds and was stopped.", + "desktop.plugins.commandInstallTitle": "Install {commands}", + "desktop.plugins.commandInstallToolDefault": "{tool}'s default location", + "desktop.plugins.commandInstallToolDefaultHelp": "Also available to the terminal and other programs, and kept when the plugin is removed.", + "desktop.plugins.commandInstallToolMissing": "{tool} not found. Install it first, or set where it is in Settings > Build, Execution, Deployment > Toolchains.", + "desktop.plugins.commandInstalled": "Installed in {directory}.", + "desktop.plugins.commandMissing": "{commands} not found", + "desktop.plugins.commandMissingBanner": "{commands} not found; some of the plugin's features will not work.", + "desktop.plugins.commandMissingHelp": "{commands} not found. Install it in Settings > Plugins, or add it to PATH.", + "desktop.plugins.commandMissingManual": "This plugin offers no way to install it. Install it yourself and make sure it is on PATH.", + "desktop.plugins.installedOnThisComputer": "Uses a program on this computer: {arg1}", "desktop.problems.group.file": "By file", "desktop.problems.group.none": "No grouping", "desktop.problems.group.severity": "By severity", @@ -3518,6 +3541,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.packageFilter": "插件包", "desktop.marketplace.permissionBackend": "启动插件的后台服务", "desktop.marketplace.permissionBuild": "为项目运行构建工具", + "desktop.marketplace.permissionCommandsInstall": "安装插件所需的命令行工具(每次安装前都会征得你的同意)", "desktop.marketplace.permissionDebug": "启动程序调试器", "desktop.marketplace.permissionGenerate": "在你选择的位置生成项目文件", "desktop.marketplace.programDetails": "程序声明({count} 项)· 展开/收起详情", @@ -3696,7 +3720,29 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginWeb.openFileTitle": "为 {plugin} 选择文件", "desktop.pluginWeb.saveFileTitle": "为 {plugin} 保存文件", "desktop.pluginWeb.unavailable": "无法显示此窗口:{reason}", - "desktop.plugins.installedOnThisComputer": "本机已安装:{arg1}", + "desktop.plugins.commandInstallCommand": "将要运行的命令", + "desktop.plugins.commandInstallCommandsMissing": "安装已完成,但在 {directory} 中没有找到 {commands}。", + "desktop.plugins.commandInstallError": "无法安装:{reason}", + "desktop.plugins.commandInstallFailed": "安装失败,退出码 {code}。请查看下面的输出。", + "desktop.plugins.commandInstallLocation": "安装位置", + "desktop.plugins.commandInstallManaged": "Lithe 管理的目录", + "desktop.plugins.commandInstallManagedHelp": "只供 Lithe 使用,卸载插件时一并删除。", + "desktop.plugins.commandInstallNetwork": "安装时可能会从网络下载。", + "desktop.plugins.commandInstallNoDirectory": "无法确定 {tool} 的默认安装位置。", + "desktop.plugins.commandInstallOutput": "输出", + "desktop.plugins.commandInstallPrompt": "将用 {tool} 安装 {commands}。", + "desktop.plugins.commandInstallStopped": "安装程序意外结束。请查看下面的输出。", + "desktop.plugins.commandInstallTimedOut": "安装超过 {seconds} 秒仍未完成,已停止。", + "desktop.plugins.commandInstallTitle": "安装 {commands}", + "desktop.plugins.commandInstallToolDefault": "{tool} 的默认位置", + "desktop.plugins.commandInstallToolDefaultHelp": "终端和其他程序也能使用,卸载插件时保留。", + "desktop.plugins.commandInstallToolMissing": "未找到 {tool}。请先安装它,或在 设置 > 构建、执行、部署 > 工具链 中指定它的位置。", + "desktop.plugins.commandInstalled": "已安装到 {directory}。", + "desktop.plugins.commandMissing": "未找到 {commands}", + "desktop.plugins.commandMissingBanner": "未找到 {commands},插件的部分功能无法使用。", + "desktop.plugins.commandMissingHelp": "未找到 {commands}。请在 设置 > 插件 中安装,或把它加入 PATH。", + "desktop.plugins.commandMissingManual": "这个插件没有提供安装方式。请自行安装,并确保它在 PATH 中。", + "desktop.plugins.installedOnThisComputer": "使用本机程序:{arg1}", "desktop.problems.group.file": "按文件", "desktop.problems.group.none": "不分组", "desktop.problems.group.severity": "按严重级别", diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index 6332edc7e9..f1b04fe4e5 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -160,6 +160,9 @@ type Runner struct { // lookup resolves a bare command name for a system-command launch. It is // exec.LookPath in production and a test replaces it to describe a machine. lookup func(name string) (string, error) + // commands adds the directories the host installed each plugin's commands + // into to lookup. Nil looks up PATH only. + commands *pluginhost.CommandStore // tools resolves a plan's {kind: "tool"} launch to an executable. Nil refuses // such a launch rather than guessing a program. tools ToolResolver @@ -242,6 +245,11 @@ type ToolResolver func(ctx context.Context, pluginID, workingDirectory, tool str // before the first Start. func (r *Runner) SetToolResolver(resolver ToolResolver) { r.tools = resolver } +// SetCommandStore installs the record of the commands the host installed for +// plugins, so a plugin's system-command launches find them after PATH. It must +// be called before the first Start. +func (r *Runner) SetCommandStore(store *pluginhost.CommandStore) { r.commands = store } + // New returns a runner that answers host requests with services. func New(kernel Kernel, services *pluginhost.Services) *Runner { if services == nil { @@ -321,7 +329,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro executable = resolved.Runtime } if executable == "" && plan.Launch.Kind == pluginhost.LaunchSystemCommand { - executable, err = pluginhost.ResolveCommand(plan.Launch.Commands, r.lookup) + executable, err = pluginhost.ResolveCommand(plan.Launch.Commands, r.commands.Lookup(request.PluginID, r.lookup)) if err != nil { return Session{}, err } @@ -688,14 +696,14 @@ func (r *Runner) RequestBuild(ctx context.Context, session Session, request core return r.kernel.RequestPluginBuild(ctx, request) } -// ResolveCommand finds the first of commands the way a system-command launch -// does, for a tool a provider runs itself rather than one the runner launches, -// such as the client a VCS provider drives. -func (r *Runner) ResolveCommand(commands []string) (string, error) { +// ResolveCommand finds the first of commands the way a system-command launch of +// pluginID does, for a tool a provider runs itself rather than one the runner +// launches, such as the client a VCS provider drives. +func (r *Runner) ResolveCommand(pluginID string, commands []string) (string, error) { if r == nil { return "", errors.New("pluginbackend: no runner") } - return pluginhost.ResolveCommand(commands, r.lookup) + return pluginhost.ResolveCommand(commands, r.commands.Lookup(pluginID, r.lookup)) } // RequestVcs submits one VCS operation to a session that negotiated the diff --git a/desktop/internal/pluginbackend/pluginbackend_test.go b/desktop/internal/pluginbackend/pluginbackend_test.go index ba44430432..f00fc2d210 100644 --- a/desktop/internal/pluginbackend/pluginbackend_test.go +++ b/desktop/internal/pluginbackend/pluginbackend_test.go @@ -442,7 +442,8 @@ func TestStartRefusesAnUnavailableSystemCommand(t *testing.T) { kernel := &fakeKernel{plan: plan, started: core.PluginBackendStarted{SessionID: "session-1"}} runner := New(kernel, echoServices(t)) runner.lookup = func(string) (string, error) { return "", errors.New("not found") } - if _, err := runner.Start(context.Background(), startRequest(root)); !errors.Is(err, pluginhost.ErrPackagePath) { + var missing *pluginhost.CommandMissingError + if _, err := runner.Start(context.Background(), startRequest(root)); !errors.As(err, &missing) || len(missing.Commands) != 1 || missing.Commands[0] != "missing" { t.Fatalf("err = %v", err) } if kernel.started_.ExecutablePath != "" { diff --git a/desktop/internal/pluginhost/commands.go b/desktop/internal/pluginhost/commands.go new file mode 100644 index 0000000000..770fb172f3 --- /dev/null +++ b/desktop/internal/pluginhost/commands.go @@ -0,0 +1,278 @@ +package pluginhost + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +// commandRecordName is the record of a plugin's installations, beside its +// versioned state directories. A version never has this name: it is not a +// version number. +const commandRecordName = "commands.json" + +// commandInstallsName holds the managed install directories, one per installer. +const commandInstallsName = "commands" + +// maxCommandRecordBytes bounds the record read on every launch that misses PATH. +// Sixteen installers with paths of a few hundred bytes fit with room to spare. +const maxCommandRecordBytes = 64 << 10 + +// installerIDPattern is the contract's installer ID: lowercase letters, digits +// and '-', at most 64 characters. Core checks it before the manifest installs; +// the host checks again because it joins the ID into a path. +var installerIDPattern = regexp.MustCompile(`^[a-z0-9-]{1,64}$`) + +// ErrCommandRecord reports an installation the host refuses to record. +var ErrCommandRecord = errors.New("command installation not recordable") + +// CommandInstallation is one recorded installation: the installer that ran, the +// target the user chose, and the absolute directory its commands landed in. +type CommandInstallation struct { + Installer string `json:"installer"` + Target string `json:"target"` + Directory string `json:"directory"` +} + +type commandRecord struct { + Installations []CommandInstallation `json:"installations"` +} + +// CommandStore keeps the commands the host installed for plugins through their +// command installers, and the record of where each installation's commands +// landed. +// +// Everything lives below the plugin root's state directory, +// /.state//, which the host owns and removes with the plugin +// (pluginpkg.RemoveState): +// +// - commands// is the install directory of a managed +// installation; the tool writes into it, the host creates it. +// - commands.json records each installation's target and command directory, +// so a toolDefault installation that landed in the tool's own directory +// (such as GOPATH/bin) is found by later launches as well. +// +// The plugin root is in Application Support or %LOCALAPPDATA%, never in the app +// bundle or the installation directory, so none of this changes the code +// signature or the Sparkle delta base. Installations outlive plugin updates: an +// update replaces the package, not its state. +type CommandStore struct { + // State is the plugin root's state directory, /.state. + State string + + mu sync.Mutex +} + +func (s *CommandStore) pluginDirectory(pluginID string) (string, error) { + if s == nil || s.State == "" || !filepath.IsAbs(s.State) { + return "", fmt.Errorf("%w: no absolute state directory", ErrCommandRecord) + } + if err := pluginpkg.CheckIdentity("plugin ID", pluginID); err != nil { + return "", err + } + return filepath.Join(s.State, pluginID), nil +} + +// InstallDirectory is the directory a managed installation of installerID writes +// into. It is not created here; the installation creates it. +func (s *CommandStore) InstallDirectory(pluginID, installerID string) (string, error) { + directory, err := s.pluginDirectory(pluginID) + if err != nil { + return "", err + } + if !installerIDPattern.MatchString(installerID) { + return "", fmt.Errorf("%w: installer ID %q", ErrCommandRecord, installerID) + } + return filepath.Join(directory, commandInstallsName, installerID), nil +} + +// Installations reads the plugin's recorded installations. A missing, oversized +// or unreadable record holds none: the commands are then looked for on PATH only +// and plugin management offers the installers again. +func (s *CommandStore) Installations(pluginID string) []CommandInstallation { + directory, err := s.pluginDirectory(pluginID) + if err != nil { + return nil + } + return readCommandRecord(filepath.Join(directory, commandRecordName)) +} + +func readCommandRecord(path string) []CommandInstallation { + file, err := os.Open(path) + if err != nil { + return nil + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, maxCommandRecordBytes+1)) + if err != nil || len(data) > maxCommandRecordBytes { + return nil + } + var record commandRecord + if json.Unmarshal(data, &record) != nil { + return nil + } + installations := record.Installations[:0] + for _, installation := range record.Installations { + if installation.valid() { + installations = append(installations, installation) + } + } + return installations +} + +func (i CommandInstallation) valid() bool { + return installerIDPattern.MatchString(i.Installer) && + (i.Target == core.CommandInstallManaged || i.Target == core.CommandInstallToolDefault) && + filepath.IsAbs(i.Directory) && filepath.Clean(i.Directory) == i.Directory +} + +// Directories lists the command directories of the plugin's installations: +// managed ones first, then the default directories, each once. +func (s *CommandStore) Directories(pluginID string) []string { + installations := s.Installations(pluginID) + directories := make([]string, 0, len(installations)) + seen := make(map[string]struct{}, len(installations)) + for _, target := range []string{core.CommandInstallManaged, core.CommandInstallToolDefault} { + for _, installation := range installations { + if installation.Target != target { + continue + } + if _, ok := seen[installation.Directory]; ok { + continue + } + seen[installation.Directory] = struct{}{} + directories = append(directories, installation.Directory) + } + } + return directories +} + +// Record notes a finished installation, replacing an earlier one of the same +// installer. The record is written to a temporary file and renamed, so a crash +// leaves the old record or the new one. +func (s *CommandStore) Record(pluginID string, installation CommandInstallation) error { + directory, err := s.pluginDirectory(pluginID) + if err != nil { + return err + } + installation.Directory = filepath.Clean(installation.Directory) + if !installation.valid() { + return fmt.Errorf("%w: %+v", ErrCommandRecord, installation) + } + s.mu.Lock() + defer s.mu.Unlock() + path := filepath.Join(directory, commandRecordName) + installations := []CommandInstallation{installation} + for _, existing := range readCommandRecord(path) { + if existing.Installer != installation.Installer { + installations = append(installations, existing) + } + } + data, err := json.MarshalIndent(commandRecord{Installations: installations}, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(directory, 0o755); err != nil { + return err + } + temporary, err := os.CreateTemp(directory, "."+commandRecordName+".*.tmp") + if err != nil { + return err + } + name := temporary.Name() + if _, err := temporary.Write(data); err != nil { + temporary.Close() + os.Remove(name) + return err + } + if err := temporary.Close(); err != nil { + os.Remove(name) + return err + } + if err := os.Rename(name, path); err != nil { + os.Remove(name) + return err + } + return nil +} + +// Lookup is the command lookup of the plugin's systemCommand launches: base +// (PATH) first, then the directories the plugin's commands were installed into. +// The record is read only when base misses, and at most once per lookup. +func (s *CommandStore) Lookup(pluginID string, base func(name string) (string, error)) func(name string) (string, error) { + var once sync.Once + var directories []string + return func(name string) (string, error) { + if base != nil { + if path, err := base(name); err == nil && path != "" { + return path, nil + } + } + once.Do(func() { directories = s.Directories(pluginID) }) + for _, directory := range directories { + if path, err := CommandInDirectory(directory, name); err == nil { + return path, nil + } + } + return "", exec.ErrNotFound + } +} + +// CommandInDirectory finds the executable command in directory, with the +// platform's executable extensions on Windows. name must be a bare command name. +func CommandInDirectory(directory, name string) (string, error) { + if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) { + return "", exec.ErrNotFound + } + return exec.LookPath(filepath.Join(directory, name)) +} + +// The contract's codes of an installation that ran without providing its commands. +const ( + // CommandInstallFailedCode: the installation exited unsuccessfully. + CommandInstallFailedCode = "plugin.commandInstaller.failed" + // CommandInstallTimedOutCode: the installation ran past its timeout and was stopped. + CommandInstallTimedOutCode = "plugin.commandInstaller.timedOut" + // CommandInstallCommandsMissingCode: the installation finished but a command it provides + // is not in its directory. + CommandInstallCommandsMissingCode = "plugin.commandInstaller.commandsMissing" +) + +// CommandInstallError is an installation that ran and did not provide its commands. Plugin +// management shows it in the user's language from the fields its code uses. +type CommandInstallError struct { + // Code is one of the CommandInstall codes. + Code string + // ExitCode is the tool's exit code, for CommandInstallFailedCode; -1 when the tool ended + // without one, such as on a signal. + ExitCode int + // Timeout is how long the installation was allowed, for CommandInstallTimedOutCode. + Timeout time.Duration + // Commands and Directory are the commands not found and where they were looked for, for + // CommandInstallCommandsMissingCode. + Commands []string + Directory string +} + +func (e *CommandInstallError) Error() string { + switch e.Code { + case CommandInstallFailedCode: + return fmt.Sprintf("%s: the installation exited with code %d", e.Code, e.ExitCode) + case CommandInstallTimedOutCode: + return fmt.Sprintf("%s: the installation ran past %s", e.Code, e.Timeout) + case CommandInstallCommandsMissingCode: + return fmt.Sprintf("%s: %s not in %s", e.Code, strings.Join(e.Commands, ", "), e.Directory) + } + return e.Code +} diff --git a/desktop/internal/pluginhost/commands_test.go b/desktop/internal/pluginhost/commands_test.go new file mode 100644 index 0000000000..1d952ea88c --- /dev/null +++ b/desktop/internal/pluginhost/commands_test.go @@ -0,0 +1,188 @@ +package pluginhost + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +const commandTestPlugin = "dev.lithe.test.commands" + +// writeCommand puts an executable command named name in directory. +func writeCommand(t *testing.T, directory, name string) string { + t.Helper() + if runtime.GOOS == "windows" { + name += ".exe" + } + if err := os.MkdirAll(directory, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(directory, name) + if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + return path +} + +func notFound(string) (string, error) { return "", errors.New("not found") } + +func TestCommandStoreInstallDirectoryStaysBelowThePluginState(t *testing.T) { + state := t.TempDir() + store := &CommandStore{State: state} + directory, err := store.InstallDirectory(commandTestPlugin, "sample-ls") + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(state, commandTestPlugin, "commands", "sample-ls"); directory != want { + t.Fatalf("directory = %q, want %q", directory, want) + } + // Both IDs are joined into the path, so neither may leave the plugin's state. + for _, ids := range [][2]string{{"../escape", "sample-ls"}, {".hidden", "sample-ls"}, {commandTestPlugin, "../x"}, {commandTestPlugin, "Upper"}, {commandTestPlugin, ""}} { + if _, err := store.InstallDirectory(ids[0], ids[1]); err == nil { + t.Fatalf("InstallDirectory(%q, %q) was accepted", ids[0], ids[1]) + } + } + if _, err := (&CommandStore{State: "relative"}).InstallDirectory(commandTestPlugin, "sample-ls"); err == nil { + t.Fatal("a relative state directory was accepted") + } +} + +func TestCommandStoreRecordsAndReplacesInstallations(t *testing.T) { + state := t.TempDir() + store := &CommandStore{State: state} + managed := filepath.Join(state, commandTestPlugin, "commands", "sample-ls", "bin") + defaults := filepath.Join(t.TempDir(), "go", "bin") + if err := store.Record(commandTestPlugin, CommandInstallation{Installer: "sample-dap", Target: core.CommandInstallToolDefault, Directory: defaults}); err != nil { + t.Fatal(err) + } + if err := store.Record(commandTestPlugin, CommandInstallation{Installer: "sample-ls", Target: core.CommandInstallManaged, Directory: defaults}); err != nil { + t.Fatal(err) + } + // Installing the same installer again replaces its entry. + if err := store.Record(commandTestPlugin, CommandInstallation{Installer: "sample-ls", Target: core.CommandInstallManaged, Directory: managed}); err != nil { + t.Fatal(err) + } + if got := store.Installations(commandTestPlugin); len(got) != 2 { + t.Fatalf("installations = %+v", got) + } + // Managed directories come first. + if got := strings.Join(store.Directories(commandTestPlugin), "|"); got != managed+"|"+defaults { + t.Fatalf("directories = %q", got) + } + // A record of one plugin is not read for another. + if got := store.Directories("dev.lithe.test.other"); len(got) != 0 { + t.Fatalf("other plugin's directories = %v", got) + } + for _, bad := range []CommandInstallation{ + {Installer: "sample-ls", Target: "elsewhere", Directory: managed}, + {Installer: "sample-ls", Target: core.CommandInstallManaged, Directory: "relative/bin"}, + {Installer: "../x", Target: core.CommandInstallManaged, Directory: managed}, + } { + if err := store.Record(commandTestPlugin, bad); !errors.Is(err, ErrCommandRecord) { + t.Fatalf("Record(%+v) = %v", bad, err) + } + } + entries, err := os.ReadDir(filepath.Join(state, commandTestPlugin)) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if strings.HasSuffix(entry.Name(), ".tmp") { + t.Fatalf("temporary file %s was left behind", entry.Name()) + } + } +} + +func TestCommandStoreReadsAnUnusableRecordAsEmpty(t *testing.T) { + state := t.TempDir() + store := &CommandStore{State: state} + directory := filepath.Join(state, commandTestPlugin) + if err := os.MkdirAll(directory, 0o755); err != nil { + t.Fatal(err) + } + record := filepath.Join(directory, "commands.json") + for _, data := range []string{ + "{not json", + `{"installations":[{"installer":"sample-ls","target":"managed","directory":"relative"}]}`, + `{"installations":[{"installer":"sample-ls","target":"managed","directory":"` + strings.Repeat("a", maxCommandRecordBytes) + `"}]}`, + } { + if err := os.WriteFile(record, []byte(data), 0o644); err != nil { + t.Fatal(err) + } + if got := store.Directories(commandTestPlugin); len(got) != 0 { + t.Fatalf("directories = %v for record %.40q", got, data) + } + } + // A corrupt record does not stop a new installation from being recorded. + bin := filepath.Join(t.TempDir(), "bin") + if err := store.Record(commandTestPlugin, CommandInstallation{Installer: "sample-ls", Target: core.CommandInstallToolDefault, Directory: bin}); err != nil { + t.Fatal(err) + } + if got := store.Directories(commandTestPlugin); len(got) != 1 || got[0] != bin { + t.Fatalf("directories = %v", got) + } +} + +func TestCommandStoreLookupTriesPathThenInstalledDirectories(t *testing.T) { + state := t.TempDir() + store := &CommandStore{State: state} + managed := filepath.Join(state, commandTestPlugin, "commands", "sample-ls") + installed := writeCommand(t, managed, "sample-ls") + if err := store.Record(commandTestPlugin, CommandInstallation{Installer: "sample-ls", Target: core.CommandInstallManaged, Directory: managed}); err != nil { + t.Fatal(err) + } + // PATH wins when it has the command. + onPath := func(name string) (string, error) { + if name == "sample-ls" { + return "/usr/bin/sample-ls", nil + } + return "", errors.New("not found") + } + if path, err := ResolveCommand([]string{"sample-ls"}, store.Lookup(commandTestPlugin, onPath)); err != nil || path != "/usr/bin/sample-ls" { + t.Fatalf("path = %q, err = %v", path, err) + } + // Otherwise the installed command is found, and only for its own plugin. + if path, err := ResolveCommand([]string{"sample-ls"}, store.Lookup(commandTestPlugin, notFound)); err != nil || path != installed { + t.Fatalf("path = %q, err = %v", path, err) + } + var missing *CommandMissingError + if _, err := ResolveCommand([]string{"sample-ls"}, store.Lookup("dev.lithe.test.other", notFound)); !errors.As(err, &missing) { + t.Fatalf("err = %v", err) + } + if _, err := ResolveCommand([]string{"sample-dap"}, store.Lookup(commandTestPlugin, notFound)); !errors.As(err, &missing) { + t.Fatalf("err = %v", err) + } + // A nil store looks up PATH only. + var none *CommandStore + if _, err := ResolveCommand([]string{"sample-ls"}, none.Lookup(commandTestPlugin, onPath)); err != nil { + t.Fatal(err) + } +} + +func TestCommandInDirectoryRefusesPaths(t *testing.T) { + directory := t.TempDir() + writeCommand(t, directory, "tool") + if _, err := CommandInDirectory(directory, "tool"); err != nil { + t.Fatal(err) + } + for _, name := range []string{"", ".", "..", "../tool", `sub\tool`} { + if _, err := CommandInDirectory(directory, name); err == nil { + t.Fatalf("CommandInDirectory(%q) was accepted", name) + } + } + if runtime.GOOS != "windows" { + // A file without the executable bit is not a command. + plain := filepath.Join(directory, "plain") + if err := os.WriteFile(plain, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := CommandInDirectory(directory, "plain"); err == nil { + t.Fatal("a non-executable file was accepted") + } + } +} diff --git a/desktop/internal/pluginhost/launch.go b/desktop/internal/pluginhost/launch.go index b9f158fb95..72d10b00e6 100644 --- a/desktop/internal/pluginhost/launch.go +++ b/desktop/internal/pluginhost/launch.go @@ -140,9 +140,11 @@ func VerifyLaunch(packageDirectory string, launch Launch) (Resolved, error) { // plan offers them. // // A system-command launch names bare commands and the host resolves them with its -// own tool discovery. This client resolves PATH; project toolchains and user -// overrides are not consulted yet, so a plan that depends on them is refused rather -// than started with whatever PATH happens to hold. +// own tool discovery. lookup decides where: PATH, then the directories the host +// installed the plugin's commands into (see CommandStore.Lookup). Project +// toolchains and user overrides are not consulted, so a plan that depends on them +// is refused rather than started with whatever PATH happens to hold. When no +// command is found the error is a *CommandMissingError naming them. // // A name that carries a separator is refused: the contract lists bare command // names, and a path would let a plan name a file the host never checked. @@ -150,6 +152,7 @@ func ResolveCommand(commands []string, lookup func(name string) (string, error)) if lookup == nil { return "", fmt.Errorf("%w: no command lookup", ErrPackagePath) } + missing := make([]string, 0, len(commands)) for _, command := range commands { if command == "" || strings.ContainsAny(command, `/\`) { continue @@ -157,8 +160,29 @@ func ResolveCommand(commands []string, lookup func(name string) (string, error)) if path, err := lookup(command); err == nil && path != "" { return path, nil } + missing = append(missing, command) } - return "", fmt.Errorf("%w: none of the plan's commands is available", ErrPackagePath) + if len(missing) == 0 { + return "", fmt.Errorf("%w: the plan names no bare command", ErrPackagePath) + } + return "", &CommandMissingError{Commands: missing} +} + +// CommandMissingCode is the contract's code for a systemCommand launch none of +// whose commands the host found. +const CommandMissingCode = "plugin.command.missing" + +// CommandMissingError is plugin.command.missing: none of the bare commands a +// systemCommand launch names is on PATH or in a directory the host installed the +// plugin's commands into. The window shows it in the user's language, and plugin +// management offers the command's installer when the plugin declares one. +type CommandMissingError struct { + // Commands are the commands looked for, in the launch's order. + Commands []string +} + +func (e *CommandMissingError) Error() string { + return CommandMissingCode + ": none of the commands " + strings.Join(e.Commands, ", ") + " is available" } // GrantServices narrows the host services a launch asks for to those this host diff --git a/desktop/internal/pluginhost/launch_test.go b/desktop/internal/pluginhost/launch_test.go index 4b9097587d..4447930f8d 100644 --- a/desktop/internal/pluginhost/launch_test.go +++ b/desktop/internal/pluginhost/launch_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" ) @@ -142,7 +143,9 @@ func TestResolveCommand(t *testing.T) { if path, err := ResolveCommand([]string{"pylsp", "gopls"}, lookup); err != nil || path != "/usr/local/bin/gopls" { t.Fatalf("path = %q, err = %v", path, err) } - if _, err := ResolveCommand([]string{"pylsp"}, lookup); !errors.Is(err, ErrPackagePath) { + // A missing command is plugin.command.missing, naming every command looked for. + var missing *CommandMissingError + if _, err := ResolveCommand([]string{"pylsp", "pyright"}, lookup); !errors.As(err, &missing) || strings.Join(missing.Commands, ",") != "pylsp,pyright" { t.Fatalf("err = %v", err) } // The contract lists bare command names; a path would name a file the host never diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 919a16c5f2..2c4e181cd7 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -102,6 +102,11 @@ type Capabilities map[string][]int // owned by the host. // - toolDefinitions: settings discovery, Build/Run selection and tool // launches use the shared Core resolver. +// - commandInstallers: plugin management reports the commands a +// systemCommand launch names but the machine lacks, and installs them with +// the plugin's tool after the user confirms the command line, the network +// use and the target (the plugin's managed directory or the tool's own); +// systemCommand launches then find them there (CommandStore). // - projectGenerators: the New Project window lists generators, evaluates // their forms through Core, discovers tools with the shared toolchain and // runs the plan in a staging directory. @@ -123,8 +128,9 @@ type Capabilities map[string][]int // // - a language server's code actions, signature help and inlay hints, and a // plugin's foldingRange provider, which is not routed. -// - tool discovery for system commands reads PATH only; a plan that depends -// on a project toolchain or a user override must use a tool launch. +// - tool discovery for system commands reads PATH and the plugin's installed +// command directories only; a plan that depends on a project toolchain or a +// user override must use a tool launch. // - build provider debug preparation, model inputs, native configuration, // inline test reports and runtime debug; build system instance options and // task preparations. @@ -141,6 +147,7 @@ func Declared() Capabilities { "backend", "buildProviders", "buildSystems", + "commandInstallers", "debugAdapters", "languageServers", "languages", diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index c9bf5fe69c..2d140989ab 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -58,7 +58,7 @@ func TestValidateRefusesBrokenValidator(t *testing.T) { func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { declared := Declared() want := []string{ - "backend", "buildProviders", "buildSystems", "debugAdapters", + "backend", "buildProviders", "buildSystems", "commandInstallers", "debugAdapters", "languageServers", "languages", "outputLinkMatchers", "pluginFunctions", "projectGenerators", "settings", "toolDefinitions", "ui", "vcsProviders", } diff --git a/desktop/internal/pluginpkg/install.go b/desktop/internal/pluginpkg/install.go index f0addc61fc..54e1253ecc 100644 --- a/desktop/internal/pluginpkg/install.go +++ b/desktop/internal/pluginpkg/install.go @@ -88,10 +88,10 @@ func Install(root, id, version, staging string) (Installed, error) { if err := checkRoot(root); err != nil { return Installed{}, err } - if err := checkIdentity("plugin ID", id); err != nil { + if err := CheckIdentity("plugin ID", id); err != nil { return Installed{}, err } - if err := checkIdentity("plugin version", version); err != nil { + if err := CheckIdentity("plugin version", version); err != nil { return Installed{}, err } if staging == "" || !filepath.IsAbs(staging) { @@ -122,10 +122,10 @@ func Uninstall(root, id, version string) error { if err := checkRoot(root); err != nil { return err } - if err := checkIdentity("plugin ID", id); err != nil { + if err := CheckIdentity("plugin ID", id); err != nil { return err } - if err := checkIdentity("plugin version", version); err != nil { + if err := CheckIdentity("plugin version", version); err != nil { return err } target := filepath.Join(root, id, version) @@ -169,7 +169,7 @@ func RemoveState(root, id string) error { if err := checkRoot(root); err != nil { return err } - if err := checkIdentity("plugin ID", id); err != nil { + if err := CheckIdentity("plugin ID", id); err != nil { return err } target := filepath.Join(root, StateDirectory, id) @@ -250,8 +250,9 @@ func checkRoot(root string) error { return nil } -// checkIdentity refuses a plugin ID or version that cannot be a directory name. -func checkIdentity(what, value string) error { +// CheckIdentity refuses a plugin ID or version that cannot be a directory name. +// what names the value in the error, such as "plugin ID". +func CheckIdentity(what, value string) error { if value == "" { return fmt.Errorf("%w: empty %s", ErrInvalidIdentity, what) } diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index e9b8ee110a..af5c5e57d5 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -80,6 +80,10 @@ type Service struct { Installer *plugininstall.Service // Backend starts and stops plugin backends and answers their host requests. Backend *pluginbackend.Runner + // Commands records the commands the host installed through plugins' command + // installers, below the plugin root's state directory; Backend's + // system-command launches look there after PATH. + Commands *pluginhost.CommandStore // Settings reads actual plugin-owned preference layers from native storage. Settings *pluginsettings.Store // HostServices is the registry a backend's grants are narrowed against. @@ -171,6 +175,7 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se Manager: pluginmanager.New(kernel, root, approvals, state), Installer: plugininstall.New(kernel, NewReviewer(kernel), approvals, pluginhost.Declared()), Backend: pluginbackend.New(kernel, hostServices), + Commands: &pluginhost.CommandStore{State: filepath.Join(root, pluginStateDirectory)}, Settings: pluginsettings.New(kernel, preferences.Dir()), HostServices: hostServices, Credentials: credentials.Default(), @@ -179,6 +184,7 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se ledger: ledger, messages: newMessageLimiter(), } + service.Backend.SetCommandStore(service.Commands) service.Host = newBackendHost(service) service.Runs = newRuns(service) service.Contexts = newWorkspaceContexts(filepath.Join(root, pluginStateDirectory)) diff --git a/desktop/internal/settingswindow/command_install.go b/desktop/internal/settingswindow/command_install.go new file mode 100644 index 0000000000..0d822d2a4b --- /dev/null +++ b/desktop/internal/settingswindow/command_install.go @@ -0,0 +1,518 @@ +package settingswindow + +import ( + "context" + "errors" + "strconv" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" + "github.com/vivaui/viva/ui" +) + +// commandCheckTimeout bounds one check of a plugin's commands: a few Core calls and PATH +// lookups. +const commandCheckTimeout = 15 * time.Second + +// commandOfferTimeout bounds preparing the install dialog: resolving the tool and running +// its directory probes. +const commandOfferTimeout = 30 * time.Second + +// commandOutputLines is how many of the last lines an installation printed the dialog keeps. +const commandOutputLines = 200 + +// commandOutputHeight is the height of the dialog's output box. +const commandOutputHeight = 160 + +// commandCheckOperation and commandOfferOperation name, in the log, a check or an install +// dialog that could not be prepared. The installation itself is a plugin operation the +// workbench records. +const ( + commandCheckOperation = "plugin_command_check" + commandOfferOperation = "plugin_command_offer" +) + +// commandCheckKey names one check: the plugin and the generation it was asked in. +type commandCheckKey struct { + plugin string + generation int +} + +// commandCheck is what one check found. +type commandCheck struct { + key commandCheckKey + missing []MissingCommand +} + +type commandOfferRequest struct{ pluginID, installerID string } + +type commandInstallRequest struct { + pluginID, installerID, target string + output *commandOutput +} + +// commandInstalls is the Installed tab's view of the commands plugins need: which of the shown +// plugin's commands are missing, and the dialog that installs them. Everything runs on the +// window thread but the effects' run functions and commandOutput. +type commandInstalls struct { + source CommandInstaller + report func(operation string, err error) + wake func() + + check *ui.EffectState[commandCheck, commandCheckKey] + // key is the check to run; a zero one means none. generation grows when the shown plugin + // changes, an installation finishes or the plugin registry changes, so the next paint of + // the plugin checks again. + key commandCheckKey + generation int + shown string + results map[string]commandCheck + + offer *ui.EffectState[CommandInstallOffer, *commandOfferRequest] + install *ui.EffectState[string, *commandInstallRequest] + dialog *commandInstallDialog +} + +// commandInstallDialog is one install dialog: the offer it shows, the target the user picks, +// then the installation's output and outcome. +type commandInstallDialog struct { + pluginID, pluginName string + missing MissingCommand + open bool + + offerRequest *commandOfferRequest + offer *CommandInstallOffer + offerErr error + target string + + installRequest *commandInstallRequest + output *commandOutput + directory string + installErr error +} + +func newCommandInstalls(source CommandInstaller, report func(string, error), wake func()) *commandInstalls { + s := &commandInstalls{source: source, report: report, wake: wake, results: make(map[string]commandCheck)} + if source == nil { + return s + } + s.check = ui.NewEffectKeyed[commandCheck, commandCheckKey](func(ctx context.Context, key commandCheckKey) (commandCheck, error) { + ctx, cancel := context.WithTimeout(ctx, commandCheckTimeout) + defer cancel() + missing, err := source.Missing(ctx, key.plugin) + return commandCheck{key: key, missing: missing}, err + }) + s.offer = ui.NewEffectKeyed[CommandInstallOffer, *commandOfferRequest](func(ctx context.Context, request *commandOfferRequest) (CommandInstallOffer, error) { + ctx, cancel := context.WithTimeout(ctx, commandOfferTimeout) + defer cancel() + return source.Offer(ctx, request.pluginID, request.installerID) + }) + // The installer bounds its own run by the plan's timeout. + s.install = ui.NewEffectKeyed[string, *commandInstallRequest](func(ctx context.Context, request *commandInstallRequest) (string, error) { + return source.Install(ctx, request.pluginID, request.installerID, request.target, request.output.add) + }) + return s +} + +// want returns what the last check of pluginID found, and asks for a new check when the +// plugin was not the one shown before or something changed since that check. +func (s *commandInstalls) want(pluginID string) []MissingCommand { + if s == nil || s.check == nil { + return nil + } + if pluginID != s.shown { + s.shown = pluginID + s.generation++ + } + result, ok := s.results[pluginID] + if !ok || result.key.generation != s.generation { + s.key = commandCheckKey{plugin: pluginID, generation: s.generation} + } + return result.missing +} + +// invalidate checks the shown plugin again on its next paint. +func (s *commandInstalls) invalidate() { + if s != nil { + s.generation++ + } +} + +// take keeps the results the effects finished with. +func (s *commandInstalls) take() { + if s == nil || s.check == nil { + return + } + if result, err, ok := s.check.Take(); ok { + if err != nil { + s.report(commandCheckOperation, err) + result.missing = nil + } + s.results[result.key.plugin] = result + if s.key == result.key { + s.key = commandCheckKey{} + } + } + dialog := s.dialog + if offer, err, ok := s.offer.Take(); ok && dialog != nil && dialog.offerRequest != nil { + dialog.offerRequest = nil + if err != nil { + dialog.offerErr = err + s.report(commandOfferOperation, err) + } else { + dialog.offer = &offer + dialog.target = "" + for _, target := range offer.Targets { + if target.Directory != "" { + dialog.target = target.Target + break + } + } + } + } + if directory, err, ok := s.install.Take(); ok && dialog != nil && dialog.installRequest != nil { + dialog.installRequest = nil + dialog.directory, dialog.installErr = directory, err + // What was installed, or half installed, changes what the plugin is missing. + s.invalidate() + } +} + +// declare declares the work the tab asked for. +func (s *commandInstalls) declare(c ui.C) { + if s == nil || s.check == nil { + return + } + if s.key.plugin != "" { + ui.Effect(c, s.check, s.key) + } + if dialog := s.dialog; dialog != nil { + if dialog.offerRequest != nil { + ui.Effect(c, s.offer, dialog.offerRequest) + } + if dialog.installRequest != nil { + ui.Effect(c, s.install, dialog.installRequest) + } + } +} + +// start opens the install dialog for one missing launch of a plugin. +func (s *commandInstalls) start(pluginID, pluginName string, missing MissingCommand) { + if s.check == nil || missing.Installer == "" { + return + } + s.dialog = &commandInstallDialog{pluginID: pluginID, pluginName: pluginName, missing: missing, open: true} + s.loadOffer() +} + +func (s *commandInstalls) loadOffer() { + dialog := s.dialog + dialog.offer, dialog.offerErr = nil, nil + dialog.offerRequest = &commandOfferRequest{pluginID: dialog.pluginID, installerID: dialog.missing.Installer} +} + +func (s *commandInstalls) runInstall() { + dialog := s.dialog + if dialog == nil || dialog.offer == nil || dialog.installRequest != nil { + return + } + dialog.directory, dialog.installErr = "", nil + dialog.output = &commandOutput{wake: s.wake} + dialog.installRequest = &commandInstallRequest{ + pluginID: dialog.pluginID, installerID: dialog.offer.Installer, target: dialog.target, output: dialog.output, + } +} + +// close drops the dialog. An installation still running stops with it: its effect is no +// longer declared, which cancels it and so stops the tool. +func (s *commandInstalls) close() { + s.dialog = nil +} + +// commandOutput keeps the last lines an installation printed. The installation's goroutine +// adds them; the window thread reads them. +type commandOutput struct { + wake func() + + mu sync.Mutex + lines []string +} + +func (o *commandOutput) add(line string) { + o.mu.Lock() + if len(o.lines) == commandOutputLines { + o.lines = append(o.lines[:0], o.lines[1:]...) + } + o.lines = append(o.lines, line) + o.mu.Unlock() + if o.wake != nil { + o.wake() + } +} + +func (o *commandOutput) text() string { + if o == nil { + return "" + } + o.mu.Lock() + defer o.mu.Unlock() + return strings.Join(o.lines, "\n") +} + +// missingFor is the missing launch of capability, if any. +func missingFor(missing []MissingCommand, capability PluginCapability) (MissingCommand, bool) { + for _, entry := range missing { + if entry.Kind != "" && entry.Kind == capability.Kind && entry.ID == capability.ID { + return entry, true + } + } + return MissingCommand{}, false +} + +// unmatchedMissing lists the missing launches no card shows, such as the backend's. +func unmatchedMissing(missing []MissingCommand, capabilities []PluginCapability) []MissingCommand { + var unmatched []MissingCommand + for _, entry := range missing { + shown := false + for _, capability := range capabilities { + if _, ok := missingFor([]MissingCommand{entry}, capability); ok { + shown = true + break + } + } + if !shown { + unmatched = append(unmatched, entry) + } + } + return unmatched +} + +func commandList(commands []string) string { + return strings.Join(commands, " | ") +} + +// commandMissingStatus is a card's status line for a launch whose commands are missing: the +// words, then an install button, or a note that the user has to install them. +func (w *window) commandMissingStatus(c ui.C, language i18n.Language, fact PluginFacts, missing MissingCommand) { + ui.Text(c, i18n.SharedFormat(language, "desktop.plugins.commandMissing", map[string]string{"commands": commandList(missing.Commands)})). + FontSize(11).Color(w.pal.warning).Shrink(1).MinWidth(0).Ellipsis() + if missing.Installer == "" { + w.infoButton(c, i18n.Shared(language, "desktop.plugins.commandMissingManual")) + return + } + if ui.Button(c, i18n.Shared(language, "desktop.marketplace.install")).XSmall().Clicked() { + pluginID, name := fact.ID, fact.Name + c.After(func() { w.commands.start(pluginID, name, missing) }) + } +} + +// commandMissingBanner shows, above the cards, the missing launches no card shows. +func (w *window) commandMissingBanner(c ui.C, language i18n.Language, fact PluginFacts, missing []MissingCommand) { + for index, entry := range missing { + k := c.KeyInt(index) + ui.Row(k).FillWidth().Gap(8).Pad(10).Radius(8).Items(ui.Center).Stroke(1, w.pal.line).Background(w.pal.card).Children(func() { + ui.Wrap(k, i18n.SharedFormat(language, "desktop.plugins.commandMissingBanner", map[string]string{"commands": commandList(entry.Commands)})). + FontSize(12).Color(w.pal.warning).Grow(1).Shrink(1).MinWidth(0) + if entry.Installer == "" { + w.infoButton(k, i18n.Shared(language, "desktop.plugins.commandMissingManual")) + return + } + if ui.Button(k, i18n.Shared(language, "desktop.marketplace.install")).XSmall().Clicked() { + pluginID, name, chosen := fact.ID, fact.Name, entry + k.After(func() { w.commands.start(pluginID, name, chosen) }) + } + }) + } +} + +// commandInstallModal is the install dialog, when one is open. +func (w *window) commandInstallModal(c ui.C) { + s := w.commands + if s == nil || s.dialog == nil { + return + } + dialog := s.dialog + language := w.marketLanguage() + installing := dialog.installRequest != nil + installed := dialog.output != nil && !installing && dialog.installErr == nil + installFailed := dialog.output != nil && !installing && dialog.installErr != nil + var cancelled, confirmed, retried bool + title := i18n.SharedFormat(language, "desktop.plugins.commandInstallTitle", map[string]string{"commands": commandList(dialog.missing.Commands)}) + closed := ui.ModalWith(c, &dialog.open, title, ui.ModalSpec{Width: 620, Description: dialog.pluginName}, func() { + ui.Column(c).FillWidth().Gap(8).Children(func() { + switch { + case installing: + ui.Text(c, i18n.Shared(language, "settings.general.installing")) + ui.Progress(c, 0).Indeterminate().FillWidth() + w.commandInstallOutput(c, language, dialog.output) + case installed: + ui.Wrap(c, i18n.SharedFormat(language, "desktop.plugins.commandInstalled", map[string]string{"directory": dialog.directory})).Color(w.pal.success) + w.commandInstallOutput(c, language, dialog.output) + case installFailed: + ui.Wrap(c, commandInstallFailureText(language, dialog.missing.Tool, dialog.installErr)).Color(w.pal.danger) + w.commandInstallOutput(c, language, dialog.output) + case dialog.offerErr != nil: + ui.Wrap(c, commandInstallFailureText(language, dialog.missing.Tool, dialog.offerErr)).Color(w.pal.danger) + case dialog.offer == nil: + ui.Text(c, i18n.Shared(language, "native.loading")) + ui.Progress(c, 0).Indeterminate().FillWidth() + default: + w.commandInstallOffer(c, language, dialog) + } + }) + }, func() { + switch { + case installing: + cancelled = ui.Button(c, i18n.Shared(language, "ui.cancel")).Outline().Clicked() + case installed: + cancelled = ui.Button(c, i18n.Shared(language, "ui.done")).AutoFocus().Clicked() + case installFailed, dialog.offerErr != nil: + cancelled = ui.Button(c, i18n.Shared(language, "ui.close")).Outline().Clicked() + retried = ui.Button(c, i18n.Shared(language, "ui.retry")).Clicked() + case dialog.offer == nil: + cancelled = ui.Button(c, i18n.Shared(language, "ui.cancel")).Outline().Clicked() + default: + cancelled = ui.Button(c, i18n.Shared(language, "ui.cancel")).Outline().Clicked() + confirmed = ui.Button(c, i18n.Shared(language, "desktop.marketplace.install")).Disabled(!dialog.targetUsable()).AutoFocus().Clicked() + } + }) + switch { + case retried: + c.After(func() { + if s.dialog != dialog { + return + } + if dialog.offerErr != nil { + s.loadOffer() + } else { + s.runInstall() + } + }) + case confirmed: + c.After(func() { + if s.dialog == dialog && dialog.targetUsable() { + s.runInstall() + } + }) + case closed || cancelled: + c.After(func() { + if s.dialog == dialog { + s.close() + } + }) + } +} + +// targetUsable says the picked target names a directory the host can find the commands in. +func (d *commandInstallDialog) targetUsable() bool { + if d.offer == nil { + return false + } + for _, target := range d.offer.Targets { + if target.Target == d.target { + return target.Directory != "" + } + } + return false +} + +// commandInstallOffer is the confirmation: what runs, whether it downloads, and where the +// commands may go. +func (w *window) commandInstallOffer(c ui.C, language i18n.Language, dialog *commandInstallDialog) { + offer := dialog.offer + ui.Wrap(c, i18n.SharedFormat(language, "desktop.plugins.commandInstallPrompt", map[string]string{ + "tool": offer.Tool, "commands": commandList(offer.Commands), + })) + if offer.MayUseNetwork { + ui.Wrap(c, i18n.Shared(language, "desktop.plugins.commandInstallNetwork")).FontSize(12).Color(w.pal.warning) + } + ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallLocation")).FontSize(13).Bold().PadTop(4) + var chosen *CommandInstallTarget + for index := range offer.Targets { + target := &offer.Targets[index] + k := c.KeyInt(index) + label, help := commandTargetWords(language, offer.Tool, target.Target) + if target.Directory == "" { + help = i18n.SharedFormat(language, "desktop.plugins.commandInstallNoDirectory", map[string]string{"tool": offer.Tool}) + } + ui.Column(k).FillWidth().Gap(2).Children(func() { + w.radio(k, &dialog.target, target.Target, label, target.Directory == "") + ui.Column(k).FillWidth().Gap(2).PadLeft(radioSize + 8).Children(func() { + ui.Wrap(k, help).FontSize(11).Color(w.pal.muted) + if target.Directory != "" { + ui.Wrap(k, target.Directory).Mono().FontSize(11).Color(w.pal.subtle) + } + }) + }) + if target.Target == dialog.target { + chosen = target + } + } + if chosen == nil { + return + } + ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallCommand")).FontSize(13).Bold().PadTop(4) + ui.Column(c).FillWidth().Gap(2).Pad(8).Radius(6).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { + for index, variable := range chosen.Environment { + ui.Wrap(c.KeyInt(index), variable).Mono().FontSize(11).Color(w.pal.muted) + } + ui.Wrap(c, chosen.CommandLine).Mono().FontSize(11).Color(w.pal.text) + }) +} + +// commandTargetWords is a target's radio label and the line under it. +func commandTargetWords(language i18n.Language, tool, target string) (string, string) { + if target == core.CommandInstallToolDefault { + return i18n.SharedFormat(language, "desktop.plugins.commandInstallToolDefault", map[string]string{"tool": tool}), + i18n.Shared(language, "desktop.plugins.commandInstallToolDefaultHelp") + } + return i18n.Shared(language, "desktop.plugins.commandInstallManaged"), i18n.Shared(language, "desktop.plugins.commandInstallManagedHelp") +} + +// commandInstallOutput shows what the installation printed so far. +func (w *window) commandInstallOutput(c ui.C, language i18n.Language, output *commandOutput) { + text := output.text() + if text == "" { + return + } + ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallOutput")).FontSize(13).Bold().PadTop(4) + ui.Scroll(c.Part("command-output")).Scrollbars().FillWidth().MaxHeight(commandOutputHeight).Pad(8).Radius(6).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { + ui.Wrap(c, text).Mono().FontSize(11).Color(w.pal.text).FillWidth() + }) +} + +// commandInstallFailureText is why an installation, or preparing it, failed, in the user's +// language. tool is the display name of the installer's tool. +func commandInstallFailureText(language i18n.Language, tool string, err error) string { + var installErr *pluginhost.CommandInstallError + var unavailable *toolchain.UnavailableError + switch { + case errors.As(err, &installErr): + switch installErr.Code { + case pluginhost.CommandInstallTimedOutCode: + return i18n.SharedFormat(language, "desktop.plugins.commandInstallTimedOut", map[string]string{ + "seconds": strconv.Itoa(int(installErr.Timeout / time.Second)), + }) + case pluginhost.CommandInstallCommandsMissingCode: + return i18n.SharedFormat(language, "desktop.plugins.commandInstallCommandsMissing", map[string]string{ + "commands": commandList(installErr.Commands), "directory": installErr.Directory, + }) + case pluginhost.CommandInstallFailedCode: + if installErr.ExitCode < 0 { + return i18n.Shared(language, "desktop.plugins.commandInstallStopped") + } + return i18n.SharedFormat(language, "desktop.plugins.commandInstallFailed", map[string]string{"code": strconv.Itoa(installErr.ExitCode)}) + } + case errors.As(err, &unavailable): + if tool == "" { + tool = unavailable.Tool + } + return i18n.SharedFormat(language, "desktop.plugins.commandInstallToolMissing", map[string]string{"tool": tool}) + } + return i18n.SharedFormat(language, "desktop.plugins.commandInstallError", map[string]string{"reason": err.Error()}) +} diff --git a/desktop/internal/settingswindow/command_install_test.go b/desktop/internal/settingswindow/command_install_test.go new file mode 100644 index 0000000000..022fe13dcc --- /dev/null +++ b/desktop/internal/settingswindow/command_install_test.go @@ -0,0 +1,194 @@ +package settingswindow + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" + "github.com/vivaui/viva/app" +) + +const fixtureCommandDirectory = "/data/commands/fixture-ls" + +// fakeCommandInstaller is a plugin whose language server misses fixture-ls, which an installer +// provides, and whose backend misses fixture-backend, which none does. An installation prints +// one line and then waits for release or a cancel. +type fakeCommandInstaller struct { + mu sync.Mutex + installed bool + targets []string + printed chan struct{} + release chan struct{} + cancelled chan struct{} +} + +func newFakeCommandInstaller() *fakeCommandInstaller { + return &fakeCommandInstaller{printed: make(chan struct{}), release: make(chan struct{}), cancelled: make(chan struct{})} +} + +func (f *fakeCommandInstaller) Missing(context.Context, string) ([]MissingCommand, error) { + f.mu.Lock() + defer f.mu.Unlock() + missing := []MissingCommand{{Commands: []string{"fixture-backend"}}} + if !f.installed { + missing = append(missing, MissingCommand{Kind: CapabilityLanguageServer, ID: "fixture", Commands: []string{"fixture-ls"}, Installer: "fixture-ls", Tool: "Builder"}) + } + return missing, nil +} + +func (f *fakeCommandInstaller) Offer(context.Context, string, string) (CommandInstallOffer, error) { + return CommandInstallOffer{ + Installer: "fixture-ls", Commands: []string{"fixture-ls"}, Tool: "Builder", Executable: "/tools/builder", + MayUseNetwork: true, Timeout: time.Minute, + Targets: []CommandInstallTarget{ + {Target: core.CommandInstallManaged, CommandLine: "/tools/builder install fixture-ls", Environment: []string{"FIXTURE_BIN=" + fixtureCommandDirectory}, Directory: fixtureCommandDirectory}, + {Target: core.CommandInstallToolDefault, CommandLine: "/tools/builder install fixture-ls"}, + }, + }, nil +} + +func (f *fakeCommandInstaller) Install(ctx context.Context, _, _, target string, output func(string)) (string, error) { + f.mu.Lock() + f.targets = append(f.targets, target) + f.mu.Unlock() + output("fixture: downloading") + close(f.printed) + select { + case <-f.release: + case <-ctx.Done(): + close(f.cancelled) + return "", ctx.Err() + } + f.mu.Lock() + f.installed = true + f.mu.Unlock() + return fixtureCommandDirectory, nil +} + +func (f *fakeCommandInstaller) installedTargets() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.targets...) +} + +func commandInstallWindow(f *fakeCommandInstaller) *window { + facts := []PluginFacts{{ + ID: "dev.lithe.test.commands", Name: "Commands Fixture", Vendor: "Test", Version: "1.0.0", Source: PluginSourceDisk, + Permissions: []string{"commands.install", "languageServer.launch"}, + Capabilities: []PluginCapability{{Kind: CapabilityLanguageServer, ID: "fixture", Title: "fixture-ls", Commands: []string{"fixture-ls"}}}, + }} + w := newWindow(NewController(Options{ + Language: func() i18n.Language { return i18n.English }, + Marketplace: func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{}, nil + }, + InstalledPlugins: func() []PluginFacts { return facts }, + PluginState: func(string) PluginState { + return PluginState{Installed: true, Version: "1.0.0", Enabled: true} + }, + CommandInstalls: f, + }), Values{}) + w.sess.page = pagePlugins + w.installed.tab = installedFeatures + return w +} + +func waitClosed(t *testing.T, what string, done <-chan struct{}) { + t.Helper() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +func TestCapabilityCardInstallsItsMissingCommand(t *testing.T) { + f := newFakeCommandInstaller() + w := commandInstallWindow(f) + d := openWindow(t, w, func(config *app.Config) { config.Width, config.Height = 1100, 800 }) + words := func(key string) string { return i18n.Shared(i18n.English, key) } + format := func(key string, values map[string]string) string { return i18n.SharedFormat(i18n.English, key, values) } + missing := format("desktop.plugins.commandMissing", map[string]string{"commands": "fixture-ls"}) + d.until("the card to report the missing command", func() bool { return d.text(missing) }) + if !d.text(format("desktop.plugins.commandMissingBanner", map[string]string{"commands": "fixture-backend"})) { + t.Fatal("a missing command no card shows has no banner") + } + + d.click(words("desktop.marketplace.install")) + prompt := format("desktop.plugins.commandInstallPrompt", map[string]string{"tool": "Builder", "commands": "fixture-ls"}) + d.until("the install offer", func() bool { return d.text(prompt) }) + for _, shown := range []string{ + words("desktop.plugins.commandInstallNetwork"), + words("desktop.plugins.commandInstallManaged"), + fixtureCommandDirectory, + "FIXTURE_BIN=" + fixtureCommandDirectory, + "/tools/builder install fixture-ls", + // The tool's own directory is unknown, so that target cannot be chosen. + format("desktop.plugins.commandInstallNoDirectory", map[string]string{"tool": "Builder"}), + } { + if !d.text(shown) { + t.Fatalf("the offer does not show %q", shown) + } + } + + // The dialog is in front, so this is its Install button. + d.click(words("desktop.marketplace.install")) + waitClosed(t, "the installation to start", f.printed) + d.until("the installation's output", func() bool { return d.text("fixture: downloading") }) + close(f.release) + installed := format("desktop.plugins.commandInstalled", map[string]string{"directory": fixtureCommandDirectory}) + d.until("the installed message", func() bool { return d.text(installed) }) + if targets := f.installedTargets(); len(targets) != 1 || targets[0] != core.CommandInstallManaged { + t.Fatalf("installed into %v, want the managed target", targets) + } + d.click(words("ui.done")) + d.until("the card to drop the installed command", func() bool { return w.commands.dialog == nil && !d.text(missing) }) +} + +func TestCancellingTheInstallDialogStopsTheInstallation(t *testing.T) { + f := newFakeCommandInstaller() + w := commandInstallWindow(f) + d := openWindow(t, w, func(config *app.Config) { config.Width, config.Height = 1100, 800 }) + words := func(key string) string { return i18n.Shared(i18n.English, key) } + missing := i18n.SharedFormat(i18n.English, "desktop.plugins.commandMissing", map[string]string{"commands": "fixture-ls"}) + d.until("the card to report the missing command", func() bool { return d.text(missing) }) + d.click(words("desktop.marketplace.install")) + d.until("the install offer", func() bool { return w.commands.dialog != nil && w.commands.dialog.offer != nil }) + d.pump() + d.click(words("desktop.marketplace.install")) + waitClosed(t, "the installation to start", f.printed) + d.until("the installation's output", func() bool { return d.text("fixture: downloading") }) + d.click(words("ui.cancel")) + d.pump() + waitClosed(t, "the cancel to reach the installation", f.cancelled) + if w.commands.dialog != nil { + t.Fatal("the dialog stayed open after the cancel") + } +} + +func TestCommandInstallFailuresAreLocalized(t *testing.T) { + format := func(key string, values map[string]string) string { return i18n.SharedFormat(i18n.English, key, values) } + for _, test := range []struct { + err error + want string + }{ + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallFailedCode, ExitCode: 3}, format("desktop.plugins.commandInstallFailed", map[string]string{"code": "3"})}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallFailedCode, ExitCode: -1}, i18n.Shared(i18n.English, "desktop.plugins.commandInstallStopped")}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallTimedOutCode, Timeout: 5 * time.Minute}, format("desktop.plugins.commandInstallTimedOut", map[string]string{"seconds": "300"})}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallCommandsMissingCode, Commands: []string{"a", "b"}, Directory: "/d"}, + format("desktop.plugins.commandInstallCommandsMissing", map[string]string{"commands": commandList([]string{"a", "b"}), "directory": "/d"})}, + {&toolchain.UnavailableError{Tool: "dev.example:builder", Code: "notFound"}, format("desktop.plugins.commandInstallToolMissing", map[string]string{"tool": "Builder"})}, + {errors.New("disk full"), format("desktop.plugins.commandInstallError", map[string]string{"reason": "disk full"})}, + } { + if got := commandInstallFailureText(i18n.English, "Builder", test.err); got != test.want { + t.Errorf("%v: %q, want %q", test.err, got, test.want) + } + } +} diff --git a/desktop/internal/settingswindow/command_install_visual_test.go b/desktop/internal/settingswindow/command_install_visual_test.go new file mode 100644 index 0000000000..38b4dc9419 --- /dev/null +++ b/desktop/internal/settingswindow/command_install_visual_test.go @@ -0,0 +1,72 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/vivaui/viva/headless" +) + +// TestVisualCommandInstall renders a capability card whose command is missing, with its +// Install button, and the install dialog it opens. Opt in with -tags 'vivahead lithevisual' +// and LITHE_VISUAL_OUTPUT_DIR. +func TestVisualCommandInstall(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture the command install dialog") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct { + theme string + language i18n.Language + }{{"dark", i18n.Chinese}, {"light", i18n.English}} { + t.Run(look.theme, func(t *testing.T) { + f := newFakeCommandInstaller() + facts := []PluginFacts{{ + ID: "dev.lithe.test.commands", Name: "Commands Fixture", Vendor: "Test", Version: "1.0.0", Source: PluginSourceDisk, + Permissions: []string{"commands.install", "languageServer.launch"}, + Capabilities: []PluginCapability{{Kind: CapabilityLanguageServer, ID: "fixture", Title: "fixture-ls", Commands: []string{"fixture-ls"}}}, + }} + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(look.language) }, Language: func() i18n.Language { return look.language }, + SystemLanguage: look.language, SystemDark: func() bool { return look.theme == "dark" }, + Marketplace: func(context.Context) (marketplace.Snapshot, error) { return marketplace.Snapshot{}, nil }, + InstalledPlugins: func() []PluginFacts { return facts }, + PluginState: func(string) PluginState { return PluginState{Installed: true, Version: "1.0.0", Enabled: true} }, + CommandInstalls: f, + }), Values{Theme: look.theme, Language: look.language.Code()}) + w.sess.page = pagePlugins + w.installed.tab = installedFeatures + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + missing := i18n.SharedFormat(look.language, "desktop.plugins.commandMissing", map[string]string{"commands": "fixture-ls"}) + d.until("the card to report the missing command", func() bool { return d.text(missing) }) + if err := session.Screenshot(filepath.Join(out, "command-install-card-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + d.click(i18n.Shared(look.language, "desktop.marketplace.install")) + prompt := i18n.SharedFormat(look.language, "desktop.plugins.commandInstallPrompt", map[string]string{"tool": "Builder", "commands": "fixture-ls"}) + d.until("the install offer", func() bool { return d.text(prompt) }) + // The dialog fades in; move the frame clock past it. + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(out, "command-install-dialog-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index b9b82b17dd..85bd3a3a1b 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -11,6 +11,7 @@ import ( "context" "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" "sync" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" @@ -198,6 +199,67 @@ type PluginSettingsActionLoader interface { Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) } +// CommandInstaller finds the commands installed plugins run from the user's system and +// installs a missing one through the installer its plugin declares (commandInstallers[], +// API-23). Every call runs off the window thread and returns once ctx ends. +type CommandInstaller interface { + // Missing lists the plugin's launches none of whose commands the host finds, looked up as + // the launches look them up. A plugin whose commands are all found has none. + Missing(ctx context.Context, pluginID string) ([]MissingCommand, error) + // Offer prepares what the install dialog shows for one installer: the tool that runs, and + // each target's command line and directory. It installs nothing; it may run the tool's + // directory probes, which only print where the tool installs. + Offer(ctx context.Context, pluginID, installerID string) (CommandInstallOffer, error) + // Install runs the installer for the target the user chose, handing each line the tool + // prints to output as it arrives, and returns the directory its commands are in once they + // are found there. Cancelling ctx stops the tool. A failed installation is a + // *pluginhost.CommandInstallError when the tool ran, and a *toolchain.UnavailableError + // from Offer or Install when the tool is not found. + Install(ctx context.Context, pluginID, installerID, target string, output func(string)) (string, error) +} + +// MissingCommand is one launch of a plugin none of whose commands the host finds. +type MissingCommand struct { + // Kind and ID name the capability the launch belongs to: one of the Capability constants + // and the capability's ID. Kind is empty for the plugin's backend, which has no card. + Kind, ID string + // Commands are the commands the launch looks for, in its order. + Commands []string + // Installer is the ID of the installer that provides them, or "" when the plugin declares + // none and the user has to install them another way. + Installer string + // Tool is the display name of the tool the installer runs; empty without an installer. + Tool string +} + +// CommandInstallOffer is what the install dialog shows before the user confirms. +type CommandInstallOffer struct { + Installer string + // Commands are the commands the installation provides. + Commands []string + // Tool is the tool definition that runs it, and Executable the program resolved for it. + Tool, Executable string + // MayUseNetwork says the installation may download. + MayUseNetwork bool + // Timeout is how long the installation may run. + Timeout time.Duration + // Targets are the places the user may install into, managed first. + Targets []CommandInstallTarget +} + +// CommandInstallTarget is one place an installation can put its commands. +type CommandInstallTarget struct { + // Target is core.CommandInstallManaged or core.CommandInstallToolDefault. + Target string + // CommandLine is the program and its arguments as they will run, and Environment the + // variables set for it, each NAME=value. + CommandLine string + Environment []string + // Directory is where the commands will land; empty when the tool's probes named no + // directory, which leaves the target unusable since the host could not find the commands. + Directory string +} + // Options configure the settings window. type Options struct { // PluginInstallsClosed releases downloads retained by the settings session. @@ -247,6 +309,9 @@ type Options struct { // LanguageServerState reports the state of a plugin's running language server: its state // name, or "" when none runs. It is read while painting on the window's thread. LanguageServerState func(pluginID string) string + // CommandInstalls finds the commands the Installed tab's plugins are missing and installs + // them; nil shows no command status. + CommandInstalls CommandInstaller // UninstallPlugin removes the installed version of a plugin. UninstallPlugin func(id string) // InstallPluginFromFile installs a plugin package the user picked on disk. The diff --git a/desktop/internal/settingswindow/installed_view.go b/desktop/internal/settingswindow/installed_view.go index 44babc7b44..93c8828e7f 100644 --- a/desktop/internal/settingswindow/installed_view.go +++ b/desktop/internal/settingswindow/installed_view.go @@ -840,6 +840,11 @@ func (w *window) installedFeatures(c ui.C, language i18n.Language, fact PluginFa return } enabled := w.pluginState(fact.ID).Enabled + var missing []MissingCommand + if enabled { + missing = w.commands.want(fact.ID) + w.commandMissingBanner(c.Part("command-missing"), language, fact, unmatchedMissing(missing, fact.Capabilities)) + } ui.Grid(c, 220).FillWidth().Gap(10).Children(func() { for index, capability := range fact.Capabilities { k := c.KeyInt(index) @@ -854,7 +859,9 @@ func (w *window) installedFeatures(c ui.C, language i18n.Language, fact PluginFa ui.Wrap(k, detail).FontSize(11).Color(w.pal.muted) } ui.Row(k).FillWidth().Gap(8).Items(ui.Center).Children(func() { - if enabled { + if entry, ok := missingFor(missing, capability); enabled && ok { + w.commandMissingStatus(k, language, fact, entry) + } else if enabled { ui.Text(k, i18n.Shared(language, "native.available")).FontSize(11).Color(w.pal.success) } else { ui.Text(k, i18n.Shared(language, "native.pluginDisabled")).FontSize(11).Color(w.pal.muted) @@ -926,6 +933,8 @@ func permissionDescription(language i18n.Language, permission string) string { return i18n.Shared(language, "native.showItsOwnPageInAToolWindow") case "process.test": return i18n.Shared(language, "native.runYourTests") + case "commands.install": + return i18n.Shared(language, "desktop.marketplace.permissionCommandsInstall") } return "" } diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 85e1f6c896..c586602dd8 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -86,6 +86,9 @@ type window struct { market *marketplaceState install *pluginInstallDialog + // commands is the Installed tab's check of the commands plugins need and the dialog that + // installs them (command_install.go). + commands *commandInstalls // pluginTab is the open tab of the plugin page, one of the pluginTab constants: // what is installed, or the marketplace. installed is the Installed tab's own list, // filter and detail (installed_view.go). @@ -240,6 +243,7 @@ func newWindow(c *Controller, current Values) *window { w.dynamic.bind() w.pluginSettings.report = func(err error) { reportSettingsError(c.opts, pluginSettingsOperation, err) } w.toolchains = newToolchainState(c.opts.Toolchains) + w.commands = newCommandInstalls(c.opts.CommandInstalls, func(operation string, err error) { reportSettingsError(c.opts, operation, err) }, func() { w.inv.Invalidate() }) w.stepping = newSteppingState(c.opts.SteppingAdapters, c.opts.NormalizeSteppingFilters) w.terminal = newTerminalShellState(c.opts.TerminalShells) w.fonts = newFontListState(c.opts.MonospaceFamilies) @@ -312,6 +316,7 @@ func (w *window) wake() { } if w.pluginRegistryChanged.Swap(false) { w.dynamic.invalidate() + w.commands.invalidate() w.rowsValid = false w.settingsChanged.Store(true) if w.market.source == 2 { @@ -433,6 +438,7 @@ func (w *window) collect() { w.terminal.take() w.fonts.take() w.takeKeymapImport() + w.commands.take() if w.dynamic.take() { w.rowsValid = false } @@ -473,6 +479,7 @@ func (w *window) declareWork(c ui.C) { if s := &w.keyImport; s.open && s.effect != nil && s.request != nil { ui.Effect(c, s.effect, s.request) } + w.commands.declare(c) w.dynamic.declare(c) w.market.declare(c) w.market.search.declare(c) diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 3ae324a676..3fee6b5ef5 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -33,6 +33,7 @@ func (w *window) view(c ui.C) { }) w.keymapImportDialog(c) w.pluginInstallModal(c.Part("plugin-install")) + w.commandInstallModal(c.Part("command-install")) w.declareWork(c) } diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 9e492d0205..d05887c9ef 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -117,6 +117,13 @@ type Kernel interface { DecodeBuildModel(ctx context.Context, manifest json.RawMessage, buildSystemID string, request core.BuildDecodeModelRequest) (core.BuildModel, error) DecodeBuildRun(ctx context.Context, manifest json.RawMessage, buildSystemID string, request core.BuildDecodeRunRequest) (core.BuildLaunch, error) ToolchainRegistryOf(ctx context.Context, manifests []json.RawMessage) (core.ToolchainRegistry, error) + // CommandInstallerRequirements, PlanCommandInstaller and CommandInstallerDefaultDirectory + // read a plugin's commandInstallers[]: which systemCommand launches name which commands, + // one installer expanded for the target the user chose, and the directory a toolDefault + // installation lands in from its probes' output (command_installers.go). + CommandInstallerRequirements(ctx context.Context, manifest json.RawMessage) (core.CommandRequirements, error) + PlanCommandInstaller(ctx context.Context, manifest json.RawMessage, installerID, target, installDirectory string) (core.CommandInstallPlan, error) + CommandInstallerDefaultDirectory(ctx context.Context, manifest json.RawMessage, installerID string, outputs []*string) (string, bool, error) ToolchainDiscoveryPlanOf(ctx context.Context, registry json.RawMessage, platform string) (core.ToolchainDiscoveryPlan, error) ToolchainCandidatesOf(ctx context.Context, request core.ToolchainCandidatesRequest) (core.ToolchainCandidates, error) ResolveToolchain(ctx context.Context, request core.ToolchainResolveRequest) (core.ToolchainResolution, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index db23c265a2..cf5154516c 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -553,9 +553,9 @@ func (a *App) finishBuildDetection(p *project, generation uint64, instances []bu p.build.selected = 0 } if err != nil && len(instances) == 0 { - p.build.failed = err.Error() + p.build.failed = a.launchFailureText(err) } else if err != nil { - p.build.status = err.Error() + p.build.status = a.launchFailureText(err) } if len(instances) == 0 { p.build.status = a.text.Build.NoBuildSystems @@ -774,8 +774,8 @@ func (a *App) finishBuildModel(p *project, id string, model core.BuildModel, err return } if err != nil { - p.build.instances[index].modelError = err.Error() - p.build.status = err.Error() + p.build.instances[index].modelError = a.launchFailureText(err) + p.build.status = p.build.instances[index].modelError a.settleTitleAction(p) return } diff --git a/desktop/internal/workbench/command_installers.go b/desktop/internal/workbench/command_installers.go new file mode 100644 index 0000000000..19fabac021 --- /dev/null +++ b/desktop/internal/workbench/command_installers.go @@ -0,0 +1,515 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "slices" + "sort" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" + "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +// commandProbeTimeout bounds one directory probe of a toolDefault installation. A probe only +// prints a directory, such as go env GOBIN. +const commandProbeTimeout = 10 * time.Second + +// maxCommandProbeOutput bounds what a directory probe may print. A longer output names no +// directory, so the probe counts as failed. +const maxCommandProbeOutput = 64 << 10 + +// maxCommandOutputLine bounds one line of an installation's output the install dialog shows; +// the rest of a longer line is dropped. +const maxCommandOutputLine = 4096 + +// settingsCommandInstalls is the settings window's settingswindow.CommandInstaller. It looks +// the commands of the plugins' systemCommand launches up the way those launches do, and runs +// the installer a plugin declares (commandInstallers[], API-23) once the user confirms one. +// Core expands every installer and names its directories; the host resolves the tool, runs +// it, checks that the commands landed and records where. +type settingsCommandInstalls struct{ app *App } + +var _ settingswindow.CommandInstaller = settingsCommandInstalls{} + +// manifest reads the manifest of the enabled plugin pluginID. +func (s settingsCommandInstalls) manifest(ctx context.Context, pluginID string) (json.RawMessage, error) { + a := s.app + if a.plugins == nil { + return nil, errors.New("the plugin host is not available") + } + entries, err := a.plugins.Manager.Installed() + if err != nil { + return nil, err + } + entries = slices.DeleteFunc(entries, func(entry pluginmanager.Entry) bool { return entry.Installed.ID != pluginID }) + plugins, err := a.plugins.ToolchainPlugins(ctx, entries) + for _, plugin := range plugins { + if plugin.PluginID == pluginID { + return plugin.Manifest, nil + } + } + if err != nil { + return nil, err + } + return nil, fmt.Errorf("plugin %s is not enabled", pluginID) +} + +// Missing asks Core for the plugin's systemCommand launches and looks each one's commands up +// as its launch does: the debug adapter's lookup for a debug adapter, the plugin runner's for +// everything else, both of which add the directories recorded for the plugin to PATH. +func (s settingsCommandInstalls) Missing(ctx context.Context, pluginID string) ([]settingswindow.MissingCommand, error) { + manifest, err := s.manifest(ctx, pluginID) + if err != nil { + return nil, err + } + requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest) + if err != nil { + return nil, err + } + installers := make(map[string]core.CommandInstaller, len(requirements.Installers)) + for _, installer := range requirements.Installers { + installers[installer.ID] = installer + } + var missing []settingswindow.MissingCommand + var tools map[string]string + for _, consumer := range requirements.Consumers { + commands := make([]string, 0, len(consumer.Commands)) + installerID := "" + for _, required := range consumer.Commands { + commands = append(commands, required.Command) + if installerID == "" && required.Installer != nil { + installerID = *required.Installer + } + } + if len(commands) == 0 || s.found(ctx, pluginID, consumer.Kind, commands) { + continue + } + if err := ctx.Err(); err != nil { + return nil, err + } + entry := settingswindow.MissingCommand{Kind: commandConsumerCapability(consumer.Kind), Commands: commands} + if consumer.ID != nil { + entry.ID = *consumer.ID + } + if installer, ok := installers[installerID]; ok { + if tools == nil { + tools = s.toolNames(ctx) + } + entry.Installer, entry.Tool = installer.ID, toolName(tools, installer.Tool) + } + missing = append(missing, entry) + } + return missing, nil +} + +// found reports whether a launch of kind finds one of commands. Only a launch that would fail +// for want of a command counts as missing; any other failure is not one an installer fixes. +func (s settingsCommandInstalls) found(ctx context.Context, pluginID, kind string, commands []string) bool { + var err error + if kind == "debugAdapter" { + lookup := s.app.installedCommands().Lookup(pluginID, func(name string) (string, error) { return debugLookupCommand(ctx, name) }) + _, err = pluginhost.ResolveCommand(commands, lookup) + } else { + _, err = s.app.plugins.Backend.ResolveCommand(pluginID, commands) + } + var missing *pluginhost.CommandMissingError + return !errors.As(err, &missing) +} + +// commandConsumerCapability is the capability card a launch of Core's consumer kind belongs +// to; empty for the backend, which has no card. +func commandConsumerCapability(kind string) string { + switch kind { + case "languageServer": + return settingswindow.CapabilityLanguageServer + case "buildProvider": + return settingswindow.CapabilityBuildSystem + case "vcsProvider": + return settingswindow.CapabilityVersionControl + case "debugAdapter": + return settingswindow.CapabilityDebugger + } + return "" +} + +// toolNames are the display names of the enabled plugins' tool definitions by ID; nil when +// the registry cannot be read, which shows the IDs. +func (s settingsCommandInstalls) toolNames(ctx context.Context) map[string]string { + manifests, _ := s.app.toolchainManifests(ctx) + if len(manifests) == 0 { + return nil + } + registry, err := s.app.kernel.ToolchainRegistryOf(ctx, manifests) + if err != nil { + return nil + } + names := make(map[string]string, len(registry.Definitions)) + for _, entry := range registry.Definitions { + if entry.Definition.DisplayName != "" { + names[entry.Definition.ID] = entry.Definition.DisplayName + } + } + return names +} + +func toolName(names map[string]string, id string) string { + if name := names[id]; name != "" { + return name + } + return id +} + +// Offer resolves the installer's tool and expands each of its targets, running a toolDefault +// target's directory probes to find where it would install. +func (s settingsCommandInstalls) Offer(ctx context.Context, pluginID, installerID string) (settingswindow.CommandInstallOffer, error) { + session, _, err := s.open(ctx, pluginID, installerID) + if err != nil { + return settingswindow.CommandInstallOffer{}, err + } + defer session.close() + offer := settingswindow.CommandInstallOffer{ + Installer: installerID, + Commands: session.installer.Commands, + Tool: toolName(s.toolNames(ctx), session.installer.Tool), + Executable: session.selection.Executable, + MayUseNetwork: session.installer.MayUseNetwork, + } + for _, target := range session.installer.Targets { + prepared, err := session.prepare(ctx, target) + if err != nil { + return settingswindow.CommandInstallOffer{}, err + } + if offer.Timeout == 0 { + offer.Timeout = prepared.timeout() + } + offer.Targets = append(offer.Targets, settingswindow.CommandInstallTarget{ + Target: target, + CommandLine: quoteArguments(append([]string{session.selection.Executable}, prepared.plan.Arguments...)), + Environment: environmentLines(prepared.plan.Environment), + Directory: prepared.directory, + }) + } + return offer, nil +} + +// environmentLines is an installation's environment as sorted NAME=value lines. +func environmentLines(environment map[string]string) []string { + lines := make([]string, 0, len(environment)) + for name, value := range environment { + lines = append(lines, name+"="+value) + } + sort.Strings(lines) + return lines +} + +// Install runs the installer for target and records where its commands landed, so the +// plugin's later launches find them. The attempt is recorded on the plugin's host channel; a +// cancelled one is not. +func (s settingsCommandInstalls) Install(ctx context.Context, pluginID, installerID, target string, output func(string)) (string, error) { + attempt := core.StartPluginAttempt(pluginID, core.OperationCommandInstallerInstall, core.OriginOf(ctx).Operation) + defer attempt.Abandon() + directory, stage, err := s.install(ctx, pluginID, installerID, target, output) + if s.app.plugins != nil { + s.app.plugins.EndAttempt(ctx, attempt, stage, err) + } + return directory, err +} + +func (s settingsCommandInstalls) install(ctx context.Context, pluginID, installerID, target string, output func(string)) (string, core.PluginStage, error) { + session, stage, err := s.open(ctx, pluginID, installerID) + if err != nil { + return "", stage, err + } + defer session.close() + if !slices.Contains(session.installer.Targets, target) { + return "", core.StagePlan, fmt.Errorf("installer %s has no target %s", installerID, target) + } + prepared, err := session.prepare(ctx, target) + if err != nil { + return "", core.StagePlan, err + } + if prepared.directory == "" { + return "", core.StagePlan, fmt.Errorf("no directory probe of installer %s named where it installs", installerID) + } + if prepared.installDirectory != "" { + if err := os.MkdirAll(prepared.installDirectory, 0o755); err != nil { + return "", core.StagePlan, err + } + } + timeout := prepared.timeout() + run, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + lines := &commandOutputLines{send: output} + process, err := buildprocess.Start(run, buildprocess.Spec{ + Kind: processledger.KindProcess, + Executable: session.selection.Executable, + Arguments: prepared.plan.Arguments, + WorkingDirectory: session.directory, + Environment: applyToolchainSelection(prepared.plan.Environment, session.selection), + }, lines.write) + if err != nil { + return "", core.StageLaunch, err + } + waitErr := process.Wait() + lines.flush() + if err := ctx.Err(); err != nil { + // The user cancelled, which is never recorded. + return "", core.StageExit, err + } + if run.Err() != nil { + return "", core.StageTimeout, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallTimedOutCode, Timeout: timeout} + } + if waitErr != nil { + code := -1 + var exit *exec.ExitError + if errors.As(waitErr, &exit) { + code = exit.ExitCode() + } + return "", core.StageExit, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallFailedCode, ExitCode: code} + } + var absent []string + for _, command := range prepared.plan.Commands { + if _, err := pluginhost.CommandInDirectory(prepared.directory, command); err != nil { + absent = append(absent, command) + } + } + if len(absent) > 0 { + return "", core.StageDecode, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallCommandsMissingCode, Commands: absent, Directory: prepared.directory} + } + // A record that cannot be written leaves the commands where later launches do not look, + // which is the same outcome for them as commands missing from the directory. + if err := s.app.plugins.Commands.Record(pluginID, pluginhost.CommandInstallation{Installer: installerID, Target: target, Directory: prepared.directory}); err != nil { + return "", core.StageDecode, err + } + return prepared.directory, "", nil +} + +// commandInstallSession is one installer with its tool resolved, for an offer or an +// installation. +type commandInstallSession struct { + app *App + pluginID string + manifest json.RawMessage + installer core.CommandInstaller + // directory is an empty directory of its own the tool runs in, so no project's files change + // what it installs; close removes it. + directory string + selection core.ToolchainSelection +} + +// open finds the installer in the plugin's manifest and resolves its tool. The tool resolves +// in the open project, so a version the project pins is the one that installs; without a +// project it resolves from the user's settings alone. stage is where a failure happened. +func (s settingsCommandInstalls) open(ctx context.Context, pluginID, installerID string) (*commandInstallSession, core.PluginStage, error) { + manifest, err := s.manifest(ctx, pluginID) + if err != nil { + return nil, core.StagePlan, err + } + requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest) + if err != nil { + return nil, core.StagePlan, err + } + index := slices.IndexFunc(requirements.Installers, func(installer core.CommandInstaller) bool { return installer.ID == installerID }) + if index < 0 { + return nil, core.StagePlan, fmt.Errorf("plugin %s declares no installer %s", pluginID, installerID) + } + directory, err := os.MkdirTemp("", "lithe-command-install-") + if err != nil { + return nil, core.StagePlan, err + } + session := &commandInstallSession{app: s.app, pluginID: pluginID, manifest: manifest, installer: requirements.Installers[index], directory: directory} + root := directory + if current := s.app.toolchainRoot.Load(); current != nil { + root = *current + } + minimumVersion := "" + if session.installer.MinimumVersion != nil { + minimumVersion = *session.installer.MinimumVersion + } + session.selection, err = s.app.resolveToolchainSelection(ctx, root, ".", session.installer.Tool, minimumVersion) + if err != nil { + session.close() + return nil, core.StageResolve, err + } + return session, "", nil +} + +func (s *commandInstallSession) close() { + if s != nil && s.directory != "" { + os.RemoveAll(s.directory) + } +} + +// preparedCommandInstall is one target of an installer, expanded. +type preparedCommandInstall struct { + plan core.CommandInstallPlan + // installDirectory is the directory a managed installation writes into; empty for + // toolDefault. + installDirectory string + // directory is where the commands land; empty when no directory probe named one. + directory string +} + +func (p preparedCommandInstall) timeout() time.Duration { + return time.Duration(p.plan.TimeoutMilliseconds) * time.Millisecond +} + +// prepare has Core expand target: a managed one into the plugin's install directory, a +// toolDefault one with the directory its probes name. +func (s *commandInstallSession) prepare(ctx context.Context, target string) (preparedCommandInstall, error) { + kernel := s.app.kernel + switch target { + case core.CommandInstallManaged: + installDirectory, err := s.app.plugins.Commands.InstallDirectory(s.pluginID, s.installer.ID) + if err != nil { + return preparedCommandInstall{}, err + } + plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, installDirectory) + if err != nil { + return preparedCommandInstall{}, err + } + return preparedCommandInstall{plan: plan, installDirectory: installDirectory, directory: *plan.CommandDirectory}, nil + case core.CommandInstallToolDefault: + plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, "") + if err != nil { + return preparedCommandInstall{}, err + } + outputs := make([]*string, len(plan.DirectoryProbes)) + for i, probe := range plan.DirectoryProbes { + if output, ok := s.probe(ctx, probe.Arguments); ok { + outputs[i] = &output + } + } + directory, _, err := kernel.CommandInstallerDefaultDirectory(ctx, s.manifest, s.installer.ID, outputs) + if err != nil { + return preparedCommandInstall{}, err + } + return preparedCommandInstall{plan: plan, directory: directory}, nil + } + return preparedCommandInstall{}, fmt.Errorf("unknown command install target %q", target) +} + +// probe runs the tool with one probe's arguments and returns its standard output. ok is +// false when the probe could not run, failed, ran too long or printed too much. +func (s *commandInstallSession) probe(ctx context.Context, arguments []string) (string, bool) { + ctx, cancel := context.WithTimeout(ctx, commandProbeTimeout) + defer cancel() + var output strings.Builder + overflow := false + process, err := buildprocess.Start(ctx, buildprocess.Spec{ + Executable: s.selection.Executable, + Arguments: arguments, + WorkingDirectory: s.directory, + Environment: applyToolchainSelection(nil, s.selection), + }, func(stream buildprocess.Stream, text string) { + // Only the stdout reader writes here, and Wait returns after it ends. + if stream != buildprocess.Stdout || overflow { + return + } + if output.Len()+len(text) > maxCommandProbeOutput { + overflow = true + return + } + output.WriteString(text) + }) + if err != nil { + return "", false + } + if process.Wait() != nil || ctx.Err() != nil || overflow { + return "", false + } + return output.String(), true +} + +// commandMissingMessage tells the user, in language, which commands a launch found none of and +// where to install them; ok is false for any other error. +func commandMissingMessage(language i18n.Language, err error) (string, bool) { + var missing *pluginhost.CommandMissingError + if !errors.As(err, &missing) { + return "", false + } + return i18n.SharedFormat(language, "desktop.plugins.commandMissingHelp", map[string]string{"commands": strings.Join(missing.Commands, " | ")}), true +} + +// launchFailureText is the message of a plugin launch that failed: the missing commands when it +// found none, the error itself otherwise. +func (a *App) launchFailureText(err error) string { + if message, ok := commandMissingMessage(a.language(), err); ok { + return message + } + return err.Error() +} + +// commandOutputLines turns an installation's output chunks into lines for the install dialog. +// Each stream keeps its own unfinished line, so the two never mix inside one line. +type commandOutputLines struct { + send func(string) + mu sync.Mutex + pending map[buildprocess.Stream]*strings.Builder +} + +func (o *commandOutputLines) write(stream buildprocess.Stream, text string) { + if o.send == nil { + return + } + o.mu.Lock() + defer o.mu.Unlock() + if o.pending == nil { + o.pending = make(map[buildprocess.Stream]*strings.Builder, 2) + } + line := o.pending[stream] + if line == nil { + line = &strings.Builder{} + o.pending[stream] = line + } + for text != "" { + end := strings.IndexByte(text, '\n') + part := text + if end >= 0 { + part = text[:end] + } + if room := maxCommandOutputLine - line.Len(); len(part) > room { + part = part[:max(room, 0)] + } + line.WriteString(part) + if end < 0 { + return + } + o.send(commandOutputText(line.String())) + line.Reset() + text = text[end+1:] + } +} + +// flush hands on the unfinished line of each stream once the tool has ended. +func (o *commandOutputLines) flush() { + if o.send == nil { + return + } + o.mu.Lock() + defer o.mu.Unlock() + for _, stream := range []buildprocess.Stream{buildprocess.Stdout, buildprocess.Stderr} { + if line := o.pending[stream]; line != nil && line.Len() > 0 { + o.send(commandOutputText(line.String())) + line.Reset() + } + } +} + +// commandOutputText is one line as the dialog shows it: without the carriage return of a CRLF +// line ending, and with the bytes of a character a bounded line cut through dropped. +func commandOutputText(line string) string { + return strings.ToValidUTF8(strings.TrimSuffix(line, "\r"), "") +} diff --git a/desktop/internal/workbench/command_installers_test.go b/desktop/internal/workbench/command_installers_test.go new file mode 100644 index 0000000000..21ac3be3cc --- /dev/null +++ b/desktop/internal/workbench/command_installers_test.go @@ -0,0 +1,448 @@ +package workbench + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +const commandInstallerPluginID = "dev.lithe.test.command-installers" + +// commandInstallerManifest declares a language server and a debug adapter that run commands +// found on PATH, and an installer for each. Both installers run the fixture tool builder, +// which the tests resolve to the copied test binary running TestCommandInstallerTool. +const commandInstallerManifest = `{ + "schemaVersion": 0, + "id": "dev.lithe.test.command-installers", + "displayName": "Command Installer Fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"commandInstallers": 0, "debugAdapters": 0, "languageServers": 0, "languages": 0}, + "requiresTools": ["builder"], + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": ["commands.install", "debug.launch", "languageServer.launch"], + "activationEvents": ["onDebug:fixture", "onLanguage:fixture"], + "languages": [{"id": "fixture", "displayName": "Fixture", "fileExtensions": ["fixture"]}], + "languageServers": [{ + "languageID": "fixture", + "launch": {"kind": "systemCommand", "commands": ["lithe-fixture-ls"]}, + "arguments": ["serve"] + }], + "debugAdapters": [{ + "id": "fixture", + "displayName": "Fixture DAP", + "adapterID": "fixture-dap", + "requests": ["launch"], + "launch": { + "process": {"launch": {"kind": "systemCommand", "commands": ["lithe-fixture-dap"]}, "arguments": ["--stdio"]}, + "transport": "stdio" + } + }], + "commandInstallers": [ + { + "id": "fixture-ls", + "commands": ["lithe-fixture-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "arguments": ["-test.run=^TestCommandInstallerTool$", "install"], + "mayUseNetwork": true, + "timeoutSeconds": 60, + "targets": { + "managed": {"environment": {"FIXTURE_BIN": "${installDirectory}"}}, + "toolDefault": {"directory": [ + {"arguments": ["-test.run=^TestCommandInstallerTool$", "env", "FIXTURE_BIN"]}, + {"arguments": ["-test.run=^TestCommandInstallerTool$", "env", "FIXTURE_HOME"], "pathList": true, "append": "bin"} + ]} + } + }, + { + "id": "fixture-dap", + "commands": ["lithe-fixture-dap"], + "tool": "builder", + "arguments": ["-test.run=^TestCommandInstallerTool$", "install"], + "mayUseNetwork": false, + "timeoutSeconds": 1, + "targets": { + "managed": { + "arguments": ["-test.run=^TestCommandInstallerTool$", "install", "--prefix", "${installDirectory}"], + "commandDirectory": "bin" + } + } + } + ] +}` + +// The fixture tool's modes, read from LITHE_FIXTURE_COMMAND_TOOL. +const ( + // fixtureToolInstalls prints progress and writes the command where it installs. + fixtureToolInstalls = "install" + // fixtureToolFails prints an error and exits with code 3. + fixtureToolFails = "fail" + // fixtureToolInstallsNothing exits successfully without writing the command. + fixtureToolInstallsNothing = "nothing" + // fixtureToolHangs prints a line and then waits to be stopped. + fixtureToolHangs = "hang" +) + +// TestCommandInstallerTool is the fixture tool builder when the test binary runs as one. Like +// a real tool it installs into FIXTURE_BIN when told, and otherwise into the bin directory of +// the first FIXTURE_HOME entry; "env NAME" prints a variable as a directory probe reads it. +func TestCommandInstallerTool(t *testing.T) { + mode := os.Getenv("LITHE_FIXTURE_COMMAND_TOOL") + if mode == "" { + t.Skip("not running as the fixture command tool") + } + arguments := flagArguments() + if len(arguments) == 2 && arguments[0] == "env" { + fmt.Println(os.Getenv(arguments[1])) + os.Exit(0) + } + if len(arguments) == 0 || arguments[0] != "install" { + os.Exit(2) + } + directory := os.Getenv("FIXTURE_BIN") + command := "lithe-fixture-ls" + if len(arguments) == 3 && arguments[1] == "--prefix" { + directory, command = filepath.Join(arguments[2], "bin"), "lithe-fixture-dap" + } else if directory == "" { + directory = filepath.Join(filepath.SplitList(os.Getenv("FIXTURE_HOME"))[0], "bin") + } + switch mode { + case fixtureToolFails: + fmt.Fprintln(os.Stderr, "fixture: no such module") + os.Exit(3) + case fixtureToolInstallsNothing: + os.Exit(0) + case fixtureToolHangs: + fmt.Println("fixture: downloading") + // A stand-in for a download that never finishes: the host stops the process on its + // timeout or a cancel. The bound only keeps an orphan from outliving the test run. + time.Sleep(time.Minute) + os.Exit(0) + } + fmt.Println("fixture: downloading") + fmt.Fprint(os.Stderr, "fixture: installed without a final newline") + if err := os.MkdirAll(directory, 0o755); err != nil { + os.Exit(4) + } + if runtime.GOOS == "windows" { + command += ".exe" + } + if err := os.WriteFile(filepath.Join(directory, command), []byte("fixture command"), 0o755); err != nil { + os.Exit(5) + } + os.Exit(0) +} + +// flagArguments are the arguments after the test binary's own flags. +func flagArguments() []string { + for index, argument := range os.Args[1:] { + if !strings.HasPrefix(argument, "-test.") { + return os.Args[1+index:] + } + } + return nil +} + +// commandInstallerHarness installs the fixture plugin and resolves its tool to the copied test +// binary in mode, with FIXTURE_HOME naming two directories. It returns the harness, the tool's +// executable and FIXTURE_HOME's first directory. +func commandInstallerHarness(t *testing.T, mode string) (*harness, string, string) { + t.Helper() + h := debugPluginHarness(t, commandInstallerPluginID, commandInstallerManifest, false) + name := "builder" + if runtime.GOOS == "windows" { + name += ".exe" + } + executable := filepath.Join(t.TempDir(), name) + copyTestBinary(t, executable) + home := filepath.Join(t.TempDir(), "home") + homes := home + string(filepath.ListSeparator) + filepath.Join(t.TempDir(), "other") + h.app.toolchainResolve = func(_ context.Context, root, directory, tool, minimum string) (core.ToolchainSelection, error) { + if !filepath.IsAbs(root) || directory != "." || tool != "builder" { + t.Errorf("tool resolved in %q %q as %q", root, directory, tool) + } + if minimum != "" && minimum != "1.2" { + t.Errorf("minimum version = %q", minimum) + } + return core.ToolchainSelection{ + Executable: executable, + Environment: map[string]string{"LITHE_FIXTURE_COMMAND_TOOL": mode, "FIXTURE_HOME": homes}, + }, nil + } + return h, executable, home +} + +func commandInstallContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + return ctx +} + +func TestCommandInstallsReportEveryLaunchMissingItsCommand(t *testing.T) { + h, _, _ := commandInstallerHarness(t, fixtureToolInstalls) + installs := settingsCommandInstalls{app: h.app} + missing, err := installs.Missing(commandInstallContext(t), commandInstallerPluginID) + if err != nil { + t.Fatal(err) + } + expected := []settingswindow.MissingCommand{ + {Kind: settingswindow.CapabilityLanguageServer, ID: "fixture", Commands: []string{"lithe-fixture-ls"}, Installer: "fixture-ls", Tool: "builder"}, + {Kind: settingswindow.CapabilityDebugger, ID: "fixture", Commands: []string{"lithe-fixture-dap"}, Installer: "fixture-dap", Tool: "builder"}, + } + slices.SortFunc(missing, func(a, b settingswindow.MissingCommand) int { return strings.Compare(b.Kind, a.Kind) }) + slices.SortFunc(expected, func(a, b settingswindow.MissingCommand) int { return strings.Compare(b.Kind, a.Kind) }) + if !reflect.DeepEqual(missing, expected) { + t.Fatalf("missing = %+v\nwant %+v", missing, expected) + } +} + +func TestCommandInstallOfferShowsEachTargetExpanded(t *testing.T) { + h, executable, home := commandInstallerHarness(t, fixtureToolInstalls) + installs := settingsCommandInstalls{app: h.app} + ctx := commandInstallContext(t) + managed, err := h.app.plugins.Commands.InstallDirectory(commandInstallerPluginID, "fixture-ls") + if err != nil { + t.Fatal(err) + } + offer, err := installs.Offer(ctx, commandInstallerPluginID, "fixture-ls") + if err != nil { + t.Fatal(err) + } + command := quoteArguments([]string{executable, "-test.run=^TestCommandInstallerTool$", "install"}) + expected := settingswindow.CommandInstallOffer{ + Installer: "fixture-ls", + Commands: []string{"lithe-fixture-ls"}, + Tool: "builder", + Executable: executable, + MayUseNetwork: true, + Timeout: time.Minute, + Targets: []settingswindow.CommandInstallTarget{ + {Target: core.CommandInstallManaged, CommandLine: command, Environment: []string{"FIXTURE_BIN=" + managed}, Directory: managed}, + // FIXTURE_BIN is unset, so the second probe names the default directory. + {Target: core.CommandInstallToolDefault, CommandLine: command, Environment: []string{}, Directory: filepath.Join(home, "bin")}, + }, + } + if !reflect.DeepEqual(offer, expected) { + t.Fatalf("offer = %+v\nwant %+v", offer, expected) + } + + offer, err = installs.Offer(ctx, commandInstallerPluginID, "fixture-dap") + if err != nil { + t.Fatal(err) + } + prefix, err := h.app.plugins.Commands.InstallDirectory(commandInstallerPluginID, "fixture-dap") + if err != nil { + t.Fatal(err) + } + if len(offer.Targets) != 1 || offer.MayUseNetwork || offer.Timeout != time.Second || + offer.Targets[0].Directory != filepath.Join(prefix, "bin") || + offer.Targets[0].CommandLine != quoteArguments([]string{executable, "-test.run=^TestCommandInstallerTool$", "install", "--prefix", prefix}) { + t.Fatalf("offer with a command directory = %+v", offer) + } + if _, err := os.Stat(prefix); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("an offer created the install directory: %v", err) + } +} + +// commandOutput collects an installation's output lines. +type commandOutput struct { + mu sync.Mutex + lines []string +} + +func (o *commandOutput) add(line string) { + o.mu.Lock() + defer o.mu.Unlock() + o.lines = append(o.lines, line) +} + +func (o *commandOutput) all() []string { + o.mu.Lock() + defer o.mu.Unlock() + return append([]string(nil), o.lines...) +} + +func TestCommandInstallManagedRecordsWhereLaterLaunchesFindTheCommand(t *testing.T) { + h, _, _ := commandInstallerHarness(t, fixtureToolInstalls) + installs := settingsCommandInstalls{app: h.app} + ctx := commandInstallContext(t) + managed, err := h.app.plugins.Commands.InstallDirectory(commandInstallerPluginID, "fixture-ls") + if err != nil { + t.Fatal(err) + } + var output commandOutput + directory, err := installs.Install(ctx, commandInstallerPluginID, "fixture-ls", core.CommandInstallManaged, output.add) + if err != nil { + t.Fatal(err) + } + if directory != managed { + t.Fatalf("installed into %q, want %q", directory, managed) + } + lines := output.all() + if !slices.Contains(lines, "fixture: downloading") || !slices.Contains(lines, "fixture: installed without a final newline") { + t.Fatalf("output = %q", lines) + } + installations := h.app.plugins.Commands.Installations(commandInstallerPluginID) + if !reflect.DeepEqual(installations, []pluginhost.CommandInstallation{{Installer: "fixture-ls", Target: core.CommandInstallManaged, Directory: managed}}) { + t.Fatalf("recorded %+v", installations) + } + path, err := h.app.plugins.Backend.ResolveCommand(commandInstallerPluginID, []string{"lithe-fixture-ls"}) + if err != nil || filepath.Dir(path) != managed { + t.Fatalf("language server command = %q, %v", path, err) + } + missing, err := installs.Missing(ctx, commandInstallerPluginID) + if err != nil { + t.Fatal(err) + } + if len(missing) != 1 || missing[0].Kind != settingswindow.CapabilityDebugger { + t.Fatalf("still missing after the install: %+v", missing) + } + entries, err := os.ReadDir(os.TempDir()) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), "lithe-command-install-") { + t.Errorf("the tool's working directory %s was left behind", entry.Name()) + } + } +} + +func TestCommandInstallToolDefaultRecordsTheProbedDirectory(t *testing.T) { + h, _, home := commandInstallerHarness(t, fixtureToolInstalls) + installs := settingsCommandInstalls{app: h.app} + directory, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, "fixture-ls", core.CommandInstallToolDefault, func(string) {}) + if err != nil { + t.Fatal(err) + } + if directory != filepath.Join(home, "bin") { + t.Fatalf("installed into %q, want the probed default directory", directory) + } + installations := h.app.plugins.Commands.Installations(commandInstallerPluginID) + if !reflect.DeepEqual(installations, []pluginhost.CommandInstallation{{Installer: "fixture-ls", Target: core.CommandInstallToolDefault, Directory: directory}}) { + t.Fatalf("recorded %+v", installations) + } +} + +func TestCommandInstallReportsWhyTheCommandsDidNotLand(t *testing.T) { + for _, test := range []struct { + name, mode, installer string + check func(t *testing.T, failure *pluginhost.CommandInstallError, directory string) + }{ + {"nonzero exit", fixtureToolFails, "fixture-ls", func(t *testing.T, failure *pluginhost.CommandInstallError, _ string) { + if failure.Code != pluginhost.CommandInstallFailedCode || failure.ExitCode != 3 { + t.Fatalf("failure = %+v", failure) + } + }}, + {"command not written", fixtureToolInstallsNothing, "fixture-ls", func(t *testing.T, failure *pluginhost.CommandInstallError, directory string) { + if failure.Code != pluginhost.CommandInstallCommandsMissingCode || failure.Directory != directory || + !reflect.DeepEqual(failure.Commands, []string{"lithe-fixture-ls"}) { + t.Fatalf("failure = %+v, want lithe-fixture-ls missing from %s", failure, directory) + } + }}, + {"past the timeout", fixtureToolHangs, "fixture-dap", func(t *testing.T, failure *pluginhost.CommandInstallError, _ string) { + if failure.Code != pluginhost.CommandInstallTimedOutCode || failure.Timeout != time.Second { + t.Fatalf("failure = %+v", failure) + } + }}, + } { + t.Run(test.name, func(t *testing.T) { + h, _, _ := commandInstallerHarness(t, test.mode) + installs := settingsCommandInstalls{app: h.app} + directory, err := h.app.plugins.Commands.InstallDirectory(commandInstallerPluginID, test.installer) + if err != nil { + t.Fatal(err) + } + installed, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, test.installer, core.CommandInstallManaged, func(string) {}) + var failure *pluginhost.CommandInstallError + if !errors.As(err, &failure) { + t.Fatalf("Install = %q, %v; want a CommandInstallError", installed, err) + } + test.check(t, failure, directory) + if installations := h.app.plugins.Commands.Installations(commandInstallerPluginID); len(installations) != 0 { + t.Fatalf("a failed installation was recorded: %+v", installations) + } + }) + } +} + +func TestCommandInstallStopsTheToolWhenCancelled(t *testing.T) { + h, _, _ := commandInstallerHarness(t, fixtureToolHangs) + installs := settingsCommandInstalls{app: h.app} + ctx, cancel := context.WithCancel(commandInstallContext(t)) + defer cancel() + // The tool prints its first line once it runs; cancelling then stops it mid-installation. + _, err := installs.Install(ctx, commandInstallerPluginID, "fixture-ls", core.CommandInstallManaged, func(line string) { + if line == "fixture: downloading" { + cancel() + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("Install = %v, want the cancel", err) + } + if installations := h.app.plugins.Commands.Installations(commandInstallerPluginID); len(installations) != 0 { + t.Fatalf("a cancelled installation was recorded: %+v", installations) + } +} + +func TestCommandInstallRefusesATargetTheInstallerLacks(t *testing.T) { + h, _, _ := commandInstallerHarness(t, fixtureToolInstalls) + installs := settingsCommandInstalls{app: h.app} + if _, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, "fixture-dap", core.CommandInstallToolDefault, func(string) {}); err == nil { + t.Fatal("installed into a target the installer does not declare") + } + if _, err := installs.Offer(commandInstallContext(t), commandInstallerPluginID, "absent"); err == nil { + t.Fatal("offered an installer the plugin does not declare") + } +} + +func TestCommandOutputLinesSplitEachStream(t *testing.T) { + var output commandOutput + lines := &commandOutputLines{send: output.add} + lines.write(buildprocess.Stdout, "one\ntw") + lines.write(buildprocess.Stderr, "warn") + lines.write(buildprocess.Stdout, "o\r\nthree") + lines.write(buildprocess.Stderr, "ing\n"+strings.Repeat("x", maxCommandOutputLine+10)+"\n") + lines.flush() + got := output.all() + expected := []string{"one", "two", "warning", strings.Repeat("x", maxCommandOutputLine), "three"} + if !reflect.DeepEqual(got, expected) { + t.Fatalf("lines = %q\nwant %q", got, expected) + } +} + +func TestCommandMissingFailuresAreLocalized(t *testing.T) { + err := fmt.Errorf("start: %w", &pluginhost.CommandMissingError{Commands: []string{"lithe-fixture-ls", "lithe-fixture-ls2"}}) + message, ok := commandMissingMessage(i18n.English, err) + if !ok || !strings.Contains(message, "lithe-fixture-ls | lithe-fixture-ls2") || strings.Contains(message, "plugin.command.missing") { + t.Fatalf("message = %q, %v", message, ok) + } + h := newHarness(t, &testKernel{Client: core.NewClient()}) + launch := h.app.launchFailureText(err) + if launch != i18n.SharedFormat(h.app.language(), "desktop.plugins.commandMissingHelp", map[string]string{"commands": "lithe-fixture-ls | lithe-fixture-ls2"}) { + t.Fatalf("launch failure = %q", launch) + } + if text := h.app.vcsFailureText(err); text != launch { + t.Fatalf("version control failure = %q, want %q", text, launch) + } + if _, ok := commandMissingMessage(i18n.English, errors.New("other")); ok { + t.Fatal("an unrelated failure counted as a missing command") + } +} diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index 79cf520f65..7d00612dfb 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -984,7 +984,7 @@ func (a *App) finishDebugError(p *project, session *debugSession, err error) { a.endDebugSession(p, session) return } - message := err.Error() + message := a.launchFailureText(err) var settingsError *debugSettingsError if errors.As(err, &settingsError) { message = i18n.Shared(a.language(), "desktop.debug.settingsUnreadable") diff --git a/desktop/internal/workbench/debug_child.go b/desktop/internal/workbench/debug_child.go index 27cd76c989..351b29cfa0 100644 --- a/desktop/internal/workbench/debug_child.go +++ b/desktop/internal/workbench/debug_child.go @@ -68,7 +68,7 @@ func (a *App) failChildDebug(p *project, child *debugSession, err error) { if errors.Is(err, context.Canceled) { return } - message := err.Error() + message := a.launchFailureText(err) var remote *debugRemoteError if errors.As(err, &remote) { message = a.text.Debug.Child.NeedsConfirmation diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index 65002b85dd..a67843511d 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -118,7 +118,8 @@ func (a *App) resolveAdapterProcess(ctx context.Context, adapter debugAdapter, p } executable = resolved.Executable if plan.Launch.Kind == pluginhost.LaunchSystemCommand { - executable, err = pluginhost.ResolveCommand(plan.Launch.Commands, func(name string) (string, error) { return debugLookupCommand(ctx, name) }) + lookup := a.installedCommands().Lookup(adapter.PluginID, func(name string) (string, error) { return debugLookupCommand(ctx, name) }) + executable, err = pluginhost.ResolveCommand(plan.Launch.Commands, lookup) if err != nil { return "", nil, nil, err } @@ -255,3 +256,12 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir } return prepared, ctx.Err() } + +// installedCommands is the record of the commands the host installed for plugins; +// nil, which looks up PATH only, before the plugin service opens. +func (a *App) installedCommands() *pluginhost.CommandStore { + if a.plugins == nil { + return nil + } + return a.plugins.Commands +} diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 3c8cea3e05..6616e4a896 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -135,6 +135,7 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { UninstallPlugin: func(id string) { a.post(func(a *App) { a.uninstallPlugin(id) }) }, + CommandInstalls: settingsCommandInstalls{app: a}, Language: func() i18n.Language { if a.shared.text.Load() == i18n.For(i18n.Chinese) { return i18n.Chinese diff --git a/desktop/internal/workbench/vcs.go b/desktop/internal/workbench/vcs.go index a5494d9af1..654dfd7b7b 100644 --- a/desktop/internal/workbench/vcs.go +++ b/desktop/internal/workbench/vcs.go @@ -661,7 +661,7 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call _, capabilities, _ := client.VcsProvider() var tool *string if len(call.tool) > 0 { - executable, err := a.plugins.Backend.ResolveCommand(call.tool) + executable, err := a.plugins.Backend.ResolveCommand(call.window.PluginID, call.tool) if err != nil { return nil, capabilities, errors.Join(errVcsToolMissing, err) } @@ -721,6 +721,9 @@ func (a *App) vcsFailureText(err error) string { if errors.As(err, &rejection) && rejection.Code == "plugin.vcs.invalidOutput" { return i18n.SharedFormat(language, "native.litheCouldNotEvaluateTheVersionControlDataArg1", map[string]string{"arg1": rejection.Message}) } + if message, ok := commandMissingMessage(language, err); ok { + return message + } switch { case errors.Is(err, errVcsToolMissing): return i18n.Shared(language, "native.theVersionControlClientCouldNotBeRunCheckThatItIsInstalled") diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 3b0fcf2ab0..d93bcebda6 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -45,7 +45,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-20 | 部分完成 | global/backend/workspace 可写目录与网页状态;语言服务器的按工作区状态目录按 `state.retention` 后台回收(Core 决定,仅 macOS,无用户可见重置入口);统一 KV/配额/session API 未做 | | API-21 | 既有能力 | 协议 2 credentials/get/set/delete;权限与插件隔离不变 | | API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);新增 `outputLinkMatchers:1`,插件声明的匹配器让 Run 与测试控制台出现链接(macOS);独立 output channel、通用 log/progress API 未做 | -| API-23 | 部分完成 | 已有进程声明与运行时解析;新增 `serverProcess:4` 的工具 ID 引用(清单 `requiresTools`)与后端发起的 `run/start`、`run/stop`、`run/didExit`(macOS,工具 ID 未找到或不可用时返回 -32025);通用 toolchains/process 服务未开放 | +| API-23 | 部分完成 | 已有进程声明与运行时解析;新增 `serverProcess:4` 的工具 ID 引用(清单 `requiresTools`)与后端发起的 `run/start`、`run/stop`、`run/didExit`(macOS,工具 ID 未找到或不可用时返回 -32025);新增 `commandInstallers:0`:插件声明用哪个已注入工具安装 `systemCommand` 启动缺的命令,Core 校验并展开(`plugins.commandInstallers.requirements/plan/defaultDirectory`),宿主在能力卡片显示缺失与安装按钮,用户选择 Lithe 管理的目录或工具默认位置后运行并记录(权限 `commands.install`,Viva 桌面端);通用 toolchains/process 服务未开放 | | API-24 | 部分完成 | 已公开插件自有原生终端 create/show/close/reopen/dispose/onExit(macOS、本机);不开放 sendText/输出读取,Windows 待接入 | | API-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增 `languageServers:3` 与 `serverProcess:3`:后端经 `languageServer/request\|notify\|setStatus` 使用自己的服务器、后端启动(`launch.kind:"backend"`),会话策略由 Core 执行(仅 macOS,远程后端启动未支持,见 Agent Note 2026-11-04-plugin-owned-language-server-sessions);新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;符号、格式化、重命名、Code Action、签名帮助、内联提示和运行期传入 JSON 动态注册高亮未做,详见下方范围说明;Java 拆分计划(C-EDIT):Spring、MyBatis 只补上游缺失的 Provider | | API-26 | 未做 | 公共诊断 collection/events API 未开放;既有 LSP 诊断不等于该 API;`registerProviders` 不接受 `diagnostics` 类型(返回 unsupportedOption),推送式诊断集合另行设计;Java 拆分计划(C-EDIT):推送式 collection,带文档版本 | diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index f3062afb3d..6fff88a7ec 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11071,7 +11071,29 @@ "desktop.debug.consoleEmpty": "The debug session's output appears here.", "desktop.debug.evaluatePlaceholder": "Evaluate expression ({evaluate}) or add a watch ({watch})", "desktop.debug.unmuteBreakpoints": "Unmute breakpoints", - "desktop.plugins.installedOnThisComputer": "Installed on this computer: {arg1}", + "desktop.plugins.installedOnThisComputer": "Uses a program on this computer: {arg1}", + "desktop.plugins.commandMissing": "{commands} not found", + "desktop.plugins.commandMissingManual": "This plugin offers no way to install it. Install it yourself and make sure it is on PATH.", + "desktop.plugins.commandMissingBanner": "{commands} not found; some of the plugin's features will not work.", + "desktop.plugins.commandMissingHelp": "{commands} not found. Install it in Settings > Plugins, or add it to PATH.", + "desktop.plugins.commandInstallTitle": "Install {commands}", + "desktop.plugins.commandInstallPrompt": "{commands} will be installed with {tool}.", + "desktop.plugins.commandInstallNetwork": "The installation may download from the network.", + "desktop.plugins.commandInstallLocation": "Install location", + "desktop.plugins.commandInstallManaged": "A directory Lithe manages", + "desktop.plugins.commandInstallManagedHelp": "Used by Lithe only and removed with the plugin.", + "desktop.plugins.commandInstallToolDefault": "{tool}'s default location", + "desktop.plugins.commandInstallToolDefaultHelp": "Also available to the terminal and other programs, and kept when the plugin is removed.", + "desktop.plugins.commandInstallNoDirectory": "Could not find where {tool} installs by default.", + "desktop.plugins.commandInstallCommand": "Command to run", + "desktop.plugins.commandInstallOutput": "Output", + "desktop.plugins.commandInstalled": "Installed in {directory}.", + "desktop.plugins.commandInstallFailed": "The installation failed with exit code {code}. See the output below.", + "desktop.plugins.commandInstallStopped": "The installation ended unexpectedly. See the output below.", + "desktop.plugins.commandInstallTimedOut": "The installation did not finish within {seconds} seconds and was stopped.", + "desktop.plugins.commandInstallCommandsMissing": "The installation finished, but {commands} was not found in {directory}.", + "desktop.plugins.commandInstallToolMissing": "{tool} not found. Install it first, or set where it is in Settings > Build, Execution, Deployment > Toolchains.", + "desktop.plugins.commandInstallError": "Could not install: {reason}", "desktop.title.configurationNotStartable": "{name} cannot be started: no build plugin runs it.", "desktop.title.currentFileNotRunnable": "The current file cannot run on its own. Choose a project run configuration from the run configuration menu.", "desktop.title.noRunConfigurations": "No run configurations", @@ -11210,6 +11232,7 @@ "desktop.marketplace.permissionBuild": "Run build tools for your projects", "desktop.marketplace.permissionGenerate": "Create project files in the location you choose", "desktop.marketplace.permissionBackend": "Start the plugin’s background service", + "desktop.marketplace.permissionCommandsInstall": "Install the command-line tools the plugin needs (asks you before each installation)", "desktop.marketplace.permissionDebug": "Start a debugger for your programs", "desktop.marketplace.installComplete": "Installation complete", "desktop.marketplace.installCompleteHelp": "The plugin is installed. You can check its enabled state in Installed plugins.", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index b6ed61e0ad..202277ec8b 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11071,7 +11071,29 @@ "desktop.debug.consoleEmpty": "调试会话的输出会显示在这里。", "desktop.debug.evaluatePlaceholder": "对表达式求值({evaluate})或添加监视({watch})", "desktop.debug.unmuteBreakpoints": "恢复断点", - "desktop.plugins.installedOnThisComputer": "本机已安装:{arg1}", + "desktop.plugins.installedOnThisComputer": "使用本机程序:{arg1}", + "desktop.plugins.commandMissing": "未找到 {commands}", + "desktop.plugins.commandMissingManual": "这个插件没有提供安装方式。请自行安装,并确保它在 PATH 中。", + "desktop.plugins.commandMissingBanner": "未找到 {commands},插件的部分功能无法使用。", + "desktop.plugins.commandMissingHelp": "未找到 {commands}。请在 设置 > 插件 中安装,或把它加入 PATH。", + "desktop.plugins.commandInstallTitle": "安装 {commands}", + "desktop.plugins.commandInstallPrompt": "将用 {tool} 安装 {commands}。", + "desktop.plugins.commandInstallNetwork": "安装时可能会从网络下载。", + "desktop.plugins.commandInstallLocation": "安装位置", + "desktop.plugins.commandInstallManaged": "Lithe 管理的目录", + "desktop.plugins.commandInstallManagedHelp": "只供 Lithe 使用,卸载插件时一并删除。", + "desktop.plugins.commandInstallToolDefault": "{tool} 的默认位置", + "desktop.plugins.commandInstallToolDefaultHelp": "终端和其他程序也能使用,卸载插件时保留。", + "desktop.plugins.commandInstallNoDirectory": "无法确定 {tool} 的默认安装位置。", + "desktop.plugins.commandInstallCommand": "将要运行的命令", + "desktop.plugins.commandInstallOutput": "输出", + "desktop.plugins.commandInstalled": "已安装到 {directory}。", + "desktop.plugins.commandInstallFailed": "安装失败,退出码 {code}。请查看下面的输出。", + "desktop.plugins.commandInstallStopped": "安装程序意外结束。请查看下面的输出。", + "desktop.plugins.commandInstallTimedOut": "安装超过 {seconds} 秒仍未完成,已停止。", + "desktop.plugins.commandInstallCommandsMissing": "安装已完成,但在 {directory} 中没有找到 {commands}。", + "desktop.plugins.commandInstallToolMissing": "未找到 {tool}。请先安装它,或在 设置 > 构建、执行、部署 > 工具链 中指定它的位置。", + "desktop.plugins.commandInstallError": "无法安装:{reason}", "desktop.title.configurationNotStartable": "无法启动 {name}:没有构建插件负责运行它。", "desktop.title.currentFileNotRunnable": "当前文件不能单独运行。请在运行配置菜单里选择一个项目运行配置。", "desktop.title.noRunConfigurations": "没有运行配置", @@ -11210,6 +11232,7 @@ "desktop.marketplace.permissionBuild": "为项目运行构建工具", "desktop.marketplace.permissionGenerate": "在你选择的位置生成项目文件", "desktop.marketplace.permissionBackend": "启动插件的后台服务", + "desktop.marketplace.permissionCommandsInstall": "安装插件所需的命令行工具(每次安装前都会征得你的同意)", "desktop.marketplace.permissionDebug": "启动程序调试器", "desktop.marketplace.installComplete": "安装完成", "desktop.marketplace.installCompleteHelp": "插件已安装,可在“已安装”中查看启用状态。", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 7f26dbf63c..c82564a01a 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -13598,7 +13598,7 @@ }, { "id": "desktop.plugins.installedOnThisComputer", - "description": "Feature card of a plugin language server that runs a program already installed on this computer; arg1 lists the commands it tries", + "description": "Feature card of a plugin language server that runs a program on this computer rather than one inside the plugin; arg1 lists the commands it tries. It must not claim the program is installed: the card shows separately when it is missing", "platforms": [ "desktop" ], @@ -13606,6 +13606,201 @@ "arg1": "string" } }, + { + "id": "desktop.plugins.commandMissing", + "description": "Status of a plugin feature card whose program was not found; commands lists the commands it looks for", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string" + } + }, + { + "id": "desktop.plugins.commandMissingManual", + "description": "Help beside a missing program whose plugin declares no way to install it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandMissingBanner", + "description": "Notice in plugin details when a program the plugin itself runs was not found; commands lists the commands", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string" + } + }, + { + "id": "desktop.plugins.commandMissingHelp", + "description": "Error when a plugin feature could not start because none of its commands was found; commands lists them", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string" + } + }, + { + "id": "desktop.plugins.commandInstallTitle", + "description": "Title of the dialog that installs a program a plugin needs; commands lists the commands", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string" + } + }, + { + "id": "desktop.plugins.commandInstallPrompt", + "description": "First line of the install dialog; tool is the tool that runs the installation, commands the commands it provides", + "platforms": [ + "desktop" + ], + "parameters": { + "tool": "string", + "commands": "string" + } + }, + { + "id": "desktop.plugins.commandInstallNetwork", + "description": "Warning in the install dialog when the installation may download", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallLocation", + "description": "Heading of the install locations in the install dialog", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallManaged", + "description": "Install location owned by Lithe for the plugin", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallManagedHelp", + "description": "Explains the Lithe-managed install location", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallToolDefault", + "description": "Install location the tool uses by default; tool is the tool's name", + "platforms": [ + "desktop" + ], + "parameters": { + "tool": "string" + } + }, + { + "id": "desktop.plugins.commandInstallToolDefaultHelp", + "description": "Explains the tool's default install location", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallNoDirectory", + "description": "Shown under the default install location when it could not be found; tool is the tool's name", + "platforms": [ + "desktop" + ], + "parameters": { + "tool": "string" + } + }, + { + "id": "desktop.plugins.commandInstallCommand", + "description": "Heading of the command line the install dialog will run", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallOutput", + "description": "Heading of what the installation prints, in the install dialog", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstalled", + "description": "Install dialog after a successful installation; directory is where the commands are", + "platforms": [ + "desktop" + ], + "parameters": { + "directory": "string" + } + }, + { + "id": "desktop.plugins.commandInstallFailed", + "description": "Install dialog when the installation exited with an error; code is the exit code", + "platforms": [ + "desktop" + ], + "parameters": { + "code": "string" + } + }, + { + "id": "desktop.plugins.commandInstallStopped", + "description": "Install dialog when the installation ended without an exit code, such as on a signal", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallTimedOut", + "description": "Install dialog when the installation ran past its time limit; seconds is the limit", + "platforms": [ + "desktop" + ], + "parameters": { + "seconds": "string" + } + }, + { + "id": "desktop.plugins.commandInstallCommandsMissing", + "description": "Install dialog when the installation finished but the commands are not where expected", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string", + "directory": "string" + } + }, + { + "id": "desktop.plugins.commandInstallToolMissing", + "description": "Install dialog when the tool that installs was not found; tool is its name", + "platforms": [ + "desktop" + ], + "parameters": { + "tool": "string" + } + }, + { + "id": "desktop.plugins.commandInstallError", + "description": "Install dialog for any other failure; reason is the underlying error, not translated", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, { "id": "desktop.problems.group.file", "description": "Grouping name: diagnostics grouped by file", @@ -106443,6 +106638,13 @@ "desktop" ] }, + { + "id": "desktop.marketplace.permissionCommandsInstall", + "description": "Plugin installation progress or review presentation.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.marketplace.permissionDebug", "description": "Plugin installation progress or review presentation.", diff --git a/shared/platform-feature-matrix/features/plugin-command-installers.json b/shared/platform-feature-matrix/features/plugin-command-installers.json new file mode 100644 index 0000000000..1e5eeeb8a7 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-command-installers.json @@ -0,0 +1,40 @@ +{ + "id": "plugin-command-installers", + "area": "插件", + "group": "插件管理", + "capability": "插件声明的命令缺失时由宿主安装:插件详情“功能”页的能力卡片检测语言服务器、构建、版本控制和调试适配器用到的本机命令,缺失时显示“未找到”和安装按钮;没有卡片的后端命令显示在横幅里。插件用 commandInstallers 声明由哪个已注入的工具安装哪些命令;宿主经 Core 校验并展开为安装计划,用户在对话框里选择 Lithe 管理的目录或工具的默认位置,看清将要运行的命令、环境变量和是否联网后确认,安装输出实时显示,可取消,超时停止;装好后后续启动在记录的目录里找到命令。命令缺失、安装失败、超时和命令没有落到目录都显示本地化原因", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/command_installers.go", + "desktop/internal/core/command_installers_test.go", + "desktop/internal/pluginhost/commands.go", + "desktop/internal/pluginhost/commands_test.go", + "desktop/internal/pluginhost/launch.go", + "desktop/internal/workbench/command_installers.go", + "desktop/internal/workbench/command_installers_test.go", + "desktop/internal/settingswindow/command_install.go", + "desktop/internal/settingswindow/command_install_test.go", + "desktop/internal/settingswindow/command_install_visual_test.go", + ".agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/command_installers.go", + "desktop/internal/pluginhost/commands.go", + "desktop/internal/pluginhost/launch.go", + "desktop/internal/workbench/command_installers.go", + "desktop/internal/workbench/command_installers_test.go", + "desktop/internal/settingswindow/command_install.go", + "desktop/internal/settingswindow/command_install_test.go", + ".agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md" + ] + }, + "owner": "Plugins", + "verification": "宿主测试只用合成插件 dev.lithe.test.command-installers(安装工具是复制出来的测试二进制,不联网):缺失检测按语言服务器、调试适配器和后端分别报告;安装计划展开两个目标,打开对话框不创建目录;managed 目标装进插件根目录 .state 下的受管目录并记录,之后 Backend.ResolveCommand 找到命令;toolDefault 目标按工具默认位置探测并记录该目录;非零退出、命令没写出来、超过超时各报对应原因;取消会停止工具且不留记录;插件没有声明的目标被拒绝。设置窗口测试覆盖卡片状态、横幅、对话框内容、安装输出、完成后卡片清除和取消。可视化证据:-tags 'vivahead lithevisual' 运行 TestVisualCommandInstall 生成深浅主题的卡片与对话框截图。macOS 真机:安装一个声明 commandInstallers 的插件,在缺少命令的机器上打开设置 → 插件 → 已安装 → 功能,确认卡片显示“未找到”与安装按钮;分别选择两个安装位置完成安装,确认之后启动语言服务器或调试不再报命令缺失;安装中取消、断网失败都显示原因;启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。Windows 真机:同样流程,命令文件带 .exe 后缀,PATH 类变量用分号分隔。", + "notes": "对应计划 API-23(工具链与受管进程)。宿主声明 commandInstallers 0;契约与计划展开在 Core(plugins.commandInstallers.requirements/plan/defaultDirectory)。受管目录随插件卸载删除;toolDefault 只记录目录,不删除工具装进默认位置的文件。安装进程不经 shell,参数与环境来自 Core 展开的计划。" +} From 98155cae971f79a709102d5c4a26b35dae1a1bb0 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 16:32:09 +0800 Subject: [PATCH 2/3] =?UTF-8?q?build(desktop):=20Core=20=E5=9B=BA=E5=AE=9A?= =?UTF-8?q?=E5=88=B0=20main=20=E4=B8=8A=E7=9A=84=20c550c2b=EF=BC=88#53=20c?= =?UTF-8?q?ommandInstallers=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/desktop/build-desktop-core.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index ed58a50b3f..d9e0bc61a9 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,6 +28,9 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" +# Lithe-core-rust #53, squash-merged into main as c550c2b: a plugin declares commandInstallers that +# install the commands its systemCommand launches need with an injected tool, and Core expands +# them (plugins.commandInstallers.requirements/plan/defaultDirectory). It is on top of # Lithe-core-rust #52, squash-merged into main as 6477e9a: a tool definition's version probe may # lead with a subcommand (go version) followed only by flags. It is on top of #51 (Rust 1.100 # clippy lints fixed and the Rust 1.100.0 toolchain pinned), #50 (Core CI runs the affected crates @@ -106,7 +109,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="6477e9a45085485d77bb77523d98e6d65ab0b27b" +PINNED_CORE_REVISION="c550c2bf10b4d82d2315e737bf83a007daafaa56" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From a9bddd922e28b4f4dcda4e92b581cbbe7b0f4eb7 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 16:37:34 +0800 Subject: [PATCH 3/3] =?UTF-8?q?feat(desktop):=20=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E8=AE=B0=E5=BD=95=E7=94=A8=E6=88=B7=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E4=B8=8E=E5=A4=B1=E8=B4=A5=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 点能力卡片的安装按钮、对话框的安装按钮各记一次 app.action.performed, 安装计划或安装失败在同一 op 下记 operation_failed(取消不记); 缺失检测失败记 background.operation_failed。 --- .../internal/workbench/command_installers.go | 21 ++++++++++++++++--- .../workbench/command_installers_test.go | 15 +++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/desktop/internal/workbench/command_installers.go b/desktop/internal/workbench/command_installers.go index 19fabac021..5438c2516c 100644 --- a/desktop/internal/workbench/command_installers.go +++ b/desktop/internal/workbench/command_installers.go @@ -69,7 +69,14 @@ func (s settingsCommandInstalls) manifest(ctx context.Context, pluginID string) // Missing asks Core for the plugin's systemCommand launches and looks each one's commands up // as its launch does: the debug adapter's lookup for a debug adapter, the plugin runner's for // everything else, both of which add the directories recorded for the plugin to PATH. -func (s settingsCommandInstalls) Missing(ctx context.Context, pluginID string) ([]settingswindow.MissingCommand, error) { +func (s settingsCommandInstalls) Missing(ctx context.Context, pluginID string) (_ []settingswindow.MissingCommand, err error) { + // A failed check leaves the cards without install buttons, which the window falls back to. + defer func() { + // log-exempt: 用户取消:设置窗口关闭或换了插件,检测结果不再需要。 + if err != nil && !errors.Is(err, context.Canceled) { + s.app.backgroundFailedIn(ctx, "plugin_command_check", err) + } + }() manifest, err := s.manifest(ctx, pluginID) if err != nil { return nil, err @@ -173,7 +180,11 @@ func toolName(names map[string]string, id string) string { // Offer resolves the installer's tool and expands each of its targets, running a toolDefault // target's directory probes to find where it would install. -func (s settingsCommandInstalls) Offer(ctx context.Context, pluginID, installerID string) (settingswindow.CommandInstallOffer, error) { +func (s settingsCommandInstalls) Offer(ctx context.Context, pluginID, installerID string) (_ settingswindow.CommandInstallOffer, err error) { + // The card's Install button is the action; its operation travels in ctx, since the settings + // worker must not touch the window thread's operation. + ctx = s.app.performedIn(ctx, "plugin.commandInstaller.offer", surfaceButton) + defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_command_install_offer", err) }() session, _, err := s.open(ctx, pluginID, installerID) if err != nil { return settingswindow.CommandInstallOffer{}, err @@ -217,7 +228,11 @@ func environmentLines(environment map[string]string) []string { // Install runs the installer for target and records where its commands landed, so the // plugin's later launches find them. The attempt is recorded on the plugin's host channel; a // cancelled one is not. -func (s settingsCommandInstalls) Install(ctx context.Context, pluginID, installerID, target string, output func(string)) (string, error) { +func (s settingsCommandInstalls) Install(ctx context.Context, pluginID, installerID, target string, output func(string)) (_ string, err error) { + // The dialog's Install button is the action; the attempt and the installer's tool run under + // its operation. + ctx = s.app.performedIn(ctx, "plugin.commandInstaller.install", surfaceButton) + defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_command_install", err) }() attempt := core.StartPluginAttempt(pluginID, core.OperationCommandInstallerInstall, core.OriginOf(ctx).Operation) defer attempt.Abandon() directory, stage, err := s.install(ctx, pluginID, installerID, target, output) diff --git a/desktop/internal/workbench/command_installers_test.go b/desktop/internal/workbench/command_installers_test.go index 21ac3be3cc..565ba42b7d 100644 --- a/desktop/internal/workbench/command_installers_test.go +++ b/desktop/internal/workbench/command_installers_test.go @@ -365,6 +365,8 @@ func TestCommandInstallReportsWhyTheCommandsDidNotLand(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { h, _, _ := commandInstallerHarness(t, test.mode) + logger := &treeRecordingLog{} + h.app.logSink = logger installs := settingsCommandInstalls{app: h.app} directory, err := h.app.plugins.Commands.InstallDirectory(commandInstallerPluginID, test.installer) if err != nil { @@ -379,12 +381,21 @@ func TestCommandInstallReportsWhyTheCommandsDidNotLand(t *testing.T) { if installations := h.app.plugins.Commands.Installations(commandInstallerPluginID); len(installations) != 0 { t.Fatalf("a failed installation was recorded: %+v", installations) } + // The click and the failure the dialog shows are each logged once. + if n := countPerformed(logger, "plugin.commandInstaller.install"); n != 1 { + t.Fatalf("the install action was logged %d times", n) + } + if failed := loggedEvents(logger, operationFailedEvent); len(failed) != 1 || failed[0].Fields["operation"] != "plugin_command_install" { + t.Fatalf("operation failures = %+v, want the one install failure", failed) + } }) } } func TestCommandInstallStopsTheToolWhenCancelled(t *testing.T) { h, _, _ := commandInstallerHarness(t, fixtureToolHangs) + logger := &treeRecordingLog{} + h.app.logSink = logger installs := settingsCommandInstalls{app: h.app} ctx, cancel := context.WithCancel(commandInstallContext(t)) defer cancel() @@ -400,6 +411,10 @@ func TestCommandInstallStopsTheToolWhenCancelled(t *testing.T) { if installations := h.app.plugins.Commands.Installations(commandInstallerPluginID); len(installations) != 0 { t.Fatalf("a cancelled installation was recorded: %+v", installations) } + // A cancel is not a failure. + if failed := loggedEvents(logger, operationFailedEvent); len(failed) != 0 { + t.Fatalf("the cancel was logged as a failure: %+v", failed) + } } func TestCommandInstallRefusesATargetTheInstallerLacks(t *testing.T) {