Skip to content

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

uninstall: magpie uninstall and Settings › Uninstall magpie put every agent back before magpie's files go

yetone96a703a591c9
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 7d914b025..8479e8a70 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -19,6 +19,7 @@ something else shows up as drift.
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable`, `proxied` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now. | [`applied.go`](../../internal/agent/applied.go) |
| What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
+| Uninstall | `magpie uninstall` and Settings › About › Uninstall magpie take magpie off this computer, because deleting magpie's folders by hand left Codex's `openai_base_url` on a gateway that was gone, and every turn failed with a 502 (Jevik_AI on X). `Run` goes in this order. `System` removes the service, opening at login, the Start menu shortcut, `magpie://` links and the privacy model's helper. `Agents` ends Codex's account failover, runs each connected agent's `Disconnect`, or its offline disconnect for a closed app, so the restore keeps what the user changed by hand since. It then ports Codex's rollouts and restarts the Codex app's app-server. `Data` deletes magpie's folders, but keeps the Library while it holds skills, servers or hooks. The executable stays where the user put it. The CLI refuses while another magpie runs, and asks first unless given `--yes`. The app runs `System` and `Agents` from `POST /api/uninstall`. If anything failed, nothing else is removed. Otherwise `POST /api/uninstall/finish` starts a detached `magpie uninstall --data-after <pid>`, which deletes the files once the app has quit, since WebView2 holds its folder open until then. magpie web refuses both routes (`TestUninstall*`, `uninstall-settings.test.cjs`). Every line magpie writes into a TOML, YAML or env config has a `# magpie:` note above it saying how to undo it, so a config left behind still names magpie (`edit.Mark`, `TestMarkedLinesEveryAgent`). | [`uninstall.go`](../../internal/uninstall/uninstall.go), [`uninstall_cli.go`](../../internal/cli/uninstall_cli.go), [`gui/uninstall.go`](../../internal/gui/uninstall.go) |
| Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Restarting a desktop app | Claude Desktop and WorkBuddy (WorkBuddy AI on macOS) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); a tray app still there after `appCloseWait` has its tree ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too, then ends only the app-server that app runs for itself (`provider.RestartCodexApp`: under its bundle, never a `--listen` one), as a switch does; the app starts another and keeps its window. Quitting and opening it, as before, opened a new window (yoshi037070 on Discord, 10-27). Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) |
diff --git a/internal/cli/main.go b/internal/cli/main.go
index 3dfa7585c..d1a3408e3 100644
--- a/internal/cli/main.go
+++ b/internal/cli/main.go
@@ -66,6 +66,7 @@ const usage = `magpie — one place to pick every agent's model
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models and the library in one file, sealed with a passphrase
magpie restore [--no-agents] [--no-library] <file> put a backup in on this machine
+ magpie uninstall [--yes] disconnect every agent, putting back what each had, then remove magpie's service and files
magpie webdav [on <address>|set k=v…|now|off] the same, kept the same on every computer through a WebDAV folder (magpie webdav help)
magpie s3 [on s3://<bucket>[/<prefix>]|set k=v…|now|off] the same through an S3-compatible bucket: AWS, R2, B2, MinIO… (magpie s3 help)
magpie github [on github://<owner>/<repo>[/<folder>]|set k=v…|now|off] the same in an encrypted GitHub repository (magpie github help)
@@ -326,6 +327,12 @@ func run(args []string) error {
return toolCmd(args[1:])
case codexrelay.Command: // internal: what a quitting magpie leaves for Codex's open threads
return codexrelay.Main(args[1:], gateway.CodexRelay())
+ case "uninstall":
+ // what the app starts as it quits from Settings › Uninstall
+ // magpie: nothing is made again before its folders go
+ if len(args) > 1 && args[1] == "--data-after" {
+ return uninstallData(args[2:])
+ }
}
}
startUp()
@@ -488,6 +495,8 @@ func run(args []string) error {
return backupCmd(args[1:])
case "restore":
return restoreCmd(args[1:])
+ case "uninstall":
+ return uninstallCmd(args[1:])
case "webdav", "dav":
return webdavCmd(args[1:])
case "plugin", "plugins":
diff --git a/internal/cli/uninstall_cli.go b/internal/cli/uninstall_cli.go
new file mode 100644
index 000000000..fd44b4454
--- /dev/null
+++ b/internal/cli/uninstall_cli.go
@@ -0,0 +1,131 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/term"
+
+ "github.com/yetone/magpie/internal/daemon"
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/uninstall"
+)
+
+const uninstallUsage = "usage: magpie uninstall [--yes]"
+
+// what uninstallCmd asks of the system; the tests put fakes in
+var (
+ servedBy = gateway.ServedBy
+ serviceStatus = daemon.Get
+ runUninstall = uninstall.Run
+)
+
+// magpie uninstall [--yes]: every agent disconnected and put back as it
+// was, magpie's service, login item and shortcuts removed, then its own
+// files (uninstall.Run). Deleting magpie's folders by hand left Codex
+// pointed at a gateway that was gone (Jevik_AI on X). It asks first on a
+// terminal; with no terminal to ask on, only --yes does it.
+func uninstallCmd(args []string) error {
+ yes := false
+ for _, a := range args {
+ switch a {
+ case "--yes", "-y":
+ yes = true
+ default:
+ return fmt.Errorf("unknown %q: nothing was changed\n%s", a, uninstallUsage)
+ }
+ }
+ // a magpie still running would serve, and keep writing its files,
+ // after its folders are gone: the service is stopped here, anything
+ // else is quit first
+ if s := servedBy(); s.Running && s.Pid != os.Getpid() {
+ if st, err := serviceStatus(); err != nil || !st.Installed || st.PID != 0 && st.PID != s.Pid {
+ how := "magpie"
+ switch s.Serves {
+ case "app", "tray":
+ how = "magpie's app"
+ case "serve", "tui", "web":
+ how = "magpie " + s.Serves
+ }
+ pid := ""
+ if s.Pid != 0 {
+ pid = " (pid " + strconv.Itoa(s.Pid) + ")"
+ }
+ return fmt.Errorf("%s is running%s: quit it first, or uninstall from the app's Settings › Uninstall magpie. Nothing was changed", how, pid)
+ }
+ }
+ connected := uninstall.Connected()
+ remove, keep := uninstall.Folders()
+ if !yes {
+ if !term.IsTerminal(int(os.Stdin.Fd())) {
+ return fmt.Errorf("this disconnects every agent and deletes magpie's settings, providers and usage; run it with --yes to do so without being asked")
+ }
+ fmt.Println("This takes magpie off this computer:")
+ if len(connected) > 0 {
+ var names []string
+ for _, a := range connected {
+ names = append(names, a.Name)
+ }
+ fmt.Println(" · disconnects", strings.Join(names, ", "), "and puts back what each had (what you changed by hand since stays)")
+ }
+ fmt.Println(" · removes magpie's background service, opening at login and shortcuts")
+ for _, p := range remove {
+ fmt.Println(" · deletes", p)
+ }
+ if keep != "" {
+ fmt.Println(" · keeps", keep, "(skills and servers your agents use)")
+ }
+ fmt.Print("Uninstall magpie? Your providers, keys and usage in magpie can't be brought back. [y/N] ")
+ line, _ := stdin().ReadString('\n')
+ if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
+ return fmt.Errorf("nothing was changed")
+ }
+ }
+ r := runUninstall(context.Background())
+ for _, l := range r.Says() {
+ switch {
+ case strings.HasPrefix(l, "✓"):
+ fmt.Println(green.Render("✓") + l[len("✓"):])
+ case strings.HasPrefix(l, "!"):
+ fmt.Println(amber.Render("!") + l[1:])
+ default:
+ fmt.Println(muted.Render(l))
+ }
+ }
+ if r.CodexApp {
+ fmt.Println(amber.Render("!"), "the Codex app is still on what it read before: quit it and open it again")
+ }
+ if r.Exe != "" {
+ fmt.Println(muted.Render(" magpie itself is left at " + r.Exe + ": delete it to finish"))
+ }
+ if r.Failed() {
+ return fmt.Errorf("some of magpie couldn't be taken off; what is marked ! above is left")
+ }
+ fmt.Println(green.Render("✓"), "magpie is uninstalled")
+ return nil
+}
+
+// uninstallData is `magpie uninstall --data-after <pid>`, which the app
+// starts as it quits from Settings › Uninstall magpie: once the app has
+// ended, its files are deleted (WebView2 holds its folder open while the
+// app runs).
+func uninstallData(args []string) error {
+ if len(args) != 1 {
+ return fmt.Errorf("usage: magpie uninstall --data-after <pid>")
+ }
+ // 0 or less is no process: kill(0) asks this process group, which
+ // is alive as long as this runs, and the files went only at the wait's end
+ pid, err := strconv.Atoi(args[0])
+ if err != nil || pid <= 0 || pid == os.Getpid() {
+ return fmt.Errorf("--data-after takes the app's process id, not %q: nothing was changed", args[0])
+ }
+ r := uninstall.AfterExit(pid, 2*time.Minute)
+ for _, l := range r.Says() {
+ fmt.Println(l)
+ }
+ return nil
+}
diff --git a/internal/cli/uninstall_cli_test.go b/internal/cli/uninstall_cli_test.go
new file mode 100644
index 000000000..37a75ac17
--- /dev/null
+++ b/internal/cli/uninstall_cli_test.go
@@ -0,0 +1,79 @@
+package cli
+
+import (
+ "context"
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/daemon"
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/uninstall"
+)
+
+func fakeUninstall(t *testing.T, served gateway.Served, service daemon.Status) *int {
+ t.Helper()
+ ran := 0
+ wasServed, wasStatus, wasRun := servedBy, serviceStatus, runUninstall
+ t.Cleanup(func() { servedBy, serviceStatus, runUninstall = wasServed, wasStatus, wasRun })
+ servedBy = func() gateway.Served { return served }
+ serviceStatus = func() (daemon.Status, error) { return service, nil }
+ runUninstall = func(context.Context) *uninstall.Report { ran++; return &uninstall.Report{} }
+ return &ran
+}
+
+// A magpie still serving that isn't the background service, which
+// uninstalling removes first, would keep writing its files after its
+// folders are gone: it is quit first, and nothing is changed.
+func TestUninstallRefusesWhileMagpieRuns(t *testing.T) {
+ ran := fakeUninstall(t, gateway.Served{Running: true, Pid: 4242, Serves: "app"}, daemon.Status{})
+ err := uninstallCmd([]string{"--yes"})
+ if err == nil || !strings.Contains(err.Error(), "magpie's app is running (pid 4242)") || *ran != 0 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+ // the background service itself is stopped and removed by uninstalling
+ ran = fakeUninstall(t, gateway.Served{Running: true, Pid: 4242, Serves: "serve"}, daemon.Status{Installed: true, Running: true, PID: 4242})
+ if err := uninstallCmd([]string{"--yes"}); err != nil || *ran != 1 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+ // a magpie serve beside an installed service is another one
+ ran = fakeUninstall(t, gateway.Served{Running: true, Pid: 4242, Serves: "serve"}, daemon.Status{Installed: true, Running: true, PID: 99})
+ if err := uninstallCmd([]string{"--yes"}); err == nil || *ran != 0 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+}
+
+// With no terminal to ask on, only --yes uninstalls; a word it doesn't
+// know changes nothing.
+func TestUninstallAsksFirst(t *testing.T) {
+ ran := fakeUninstall(t, gateway.Served{}, daemon.Status{})
+ if err := uninstallCmd(nil); err == nil || !strings.Contains(err.Error(), "--yes") || *ran != 0 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+ if err := uninstallCmd([]string{"--help-me"}); err == nil || *ran != 0 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+ if err := uninstallCmd([]string{"--yes"}); err != nil || *ran != 1 {
+ t.Fatalf("err %v, ran %d", err, *ran)
+ }
+}
+
+// --help prints its usage and uninstalls nothing.
+func TestUninstallHelp(t *testing.T) {
+ ran := fakeUninstall(t, gateway.Served{}, daemon.Status{})
+ if !helpAsked([]string{"uninstall", "--help"}) || !strings.Contains(helpFor([]string{"uninstall"}), "magpie uninstall [--yes]") || *ran != 0 {
+ t.Fatal("no help for uninstall")
+ }
+}
+
+// --data-after with no process to wait for (0, a negative, this one)
+// refuses at once: kill(0) asks the caller's own group, alive while it
+// runs, and the files went only when the wait ran out.
+func TestUninstallDataAfterNeedsAProcess(t *testing.T) {
+ for _, a := range []string{"0", "-1", "x", strconv.Itoa(os.Getpid())} {
+ if err := uninstallData([]string{a}); err == nil || !strings.Contains(err.Error(), "nothing was changed") {
+ t.Errorf("%s: %v", a, err)
+ }
+ }
+}
diff --git a/internal/gui/api.go b/internal/gui/api.go
index f5f9e0902..18233a9c4 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -1243,6 +1243,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
sessionRoutes(mux, w)
sessionManageRoutes(mux, w)
backupRoutes(mux, w)
+ uninstallRoutes(mux, w)
archiveRoutes(mux)
libraryRoutes(mux, w)
updateRoutes(mux, w)
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 9bcfea863..cc33e4978 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -7665,6 +7665,27 @@ function confirmAction(title, message, action) {
});
});
}
+// Settings › Uninstall magpie: the agents and the service first, each
+// failure said and nothing more removed; then magpie quits and its files go
+// once it has (uninstall.go).
+async function uninstallMagpie(btn) {
+ if (!(await confirmAction(t("Uninstall magpie?"), t("Every agent is disconnected and gets back what it had before magpie; what you changed by hand since stays. magpie's background service, opening at login and shortcuts are removed, and once it quits, its providers, keys, settings and usage are deleted. The app itself stays where it is: delete it to finish."), t("Uninstall")))) return;
+ btn.disabled = true;
+ try {
+ const r = await api("uninstall", {});
+ if (r.failed) {
+ const left = r.says.filter((l) => l.startsWith("!")).map((l) => l.slice(2)).join("; ");
+ if (await confirmAction(t("Some of magpie couldn't be taken off"), t("Nothing else was removed, and magpie keeps running. What is left: {left}", { left }), t("Try again"))) return uninstallMagpie(btn);
+ return;
+ }
+ if (r.codexApp && !(await confirmAction(t("Open the Codex app again"), t("The Codex app is still on the settings it read before: quit it and open it again. magpie quits now, and its files are deleted once it has."), t("Quit magpie")))) return;
+ await api("uninstall/finish", {});
+ } catch (e) {
+ status(t(e.message), "err");
+ } finally {
+ if (btn.isConnected) btn.disabled = false;
+ }
+}
function confirmRemoval(name, consequence = "This removes the selected item. Continue?") {
return confirmAction(t("Remove {name}?", { name }), t(consequence), t("Remove"));
}
@@ -19813,6 +19834,14 @@ function renderSettings() {
repo.title = "github.com/yetone/magpie";
repo.onclick = () => api("open", { url: "https://github.com/yetone/magpie" }).catch(() => {});
row(t("Community"), t("questions, ideas and feedback, on Discord or GitHub"), "", join, repo);
+ // magpie uninstall, from the app (Jevik_AI on X deleted magpie's folders
+ // by hand and Codex kept pointing at a gateway that was gone). Never in a
+ // browser: magpie web would be taken off the computer serving the page.
+ if (!web) {
+ const go = el("button", "text danger", t("Uninstall…"));
+ go.onclick = () => uninstallMagpie(go);
+ row(t("Uninstall magpie"), t("Disconnects every agent, putting back what each had, then removes magpie's service and files"), "", go).id = "uninstallRow";
+ }
// gateway mode leaves out what is written into this computer's agents'
// files, and the alerts its desktop would show
for (const r of [$("#plainNamesSegs").parentElement, $("#usageAlertRow"), $("#balanceAlertRow"), $("#resetReminderRow"), $("#turnDoneRow"), $("#maskAlertRow")]) r.hidden = gatewayMode;
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 0708211c2..f9c57db31 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -3665,6 +3665,17 @@ const I18N = {
"{n} couldn't be checked: {error}": "{n} 个无法检查:{error}",
"Not checked": "未能检查",
"Remove {name}?": "移除 {name}?",
+ "Uninstall…": "卸载…",
+ "Uninstall magpie": "卸载 magpie",
+ "Disconnects every agent, putting back what each had, then removes magpie's service and files": "断开每个智能体,恢复各自原有的设置,然后移除 magpie 的服务和文件",
+ "Uninstall magpie?": "卸载 magpie?",
+ "Every agent is disconnected and gets back what it had before magpie; what you changed by hand since stays. magpie's background service, opening at login and shortcuts are removed, and once it quits, its providers, keys, settings and usage are deleted. The app itself stays where it is: delete it to finish.": "每个智能体都会断开,并恢复接入 magpie 之前的设置;之后你手动改过的地方保持不变。magpie 的后台服务、登录时打开和快捷方式会被移除;magpie 退出后,它的供应商、密钥、设置和用量记录会被删除。应用本身留在原处,删除它即完成卸载。",
+ "Uninstall": "卸载",
+ "Some of magpie couldn't be taken off": "magpie 有部分内容未能移除",
+ "Nothing else was removed, and magpie keeps running. What is left: {left}": "其他内容都没有移除,magpie 仍在运行。未完成的:{left}",
+ "Open the Codex app again": "重新打开 Codex 应用",
+ "The Codex app is still on the settings it read before: quit it and open it again. magpie quits now, and its files are deleted once it has.": "Codex 应用仍在使用它之前读取的设置:请退出后重新打开。magpie 现在退出,退出后删除它的文件。",
+ "Quit magpie": "退出 magpie",
"in the library's folder, not listed": "在资源库文件夹中,但未列入",
"Discover": "发现",
"Go to the MCP servers you can add, under the list": "前往列表下方可添加的 MCP 服务器",
@@ -7729,6 +7740,17 @@ const I18N = {
"{n} couldn't be checked: {error}": "{n} 個無法檢查:{error}",
"Not checked": "未能檢查",
"Remove {name}?": "移除 {name}?",
+ "Uninstall…": "解除安裝…",
+ "Uninstall magpie": "解除安裝 magpie",
+ "Disconnects every agent, putting back what each had, then removes magpie's service and files": "中斷每個代理的連線,還原各自原有的設定,然後移除 magpie 的服務和檔案",
+ "Uninstall magpie?": "解除安裝 magpie?",
+ "Every agent is disconnected and gets back what it had before magpie; what you changed by hand since stays. magpie's background service, opening at login and shortcuts are removed, and once it quits, its providers, keys, settings and usage are deleted. The app itself stays where it is: delete it to finish.": "每個代理都會中斷連線,並還原接入 magpie 之前的設定;之後你手動改過的地方保持不變。magpie 的背景服務、登入時開啟和捷徑會被移除;magpie 結束後,它的供應商、金鑰、設定和用量紀錄會被刪除。應用程式本身留在原處,刪除它即完成解除安裝。",
+ "Uninstall": "解除安裝",
+ "Some of magpie couldn't be taken off": "magpie 有部分內容未能移除",
+ "Nothing else was removed, and magpie keeps running. What is left: {left}": "其他內容都沒有移除,magpie 仍在執行。未完成的:{left}",
+ "Open the Codex app again": "重新開啟 Codex 應用程式",
+ "The Codex app is still on the settings it read before: quit it and open it again. magpie quits now, and its files are deleted once it has.": "Codex 應用程式仍在使用它之前讀取的設定:請結束後重新開啟。magpie 現在結束,結束後刪除它的檔案。",
+ "Quit magpie": "結束 magpie",
"in the library's folder, not listed": "在資源庫資料夾中,但未列入",
"Discover": "發現",
"Go to the MCP servers you can add, under the list": "前往清單下方可新增的 MCP 伺服器",
@@ -11814,6 +11836,17 @@ const I18N = {
"{n} couldn't be checked: {error}": "{n} 個を確認できませんでした:{error}",
"Not checked": "未確認",
"Remove {name}?": "{name} を削除しますか?",
+ "Uninstall…": "アンインストール…",
+ "Uninstall magpie": "magpie をアンインストール",
+ "Disconnects every agent, putting back what each had, then removes magpie's service and files": "すべてのエージェントの接続を解除して元の設定に戻し、magpie のサービスとファイルを削除します",
+ "Uninstall magpie?": "magpie をアンインストールしますか?",
+ "Every agent is disconnected and gets back what it had before magpie; what you changed by hand since stays. magpie's background service, opening at login and shortcuts are removed, and once it quits, its providers, keys, settings and usage are deleted. The app itself stays where it is: delete it to finish.": "すべてのエージェントの接続を解除し、magpie を使う前の設定に戻します。その後に手で変更した箇所はそのまま残ります。magpie のバックグラウンドサービス、ログイン時の起動、ショートカットを削除し、magpie の終了後にプロバイダ、キー、設定、使用量を削除します。アプリ本体は元の場所に残るので、削除すれば完了です。",
+ "Uninstall": "アンインストール",
+ "Some of magpie couldn't be taken off": "magpie の一部を削除できませんでした",
+ "Nothing else was removed, and magpie keeps running. What is left: {left}": "ほかには何も削除しておらず、magpie は動作を続けます。残っているもの:{left}",
+ "Open the Codex app again": "Codex アプリを開き直してください",
+ "The Codex app is still on the settings it read before: quit it and open it again. magpie quits now, and its files are deleted once it has.": "Codex アプリは以前に読み込んだ設定のままです。終了してから開き直してください。magpie は今から終了し、終了後にファイルを削除します。",
+ "Quit magpie": "magpie を終了",
"in the library's folder, not listed": "ライブラリのフォルダ内にあるが未登録",
"Discover": "発見",
"Go to the MCP servers you can add, under the list": "リストの下にある追加できる MCP サーバーへ移動",
@@ -15912,6 +15945,17 @@ const I18N = {
"{n} couldn't be checked: {error}": "{n} konnten nicht geprüft werden: {error}",
"Not checked": "Nicht geprüft",
"Remove {name}?": "{name} entfernen?",
+ "Uninstall…": "Deinstallieren…",
+ "Uninstall magpie": "magpie deinstallieren",
+ "Disconnects every agent, putting back what each had, then removes magpie's service and files": "Trennt jeden Agenten, stellt seine vorherigen Einstellungen wieder her und entfernt dann magpies Dienst und Dateien",
+ "Uninstall magpie?": "magpie deinstallieren?",
+ "Every agent is disconnected and gets back what it had before magpie; what you changed by hand since stays. magpie's background service, opening at login and shortcuts are removed, and once it quits, its providers, keys, settings and usage are deleted. The app itself stays where it is: delete it to finish.": "Jeder Agent wird getrennt und bekommt seine Einstellungen von vor magpie zurück; was du seitdem von Hand geändert hast, bleibt. magpies Hintergrunddienst, das Öffnen bei der Anmeldung und die Verknüpfungen werden entfernt, und sobald magpie beendet ist, werden seine Anbieter, Schlüssel, Einstellungen und Nutzungsdaten gelöscht. Die App selbst bleibt, wo sie ist: lösche sie, um fertig zu werden.",
+ "Uninstall": "Deinstallieren",
+ "Some of magpie couldn't be taken off": "Ein Teil von magpie konnte nicht entfernt werden",
+ "Nothing else was removed, and magpie keeps running. What is left: {left}": "Sonst wurde nichts entfernt, und magpie läuft weiter. Übrig ist: {left}",
+ "Open the Codex app again": "Codex-App neu öffnen",
+ "The Codex app is still on the settings it read before: quit it and open it again. magpie quits now, and its files are deleted once it has.": "Die Codex-App nutzt noch die Einstellungen, die sie vorher gelesen hat: beende sie und öffne sie erneut. magpie wird jetzt beendet, danach werden seine Dateien gelöscht.",
+ "Quit magpie": "magpie beenden",
"in the library's folder, not listed": "im Ordner der Bibliothek, nicht gelistet",
"Discover": "Entdecken",
"Go to the MCP servers you can add, under the list": "Zu den MCP-Servern unter der Liste, die Sie hinzufügen können",
diff --git a/internal/gui/tests/uninstall-settings.test.cjs b/internal/gui/tests/uninstall-settings.test.cjs
new file mode 100644
index 000000000..d06291e4c
--- /dev/null
+++ b/internal/gui/tests/uninstall-settings.test.cjs
@@ -0,0 +1,130 @@
+const assert = require("node:assert/strict");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+const { fixture } = require("./fixtures/caller-keys.cjs");
+const { openPart } = require("./reader.cjs");
+
+// Jevik_AI on X deleted magpie's folders by hand, and Codex kept pointing
+// at a gateway that was gone. Settings › About › Uninstall magpie asks
+// first, disconnects every agent and removes the service (POST
+// /api/uninstall), and only then has magpie quit and its files deleted
+// (POST /api/uninstall/finish). A failure is said and nothing more is
+// removed; the Codex app still on the old settings is said before magpie
+// quits. magpie web never offers it.
+const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
+const words = {
+ en: { row: "Uninstall magpie", title: "Uninstall magpie?", go: "Uninstall", cancel: "Cancel", again: "Try again", quit: "Quit magpie" },
+ zh: { row: "卸载 magpie", title: "卸载 magpie?", go: "卸载", cancel: "取消" },
+ "zh-TW": { row: "解除安裝 magpie", title: "解除安裝 magpie?", go: "解除安裝", cancel: "取消" },
+ ja: { row: "magpie をアンインストール", title: "magpie をアンインストールしますか?", go: "アンインストール", cancel: "キャンセル" },
+ de: { row: "magpie deinstallieren", title: "magpie deinstallieren?", go: "Deinstallieren", cancel: "Abbrechen" },
+};
+
+async function setup(t, engine, lang, width, { web = false, reply = { failed: false, says: [] } } = {}) {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
+ page.setDefaultTimeout(6000);
+ const errors = [], posts = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", fixture(lang, "light", [], { web }));
+ await page.route("**/api/uninstall**", (route) => {
+ const p = new URL(route.request().url()).pathname;
+ posts.push(p);
+ if (p === "/api/uninstall/finish") return route.fulfill({ status: 204 });
+ return route.fulfill({ json: { agents: [], system: [], data: [], ...reply } });
+ });
+ await page.goto("http://magpie.test/?view=gateway");
+ await page.locator("#prefs").click();
+ await openPart(page, "about");
+ await page.locator("#about .row").first().waitFor();
+ return { page, errors, posts };
+}
+
+const dialog = (page) => page.locator("dialog.action-confirm");
+const scrolled = (page) => page.evaluate(() => document.querySelector("#view-settings").scrollTop);
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of LANGS) {
+ for (const width of [1100, 420]) {
+ test(`${engine} ${lang} ${width}: Uninstall magpie asks, then disconnects and quits`, async (t) => {
+ const { page, errors, posts } = await setup(t, engine, lang, width);
+ const w = words[lang];
+ const row = page.locator("#uninstallRow");
+ await showRow(page, row);
+ assert.match(await row.locator(".name").textContent(), new RegExp(w.row.replace(/[??]/g, "")));
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "wider than the window");
+ const before = await scrolled(page);
+ const go = row.locator("button");
+ await go.click();
+ await dialog(page).waitFor();
+ assert.equal(await scrolled(page), before, "the click moved the page");
+ assert.equal(await dialog(page).locator("h2").textContent(), w.title);
+ // Cancel does nothing at all
+ await dialog(page).getByRole("button", { name: w.cancel, exact: true }).click();
+ await dialog(page).waitFor({ state: "detached" });
+ assert.deepEqual(posts, []);
+ // Uninstall: the agents and the service, then the files on quitting
+ await go.click();
+ await dialog(page).getByRole("button", { name: w.go, exact: true }).click();
+ await waitFor(() => posts.length === 2);
+ assert.deepEqual(posts, ["/api/uninstall", "/api/uninstall/finish"]);
+ assert.deepEqual(errors, []);
+ });
+ }
+ }
+
+ test(`${engine}: what couldn't be undone is said, and nothing more is removed`, async (t) => {
+ const { page, errors, posts } = await setup(t, engine, "en", 1100, {
+ reply: { failed: true, says: ["✓ removed background service", "! disconnected Codex: config.toml: permission denied"] },
+ });
+ await page.locator("#uninstallRow button").click();
+ await dialog(page).getByRole("button", { name: "Uninstall", exact: true }).click();
+ await dialog(page).getByRole("button", { name: "Try again", exact: true }).waitFor();
+ assert.match(await dialog(page).locator("p").textContent(), /disconnected Codex: config\.toml: permission denied/);
+ assert.doesNotMatch(await dialog(page).locator("p").textContent(), /background service/);
+ await dialog(page).getByRole("button", { name: "Cancel", exact: true }).click();
+ await dialog(page).waitFor({ state: "detached" });
+ assert.deepEqual(posts, ["/api/uninstall"]);
+ assert.equal(await page.locator("#uninstallRow button").isEnabled(), true);
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine}: the Codex app on its old settings is said before magpie quits`, async (t) => {
+ const { page, errors, posts } = await setup(t, engine, "en", 1100, { reply: { failed: false, codexApp: true, says: [] } });
+ await page.locator("#uninstallRow button").click();
+ await dialog(page).getByRole("button", { name: "Uninstall", exact: true }).click();
+ await dialog(page).getByRole("button", { name: "Quit magpie", exact: true }).waitFor();
+ assert.deepEqual(posts, ["/api/uninstall"]);
+ await dialog(page).getByRole("button", { name: "Quit magpie", exact: true }).click();
+ await waitFor(() => posts.length === 2);
+ assert.deepEqual(posts, ["/api/uninstall", "/api/uninstall/finish"]);
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine}: magpie web never offers it`, async (t) => {
+ const { page, errors } = await setup(t, engine, "en", 1100, { web: true });
+ assert.equal(await page.locator("#uninstallRow").count(), 0);
+ assert.doesNotMatch(await page.locator("#about").textContent(), /Uninstall/);
+ assert.deepEqual(errors, []);
+ });
+}
+
+// scrolled to as a reader does, with the wheel: a scroll the page makes
+// itself is put back by the hold a click keeps on what was clicked
+async function showRow(page, row) {
+ await page.locator("#view-settings").hover();
+ for (let i = 0; i < 40; i++) {
+ const box = await row.boundingBox();
+ const v = await page.locator("#view-settings").boundingBox();
+ if (box && v && box.y >= v.y + 4 && box.y + box.height <= v.y + v.height - 4) break;
+ await page.mouse.wheel(0, 180);
+ await page.waitForTimeout(16);
+ }
+ await page.waitForTimeout(250);
+}
+
+async function waitFor(ok) {
+ for (const until = Date.now() + 5000; Date.now() < until; await new Promise((r) => setTimeout(r, 20))) if (ok()) return;
+ assert.fail("waited for state that never came");
+}
diff --git a/internal/gui/uninstall.go b/internal/gui/uninstall.go
new file mode 100644
index 000000000..3f5636bc6
--- /dev/null
+++ b/internal/gui/uninstall.go
@@ -0,0 +1,63 @@
+package gui
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/yetone/magpie/internal/uninstall"
+)
+
+// what Settings › Uninstall magpie asks of the system; the tests put
+// fakes in
+var (
+ uninstallSystem = uninstall.System
+ uninstallAgents = uninstall.Agents
+ uninstallData = uninstall.DataAfterExit
+)
+
+// uninstallRoutes: Settings › Uninstall magpie, the app's `magpie
+// uninstall`. The app does it in two steps. POST /api/uninstall removes
+// magpie's service, login item and shortcuts and disconnects every agent,
+// putting back what each had, and answers with what it did, so the page
+// can say what failed or that the Codex app needs a restart. POST
+// /api/uninstall/finish then starts the removal of magpie's files once the
+// app has quit (WebView2 holds its folder while the app runs), and quits.
+// Never from a browser (magpie web): that would take magpie off the
+// computer it serves from, not the one the page is on.
+func uninstallRoutes(mux *http.ServeMux, w Windows) {
+ web := isWeb(w)
+ refuse := func(rw http.ResponseWriter) bool {
+ if web {
+ http.Error(rw, "magpie is uninstalled from the computer it runs on, with magpie uninstall there", http.StatusForbidden)
+ }
+ return web
+ }
+ mux.HandleFunc("POST /api/uninstall", func(rw http.ResponseWriter, r *http.Request) {
+ if refuse(rw) {
+ return
+ }
+ rep := &uninstall.Report{}
+ // the service first: one still serving would put magpie back
+ uninstallSystem(rep)
+ uninstallAgents(r.Context(), rep)
+ writeJSON(rw, struct {
+ *uninstall.Report
+ Failed bool `json:"failed"`
+ Says []string `json:"says"`
+ }{rep, rep.Failed(), rep.Says()})
+ })
+ mux.HandleFunc("POST /api/uninstall/finish", func(rw http.ResponseWriter, r *http.Request) {
+ if refuse(rw) {
+ return
+ }
+ if err := uninstallData(); err != nil {
+ fail(rw, errors.New("magpie's files can't be removed after it quits: "+err.Error()))
+ return
+ }
+ rw.WriteHeader(http.StatusNoContent)
+ if f, ok := rw.(http.Flusher); ok {
+ f.Flush()
+ }
+ go w.Quit()
+ })
+}
diff --git a/internal/gui/uninstall_test.go b/internal/gui/uninstall_test.go
new file mode 100644
index 000000000..4bd179da7
--- /dev/null
+++ b/internal/gui/uninstall_test.go
@@ -0,0 +1,119 @@
+package gui
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/yetone/magpie/internal/uninstall"
+)
+
+// fakeUninstall puts fakes in for what Settings › Uninstall magpie does,
+// and returns the order they ran in
+func fakeUninstall(t *testing.T, agentErr string) *[]string {
+ t.Helper()
+ var ran []string
+ sys, ag, data := uninstallSystem, uninstallAgents, uninstallData
+ uninstallSystem = func(r *uninstall.Report) {
+ ran = append(ran, "system")
+ r.System = append(r.System, uninstall.Done{What: "background service"})
+ }
+ uninstallAgents = func(_ context.Context, r *uninstall.Report) {
+ ran = append(ran, "agents")
+ r.Agents = append(r.Agents, uninstall.Done{What: "Codex", Err: agentErr})
+ }
+ uninstallData = func() error { ran = append(ran, "data"); return nil }
+ t.Cleanup(func() { uninstallSystem, uninstallAgents, uninstallData = sys, ag, data })
+ return &ran
+}
+
+func postTo(mux http.Handler, path string) *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, httptest.NewRequest("POST", path, nil))
+ return rec
+}
+
+// Uninstall from the app disconnects every agent after the service is
+// gone, and says what it did; magpie's files go only on Finish, once the
+// app quits, never with the agents.
+func TestUninstallFromTheApp(t *testing.T) {
+ ran := fakeUninstall(t, "")
+ w := &quitCount{}
+ mux := http.NewServeMux()
+ uninstallRoutes(mux, w)
+ rec := postTo(mux, "/api/uninstall")
+ var j struct {
+ Agents []uninstall.Done `json:"agents"`
+ Failed bool `json:"failed"`
+ Says []string `json:"says"`
+ }
+ if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &j) != nil {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ if j.Failed || len(j.Agents) != 1 || j.Agents[0].What != "Codex" || len(j.Says) != 2 {
+ t.Fatalf("%s", rec.Body)
+ }
+ if got := *ran; len(got) != 2 || got[0] != "system" || got[1] != "agents" {
+ t.Fatalf("ran %v", got)
+ }
+ if w.quits.Load() != 0 {
+ t.Fatal("quit before Finish")
+ }
+ if rec := postTo(mux, "/api/uninstall/finish"); rec.Code != http.StatusNoContent {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ eventually(t, "Finish never quit", func() bool { return w.quits.Load() == 1 })
+ if got := *ran; len(got) != 3 || got[2] != "data" {
+ t.Fatalf("ran %v", got)
+ }
+}
+
+// What couldn't be undone is said, for the page to show and not quit on.
+func TestUninstallFromTheAppSaysWhatFailed(t *testing.T) {
+ fakeUninstall(t, "config.toml: permission denied")
+ mux := http.NewServeMux()
+ uninstallRoutes(mux, &quitCount{})
+ rec := postTo(mux, "/api/uninstall")
+ var j struct {
+ Failed bool `json:"failed"`
+ Says []string `json:"says"`
+ }
+ if json.Unmarshal(rec.Body.Bytes(), &j) != nil || !j.Failed || j.Says[0] != "! disconnected Codex: config.toml: permission denied" {
+ t.Fatalf("%s", rec.Body)
+ }
+}
+
+// A Finish whose removal can't start doesn't quit: the files would stay
+// with nothing left to say so.
+func TestUninstallFinishThatCantStartStays(t *testing.T) {
+ fakeUninstall(t, "")
+ uninstallData = func() error { return errors.New("no exe") }
+ w := &quitCount{}
+ mux := http.NewServeMux()
+ uninstallRoutes(mux, w)
+ if rec := postTo(mux, "/api/uninstall/finish"); rec.Code < 400 {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ if w.quits.Load() != 0 {
+ t.Fatal("quit")
+ }
+}
+
+// magpie web never uninstalls: the page is on another computer, or a
+// browser on this one that isn't the app.
+func TestUninstallNeverFromABrowser(t *testing.T) {
+ ran := fakeUninstall(t, "")
+ mux := http.NewServeMux()
+ uninstallRoutes(mux, webHost{func() { t.Error("quit") }})
+ for _, p := range []string{"/api/uninstall", "/api/uninstall/finish"} {
+ if rec := postTo(mux, p); rec.Code != http.StatusForbidden {
+ t.Fatalf("%s: %d %s", p, rec.Code, rec.Body)
+ }
+ }
+ if len(*ran) != 0 {
+ t.Fatalf("ran %v", *ran)
+ }
+}
diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go
index 52e89614d..adf0e7a92 100644
--- a/internal/provider/codex_app_server.go
+++ b/internal/provider/codex_app_server.go
@@ -387,3 +387,39 @@ func RestartCodexApp(ctx context.Context, bundle string) error {
}
}
}
+
+// RestartCodexAppWhenIdle ends the Codex app's own app-servers once, for a magpie
+// that won't be running to watch them (magpie uninstall): the app starts
+// a new one, which reads Codex's config as it is now. It waits up to wait
+// for a running Codex turn to end, and cuts none short: left says an
+// app-server was still on the old config when it gave up, or couldn't be
+// ended, so the user quits and opens the app.
+func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int, left bool, err error) {
+ home := codexHome()
+ lctx, cancel := context.WithTimeout(ctx, codexAppListWait)
+ pids, err := codexAppServersOn(lctx, home)
+ cancel()
+ if err != nil || len(pids) == 0 {
+ return 0, false, err
+ }
+ until := time.Now().Add(wait)
+ for codexTurnRunning(home, time.Now()) {
+ if time.Now().After(until) {
+ return 0, true, nil
+ }
+ select {
+ case <-ctx.Done():
+ return 0, true, ctx.Err()
+ case <-time.After(codexAppEvery):
+ }
+ }
+ for _, p := range pids {
+ if err := endCodexAppServer(p); err != nil {
+ log.Printf("codex: restarting the Codex app's app-server %d: %v", p, err)
+ left = true
+ continue
+ }
+ ended++
+ }
+ return ended, left, nil
+}
diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go
index ec54c0313..243ee267d 100644
--- a/internal/provider/codex_app_server_test.go
+++ b/internal/provider/codex_app_server_test.go
@@ -512,3 +512,29 @@ func TestRestartCodexAppEndsOnlyItsServer(t *testing.T) {
t.Fatal("an app-server that stays: no error")
}
}
+
+// magpie uninstall restarts the Codex app's app-server once, so the app
+// reads a config with magpie out of it with no magpie left to watch it;
+// a running turn is waited for, never cut short.
+func TestRestartCodexAppWhenIdle(t *testing.T) {
+ s := stubCodexApp(t)
+ oldEvery := codexAppEvery
+ codexAppEvery = time.Millisecond
+ t.Cleanup(func() { codexAppEvery = oldEvery })
+ if n, left, err := RestartCodexAppWhenIdle(context.Background(), time.Second); n != 0 || left || err != nil {
+ t.Fatalf("no app running: %d %v %v", n, left, err)
+ }
+ s.running = []int{7, 8}
+ s.turnOpen = true
+ if n, left, _ := RestartCodexAppWhenIdle(context.Background(), 20*time.Millisecond); n != 0 || !left || len(s.ended) != 0 {
+ t.Fatalf("a turn running: ended %v, left %v", s.ended, left)
+ }
+ s.turnOpen = false
+ if n, left, err := RestartCodexAppWhenIdle(context.Background(), time.Second); n != 2 || left || err != nil || !slices.Equal(s.ended, []int{7, 8}) {
+ t.Fatalf("ended %v (%d), left %v, %v", s.ended, n, left, err)
+ }
+ s.endErr = proc.ErrDenied
+ if _, left, _ := RestartCodexAppWhenIdle(context.Background(), time.Second); !left {
+ t.Fatal("an app-server not ended isn't said")
+ }
+}
diff --git a/internal/shortcut/ensure_test.go b/internal/shortcut/ensure_test.go
index 51d39af6d..36f6308ee 100644
--- a/internal/shortcut/ensure_test.go
+++ b/internal/shortcut/ensure_test.go
@@ -105,3 +105,35 @@ func TestEnsurePortable(t *testing.T) {
t.Fatalf("portable: %d writes, shortcut %v, App Paths %v, state %v", f.writes, exists(f.lnk), f.paths, exists(state))
}
}
+
+// magpie uninstall takes the Start menu shortcut and the App Paths entry
+// out, for the exe in place of one an update moved aside.
+func TestRemove(t *testing.T) {
+ dir := t.TempDir()
+ lnk := filepath.Join(dir, "Magpie.lnk")
+ if err := os.WriteFile(lnk, []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ oldMenu, oldUn := startMenu, unregister
+ t.Cleanup(func() { startMenu, unregister = oldMenu, oldUn })
+ startMenu = func() (string, error) { return lnk, nil }
+ var asked string
+ unregister = func(exe string) error { asked = exe; return nil }
+ if err := Remove(`C:\Tools\magpie.exe.old`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(lnk); !os.IsNotExist(err) {
+ t.Error("the shortcut is still there")
+ }
+ if asked != `C:\Tools\magpie.exe` {
+ t.Errorf("App Paths asked for %q", asked)
+ }
+ // none there, or no Start menu: nothing to say
+ if err := Remove(`C:\Tools\magpie.exe`); err != nil {
+ t.Fatal(err)
+ }
+ startMenu = func() (string, error) { return "", errNoStartMenu }
+ if err := Remove("/usr/local/bin/magpie"); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/shortcut/shortcut.go b/internal/shortcut/shortcut.go
index c399f412a..874f26271 100644
--- a/internal/shortcut/shortcut.go
+++ b/internal/shortcut/shortcut.go
@@ -127,3 +127,25 @@ func Stale(target, dir, exe string) bool {
}
return !same(target, exe) || !same(dir, filepath.Dir(exe))
}
+
+// what Remove asks of the system besides startMenu; the tests put fakes in
+var unregister = unregisterAppPath
+
+// Remove takes out what Ensure made, for magpie uninstall: the Start menu
+// shortcut, the App Paths entry while it names exe (or an exe gone), and
+// the record of having made them. A portable magpie made none, and an
+// entry another copy of magpie registered stays that copy's.
+func Remove(exe string) error {
+ var errs []error
+ if lnk, err := startMenu(); err == nil {
+ if err := os.Remove(lnk); err != nil && !os.IsNotExist(err) {
+ errs = append(errs, err)
+ }
+ } else if !errors.Is(err, errNoStartMenu) {
+ errs = append(errs, err)
+ }
+ if err := unregister(Target(exe)); err != nil {
+ errs = append(errs, err)
+ }
+ return errors.Join(errs...)
+}
diff --git a/internal/shortcut/shortcut_other.go b/internal/shortcut/shortcut_other.go
index d6eab6550..cb419f72a 100644
--- a/internal/shortcut/shortcut_other.go
+++ b/internal/shortcut/shortcut_other.go
@@ -9,3 +9,5 @@ func writeShortcut(string, string) (bool, error) { return false, nil }
func registerAppPath(string) {}
func registeredAppPath() bool { return false }
+
+func unregisterAppPath(string) error { return nil }
diff --git a/internal/shortcut/shortcut_windows.go b/internal/shortcut/shortcut_windows.go
index c4443145c..d66236e8f 100644
--- a/internal/shortcut/shortcut_windows.go
+++ b/internal/shortcut/shortcut_windows.go
@@ -5,6 +5,7 @@ import (
"os"
"path/filepath"
"runtime"
+ "strings"
ole "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
@@ -121,3 +122,20 @@ func write(lnk, exe string) (bool, error) {
}
return true, nil
}
+
+// unregisterAppPath takes magpie's App Paths entry out while it opens exe,
+// or an exe that is gone.
+func unregisterAppPath(exe string) error {
+ k, err := registry.OpenKey(registry.CURRENT_USER, appPath, registry.QUERY_VALUE)
+ if err != nil {
+ return nil // none
+ }
+ v, _, err := k.GetStringValue("")
+ k.Close()
+ if err == nil && v != "" && !strings.EqualFold(filepath.Clean(v), filepath.Clean(exe)) {
+ if _, err := os.Stat(v); err == nil {
+ return nil // another magpie's
+ }
+ }
+ return registry.DeleteKey(registry.CURRENT_USER, appPath)
+}
diff --git a/internal/uninstall/detach_unix.go b/internal/uninstall/detach_unix.go
new file mode 100644
index 000000000..24ccaed2b
--- /dev/null
+++ b/internal/uninstall/detach_unix.go
@@ -0,0 +1,17 @@
+//go:build !windows
+
+package uninstall
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+// detach puts cmd in a session of its own: launchd ends the process
+// group of an app that exits, which would take the files' removal with it.
+func detach(cmd *exec.Cmd) {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.Setsid = true
+}
diff --git a/internal/uninstall/detach_windows.go b/internal/uninstall/detach_windows.go
new file mode 100644
index 000000000..52b36cf20
--- /dev/null
+++ b/internal/uninstall/detach_windows.go
@@ -0,0 +1,20 @@
+package uninstall
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+const (
+ detachedProcess = 0x00000008
+ newProcessGroup = 0x00000200
+)
+
+// detach starts cmd outside the app's console and process group, so it
+// outlives the app.
+func detach(cmd *exec.Cmd) {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.CreationFlags |= detachedProcess | newProcessGroup
+}
diff --git a/internal/uninstall/main_test.go b/internal/uninstall/main_test.go
new file mode 100644
index 000000000..3a033dc75
--- /dev/null
+++ b/internal/uninstall/main_test.go
@@ -0,0 +1,10 @@
+package uninstall
+
+import (
+ "testing"
+
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// The tests run in a home of their own, never the user's real files.
+func TestMain(m *testing.M) { testenv.Main(m) }
diff --git a/internal/uninstall/system_linux.go b/internal/uninstall/system_linux.go
new file mode 100644
index 000000000..13c45d933
--- /dev/null
+++ b/internal/uninstall/system_linux.go
@@ -0,0 +1,53 @@
+package uninstall
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/yetone/magpie/internal/appdir"
+)
+
+// dataHome is where the app's desktop entry, icon and WebKitGTK's data
+// are (gui's dataHome).
+func dataHome() string {
+ if x := appdir.Getenv("XDG_DATA_HOME"); filepath.IsAbs(x) {
+ return x
+ }
+ h, _ := os.UserHomeDir()
+ return filepath.Join(h, ".local", "share")
+}
+
+// unregisterScheme takes out the desktop entry the app made for magpie://
+// links while it runs exe, or an exe that is gone, and its icon with it.
+func unregisterScheme(exe string) error {
+ entry := filepath.Join(dataHome(), "applications", "magpie.desktop")
+ b, err := os.ReadFile(entry)
+ if err != nil {
+ return nil
+ }
+ for _, l := range strings.Split(string(b), "\n") {
+ if run, ok := strings.CutPrefix(l, "Exec="); ok {
+ run = strings.TrimSuffix(run, " %u")
+ if run != exe {
+ if _, err := os.Stat(run); err == nil {
+ return nil // another magpie's
+ }
+ }
+ }
+ }
+ if err := os.Remove(entry); err != nil {
+ return err
+ }
+ _ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png"))
+ return nil
+}
+
+// webData is WebKitGTK's folder for the app's pages (named after the
+// program, gui's programName).
+func webData() []string {
+ if appdir.Portable() != "" {
+ return nil
+ }
+ return []string{filepath.Join(dataHome(), "magpie")}
+}
diff --git a/internal/uninstall/system_other.go b/internal/uninstall/system_other.go
new file mode 100644
index 000000000..29fa38fbe
--- /dev/null
+++ b/internal/uninstall/system_other.go
@@ -0,0 +1,10 @@
+//go:build !windows && !linux
+
+package uninstall
+
+// unregisterScheme: the Mac reads magpie:// from the app's Info.plist.
+func unregisterScheme(string) error { return nil }
+
+// webData: the Mac's webview keeps the app's pages by its bundle id, in
+// folders the system manages.
+func webData() []string { return nil }
diff --git a/internal/uninstall/system_windows.go b/internal/uninstall/system_windows.go
new file mode 100644
index 000000000..1beaf148b
--- /dev/null
+++ b/internal/uninstall/system_windows.go
@@ -0,0 +1,54 @@
+package uninstall
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+
+ "golang.org/x/sys/windows/registry"
+
+ "github.com/yetone/magpie/internal/appdir"
+)
+
+const schemeKey = `Software\Classes\magpie`
+
+// unregisterScheme takes out the magpie:// handler the app registered
+// while it opens exe, or an exe that is gone.
+func unregisterScheme(exe string) error {
+ k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE)
+ if err != nil {
+ return nil
+ }
+ v, _, _ := k.GetStringValue("")
+ k.Close()
+ if run, _, ok := strings.Cut(strings.TrimPrefix(v, `"`), `"`); ok && !strings.EqualFold(filepath.Clean(run), filepath.Clean(exe)) {
+ if _, err := os.Stat(run); err == nil {
+ return nil // another magpie's
+ }
+ }
+ for _, sub := range []string{`\shell\open\command`, `\shell\open`, `\shell`, `\DefaultIcon`, ``} {
+ if err := registry.DeleteKey(registry.CURRENT_USER, schemeKey+sub); err != nil && err != registry.ErrNotExist {
+ return err
+ }
+ }
+ return nil
+}
+
+// webData is WebView2's profile of an installed magpie: %APPDATA%\<exe
+// name> (portable, it is in the data folder already).
+func webData() []string {
+ if appdir.Portable() != "" {
+ return nil
+ }
+ exe, err := os.Executable()
+ a := appdir.Getenv("APPDATA")
+ if err != nil || a == "" {
+ return nil
+ }
+ p := filepath.Join(a, filepath.Base(exe))
+ // only a folder WebView2 made: its EBWebView inside
+ if _, err := os.Stat(filepath.Join(p, "EBWebView")); err != nil {
+ return nil
+ }
+ return []string{p}
+}
diff --git a/internal/uninstall/uninstall.go b/internal/uninstall/uninstall.go
new file mode 100644
index 000000000..21b801576
--- /dev/null
+++ b/internal/uninstall/uninstall.go
@@ -0,0 +1,357 @@
+// Package uninstall takes magpie off this computer: `magpie uninstall` and
+// Settings › Uninstall magpie.
+//
+// Jevik_AI on X deleted magpie's folders by hand, and Codex's config.toml
+// kept openai_base_url on 127.0.0.1:3425: every Codex turn failed with a
+// 502, with nothing left that knew why. Deleting magpie's files never puts
+// an agent back, so uninstalling does that first, the way each agent's
+// Disconnect does (what magpie changed goes back, what the user changed
+// by hand since stays theirs), then removes what magpie registered with
+// the system, then its own files.
+//
+// What it leaves: the magpie executable itself (a running program can't
+// delete itself everywhere, and the user put it there), and the Library's
+// folder while it holds skills or servers the user's agents use.
+package uninstall
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/yetone/magpie/internal/agent"
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/autostart"
+ "github.com/yetone/magpie/internal/claudecode"
+ "github.com/yetone/magpie/internal/daemon"
+ "github.com/yetone/magpie/internal/library"
+ "github.com/yetone/magpie/internal/pii"
+ "github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/shortcut"
+ "github.com/yetone/magpie/internal/update"
+)
+
+// Done is one thing uninstalling did, or couldn't.
+type Done struct {
+ What string `json:"what"`
+ Err string `json:"error,omitempty"`
+}
+
+// Report is what Run did.
+type Report struct {
+ Agents []Done `json:"agents"`
+ System []Done `json:"system"`
+ Data []Done `json:"data"`
+ // Kept are folders left on purpose, each with why
+ Kept []Done `json:"kept,omitempty"`
+ // CodexApp: a Codex app still on the config it read before, which
+ // the user quits and opens
+ CodexApp bool `json:"codexApp,omitempty"`
+ // Exe is the magpie executable, left where it is
+ Exe string `json:"exe"`
+}
+
+// Failed says whether anything couldn't be done.
+func (r *Report) Failed() bool {
+ for _, l := range [][]Done{r.Agents, r.System, r.Data} {
+ for _, d := range l {
+ if d.Err != "" {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// what Run asks of the system; the tests put fakes in
+var (
+ agents = agent.All
+ endFailover = agent.EndCodexFailover
+ portRollouts = agent.PortCodexRollouts
+ restartCodexApp = provider.RestartCodexAppWhenIdle
+ removeService = func() error {
+ err := daemon.Uninstall()
+ if errors.Is(err, daemon.ErrUnsupported) {
+ return nil
+ }
+ return err
+ }
+ autostartOff = func() error { return autostart.Set(false) }
+ removeShortcut = shortcut.Remove
+ removeScheme = unregisterScheme
+ endPII = pii.Remove
+ executable = os.Executable
+ wired = (*agent.Agent).Wired
+ disconnectOne = disconnect
+)
+
+// codexAppWait is how long Run waits for a running Codex turn to end
+// before it restarts the Codex app's app-server.
+var codexAppWait = 30 * time.Second
+
+// Connected are the agents magpie is in now, which Run disconnects.
+func Connected() []*agent.Agent {
+ var out []*agent.Agent
+ for _, a := range agents() {
+ if wired(a) {
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
+// Agents disconnects every agent magpie is in: the first half of
+// uninstalling, which the app does while it still runs.
+func Agents(ctx context.Context, r *Report) {
+ // failover first: it is a provider in Codex's config too
+ if _, err := endFailover(); err != nil {
+ r.Agents = append(r.Agents, Done{What: "Codex account failover", Err: err.Error()})
+ }
+ codex := false
+ for _, a := range Connected() {
+ err := disconnectOne(a)
+ d := Done{What: a.Name}
+ if err != nil {
+ d.Err = err.Error()
+ }
+ r.Agents = append(r.Agents, d)
+ codex = codex || a.ID == "codex"
+ }
+ // the threads Codex ran on magpie's models open without magpie
+ portRollouts(10 * time.Second)
+ if codex {
+ // the Codex app read the old config as its app-server started
+ if _, left, err := restartCodexApp(ctx, codexAppWait); left || err != nil {
+ r.CodexApp = true
+ }
+ }
+}
+
+// disconnect is the Agents page's Disconnect, and for an app whose
+// settings can't be read while it is closed, its offline disconnect.
+func disconnect(a *agent.Agent) error {
+ err := a.Disconnect()
+ var off *agent.RuntimeUnavailableError
+ if errors.As(err, &off) && off.Offline == agent.OfflineDisconnect && a.Native != nil && a.Native.ExecuteOffline != nil {
+ plan, perr := a.Native.Disconnect()
+ if perr != nil {
+ return perr
+ }
+ return a.Native.ExecuteOffline(plan)
+ }
+ return err
+}
+
+// System removes what magpie registered with the system: its background
+// service, opening at login, its Start menu shortcut and links.
+func System(r *Report) {
+ exe, _ := executable()
+ for _, s := range []struct {
+ what string
+ do func() error
+ }{
+ {"background service", removeService},
+ {"open at login", autostartOff},
+ {"Start menu shortcut", func() error { return removeShortcut(exe) }},
+ {"magpie:// links", func() error { return removeScheme(exe) }},
+ {"privacy model's helper", endPII},
+ } {
+ d := Done{What: s.what}
+ if err := s.do(); err != nil {
+ d.Err = err.Error()
+ }
+ r.System = append(r.System, d)
+ }
+}
+
+// Folders are magpie's own folders Data removes, and the Library's folder
+// when it keeps that.
+func Folders() (remove []string, keep string) {
+ home, _ := os.UserHomeDir()
+ add := func(p string) {
+ if removable(p, home) && !slices.Contains(remove, p) {
+ remove = append(remove, p)
+ }
+ }
+ cfg := appdir.Config()
+ if libraryInUse() {
+ keep = library.Dir()
+ }
+ add(cfg)
+ add(appdir.Cache())
+ if c, err := appdir.SystemCache(); err == nil {
+ add(c)
+ }
+ add(appdir.WebView())
+ add(claudecode.Root())
+ for _, p := range webData() {
+ add(p)
+ }
+ // a folder inside another is removed with it
+ var out []string
+ for _, p := range remove {
+ if !slices.ContainsFunc(remove, func(q string) bool { return q != p && within(p, q) }) {
+ out = append(out, p)
+ }
+ }
+ return out, keep
+}
+
+// libraryInUse says whether the Library holds skills, servers or hooks:
+// an agent given one reads it from there, or has it from there, and it
+// is the user's, so it stays.
+func libraryInUse() bool {
+ es, err := os.ReadDir(library.Dir())
+ if err != nil {
+ return false
+ }
+ for _, e := range es {
+ if e.IsDir() {
+ if sub, _ := os.ReadDir(filepath.Join(library.Dir(), e.Name())); len(sub) > 0 {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// Data removes magpie's own files: settings, providers, sign-ins kept by
+// magpie, usage, caches. With the Library in use, everything in magpie's
+// folder but it goes.
+func Data(r *Report) {
+ remove, keep := Folders()
+ for _, p := range remove {
+ d := Done{What: p}
+ var err error
+ if keep != "" && within(keep, p) {
+ err = removeAllBut(p, keep)
+ } else {
+ err = os.RemoveAll(p)
+ }
+ if err != nil {
+ d.Err = err.Error()
+ }
+ r.Data = append(r.Data, d)
+ }
+ if keep != "" {
+ r.Kept = append(r.Kept, Done{What: keep, Err: "skills and servers your agents use from magpie's Library"})
+ }
+}
+
+// removeAllBut removes dir but keep, which is inside it.
+func removeAllBut(dir, keep string) error {
+ es, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, e := range es {
+ p := filepath.Join(dir, e.Name())
+ switch {
+ case samePath(p, keep):
+ case within(keep, p):
+ errs = append(errs, removeAllBut(p, keep))
+ default:
+ errs = append(errs, os.RemoveAll(p))
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// Run uninstalls magpie: agents, then the system, then its files. The
+// app runs Data itself once it has quit (WebView2 holds its folder open
+// while it runs), so it calls Agents and System only.
+func Run(ctx context.Context) *Report {
+ r := &Report{}
+ // the service first: one still serving would put magpie back
+ System(r)
+ Agents(ctx, r)
+ Data(r)
+ r.Exe, _ = executable()
+ return r
+}
+
+// AfterExit waits for process pid to end, for up to wait, then removes
+// magpie's files: what the app starts as it quits.
+func AfterExit(pid int, wait time.Duration) *Report {
+ until := time.Now().Add(wait)
+ for update.Alive(pid) && time.Now().Before(until) {
+ time.Sleep(200 * time.Millisecond)
+ }
+ r := &Report{}
+ Data(r)
+ return r
+}
+
+// startAfter starts cmd outside this process, which it outlives; the
+// tests put a fake in
+var startAfter = func(cmd *exec.Cmd) error {
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil
+ detach(cmd)
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
+
+// DataAfterExit starts `magpie uninstall --data-after <this pid>`, which
+// removes magpie's files once this process, the app, has quit: the app's
+// half of Run after Agents and System.
+func DataAfterExit() error {
+ exe, err := executable()
+ if err != nil {
+ return err
+ }
+ return startAfter(proc.Command(exe, "uninstall", "--data-after", strconv.Itoa(os.Getpid())))
+}
+
+// removable says whether p can be one of magpie's folders: never one
+// that holds more than magpie's, as the home, a root or a relative path
+// would, from a variable set to one.
+func removable(p, home string) bool {
+ return p != "" && filepath.IsAbs(p) && filepath.Dir(p) != p && (home == "" || !within(home, p))
+}
+
+// within says whether p is dir or inside it.
+func within(p, dir string) bool {
+ rel, err := filepath.Rel(dir, p)
+ return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
+}
+
+func samePath(a, b string) bool { return filepath.Clean(a) == filepath.Clean(b) }
+
+// Says is the report as lines, for the terminal and the app's log.
+func (r *Report) Says() []string {
+ var out []string
+ line := func(kind string, d Done) {
+ if d.Err != "" {
+ out = append(out, fmt.Sprintf("! %s %s: %s", kind, d.What, d.Err))
+ } else {
+ out = append(out, fmt.Sprintf("✓ %s %s", kind, d.What))
+ }
+ }
+ for _, d := range r.Agents {
+ line("disconnected", d)
+ }
+ for _, d := range r.System {
+ line("removed", d)
+ }
+ for _, d := range r.Data {
+ line("deleted", d)
+ }
+ for _, d := range r.Kept {
+ out = append(out, "· kept "+d.What+": "+d.Err)
+ }
+ return out
+}
diff --git a/internal/uninstall/uninstall_test.go b/internal/uninstall/uninstall_test.go
new file mode 100644
index 000000000..845f986c4
--- /dev/null
+++ b/internal/uninstall/uninstall_test.go
@@ -0,0 +1,230 @@
+package uninstall
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/agent"
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/library"
+)
+
+// fakes puts a fake in for everything Run asks of the system, and records
+// what it was asked, in order.
+func fakes(t *testing.T, list []*agent.Agent, isWired map[string]bool, failing map[string]error) *[]string {
+ t.Helper()
+ var did []string
+ wasAgents, wasWired, wasDisconnect := agents, wired, disconnectOne
+ wasFailover, wasPort, wasRestart := endFailover, portRollouts, restartCodexApp
+ wasService, wasAutostart, wasShortcut, wasScheme, wasPII, wasExe := removeService, autostartOff, removeShortcut, removeScheme, endPII, executable
+ t.Cleanup(func() {
+ agents, wired, disconnectOne = wasAgents, wasWired, wasDisconnect
+ endFailover, portRollouts, restartCodexApp = wasFailover, wasPort, wasRestart
+ removeService, autostartOff, removeShortcut, removeScheme, endPII, executable = wasService, wasAutostart, wasShortcut, wasScheme, wasPII, wasExe
+ })
+ agents = func() []*agent.Agent { return list }
+ wired = func(a *agent.Agent) bool { return isWired[a.ID] }
+ disconnectOne = func(a *agent.Agent) error {
+ did = append(did, "disconnect "+a.ID)
+ if err := failing[a.ID]; err != nil {
+ return err
+ }
+ isWired[a.ID] = false
+ return nil
+ }
+ endFailover = func() (bool, error) { did = append(did, "failover"); return true, nil }
+ portRollouts = func(time.Duration) { did = append(did, "rollouts") }
+ restartCodexApp = func(context.Context, time.Duration) (int, bool, error) {
+ did = append(did, "codex app")
+ return 1, false, nil
+ }
+ step := func(name string) func() error {
+ return func() error { did = append(did, name); return nil }
+ }
+ removeService = step("service")
+ autostartOff = step("autostart")
+ removeShortcut = func(string) error { did = append(did, "shortcut"); return nil }
+ removeScheme = func(string) error { did = append(did, "scheme"); return nil }
+ endPII = step("pii")
+ executable = func() (string, error) { return "/opt/magpie/magpie", nil }
+ return &did
+}
+
+func write(t *testing.T, p, s string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func gone(t *testing.T, p string) bool {
+ t.Helper()
+ _, err := os.Stat(p)
+ return errors.Is(err, os.ErrNotExist)
+}
+
+// Uninstalling stops the service before anything else (one still serving
+// would wire agents again), disconnects only the agents magpie is in,
+// restarts the Codex app's app-server when Codex was one of them, and
+// removes magpie's files last.
+func TestRunOrder(t *testing.T) {
+ codex := &agent.Agent{ID: "codex", Name: "Codex"}
+ claude := &agent.Agent{ID: "claude", Name: "Claude Code"}
+ gemini := &agent.Agent{ID: "gemini", Name: "Gemini CLI"}
+ did := fakes(t, []*agent.Agent{codex, claude, gemini}, map[string]bool{"codex": true, "claude": true}, nil)
+ settings := filepath.Join(appdir.Config(), "settings.json")
+ write(t, settings, "{}")
+ write(t, filepath.Join(appdir.Cache(), "models.json"), "{}")
+
+ r := Run(context.Background())
+
+ want := []string{"service", "autostart", "shortcut", "scheme", "pii", "failover", "disconnect codex", "disconnect claude", "rollouts", "codex app"}
+ if !slices.Equal(*did, want) {
+ t.Fatalf("did %q, want %q", *did, want)
+ }
+ if r.Failed() || r.CodexApp {
+ t.Fatalf("report: %+v", r)
+ }
+ if !gone(t, appdir.Config()) || !gone(t, appdir.Cache()) {
+ t.Fatal("magpie's folders left")
+ }
+ if r.Exe != "/opt/magpie/magpie" {
+ t.Fatalf("exe %q", r.Exe)
+ }
+ if len(r.Agents) != 2 || r.Agents[0].What != "Codex" || r.Agents[1].What != "Claude Code" {
+ t.Fatalf("agents %+v", r.Agents)
+ }
+}
+
+// An agent that can't be disconnected is said, and the rest are still
+// done; Codex not among them leaves the Codex app alone.
+func TestRunSaysWhatFailed(t *testing.T) {
+ claude := &agent.Agent{ID: "claude", Name: "Claude Code"}
+ goose := &agent.Agent{ID: "goose", Name: "Goose"}
+ did := fakes(t, []*agent.Agent{claude, goose}, map[string]bool{"claude": true, "goose": true}, map[string]error{"claude": errors.New("settings.json: permission denied")})
+ r := Run(context.Background())
+ if slices.Contains(*did, "codex app") {
+ t.Fatalf("the Codex app restarted with no Codex connected: %q", *did)
+ }
+ if !slices.Contains(*did, "disconnect goose") {
+ t.Fatalf("goose skipped after claude failed: %q", *did)
+ }
+ if !r.Failed() {
+ t.Fatal("not failed")
+ }
+ says := strings.Join(r.Says(), "\n")
+ if !strings.Contains(says, "! disconnected Claude Code: settings.json: permission denied") || !strings.Contains(says, "✓ disconnected Goose") {
+ t.Fatalf("says:\n%s", says)
+ }
+}
+
+// A Codex turn still running past the wait leaves the app-server alone,
+// and the report tells the user to reopen the app.
+func TestRunCodexAppLeft(t *testing.T) {
+ codex := &agent.Agent{ID: "codex", Name: "Codex"}
+ fakes(t, []*agent.Agent{codex}, map[string]bool{"codex": true}, nil)
+ restartCodexApp = func(context.Context, time.Duration) (int, bool, error) { return 0, true, nil }
+ if r := Run(context.Background()); !r.CodexApp {
+ t.Fatal("CodexApp not said")
+ }
+}
+
+// Skills and servers the user's agents use from the Library stay; the
+// rest of magpie's folder goes.
+func TestDataKeepsLibraryInUse(t *testing.T) {
+ fakes(t, nil, map[string]bool{}, nil)
+ skill := filepath.Join(library.Dir(), "skills", "docx", "SKILL.md")
+ write(t, skill, "# docx")
+ settings := filepath.Join(appdir.Config(), "settings.json")
+ write(t, settings, "{}")
+ write(t, filepath.Join(appdir.Config(), "usage", "2026-10.db"), "x")
+
+ r := &Report{}
+ Data(r)
+ if !gone(t, settings) || !gone(t, filepath.Join(appdir.Config(), "usage")) {
+ t.Fatal("magpie's own files left")
+ }
+ if gone(t, skill) {
+ t.Fatal("a skill in use removed")
+ }
+ if len(r.Kept) != 1 || r.Kept[0].What != library.Dir() {
+ t.Fatalf("kept %+v", r.Kept)
+ }
+
+ // an empty Library goes with the rest
+ os.RemoveAll(filepath.Join(library.Dir(), "skills", "docx"))
+ r = &Report{}
+ Data(r)
+ if !gone(t, appdir.Config()) || len(r.Kept) != 0 {
+ t.Fatalf("empty library kept: %+v", r)
+ }
+}
+
+// Never the home, a root or a relative path, from a variable pointing at
+// one; a folder inside another is listed once.
+func TestFoldersNeverHome(t *testing.T) {
+ home, _ := os.UserHomeDir()
+ remove, _ := Folders()
+ if len(remove) == 0 {
+ t.Fatal("nothing to remove")
+ }
+ for _, p := range remove {
+ if !filepath.IsAbs(p) || within(home, p) {
+ t.Fatalf("would remove %s (home %s)", p, home)
+ }
+ for _, q := range remove {
+ if p != q && within(p, q) {
+ t.Fatalf("%s listed inside %s", p, q)
+ }
+ }
+ }
+ root := "/"
+ if runtime.GOOS == "windows" {
+ root = `C:\`
+ }
+ h := filepath.Join(root, "Users", "me")
+ for p, ok := range map[string]bool{
+ "": false,
+ "magpie": false,
+ root: false,
+ h: false,
+ filepath.Join(root, "Users"): false,
+ filepath.Join(h, ".config", "magpie"): true,
+ filepath.Join(root, "Users", "me2"): true,
+ } {
+ if removable(p, h) != ok {
+ t.Errorf("removable(%q) = %v", p, !ok)
+ }
+ }
+}
+
+// What the app starts as it quits removes magpie's files once the app is
+// gone.
+func TestAfterExit(t *testing.T) {
+ fakes(t, nil, map[string]bool{}, nil)
+ settings := filepath.Join(appdir.Config(), "settings.json")
+ write(t, settings, "{}")
+ cmd := exec.Command(os.Args[0], "-test.run=^$")
+ if err := cmd.Run(); err != nil {
+ t.Fatal(err)
+ }
+ start := time.Now()
+ r := AfterExit(cmd.Process.Pid, time.Minute)
+ if time.Since(start) > 30*time.Second {
+ t.Fatal("waited on a process that had ended")
+ }
+ if r.Failed() || !gone(t, settings) {
+ t.Fatalf("report %+v", r)
+ }
+}