Skip to content

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

gui: a magpie folder the user can't write gets a one-click Repair (YouWhat)

yetone5be581a1c326
diff --git a/internal/appdir/blocked.go b/internal/appdir/blocked.go
new file mode 100644
index 000000000..0f9072f61
--- /dev/null
+++ b/internal/appdir/blocked.go
@@ -0,0 +1,92 @@
+//go:build !windows
+
+package appdir
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+// Blocked is the folder that keeps magpie from writing its own files, or ""
+// when it can: magpie's config or cache folder that this user can't write,
+// or, while one of them isn't there yet, the folder it would be made in. A
+// ~/.config that a command run under sudo made belongs to root, so magpie
+// couldn't make ~/.config/magpie and every save failed with "permission
+// denied" (YouWhat on Discord). Only a folder inside the home folder is
+// named: one outside it (an XDG_CONFIG_HOME on a shared disk) isn't the
+// user's to take back.
+func Blocked() string {
+ h, err := Home()
+ if err != nil {
+ return ""
+ }
+ for _, dir := range []string{Config(), Cache()} {
+ if b := blockedAt(dir); b != "" && inside(b, h) {
+ return b
+ }
+ }
+ return ""
+}
+
+// blockedAt is the folder on the way to dir this user can't write, "" when
+// dir is writable or can be made.
+func blockedAt(dir string) string {
+ for p := filepath.Clean(dir); ; {
+ fi, err := os.Stat(p)
+ switch {
+ case err == nil:
+ if !fi.IsDir() || writable(p) {
+ return "" // a file in the way isn't a matter of owners
+ }
+ return p
+ case !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission):
+ return ""
+ }
+ up := filepath.Dir(p)
+ if up == p {
+ return ""
+ }
+ p = up
+ }
+}
+
+// writable says whether this user can make and change files in dir.
+func writable(dir string) bool {
+ return syscall.Access(dir, 0x2|0x1) == nil // W_OK|X_OK
+}
+
+// inside says whether p is strictly inside dir.
+func inside(p, dir string) bool {
+ rel, err := filepath.Rel(filepath.Clean(dir), filepath.Clean(p))
+ return err == nil && rel != "." && rel != ".." && !filepath.IsAbs(rel) && !startsUp(rel)
+}
+
+func startsUp(rel string) bool {
+ return len(rel) >= 3 && rel[:3] == ".."+string(filepath.Separator)
+}
+
+// Own says whether p is magpie's own folder or inside it: its config or
+// cache folder. A repair may take back everything in it; anything above
+// it is changed only by itself.
+func Own(p string) bool {
+ for _, dir := range []string{Config(), Cache()} {
+ if c := filepath.Clean(p); c == filepath.Clean(dir) || inside(c, dir) {
+ return true
+ }
+ }
+ return false
+}
+
+// Mine says whether this user owns p, so its mode can be put right without
+// an administrator.
+func Mine(p string) bool {
+ fi, err := os.Stat(p)
+ if err != nil {
+ return false
+ }
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ return ok && int(st.Uid) == os.Getuid()
+}
diff --git a/internal/appdir/blocked_test.go b/internal/appdir/blocked_test.go
new file mode 100644
index 000000000..fe7c0c4a5
--- /dev/null
+++ b/internal/appdir/blocked_test.go
@@ -0,0 +1,49 @@
+//go:build !windows
+
+package appdir
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// A ~/.config the user can't write (sudo made it root's) is named as what
+// blocks magpie; a writable one, or one not there yet under a writable
+// home, isn't; and a folder outside the home folder is never named.
+func TestBlockedNamesTheFolderInTheWay(t *testing.T) {
+ if os.Getuid() == 0 {
+ t.Skip("root writes any folder")
+ }
+ UseExecutable("")
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ t.Setenv("XDG_CACHE_HOME", "")
+ if b := Blocked(); b != "" {
+ t.Fatalf("Blocked = %q with nothing made yet, want empty", b)
+ }
+ cfg := filepath.Join(home, ".config")
+ os.Mkdir(cfg, 0o555)
+ t.Cleanup(func() { os.Chmod(cfg, 0o755) })
+ if b := Blocked(); b != cfg {
+ t.Fatalf("Blocked = %q, want %s", b, cfg)
+ }
+ if !Mine(cfg) {
+ t.Fatal("Mine = false for the user's own folder")
+ }
+ if Own(cfg) || !Own(filepath.Join(cfg, "magpie")) || !Own(filepath.Join(cfg, "magpie", "x")) {
+ t.Fatal("Own: only magpie's own folder and what is in it")
+ }
+ os.Chmod(cfg, 0o755)
+ if b := Blocked(); b != "" {
+ t.Fatalf("Blocked = %q once writable, want empty", b)
+ }
+ outside := t.TempDir()
+ os.Chmod(outside, 0o555)
+ t.Cleanup(func() { os.Chmod(outside, 0o755) })
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(outside, "cfg"))
+ if b := Blocked(); b != "" {
+ t.Fatalf("Blocked = %q outside the home folder, want empty: not the user's to take back", b)
+ }
+}
diff --git a/internal/appdir/blocked_windows.go b/internal/appdir/blocked_windows.go
new file mode 100644
index 000000000..65da4901a
--- /dev/null
+++ b/internal/appdir/blocked_windows.go
@@ -0,0 +1,11 @@
+package appdir
+
+// Blocked is "" on Windows: a profile folder there isn't taken over by a
+// command run as Administrator the way sudo leaves ~/.config root's.
+func Blocked() string { return "" }
+
+// Own says whether p is magpie's own folder or inside it.
+func Own(p string) bool { return false }
+
+// Mine says whether this user owns p.
+func Mine(p string) bool { return false }
diff --git a/internal/gui/api.go b/internal/gui/api.go
index c3ebdeb05..46de8c878 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -287,8 +287,12 @@ type stateJSON struct {
// it's a copied file rather than the installer's link: a copy can't
// follow updates (#531's lesson). "" when it's the link or absent, or
// the advice was dismissed for this version.
- CLIBehind string `json:"cliBehind,omitempty"`
- Settings settings.Settings `json:"settings"`
+ CLIBehind string `json:"cliBehind,omitempty"`
+ // ConfigBlocked is the folder this user can't write that keeps magpie
+ // from saving its files (a ~/.config sudo left root's), which the
+ // window offers to make theirs again; "" when magpie can save
+ ConfigBlocked string `json:"configBlocked,omitempty"`
+ Settings settings.Settings `json:"settings"`
// FX is the dollar-to-yuan rate the cny currency choice shows costs at,
// here too (not only in settingsJSON) so a cost drawn before the reader
// ever opens Settings already converts, if cny was chosen last time.
@@ -1249,6 +1253,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
updateRoutes(mux, w)
whatsNewRoutes(mux)
cliBehindRoutes(mux)
+ configRepairRoutes(mux, !isWeb(w))
gatewayFixRoutes(mux)
gatewayModeRoutes(mux)
if !isWeb(w) {
@@ -2557,6 +2562,7 @@ func state() stateJSON {
}
s.Unlisted = unlistedModels()
s.CLIBehind = cliBehind()
+ s.ConfigBlocked = configBlocked()
for _, e := range provider.Served() {
if e.Group == "" {
s.Served++
@@ -2841,6 +2847,13 @@ func fail(rw http.ResponseWriter, err error) {
if errors.As(err, &noHandler) {
out["code"], out["app"], out["exe"], out["said"] = "no_link_handler", noHandler.App, noHandler.Exe, linkSaid[noHandler.Exe != ""]
}
+ // a save refused because a folder on the way to magpie's own isn't the
+ // user's: the window offers to make it theirs again
+ if permissionDenied(err) {
+ if b := configBlocked(); b != "" {
+ out["code"], out["blocked"] = "config_blocked", b
+ }
+ }
var noModels *agent.NoModelsError
if errors.As(err, &noModels) {
out["code"] = "no_models"
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index cce8d6b12..143c665aa 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -150,6 +150,11 @@ async function api(path, body, heads, signal) {
err.code = data.code;
err.message = t("None of magpie's models is left in {agent}'s model list: pick one under Model list → Pick, then connect {agent}", { agent: data.agent });
}
+ if (data?.code === "config_blocked") { // a folder magpie can't write: Repair offered
+ err.code = data.code;
+ err.message = t("magpie can't save into {path}: it belongs to another user", { path: data.blocked });
+ setTimeout(() => configBlockedAsk(data.blocked), 0);
+ }
if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language
if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go)
// an account the agent is signed in to, refused removal while it has
@@ -4251,6 +4256,7 @@ async function load(again) {
}
renderUpdateBadge();
cliBehindOnce();
+ if (state?.configBlocked && !configBlockedAsked && $("#modal").hidden) configBlockedAsk(state.configBlocked);
whatsNewOnce();
recoveredOnce();
}
@@ -4482,6 +4488,37 @@ function cliBehindOnce() {
$("#modal").classList.add("lib");
ok.focus({ preventScroll: true });
}
+// configBlockedAsk: a folder on the way to magpie's own isn't the user's (a
+// ~/.config sudo made root's, YouWhat): Repair makes it theirs, once a load
+// and over the save it failed, which it goes back to
+let configBlockedAsked = false;
+function configBlockedAsk(path) {
+ if (mode === "panel" || !path || confirmAsk?.classList.contains("cfg-blocked")) return;
+ configBlockedAsked = true;
+ const m = $("#modal"), under = !m.hidden && !m.classList.contains("out") && !confirmAsk && m.firstElementChild.firstElementChild;
+ const ed = el("div", "editor cfg-blocked"), head = el("div", "ehead"), bar = el("div", "bar");
+ head.append(el("b", "", t("magpie can't save its settings")));
+ ed.append(head, el("p", "lib-confirm", t("{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.", { path })));
+ const later = el("button", "text", t("Not now")), go = el("button", "text primary", t("Repair"));
+ later.onclick = cancelAsk;
+ go.onclick = async (e) => {
+ e.stopPropagation();
+ go.disabled = true;
+ try {
+ if ((await api("config/repair", {}))?.canceled) return;
+ if (state) state.configBlocked = "";
+ closeConfirmAsk();
+ status(t("Repaired: magpie can save again"), "ok");
+ } catch (err) { status(err.message, "err", 12000); } finally { go.disabled = false; }
+ };
+ bar.append(el("span", "grow"), later, go);
+ ed.append(bar);
+ if (under) ed.back = () => openModal(under);
+ confirmAsk = ed;
+ openModal(ed);
+ m.classList.add("lib");
+ go.focus({ preventScroll: true });
+}
async function whatsNewOnce() {
if (whatsNewAsked || mode === "panel" || document.hidden || !$("#modal").hidden) return;
whatsNewAsked = true;
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 1182180e1..6db0ce73b 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -1612,6 +1612,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "隐藏,直到又有已弃用的订阅登录",
"{names} can run on it again, with the same accounts.": "{names} 可以再次由它运行,账号不变。",
"Not now": "暂不",
+ "magpie can't save into {path}: it belongs to another user": "magpie 无法保存到 {path}:它属于另一个用户",
+ "magpie can't save its settings": "magpie 无法保存设置",
+ "{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} 属于另一个用户(常见于以前用 sudo 运行过某个命令),magpie 无法在那里保存供应商和设置。点「修复」把它改回归你所有;系统可能会要求输入密码。",
+ "Repair": "修复",
+ "Repaired: magpie can save again": "已修复:magpie 可以保存了",
"{user} is signed out": "{user} 已退出登录",
"Signed out": "已退出登录",
"Move {name} here": "把 {name} 迁到这里",
@@ -5712,6 +5717,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "隱藏,直到又有已棄用的訂閱登入",
"{names} can run on it again, with the same accounts.": "{names} 可以再次由它執行,帳號不變。",
"Not now": "暫不",
+ "magpie can't save into {path}: it belongs to another user": "magpie 無法儲存到 {path}:它屬於另一個使用者",
+ "magpie can't save its settings": "magpie 無法儲存設定",
+ "{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} 屬於另一個使用者(常見於以前用 sudo 執行過某個指令),magpie 無法在那裡儲存供應商和設定。按「修復」把它改回歸你所有;系統可能會要求輸入密碼。",
+ "Repair": "修復",
+ "Repaired: magpie can save again": "已修復:magpie 可以儲存了",
"{user} is signed out": "{user} 已退出登入",
"Signed out": "已退出登入",
"Move {name} here": "把 {name} 遷到這裡",
@@ -9789,6 +9799,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "別の非推奨サブスクリプションにサインインするまで非表示にする",
"{names} can run on it again, with the same accounts.": "{names} は同じアカウントのまま、再びこれで動作できます。",
"Not now": "後で",
+ "magpie can't save into {path}: it belongs to another user": "magpie は {path} に保存できません:別のユーザーのものです",
+ "magpie can't save its settings": "magpie が設定を保存できません",
+ "{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} は別のユーザーのものです(sudo でコマンドを実行した後によくあります)。そのため magpie はプロバイダーや設定をそこに保存できません。「修復」であなたのものに戻します。システムがパスワードを求めることがあります。",
+ "Repair": "修復",
+ "Repaired: magpie can save again": "修復しました:magpie は保存できます",
"{user} is signed out": "{user} はサインアウトしました",
"Signed out": "サインアウトしました",
"Move {name} here": "{name} をここへ移行",
@@ -13896,6 +13911,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "Ausblenden, bis ein weiteres veraltetes Abo angemeldet wird",
"{names} can run on it again, with the same accounts.": "{names} kann wieder darüber laufen, mit denselben Konten.",
"Not now": "Nicht jetzt",
+ "magpie can't save into {path}: it belongs to another user": "magpie kann nicht in {path} speichern: Der Ordner gehört einem anderen Benutzer",
+ "magpie can't save its settings": "magpie kann seine Einstellungen nicht speichern",
+ "{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} gehört einem anderen Benutzer, oft nachdem ein Befehl mit sudo ausgeführt wurde, daher kann magpie dort keine Anbieter oder Einstellungen speichern. „Reparieren“ macht ihn wieder zu Ihrem; das System fragt eventuell nach Ihrem Passwort.",
+ "Repair": "Reparieren",
+ "Repaired: magpie can save again": "Repariert: magpie kann wieder speichern",
"{user} is signed out": "{user} ist abgemeldet",
"Signed out": "Abgemeldet",
"Move {name} here": "{name} hierher umziehen",
diff --git a/internal/gui/config_repair.go b/internal/gui/config_repair.go
new file mode 100644
index 000000000..fc7f48da6
--- /dev/null
+++ b/internal/gui/config_repair.go
@@ -0,0 +1,108 @@
+package gui
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/update"
+)
+
+// A folder on the way to magpie's own that this user can't write — most
+// often a ~/.config a command run under sudo once made, so it belongs to
+// root — fails every save with "permission denied" (YouWhat on Discord:
+// adding a custom provider said "mkdir ~/.config/magpie: permission
+// denied"). magpie's files stay where every reader looks for them; the
+// window offers to make that folder the user's again, with one click and
+// the system's password prompt. Only that folder changes: ~/.config gets
+// its owner back and nothing in it does, since the other apps' folders
+// there are theirs, and magpie's own folder, when it is the one taken, is
+// taken back whole.
+
+// configBlocked is the folder that keeps magpie from saving, as the window
+// names it, or "".
+func configBlocked() string {
+ if b := appdir.Blocked(); b != "" {
+ return tilde(b)
+ }
+ return ""
+}
+
+// permissionDenied says whether err is the system refusing a write.
+func permissionDenied(err error) bool {
+ if errors.Is(err, fs.ErrPermission) {
+ return true
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "permission denied") || strings.Contains(msg, "operation not permitted")
+}
+
+// asAdmin runs a script as root after the system's password prompt; tests
+// stand in for it.
+var asAdmin = update.AsAdmin
+
+// mine says whether this user owns a folder; tests stand in for it.
+var mine = appdir.Mine
+
+// errRepairCanceled is the password prompt dismissed.
+var errRepairCanceled = update.ErrCanceled
+
+// repairConfig makes the folder that keeps magpie from saving this user's
+// again, then makes magpie's folders. prompt is whether the system's
+// password prompt can be shown: not to magpie web's page on another
+// device, where no one sits at this computer's screen to answer it.
+func repairConfig(prompt bool) error {
+ if b := appdir.Blocked(); b != "" {
+ if mine(b) {
+ // the user's own, only its mode is wrong: no password needed
+ fi, err := os.Stat(b)
+ if err != nil {
+ return err
+ }
+ if err := os.Chmod(b, fi.Mode().Perm()|0o700); err != nil {
+ return err
+ }
+ } else {
+ recurse := ""
+ if appdir.Own(b) {
+ recurse = "-R " // magpie's own folder: everything in it is magpie's
+ }
+ q := update.ShellQuote(b)
+ script := fmt.Sprintf("chown %s%d:%d %s && chmod u+rwx %s", recurse, os.Getuid(), os.Getgid(), q, q)
+ if !prompt || !canElevate() {
+ return fmt.Errorf("%s belongs to another user, and no administrator prompt can be shown here: run `sudo %s` in a terminal", b, script)
+ }
+ if err := asAdmin("magpie needs "+b+" to be yours again to save its settings.", script); err != nil {
+ return err
+ }
+ }
+ }
+ for _, dir := range []string{appdir.Config(), appdir.Cache()} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ }
+ if b := appdir.Blocked(); b != "" {
+ return fmt.Errorf("%s still can't be written", b)
+ }
+ return nil
+}
+
+// configRepairRoutes serves the window's Repair.
+func configRepairRoutes(mux *http.ServeMux, prompt bool) {
+ mux.HandleFunc("POST /api/config/repair", func(rw http.ResponseWriter, r *http.Request) {
+ if err := repairConfig(prompt); err != nil {
+ if errors.Is(err, errRepairCanceled) {
+ writeJSON(rw, map[string]bool{"canceled": true})
+ return
+ }
+ fail(rw, err)
+ return
+ }
+ rw.WriteHeader(http.StatusNoContent)
+ })
+}
diff --git a/internal/gui/config_repair_test.go b/internal/gui/config_repair_test.go
new file mode 100644
index 000000000..5ab883356
--- /dev/null
+++ b/internal/gui/config_repair_test.go
@@ -0,0 +1,133 @@
+//go:build !windows
+
+package gui
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// YouWhat on Discord: ~/.config wasn't the user's (sudo had made it), so
+// adding a custom provider failed with "mkdir ~/.config/magpie: permission
+// denied" and nothing said what to do. The failed save now names the
+// folder (config_blocked), /api/state names it for the window's Repair,
+// and Repair makes it writable again, after which the same save goes
+// through, into the folder every reader looks in.
+func TestBlockedConfigIsRepairedInOneClick(t *testing.T) {
+ if os.Getuid() == 0 {
+ t.Skip("root writes any folder")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ dotConfig := filepath.Join(home, ".config")
+ if err := os.Mkdir(dotConfig, 0o555); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(dotConfig, 0o755) })
+ h := Handler(nil, nil)
+ call := func(method, path, body string) (int, string) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
+ return rec.Code, rec.Body.String()
+ }
+ const add = `{"id":"mine","name":"Mine","chat":"http://127.0.0.1:1/v1","key":"sk-a","models":["m1"],"new":true}`
+
+ code, body := call("POST", "/api/provider/save", add)
+ var failed struct{ Error, Code, Blocked string }
+ json.Unmarshal([]byte(body), &failed)
+ if code == 200 {
+ t.Fatalf("save into a folder the user can't write went through: %s", body)
+ }
+ if failed.Code != "config_blocked" || failed.Blocked != "~/.config" {
+ t.Fatalf("failed save = %d %s; want code config_blocked naming ~/.config, so the window can offer Repair", code, body)
+ }
+ _, body = call("GET", "/api/state", "")
+ var s struct {
+ ConfigBlocked string `json:"configBlocked"`
+ }
+ json.Unmarshal([]byte(body), &s)
+ if s.ConfigBlocked != "~/.config" {
+ t.Fatalf("state configBlocked = %q, want ~/.config", s.ConfigBlocked)
+ }
+
+ if code, body := call("POST", "/api/config/repair", "{}"); code != 204 {
+ t.Fatalf("repair: %d %s", code, body)
+ }
+ if code, body := call("POST", "/api/provider/save", add); code != 200 {
+ t.Fatalf("save after repair: %d %s", code, body)
+ }
+ if _, err := os.Stat(filepath.Join(dotConfig, "magpie", "providers.json")); err != nil {
+ t.Fatalf("the provider isn't in ~/.config/magpie, where every reader looks: %v", err)
+ }
+ _, body = call("GET", "/api/state", "")
+ s.ConfigBlocked = ""
+ json.Unmarshal([]byte(body), &s)
+ if s.ConfigBlocked != "" {
+ t.Fatalf("state configBlocked = %q after repair, want empty", s.ConfigBlocked)
+ }
+}
+
+// A folder another user owns (root, after sudo) can't be chmodded by the
+// user: Repair asks the system's password prompt to give that folder alone
+// back, not everything under it, while magpie's own folder is given back
+// whole. Magpie web's page, on another device, never shows the prompt.
+func TestRepairOfAnotherUsersFolderAsksAnAdmin(t *testing.T) {
+ if os.Getuid() == 0 {
+ t.Skip("root writes any folder")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ dotConfig := filepath.Join(home, ".config")
+ if err := os.Mkdir(dotConfig, 0o555); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(dotConfig, 0o755) })
+ wasAdmin, wasElevate, wasMine := asAdmin, canElevate, mine
+ t.Cleanup(func() { asAdmin, canElevate, mine = wasAdmin, wasElevate, wasMine })
+ mine = func(string) bool { return false } // as if root's
+ canElevate = func() bool { return true }
+ var scripts []string
+ asAdmin = func(why, script string) error {
+ scripts = append(scripts, script)
+ return os.Chmod(dotConfig, 0o755) // what chown + chmod u+rwx would leave
+ }
+ if err := repairConfig(true); err != nil {
+ t.Fatal(err)
+ }
+ if len(scripts) != 1 || strings.Contains(scripts[0], "-R") || !strings.Contains(scripts[0], "'"+dotConfig+"'") {
+ t.Fatalf("scripts = %q; want one chown of %s alone, not -R over other apps' folders", scripts, dotConfig)
+ }
+ if _, err := os.Stat(filepath.Join(dotConfig, "magpie")); err != nil {
+ t.Fatalf("magpie's folder not made after repair: %v", err)
+ }
+
+ // magpie's own folder taken: given back whole
+ own := filepath.Join(dotConfig, "magpie")
+ os.Chmod(own, 0o555)
+ t.Cleanup(func() { os.Chmod(own, 0o755) })
+ scripts = nil
+ asAdmin = func(why, script string) error { scripts = append(scripts, script); return os.Chmod(own, 0o755) }
+ if err := repairConfig(true); err != nil {
+ t.Fatal(err)
+ }
+ if len(scripts) != 1 || !strings.Contains(scripts[0], "chown -R ") {
+ t.Fatalf("scripts = %q; want magpie's own folder given back whole", scripts)
+ }
+
+ // magpie web: no prompt, the command to run instead
+ os.Chmod(own, 0o555)
+ scripts = nil
+ err := repairConfig(false)
+ if err == nil || len(scripts) != 0 || !strings.Contains(err.Error(), "sudo chown") {
+ t.Fatalf("web repair = %v, scripts %q; want no prompt and the command named", err, scripts)
+ }
+}
diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go
index 523a78183..afc6db553 100644
--- a/internal/gui/core_budget_test.go
+++ b/internal/gui/core_budget_test.go
@@ -16,7 +16,7 @@ import (
// raises them and says why in its commit.
const (
appScriptBudget = 1_311_735 // 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)
- coreScriptBudget = 1_530_861 // 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)
+ coreScriptBudget = 1_531_973 // 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,531,973 with Repair for a magpie folder the user can't write (a ~/.config sudo made root's, YouWhat on Discord), asked over any page's failed save, so the core's own, in app.js, with no room added (10-29)
)
func TestCoreScriptBudget(t *testing.T) {
diff --git a/internal/gui/tests/config-blocked.test.cjs b/internal/gui/tests/config-blocked.test.cjs
new file mode 100644
index 000000000..aa3c4781b
--- /dev/null
+++ b/internal/gui/tests/config-blocked.test.cjs
@@ -0,0 +1,108 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// YouWhat on Discord: ~/.config wasn't the user's (a command run with sudo
+// had made it root's), so adding a custom provider failed with "mkdir
+// ~/.config/magpie: permission denied". /api/state names the folder that
+// blocks magpie (configBlocked), and the window asks once a load to Repair
+// it, which POSTs /api/config/repair. A save refused for it (code
+// config_blocked) says so in the reader's language and asks again, over
+// the editor whose save failed; Not now goes back to that editor as it was
+// left. The panel is too small for a dialog. No backend, the API is faked.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+
+const assets = path.resolve(__dirname, "../assets");
+const KEYS = [
+ "magpie can't save into {path}: it belongs to another user",
+ "magpie can't save its settings",
+ "{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.",
+ "Repair",
+ "Repaired: magpie can save again",
+];
+const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
+
+function server(lang, calls) {
+ return async (route) => {
+ const url = new URL(route.request().url());
+ const json = (data, status = 200) => route.fulfill({ status, json: data });
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") {
+ const s = { agents: [], profiles: [], settings: { lang, theme: "light" } };
+ if (calls.blocked) s.configBlocked = "~/.config";
+ return json(s);
+ }
+ if (url.pathname === "/api/config/repair") { calls.repair++; calls.blocked = false; return route.fulfill({ status: 204 }); }
+ if (url.pathname === "/api/test-save") return json({ error: "mkdir /Users/u/.config/magpie: permission denied", code: "config_blocked", blocked: "~/.config" }, 400);
+ if (url.pathname === "/api/usage/quotas") return json([]);
+ if (url.pathname === "/api/groups") return json({ groups: [] });
+ if (url.pathname === "/api/update" || url.pathname === "/api/drift") return json({});
+ if (url.pathname.startsWith("/api/")) return json({});
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
+ };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of ["en", "zh"]) {
+ test(`${engine} ${lang}: a folder magpie can't write is repaired in one click`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(async () => { await browser.close(); });
+ const errors = [];
+ const open = async (calls, url = "http://magpie.test/", width = 900) => {
+ const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
+ page.setDefaultTimeout(5000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server(lang, calls));
+ await page.goto(url);
+ return page;
+ };
+ const tr = (page, k) => page.evaluate(([k, lang]) => (lang === "en" ? k : I18N[lang][k]), [k, lang]);
+
+ // blocked at load: asked, and Repair repairs
+ const calls = { blocked: true, repair: 0 };
+ const page = await open(calls);
+ const dialog = page.locator("#modal:not([hidden])");
+ await dialog.waitFor();
+ assert.match(await dialog.textContent(), /~\/\.config/, "the dialog names the folder");
+ assert.ok((await dialog.textContent()).includes(await tr(page, "magpie can't save its settings")));
+ await dialog.getByRole("button", { name: await tr(page, "Repair"), exact: true }).click();
+ await page.waitForFunction(() => document.querySelector("#modal").hidden);
+ assert.equal(calls.repair, 1, "Repair reached the API");
+ assert.equal(await page.locator("#status").textContent(), await tr(page, "Repaired: magpie can save again"));
+
+ // a save refused for it: said in the reader's language, asked over
+ // the editor, and Not now goes back to that editor as it was
+ const p2 = await open({ blocked: false, repair: 0 });
+ await p2.waitForTimeout(300);
+ assert.ok(await p2.locator("#modal").evaluate((m) => m.hidden), "nothing asked while magpie can save");
+ const said = await p2.evaluate(async () => {
+ const ed = el("div", "editor");
+ const head = el("div", "ehead"); head.append(el("b", "", "Add provider"));
+ const input = el("input"); input.id = "typed"; input.value = "my provider";
+ ed.append(head, input);
+ openModal(ed);
+ try { await api("test-save", {}); } catch (e) { return e.message; }
+ return "";
+ });
+ assert.equal(said, (await tr(p2, "magpie can't save into {path}: it belongs to another user")).replace("{path}", "~/.config"));
+ const ask = p2.locator("#modal .cfg-blocked");
+ await ask.waitFor();
+ await ask.getByRole("button", { name: await tr(p2, "Not now"), exact: true }).click();
+ await p2.locator("#modal #typed").waitFor();
+ assert.equal(await p2.locator("#modal #typed").inputValue(), "my provider", "back to the editor as it was left");
+
+ // the panel stays quiet
+ const panel = await open({ blocked: true, repair: 0 }, "http://magpie.test/?mode=panel", 380);
+ await panel.waitForTimeout(500);
+ assert.ok(await panel.locator("#modal").evaluate((m) => m.hidden), "the panel stays quiet");
+
+ const missing = await page.evaluate(([ks, langs]) => langs.filter((l) => l !== "en").flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => l + ": " + k)), [KEYS, LANGS]);
+ assert.deepEqual(missing, [], "every language has the dialog's words");
+ assert.deepEqual(errors, []);
+ });
+ }
+}
diff --git a/internal/update/admin.go b/internal/update/admin.go
index 812f2282a..f5fb9328a 100644
--- a/internal/update/admin.go
+++ b/internal/update/admin.go
@@ -56,12 +56,16 @@ var run = func(name string, args ...string) ([]byte, error) {
}
// asAdmin runs a shell script as root, after the system's password prompt.
-func asAdmin(script string) error {
+func asAdmin(script string) error { return AsAdmin("magpie is updating itself.", script) }
+
+// AsAdmin runs a shell script as root, after the system's password prompt,
+// which says why (on a Mac). ErrCanceled is the prompt dismissed.
+func AsAdmin(why, script string) error {
var out []byte
var err error
switch runtime.GOOS {
case "darwin":
- out, err = run("osascript", "-e", `do shell script "`+appleString(script)+`" with prompt "magpie is updating itself." with administrator privileges`)
+ out, err = run("osascript", "-e", `do shell script "`+appleString(script)+`" with prompt "`+appleString(why)+`" with administrator privileges`)
if err != nil && strings.Contains(string(out), "(-128)") {
return ErrCanceled
}
@@ -88,6 +92,9 @@ func swapScript(staged, bundle, old string) string {
return "rm -rf " + o + " && mv " + b + " " + o + " && if mv " + s + " " + b + "; then rm -rf " + o + "; else mv " + o + " " + b + "; exit 1; fi"
}
+// ShellQuote quotes s for /bin/sh.
+func ShellQuote(s string) string { return shellQuote(s) }
+
// shellQuote quotes s for /bin/sh.
func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }