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 index f5fb78196..c5a11f927 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md +++ b/.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md @@ -6,12 +6,15 @@ 很多插件不打包自己要运行的程序,而是用本机已有的命令:Go 插件的语言服务器是 `gopls`,调试器是 `dlv`。以前这些命令不在时,用户只看到“plugin package path is not usable: none of the plan's commands is available”这类原始错误,也不知道怎么装。现在插件可以在清单里用 `commandInstallers` 声明“用哪个工具、跑什么参数来安装哪些命令”。宿主在插件详情“功能”页的能力卡片上显示“未找到 xxx”和安装按钮,用户在对话框里选择安装位置、看清要运行的命令后确认,宿主运行安装并记录命令所在目录,之后该插件的启动都能找到它们。宿主里没有任何针对具体插件或具体工具的代码。 +有的命令没有可以用来安装的工具,只以压缩包发布,例如调试器 CodeLLDB。这时插件改为声明“下载安装器”(download installer):写明每个平台压缩包的固定地址和 SHA-256,宿主在用户确认后下载、校验、解压到受管目录。插件包里不带这个程序,用户第一次需要时才下载。 + ## 问题 - 插件的 `systemCommand` 启动(语言服务器、构建、版本控制、调试适配器、后端)只在 PATH 和工具默认目录里找命令。找不到时,启动失败的原因是英文原始错误,用户不知道缺什么、该装到哪。 - 安装命令的方式因工具而异(`go install`、`npm install -g`、`cargo install`……),装到哪里也因工具而异(`GOBIN`、`GOPATH/bin`)。宿主如果按工具写死安装逻辑,就违反了“宿主对具体插件和工具零依赖”。 - 安装会运行下载代码的程序,必须让用户看清要运行什么、会不会联网,并且可以取消。 - 发行包在运行时只读,装好的命令不能写进 app bundle 或安装目录。 +- 有的命令只以压缩包发布,没有工具能装它。CodeLLDB 就是这样,它每个平台一个 VSIX 包。如果把它打进插件包,每个平台的插件包都会多出几十 MB,不调试的用户也要下载。如果让用户自己下载解压,又容易放错位置,也没人校验内容。 ## 决策 @@ -22,12 +25,17 @@ - **插件声明**:清单 `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`)找出那个目录。 +- **下载安装器**(`requires.commandInstallers: 1`):安装器不写 `tool`,改写 `download`。`download` 包含版本号、每个平台的地址、可选镜像、SHA-256、压缩格式(zip 或 tar.gz)、要去掉的顶层目录,以及命令在解压结果里的相对目录。下载安装器只能装进 `managed` 目标。 - **Core 校验与展开**(Lithe-core-rust#53):`plugins.commandInstallers.requirements` 列出每个 `systemCommand` 启动和它的命令、能安装它的安装器;`plugins.commandInstallers.plan` 把一个目标展开成参数、环境和命令目录;`plugins.commandInstallers.defaultDirectory` 从探测输出里取出目录。宿主不自己解释清单字段。 + - 下载安装器(Lithe-core-rust#133):宿主把自己的平台传给 `requirements` 和 `plan`。没有当前平台压缩包的安装器不出现在 `requirements` 里,界面也就不提供安装按钮。`plan` 返回选中的压缩包和一个缓存键(cache key)。缓存键由压缩包内容身份算出,地址、版本、校验值、格式或目录变化时都会换一个,镜像变化不影响它。 - **宿主执行**(`desktop/internal/workbench/command_installers.go`): - 缺失检测:按启动自己的查找方式找命令。调试适配器用调试的查找(macOS 上还会问 `xcrun --find`),其他用插件运行器的查找。两者都会加上已记录的安装目录。只有“找不到命令”算缺失,别的失败不提示安装。 - 解析工具:在打开的项目里解析,项目固定的工具版本就是安装用的版本。 - 运行:经 `buildprocess` 直接启动工具,不经过 shell。工作目录是项目目录,输出逐行送到对话框(每行有上限),到超时就停止,用户取消就停止。 - 核对:工具退出码为 0 之后,再确认每个命令确实落在目标目录里,才写记录。 + - 下载安装器不运行任何工具,而是复用受管运行时(managed runtimes)的 `pluginruntime.Manager.Prepare`。这样,镜像测速、SHA-256 校验、在私有暂存区解压、路径不能逃出解压根、大小和条目数上限、`ready.json` 完成记录都和受管运行时一致,宿主没有第二套下载代码。解压结果发布之前,先检查每个命令都在命令目录里(Unix 上还要有执行位)。缺命令时整次解压丢弃,错误里写出在压缩包的哪个位置找过,例如 `codelldb-darwin-arm64.vsix/extension/adapter`。 + - 下载安装的布局是 `commands/<安装器 ID>/<缓存键>/`,里面是校验过的压缩包和解压出的一代文件。记录写好后,宿主删除同一安装器下其他缓存键的目录,也就是插件升级前固定的旧版本。删不掉的(例如 Windows 上旧版本的适配器还在运行)留到下次安装再删,不影响这次安装的结果。 + - 失败原因分开报告:下载失败、校验值不符、压缩包无效、命令不在压缩包里、超时。用户取消不算失败,不写失败日志。 - **记录与查找**(`desktop/internal/pluginhost/commands.go` 的 `CommandStore`): - 受管目录是 `<插件根目录>/.state/<插件 ID>/commands/<安装器 ID>`。 - 记录文件是 `<插件根目录>/.state/<插件 ID>/commands.json`,读取上限 64 KiB,先写临时文件再改名替换。 @@ -35,14 +43,14 @@ - **界面**(`desktop/internal/settingswindow/command_install.go`): - 能力卡片显示“未找到 xxx”和安装按钮。没有卡片的后端命令显示在横幅里。 - 对话框列出两个位置。工具默认位置探测不到时,该选项不可选并说明原因。 - - 对话框还显示要运行的命令和环境、是否可能联网。 + - 对话框还显示要运行的命令和环境、是否可能联网。下载安装器的对话框不显示命令,改为显示下载地址、镜像和 SHA-256,并说明下载会联网、校验通过才会安装。下载时显示已下载和总大小的进度条。 - 安装输出实时显示,失败原因全部本地化。命令缺失导致的启动失败(调试、构建、版本控制)也改用本地化提示。 **运行时写入位置**:只写插件根目录下的 `.state`。它属于平台存储目录,不在 app bundle 或安装目录里,所以不影响代码签名,也不影响 Sparkle 增量包的源基线。卸载插件时,Core 的卸载计划包含删除状态目录的步骤(`core.PluginRemoveState`),受管目录和记录随之删除。`toolDefault` 只记录目录,工具装进默认位置的文件归用户和工具所有,卸载不删除。 -正确做法:新插件需要本机命令时,在清单里声明 `commandInstallers`,安装方式写成该工具自己的参数;需要知道工具把命令装到哪,就用 `directory` 探测,不在宿主里加分支。 +正确做法:新插件需要本机命令时,在清单里声明 `commandInstallers`,安装方式写成该工具自己的参数;需要知道工具把命令装到哪,就用 `directory` 探测,不在宿主里加分支。命令只以压缩包发布时,声明 `download`,给每个平台写固定地址和 SHA-256;升级这个命令就是发一个改了地址和校验值的插件版本。 -不要这样做:在宿主里写“缺 gopls 就运行 `go install golang.org/x/tools/gopls@latest`”;也不要让插件后端自己下载并解压命令到插件包目录,插件包和发行包一样,运行时只读。 +不要这样做:在宿主里写“缺 gopls 就运行 `go install golang.org/x/tools/gopls@latest`”;也不要让插件后端自己下载并解压命令到插件包目录,插件包和发行包一样,运行时只读。也不要把 CodeLLDB 这类只在调试时才用的程序打进插件包。 ## 考虑过的备选方案 @@ -51,6 +59,10 @@ 3. **只提示“请手动运行 xxx”**:安全但麻烦,用户要自己找终端并设对 `GOBIN`;用户明确要求提供自动安装按钮。作为退路仍然可用:对话框始终显示要运行的命令和环境,安装失败后用户可以照着手动运行。 4. **只支持装进 Lithe 管理的目录**:最可控,但用户已有 `GOPATH/bin` 习惯时会装出第二份。按用户选择,两种位置都提供,由用户在对话框里选。 5. **把装好的命令写进插件包目录**:卸载时自然删除,但插件包要保持签名后的原样,运行时写入会破坏校验。否决,改为 `.state`。 +6. **把只以压缩包发布的命令打进插件包**(每个平台一个插件包):不需要下载逻辑,但每个平台的插件包都变大,不用这个命令的用户也要下载它;升级命令也必须重新打插件包。用户明确要求像 Go 插件的 `dlv` 一样按需下载。否决。 +7. **用受管运行时(`managedRuntimes`)声明这个压缩包**:下载和校验代码已经现成,但受管运行时在安装插件提交前就准备好,会让每个装了插件的用户都下载;它也不和某个 `systemCommand` 启动绑定,能力卡片不知道缺的是它。否决,只复用它的下载、校验和解压实现,不复用它的触发时机。 +8. **像受管运行时那样,旧缓存键的目录一直保留到卸载插件**:受管运行时这样做,是因为旧插件版本和仍在运行的进程还会按旧路径读取(见[受管插件运行时](2026-11-18-managed-plugin-runtimes.md))。命令安装不同:每个安装器只记录一个目录,记录换成新目录后,任何启动都不再找旧目录,留着只占磁盘,调试器这类程序每次升级都会多留一份。所以记录写好后就删旧目录。代价是:正在运行的旧版本命令在 macOS 和 Linux 上会失去尚未加载的文件,在 Windows 上则删不掉、留到下次。只有用户在旧版本运行时安装新版本才会遇到。 +9. **写一个工具安装器,让它调用 `curl` 和 `tar`**:不用改契约,但各平台自带的下载解压程序不同(Windows 不一定有),校验值要插件自己核对,用户在对话框里看到的是一串 shell 命令而不是地址和校验值。否决。 ## 后果 @@ -59,16 +71,19 @@ - 代价:打开“功能”页时,要为每个 `systemCommand` 启动查找一次命令。这一步在后台运行,有超时限制,不阻塞界面线程。 - 代价:安装会运行插件指定的工具和参数,所以需要 `commands.install` 权限,并在对话框里显示完整命令,由用户确认。 - 代价:`toolDefault` 装的文件不随插件卸载删除,用户需要自己清理。 +- 收益:下载安装器让插件包保持小,只有用到这个命令的用户才下载;下载内容必须和插件固定的 SHA-256 一致。 +- 代价:下载安装器的版本固定在插件清单里,命令要升级就要发插件版本;没有当前平台压缩包时(例如 CodeLLDB 没有 Windows arm64 版本)不提供安装。 - 尚未在原生窗口真机和 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/workbench -run 'CommandDownload' -count=1`:合成插件 `dev.lithe.test.command-downloads` 的下载经假的 HTTP 传输完成(不联网),覆盖打开对话框不发请求、解压后记录且之后能找到命令、删除旧缓存键、再次安装不再下载、校验值不符/下载失败/命令不在压缩包里/条目逃出解压根各报对应原因且不留记录、取消不写失败日志、超时停止。 +- `scripts/desktop/desktop-go.sh test ./internal/settingswindow -run 'CommandInstall|CapabilityCard|DownloadInstaller' -count=1`:卡片状态、横幅、对话框内容(含下载地址、镜像、SHA-256 和下载进度)、安装输出、完成后卡片清除、取消、失败文案。 - `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`:深浅主题的卡片与对话框截图。 +- `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` 启动)不走这里。 +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/pluginruntime/`(下载安装器复用)、`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 index 80e8133bb..b6953d985 100644 --- a/desktop/internal/core/command_installers.go +++ b/desktop/internal/core/command_installers.go @@ -37,33 +37,81 @@ type RequiredCommand struct { Installer *string `json:"installer"` } -// CommandInstaller is the summary of one commandInstallers[] entry. +// CommandInstaller is the summary of one commandInstallers[] entry: a tool installer runs Tool, +// a download installer (commandInstallers 1) downloads a pinned archive and has no tool. type CommandInstaller struct { - ID string `json:"id"` - Commands []string `json:"commands"` - Tool string `json:"tool"` - MinimumVersion *string `json:"minimumVersion"` - MayUseNetwork bool `json:"mayUseNetwork"` + ID string `json:"id"` + Commands []string `json:"commands"` + // Tool is the tool definition a tool installer runs; nil for a download installer. + Tool *string `json:"tool"` + MinimumVersion *string `json:"minimumVersion"` + // Download is the pinned version of a download installer; nil for a tool installer. + Download *CommandInstallerDownload `json:"download"` + 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. +// CommandInstallerDownload is what the requirements say of a download installer. +type CommandInstallerDownload struct { + Version string `json:"version"` +} + +// ToolID is the tool definition a tool installer runs, or "" for a download installer. +func (i CommandInstaller) ToolID() string { + if i.Tool == nil { + return "" + } + return *i.Tool +} + +// CommandArchivePlatform is the host platform a download installer selects its archive for: +// os macos, windows or linux and arch arm64 or x86_64. +type CommandArchivePlatform = ManagedRuntimePlatform + +// CommandInstallPlan is one installer expanded for the target the user chose. For a tool +// installer the host runs Tool's resolved executable with Arguments and Environment set over the +// tool's environment; for a download installer it downloads, checks and extracts Download. type CommandInstallPlan struct { Installer string `json:"installer"` Target string `json:"target"` Commands []string `json:"commands"` - Tool string `json:"tool"` + 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 is where a managed tool installation's commands land; nil for + // toolDefault, whose directory the probes find, and for a download installation, whose + // directory is below the extracted archive. CommandDirectory *string `json:"commandDirectory"` DirectoryProbes []CommandDirectoryProbe `json:"directoryProbes"` + // Download is the archive a download installation extracts; nil for a tool installation. + Download *CommandInstallDownload `json:"download"` +} + +// CommandInstallDownload is the archive Core selected for the host's platform. CacheKey names +// the extraction, which every change to what the archive holds replaces; mirrors do not count. +type CommandInstallDownload struct { + Installer string `json:"installer"` + Version string `json:"version"` + OS string `json:"os"` + Arch string `json:"arch"` + URL string `json:"url"` + // Mirrors are fallback URLs for the same bytes. + Mirrors []string `json:"mirrors,omitempty"` + // SHA256 is the lowercase digest the archive must have. + SHA256 string `json:"sha256"` + // Archive is zip or tar.gz. + Archive string `json:"archive"` + // StripPrefix is the slash-separated directory the archive's entries are below; empty + // for none. + StripPrefix string `json:"stripPrefix"` + CacheKey string `json:"cacheKey"` + // CommandDirectory is where the commands are, slash-separated and relative to the + // extracted root; empty for the root. + CommandDirectory string `json:"commandDirectory"` } // CommandDirectoryProbe is one run of the plan's tool whose output names the directory a @@ -73,8 +121,9 @@ type CommandDirectoryProbe struct { } // 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) { +// of each command. With platform, a download installer without an archive for it is left out; +// a host that installs downloads always passes its own. It reads nothing and starts nothing. +func (c *Client) CommandInstallerRequirements(ctx context.Context, manifest json.RawMessage, platform *CommandArchivePlatform) (CommandRequirements, error) { const command = "plugins.commandInstallers.requirements" var result struct { Status string `json:"status"` @@ -82,8 +131,9 @@ func (c *Client) CommandInstallerRequirements(ctx context.Context, manifest json Requirements *CommandRequirements `json:"requirements"` } if err := c.Execute(ctx, command, struct { - Manifest json.RawMessage `json:"manifest"` - }{manifest}, &result); err != nil { + Manifest json.RawMessage `json:"manifest"` + Platform *CommandArchivePlatform `json:"platform,omitempty"` + }{manifest, platform}, &result); err != nil { return CommandRequirements{}, err } if result.Status == "rejected" && result.Error != nil { @@ -96,8 +146,9 @@ func (c *Client) CommandInstallerRequirements(ctx context.Context, manifest json } // 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) { +// directory the host made for a managed tool installation and must be empty for toolDefault +// and for a download installation, which needs platform to select its archive. +func (c *Client) PlanCommandInstaller(ctx context.Context, manifest json.RawMessage, installerID, target, installDirectory string, platform *CommandArchivePlatform) (CommandInstallPlan, error) { const command = "plugins.commandInstallers.plan" var result struct { Status string `json:"status"` @@ -105,11 +156,12 @@ func (c *Client) PlanCommandInstaller(ctx context.Context, manifest json.RawMess 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 { + Manifest json.RawMessage `json:"manifest"` + InstallerID string `json:"installerID"` + Target string `json:"target"` + InstallDirectory string `json:"installDirectory,omitempty"` + Platform *CommandArchivePlatform `json:"platform,omitempty"` + }{manifest, installerID, target, installDirectory, platform}, &result); err != nil { return CommandInstallPlan{}, err } if result.Status == "rejected" && result.Error != nil { @@ -118,12 +170,25 @@ func (c *Client) PlanCommandInstaller(ctx context.Context, manifest json.RawMess 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) { + if !result.Plan.consistent() { return CommandInstallPlan{}, newParseError(command, "command installer plan returned an invalid outcome", "") } return *result.Plan, nil } +// consistent says the plan is one the host can carry out: a download installs into the managed +// target with nothing to run, and a tool installation has a command directory exactly when +// it is managed. +func (p *CommandInstallPlan) consistent() bool { + if download := p.Download; download != nil { + return p.Target == CommandInstallManaged && p.CommandDirectory == nil && p.Tool == nil && + len(p.Arguments) == 0 && len(p.Environment) == 0 && len(p.DirectoryProbes) == 0 && + download.Installer == p.Installer && download.URL != "" && download.SHA256 != "" && + download.CacheKey != "" && (download.Archive == "zip" || download.Archive == "tar.gz") + } + return p.Tool != nil && (p.Target == CommandInstallManaged) == (p.CommandDirectory != 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. diff --git a/desktop/internal/core/command_installers_test.go b/desktop/internal/core/command_installers_test.go index 15efed6e5..a3e65dcc0 100644 --- a/desktop/internal/core/command_installers_test.go +++ b/desktop/internal/core/command_installers_test.go @@ -17,7 +17,9 @@ import ( ) type commandInstallerCase struct { - Name string `json:"name"` + Name string `json:"name"` + // Plugin names the case's manifest in place of the fixture's. + Plugin string `json:"plugin"` Operation string `json:"operation"` Payload json.RawMessage `json:"payload"` ManifestEdits []struct { @@ -46,9 +48,18 @@ func TestCommandInstallersSharedFixture(t *testing.T) { 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) + plugins := map[string][]byte{} + load := func(name string) []byte { + t.Helper() + if plugin, ok := plugins[name]; ok { + return plugin + } + plugin, err := os.ReadFile(filepath.Join(directory, name)) + if err != nil { + t.Fatal(err) + } + plugins[name] = plugin + return plugin } if len(fixture.Cases) == 0 { t.Fatal("fixture has no cases") @@ -67,12 +78,17 @@ func TestCommandInstallersSharedFixture(t *testing.T) { payload = mergeObjects(t, payload, specific.Payload) expected = specific.Expected } - manifest := editManifest(t, plugin, c) + pluginName := fixture.Plugin + if c.Plugin != "" { + pluginName = c.Plugin + } + manifest := editManifest(t, load(pluginName), c) var fields struct { - InstallerID string `json:"installerID"` - Target string `json:"target"` - InstallDirectory string `json:"installDirectory"` - Outputs []*string `json:"outputs"` + InstallerID string `json:"installerID"` + Target string `json:"target"` + InstallDirectory string `json:"installDirectory"` + Platform *CommandArchivePlatform `json:"platform"` + Outputs []*string `json:"outputs"` } if err := json.Unmarshal(payload, &fields); err != nil { t.Fatal(err) @@ -80,9 +96,9 @@ func TestCommandInstallersSharedFixture(t *testing.T) { var got any switch c.Operation { case "requirements": - got, err = client.CommandInstallerRequirements(ctx, manifest) + got, err = client.CommandInstallerRequirements(ctx, manifest, fields.Platform) case "plan": - got, err = client.PlanCommandInstaller(ctx, manifest, fields.InstallerID, fields.Target, fields.InstallDirectory) + got, err = client.PlanCommandInstaller(ctx, manifest, fields.InstallerID, fields.Target, fields.InstallDirectory, fields.Platform) case "defaultDirectory": var directory string var ok bool @@ -136,7 +152,7 @@ func TestPlanCommandInstallerRefusesAnInconsistentOutcome(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client := NewClient() - if _, err := client.PlanCommandInstaller(ctx, manifest, "sample-ls", "unknown", ""); err == nil { + if _, err := client.PlanCommandInstaller(ctx, manifest, "sample-ls", "unknown", "", nil); 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 != "" { @@ -144,6 +160,42 @@ func TestPlanCommandInstallerRefusesAnInconsistentOutcome(t *testing.T) { } } +// A download plan is one the host can carry out only when it installs into the managed target +// with nothing to run and names an archive it can check. +func TestCommandInstallPlanConsistency(t *testing.T) { + tool := "builder" + directory := "/data/commands/sample" + download := func(edit func(*CommandInstallDownload)) *CommandInstallDownload { + d := &CommandInstallDownload{Installer: "sample", URL: "https://example.org/a.zip", SHA256: strings.Repeat("a", 64), Archive: "zip", CacheKey: strings.Repeat("b", 64)} + if edit != nil { + edit(d) + } + return d + } + for _, c := range []struct { + name string + plan CommandInstallPlan + want bool + }{ + {"managed tool plan", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Tool: &tool, CommandDirectory: &directory}, true}, + {"toolDefault tool plan", CommandInstallPlan{Installer: "sample", Target: CommandInstallToolDefault, Tool: &tool}, true}, + {"managed tool plan without a directory", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Tool: &tool}, false}, + {"tool plan without a tool", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, CommandDirectory: &directory}, false}, + {"download plan", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Download: download(nil)}, true}, + {"download plan for toolDefault", CommandInstallPlan{Installer: "sample", Target: CommandInstallToolDefault, Download: download(nil)}, false}, + {"download plan with a tool", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Tool: &tool, Download: download(nil)}, false}, + {"download plan with a command directory", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, CommandDirectory: &directory, Download: download(nil)}, false}, + {"download plan with arguments", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Arguments: []string{"x"}, Download: download(nil)}, false}, + {"download of another installer", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Download: download(func(d *CommandInstallDownload) { d.Installer = "other" })}, false}, + {"download without a digest", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Download: download(func(d *CommandInstallDownload) { d.SHA256 = "" })}, false}, + {"download of an unknown format", CommandInstallPlan{Installer: "sample", Target: CommandInstallManaged, Download: download(func(d *CommandInstallDownload) { d.Archive = "rar" })}, false}, + } { + if got := c.plan.consistent(); got != c.want { + t.Errorf("%s: consistent() = %v, want %v", c.name, got, c.want) + } + } +} + func mergeObjects(t *testing.T, base, overlay json.RawMessage) json.RawMessage { t.Helper() merged := map[string]json.RawMessage{} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index cc4925dc5..71edb4fd5 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1429,17 +1429,25 @@ 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.commandInstallArchiveInvalid": "Could not extract the archive: {reason}", + "desktop.plugins.commandInstallChecksumMismatch": "The downloaded archive does not match the SHA-256 the plugin pins. It was discarded without being installed.", "desktop.plugins.commandInstallCommand": "Command to run", "desktop.plugins.commandInstallCommandsMissing": "The installation finished, but {commands} was not found in {directory}.", + "desktop.plugins.commandInstallDigest": "SHA-256", + "desktop.plugins.commandInstallDownloadFailed": "Could not download the archive: {reason}", + "desktop.plugins.commandInstallDownloadNetwork": "The archive is downloaded from the address below and installed only if its SHA-256 matches the one the plugin pins.", + "desktop.plugins.commandInstallDownloadPrompt": "{commands} {version} will be downloaded and extracted.", "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.commandInstallMirror": "Mirror", "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.commandInstallSource": "Download from", "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}", @@ -4712,17 +4720,25 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginWeb.openFileTitle": "为 {plugin} 选择文件", "desktop.pluginWeb.saveFileTitle": "为 {plugin} 保存文件", "desktop.pluginWeb.unavailable": "无法显示此窗口:{reason}", + "desktop.plugins.commandInstallArchiveInvalid": "无法解压压缩包:{reason}", + "desktop.plugins.commandInstallChecksumMismatch": "下载的压缩包与插件固定的 SHA-256 不一致,已丢弃,没有安装。", "desktop.plugins.commandInstallCommand": "将要运行的命令", "desktop.plugins.commandInstallCommandsMissing": "安装已完成,但在 {directory} 中没有找到 {commands}。", + "desktop.plugins.commandInstallDigest": "SHA-256", + "desktop.plugins.commandInstallDownloadFailed": "无法下载压缩包:{reason}", + "desktop.plugins.commandInstallDownloadNetwork": "将从下面的地址下载压缩包,SHA-256 与插件固定的值一致才会安装。", + "desktop.plugins.commandInstallDownloadPrompt": "将下载并解压 {commands} {version}。", "desktop.plugins.commandInstallError": "无法安装:{reason}", "desktop.plugins.commandInstallFailed": "安装失败,退出码 {code}。请查看下面的输出。", "desktop.plugins.commandInstallLocation": "安装位置", "desktop.plugins.commandInstallManaged": "Lithe 管理的目录", "desktop.plugins.commandInstallManagedHelp": "只供 Lithe 使用,卸载插件时一并删除。", + "desktop.plugins.commandInstallMirror": "镜像", "desktop.plugins.commandInstallNetwork": "安装时可能会从网络下载。", "desktop.plugins.commandInstallNoDirectory": "无法确定 {tool} 的默认安装位置。", "desktop.plugins.commandInstallOutput": "输出", "desktop.plugins.commandInstallPrompt": "将用 {tool} 安装 {commands}。", + "desktop.plugins.commandInstallSource": "下载地址", "desktop.plugins.commandInstallStopped": "安装程序意外结束。请查看下面的输出。", "desktop.plugins.commandInstallTimedOut": "安装超过 {seconds} 秒仍未完成,已停止。", "desktop.plugins.commandInstallTitle": "安装 {commands}", diff --git a/desktop/internal/pluginhost/commands.go b/desktop/internal/pluginhost/commands.go index 770fb172f..b91a3d4a6 100644 --- a/desktop/internal/pluginhost/commands.go +++ b/desktop/internal/pluginhost/commands.go @@ -58,7 +58,10 @@ type commandRecord struct { // (pluginpkg.RemoveState): // // - commands// is the install directory of a managed -// installation; the tool writes into it, the host creates it. +// installation; the tool writes into it, the host creates it. A download +// installer keeps its verified archive and the extraction below it in +// /, pluginruntime.Manager's layout; after an installation +// records a new key, the host removes the others. // - 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. @@ -247,6 +250,15 @@ const ( // CommandInstallCommandsMissingCode: the installation finished but a command it provides // is not in its directory. CommandInstallCommandsMissingCode = "plugin.commandInstaller.commandsMissing" + // CommandInstallDownloadFailedCode: no URL of a download installation delivered its + // archive. + CommandInstallDownloadFailedCode = "plugin.commandInstaller.downloadFailed" + // CommandInstallChecksumMismatchCode: a download installation's archive does not have its + // pinned SHA-256. + CommandInstallChecksumMismatchCode = "plugin.commandInstaller.checksumMismatch" + // CommandInstallArchiveInvalidCode: a download installation's archive is not a zip or + // tar.gz whose entries extract safely below its strip prefix. + CommandInstallArchiveInvalidCode = "plugin.commandInstaller.archiveInvalid" ) // CommandInstallError is an installation that ran and did not provide its commands. Plugin @@ -263,6 +275,9 @@ type CommandInstallError struct { // CommandInstallCommandsMissingCode. Commands []string Directory string + // Err is what went wrong, for the download codes; it is the host's own diagnostic and + // not shown translated. + Err error } func (e *CommandInstallError) Error() string { @@ -273,6 +288,12 @@ func (e *CommandInstallError) Error() string { 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) + case CommandInstallDownloadFailedCode, CommandInstallChecksumMismatchCode, CommandInstallArchiveInvalidCode: + if e.Err != nil { + return fmt.Sprintf("%s: %v", e.Code, e.Err) + } } return e.Code } + +func (e *CommandInstallError) Unwrap() error { return e.Err } diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 5009a3933..fabf9f773 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -126,7 +126,10 @@ type Capabilities map[string][]int // 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). +// systemCommand launches then find them there (CommandStore). Version 1 +// adds pinned archive downloads, which the host downloads, checks against +// the pinned SHA-256 and extracts below the plugin's managed directory +// after the user confirms the version and the URL. // - 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. @@ -202,6 +205,9 @@ func Declared() Capabilities { // Version 1 adds optional mirror URLs on managed runtime artifacts for automatic // fastest-source selection and failover. declared["managedRuntimes"] = []int{0, 1} + // Version 1 adds installers that download a pinned archive instead of running + // a tool; the host extracts it below the plugin's managed command directory. + declared["commandInstallers"] = []int{0, 1} return declared } diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 725375f8e..8f6233d70 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -91,6 +91,10 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "managedRuntimes" { wanted = []int{0, 1} } + // Plugin management installs the pinned archive downloads version 1 adds. + if name == "commandInstallers" { + wanted = []int{0, 1} + } if versions := declared[name]; !slices.Equal(versions, wanted) { t.Fatalf("%s = %v, want %v", name, versions, wanted) } diff --git a/desktop/internal/pluginruntime/mirrors.go b/desktop/internal/pluginruntime/mirrors.go index 510b8af0a..1b925bcc1 100644 --- a/desktop/internal/pluginruntime/mirrors.go +++ b/desktop/internal/pluginruntime/mirrors.go @@ -3,6 +3,7 @@ package pluginruntime import ( "context" "errors" + "fmt" "io" "net/http" "sort" @@ -68,7 +69,7 @@ func (m *Manager) downloadArchive(ctx context.Context, artifact Artifact, progre return nil, nil, ctx.Err() } } - return nil, nil, lastErr + return nil, nil, fmt.Errorf("%w: %w", ErrDownload, lastErr) } func (m *Manager) downloadFromMirror(ctx context.Context, artifact Artifact, location string, allowSpeedFailover bool, progress func(Progress)) (*marketplace.DownloadedArchive, func() error, error) { diff --git a/desktop/internal/pluginruntime/runtime.go b/desktop/internal/pluginruntime/runtime.go index 72c87e6b9..d4fb9a6c3 100644 --- a/desktop/internal/pluginruntime/runtime.go +++ b/desktop/internal/pluginruntime/runtime.go @@ -30,6 +30,9 @@ var ( ErrArtifact = errors.New("managed runtime artifact is not usable") ErrArchive = errors.New("managed runtime archive is not safe to extract") ErrBusy = errors.New("managed runtime preparation is busy") + // ErrDownload means no URL of the artifact delivered its archive; it wraps the last + // URL's failure, such as marketplace.ErrArchiveChecksum for bytes that do not match. + ErrDownload = errors.New("managed runtime archive could not be downloaded") ) // Artifact is the selected platform artifact returned by Core. All paths are diff --git a/desktop/internal/pluginruntime/runtime_test.go b/desktop/internal/pluginruntime/runtime_test.go index f088ed865..ad5455d76 100644 --- a/desktop/internal/pluginruntime/runtime_test.go +++ b/desktop/internal/pluginruntime/runtime_test.go @@ -369,7 +369,8 @@ func TestChecksumFailureAndCancelledValidationNeverPublish(t *testing.T) { artifact := selected(body, "tar.gz", "1") manager, _ := testManager(t, map[string][]byte{artifact.URL: []byte("damaged download")}) ctx := testContext(t) - if _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil); !errors.Is(err, marketplace.ErrArchiveChecksum) { + // A download that never delivered the pinned bytes says so, with the transfer's own cause. + if _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil); !errors.Is(err, ErrDownload) || !errors.Is(err, marketplace.ErrArchiveChecksum) { t.Fatalf("checksum failure = %v", err) } manager, _ = testManager(t, map[string][]byte{artifact.URL: body}) diff --git a/desktop/internal/pluginservice/runtime_trust_test.go b/desktop/internal/pluginservice/runtime_trust_test.go index 664091c43..1f5264757 100644 --- a/desktop/internal/pluginservice/runtime_trust_test.go +++ b/desktop/internal/pluginservice/runtime_trust_test.go @@ -353,7 +353,9 @@ func TestManagedToolchainFactsFeedToolchainResolutionWithoutStartingBackend(t *t } var archiveBuf bytes.Buffer zw := zip.NewWriter(&archiveBuf) - header := &zip.FileHeader{Name: "bin/" + runtimeFixtureCommand(), Method: zip.Deflate} + // The entry is the test binary itself, about 250 MB. Stored rather than deflated: under + // -race, compressing and inflating it took longer than the whole deadline. + header := &zip.FileHeader{Name: "bin/" + runtimeFixtureCommand(), Method: zip.Store} header.SetMode(0o755) fw, err := zw.CreateHeader(header) if err != nil { diff --git a/desktop/internal/pluginservice/runtimes.go b/desktop/internal/pluginservice/runtimes.go index b4d9f87f3..f71e811b9 100644 --- a/desktop/internal/pluginservice/runtimes.go +++ b/desktop/internal/pluginservice/runtimes.go @@ -45,6 +45,12 @@ type RuntimeEnvironment struct { // SetRuntimeLanguage supplies the UI's current language without reading view state on an I/O worker. func (s *Service) SetRuntimeLanguage(language string) { s.runtimeLanguage.Store(&language) } +// ArchivePlatform is the platform Core selects this host's pinned archives for: managed runtime +// artifacts and command installer downloads. +func ArchivePlatform() core.ManagedRuntimePlatform { + return core.ManagedRuntimePlatform{OS: toolchain.PlatformName(runtime.GOOS), Arch: core.PluginArchitecture()} +} + // HasManagedRuntimes is a dispatch check, not manifest validation. Core validates the declaration // before any process or I/O; old plugins keep their existing path without a new service call. func HasManagedRuntimes(manifest json.RawMessage) bool { @@ -85,7 +91,7 @@ func (s *Service) ensureRuntimes(ctx context.Context, manifest json.RawMessage, if !ok { return RuntimeEnvironment{}, fmt.Errorf("%w: managed runtime service unavailable", ErrAssembly) } - platform := core.ManagedRuntimePlatform{OS: toolchain.PlatformName(runtime.GOOS), Arch: core.PluginArchitecture()} + platform := ArchivePlatform() plan, err := kernel.PlanManagedRuntimes(ctx, manifest, platform) if err != nil { return RuntimeEnvironment{}, err @@ -410,7 +416,7 @@ func (s *Service) ManagedToolchainFacts(ctx context.Context, manifests []json.Ra if !ok { return nil, nil, nil } - platform := core.ManagedRuntimePlatform{OS: toolchain.PlatformName(runtime.GOOS), Arch: core.PluginArchitecture()} + platform := ArchivePlatform() for _, manifest := range manifests { if !HasManagedRuntimes(manifest) { continue diff --git a/desktop/internal/settingswindow/command_install.go b/desktop/internal/settingswindow/command_install.go index 0d822d2a4..d1a184151 100644 --- a/desktop/internal/settingswindow/command_install.go +++ b/desktop/internal/settingswindow/command_install.go @@ -11,6 +11,7 @@ import ( "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/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" "github.com/vivaui/viva/ui" ) @@ -114,7 +115,7 @@ func newCommandInstalls(source CommandInstaller, report func(string, error), wak }) // 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 source.Install(ctx, request.pluginID, request.installerID, request.target, request.output.add, request.output.setProgress) }) return s } @@ -234,13 +235,37 @@ 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. +// commandOutput keeps the last lines an installation printed, or the last phase a download +// reported. The installation's goroutine adds them; the window thread reads them. type commandOutput struct { wake func() - mu sync.Mutex - lines []string + mu sync.Mutex + lines []string + progress *pluginruntime.Progress +} + +func (o *commandOutput) setProgress(progress pluginruntime.Progress) { + o.mu.Lock() + o.progress = &progress + o.mu.Unlock() + if o.wake != nil { + o.wake() + } +} + +// lastProgress is the last phase a download reported; ok is false before the first and for +// a tool installation. +func (o *commandOutput) lastProgress() (pluginruntime.Progress, bool) { + if o == nil { + return pluginruntime.Progress{}, false + } + o.mu.Lock() + defer o.mu.Unlock() + if o.progress == nil { + return pluginruntime.Progress{}, false + } + return *o.progress, true } func (o *commandOutput) add(line string) { @@ -347,8 +372,7 @@ func (w *window) commandInstallModal(c ui.C) { 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.commandInstallProgress(c, language, dialog.output) 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) @@ -421,15 +445,56 @@ func (d *commandInstallDialog) targetUsable() bool { return false } +// commandInstallProgress is the running installation's status: a download's phase, with +// how much of the archive arrived when its size is known, or that a tool is installing. +func (w *window) commandInstallProgress(c ui.C, language i18n.Language, output *commandOutput) { + progress, ok := output.lastProgress() + if !ok { + ui.Text(c, i18n.Shared(language, "settings.general.installing")) + ui.Progress(c, 0).Indeterminate().FillWidth() + return + } + ui.Wrap(c, RuntimeProgressText(language, progress)) + if progress.Phase == "downloading" && progress.Total > 0 { + ui.Progress(c, float32(progress.Received)/float32(progress.Total)).FillWidth() + return + } + ui.Progress(c, 0).Indeterminate().FillWidth() +} + // commandInstallOffer is the confirmation: what runs, whether it downloads, and where the -// commands may go. +// commands may go. A download names the archive's addresses and digest instead of a tool and +// its command line. 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) + if download := offer.Download; download != nil { + ui.Wrap(c, i18n.SharedFormat(language, "desktop.plugins.commandInstallDownloadPrompt", map[string]string{ + "commands": commandList(offer.Commands), "version": download.Version, + })) + ui.Wrap(c, i18n.Shared(language, "desktop.plugins.commandInstallDownloadNetwork")).FontSize(12).Color(w.pal.warning) + ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallSource")).FontSize(13).Bold().PadTop(4) + // Labels are in the text font, so a translated label keeps its own spacing; the address + // and the digest are monospaced. + labelled := func(k ui.C, label, value string) { + ui.Row(k).FillWidth().Gap(6).Children(func() { + ui.Text(k, label).FontSize(11).Color(w.pal.muted).Shrink(0) + ui.Wrap(k, value).Mono().FontSize(11).Color(w.pal.muted).Grow(1).Shrink(1).MinWidth(0) + }) + } + ui.Column(c).FillWidth().Gap(2).Pad(8).Radius(6).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { + ui.Wrap(c, download.URL).Mono().FontSize(11).Color(w.pal.text) + for index, mirror := range download.Mirrors { + labelled(c.KeyInt(index), i18n.Shared(language, "desktop.plugins.commandInstallMirror"), mirror) + } + labelled(c.KeyInt(len(download.Mirrors)), i18n.Shared(language, "desktop.plugins.commandInstallDigest"), download.SHA256) + }) + } else { + 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 @@ -453,7 +518,7 @@ func (w *window) commandInstallOffer(c ui.C, language i18n.Language, dialog *com chosen = target } } - if chosen == nil { + if chosen == nil || chosen.CommandLine == "" { return } ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallCommand")).FontSize(13).Bold().PadTop(4) @@ -507,6 +572,12 @@ func commandInstallFailureText(language i18n.Language, tool string, err error) s return i18n.Shared(language, "desktop.plugins.commandInstallStopped") } return i18n.SharedFormat(language, "desktop.plugins.commandInstallFailed", map[string]string{"code": strconv.Itoa(installErr.ExitCode)}) + case pluginhost.CommandInstallDownloadFailedCode: + return i18n.SharedFormat(language, "desktop.plugins.commandInstallDownloadFailed", map[string]string{"reason": causeText(installErr)}) + case pluginhost.CommandInstallChecksumMismatchCode: + return i18n.Shared(language, "desktop.plugins.commandInstallChecksumMismatch") + case pluginhost.CommandInstallArchiveInvalidCode: + return i18n.SharedFormat(language, "desktop.plugins.commandInstallArchiveInvalid", map[string]string{"reason": causeText(installErr)}) } case errors.As(err, &unavailable): if tool == "" { @@ -516,3 +587,11 @@ func commandInstallFailureText(language i18n.Language, tool string, err error) s } return i18n.SharedFormat(language, "desktop.plugins.commandInstallError", map[string]string{"reason": err.Error()}) } + +// causeText is the untranslated error a download failure wraps, or its code without one. +func causeText(err *pluginhost.CommandInstallError) string { + if err.Err == nil { + return err.Code + } + return err.Err.Error() +} diff --git a/desktop/internal/settingswindow/command_install_test.go b/desktop/internal/settingswindow/command_install_test.go index 022fe13dc..34308ec37 100644 --- a/desktop/internal/settingswindow/command_install_test.go +++ b/desktop/internal/settingswindow/command_install_test.go @@ -11,16 +11,22 @@ import ( "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/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" "github.com/vivaui/viva/app" ) -const fixtureCommandDirectory = "/data/commands/fixture-ls" +const ( + fixtureCommandDirectory = "/data/commands/fixture-ls" + fixtureDigest = "2f114a990e1b368dd1dbd33c80c0e719767af2d228391ec0df0571c957f9ac91" +) // 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. +// one line, or with download reports a download half done, and then waits for release or a +// cancel. type fakeCommandInstaller struct { + download bool mu sync.Mutex installed bool targets []string @@ -44,6 +50,16 @@ func (f *fakeCommandInstaller) Missing(context.Context, string) ([]MissingComman } func (f *fakeCommandInstaller) Offer(context.Context, string, string) (CommandInstallOffer, error) { + if f.download { + return CommandInstallOffer{ + Installer: "fixture-ls", Commands: []string{"fixture-ls"}, MayUseNetwork: true, Timeout: time.Minute, + Download: &CommandInstallDownload{ + Version: "1.2.3", URL: "https://downloads.example.org/fixture-ls-1.2.3.zip", + Mirrors: []string{"https://mirror.example.net/fixture-ls-1.2.3.zip"}, SHA256: fixtureDigest, + }, + Targets: []CommandInstallTarget{{Target: core.CommandInstallManaged, Directory: fixtureCommandDirectory}}, + }, nil + } return CommandInstallOffer{ Installer: "fixture-ls", Commands: []string{"fixture-ls"}, Tool: "Builder", Executable: "/tools/builder", MayUseNetwork: true, Timeout: time.Minute, @@ -54,11 +70,15 @@ func (f *fakeCommandInstaller) Offer(context.Context, string, string) (CommandIn }, nil } -func (f *fakeCommandInstaller) Install(ctx context.Context, _, _, target string, output func(string)) (string, error) { +func (f *fakeCommandInstaller) Install(ctx context.Context, _, _, target string, output func(string), progress func(pluginruntime.Progress)) (string, error) { f.mu.Lock() f.targets = append(f.targets, target) f.mu.Unlock() - output("fixture: downloading") + if f.download { + progress(pluginruntime.Progress{ID: "fixture-ls", Phase: "downloading", Received: 512 << 10, Total: 1 << 20}) + } else { + output("fixture: downloading") + } close(f.printed) select { case <-f.release: @@ -152,6 +172,58 @@ func TestCapabilityCardInstallsItsMissingCommand(t *testing.T) { d.until("the card to drop the installed command", func() bool { return w.commands.dialog == nil && !d.text(missing) }) } +func TestDownloadInstallerShowsItsArchiveAndProgress(t *testing.T) { + f := newFakeCommandInstaller() + f.download = true + 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) }) + + d.click(words("desktop.marketplace.install")) + prompt := format("desktop.plugins.commandInstallDownloadPrompt", map[string]string{"commands": "fixture-ls", "version": "1.2.3"}) + d.until("the download offer", func() bool { return d.text(prompt) }) + for _, shown := range []string{ + words("desktop.plugins.commandInstallDownloadNetwork"), + "https://downloads.example.org/fixture-ls-1.2.3.zip", + words("desktop.plugins.commandInstallMirror"), + "https://mirror.example.net/fixture-ls-1.2.3.zip", + words("desktop.plugins.commandInstallDigest"), + fixtureDigest, + words("desktop.plugins.commandInstallManaged"), + fixtureCommandDirectory, + } { + // The network note is long enough to wrap in the dialog. + if !d.showsWrapped(shown) { + t.Fatalf("the download offer does not show %q", shown) + } + } + // A download runs no tool, so there is neither a tool's prompt nor a command line. + for _, hidden := range []string{ + words("desktop.plugins.commandInstallCommand"), + words("desktop.plugins.commandInstallNetwork"), + } { + if d.showsWrapped(hidden) { + t.Fatalf("the download offer shows %q", hidden) + } + } + + d.click(words("desktop.marketplace.install")) + waitClosed(t, "the download to start", f.printed) + downloading := format("desktop.marketplace.runtimeDownloading", map[string]string{"dependency": "fixture-ls", "received": "0.5", "total": "1.0"}) + d.until("the download's progress", func() bool { return d.text(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) @@ -184,6 +256,12 @@ func TestCommandInstallFailuresAreLocalized(t *testing.T) { {&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"})}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallDownloadFailedCode, Err: errors.New("HTTP 404")}, + format("desktop.plugins.commandInstallDownloadFailed", map[string]string{"reason": "HTTP 404"})}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallChecksumMismatchCode, Err: errors.New("digest differs")}, + i18n.Shared(i18n.English, "desktop.plugins.commandInstallChecksumMismatch")}, + {&pluginhost.CommandInstallError{Code: pluginhost.CommandInstallArchiveInvalidCode, Err: errors.New("entry escapes the root")}, + format("desktop.plugins.commandInstallArchiveInvalid", map[string]string{"reason": "entry escapes the root"})}, {&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"})}, } { diff --git a/desktop/internal/settingswindow/command_install_visual_test.go b/desktop/internal/settingswindow/command_install_visual_test.go index 38b4dc941..5a16ca950 100644 --- a/desktop/internal/settingswindow/command_install_visual_test.go +++ b/desktop/internal/settingswindow/command_install_visual_test.go @@ -15,7 +15,8 @@ import ( ) // 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' +// Install button, and the install dialog it opens, for a tool installer and for a download +// installer, whose download is also shown under way. Opt in with -tags 'vivahead lithevisual' // and LITHE_VISUAL_OUTPUT_DIR. func TestVisualCommandInstall(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") @@ -28,9 +29,22 @@ func TestVisualCommandInstall(t *testing.T) { for _, look := range []struct { theme string language i18n.Language - }{{"dark", i18n.Chinese}, {"light", i18n.English}} { - t.Run(look.theme, func(t *testing.T) { + download bool + }{{"dark", i18n.Chinese, false}, {"light", i18n.English, false}, {"dark", i18n.Chinese, true}, {"light", i18n.English, true}} { + name := look.theme + if look.download { + name = "download-" + look.theme + } + t.Run(name, func(t *testing.T) { f := newFakeCommandInstaller() + f.download = look.download + t.Cleanup(func() { + select { + case <-f.release: + default: + close(f.release) + } + }) facts := []PluginFacts{{ ID: "dev.lithe.test.commands", Name: "Commands Fixture", Vendor: "Test", Version: "1.0.0", Source: PluginSourceDisk, Permissions: []string{"commands.install", "languageServer.launch"}, @@ -54,17 +68,32 @@ func TestVisualCommandInstall(t *testing.T) { 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) + if !look.download { + if err := session.Screenshot(filepath.Join(out, "command-install-card-"+name+".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"}) + if look.download { + prompt = i18n.SharedFormat(look.language, "desktop.plugins.commandInstallDownloadPrompt", map[string]string{"commands": "fixture-ls", "version": "1.2.3"}) + } 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 { + if err := session.Screenshot(filepath.Join(out, "command-install-dialog-"+name+".png")); err != nil { + t.Fatal(err) + } + if !look.download { + return + } + d.click(i18n.Shared(look.language, "desktop.marketplace.install")) + waitClosed(t, "the download to start", f.printed) + downloading := i18n.SharedFormat(look.language, "desktop.marketplace.runtimeDownloading", map[string]string{"dependency": "fixture-ls", "received": "0.5", "total": "1.0"}) + d.until("the download's progress", func() bool { return d.text(downloading) }) + if err := session.Screenshot(filepath.Join(out, "command-install-progress-"+name+".png")); err != nil { t.Fatal(err) } }) diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index b01a0dc12..952236a34 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -291,15 +291,17 @@ type CommandInstaller interface { // 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. + // each target's command line and directory, or the archive a download installer fetches. + // 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) + // Install runs the installer for the target the user chose and returns the directory its + // commands are in once they are found there. A tool hands each line it prints to output as + // it arrives; a download reports its phases to progress, from any goroutine. Cancelling + // ctx stops the tool or the transfer. A failed installation is a + // *pluginhost.CommandInstallError when the tool ran or the download failed, 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), progress func(pluginruntime.Progress)) (string, error) } // MissingCommand is one launch of a plugin none of whose commands the host finds. @@ -312,7 +314,8 @@ type MissingCommand struct { // 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 is the display name of the tool the installer runs; empty without an installer and + // for a download installer, which runs no tool. Tool string } @@ -321,16 +324,31 @@ 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 is the tool definition that runs it, and Executable the program resolved for it; + // both empty for a download. Tool, Executable string + // Download is the archive a download installer fetches; nil for a tool installer. + Download *CommandInstallDownload // 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 are the places the user may install into, managed first. A download has only + // managed, without a command line. Targets []CommandInstallTarget } +// CommandInstallDownload is the archive a download installer fetches for this host. +type CommandInstallDownload struct { + // Version is the pinned upstream version. + Version string + // URL is where the archive is fetched from, and Mirrors the fallbacks for the same bytes. + URL string + Mirrors []string + // SHA256 is the digest the archive must have; anything else is discarded unextracted. + SHA256 string +} + // CommandInstallTarget is one place an installation can put its commands. type CommandInstallTarget struct { // Target is core.CommandInstallManaged or core.CommandInstallToolDefault. diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index ee587e10f..ceb07ab7b 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -157,10 +157,11 @@ type Kernel interface { ToolchainSettingsViewOf(ctx context.Context, request core.ToolchainSettingsViewRequest) (core.ToolchainSettingsView, 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) + // one installer expanded for the target the user chose, with a download's archive selected + // for platform, and the directory a toolDefault installation lands in from its probes' + // output (command_installers.go). + CommandInstallerRequirements(ctx context.Context, manifest json.RawMessage, platform *core.CommandArchivePlatform) (core.CommandRequirements, error) + PlanCommandInstaller(ctx context.Context, manifest json.RawMessage, installerID, target, installDirectory string, platform *core.CommandArchivePlatform) (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) diff --git a/desktop/internal/workbench/command_downloads_test.go b/desktop/internal/workbench/command_downloads_test.go new file mode 100644 index 000000000..9191dc418 --- /dev/null +++ b/desktop/internal/workbench/command_downloads_test.go @@ -0,0 +1,452 @@ +package workbench + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path" + "path/filepath" + "reflect" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +const ( + commandDownloadPluginID = "dev.lithe.test.command-downloads" + commandDownloadCommand = "lithe-fixture-lldb" +) + +// commandDownloadManifest declares a debug adapter that runs lithe-fixture-lldb from PATH and a +// download installer whose archive for every platform has digest and a mirror, with its +// commands in extension/adapter, a directory below the archive's top level. +func commandDownloadManifest(t *testing.T, digest string, timeoutSeconds int) string { + t.Helper() + var artifacts []map[string]any + for _, system := range []string{"macos", "linux", "windows"} { + for _, arch := range []string{"arm64", "x86_64"} { + name := fmt.Sprintf("lithe-fixture-lldb-%s-%s.zip", system, arch) + artifacts = append(artifacts, map[string]any{ + "os": system, "arch": arch, + "url": "https://downloads.example.org/lldb/1.2.3/" + name, + "mirrors": []string{"https://mirror.example.net/lldb/1.2.3/" + name}, + "sha256": digest, "archive": "zip", + }) + } + } + encoded, err := json.Marshal(artifacts) + if err != nil { + t.Fatal(err) + } + return fmt.Sprintf(`{ + "schemaVersion": 0, + "id": %q, + "displayName": "Command Download Fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"commandInstallers": 1, "debugAdapters": 0, "languages": 0}, + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": ["commands.install", "debug.launch"], + "activationEvents": ["onDebug:fixture"], + "languages": [{"id": "fixture", "displayName": "Fixture", "fileExtensions": ["fixture"]}], + "debugAdapters": [{ + "id": "fixture", + "displayName": "Fixture LLDB", + "adapterID": "fixture-lldb", + "requests": ["launch"], + "launch": { + "process": {"launch": {"kind": "systemCommand", "commands": [%q]}, "arguments": ["--stdio"]}, + "transport": "stdio" + } + }], + "commandInstallers": [{ + "id": "fixture-lldb", + "commands": [%q], + "download": {"version": "1.2.3", "artifacts": %s}, + "mayUseNetwork": true, + "timeoutSeconds": %d, + "targets": {"managed": {"commandDirectory": "extension/adapter"}} + }] +}`, commandDownloadPluginID, commandDownloadCommand, commandDownloadCommand, encoded, timeoutSeconds) +} + +// fixtureZip is a zip archive of files, each name mapped to its mode. Nothing in it runs. +func fixtureZip(t *testing.T, files map[string]os.FileMode) []byte { + t.Helper() + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + slices.Sort(names) + var buffer bytes.Buffer + archive := zip.NewWriter(&buffer) + for _, name := range names { + header := &zip.FileHeader{Name: name, Method: zip.Deflate} + header.SetMode(files[name]) + writer, err := archive.CreateHeader(header) + if err != nil { + t.Fatal(err) + } + if _, err := writer.Write([]byte("fixture " + name + "\n")); err != nil { + t.Fatal(err) + } + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +// adapterArchive is an archive with the fixture command in extension/adapter next to a data file. +func adapterArchive(t *testing.T) []byte { + t.Helper() + name := commandDownloadCommand + if runtime.GOOS == "windows" { + name += ".exe" + } + return fixtureZip(t, map[string]os.FileMode{ + "extension/package.json": 0o644, + "extension/adapter/" + name: 0o755, + }) +} + +func sha256Hex(data []byte) string { + digest := sha256.Sum256(data) + return hex.EncodeToString(digest[:]) +} + +// archiveServer answers the fixture's archive hosts in memory and counts the requests. +type archiveServer struct { + mu sync.Mutex + requests []string + // serve answers one request; nil serves body. + serve func(*http.Request) (*http.Response, error) + body []byte +} + +func (s *archiveServer) RoundTrip(request *http.Request) (*http.Response, error) { + s.mu.Lock() + s.requests = append(s.requests, request.Method+" "+request.URL.String()) + serve := s.serve + s.mu.Unlock() + if serve != nil { + return serve(request) + } + return archiveResponse(request, http.StatusOK, s.body), nil +} + +func (s *archiveServer) seen() []string { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.requests) +} + +func archiveResponse(request *http.Request, status int, body []byte) *http.Response { + if request.Method == http.MethodHead { + return &http.Response{StatusCode: status, Header: http.Header{}, Body: http.NoBody, ContentLength: int64(len(body)), Request: request} + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {"application/zip"}}, + Body: io.NopCloser(bytes.NewReader(body)), + ContentLength: int64(len(body)), + Request: request, + } +} + +// hangUntilCancelled answers nothing until the request's context ends. +func hangUntilCancelled(request *http.Request) (*http.Response, error) { + <-request.Context().Done() + return nil, request.Context().Err() +} + +// commandDownloadHarness installs the download fixture plugin pinning digest, with its archive +// hosts answered by server. It returns the harness and the installer's managed directory. +func commandDownloadHarness(t *testing.T, digest string, timeoutSeconds int, server *archiveServer) (*harness, string) { + t.Helper() + h := debugPluginHarness(t, commandDownloadPluginID, commandDownloadManifest(t, digest, timeoutSeconds), false) + h.app.plugins.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: server}) + root, err := h.app.plugins.Commands.InstallDirectory(commandDownloadPluginID, "fixture-lldb") + if err != nil { + t.Fatal(err) + } + return h, root +} + +// hostArchiveName is the file name of the fixture archive for this machine's platform. +func hostArchiveName() string { + platform := pluginservice.ArchivePlatform() + return fmt.Sprintf("lithe-fixture-lldb-%s-%s.zip", platform.OS, platform.Arch) +} + +func TestCommandDownloadOfferShowsTheArchiveWithoutFetchingIt(t *testing.T) { + archive := adapterArchive(t) + server := &archiveServer{body: archive} + h, root := commandDownloadHarness(t, sha256Hex(archive), 900, server) + installs := settingsCommandInstalls{app: h.app} + ctx := commandInstallContext(t) + + missing, err := installs.Missing(ctx, commandDownloadPluginID) + if err != nil { + t.Fatal(err) + } + // A download runs no tool, so the card names none. + expectedMissing := []settingswindow.MissingCommand{{Kind: settingswindow.CapabilityDebugger, ID: "fixture", Commands: []string{commandDownloadCommand}, Installer: "fixture-lldb"}} + if !reflect.DeepEqual(missing, expectedMissing) { + t.Fatalf("missing = %+v\nwant %+v", missing, expectedMissing) + } + + offer, err := installs.Offer(ctx, commandDownloadPluginID, "fixture-lldb") + if err != nil { + t.Fatal(err) + } + expected := settingswindow.CommandInstallOffer{ + Installer: "fixture-lldb", + Commands: []string{commandDownloadCommand}, + MayUseNetwork: true, + Timeout: 900 * time.Second, + Download: &settingswindow.CommandInstallDownload{ + Version: "1.2.3", + URL: "https://downloads.example.org/lldb/1.2.3/" + hostArchiveName(), + Mirrors: []string{"https://mirror.example.net/lldb/1.2.3/" + hostArchiveName()}, + SHA256: sha256Hex(archive), + }, + Targets: []settingswindow.CommandInstallTarget{{Target: core.CommandInstallManaged, Directory: root}}, + } + if !reflect.DeepEqual(offer, expected) { + t.Fatalf("offer = %+v\nwant %+v", offer, expected) + } + // The offer is read before the user agrees: nothing is fetched and nothing is created. + if requests := server.seen(); len(requests) != 0 { + t.Fatalf("the offer sent %q", requests) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the offer created the install directory: %v", err) + } +} + +// downloadProgress collects an installation's progress. +type downloadProgress struct { + mu sync.Mutex + phases []string +} + +func (p *downloadProgress) add(progress pluginruntime.Progress) { + p.mu.Lock() + defer p.mu.Unlock() + p.phases = append(p.phases, progress.Phase) +} + +func (p *downloadProgress) all() []string { + p.mu.Lock() + defer p.mu.Unlock() + return slices.Clone(p.phases) +} + +func TestCommandDownloadExtractsAndRecordsWhereLaterLaunchesFindTheCommand(t *testing.T) { + archive := adapterArchive(t) + server := &archiveServer{body: archive} + h, root := commandDownloadHarness(t, sha256Hex(archive), 900, server) + installs := settingsCommandInstalls{app: h.app} + ctx := commandInstallContext(t) + // What the archive of a version pinned before an update left behind. + stale := filepath.Join(root, "0123456789abcdef") + if err := os.MkdirAll(filepath.Join(stale, "install-old", "extension", "adapter"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(stale, "archive"), []byte("older archive"), 0o600); err != nil { + t.Fatal(err) + } + + var progress downloadProgress + directory, err := installs.Install(ctx, commandDownloadPluginID, "fixture-lldb", core.CommandInstallManaged, func(line string) { + t.Errorf("a download printed %q", line) + }, progress.add) + if err != nil { + t.Fatal(err) + } + relative, err := filepath.Rel(root, directory) + if err != nil || !filepath.IsLocal(relative) || filepath.Base(directory) != "adapter" || filepath.Base(filepath.Dir(directory)) != "extension" { + t.Fatalf("installed into %q, want extension/adapter below %q", directory, root) + } + if !slices.Contains(progress.all(), "downloading") { + t.Fatalf("progress = %q, want the transfer", progress.all()) + } + // Only the extraction that was just recorded is kept. + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || !strings.HasPrefix(relative, entries[0].Name()+string(filepath.Separator)) { + t.Fatalf("the install directory holds %v, want only the extraction of %s", entries, relative) + } + installations := h.app.plugins.Commands.Installations(commandDownloadPluginID) + if !reflect.DeepEqual(installations, []pluginhost.CommandInstallation{{Installer: "fixture-lldb", Target: core.CommandInstallManaged, Directory: directory}}) { + t.Fatalf("recorded %+v", installations) + } + command, err := h.app.plugins.Backend.ResolveCommand(commandDownloadPluginID, []string{commandDownloadCommand}) + if err != nil || filepath.Dir(command) != directory { + t.Fatalf("debug adapter command = %q, %v", command, err) + } + missing, err := installs.Missing(ctx, commandDownloadPluginID) + if err != nil { + t.Fatal(err) + } + if len(missing) != 0 { + t.Fatalf("still missing after the install: %+v", missing) + } + gets := func() int { + count := 0 + for _, request := range server.seen() { + if strings.HasPrefix(request, http.MethodGet+" ") { + count++ + } + } + return count + } + if n := gets(); n != 1 { + t.Fatalf("the archive was fetched %d times", n) + } + + // The extraction in place still holds the command, so installing again fetches nothing. + sent := len(server.seen()) + again, err := installs.Install(ctx, commandDownloadPluginID, "fixture-lldb", core.CommandInstallManaged, func(string) {}, nil) + if err != nil || again != directory { + t.Fatalf("second Install = %q, %v; want %q", again, err, directory) + } + if requests := server.seen(); len(requests) != sent { + t.Fatalf("the second install sent %q", requests[sent:]) + } +} + +func TestCommandDownloadReportsWhyTheCommandsDidNotLand(t *testing.T) { + adapter := adapterArchive(t) + withoutCommand := fixtureZip(t, map[string]os.FileMode{"extension/adapter/other": 0o755}) + escaping := fixtureZip(t, map[string]os.FileMode{"../escaped": 0o644}) + for _, test := range []struct { + name string + digest string + server *archiveServer + check func(t *testing.T, failure *pluginhost.CommandInstallError) + }{ + {"digest differs", sha256Hex(adapter), &archiveServer{body: append(slices.Clone(adapter), 0)}, func(t *testing.T, failure *pluginhost.CommandInstallError) { + if failure.Code != pluginhost.CommandInstallChecksumMismatchCode || !errors.Is(failure, marketplace.ErrArchiveChecksum) { + t.Fatalf("failure = %+v", failure) + } + }}, + {"not served", sha256Hex(adapter), &archiveServer{serve: func(request *http.Request) (*http.Response, error) { + return archiveResponse(request, http.StatusNotFound, nil), nil + }}, func(t *testing.T, failure *pluginhost.CommandInstallError) { + if failure.Code != pluginhost.CommandInstallDownloadFailedCode || !errors.Is(failure, pluginruntime.ErrDownload) { + t.Fatalf("failure = %+v", failure) + } + }}, + {"command not in the archive", sha256Hex(withoutCommand), &archiveServer{body: withoutCommand}, func(t *testing.T, failure *pluginhost.CommandInstallError) { + // The extraction is discarded, so the failure names the place in the archive. + location := path.Join(hostArchiveName(), "extension/adapter") + if failure.Code != pluginhost.CommandInstallCommandsMissingCode || failure.Directory != location || + !reflect.DeepEqual(failure.Commands, []string{commandDownloadCommand}) { + t.Fatalf("failure = %+v, want %s missing from %s", failure, commandDownloadCommand, location) + } + }}, + {"entry outside the archive", sha256Hex(escaping), &archiveServer{body: escaping}, func(t *testing.T, failure *pluginhost.CommandInstallError) { + if failure.Code != pluginhost.CommandInstallArchiveInvalidCode || !errors.Is(failure, pluginruntime.ErrArchive) { + t.Fatalf("failure = %+v", failure) + } + }}, + } { + t.Run(test.name, func(t *testing.T) { + h, root := commandDownloadHarness(t, test.digest, 900, test.server) + logger := &treeRecordingLog{} + h.app.logSink = logger + installs := settingsCommandInstalls{app: h.app} + installed, err := installs.Install(commandInstallContext(t), commandDownloadPluginID, "fixture-lldb", core.CommandInstallManaged, func(string) {}, nil) + var failure *pluginhost.CommandInstallError + if !errors.As(err, &failure) { + t.Fatalf("Install = %q, %v; want a CommandInstallError", installed, err) + } + test.check(t, failure) + if installations := h.app.plugins.Commands.Installations(commandDownloadPluginID); len(installations) != 0 { + t.Fatalf("a failed installation was recorded: %+v", installations) + } + // Nothing the archive names lands anywhere in the plugin's command directories. + if err := filepath.WalkDir(filepath.Dir(root), func(name string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.Name() == "escaped" { + t.Errorf("the archive wrote %s", name) + } + return nil + }); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + // 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 TestCommandDownloadStopsWhenCancelled(t *testing.T) { + ctx, cancel := context.WithCancel(commandInstallContext(t)) + defer cancel() + // The archive hosts answer nothing; cancelling once the first request arrives stops the + // installation mid-transfer. + server := &archiveServer{serve: func(request *http.Request) (*http.Response, error) { + cancel() + return hangUntilCancelled(request) + }} + archive := adapterArchive(t) + h, _ := commandDownloadHarness(t, sha256Hex(archive), 900, server) + logger := &treeRecordingLog{} + h.app.logSink = logger + installs := settingsCommandInstalls{app: h.app} + if _, err := installs.Install(ctx, commandDownloadPluginID, "fixture-lldb", core.CommandInstallManaged, func(string) {}, nil); !errors.Is(err, context.Canceled) { + t.Fatalf("Install = %v, want the cancel", err) + } + if installations := h.app.plugins.Commands.Installations(commandDownloadPluginID); 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 TestCommandDownloadEndsAtItsTimeout(t *testing.T) { + archive := adapterArchive(t) + h, _ := commandDownloadHarness(t, sha256Hex(archive), 1, &archiveServer{serve: hangUntilCancelled}) + installs := settingsCommandInstalls{app: h.app} + _, err := installs.Install(commandInstallContext(t), commandDownloadPluginID, "fixture-lldb", core.CommandInstallManaged, func(string) {}, nil) + var failure *pluginhost.CommandInstallError + if !errors.As(err, &failure) || failure.Code != pluginhost.CommandInstallTimedOutCode || failure.Timeout != time.Second { + t.Fatalf("Install = %v, want the one-second timeout", err) + } + if installations := h.app.plugins.Commands.Installations(commandDownloadPluginID); len(installations) != 0 { + t.Fatalf("a timed-out installation was recorded: %+v", installations) + } +} diff --git a/desktop/internal/workbench/command_installers.go b/desktop/internal/workbench/command_installers.go index 1f41b5e4e..b9afa54be 100644 --- a/desktop/internal/workbench/command_installers.go +++ b/desktop/internal/workbench/command_installers.go @@ -5,8 +5,11 @@ import ( "encoding/json" "errors" "fmt" + "net/url" "os" "os/exec" + "path" + "path/filepath" "slices" "sort" "strings" @@ -17,8 +20,11 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" "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/pluginmanager" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" ) @@ -38,10 +44,18 @@ 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. +// Core expands every installer, selects a download's archive and names the directories; the +// host resolves and runs a tool, or downloads, checks and extracts the archive, then checks +// that the commands landed and records where. type settingsCommandInstalls struct{ app *App } +// archivePlatform is the platform Core selects a download installer's archive for. It is +// passed on every call, so an installer without an archive for this host is never offered. +func archivePlatform() *core.CommandArchivePlatform { + platform := pluginservice.ArchivePlatform() + return &platform +} + var _ settingswindow.CommandInstaller = settingsCommandInstalls{} // manifest reads the manifest of the enabled plugin pluginID. @@ -82,7 +96,7 @@ func (s settingsCommandInstalls) Missing(ctx context.Context, pluginID string) ( if err != nil { return nil, err } - requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest) + requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest, archivePlatform()) if err != nil { return nil, err } @@ -112,10 +126,13 @@ func (s settingsCommandInstalls) Missing(ctx context.Context, pluginID string) ( entry.ID = *consumer.ID } if installer, ok := installers[installerID]; ok { - if tools == nil { - tools = s.toolNames(ctx) + entry.Installer = installer.ID + if installer.Tool != nil { + if tools == nil { + tools = s.toolNames(ctx) + } + entry.Tool = toolName(tools, *installer.Tool) } - entry.Installer, entry.Tool = installer.ID, toolName(tools, installer.Tool) } missing = append(missing, entry) } @@ -180,7 +197,8 @@ 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. +// target's directory probes to find where it would install. A download installer has no tool: +// its offer names the archive Core selected for this host. 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. @@ -191,10 +209,13 @@ func (s settingsCommandInstalls) Offer(ctx context.Context, pluginID, installerI return settingswindow.CommandInstallOffer{}, err } defer session.close() + if session.installer.Download != nil { + return session.downloadOffer(ctx) + } offer := settingswindow.CommandInstallOffer{ Installer: installerID, Commands: session.installer.Commands, - Tool: toolName(s.toolNames(ctx), session.installer.Tool), + Tool: toolName(s.toolNames(ctx), session.installer.ToolID()), Executable: session.selection.Executable, MayUseNetwork: session.installer.MayUseNetwork, } @@ -216,6 +237,26 @@ func (s settingsCommandInstalls) Offer(ctx context.Context, pluginID, installerI return offer, nil } +// downloadOffer is the offer of a download installer: the archive's version, URL and digest, +// and the managed directory it extracts below, its only target. +func (s *commandInstallSession) downloadOffer(ctx context.Context) (settingswindow.CommandInstallOffer, error) { + prepared, err := s.prepare(ctx, core.CommandInstallManaged) + if err != nil { + return settingswindow.CommandInstallOffer{}, err + } + download := prepared.plan.Download + return settingswindow.CommandInstallOffer{ + Installer: s.installer.ID, + Commands: s.installer.Commands, + MayUseNetwork: s.installer.MayUseNetwork, + Timeout: prepared.timeout(), + Download: &settingswindow.CommandInstallDownload{ + Version: download.Version, URL: download.URL, Mirrors: download.Mirrors, SHA256: download.SHA256, + }, + Targets: []settingswindow.CommandInstallTarget{{Target: core.CommandInstallManaged, Directory: prepared.directory}}, + }, 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)) @@ -227,23 +268,24 @@ 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, err error) { +// plugin's later launches find them. A tool's output goes to output; a download reports its +// phases to progress. 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), progress func(pluginruntime.Progress)) (_ 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) + directory, stage, err := s.install(ctx, pluginID, installerID, target, output, progress) 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) { +func (s settingsCommandInstalls) install(ctx context.Context, pluginID, installerID, target string, output func(string), progress func(pluginruntime.Progress)) (string, core.PluginStage, error) { session, stage, err := s.open(ctx, pluginID, installerID) if err != nil { return "", stage, err @@ -256,6 +298,9 @@ func (s settingsCommandInstalls) install(ctx context.Context, pluginID, installe if err != nil { return "", core.StagePlan, err } + if prepared.plan.Download != nil { + return session.download(ctx, prepared, progress) + } if prepared.directory == "" { return "", core.StagePlan, fmt.Errorf("no directory probe of installer %s named where it installs", installerID) } @@ -312,15 +357,122 @@ func (s settingsCommandInstalls) install(ctx context.Context, pluginID, installe return prepared.directory, "", nil } +// download fetches the archive of a download plan, checks its pinned SHA-256 and extracts it +// below the installer's managed directory, then checks that every command is in the plan's +// command directory there and records it. pluginruntime.Manager does the transfer and the +// extraction, the same as for managed runtimes: an extraction already in place that still +// holds the commands is used as it is, and a damaged one is replaced. +func (s *commandInstallSession) download(ctx context.Context, prepared preparedCommandInstall, progress func(pluginruntime.Progress)) (string, core.PluginStage, error) { + plan, download := prepared.plan, prepared.plan.Download + commandDirectory := func(installation pluginruntime.Installation) string { + return filepath.Join(installation.Home, filepath.FromSlash(download.CommandDirectory)) + } + timeout := prepared.timeout() + run, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + manager := pluginruntime.Manager{Root: prepared.installDirectory, Downloader: s.app.plugins.RuntimeDownloader} + installation, err := manager.Prepare(run, pluginruntime.Artifact{ + ID: strings.Join(plan.Commands, ", "), + Version: download.Version, + CacheKey: download.CacheKey, + URL: download.URL, + Mirrors: download.Mirrors, + SHA256: download.SHA256, + Archive: download.Archive, + StripPrefix: download.StripPrefix, + }, func(_ context.Context, installation pluginruntime.Installation) error { + directory := commandDirectory(installation) + var absent []string + for _, command := range plan.Commands { + if _, err := pluginhost.CommandInDirectory(directory, command); err != nil { + absent = append(absent, command) + } + } + if len(absent) > 0 { + // The extraction that lacks them is discarded, so the failure names where in the + // archive they were looked for. + return &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallCommandsMissingCode, Commands: absent, Directory: archiveLocation(download)} + } + return nil + }, progress) + if err != nil { + stage, err := downloadFailure(ctx, run, timeout, err) + return "", stage, err + } + directory := commandDirectory(installation) + // 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(s.pluginID, pluginhost.CommandInstallation{Installer: s.installer.ID, Target: core.CommandInstallManaged, Directory: directory}); err != nil { + return "", core.StageDecode, err + } + if err := removeOtherExtractions(prepared.installDirectory, download.CacheKey); err != nil { + s.app.backgroundFailedIn(ctx, "plugin_command_download_cleanup", err) + } + return directory, "", nil +} + +// removeOtherExtractions removes what earlier archives of an installer left in its managed +// directory root, every entry but keep's: the archive and extraction of a version the plugin +// pinned before an update, which no record names any more. An entry that cannot go, such as +// an adapter of the old version still running on Windows, stays for the next installation to +// remove; the installation that just finished does not depend on it. +func removeOtherExtractions(root, keep string) error { + entries, err := os.ReadDir(root) + if err != nil { + return err + } + var failures []error + for _, entry := range entries { + if entry.Name() != keep { + failures = append(failures, os.RemoveAll(filepath.Join(root, entry.Name()))) + } + } + return errors.Join(failures...) +} + +// archiveLocation is a download's command directory inside its archive, after the archive's +// file name: tool-1.2.3-darwin-arm64.zip/extension/bin. +func archiveLocation(download *core.CommandInstallDownload) string { + name := download.URL + if parsed, err := url.Parse(download.URL); err == nil && path.Base(parsed.Path) != "/" && path.Base(parsed.Path) != "." { + name = path.Base(parsed.Path) + } + return path.Join(name, download.StripPrefix, download.CommandDirectory) +} + +// downloadFailure is the stage and the contract code of a download installation that failed +// with err. run is the installation's context, bounded by timeout within ctx, the user's. +func downloadFailure(ctx, run context.Context, timeout time.Duration, err error) (core.PluginStage, error) { + var installErr *pluginhost.CommandInstallError + switch { + case ctx.Err() != nil: + // The user cancelled, which is never recorded. + return core.StageExit, ctx.Err() + case run.Err() != nil: + // A stalled transfer also ends with a deadline, so the installation's own context + // decides whether its time ran out. + return core.StageTimeout, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallTimedOutCode, Timeout: timeout} + case errors.As(err, &installErr): + return core.StageDecode, installErr + case errors.Is(err, marketplace.ErrArchiveChecksum): + return core.StageResolve, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallChecksumMismatchCode, Err: err} + case errors.Is(err, pluginruntime.ErrDownload): + return core.StageResolve, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallDownloadFailedCode, Err: err} + case errors.Is(err, pluginruntime.ErrArchive): + return core.StageDecode, &pluginhost.CommandInstallError{Code: pluginhost.CommandInstallArchiveInvalidCode, Err: err} + } + return core.StageDecode, err +} + // commandInstallSession is one installer with its tool resolved, for an offer or an -// installation. +// installation. A download installer has no tool, so nothing is resolved for it. 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. + // what it installs; close removes it. Empty for a download installer. directory string selection core.ToolchainSelection } @@ -333,7 +485,7 @@ func (s settingsCommandInstalls) open(ctx context.Context, pluginID, installerID if err != nil { return nil, core.StagePlan, err } - requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest) + requirements, err := s.app.kernel.CommandInstallerRequirements(ctx, manifest, archivePlatform()) if err != nil { return nil, core.StagePlan, err } @@ -341,11 +493,15 @@ func (s settingsCommandInstalls) open(ctx context.Context, pluginID, installerID if index < 0 { return nil, core.StagePlan, fmt.Errorf("plugin %s declares no installer %s", pluginID, installerID) } + installer := requirements.Installers[index] + if installer.Download != nil || installer.Tool == nil { + return &commandInstallSession{app: s.app, pluginID: pluginID, manifest: manifest, installer: installer}, "", nil + } 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} + session := &commandInstallSession{app: s.app, pluginID: pluginID, manifest: manifest, installer: installer, directory: directory} root := directory if current := s.app.toolchainRoot.Load(); current != nil { root = *current @@ -354,7 +510,7 @@ func (s settingsCommandInstalls) open(ctx context.Context, pluginID, installerID if session.installer.MinimumVersion != nil { minimumVersion = *session.installer.MinimumVersion } - session.selection, err = s.app.resolveToolchainSelection(ctx, root, ".", session.installer.Tool, minimumVersion) + session.selection, err = s.app.resolveToolchainSelection(ctx, root, ".", *session.installer.Tool, minimumVersion) if err != nil { session.close() return nil, core.StageResolve, err @@ -374,7 +530,9 @@ type preparedCommandInstall struct { // 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 is where the commands land; empty when no directory probe named one. For a + // download it is installDirectory, below which the archive's extraction gets a directory + // of its own. directory string } @@ -383,7 +541,8 @@ func (p preparedCommandInstall) timeout() time.Duration { } // prepare has Core expand target: a managed one into the plugin's install directory, a -// toolDefault one with the directory its probes name. +// toolDefault one with the directory its probes name. A download is planned for this host's +// platform without a directory; the host extracts it below the install directory itself. func (s *commandInstallSession) prepare(ctx context.Context, target string) (preparedCommandInstall, error) { kernel := s.app.kernel switch target { @@ -392,13 +551,26 @@ func (s *commandInstallSession) prepare(ctx context.Context, target string) (pre if err != nil { return preparedCommandInstall{}, err } - plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, installDirectory) + if s.installer.Download != nil { + plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, "", archivePlatform()) + if err != nil { + return preparedCommandInstall{}, err + } + if plan.Download == nil { + return preparedCommandInstall{}, fmt.Errorf("installer %s was planned without its download", s.installer.ID) + } + return preparedCommandInstall{plan: plan, installDirectory: installDirectory, directory: installDirectory}, nil + } + plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, installDirectory, archivePlatform()) if err != nil { return preparedCommandInstall{}, err } + if plan.CommandDirectory == nil { + return preparedCommandInstall{}, fmt.Errorf("installer %s was planned without its command directory", s.installer.ID) + } return preparedCommandInstall{plan: plan, installDirectory: installDirectory, directory: *plan.CommandDirectory}, nil case core.CommandInstallToolDefault: - plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, "") + plan, err := kernel.PlanCommandInstaller(ctx, s.manifest, s.installer.ID, target, "", archivePlatform()) if err != nil { return preparedCommandInstall{}, err } diff --git a/desktop/internal/workbench/command_installers_test.go b/desktop/internal/workbench/command_installers_test.go index 166f795cf..633386024 100644 --- a/desktop/internal/workbench/command_installers_test.go +++ b/desktop/internal/workbench/command_installers_test.go @@ -302,7 +302,7 @@ func TestCommandInstallManagedRecordsWhereLaterLaunchesFindTheCommand(t *testing t.Setenv(name, private) } var output commandOutput - directory, err := installs.Install(ctx, commandInstallerPluginID, "fixture-ls", core.CommandInstallManaged, output.add) + directory, err := installs.Install(ctx, commandInstallerPluginID, "fixture-ls", core.CommandInstallManaged, output.add, nil) if err != nil { t.Fatal(err) } @@ -342,7 +342,7 @@ func TestCommandInstallManagedRecordsWhereLaterLaunchesFindTheCommand(t *testing 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) {}) + directory, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, "fixture-ls", core.CommandInstallToolDefault, func(string) {}, nil) if err != nil { t.Fatal(err) } @@ -386,7 +386,7 @@ func TestCommandInstallReportsWhyTheCommandsDidNotLand(t *testing.T) { if err != nil { t.Fatal(err) } - installed, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, test.installer, core.CommandInstallManaged, func(string) {}) + installed, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, test.installer, core.CommandInstallManaged, func(string) {}, nil) var failure *pluginhost.CommandInstallError if !errors.As(err, &failure) { t.Fatalf("Install = %q, %v; want a CommandInstallError", installed, err) @@ -418,7 +418,7 @@ func TestCommandInstallStopsTheToolWhenCancelled(t *testing.T) { if line == "fixture: downloading" { cancel() } - }) + }, nil) if !errors.Is(err, context.Canceled) { t.Fatalf("Install = %v, want the cancel", err) } @@ -434,7 +434,7 @@ func TestCommandInstallStopsTheToolWhenCancelled(t *testing.T) { 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 { + if _, err := installs.Install(commandInstallContext(t), commandInstallerPluginID, "fixture-dap", core.CommandInstallToolDefault, func(string) {}, nil); err == nil { t.Fatal("installed into a target the installer does not declare") } if _, err := installs.Offer(commandInstallContext(t), commandInstallerPluginID, "absent"); err == nil { diff --git a/docs/assets/command-installer-downloads/download-dialog-dark.png b/docs/assets/command-installer-downloads/download-dialog-dark.png new file mode 100644 index 000000000..f74d768f3 Binary files /dev/null and b/docs/assets/command-installer-downloads/download-dialog-dark.png differ diff --git a/docs/assets/command-installer-downloads/download-dialog-light.png b/docs/assets/command-installer-downloads/download-dialog-light.png new file mode 100644 index 000000000..22ce472ff Binary files /dev/null and b/docs/assets/command-installer-downloads/download-dialog-light.png differ diff --git a/docs/assets/command-installer-downloads/download-progress-dark.png b/docs/assets/command-installer-downloads/download-progress-dark.png new file mode 100644 index 000000000..ea7d04e17 Binary files /dev/null and b/docs/assets/command-installer-downloads/download-progress-dark.png differ diff --git a/docs/assets/command-installer-downloads/download-progress-light.png b/docs/assets/command-installer-downloads/download-progress-light.png new file mode 100644 index 000000000..bdd243b26 Binary files /dev/null and b/docs/assets/command-installer-downloads/download-progress-light.png differ diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 74c74548c..7477fe561 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -260,6 +260,16 @@ Provider 状态经平台 adapter 写 Application Support;插件安装目录和 路径和链接不能逃出解压根。相关边界见 [受管插件运行时](../.agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md)。 +插件用 `commandInstallers` 声明的下载安装器(`requires.commandInstallers: 1`,权限 `commands.install`) +在用户点击安装并确认后,才下载插件固定地址和 SHA-256 的压缩包。结果位于 +`/.state//commands///`,布局与上面的受管运行时相同 +(`archive`、`install-/`、`ready.json`、`.lock`),大小和路径上限也相同; +命令所在目录记录在 `/.state//commands.json`。缓存键由 Core 按压缩包内容身份 +(地址、版本、平台、校验值、格式和目录)生成,镜像不参与。记录新缓存键后,宿主删除同一安装器下的其他缓存键目录; +删不掉的留到下次安装。卸载插件时随插件状态一起删除。它是用户运行时状态,不是工作树构建输入, +不跨工作树复制或共享,也不写插件包、app bundle 或 Windows 安装目录。决策见 +[插件声明的命令缺失时由宿主安装](../.agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md)。 + 插件网页的宿主持久状态(Viva 的 `pluginservice.SetPageState`)写到每用户插件根目录 (`pluginpkg.DefaultRoot`)下的 `/.state//pages/workspaces//.json`, diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 8eee1390d..5bbb4f781 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);新增 `commandInstallers:0`:插件声明用哪个已注入工具安装 `systemCommand` 启动缺的命令,Core 校验并展开(`plugins.commandInstallers.requirements/plan/defaultDirectory`),宿主在能力卡片显示缺失与安装按钮,用户选择 Lithe 管理的目录或工具默认位置后运行并记录(权限 `commands.install`,Viva 桌面端);通用 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 桌面端);`commandInstallers:1` 增加下载安装器:插件为每个平台固定压缩包地址和 SHA-256,宿主确认后复用受管运行时的下载、校验、解压实现装进受管目录(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 绑定到普通插件函数,语言服务器优先、插件只补充;标准 LSP 的 Code Actions、签名帮助和内联提示由 Viva 编辑器呈现(#2128)。自定义插件 Provider 的符号、格式化、重命名、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/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 6fa7101d0..8251da522 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -293,7 +293,8 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Lithe-core-rust main at d630938 (#130 squash-merged): companion marketplace recommendations # contract, resolveSource.recommendationsURL, and plugins.marketplace.recommendForWorkspace (#2228). # Core #132, merged into main: reviewed-tip force deletion and first-primary-click selection. -PINNED_CORE_REVISION="4ef9d9e0ad1c28d195242d9e8986da151bcc50c2" +# Core #133, merged into main: commandInstallers 1 pinned archive downloads (API-23). +PINNED_CORE_REVISION="72036de379e4a71bb995c81a8f574859937bc616" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/features/command-installer-downloads.json b/shared/i18n/features/command-installer-downloads.json new file mode 100644 index 000000000..65c5bbb1e --- /dev/null +++ b/shared/i18n/features/command-installer-downloads.json @@ -0,0 +1,93 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.plugins.commandInstallDownloadPrompt", + "description": "First line of the install dialog for an installer that downloads a pinned archive; commands are the commands it provides, version the pinned version", + "platforms": [ + "desktop" + ], + "parameters": { + "commands": "string", + "version": "string" + } + }, + { + "id": "desktop.plugins.commandInstallDownloadNetwork", + "description": "Note in the install dialog of a download installer: the archive is checked against the pinned digest before it is extracted", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallSource", + "description": "Heading of the download address and digest in the install dialog of a download installer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallMirror", + "description": "Label before one fallback address of the archive in the install dialog; the address follows in a monospaced font", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallDigest", + "description": "Label before the SHA-256 digest the downloaded archive must have in the install dialog; the hexadecimal digest follows in a monospaced font", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallDownloadFailed", + "description": "Install dialog when the archive could not be downloaded from any address; reason is the underlying error, not translated", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.plugins.commandInstallChecksumMismatch", + "description": "Install dialog when the downloaded archive's SHA-256 differs from the pinned one", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.plugins.commandInstallArchiveInvalid", + "description": "Install dialog when the downloaded archive could not be extracted safely; reason is the underlying error, not translated", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + } + ], + "locales": { + "en-US": { + "desktop.plugins.commandInstallDownloadPrompt": "{commands} {version} will be downloaded and extracted.", + "desktop.plugins.commandInstallDownloadNetwork": "The archive is downloaded from the address below and installed only if its SHA-256 matches the one the plugin pins.", + "desktop.plugins.commandInstallSource": "Download from", + "desktop.plugins.commandInstallMirror": "Mirror", + "desktop.plugins.commandInstallDigest": "SHA-256", + "desktop.plugins.commandInstallDownloadFailed": "Could not download the archive: {reason}", + "desktop.plugins.commandInstallChecksumMismatch": "The downloaded archive does not match the SHA-256 the plugin pins. It was discarded without being installed.", + "desktop.plugins.commandInstallArchiveInvalid": "Could not extract the archive: {reason}" + }, + "zh-CN": { + "desktop.plugins.commandInstallDownloadPrompt": "将下载并解压 {commands} {version}。", + "desktop.plugins.commandInstallDownloadNetwork": "将从下面的地址下载压缩包,SHA-256 与插件固定的值一致才会安装。", + "desktop.plugins.commandInstallSource": "下载地址", + "desktop.plugins.commandInstallMirror": "镜像", + "desktop.plugins.commandInstallDigest": "SHA-256", + "desktop.plugins.commandInstallDownloadFailed": "无法下载压缩包:{reason}", + "desktop.plugins.commandInstallChecksumMismatch": "下载的压缩包与插件固定的 SHA-256 不一致,已丢弃,没有安装。", + "desktop.plugins.commandInstallArchiveInvalid": "无法解压压缩包:{reason}" + } + } +} diff --git a/shared/platform-feature-matrix/features/plugin-command-installers.json b/shared/platform-feature-matrix/features/plugin-command-installers.json index 1e5eeeb8a..cd074a0ce 100644 --- a/shared/platform-feature-matrix/features/plugin-command-installers.json +++ b/shared/platform-feature-matrix/features/plugin-command-installers.json @@ -2,7 +2,7 @@ "id": "plugin-command-installers", "area": "插件", "group": "插件管理", - "capability": "插件声明的命令缺失时由宿主安装:插件详情“功能”页的能力卡片检测语言服务器、构建、版本控制和调试适配器用到的本机命令,缺失时显示“未找到”和安装按钮;没有卡片的后端命令显示在横幅里。插件用 commandInstallers 声明由哪个已注入的工具安装哪些命令;宿主经 Core 校验并展开为安装计划,用户在对话框里选择 Lithe 管理的目录或工具的默认位置,看清将要运行的命令、环境变量和是否联网后确认,安装输出实时显示,可取消,超时停止;装好后后续启动在记录的目录里找到命令。命令缺失、安装失败、超时和命令没有落到目录都显示本地化原因", + "capability": "插件声明的命令缺失时由宿主安装:插件详情“功能”页的能力卡片检测语言服务器、构建、版本控制和调试适配器用到的本机命令,缺失时显示“未找到”和安装按钮;没有卡片的后端命令显示在横幅里。插件用 commandInstallers 声明由哪个已注入的工具安装哪些命令;宿主经 Core 校验并展开为安装计划,用户在对话框里选择 Lithe 管理的目录或工具的默认位置,看清将要运行的命令、环境变量和是否联网后确认,安装输出实时显示,可取消,超时停止;装好后后续启动在记录的目录里找到命令。命令只以压缩包发布时,插件声明下载安装器:对话框显示每个平台固定的下载地址、镜像和 SHA-256,确认后下载并显示进度,校验通过才解压到 Lithe 管理的目录,插件升级换了压缩包后删除旧版本。命令缺失、安装失败、超时、命令没有落到目录、下载失败、校验值不符和压缩包无效都显示本地化原因", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -14,6 +14,8 @@ "desktop/internal/pluginhost/launch.go", "desktop/internal/workbench/command_installers.go", "desktop/internal/workbench/command_installers_test.go", + "desktop/internal/workbench/command_downloads_test.go", + "desktop/internal/pluginruntime/runtime.go", "desktop/internal/settingswindow/command_install.go", "desktop/internal/settingswindow/command_install_test.go", "desktop/internal/settingswindow/command_install_visual_test.go", @@ -29,12 +31,14 @@ "desktop/internal/pluginhost/launch.go", "desktop/internal/workbench/command_installers.go", "desktop/internal/workbench/command_installers_test.go", + "desktop/internal/workbench/command_downloads_test.go", + "desktop/internal/pluginruntime/runtime.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 展开的计划。" + "verification": "宿主测试只用合成插件 dev.lithe.test.command-installers(安装工具是复制出来的测试二进制,不联网):缺失检测按语言服务器、调试适配器和后端分别报告;安装计划展开两个目标,打开对话框不创建目录;managed 目标装进插件根目录 .state 下的受管目录并记录,之后 Backend.ResolveCommand 找到命令;toolDefault 目标按工具默认位置探测并记录该目录;非零退出、命令没写出来、超过超时各报对应原因;取消会停止工具且不留记录;插件没有声明的目标被拒绝。下载安装器用合成插件 dev.lithe.test.command-downloads 和假的 HTTP 传输(不联网):打开对话框不发请求、不建目录;下载解压后记录并能找到命令,旧缓存键被删除,再次安装不再下载;校验值不符、下载失败、命令不在压缩包里、条目逃出解压根各报对应原因且不留记录;取消不写失败日志;超时停止。设置窗口测试覆盖卡片状态、横幅、对话框内容(含下载地址、镜像、SHA-256 和下载进度)、安装输出、完成后卡片清除和取消。可视化证据:-tags 'vivahead lithevisual' 运行 TestVisualCommandInstall 生成深浅主题的卡片、对话框、下载对话框和下载进度截图。macOS 真机:安装一个声明 commandInstallers 的插件,在缺少命令的机器上打开设置 → 插件 → 已安装 → 功能,确认卡片显示“未找到”与安装按钮;分别选择两个安装位置完成安装,确认之后启动语言服务器或调试不再报命令缺失;安装一个声明下载安装器的测试插件(清单固定一个本机可下载的压缩包),确认对话框显示地址和 SHA-256、下载有进度、装好后启动能找到命令;安装中取消、断网失败都显示原因;启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。Windows 真机:同样流程,命令文件带 .exe 后缀,PATH 类变量用分号分隔。", + "notes": "对应计划 API-23(工具链与受管进程)。宿主声明 commandInstallers 1(1 增加下载安装器,Lithe-core-rust#133);契约与计划展开在 Core(plugins.commandInstallers.requirements/plan/defaultDirectory)。下载安装器复用受管运行时的下载、校验和解压(pluginruntime.Manager.Prepare),结果在插件状态目录 commands/<安装器>/<缓存键>/。受管目录随插件卸载删除;toolDefault 只记录目录,不删除工具装进默认位置的文件。安装进程不经 shell,参数与环境来自 Core 展开的计划。" }