windows: magpie is listed in Installed apps, and its Uninstall puts every agent back

Jevik_AI on X uninstalled magpie and rebooted, and Codex's config.toml
still had openai_base_url = "http://127.0.0.1:3425/backend-api/codex";
Rk1ngggg asked whether an update cleans it. magpie's own uninstall
(Settings › About › Uninstall magpie, `magpie uninstall`) already
disconnects every agent and takes Codex's leftovers (#3866), but on
Windows magpie wasn't in Settings › Apps › Installed apps, so it was
removed the way Windows offers for a program it doesn't list: by
deleting the exe and folders, which runs no code.

shortcut.Ensure now writes
HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie
(DisplayName, DisplayIcon, Publisher, InstallLocation, UninstallString,
URLInfoAbout, NoModify, NoRepair) at every installed start, beside App
Paths, and Remove (uninstall's System step) takes it out the same way:
only while it names this exe, or an exe that is gone. Its Uninstall
runs `magpie.exe uninstall --window` (shortcut.UninstallArgs). magpie.exe
has no console, where the terminal's `magpie uninstall` would refuse
for want of one to ask on, so those exact args open the app's window
(or forward to the running app, OnSecondInstanceLaunch) on Settings ›
About with Uninstall magpie's question asked (uninstallView,
?uninstall=1). It asks once: a redraw of Settings doesn't ask again,
and Cancel removes nothing. magpie web opened at that link asks
nothing. Deleting the app by hand still runs no code (macOS
drag-to-Trash included); agent-wiring.md says so.

Run on mote at the pushed head (rebased onto be9dbce02):
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -tags nogui ./internal/gui ./internal/cli ./internal/shortcut
  ./internal/uninstall: ok (TestCoreScriptBudget included).
- uninstall-settings.test.cjs and i18n-keys.test.cjs: 40 of 40
  (chromium and webkit; the new Installed-apps cases in en and zh at
  1100 and 420).
At d3f40bedd, the same change on c7ebb6f8d, under suite.lock:
- go test -tags nogui -timeout 45m ./...: ok, every package.
- The whole GUI suite (--test-concurrency=4): 22518 of 22800; the 282
  reds are in 53 files the change doesn't reach (model-chip-steady 40,
  usage-agents-hide 22, zero-priced-free 20, provider-fetch-again 14,
  ...), the full-suite reds of #5475; the numbers are on that issue.
  Their run at c7ebb6f8d alone is queued behind other sessions' suites.
- The first full run found the core scripts 147 bytes over
  TestCoreScriptBudget; the page's part was cut to one line (the
  budget is not raised).
On xiaomi-gpu (win-run): go test ./internal/shortcut, incl.
TestInstalledAppsEntry on the real HKCU registry under a test key: ok.

Broken by hand, each red:
- registerAppPath not calling registerUninstall: TestInstalledAppsEntry
  (UninstallString = "") on Windows.
- main.go not taking UninstallArgs to the window:
  TestInstalledAppsUninstallOpensTheWindow (unknown "--window").
- app.js not asking on ?uninstall=1: 4 of 4 Installed-apps GUI cases.
- app.js asking without its once guard (params.delete): the same 4
  ("asked again").

Not tried: a real Settings › Apps › Uninstall click on Windows with an
installed magpie (the test box's install belongs to other sessions); the
second-instance forward (OnSecondInstanceLaunch) has no test of its own.
This commit is contained in:
yetone
2026-11-09 22:33:31 +08:00
parent 39569d5604
commit 92e8edd7fc
12 changed files with 273 additions and 9 deletions
+1 -1
View File
@@ -19,7 +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, and keeps the agent connected (`applied.Kept`). An agent whose magpie is a provider of its own config (`Spelled`, not `Native`) is connected only when magpie set it up (`setUp`: a record, `Kept`, or a `<id>.connect.was` stash). A provider named magpie the user wrote by hand (`handWired`) is theirs: it isn't `Wired`, has no `Drift`, and neither `SyncCatalog`, `RenameProvider` nor `Disconnect` writes it; connecting in magpie takes it on (JFunfunfun on X, Pi on `magpie/<model>`; `TestPiHandWiredMagpieProviderIsTheirs`, `TestPiConnectedBeforeStaysConnected`, `TestHandWiredMagpieProviderSiblings`). | [`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 takes Codex's leftovers (`TakeCodexLeftovers`): an `openai_base_url` at magpie's gateway, or magpie as Codex's provider, goes by the gates a Disconnect uses even when magpie's notes are gone and Codex reads as not connected (#3866); magpie's provider table stays for the threads that name it. 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) |
| 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 takes Codex's leftovers (`TakeCodexLeftovers`): an `openai_base_url` at magpie's gateway, or magpie as Codex's provider, goes by the gates a Disconnect uses even when magpie's notes are gone and Codex reads as not connected (#3866); magpie's provider table stays for the threads that name it. 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`. On Windows magpie is listed in Settings › Apps › Installed apps: `shortcut.Ensure` writes `HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie` at every installed start, and `System` takes it out with the Start menu shortcut. Its Uninstall runs `magpie uninstall --window` with no console, which opens the app's window (or the running app's) on Settings › About with the question asked (`uninstallView`, `shortcut.UninstallArgs`). Deleting the app by hand still runs no code. 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. For Codex that is where its config sends it and which models its lists hold (`listedModels`, slug and visibility), not every byte of each entry: the Codex app's list carries the ChatGPT backend's entries as sent, asked for each hour, and a rewrite with the same models told the user to reopen the app several times a day (Qyburn3 on X). A digest an older magpie stashed over the same files is kept (`readsBefore`). | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Restarting a desktop app | Claude Desktop, WorkBuddy (WorkBuddy AI on macOS) and OpenMausBot 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`), but a script run on the app's own executable (`runsScript`: a `.js` argument or an absolute path as its first argument), which the running check skips too. WorkBuddy starts its sidecar (`sidecar-entry.js`) and its `codebuddy` CLIs that way, detached; the sidecar outlives a quit, so counting it kept the row behind after every restart and made Restart wait it out and never open the app (Northes on Discord, 11-04, #3700). On Windows the same check reads each process's command line (`proc.CommandLine`); 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`); one that has hidden every window and still runs after `appTrayGrace` (1s) is in the tray and has its tree ended at once (`waitClosed`, `winShown`: Claude Desktop hides its window in ~0.6s and keeps all its processes, so waiting the whole `appCloseWait` made a Restart ~12s where quitting by hand takes ~2s, CyberCaius on Discord, 10-29); one still showing a window (a question) gets `appCloseWait` before it is 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) |
+2
View File
@@ -11,3 +11,5 @@ func runGUI(bool, string) error { return errors.New("this build has no GUI; run
func runPanel() error { return runGUI(false, "") }
func runWindow(string) error { return runGUI(true, "") }
func runUninstallWindow() error { return runGUI(true, "") }
+8
View File
@@ -34,6 +34,14 @@ func runWindow(view string) error {
return runGUI(true, "")
}
// runUninstallWindow starts the app with its window on Settings ›
// Uninstall magpie, asking, or brings the running one's there: what
// Windows' Installed apps runs for magpie's Uninstall.
func runUninstallWindow() error {
gui.OpenUninstall = true
return runGUI(true, "")
}
// runPanel starts the app with its quick panel open, or toggles the panel
// of the one already running.
func runPanel() error {
+6
View File
@@ -34,6 +34,7 @@ import (
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/shortcut"
"github.com/yetone/magpie/internal/tui"
"github.com/yetone/magpie/internal/update"
)
@@ -587,6 +588,11 @@ func run(args []string) error {
case "restore":
return restoreCmd(args[1:])
case "uninstall":
// Windows' Installed apps: the app's window asks (shortcut.UninstallArgs)
if hasGUI && slices.Equal(args, shortcut.UninstallArgs) {
gateway.Serves = "app"
return runUninstallWindow()
}
return uninstallCmd(args[1:])
case "webdav", "dav":
return webdavCmd(args[1:])
+36
View File
@@ -0,0 +1,36 @@
//go:build !nogui
package cli
import (
"testing"
"github.com/yetone/magpie/internal/applog"
"github.com/yetone/magpie/internal/gui"
"github.com/yetone/magpie/internal/shortcut"
)
// Windows' Installed apps runs magpie's Uninstall with no console
// (shortcut.UninstallArgs): the terminal's `magpie uninstall` would refuse
// for want of one to ask on, so it opens the app's window at Settings ›
// Uninstall magpie, which asks, and puts every agent back before magpie's
// files go. Nothing is removed by the command itself.
func TestInstalledAppsUninstallOpensTheWindow(t *testing.T) {
was, wasRun := openApp, runUninstall
t.Cleanup(func() { openApp, runUninstall = was, wasRun; gui.OpenUninstall = false; applog.Stop() })
var shown []bool
openApp = func(show bool, link string) error {
if link != "" {
t.Errorf("opened on a link %q", link)
}
shown = append(shown, show && gui.OpenUninstall)
return nil
}
runUninstall = nil // called, it panics: the window asks, not this
if err := run(shortcut.UninstallArgs); err != nil {
t.Fatal(err)
}
if len(shown) != 1 || !shown[0] {
t.Fatalf("the app's window wasn't opened on Uninstall magpie: %v", shown)
}
}
+16 -1
View File
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"sync"
"sync/atomic"
"time"
@@ -677,7 +678,11 @@ func Run(version string, showMain bool, link string) error {
h.whenReady(h.applyZoom)
}
if showMain {
h.whenReady(func() { h.ShowMain(argView(OpenView)) })
view := argView(OpenView)
if OpenUninstall {
view = uninstallView
}
h.whenReady(func() { h.ShowMain(view) })
} else if quiet && settings.Load().Dock {
// kept out of the Dock to start (Mac options above), it joins
// now without coming to the front
@@ -741,6 +746,8 @@ func singleInstance(h *host) *application.SingleInstanceOptions {
case len(args) == 1 && args[0] == "tray":
case len(args) == 1 && args[0] == "panel":
h.whenReady(func() { application.InvokeAsync(h.togglePanel) })
case slices.Equal(args, shortcut.UninstallArgs):
h.whenReady(func() { h.ShowMain(uninstallView) })
case len(args) == 2 && (args[0] == "gui" || args[0] == "app"):
h.whenReady(func() { h.ShowMain(argView(args[1])) })
default:
@@ -846,6 +853,14 @@ func panelOptions(goos, theme string) application.WebviewWindowOptions {
// icon runs it (see omarchy.AddWidget).
var OpenPanel bool
// OpenUninstall opens the window on Settings › Uninstall magpie, asking
// (Windows' Installed apps, shortcut.UninstallArgs).
var OpenUninstall bool
// uninstallView is Settings' About part with Uninstall magpie's question
// open (uninstallMagpie in app.js).
const uninstallView = "settings&tab=about&uninstall=1"
// OpenView is the tab the window opens on, as `magpie gui settings` asks:
// a restart to update comes back where it was asked for.
var OpenView string
+1
View File
@@ -20178,6 +20178,7 @@ function renderSettings() {
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";
if (mode === "window" && params.has("uninstall")) params.delete("uninstall"), uninstallMagpie(go);
}
// gateway mode leaves out what is written into this computer's agents'
// files, and the alerts its desktop would show
@@ -42,6 +42,26 @@ async function setup(t, engine, lang, width, { web = false, reply = { failed: fa
return { page, errors, posts };
}
// the window as `magpie uninstall --window` opens it
async function opened(t, engine, lang, width, { web = false }) {
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);
page.setDefaultNavigationTimeout(60000);
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: [], failed: false, says: [] } });
});
await page.goto("http://magpie.test/?view=settings&tab=about&uninstall=1");
return { page, errors, posts };
}
const dialog = (page) => page.locator("dialog.action-confirm");
const scrolled = (page) => page.evaluate(() => document.querySelector("#view-settings").scrollTop);
@@ -103,6 +123,42 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
// Windows' Installed apps › Uninstall runs `magpie uninstall --window`,
// which opens the window here (uninstallView): the question is asked at
// once, once, and nothing goes before the reader says Uninstall.
for (const lang of ["en", "zh"]) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}: opened from Installed apps, it asks at once`, async (t) => {
const { page, errors, posts } = await opened(t, engine, lang, width, {});
const w = words[lang];
await dialog(page).waitFor();
assert.equal(await dialog(page).locator("h2").textContent(), w.title);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "wider than the window");
await dialog(page).getByRole("button", { name: w.cancel, exact: true }).click();
await dialog(page).waitFor({ state: "detached" });
// Settings drawn again (a text size change) doesn't ask again
await page.evaluate(() => renderSettings());
await page.waitForTimeout(300);
assert.equal(await dialog(page).count(), 0, "asked again");
assert.deepEqual(posts, []);
await page.locator("#uninstallRow button").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}: magpie web opened at the uninstall link asks nothing`, async (t) => {
const { page, errors, posts } = await opened(t, engine, "en", 1100, { web: true });
await page.locator("#about .row").first().waitFor();
await page.waitForTimeout(300);
assert.equal(await dialog(page).count(), 0);
assert.deepEqual(posts, []);
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);
+13 -1
View File
@@ -128,11 +128,23 @@ func Stale(target, dir, exe string) bool {
return !same(target, exe) || !same(dir, filepath.Dir(exe))
}
// UninstallArgs are what Windows' Installed apps runs magpie with for its
// Uninstall: the app's window on Settings › Uninstall magpie, which asks
// first and puts every agent back before magpie's files go. It is started
// with no console, so the terminal's `magpie uninstall` couldn't ask.
var UninstallArgs = []string{"uninstall", "--window"}
// UninstallCommand is the command line Installed apps runs for exe.
func UninstallCommand(exe string) string {
return `"` + exe + `" ` + strings.Join(UninstallArgs, " ")
}
// 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
// shortcut, the App Paths and Installed apps entries while they name 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 {
+10
View File
@@ -38,3 +38,13 @@ func TestStale(t *testing.T) {
}
}
}
// Installed apps runs the exe it names, quoted, with the arguments the
// CLI opens the window on (the path has spaces under a user's name).
func TestUninstallCommand(t *testing.T) {
got := UninstallCommand(`C:\Users\Ann Lee\AppData\Local\Programs\magpie\magpie.exe`)
want := `"C:\Users\Ann Lee\AppData\Local\Programs\magpie\magpie.exe" uninstall --window`
if got != want {
t.Fatalf("UninstallCommand = %s, want %s", got, want)
}
}
+58 -6
View File
@@ -16,8 +16,8 @@ import (
)
// appPath is where Win+R and `start magpie` look magpie.exe up: the user's
// own, no administrator needed
const appPath = `Software\Microsoft\Windows\CurrentVersion\App Paths\magpie.exe`
// own, no administrator needed. A var so the test writes a key of its own.
var appPath = `Software\Microsoft\Windows\CurrentVersion\App Paths\magpie.exe`
func registerAppPath(exe string) {
if k, _, err := registry.CreateKey(registry.CURRENT_USER, appPath, registry.SET_VALUE); err == nil {
@@ -25,6 +25,57 @@ func registerAppPath(exe string) {
_ = k.SetStringValue("Path", filepath.Dir(exe))
k.Close()
}
registerUninstall(exe)
}
// uninstallKey is magpie's entry in Settings › Apps › Installed apps (and
// Control Panel's Programs and Features), the user's own. With none,
// Windows' own way to remove a program didn't list magpie, so it was
// deleted by hand, which runs no code: Codex kept openai_base_url on a
// gateway that was gone (Jevik_AI on X). Its Uninstall runs magpie's own
// (UninstallCommand), which puts every agent back first. A var so the
// test writes a key of its own.
var uninstallKey = `Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie`
// registerUninstall writes the entry for exe, at every start, so it
// follows an exe that was moved.
func registerUninstall(exe string) {
k, _, err := registry.CreateKey(registry.CURRENT_USER, uninstallKey, registry.SET_VALUE)
if err != nil {
return
}
defer k.Close()
for name, v := range map[string]string{
"DisplayName": Name,
"DisplayIcon": exe + ",0",
"Publisher": Name,
"InstallLocation": filepath.Dir(exe),
"UninstallString": UninstallCommand(exe),
"URLInfoAbout": "https://usemagpie.ai",
} {
_ = k.SetStringValue(name, v)
}
// Uninstall is the one button: there is nothing to modify or repair
_ = k.SetDWordValue("NoModify", 1)
_ = k.SetDWordValue("NoRepair", 1)
}
// unregisterUninstall takes the entry out while it is exe's, or its exe
// is gone; another magpie's stays.
func unregisterUninstall(exe string) error {
k, err := registry.OpenKey(registry.CURRENT_USER, uninstallKey, registry.QUERY_VALUE)
if err != nil {
return nil // none
}
v, _, err := k.GetStringValue("DisplayIcon")
k.Close()
v = strings.TrimSuffix(v, ",0")
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, uninstallKey)
}
func registeredAppPath() bool {
@@ -124,18 +175,19 @@ func write(lnk, exe string) (bool, error) {
}
// unregisterAppPath takes magpie's App Paths entry out while it opens exe,
// or an exe that is gone.
// or an exe that is gone, and its Installed apps entry the same way.
func unregisterAppPath(exe string) error {
uerr := unregisterUninstall(exe)
k, err := registry.OpenKey(registry.CURRENT_USER, appPath, registry.QUERY_VALUE)
if err != nil {
return nil // none
return uerr // 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 uerr // another magpie's
}
}
return registry.DeleteKey(registry.CURRENT_USER, appPath)
return errors.Join(uerr, registry.DeleteKey(registry.CURRENT_USER, appPath))
}
@@ -4,6 +4,8 @@ import (
"os"
"path/filepath"
"testing"
"golang.org/x/sys/windows/registry"
)
// A shortcut is made, left be while it opens this exe, and pointed at the
@@ -33,3 +35,67 @@ func TestWrite(t *testing.T) {
t.Fatal("no shortcut:", err)
}
}
// magpie is in Installed apps (Jevik_AI on X deleted it by hand, which
// runs no code, and Codex kept pointing at a gateway that was gone): the
// entry opens this exe's Uninstall, follows an exe that moved, goes with
// Remove, and one another magpie's exe still holds stays.
func TestInstalledAppsEntry(t *testing.T) {
was, wasApp := uninstallKey, appPath
uninstallKey = `Software\magpie-test\` + t.Name() + `\Uninstall\magpie`
appPath = `Software\magpie-test\` + t.Name() + `\App Paths\magpie.exe`
t.Cleanup(func() {
registry.DeleteKey(registry.CURRENT_USER, uninstallKey)
registry.DeleteKey(registry.CURRENT_USER, appPath)
registry.DeleteKey(registry.CURRENT_USER, `Software\magpie-test\`+t.Name()+`\Uninstall`)
registry.DeleteKey(registry.CURRENT_USER, `Software\magpie-test\`+t.Name()+`\App Paths`)
registry.DeleteKey(registry.CURRENT_USER, `Software\magpie-test\`+t.Name())
uninstallKey, appPath = was, wasApp
})
read := func(name string) string {
k, err := registry.OpenKey(registry.CURRENT_USER, uninstallKey, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer k.Close()
v, _, _ := k.GetStringValue(name)
return v
}
dir := t.TempDir()
exe := filepath.Join(dir, "a", "magpie.exe")
other := filepath.Join(dir, "b", "magpie.exe")
for _, f := range []string{exe, other} {
os.MkdirAll(filepath.Dir(f), 0o755)
os.WriteFile(f, []byte("MZ"), 0o755)
}
// written where every installed start writes App Paths
registerAppPath(exe)
if got := read("UninstallString"); got != UninstallCommand(exe) {
t.Fatalf("UninstallString = %q", got)
}
if read("DisplayName") != Name || read("InstallLocation") != filepath.Dir(exe) || read("DisplayIcon") != exe+",0" {
t.Fatalf("entry: %q %q %q", read("DisplayName"), read("InstallLocation"), read("DisplayIcon"))
}
// another magpie, still there, keeps its entry
if err := unregisterAppPath(other); err != nil {
t.Fatal(err)
}
if read("UninstallString") == "" {
t.Fatal("removed another magpie's entry")
}
if err := unregisterAppPath(exe); err != nil {
t.Fatal(err)
}
if read("UninstallString") != "" {
t.Fatal("the entry stayed after Remove")
}
// one whose exe is gone goes with any magpie's uninstall
registerUninstall(other)
os.Remove(other)
if err := unregisterUninstall(exe); err != nil {
t.Fatal(err)
}
if read("UninstallString") != "" {
t.Fatal("an entry for an exe that is gone stayed")
}
}