Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

library: a cargo RTK upgrades on Windows, and says why when it can't

yetonee4552cca9fa2
diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go
index 4396e8c27..24be504ec 100644
--- a/internal/cli/library_cli.go
+++ b/internal/cli/library_cli.go
@@ -487,8 +487,11 @@ func rtkCmd(args []string) error {
fmt.Println(amber.Render(" RTK "+v.Latest+" is out · waiting for "+v.Waiting), muted.Render("— "+v.Waiting+" has "+v.WaitingHas+" so far, and usually has a release within a few days"))
case v.Latest != "" && v.Version != "" && library.RTKNewer(v.Latest, v.Version):
up := "update it the way it was installed"
- if v.Upgrade != "" {
+ switch {
+ case v.Upgrade != "":
up = "magpie library rtk upgrade runs: " + v.Upgrade
+ case v.NoUpgrade == "cargo":
+ up = "it was installed with cargo, but magpie can't find cargo: install Rust from https://rustup.rs, or run " + v.Manual
}
fmt.Println(amber.Render(" RTK "+v.Latest+" is out"), muted.Render("— "+up))
case len(args) == 1 && args[0] == "upgrade":
diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js
index a6f4905bf..9e093d135 100644
--- a/internal/gui/assets/plugins/library/client.js
+++ b/internal/gui/assets/plugins/library/client.js
@@ -871,6 +871,11 @@ magpie.plugin("library", (ctx) => {
// (#1025), so none is offered until it does
const waiting = !rtkUpgrading && rtk.waiting;
const behind = !waiting && rtk.latest && rtk.version && vNewer(rtk.latest, rtk.version);
+ // why there is no upgrade to run: a cargo RTK with no cargo to be
+ // found says what to install or run (新v学员)
+ const noUpgrade = rtk.noUpgrade === "cargo"
+ ? t("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.", { cmd: rtk.manual })
+ : t("magpie can't tell how this RTK was installed — update it the way you installed it");
if (rtkUpgrading) ttl.append(tag(t("Upgrading…"), "lib-new"));
else if (waiting) ttl.append(tag(t("v{v} is out · waiting for {via}", { v: rtk.latest, via: rtk.waiting }), "", t("RTK {v} is out, but {via} has {has} so far — usually within a few days. Upgrade comes back once {via} has it.", { v: rtk.latest, via: rtk.waiting, has: rtk.waitingHas || rtk.version })));
else if (behind) ttl.append(tag(t("v{v} is out", { v: rtk.latest }), "lib-new", t("RTK {v} is the latest release; this one is {have}", { v: rtk.latest, have: rtk.version })));
@@ -878,7 +883,7 @@ magpie.plugin("library", (ctx) => {
if (behind || rtkUpgrading) {
const ub = button(rtkUpgrading ? t("Upgrading…") : t("Upgrade"), "action", upgradeRTK);
ub.disabled = rtkUpgrading || !rtk.upgrade;
- ub.title = rtk.upgrade ? (rtk.admin ? t("Runs {cmd}, as administrator: Windows asks first", { cmd: rtk.upgrade }) : t("Runs {cmd}", { cmd: rtk.upgrade })) : t("magpie can't tell how this RTK was installed — update it the way you installed it");
+ ub.title = rtk.upgrade ? (rtk.admin ? t("Runs {cmd}, as administrator: Windows asks first", { cmd: rtk.upgrade }) : t("Runs {cmd}", { cmd: rtk.upgrade })) : noUpgrade;
ttl.append(ub);
}
card.append(ttl);
@@ -886,6 +891,10 @@ magpie.plugin("library", (ctx) => {
// with the tool's exit code and what it said, until the next try (#741)
if (rtkUpgrading && rtk.upgrade) card.append(el("p", "lib-rtk-gain", t("Running {cmd} — this can take a few minutes.", { cmd: rtk.upgrade })));
else if (rtkUpgradeErr) card.append(el("p", "lib-rtk-note lib-rtk-err", t("The upgrade failed: {why}", { why: rtkUpgradeErr })));
+ // no upgrade to run: said on the card, not only in the disabled
+ // button's tooltip, which a click never shows (新v学员: a cargo RTK
+ // on Windows whose Upgrade did nothing)
+ else if (behind && !rtk.upgrade) card.append(el("p", "lib-rtk-note lib-rtk-noupgrade", noUpgrade));
if (rtk.note) card.append(el("p", "lib-rtk-note", rtk.note));
// found where magpie looks, but not on the PATH the agents get: their
// hooks run rtk by name, so it does nothing for them (#601)
diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js
index 9c655a38a..2e83216f4 100644
--- a/internal/gui/assets/plugins/library/i18n.js
+++ b/internal/gui/assets/plugins/library/i18n.js
@@ -149,6 +149,7 @@ magpie.strings({
"Runs {cmd}": "将运行 {cmd}",
"Runs {cmd}, as administrator: Windows asks first": "将以管理员身份运行 {cmd}:Windows 会先询问",
"magpie can't tell how this RTK was installed — update it the way you installed it": "无法判断 RTK 的安装方式,请按原安装方式更新",
+ "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 upgrade failed: {why}": "升级失败:{why}",
@@ -781,6 +782,7 @@ magpie.strings({
"Runs {cmd}": "將執行 {cmd}",
"Runs {cmd}, as administrator: Windows asks first": "將以系統管理員身分執行 {cmd}:Windows 會先詢問",
"magpie can't tell how this RTK was installed — update it the way you installed it": "無法判斷 RTK 的安裝方式,請按原安裝方式更新",
+ "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 upgrade failed: {why}": "升級失敗:{why}",
@@ -1408,6 +1410,7 @@ magpie.strings({
"Runs {cmd}": "{cmd} を実行します",
"Runs {cmd}, as administrator: Windows asks first": "{cmd} を管理者として実行します:Windows が先に確認します",
"magpie can't tell how this RTK was installed — update it the way you installed it": "magpie はこの RTK のインストール方法を判別できません — インストールしたのと同じ方法で更新してください",
+ "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 upgrade failed: {why}": "アップグレードに失敗しました:{why}",
@@ -2038,6 +2041,7 @@ magpie.strings({
"Runs {cmd}": "Führt {cmd} aus",
"Runs {cmd}, as administrator: Windows asks first": "Führt {cmd} als Administrator aus: Windows fragt vorher",
"magpie can't tell how this RTK was installed — update it the way you installed it": "magpie kann nicht erkennen, wie dieses RTK installiert wurde – aktualisieren Sie es auf dem Weg, auf dem Sie es installiert haben",
+ "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 upgrade failed: {why}": "Das Upgrade ist fehlgeschlagen: {why}",
diff --git a/internal/gui/tests/library-rtk-upgrade.test.cjs b/internal/gui/tests/library-rtk-upgrade.test.cjs
index e706f3798..437c12c03 100644
--- a/internal/gui/tests/library-rtk-upgrade.test.cjs
+++ b/internal/gui/tests/library-rtk-upgrade.test.cjs
@@ -202,3 +202,72 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
}
+
+// 新v学员 (10-27): on Windows, an RTK cargo installed had a newer release
+// and a greyed Upgrade that did nothing — magpie found no cargo, and only
+// the button's tooltip, which a click never shows, said anything. Now the
+// card says it: for cargo's RTK, what to install or run; for one magpie
+// can't place, to update it the way it was installed. In every language,
+// at 440px.
+const CARGO = "cargo install --git https://github.com/rtk-ai/rtk --branch master rtk --force";
+const noUpgradeWords = {
+ en: { cargo: `RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run ${CARGO} in a terminal.`, other: "magpie can't tell how this RTK was installed — update it the way you installed it" },
+ zh: { cargo: `RTK 是用 cargo 安装的,但 magpie 找不到 cargo 来升级它。请从 rustup.rs 安装 Rust,或在终端里运行 ${CARGO}。`, other: "无法判断 RTK 的安装方式,请按原安装方式更新" },
+ "zh-TW": { cargo: `RTK 是用 cargo 安裝的,但 magpie 找不到 cargo 來升級它。請從 rustup.rs 安裝 Rust,或在終端機裡執行 ${CARGO}。`, other: "無法判斷 RTK 的安裝方式,請按原安裝方式更新" },
+ ja: { cargo: `RTK は cargo でインストールされていますが、magpie は更新に使う cargo を見つけられません。rustup.rs から Rust をインストールするか、ターミナルで ${CARGO} を実行してください。`, other: "magpie はこの RTK のインストール方法を判別できません — インストールしたのと同じ方法で更新してください" },
+ de: { cargo: `RTK wurde mit cargo installiert, aber magpie findet kein cargo, um es zu aktualisieren. Installieren Sie Rust von rustup.rs, oder führen Sie ${CARGO} in einem Terminal aus.`, other: "magpie kann nicht erkennen, wie dieses RTK installiert wurde – aktualisieren Sie es auf dem Weg, auf dem Sie es installiert haben" },
+};
+
+function noUpgradeServer(lang, state) {
+ const base = server(lang, state);
+ return async (route) => {
+ const url = new URL(route.request().url());
+ if (url.pathname === "/api/library/rtk") {
+ const v = { ...rtkView("1.0.0"), path: `${HOME}/.cargo/bin/rtk.exe`, latest: "1.1.0", upgrade: "" };
+ return route.fulfill({ json: state.cargo ? { ...v, noUpgrade: "cargo", manual: CARGO } : v });
+ }
+ if (url.pathname === "/api/library/rtk/upgrade") { state.upgrades++; return route.fulfill({ status: 400, json: { error: "no" } }); }
+ return base(route);
+ };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": an RTK magpie can't upgrade says why on the card", async (t) => {
+ 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 Object.keys(noUpgradeWords)) {
+ for (const cargo of [true, false]) {
+ await t.test(`${lang} ${cargo ? "cargo" : "unknown"}`, async () => {
+ const want = noUpgradeWords[lang][cargo ? "cargo" : "other"];
+ const state = { cargo, upgrades: 0, reads: 0 };
+ const ctx = await browser.newContext({ viewport: { width: 440, 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("**/*", noUpgradeServer(lang, state));
+ await page.goto("http://magpie.test/");
+ await page.locator('button[data-view="library"]').click();
+ const v = page.locator("#view-library");
+ const note = v.locator(".lib-rtk-noupgrade");
+ await note.waitFor();
+ assert.equal(await note.textContent(), want);
+ assert(await note.isVisible());
+ const button = v.locator(".lib-cardhead button");
+ assert(await button.isDisabled());
+ assert.equal(await button.getAttribute("title"), want);
+ await button.click({ force: true });
+ assert.equal(state.upgrades, 0);
+ const box = await v.evaluate(() => ({ doc: document.documentElement.scrollWidth, vw: innerWidth }));
+ assert(box.doc <= box.vw, `page scrolls sideways: ${JSON.stringify(box)}`);
+ await ctx.close();
+ });
+ }
+ }
+ assert.deepEqual(errors, []);
+ });
+}
diff --git a/internal/library/rtk.go b/internal/library/rtk.go
index bc45fe123..d62179821 100644
--- a/internal/library/rtk.go
+++ b/internal/library/rtk.go
@@ -590,6 +590,12 @@ type RTKView struct {
// doesn't know how this rtk was installed
Latest string `json:"latest,omitempty"`
Upgrade string `json:"upgrade,omitempty"`
+ // NoUpgrade is why there is no Upgrade when magpie knows: "cargo", an
+ // rtk cargo installed with no cargo to be found to upgrade it, which
+ // the page says with Manual, the command to run in a terminal once
+ // there is (新v学员: its Upgrade button only did nothing)
+ NoUpgrade string `json:"noUpgrade,omitempty"`
+ Manual string `json:"manual,omitempty"`
// Admin is the folder rtk is in when only an administrator can change
// it (winget's for every user, under Program Files): Upgrade asks
// Windows for one first
@@ -632,10 +638,10 @@ func rtkPath() string {
if p, err := proc.Look("rtk"); err == nil {
return p
}
- name, dirs := "rtk", []string{filepath.Join(home(), ".local", "bin"), filepath.Join(home(), ".cargo", "bin")}
+ name, dirs := "rtk", append([]string{filepath.Join(home(), ".local", "bin")}, cargoBins()...)
if runtime.GOOS == "windows" {
winget := filepath.Join(appdir.Getenv("LOCALAPPDATA"), "Microsoft", "WinGet")
- name, dirs = "rtk.exe", []string{filepath.Join(winget, "Links"), filepath.Join(home(), ".cargo", "bin")}
+ name, dirs = "rtk.exe", append([]string{filepath.Join(winget, "Links")}, cargoBins()...)
if appdir.Getenv("LOCALAPPDATA") != "" {
pkgs, _ := filepath.Glob(filepath.Join(winget, "Packages", "rtk-ai.rtk_*"))
dirs = append(dirs, pkgs...)
@@ -741,6 +747,10 @@ func ReadRTK() *RTKView {
}
if c := upgraderOf(v.Path); c != nil {
v.Upgrade, v.Admin = shown(c), rtkAdminFolder(c, v.Path)
+ } else {
+ if v.NoUpgrade = rtkNoUpgrade(v.Path); v.NoUpgrade == "cargo" {
+ v.Manual = rtkCargoCmd
+ }
}
v.Gain, v.Days, v.GainErr = rtkGain(v.Path)
if runtime.GOOS == "windows" {
diff --git a/internal/library/rtk_cargo_test.go b/internal/library/rtk_cargo_test.go
new file mode 100644
index 000000000..0494defeb
--- /dev/null
+++ b/internal/library/rtk_cargo_test.go
@@ -0,0 +1,239 @@
+package library
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// What cargo printed on the Windows test box (cargo 1.99.1, a Chinese
+// Windows) when the rtk.exe it was to replace was running.
+const cargoInUseOut = " Compiling rtk v1.1.0\r\n Finished `release` profile [optimized] target(s) in 1m 02s\r\n" +
+ " Replacing C:\\Users\\yeton\\rtkcargo-sb\\home\\.cargo\\bin\\rtk.exe\r\n" +
+ "error: failed to move `C:\\Users\\yeton\\rtkcargo-sb\\home\\.cargo\\bin\\cargo-installQ79RGS\\rtk.exe` to `C:\\Users\\yeton\\rtkcargo-sb\\home\\.cargo\\bin\\rtk.exe`\r\n" +
+ "\r\nCaused by:\r\n 拒绝访问。 (os error 5)\r\n"
+
+// What it printed building rtk with the windows-gnu toolchain and no
+// dlltool: the cause is three lines above the last.
+const cargoDlltoolOut = " Compiling paste v1.0.15\r\n Compiling adler2 v2.0.1\r\n" +
+ "error: error calling dlltool 'dlltool.exe': program not found\r\n" +
+ " Compiling colorchoice v1.0.5\r\n" +
+ "error: could not compile `parking_lot_core` (lib) due to 1 previous error\r\n" +
+ "warning: build failed, waiting for other jobs to finish...\r\n" +
+ "error: could not compile `windows-sys` (lib) due to 1 previous error\r\n" +
+ "error: failed to compile `rtk v1.1.0 (https://github.com/rtk-ai/rtk?branch=master#753a3b0e)`, intermediate artifacts can be found at `C:\\Users\\yeton\\AppData\\Local\\Temp\\cargo-installJjS3qF`.\r\n" +
+ "To reuse those artifacts with a future compilation, set the environment variable `CARGO_BUILD_BUILD_DIR` to that path.\r\n"
+
+func onWindows(t *testing.T, yes bool) {
+ t.Helper()
+ old := rtkOnWindows
+ rtkOnWindows = yes
+ t.Cleanup(func() { rtkOnWindows = old })
+}
+
+// A magpie whose PATH has no cargo — started before Rust was installed, or
+// from a shortcut whose PATH rustup never touched — upgrades the rtk in
+// cargo's folder with the cargo rustup put beside it, by its path. It had
+// no upgrade at all, and its Upgrade button did nothing (新v学员).
+func TestRTKCargoBesideRTK(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("the fakes are shell scripts")
+ }
+ h := sandbox(t)
+ latestServer(t, "v1.1.0")
+ dir := filepath.Join(h, ".cargo", "bin")
+ testenv.Program(t, filepath.Join(dir, "rtk"), strings.ReplaceAll(versionedRTK, "VERSION", filepath.Join(dir, "VERSION")))
+ write(t, filepath.Join(dir, "VERSION"), "1.0.0")
+ testenv.Program(t, filepath.Join(dir, "cargo"), `#!/bin/sh
+[ "$*" = "install --git https://github.com/rtk-ai/rtk --branch master rtk --force" ] || exit 2
+echo 1.1.0 > "`+filepath.Join(dir, "VERSION")+`"
+`)
+ t.Setenv("PATH", filepath.Join(h, "bin")) // no cargo, no rtk
+
+ v := ReadRTK()
+ if v.Path != filepath.Join(dir, "rtk") || v.Upgrade == "" || !strings.Contains(v.Upgrade, "--branch master") || v.NoUpgrade != "" {
+ t.Fatalf("view: %+v", v)
+ }
+ if c := rtkUpgrader(v.Path); len(c) == 0 || c[0] != filepath.Join(dir, "cargo") {
+ t.Fatalf("upgrader %q, want cargo by its path", c)
+ }
+ if v, err := UpgradeRTK(); err != nil || v.Version != "1.1.0" {
+ t.Fatalf("after: %+v, %v", v, err)
+ }
+}
+
+// With no cargo anywhere, the card says so and what to run, and Upgrade's
+// error does too — not "magpie can't tell how this RTK was installed".
+func TestRTKCargoMissingSaysSo(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("the fakes are shell scripts")
+ }
+ h := sandbox(t)
+ latestServer(t, "v1.1.0")
+ dir := filepath.Join(h, ".cargo", "bin")
+ testenv.Program(t, filepath.Join(dir, "rtk"), strings.ReplaceAll(versionedRTK, "VERSION", filepath.Join(dir, "VERSION")))
+ write(t, filepath.Join(dir, "VERSION"), "1.0.0")
+ t.Setenv("PATH", filepath.Join(h, "bin"))
+
+ v := ReadRTK()
+ if v.Path != filepath.Join(dir, "rtk") || v.Upgrade != "" || v.NoUpgrade != "cargo" || v.Manual != rtkCargoCmd {
+ t.Fatalf("view: %+v", v)
+ }
+ _, err := UpgradeRTK()
+ if err == nil || !strings.Contains(err.Error(), "installed with cargo") || !strings.Contains(err.Error(), "rustup.rs") || !strings.Contains(err.Error(), rtkCargoCmd) {
+ t.Fatalf("error: %v", err)
+ }
+}
+
+// CARGO_HOME moves cargo's folder (D:\Rust\.cargo is common): an rtk there
+// is cargo's too, and on Windows its path matches whatever its case.
+func TestRTKCargoHome(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("the fakes are shell scripts")
+ }
+ h := sandbox(t)
+ ch := filepath.Join(h, "Rust", ".cargo")
+ t.Setenv("CARGO_HOME", ch)
+ dir := filepath.Join(ch, "bin")
+ testenv.Program(t, filepath.Join(dir, "rtk"), strings.ReplaceAll(versionedRTK, "VERSION", filepath.Join(dir, "VERSION")))
+ write(t, filepath.Join(dir, "VERSION"), "1.0.0")
+ testenv.Program(t, filepath.Join(dir, "cargo"), "#!/bin/sh\n")
+ t.Setenv("PATH", filepath.Join(h, "bin"))
+
+ if p := rtkPath(); p != filepath.Join(dir, "rtk") {
+ t.Fatalf("rtkPath %q", p)
+ }
+ if c := rtkUpgrader(filepath.Join(dir, "rtk")); len(c) == 0 || c[0] != filepath.Join(dir, "cargo") {
+ t.Fatalf("upgrader %q", c)
+ }
+ onWindows(t, true)
+ if !inCargoBin(strings.ToUpper(dir)) || !inCargoBin(filepath.Join(h, ".cargo", "bin")) {
+ t.Fatal("Windows: cargo's folders by another case")
+ }
+ onWindows(t, false)
+ if inCargoBin(strings.ToUpper(dir)) {
+ t.Fatal("elsewhere the case counts")
+ }
+}
+
+// On Windows cargo can't replace an rtk.exe that is running: the rtk is
+// moved aside, a copy put in its place, and cargo run again, which
+// installs over the copy. Anywhere else, and for any other failure,
+// cargo's failure stands.
+func TestRTKCargoInUseMovesAside(t *testing.T) {
+ h := sandbox(t)
+ bin := filepath.Join(h, ".cargo", "bin", "rtk.exe")
+ write(t, bin, "old rtk")
+ write(t, bin+".old-1", "an earlier upgrade's")
+ cargo := []string{"cargo", "install", "--git", "x", "rtk", "--force"}
+
+ run := func(fails int, out string) (int, []string) {
+ var envs []string
+ n := 0
+ p := runPlain
+ runPlain = func(c []string, _ time.Duration, env ...string) (string, error) {
+ n++
+ envs = append(envs, env...)
+ if n <= fails {
+ return out, installFailed(c, out, 101, errors.New("exit status 101"))
+ }
+ if b, err := os.ReadFile(bin); err != nil || string(b) != "old rtk" {
+ t.Errorf("cargo ran over %q, %v; want the copy", b, err)
+ }
+ return "", os.WriteFile(bin, []byte("new rtk"), 0o755)
+ }
+ t.Cleanup(func() { runPlain = p })
+ return n, envs
+ }
+
+ onWindows(t, true)
+ run(1, cargoInUseOut)
+ if err := runCargoRTK(cargo, bin, time.Minute); err != nil {
+ t.Fatalf("in use: %v", err)
+ }
+ if b, _ := os.ReadFile(bin); string(b) != "new rtk" {
+ t.Fatalf("rtk.exe: %q", b)
+ }
+ if exists(bin + ".old-1") {
+ t.Fatal("an earlier upgrade's rtk left behind")
+ }
+ aside := bin + ".old-" + strconv.Itoa(os.Getpid())
+ if exists(aside) {
+ t.Fatal("this upgrade's rtk left behind though nothing runs it")
+ }
+
+ // in use twice: the second failure is the one returned
+ write(t, bin, "old rtk")
+ run(2, cargoInUseOut)
+ if err := runCargoRTK(cargo, bin, time.Minute); err == nil || !strings.Contains(err.Error(), "rtk is in use") {
+ t.Fatalf("in use twice: %v", err)
+ }
+
+ // another failure isn't retried
+ write(t, bin, "old rtk")
+ run(1, cargoDlltoolOut)
+ if err := runCargoRTK(cargo, bin, time.Minute); err == nil || exists(aside) {
+ t.Fatalf("dlltool: %v", err)
+ }
+
+ onWindows(t, false)
+ run(1, cargoInUseOut)
+ if err := runCargoRTK(cargo, bin, time.Minute); err == nil {
+ t.Fatal("not Windows: retried")
+ }
+}
+
+// cargo's own build folder is magpie's, so the retry builds nothing again
+// and no build is left behind in the user's temp folder.
+func TestRTKCargoTargetDir(t *testing.T) {
+ sandbox(t)
+ var dir string
+ p := runPlain
+ runPlain = func(c []string, _ time.Duration, env ...string) (string, error) {
+ for _, e := range env {
+ if v, ok := strings.CutPrefix(e, "CARGO_TARGET_DIR="); ok {
+ dir = v
+ }
+ }
+ return "", nil
+ }
+ t.Cleanup(func() { runPlain = p })
+ if err := runCargoRTK([]string{"cargo"}, filepath.Join(t.TempDir(), "rtk"), time.Minute); err != nil || dir == "" {
+ t.Fatalf("%v, CARGO_TARGET_DIR %q", err, dir)
+ }
+ if exists(dir) {
+ t.Fatalf("%s left behind", dir)
+ }
+}
+
+// A failed cargo says its first error, the cause, with what to do — not
+// its last lines, which only say the build failed and where its files are.
+func TestRTKCargoSaysWhy(t *testing.T) {
+ cargoAt := []string{`C:\Users\me\.cargo\bin\cargo.exe`, "install"}
+ for _, c := range []struct {
+ out string
+ want []string
+ }{
+ {cargoInUseOut, []string{"cargo failed (exit code 101)", "rtk is in use", "failed to move", "(os error 5)"}},
+ {cargoDlltoolOut, []string{"cargo failed", "missing a tool", "error calling dlltool 'dlltool.exe': program not found"}},
+ {"error: linker `link.exe` not found\r\n |\r\n = note: program not found\r\n", []string{"Visual Studio Build Tools", "link.exe"}},
+ {"error: failed to clone into: C:\\x\r\n\r\nCaused by:\r\n network failure seems to have happened\r\n", []string{"couldn't download", "network failure"}},
+ } {
+ msg := installFailed(cargoAt, c.out, 101, errors.New("exit status 101")).Error()
+ for _, w := range c.want {
+ if !strings.Contains(msg, w) {
+ t.Errorf("%q\nmissing %q", msg, w)
+ }
+ }
+ if strings.Contains(msg, `C:\Users\me\.cargo\bin\cargo.exe failed`) || strings.Contains(msg, "CARGO_BUILD_BUILD_DIR") {
+ t.Errorf("%q", msg)
+ }
+ }
+}
diff --git a/internal/library/rtk_upgrade.go b/internal/library/rtk_upgrade.go
index 51f236d55..290b56bda 100644
--- a/internal/library/rtk_upgrade.go
+++ b/internal/library/rtk_upgrade.go
@@ -350,12 +350,16 @@ func rtkUpgrader(bin string) []string {
if have("winget") {
return wingetUp
}
- case dir == filepath.Join(home(), ".cargo", "bin"):
- if have("cargo") {
+ // cargo's folder, ~/.cargo/bin or CARGO_HOME's. With no cargo to be
+ // found there is no upgrade, and the page says why (RTKView.NoUpgrade):
+ // taking it over with rtk's Windows release would leave cargo's own
+ // records of it behind
+ case inCargoBin(dir):
+ if cargo := cargoFor(dir); cargo != "" {
// the package named: rtk-ai/rtk keeps proxy/ (rtk-proxy) beside
// rtk, and cargo install --git scans every Cargo.toml in the
// repository and won't choose between their binaries (#2328)
- return []string{"cargo", "install", "--git", "https://github.com/rtk-ai/rtk", "rtk", "--force"}
+ return append([]string{cargo}, strings.Fields(rtkCargoCmd)[1:]...)
}
case !rtkOnWindows:
// its own script, told the folder it is in (RTK_INSTALL_DIR): the
@@ -385,6 +389,76 @@ func rtkUpgrader(bin string) []string {
return nil
}
+// rtkCargoCmd is how cargo upgrades rtk, as a terminal would run it.
+// rtk-ai/rtk's default branch is develop, whose rtk is behind the release:
+// on 10-27 develop's Cargo.toml said 0.49.0 while v1.1.0 was out, built
+// from master, so an upgrade without the branch put 0.49.0 in place of a
+// newer rtk, or left it as it was. rtk's own installation guide names
+// master, as this does.
+const rtkCargoCmd = "cargo install --git https://github.com/rtk-ai/rtk --branch master rtk --force"
+
+// cargoBins are the folders cargo install puts programs in: CARGO_HOME's
+// bin when it is set (rustup's installer and many guides move it off C:,
+// to D:\Rust\.cargo), and ~/.cargo/bin, its default.
+func cargoBins() []string {
+ var dirs []string
+ if h := os.Getenv("CARGO_HOME"); filepath.IsAbs(h) {
+ dirs = append(dirs, filepath.Join(h, "bin"))
+ }
+ return append(dirs, filepath.Join(home(), ".cargo", "bin"))
+}
+
+// inCargoBin says whether dir is one of cargo's folders; case aside on
+// Windows, where C:\Users\Me and c:\users\me are the same folder.
+func inCargoBin(dir string) bool {
+ for _, d := range cargoBins() {
+ if filepath.Clean(dir) == filepath.Clean(d) || rtkOnWindows && strings.EqualFold(filepath.Clean(dir), filepath.Clean(d)) {
+ return true
+ }
+ }
+ return false
+}
+
+// cargoFor is the cargo that upgrades the rtk in cargo's folder dir: the one
+// on magpie's PATH, by name, else the one rustup put in that same folder
+// beside rtk, by its path. A magpie started before Rust was installed, or
+// with a PATH without cargo's folder (rustup adds it for terminals opened
+// after), found no cargo by name, and the rtk cargo installed had no
+// upgrade at all: its Upgrade button did nothing (新v学员, 10-27). "" when
+// there is no cargo in either.
+func cargoFor(dir string) string {
+ if _, err := exec.LookPath("cargo"); err == nil {
+ return "cargo"
+ }
+ name := "cargo"
+ if rtkOnWindows {
+ name = "cargo.exe"
+ }
+ if p := filepath.Join(dir, name); exists(p) {
+ return p
+ }
+ return ""
+}
+
+// isCargo says whether installer c is cargo, by name or by its path.
+func isCargo(c []string) bool {
+ if len(c) == 0 {
+ return false
+ }
+ name := c[0][strings.LastIndexAny(c[0], `/\`)+1:]
+ return strings.TrimSuffix(strings.ToLower(name), ".exe") == "cargo"
+}
+
+// rtkNoUpgrade is why the rtk at bin has no upgrade, for the page to say
+// when a newer release is out (RTKView.NoUpgrade): "cargo" when cargo
+// installed it but magpie finds no cargo to run, "" otherwise.
+func rtkNoUpgrade(bin string) string {
+ if inCargoBin(filepath.Dir(bin)) && cargoFor(filepath.Dir(bin)) == "" {
+ return "cargo"
+ }
+ return ""
+}
+
// rtkWindowsRelease is the upgrader rtkUpgrader gives a Windows rtk no
// package manager installed (#2006): magpie replaces it with rtk.exe out of
// rtk's own Windows release. The action names only the binary to replace:
@@ -533,13 +607,7 @@ func replaceRTKBinary(bin string, b []byte) error {
// the old binary renamed, not removed: a rename that fails leaves it.
// One an agent was running when it was moved aside can't be removed
// until it exits, so the ones earlier upgrades left are removed now
- if ents, err := os.ReadDir(filepath.Dir(bin)); err == nil {
- for _, e := range ents {
- if strings.HasPrefix(e.Name(), filepath.Base(bin)+".old-") {
- os.Remove(filepath.Join(filepath.Dir(bin), e.Name()))
- }
- }
- }
+ removeOldRTKs(bin)
aside := bin + ".old-" + strconv.Itoa(os.Getpid())
if err := steady.Rename(bin, aside); err != nil {
os.Remove(tmpName)
@@ -668,6 +736,9 @@ func UpgradeRTK() (*RTKView, error) {
}
c := upgraderOf(bin)
if c == nil {
+ if rtkNoUpgrade(bin) == "cargo" {
+ return nil, fmt.Errorf("the rtk at %s was installed with cargo, but magpie can't find cargo — install Rust from https://rustup.rs, or run %s in a terminal", bin, rtkCargoCmd)
+ }
return nil, fmt.Errorf("magpie can't tell how the rtk at %s was installed — update it the way you installed it", bin)
}
before := rtkVersion()
@@ -689,12 +760,19 @@ func UpgradeRTK() (*RTKView, error) {
c = c[:3]
}
timeout := 10 * time.Minute
- if c[0] == "cargo" {
+ if isCargo(c) {
timeout = 30 * time.Minute // it builds rtk
}
+ run := func() error {
+ _, err := runRTKInstaller(c, timeout, rtkAdminFolder(c, bin), env...)
+ return err
+ }
+ if isCargo(c) {
+ run = func() error { return runCargoRTK(c, bin, timeout) }
+ }
// brew upgrade updates Homebrew first, for its newest rtk
// winget having no newer rtk than this one yet is no failure
- if _, err := runRTKInstaller(c, timeout, rtkAdminFolder(c, bin), env...); err != nil {
+ if err := run(); err != nil {
var ie *installError
if none = errors.As(err, &ie) && c[0] == "winget" && uint32(ie.code) == wingetNoUpgrade; !none {
return nil, err
@@ -722,6 +800,88 @@ func UpgradeRTK() (*RTKView, error) {
return v, nil
}
+// runCargoRTK runs cargo's upgrade c of the rtk at bin. On Windows cargo
+// can't write over an rtk.exe that is running (os error 5), and one is
+// whenever an agent's command runs through RTK — an rtk cargo test runs as
+// long as the tests do — so its upgrade failed once the build was done.
+// Windows does let a running rtk.exe be renamed: when cargo is refused, the
+// rtk.exe is moved aside, a copy of it put in its place for the agents to
+// run meanwhile, and cargo run again, which builds nothing again (its build
+// is kept in a folder of magpie's, CARGO_TARGET_DIR, removed after) and only
+// installs over the copy.
+func runCargoRTK(c []string, bin string, timeout time.Duration) error {
+ var env []string
+ if dir, err := os.MkdirTemp("", "magpie-rtk-cargo-"); err == nil {
+ defer os.RemoveAll(dir)
+ env = append(env, "CARGO_TARGET_DIR="+dir)
+ }
+ removeOldRTKs(bin)
+ out, err := runPlain(c, timeout, env...)
+ if err == nil || !rtkOnWindows || !cargoInUse(out) {
+ return err
+ }
+ aside, merr := copyRTKAside(bin)
+ if merr != nil {
+ return err
+ }
+ if _, err := runPlain(c, timeout, env...); err != nil {
+ return err
+ }
+ os.Remove(aside) // still running: removed by the next upgrade
+ return nil
+}
+
+// cargoInUse says whether cargo install failed because the rtk it was to
+// replace is running: it couldn't move the new one over it, refused with
+// os error 5 (access denied) or 32 (in use). cargo prints the system's
+// own words before the code, in its language: only the code is read.
+func cargoInUse(out string) bool {
+ return strings.Contains(out, "failed to move") &&
+ (strings.Contains(out, "(os error 5)") || strings.Contains(out, "(os error 32)"))
+}
+
+// copyRTKAside moves the rtk at bin aside, to bin.old-<pid>, and puts a copy
+// of it back at bin: for an install to write over the copy while what runs
+// the old one goes on running it. Should the copy fail, the rtk is moved
+// back.
+func copyRTKAside(bin string) (string, error) {
+ aside := bin + ".old-" + strconv.Itoa(os.Getpid())
+ b, err := os.ReadFile(bin)
+ if err != nil {
+ return "", err
+ }
+ st, err := os.Stat(bin)
+ if err != nil {
+ return "", err
+ }
+ if err := steady.Rename(bin, aside); err != nil {
+ return "", err
+ }
+ if err := os.WriteFile(bin, b, st.Mode().Perm()); err != nil {
+ os.Remove(bin)
+ if rerr := steady.Rename(aside, bin); rerr != nil {
+ return "", fmt.Errorf("couldn't put the rtk at %s back from %s: %w", bin, aside, rerr)
+ }
+ return "", err
+ }
+ return aside, nil
+}
+
+// removeOldRTKs removes the rtks earlier upgrades moved aside from bin's
+// folder: one an agent was running when it was moved can't be removed
+// until it exits.
+func removeOldRTKs(bin string) {
+ ents, err := os.ReadDir(filepath.Dir(bin))
+ if err != nil {
+ return
+ }
+ for _, e := range ents {
+ if strings.HasPrefix(e.Name(), filepath.Base(bin)+".old-") {
+ os.Remove(filepath.Join(filepath.Dir(bin), e.Name()))
+ }
+ }
+}
+
// runInstaller runs an installer with nothing to answer it. A failure says
// which tool failed, how it ended and what it said that matters — not its
// command line, which was all the page had room for (#741: a red
@@ -799,6 +959,9 @@ func installFailed(c []string, out string, code int, err error) error {
if tool == "sh" {
tool = "RTK's install script"
}
+ if isCargo(c) {
+ tool = "cargo" // by name, not the path it was run by
+ }
ie := &installError{code: code}
if code == -1 {
ie.msg = fmt.Sprintf("%s %v", tool, err)
@@ -810,6 +973,18 @@ func installFailed(c []string, out string, code int, err error) error {
}
}
}
+ if isCargo(c) {
+ // what went wrong is cargo's first error; its last lines only say
+ // the build failed and where its files were left (a missing
+ // linker, "error calling dlltool", came three lines before them)
+ if s := cargoSays(out); s != "" {
+ ie.msg += ": " + s
+ }
+ if said := cargoError(out); said != "" {
+ ie.msg += " — " + said
+ }
+ return ie
+ }
if said := installerSaid(out, 3); said != "" {
ie.msg += " — " + said
}
@@ -847,3 +1022,45 @@ func installerSaid(out string, n int) string {
}
return s
}
+
+// cargoSays is what a failed cargo install of rtk printed, said plainly with
+// what to do, for the failures a user meets; "" for any other.
+func cargoSays(out string) string {
+ low := strings.ToLower(out)
+ switch {
+ case cargoInUse(out):
+ return "rtk is in use — close the agents running it, and the commands they run through RTK, then try again"
+ case strings.Contains(low, "link.exe") && strings.Contains(low, "not found"):
+ return "Rust can't find Visual Studio's C++ linker (link.exe) to build RTK — install Visual Studio Build Tools with \"Desktop development with C++\", then try again"
+ case strings.Contains(low, "linker") && strings.Contains(low, "not found"),
+ strings.Contains(low, "dlltool") && strings.Contains(low, "not found"):
+ return "Rust's toolchain is missing a tool it needs to build RTK — install the C/C++ build tools it uses, then try again"
+ case strings.Contains(low, "failed to fetch into"), strings.Contains(low, "failed to clone"),
+ strings.Contains(low, "network failure"), strings.Contains(low, "could not resolve host"),
+ strings.Contains(low, "couldn't resolve host"):
+ return "cargo couldn't download RTK's source from GitHub — check the network or proxy, then try again"
+ }
+ return ""
+}
+
+// cargoError is the first error cargo printed, with the cause it gave on
+// the line after "Caused by:"; the last lines that say something when it
+// printed no error line.
+func cargoError(out string) string {
+ out = strings.ToValidUTF8(ansiSeq.ReplaceAllString(out, ""), "")
+ lines := strings.FieldsFunc(out, func(r rune) bool { return r == '\n' || r == '\r' })
+ for i, l := range lines {
+ l = strings.TrimSpace(l)
+ if !strings.HasPrefix(l, "error") {
+ continue
+ }
+ if i+2 < len(lines) && strings.TrimSpace(lines[i+1]) == "Caused by:" {
+ l += " " + strings.TrimSpace(lines[i+2])
+ }
+ if r := []rune(l); len(r) > 400 {
+ l = string(r[:400]) + "…"
+ }
+ return l
+ }
+ return installerSaid(out, 3)
+}
diff --git a/internal/library/rtk_upgrade_test.go b/internal/library/rtk_upgrade_test.go
index c445359ab..f2f14b9a3 100644
--- a/internal/library/rtk_upgrade_test.go
+++ b/internal/library/rtk_upgrade_test.go
@@ -309,8 +309,9 @@ func TestRTKChannelVersion(t *testing.T) {
// An rtk cargo put in ~/.cargo/bin is upgraded with cargo, naming the
// package: rtk-ai/rtk has rtk-proxy beside rtk, and cargo install --git
-// refuses to choose between them (#2328, #2092). The fake cargo answers as
-// cargo does.
+// refuses to choose between them (#2328, #2092). And the branch: rtk's
+// default branch, develop, has an older rtk than the release, built from
+// master (新v学员). The fake cargo answers as cargo does.
func TestRTKUpgradeCargoNamesThePackage(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the fakes are shell scripts")
@@ -321,7 +322,7 @@ func TestRTKUpgradeCargoNamesThePackage(t *testing.T) {
testenv.Program(t, filepath.Join(dir, "rtk"), strings.ReplaceAll(versionedRTK, "VERSION", filepath.Join(dir, "VERSION")))
write(t, filepath.Join(dir, "VERSION"), "0.40.1")
testenv.Program(t, filepath.Join(dir, "cargo"), `#!/bin/sh
-[ "$1 $2 $3" = "install --git https://github.com/rtk-ai/rtk" ] || exit 2
+[ "$*" = "install --git https://github.com/rtk-ai/rtk --branch master rtk --force" ] || exit 2
case " $* " in
*" rtk "*) echo 0.50.0 > "`+filepath.Join(dir, "VERSION")+`" ;;
*) echo "error: multiple packages with binaries found: rtk, rtk-proxy." >&2; exit 101 ;;