Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: Install RTK uses brew only when Homebrew has rtk's bottle, and keeps why it failed on the card (Scott__D on X)
yetone053d0d37f8fe
diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex 342505535..21cce8d6b 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -938,6 +938,10 @@ magpie.plugin("library", (ctx) => {? t("Installing RTK… this can take a minute."): t("RTK isn't installed. magpie can install it for you, or get it from its site.")));if (rtk.install) card.append(el("p", "lib-rtk-cmd", rtk.install));+ // why the last install failed stays on the card, beside Get RTK, not+ // only in a status line gone after ten seconds (Scott__D on X: the+ // install never succeeded, and nothing on the page said why)+ if (rtkInstallErr && !rtkInstalling) card.append(el("p", "lib-rtk-note lib-rtk-err lib-rtk-install-err", t("The install failed: {why}", { why: rtkInstallErr })));const acts = el("div", "lib-acts");if (rtk.install) {const ib = button(rtkInstalling ? t("Installing…") : t("Install RTK"), "action", installRTK);@@ -1110,14 +1114,16 @@ magpie.plugin("library", (ctx) => {rtkPathing = false;render();}- let rtkInstalling = false;+ let rtkInstalling = false, rtkInstallErr = "";async function installRTK() {rtkInstalling = true;+ rtkInstallErr = "";render();try {rtk = await api("library/rtk/install", {});status(t("RTK is installed — switch it on for your agents below"), "ok", 6000);} catch (e) {+ rtkInstallErr = e.message;status(e.message, "err", 10000);}rtkInstalling = false;diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex 2e83216f4..7247fbadd 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -152,6 +152,7 @@ magpie.strings({"RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run {cmd} in a terminal.": "RTK 是用 cargo 安装的,但 magpie 找不到 cargo 来升级它。请从 rustup.rs 安装 Rust,或在终端里运行 {cmd}。","RTK is now {v}": "RTK 已升级到 {v}","Running {cmd} — this can take a few minutes.": "正在运行 {cmd},可能需要几分钟。",+ "The install failed: {why}": "安装失败:{why}","The upgrade failed: {why}": "升级失败:{why}","RTK's upgrade failed — the RTK card says why": "RTK 升级失败,原因见 RTK 卡片","{saved} tokens saved over {n} commands — {pct}%": "{n} 条命令节省 {saved} token,省 {pct}%",@@ -785,6 +786,7 @@ magpie.strings({"RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run {cmd} in a terminal.": "RTK 是用 cargo 安裝的,但 magpie 找不到 cargo 來升級它。請從 rustup.rs 安裝 Rust,或在終端機裡執行 {cmd}。","RTK is now {v}": "RTK 已升級到 {v}","Running {cmd} — this can take a few minutes.": "正在執行 {cmd},可能需要幾分鐘。",+ "The install failed: {why}": "安裝失敗:{why}","The upgrade failed: {why}": "升級失敗:{why}","RTK's upgrade failed — the RTK card says why": "RTK 升級失敗,原因見 RTK 卡片","{saved} tokens saved over {n} commands — {pct}%": "{n} 條命令節省 {saved} token,省 {pct}%",@@ -1413,6 +1415,7 @@ magpie.strings({"RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run {cmd} in a terminal.": "RTK は cargo でインストールされていますが、magpie は更新に使う cargo を見つけられません。rustup.rs から Rust をインストールするか、ターミナルで {cmd} を実行してください。","RTK is now {v}": "RTK を {v} にしました","Running {cmd} — this can take a few minutes.": "{cmd} を実行中 — 数分かかることがあります。",+ "The install failed: {why}": "インストールに失敗しました:{why}","The upgrade failed: {why}": "アップグレードに失敗しました:{why}","RTK's upgrade failed — the RTK card says why": "RTK のアップグレードに失敗しました — 理由は RTK カードに表示されています","{saved} tokens saved over {n} commands — {pct}%": "{n} 件のコマンドで {saved} トークンを節約 — {pct}%",@@ -2044,6 +2047,7 @@ magpie.strings({"RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run {cmd} in a terminal.": "RTK wurde mit cargo installiert, aber magpie findet kein cargo, um es zu aktualisieren. Installieren Sie Rust von rustup.rs, oder führen Sie {cmd} in einem Terminal aus.","RTK is now {v}": "RTK ist jetzt auf {v}","Running {cmd} — this can take a few minutes.": "{cmd} läuft — das kann einige Minuten dauern.",+ "The install failed: {why}": "Die Installation ist fehlgeschlagen: {why}","The upgrade failed: {why}": "Das Upgrade ist fehlgeschlagen: {why}","RTK's upgrade failed — the RTK card says why": "Upgrade von RTK fehlgeschlagen — die RTK-Karte nennt den Grund","{saved} tokens saved over {n} commands — {pct}%": "{saved} Token bei {n} Befehlen gespart – {pct} %",diff --git a/internal/gui/tests/library-rtk-install.test.cjs b/internal/gui/tests/library-rtk-install.test.cjsnew file mode 100644index 000000000..3f41bdefc--- /dev/null+++ b/internal/gui/tests/library-rtk-install.test.cjs@@ -0,0 +1,115 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// Scott__D on X: Install RTK never succeeded. The page said "Installing+// RTK… this can take a minute." and, when the install failed, said why only+// in a status line gone after ten seconds. Now the button is held while the+// install runs, and once it fails the card keeps the reason beside Get RTK,+// with Install RTK to try again; a second try that works shows rtk+// installed and drops the reason. Every language, Chromium and WebKit, 1100+// and 420 wide, nothing sideways. No backend: the API is faked here.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const HOME = "/Users/aimer";+const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });+const lib = () => ({+ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,+ agents: [agent("claude", "Claude Code")],+ instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],+});+const script = "curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh";+const missing = () => ({ url: "https://www.rtk-ai.app", install: script, agents: [{ id: "claude", name: "Claude Code", icon: "", on: false }] });+const installed = () => ({ path: `${HOME}/.local/bin/rtk`, version: "1.1.0", url: "https://www.rtk-ai.app", agents: [{ id: "claude", name: "Claude Code", icon: "", on: false }] });+// InstallRTK's error for a failed script run (installFailed in rtk_upgrade.go)+const why = "RTK's install script failed (exit code 1) — [ERROR] Failed to download binary https://github.com/rtk-ai/rtk/releases/download/v1.1.0/rtk-aarch64-apple-darwin.tar.gz";++function server(lang, st) {+ return async (route) => {+ const req = route.request(), url = new URL(req.url());+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });+ if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });+ if (url.pathname === "/api/library") return route.fulfill({ json: lib() });+ if (url.pathname === "/api/library/rtk") return route.fulfill({ json: st.done ? installed() : missing() });+ if (url.pathname === "/api/library/rtk/install") {+ st.calls++;+ await st.hold; // the install runs until the test lets it end+ if (st.calls === 1) return route.fulfill({ status: 400, json: { error: why } });+ st.done = true;+ return route.fulfill({ json: installed() });+ }+ if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });+ if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });+ if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });+ if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await route.fulfill({ body: await fs.readFile(file), contentType });+ };+}++const LANGS = ["en", "zh", "zh-TW", "ja", "de"];+const failed = { en: "The install failed: ", zh: "安装失败:", "zh-TW": "安裝失敗:", ja: "インストールに失敗しました:", de: "Die Installation ist fehlgeschlagen: " };++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": a failed RTK install keeps its reason on the card, and Install RTK tries again", async (t) => {+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ const errors = [];+ t.after(async () => {+ if (errors.length) console.log(errors);+ await browser.close();+ });+ for (const lang of LANGS) for (const width of [1100, 420]) {+ await t.test(`${lang} ${width}`, async () => {+ let release;+ const st = { calls: 0, done: false, hold: new Promise((r) => { release = r; }) };+ const ctx = await browser.newContext({ viewport: { width, height: 800 } });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "rtk"); } catch {} });+ const page = await ctx.newPage();+ page.setDefaultTimeout(5000);+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", server(lang, st));+ await page.goto("http://magpie.test/");+ await page.locator('button[data-view="library"]').click();+ const v = page.locator("#view-library");+ const cmd = v.locator(".lib-rtk-cmd");+ await cmd.waitFor();+ assert.equal(await cmd.textContent(), script);+ const install = v.locator(".lib-acts button").first();+ assert.equal(await install.isDisabled(), false);+ const label = await install.textContent();++ // running: held, and no reason yet+ await install.click();+ await page.waitForFunction(() => document.querySelector("#view-library .lib-acts button")?.disabled);+ assert.equal(await v.locator(".lib-rtk-install-err").count(), 0);+ release();++ // failed: the reason stays on the card, and the button is back+ const err = v.locator(".lib-rtk-install-err");+ await err.waitFor();+ assert.equal(await err.textContent(), failed[lang] + why);+ await page.waitForFunction(() => !document.querySelector("#view-library .lib-acts button")?.disabled);+ assert.equal(await install.textContent(), label);+ const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert(sideways <= 0, `the page scrolls sideways by ${sideways}px`);+ // a re-render (Check again) keeps it+ await v.locator(".lib-acts button").last().click();+ await err.waitFor();++ // tried again, and it works: the reason is gone, rtk is shown installed+ await v.locator(".lib-acts button").first().click();+ await page.waitForFunction(() => !document.querySelector("#view-library .lib-rtk-cmd"));+ assert.equal(await v.locator(".lib-rtk-install-err").count(), 0);+ assert.equal(st.calls, 2);+ await ctx.close();+ });+ }+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/library/rtk.go b/internal/library/rtk.goindex d62179821..1e0fcb0f0 100644--- a/internal/library/rtk.go+++ b/internal/library/rtk.go@@ -970,8 +970,9 @@ func rtkInstall(bin string, a *agent.Agent) error {// rtkScript is rtk's own installer, which puts it in ~/.local/bin.const rtkScript = "https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh"-// rtkInstaller is how rtk is installed here: with Homebrew when there is-// one, winget on Windows, else rtk's own script; nil when there's no way.+// rtkInstaller is how rtk is installed here: with Homebrew when it has+// rtk's bottle for this computer, winget on Windows, else rtk's own+// script; nil when there's no way.func rtkInstaller() []string {if runtime.GOOS == "windows" {if _, err := proc.Look("winget"); err == nil {@@ -979,7 +980,7 @@ func rtkInstaller() []string {}return nil}- if _, err := proc.Look("brew"); err == nil {+ if brew, err := proc.Look("brew"); err == nil && brewBottled(brew) {return []string{"brew", "install", "rtk"}}if _, err := proc.Look("curl"); err == nil {@@ -988,6 +989,61 @@ func rtkInstaller() []string {return nil}+// brewBottled says whether Homebrew installs rtk on this computer from its+// bottle, a download of seconds. Without one, `brew install rtk` builds rtk+// from source, and first the Rust, LLVM and Python it builds with: hours,+// while Install RTK waits five minutes, so it never finished and was ended+// each time it was tried again (Scott__D on X). Homebrew bottles rtk for+// Apple silicon on the newest macOS versions only: not for an Intel Mac,+// nor for macOS 14 and older (brew there would install 19 formulae, rust+// and llvm among them, from source). brew info says which: "rtk: stable+// 1.1.0 (bottled)" only when brew would pour the bottle here. A brew that+// doesn't say, or doesn't answer, is not used: rtk's own script, which+// downloads rtk's release for this system, is.+//+// ReadRTK asks it on every read while rtk isn't installed, so the answer is+// kept for brewBottledFor, per brew.+var brewBottled = func(brew string) bool {+ bottled.Lock()+ defer bottled.Unlock()+ if bottled.brew == brew && time.Since(bottled.at) < brewBottledFor {+ return bottled.ok+ }+ ctx, cancel := context.WithTimeout(context.Background(), brewInfoWait)+ defer cancel()+ cmd := proc.CommandContext(ctx, brew, "info", "rtk")+ cmd.Stdin = nil+ cmd.Env = append(os.Environ(), "HOMEBREW_NO_AUTO_UPDATE=1", "HOMEBREW_NO_ENV_HINTS=1", "NONINTERACTIVE=1")+ out, err := cmd.Output()+ ok := err == nil && brewSaysBottled(string(out))+ bottled.brew, bottled.ok, bottled.at = brew, ok, time.Now()+ return ok+}++var bottled struct {+ sync.Mutex+ brew string+ ok bool+ at time.Time+}++const brewBottledFor = time.Hour++// brewInfoWait is how long brew info is given: it may first download+// Homebrew's formula list when its copy is old.+var brewInfoWait = 30 * time.Second++// brewSaysBottled reads brew info rtk's first line, "==> rtk: stable 1.1.0+// (bottled), HEAD".+func brewSaysBottled(out string) bool {+ for _, l := range strings.Split(ansiSeq.ReplaceAllString(out, ""), "\n") {+ if l = strings.TrimSpace(l); strings.HasPrefix(l, "==> rtk: ") {+ return strings.Contains(l, "(bottled)")+ }+ }+ return false+}+// InstallRTK installs rtk, when the user asks for it.func InstallRTK() (*RTKView, error) {rtkMu.Lock()diff --git a/internal/library/rtk_install_bottle_test.go b/internal/library/rtk_install_bottle_test.gonew file mode 100644index 000000000..4cc66cdbc--- /dev/null+++ b/internal/library/rtk_install_bottle_test.go@@ -0,0 +1,156 @@+package library++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/proc"+ "github.com/yetone/magpie/internal/testenv"+)++// What brew info rtk printed on an Apple silicon Mac (macOS 27), and with+// HOMEBREW_FAKE_MACOS=14.7, where Homebrew has no rtk bottle: read from a+// real brew 5 on mote.+const (+ brewInfoBottled = `==> rtk: stable 1.1.0 (bottled), HEAD+CLI proxy to minimize LLM token consumption+https://www.rtk-ai.app/+Not installed+From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/r/rtk.rb+License: Apache-2.0+==> Dependencies+Build (1): rust+`+ brewInfoSource = `==> rtk: stable 1.1.0, HEAD+CLI proxy to minimize LLM token consumption+https://www.rtk-ai.app/+Not installed+From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/r/rtk.rb+License: Apache-2.0+==> Dependencies+Build (1): rust+`+)++// fakeBrew puts a brew in the sandbox's bin answering info rtk with info+// (and exit code), counting each ask in a file; install rtk prints+// install and fails. The kept answer is dropped before and after.+func fakeBrew(t *testing.T, h, info string, code int, install string) (asked func() int) {+ t.Helper()+ bin := filepath.Join(h, "bin")+ write(t, filepath.Join(h, "info.txt"), info)+ write(t, filepath.Join(h, "install.txt"), install)+ count := filepath.Join(h, "asked")+ testenv.Program(t, filepath.Join(bin, "brew"), `#!/bin/sh+case "$*" in+"info rtk") echo x >> "`+count+`"; /bin/cat "`+filepath.Join(h, "info.txt")+`"; exit `+itoa(code)+` ;;+"install rtk") /bin/cat "`+filepath.Join(h, "install.txt")+`"; exit 1 ;;+esac+exit 2+`)+ testenv.Program(t, filepath.Join(bin, "curl"), "#!/bin/sh\nexit 1\n")+ forgetBottled := func() {+ bottled.Lock()+ bottled.brew, bottled.ok, bottled.at = "", false, time.Time{}+ bottled.Unlock()+ }+ forgetBottled()+ t.Cleanup(forgetBottled)+ proc.Forget()+ t.Cleanup(proc.Forget)+ return func() int {+ b, _ := os.ReadFile(count)+ return strings.Count(string(b), "x")+ }+}++func itoa(n int) string {+ if n == 0 {+ return "0"+ }+ return "1"+}++// Scott__D on X: Install RTK ran brew install rtk on a Mac Homebrew has no+// rtk bottle for, so brew set out to build rust, llvm and python from+// source, and the five-minute wait ended it every time. Such a brew is+// passed over for rtk's own script; one with the bottle is still used.+func TestRTKInstallsWithBrewOnlyFromItsBottle(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("winget installs rtk on Windows; the fakes are shell scripts")+ }+ script := "curl -fsSL " + rtkScript + " | sh"+ for _, c := range []struct {+ name, info string+ code int+ want string+ }{+ {"bottled", brewInfoBottled, 0, "brew install rtk"},+ {"built from source", brewInfoSource, 0, script},+ // mote's brew, which can't run git: it says nothing of rtk+ {"brew that fails", "Error: Unable to automatically install a working Git.\n", 1, script},+ {"brew that says nothing", "", 0, script},+ } {+ t.Run(c.name, func(t *testing.T) {+ h := sandbox(t)+ asked := fakeBrew(t, h, c.info, c.code, "")+ if v := ReadRTK(); v.Path != "" || v.Install != c.want {+ t.Fatalf("install %q, want %q (path %q)", v.Install, c.want, v.Path)+ }+ // the page reads it again: brew is asked once+ if v := ReadRTK(); v.Install != c.want || asked() != 1 {+ t.Fatalf("read again: install %q, brew asked %d times", v.Install, asked())+ }+ })+ }+}++// A brew info that doesn't answer is given brewInfoWait, then rtk's own+// script is used.+func TestRTKBrewInfoThatHangs(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fakes are shell scripts")+ }+ h := sandbox(t)+ fakeBrew(t, h, "", 0, "")+ testenv.Program(t, filepath.Join(h, "bin", "brew"), "#!/bin/sh\nexec /bin/sleep 60\n")+ w := brewInfoWait+ brewInfoWait = 300 * time.Millisecond+ t.Cleanup(func() { brewInfoWait = w })+ start := time.Now()+ if v := ReadRTK(); !strings.HasPrefix(v.Install, "curl ") {+ t.Fatalf("install %q", v.Install)+ }+ if d := time.Since(start); d > 20*time.Second {+ t.Fatalf("waited %s for brew", d)+ }+}++// A failed brew install says Homebrew's error and what to do, not the+// support-tier notice its output ends with. The output is brew 5's on mote+// (macOS without the Command Line Tools for its Homebrew), from its last+// download on.+func TestRTKBrewInstallSaysBrewsError(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fakes are shell scripts")+ }+ h := sandbox(t)+ fakeBrew(t, h, brewInfoBottled, 0, "✔︎ Formula rtk (1.1.0)\n✔︎ Formula rust (1.99.1)\n"++ "Error: No developer tools installed.\n\nInstall the Command Line Tools:\n xcode-select --install\n"++ "Error: Xcode alone is not sufficient on Sonoma.\n\nInstall the Command Line Tools:\n xcode-select --install\n\n"++ "This is a Tier 3 configuration:\n https://docs.brew.sh/Support-Tiers#tier-3\n"++ "You can report issues with Tier 3 configurations to Homebrew/* repositories!\n \n"++ "Read the above document before opening any issues or PRs.\n")+ _, err := InstallRTK()+ if err == nil {+ t.Fatal("brew failed, and InstallRTK didn't")+ }+ want := "brew failed (exit code 1) — Error: No developer tools installed. Install the Command Line Tools: xcode-select --install"+ if err.Error() != want {+ t.Fatalf("error %q\nwant %q", err, want)+ }+}diff --git a/internal/library/rtk_upgrade.go b/internal/library/rtk_upgrade.goindex 290b56bda..7871d405f 100644--- a/internal/library/rtk_upgrade.go+++ b/internal/library/rtk_upgrade.go@@ -985,12 +985,47 @@ func installFailed(c []string, out string, code int, err error) error {}return ie}- if said := installerSaid(out, 3); said != "" {+ said := installerSaid(out, 3)+ // what went wrong is Homebrew's first Error: line; its last lines can+ // be the support-tier notice it ends with+ if tool == "brew" {+ if e := brewError(out); e != "" {+ said = e+ }+ }+ if said != "" {ie.msg += " — " + said}return ie}+// brewError is the first "Error:" line Homebrew printed, and the line+// after it that says what to do, when there is one.+func brewError(out string) string {+ ls := strings.Split(strings.ToValidUTF8(ansiSeq.ReplaceAllString(out, ""), ""), "\n")+ for i, l := range ls {+ l = strings.TrimSpace(l)+ if !strings.HasPrefix(l, "Error:") {+ continue+ }+ // "Error: No developer tools installed.", then "Install the+ // Command Line Tools:" and the command, a blank line between+ var then []string+ for _, n := range ls[i+1:] {+ n = strings.TrimSpace(n)+ if n == "" && len(then) == 0 {+ continue+ }+ if n == "" || strings.HasPrefix(n, "Error:") || len(then) == 2 {+ break+ }+ then = append(then, n)+ }+ return strings.Join(append([]string{l}, then...), " ")+ }+ return ""+}+var (ansiSeq = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]`)// a line that is only a spinner frame or a progress bar (winget's