diff --git a/internal/cli/update_cli.go b/internal/cli/update_cli.go index 40efecf06..0a72d9e6a 100644 --- a/internal/cli/update_cli.go +++ b/internal/cli/update_cli.go @@ -23,6 +23,7 @@ var ( updateExecutable = update.Executable updateCanElevate = update.CanElevate updateInContainer = gateway.InContainer + updatePackagedBy = update.PackagedBy ) // updateEveries are the intervals magpie update auto takes, by their @@ -247,8 +248,13 @@ func updateCmd(args []string) error { if exe, err := updateExecutable(); err == nil && !update.Writable(filepath.Dir(exe)) && !updateCanElevate() && updateInContainer() { return fmt.Errorf("this magpie runs in a container and can't replace itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container") } - if exe, err := update.Executable(); err == nil && update.Homebrew(exe) { - return fmt.Errorf("this magpie was installed with Homebrew; update it with: brew upgrade magpie") + // a package manager's binary (Homebrew's, pacman's magpie-bin from + // the AUR, a .deb's): replaced under it, the manager's database names + // the old version and its next upgrade writes over this one + if exe, err := updateExecutable(); err == nil { + if p := updatePackagedBy(exe); p != nil { + return fmt.Errorf("%s", p.Say()) + } } fmt.Println(muted.Render(" downloading " + update.BinaryAsset() + via(ctx) + " …")) if err := update.ReplaceBinary(ctx, rel); err != nil { diff --git a/internal/cli/update_packaged_cli_test.go b/internal/cli/update_packaged_cli_test.go new file mode 100644 index 000000000..ba8f75a4a --- /dev/null +++ b/internal/cli/update_packaged_cli_test.go @@ -0,0 +1,47 @@ +package cli + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/update" +) + +// `magpie update` from the AUR's magpie-bin (/usr/bin/magpie) asked for the +// password and replaced the package's file under pacman (shuhai on +// Discord). It now says the version is out and the command that updates +// the package, and replaces nothing. +func TestUpdatePackagedSaysTheManager(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/asset" { + t.Errorf("a packaged binary downloaded the release") + } + json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", URL: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.11", + Assets: map[string]update.Asset{update.BinaryAsset(): {URL: "http://" + r.Host + "/asset"}}}) + })) + defer srv.Close() + t.Setenv("MAGPIE_UPDATE_FEED", srv.URL) + exe := filepath.Join(t.TempDir(), "magpie") + if err := os.WriteFile(exe, []byte("magpie"), 0o755); err != nil { + t.Fatal(err) + } + wasV, wasX, wasE, wasP := version, updateExecutable, updateCanElevate, updatePackagedBy + t.Cleanup(func() { version, updateExecutable, updateCanElevate, updatePackagedBy = wasV, wasX, wasE, wasP }) + version = "0.1.10" + updateExecutable = func() (string, error) { return exe, nil } + updateCanElevate = func() bool { return true } + updatePackagedBy = func(string) *update.Packaged { return &update.Packaged{Manager: "pacman", Package: "magpie-bin"} } + + err := updateCmd([]string{"update"}) + if err == nil || !strings.Contains(err.Error(), "pacman") || !strings.Contains(err.Error(), "yay -S magpie-bin") { + t.Fatalf("%v", err) + } + if b, _ := os.ReadFile(exe); string(b) != "magpie" { + t.Fatalf("the package's file was changed: %q", b) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a315b294c..d95f52a21 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -4413,7 +4413,8 @@ async function renderUpdateBadge() { delete b.dataset.pulling; b.classList.remove("busy"); } - const on = pulling || (!!u && !updatePillOff(u.latest) && (u.state === "ready" || u.state === "available" || u.state === "found" || (u.state === "error" && u.retry))); + // a package manager's magpie: Settings names its command, no pill + const on = pulling || (!!u && !updatePillOff(u.latest) && (u.state === "ready" || (u.state === "available" && !u.packaged) || u.state === "found" || (u.state === "error" && u.retry))); if (b.hidden !== !on) b.hidden = !on; if (!on) return; const hide = $("#updateHide"); @@ -4539,6 +4540,8 @@ async function backAsNew(was) { // the Mac, a folder it may not write to, such as C:\ (#1277), or a // container, whose image is what gets updated. function updateStuck(u) { + const p = u.packaged; + if (p) return p.command ? t("{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}", { manager: p.manager, pkg: p.package, cmd: p.command }) : t("{manager} installed magpie, so {manager} updates it, not magpie.", { manager: p.manager }); if (u.stuck === "container") return t("magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container."); if (u.stuck === "not-writable") return t("magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.", { dir: u.stuckDir || "" }); return u.stuck === "translocated" @@ -22642,6 +22645,7 @@ async function renderUpdate(r, u) { case "available": sub.textContent = t("{v} is out", { v: u.latest }); if (u.stuck) sub.textContent += " · " + updateStuck(u); + if (u.packaged) { sub.classList.add("wraps"); btn(t("Check"), check); break; } btn(t("Download"), () => (web && u.url ? window.open(u.url, "_blank", "noopener") : api("update/install", {}))); if (!web) page(); break; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 858122e23..a55e8d1b8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3274,6 +3274,8 @@ const I18N = { "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正从临时副本运行 magpie,无法自动更新;请将 magpie 移到「应用程序」文件夹后从那里打开。", "magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie 正从磁盘映像运行,无法自动更新;请将它拖到「应用程序」文件夹后从那里打开。", "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 无法写入它所在的文件夹({dir}),所以无法自动更新;请把它移到你有写入权限的文件夹,再从那里打开。", + "{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} 安装了 magpie({pkg}),所以由 {manager} 更新它,而不是 magpie 自己:{cmd}", + "{manager} installed magpie, so {manager} updates it, not magpie.": "由 {manager} 安装的 magpie 由 {manager} 更新,而不是 magpie 自己。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 运行在容器里,无法自动更新;请拉取新镜像(docker pull ghcr.io/yetone/magpie:latest)并重新创建容器。", "Config folder": "配置目录", "Log": "日志", @@ -7504,6 +7506,8 @@ const I18N = { "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正從臨時副本執行 magpie,無法自動更新;請將 magpie 移到「應用程式」資料夾後從那裡開啟。", "magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie 正從磁碟映像執行,無法自動更新;請將它拖到「應用程式」資料夾後從那裡開啟。", "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 無法寫入它所在的資料夾({dir}),所以無法自動更新;請把它移到你有寫入權限的資料夾,再從那裡開啟。", + "{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} 安裝了 magpie({pkg}),所以由 {manager} 更新它,而不是 magpie 自己:{cmd}", + "{manager} installed magpie, so {manager} updates it, not magpie.": "由 {manager} 安裝的 magpie 由 {manager} 更新,而不是 magpie 自己。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 在容器中執行,無法自動更新;請拉取新映像(docker pull ghcr.io/yetone/magpie:latest)並重新建立容器。", "Config folder": "設定目錄", "Log": "日誌", @@ -11745,6 +11749,8 @@ const I18N = { "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS が magpie を一時的なコピーから実行しているため、自動アップデートできません。magpie を「アプリケーション」フォルダに移動し、そこから開いてください。", "magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie がディスクイメージから実行されているため、自動アップデートできません。「アプリケーション」フォルダにドラッグし、そこから開いてください。", "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie は実行中のフォルダ({dir})に書き込めないため、自動アップデートできません。書き込み可能なフォルダに移動し、そこから開いてください。", + "{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "magpie は {manager} でインストールされている({pkg})ため、magpie ではなく {manager} がアップデートします:{cmd}", + "{manager} installed magpie, so {manager} updates it, not magpie.": "magpie は {manager} でインストールされているため、magpie ではなく {manager} がアップデートします。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie はコンテナで実行されているため、自動アップデートできません。新しいイメージを取得し(docker pull ghcr.io/yetone/magpie:latest)、コンテナを作り直してください。", "Config folder": "設定フォルダ", "Log": "ログ", @@ -15997,6 +16003,8 @@ const I18N = { "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS führt magpie aus einer temporären Kopie aus, daher kann es sich nicht selbst aktualisieren; verschieben Sie magpie in „Programme“ und öffnen Sie es von dort.", "magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie läuft aus seinem Disk-Image und kann sich daher nicht selbst aktualisieren; ziehen Sie es in „Programme“ und öffnen Sie es von dort.", "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie kann nicht in den Ordner schreiben, aus dem es läuft ({dir}), und kann sich daher nicht selbst aktualisieren; verschieben Sie es in einen Ordner mit Schreibrechten und öffnen Sie es von dort.", + "{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} hat magpie installiert ({pkg}), daher aktualisiert {manager} es, nicht magpie: {cmd}", + "{manager} installed magpie, so {manager} updates it, not magpie.": "{manager} hat magpie installiert, daher aktualisiert {manager} es, nicht magpie.", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie läuft in einem Container und kann sich daher nicht selbst aktualisieren; laden Sie das neue Image (docker pull ghcr.io/yetone/magpie:latest) und erstellen Sie den Container neu.", "Config folder": "Konfigurationsordner", "Log": "Protokoll", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 014de12c1..ac2ce1e1a 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -15,8 +15,8 @@ import ( // so a page can't quietly grow back into the core; a change that needs more // raises them and says why in its commit. const ( - appScriptBudget = 1_316_781 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31) - coreScriptBudget = 1_541_427 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); 1,541,427 with Tuned for you's Codex row offering the advice to background compaction, its foreground limit kept (herman_hong on Discord), in context.js, which Usage and Routing draw, the Codex-too-old line shared with Settings' row (codexHeld, app.js 278 bytes less), with no room added (10-31) + appScriptBudget = 1_316_874 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31); 1,316,874 with a package manager's magpie (the AUR's magpie-bin) naming the command that updates it in Settings' Version row and lighting no Update pill (shuhai on Discord), the core's own update row, which the tray panel reads too, its comments cut to one line, with no room added (10-31) + coreScriptBudget = 1_541_798 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); 1,541,427 with Tuned for you's Codex row offering the advice to background compaction, its foreground limit kept (herman_hong on Discord), in context.js, which Usage and Routing draw, the Codex-too-old line shared with Settings' row (codexHeld, app.js 278 bytes less), with no room added (10-31); 1,541,798 with a package manager's magpie naming its command (shuhai on Discord), in app.js, with no room added (10-31) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/update-stuck.test.cjs b/internal/gui/tests/update-stuck.test.cjs index 0e2ae3866..ad603b33e 100644 --- a/internal/gui/tests/update-stuck.test.cjs +++ b/internal/gui/tests/update-stuck.test.cjs @@ -98,3 +98,54 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } }); } + +// A magpie a package manager installed (the AUR's magpie-bin, shuhai on +// Discord) leaves its updates to the manager: the Version row says the +// version is out and the command that updates the package, with no +// Download (the release's binary isn't for this install) and no Update +// pill (the package can come days after the release). +const packaged = { state: "available", current: "0.1.400", latest: "0.1.401", url: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.401", stuck: "package", packaged: { manager: "pacman", package: "magpie-bin", command: "yay -S magpie-bin" } }; +const byManager = { + en: "pacman installed magpie (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin", + zh: "pacman 安装了 magpie(magpie-bin),所以由 pacman 更新它,而不是 magpie 自己:yay -S magpie-bin", + "zh-TW": "pacman 安裝了 magpie(magpie-bin),所以由 pacman 更新它,而不是 magpie 自己:yay -S magpie-bin", + ja: "magpie は pacman でインストールされている(magpie-bin)ため、magpie ではなく pacman がアップデートします:yay -S magpie-bin", + de: "pacman hat magpie installiert (magpie-bin), daher aktualisiert pacman es, nicht magpie: yay -S magpie-bin", +}; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a packaged magpie names its package manager's command", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1000, 440]) { + await t.test(`${lang} at ${width}px`, async () => { + const ctl = { installs: 0 }; + const errors = []; + const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); + await page.route("**/*", server(lang, ctl, packaged)); + await page.goto("http://magpie.test/?view=settings&tab=about"); + const want = byManager[lang]; + const sub = await (await page.waitForFunction((w) => [...document.querySelectorAll("#about .row.pref .sub")].find((s) => s.textContent.includes(w))?.textContent, want)).jsonValue(); + assert.ok(sub.includes("0.1.401"), sub); + const row = page.locator("#about .row.pref", { has: page.locator(".sub", { hasText: want }) }); + const buttons = await row.locator("button").allTextContents(); + const download = { en: "Download", zh: "下载", "zh-TW": "下載", ja: "ダウンロード", de: "Herunterladen" }[lang]; + assert.ok(!buttons.some((b) => b.trim() === download), buttons.join("|")); + // no Update pill, once the pill has read the update too (a fetch + // of /api/update beside the row's) + await page.waitForFunction(() => performance.getEntriesByType("resource").filter((e) => new URL(e.name).pathname === "/api/update").length >= 2); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + assert.equal(await page.locator("#update").isHidden(), true); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + assert.equal(ctl.installs, 0); + assert.deepEqual(errors, []); + await page.close(); + }); + } + } + }); +} diff --git a/internal/gui/update.go b/internal/gui/update.go index e60da7ca3..61145544d 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -28,19 +28,22 @@ import ( // restart asks for the administrator's password; only an app that can't be // replaced at all (run from its disk image, say) is sent to the release page. type updater struct { - mu sync.Mutex - state string // checking | latest | found | downloading | ready | available | source | error | blocked - latest *update.Release - err string - bundle string // the .app to replace, "" when not in one or stuck - stuck string // why the .app or binary can't be replaced where it is (update.Stuck, exeStuck) - exe string // not in a .app: the binary to replace, "" when not writable - exeDir string // not in a .app: the binary's folder, named when it is stuck there - self os.FileInfo // exe (in a .app: bundleExe) as this process started from it - retry bool // error: the download failed, and may be tried again - mirror string // error: the mirror the failed download came through (#893) - network bool // error: the network broke the download off (update.Network) - staged string + mu sync.Mutex + state string // checking | latest | found | downloading | ready | available | source | error | blocked + latest *update.Release + err string + bundle string // the .app to replace, "" when not in one or stuck + stuck string // why the .app or binary can't be replaced where it is (update.Stuck, exeStuck) + exe string // not in a .app: the binary to replace, "" when not writable + exeDir string // not in a .app: the binary's folder, named when it is stuck there + // stuck "package": the package manager that installed the binary, + // which updates it instead (update.PackagedBy) + packaged *update.Packaged + self os.FileInfo // exe (in a .app: bundleExe) as this process started from it + retry bool // error: the download failed, and may be tried again + mirror string // error: the mirror the failed download came through (#893) + network bool // error: the network broke the download off (update.Network) + staged string // stable: latest was found on Settings' Stable channel stable bool aside string // Windows: where install moved the running exe, to put back @@ -92,7 +95,11 @@ type updateJSON struct { Stuck string `json:"stuck,omitempty"` // available: why it can't update itself // available, stuck "not-writable": the folder magpie may not write to StuckDir string `json:"stuckDir,omitempty"` - Retry bool `json:"retry,omitempty"` // error: a click downloads it again + // available, stuck "package": the package manager that installed + // magpie and updates it (pacman's magpie-bin from the AUR, say), and + // the command that does + Packaged *packagedJSON `json:"packaged,omitempty"` + Retry bool `json:"retry,omitempty"` // error: a click downloads it again // error: the download failed through this mirror (Settings' UpdateMirror), // and GitHub itself may do (#893) Mirror string `json:"mirror,omitempty"` @@ -183,9 +190,16 @@ func (u *updater) place(goos string, gui bool) { } // placeExe takes exe as the binary an update replaces, or -// says why it can't be (stuck). +// says why it can't be (stuck). A binary a package manager installed is +// left to it ("package"), even where magpie may write or ask for the +// administrator's password: replacing it under the manager is what made +// the two fight (shuhai on Discord, the AUR's magpie-bin). func (u *updater) placeExe(exe string) { u.exeDir = filepath.Dir(exe) + if p := packagedBy(exe); p != nil { + u.stuck, u.packaged = "package", p + return + } if u.stuck = exeStuck(u.exeDir); u.stuck != "" { return } @@ -219,8 +233,15 @@ func exeStuck(dir string) string { var ( canElevate = update.CanElevate inContainer = gateway.InContainer + packagedBy = update.PackagedBy ) +type packagedJSON struct { + Manager string `json:"manager"` // as its users call it: pacman, apt, rpm, Homebrew, Nix + Package string `json:"package,omitempty"` + Command string `json:"command,omitempty"` // what updates it, "" when no one command does +} + // check asks the feed and, when it can, stages the new version. func (u *updater) check() { if u.begin() { @@ -582,6 +603,9 @@ func (u *updater) jsonIn(lang string) updateJSON { if u.stuck == "not-writable" { j.StuckDir = u.exeDir } + if u.stuck == "package" && u.packaged != nil { + j.Packaged = &packagedJSON{Manager: u.packaged.Name(), Package: u.packaged.Package, Command: u.packaged.Command()} + } } if u.state == "downloading" { j.Done, j.Total = u.done, u.total @@ -730,6 +754,9 @@ func updateRoutes(mux *http.ServeMux, w Windows) { // a click: the download is asked for, whatever Settings' // NoAutoDownload says (#2296) updates.download() + case j.State == "available" && j.Stuck == "package": + // the package manager updates it: the release page's download + // isn't for this install case j.State == "available" && j.URL != "": // the newest's page, not the one the last check found: a check // over a minute old is made again first (coeo91 on Discord) diff --git a/internal/gui/update_packaged_test.go b/internal/gui/update_packaged_test.go new file mode 100644 index 000000000..c860c759f --- /dev/null +++ b/internal/gui/update_packaged_test.go @@ -0,0 +1,69 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/update" +) + +// The AUR's magpie-bin installs /usr/bin/magpie, and with pkexec there +// magpie put its own download over the package's file on a restart, so +// pacman's database named one version and the disk had another, and the +// next yay upgrade wrote over it again (shuhai on Discord). A binary a +// package manager installed now says a version is out and the command +// that updates it, and never downloads or replaces anything, even where +// it may write or ask for the password. +func TestUpdatePackagedLeavesItToTheManager(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/asset" { + t.Errorf("a packaged binary downloaded the release") + } + json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", URL: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.11", Assets: map[string]update.Asset{ + update.BinaryAsset(): {URL: "http://" + r.Host + "/asset"}, + }}) + })) + defer srv.Close() + t.Setenv("MAGPIE_UPDATE_FEED", srv.URL) + old := Version + Version = "0.1.10" + defer func() { Version = old }() + wasE, wasP := canElevate, packagedBy + defer func() { canElevate, packagedBy = wasE, wasP }() + canElevate = func() bool { return true } + + dir := t.TempDir() // writable: ownership alone decides + exe := filepath.Join(dir, "magpie") + if err := os.WriteFile(exe, []byte("magpie"), 0o755); err != nil { + t.Fatal(err) + } + packagedBy = func(string) *update.Packaged { return &update.Packaged{Manager: "pacman", Package: "magpie-bin"} } + u := &updater{} + u.placeExe(exe) + if u.exe != "" { + t.Fatalf("a packaged binary is to be replaced: %q", u.exe) + } + u.check() + j := u.json() + if j.State != "available" || j.Stuck != "package" || j.Packaged == nil || j.Packaged.Manager != "pacman" || j.Packaged.Package != "magpie-bin" || j.Packaged.Command != "yay -S magpie-bin" || j.Latest != "0.1.11" { + t.Fatalf("%+v %+v", j, j.Packaged) + } + if u.install(true) { + t.Fatal("install put something in") + } + if b, _ := os.ReadFile(exe); string(b) != "magpie" { + t.Fatalf("the package's file was changed: %q", b) + } + + // a binary no package owns updates itself as before + packagedBy = func(string) *update.Packaged { return nil } + u = &updater{} + u.placeExe(exe) + if u.exe != exe || u.stuck != "" { + t.Fatalf("not packaged: exe %q, stuck %q", u.exe, u.stuck) + } +} diff --git a/internal/update/packaged.go b/internal/update/packaged.go new file mode 100644 index 000000000..b7beefb37 --- /dev/null +++ b/internal/update/packaged.go @@ -0,0 +1,262 @@ +package update + +import ( + "bufio" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + + "github.com/yetone/magpie/internal/proc" +) + +// Packaged is the package manager that installed a magpie binary, which +// then has to be the one to update it. magpie replacing a file a package +// owns (pkexec over /usr/bin/magpie from the AUR's magpie-bin, shuhai on +// Discord) leaves the manager's database naming an older version and a +// file that no longer matches it, and the manager's next upgrade, which +// can be a version older than the one magpie put in, writes over it again. +type Packaged struct { + Manager string `json:"manager"` // pacman, dpkg, rpm, homebrew or nix + Package string `json:"package,omitempty"` // the package's name, when known +} + +// Name is the manager as its users call it. +func (p *Packaged) Name() string { + switch p.Manager { + case "dpkg": + return "apt" + case "homebrew": + return "Homebrew" + case "nix": + return "Nix" + } + return p.Manager +} + +// Command is what updates the package, "" when there is no one command +// (Nix: a profile or a system configuration). magpie is in no distribution's +// own repository, so a pacman package is the AUR's, which pacman alone +// doesn't upgrade: its AUR helper does. +func (p *Packaged) Command() string { + pkg := p.Package + if pkg == "" { + pkg = "magpie" + } + switch p.Manager { + case "pacman": + return "yay -S " + pkg + case "dpkg": + return "sudo apt install --only-upgrade " + pkg + case "rpm": + return "sudo dnf upgrade " + pkg + case "homebrew": + return "brew upgrade " + pkg + } + return "" +} + +// Say is the sentence a terminal is told: who updates this magpie, and how. +func (p *Packaged) Say() string { + s := "this magpie was installed with " + p.Name() + if p.Package != "" { + s += " (package " + p.Package + ")" + } + s += ", which updates it, not magpie" + if c := p.Command(); c != "" { + s += ": " + c + if p.Manager == "pacman" { + s += " (or paru, or the AUR helper it came from)" + } + } + return s +} + +// PackagedBy says which package manager installed exe (the running +// binary, symlinks resolved), nil when none did. +func PackagedBy(exe string) *Packaged { + return packagedIn("/", runtime.GOOS, exe) +} + +// rpmOwner is the rpm package owning path, "" when none; a test stands in +// for it. rpm's database is SQLite (or Berkeley DB), read through rpm. +var rpmOwner = func(path string) string { + out, err := proc.Command("rpm", "-qf", "--queryformat", "%{NAME}", path).Output() + if err != nil { + return "" + } + s := strings.TrimSpace(string(out)) + if s == "" || strings.Contains(s, " ") { // "file … is not owned by any package" + return "" + } + return s +} + +// packagedIn is PackagedBy with the system's files under root. +func packagedIn(root, goos, exe string) *Packaged { + p := filepath.ToSlash(exe) + if _, rest, ok := strings.Cut(p, "/Cellar/"); ok { + name, _, _ := strings.Cut(rest, "/") + return &Packaged{Manager: "homebrew", Package: name} + } + if goos != "linux" { + return nil + } + if strings.HasPrefix(p, "/nix/store/") { + return &Packaged{Manager: "nix"} + } + if !systemPath(p) { + return nil + } + if name, ok := pacmanOwner(root, p); ok { + return &Packaged{Manager: "pacman", Package: name} + } + if name, ok := dpkgOwner(root, p); ok { + return &Packaged{Manager: "dpkg", Package: name} + } + if isDir(filepath.Join(root, "var/lib/rpm")) { + if name := rpmOwner(p); name != "" { + return &Packaged{Manager: "rpm", Package: name} + } + } + return nil +} + +// systemPath is whether a package may own p: /usr (but not /usr/local, +// which packages leave to the machine's own), /bin, /sbin, /opt. +func systemPath(p string) bool { + if strings.HasPrefix(p, "/usr/local/") { + return false + } + for _, d := range []string{"/usr/", "/bin/", "/sbin/", "/opt/"} { + if strings.HasPrefix(p, d) { + return true + } + } + return false +} + +// aliases are the names p has in a package's file list: on a merged /usr +// /bin is /usr/bin, and a package may list either. +func aliases(p string) []string { + out := []string{p} + for _, d := range []string{"/bin/", "/sbin/", "/lib/"} { + if strings.HasPrefix(p, "/usr"+d) { + out = append(out, strings.TrimPrefix(p, "/usr")) + } else if strings.HasPrefix(p, d) { + out = append(out, "/usr"+p) + } + } + return out +} + +// magpieFirst orders names with those starting "magpie" first: the package +// owning magpie is all but always one of them (magpie-bin, magpie-cli-bin, +// magpie-git), so the rest are read only when none is. +func magpieFirst(names []string) []string { + slices.SortStableFunc(names, func(a, b string) int { + ma, mb := strings.HasPrefix(a, "magpie"), strings.HasPrefix(b, "magpie") + switch { + case ma && !mb: + return -1 + case mb && !ma: + return 1 + } + return 0 + }) + return names +} + +// pacmanOwner reads pacman's local database, a folder per installed +// package (name-version-release) holding the list of its files, each +// without its leading slash. +func pacmanOwner(root, p string) (string, bool) { + dir := filepath.Join(root, "var/lib/pacman/local") + ents, err := os.ReadDir(dir) + if err != nil { + return "", false + } + var names []string + for _, e := range ents { + if e.IsDir() { + names = append(names, e.Name()) + } + } + want := aliases(p) + for i := range want { + want[i] = strings.TrimPrefix(want[i], "/") + } + for _, n := range magpieFirst(names) { + if listed(filepath.Join(dir, n, "files"), want) { + return pacmanName(filepath.Join(dir, n), n), true + } + } + return "", false +} + +// pacmanName is the package's name, from its desc (%NAME%), else its +// folder's name without its version and release. +func pacmanName(dir, folder string) string { + if b, err := os.ReadFile(filepath.Join(dir, "desc")); err == nil { + lines := strings.Split(string(b), "\n") + for i, l := range lines { + if strings.TrimSpace(l) == "%NAME%" && i+1 < len(lines) { + if n := strings.TrimSpace(lines[i+1]); n != "" { + return n + } + } + } + } + parts := strings.Split(folder, "-") + if len(parts) > 2 { + return strings.Join(parts[:len(parts)-2], "-") + } + return folder +} + +// dpkgOwner reads dpkg's file lists, one name.list (or name:arch.list) per +// installed package, each line an absolute path. +func dpkgOwner(root, p string) (string, bool) { + dir := filepath.Join(root, "var/lib/dpkg/info") + ents, err := os.ReadDir(dir) + if err != nil { + return "", false + } + var names []string + for _, e := range ents { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".list") { + names = append(names, e.Name()) + } + } + want := aliases(p) + for _, n := range magpieFirst(names) { + if listed(filepath.Join(dir, n), want) { + name, _, _ := strings.Cut(strings.TrimSuffix(n, ".list"), ":") + return name, true + } + } + return "", false +} + +// listed is whether the file list at path has a line equal to one of want. +func listed(path string, want []string) bool { + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + sc := bufio.NewScanner(f) + sc.Buffer(make([]byte, 64*1024), 1<<20) + for sc.Scan() { + if slices.Contains(want, strings.TrimSpace(sc.Text())) { + return true + } + } + return false +} + +func isDir(path string) bool { + st, err := os.Stat(path) + return err == nil && st.IsDir() +} diff --git a/internal/update/packaged_test.go b/internal/update/packaged_test.go new file mode 100644 index 000000000..4075069fa --- /dev/null +++ b/internal/update/packaged_test.go @@ -0,0 +1,135 @@ +package update + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// pacman's local database as the AUR's magpie-bin 0.1.2342-1 leaves it +// (its PKGBUILD installs /usr/bin/magpie), beside a package that doesn't +// own magpie. +func pacmanRoot(t *testing.T) string { + root := t.TempDir() + local := filepath.Join(root, "var/lib/pacman/local") + writeFile(t, filepath.Join(local, "ALPM_DB_VERSION"), "9\n") + writeFile(t, filepath.Join(local, "bash-5.3.3-2/files"), "%FILES%\nusr/\nusr/bin/\nusr/bin/bash\nusr/bin/sh\n\n%BACKUP%\netc/bash.bashrc\t0b5ab6a3\n") + writeFile(t, filepath.Join(local, "bash-5.3.3-2/desc"), "%NAME%\nbash\n\n%VERSION%\n5.3.3-2\n") + writeFile(t, filepath.Join(local, "magpie-bin-0.1.2342-1/files"), "%FILES%\nusr/\nusr/bin/\nusr/bin/magpie\nusr/share/\nusr/share/applications/\nusr/share/applications/magpie.desktop\nusr/share/icons/hicolor/256x256/apps/magpie.png\nusr/share/licenses/magpie-bin/LICENSE\n\n") + writeFile(t, filepath.Join(local, "magpie-bin-0.1.2342-1/desc"), "%NAME%\nmagpie-bin\n\n%VERSION%\n0.1.2342-1\n\n%BASE%\nmagpie-bin\n") + return root +} + +func TestPackagedByPacman(t *testing.T) { + root := pacmanRoot(t) + p := packagedIn(root, "linux", "/usr/bin/magpie") + if p == nil || p.Manager != "pacman" || p.Package != "magpie-bin" { + t.Fatalf("/usr/bin/magpie from magpie-bin: %+v", p) + } + if c := p.Command(); c != "yay -S magpie-bin" { + t.Fatalf("command %q", c) + } + if s := p.Say(); !strings.Contains(s, "pacman") || !strings.Contains(s, "yay -S magpie-bin") { + t.Fatalf("said %q", s) + } + // /bin is /usr/bin on Arch: the same file + if p := packagedIn(root, "linux", "/bin/magpie"); p == nil || p.Package != "magpie-bin" { + t.Fatalf("/bin/magpie: %+v", p) + } + // a copy in /usr/local, ~/.local/bin or /opt that no package lists is + // the user's own, and updates itself + for _, exe := range []string{"/usr/local/bin/magpie", "/home/u/.local/bin/magpie", "/opt/magpie/magpie", "/usr/lib/magpie/magpie"} { + if p := packagedIn(root, "linux", exe); p != nil { + t.Fatalf("%s: %+v", exe, p) + } + } + // not Linux: pacman's files aren't read + if p := packagedIn(root, "darwin", "/usr/bin/magpie"); p != nil { + t.Fatalf("darwin: %+v", p) + } +} + +// A package named otherwise is found too, its name from the folder when +// its desc can't be read. +func TestPackagedByPacmanOtherName(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "var/lib/pacman/local/ai-tools-2.0-3/files"), "%FILES%\nopt/ai/bin/magpie\n") + p := packagedIn(root, "linux", "/opt/ai/bin/magpie") + if p == nil || p.Package != "ai-tools" { + t.Fatalf("%+v", p) + } +} + +// dpkg lists absolute paths, and on a merged /usr may list /bin for the +// /usr/bin the binary resolves to. +func TestPackagedByDpkg(t *testing.T) { + root := t.TempDir() + info := filepath.Join(root, "var/lib/dpkg/info") + writeFile(t, filepath.Join(info, "coreutils.list"), "/.\n/bin\n/bin/ls\n") + writeFile(t, filepath.Join(info, "magpie:amd64.list"), "/.\n/usr\n/usr/bin\n/usr/bin/magpie\n") + p := packagedIn(root, "linux", "/usr/bin/magpie") + if p == nil || p.Manager != "dpkg" || p.Package != "magpie" || p.Name() != "apt" || p.Command() != "sudo apt install --only-upgrade magpie" { + t.Fatalf("%+v", p) + } + if p := packagedIn(root, "linux", "/usr/bin/ls"); p == nil || p.Package != "coreutils" { + t.Fatalf("merged /usr: %+v", p) + } + if p := packagedIn(root, "linux", "/usr/sbin/magpie"); p != nil { + t.Fatalf("not listed: %+v", p) + } +} + +func TestPackagedByRpm(t *testing.T) { + root := t.TempDir() + was := rpmOwner + t.Cleanup(func() { rpmOwner = was }) + asked := "" + rpmOwner = func(path string) string { asked = path; return "magpie" } + // no rpm database: rpm isn't asked + if p := packagedIn(root, "linux", "/usr/bin/magpie"); p != nil || asked != "" { + t.Fatalf("no rpm here: %+v, asked %q", p, asked) + } + if err := os.MkdirAll(filepath.Join(root, "var/lib/rpm"), 0o755); err != nil { + t.Fatal(err) + } + p := packagedIn(root, "linux", "/usr/bin/magpie") + if p == nil || p.Manager != "rpm" || asked != "/usr/bin/magpie" || p.Command() != "sudo dnf upgrade magpie" { + t.Fatalf("%+v, asked %q", p, asked) + } + rpmOwner = func(string) string { return "" } + if p := packagedIn(root, "linux", "/usr/bin/magpie"); p != nil { + t.Fatalf("not owned: %+v", p) + } +} + +func TestPackagedByHomebrewAndNix(t *testing.T) { + root := t.TempDir() + for exe, want := range map[string]string{ + "/opt/homebrew/Cellar/magpie/0.1.126/bin/magpie": "homebrew magpie brew upgrade magpie", + "/home/linuxbrew/.linuxbrew/Cellar/magpie/0.1.126/bin/magpie": "homebrew magpie brew upgrade magpie", + "/nix/store/abc123-magpie-0.1.2342/bin/magpie": "nix ", + } { + goos := "linux" + if strings.HasPrefix(exe, "/opt/homebrew") { + goos = "darwin" + } + p := packagedIn(root, goos, exe) + if p == nil || p.Manager+" "+p.Package+" "+p.Command() != want { + t.Fatalf("%s: %+v", exe, p) + } + } + if p := packagedIn(root, "darwin", "/Applications/magpie.app/Contents/MacOS/magpie"); p != nil { + t.Fatalf("the app: %+v", p) + } +}