Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
agent: a Windows app closed to the tray is ended at once on Restart, not after 10s
yetone172e65c80bef
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex f26ba2c38..94591ce95 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -21,7 +21,7 @@ something else shows up as drift.| 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) |+| 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`); 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) || Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) || WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-<agent>` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) |diff --git a/internal/agent/apprestart.go b/internal/agent/apprestart.goindex 86e703b8d..cf569bfc7 100644--- a/internal/agent/apprestart.go+++ b/internal/agent/apprestart.go@@ -88,17 +88,23 @@ type winProc struct {// The Windows part of a restart, vars so tests stand in for each:// winProcs lists the running processes named exe, winClose asks pids to close as-// their windows' close does, winEnd ends pid with its tree, and winLaunch-// opens what a restart opens again.+// their windows' close does, winShown says whether any of pids still shows+// a window (true when it can't tell), winEnd ends pid with its tree, and+// winLaunch opens what a restart opens again.var (winProcs = listWinProcswinClose = closeWinProcs+ winShown = winWindowsShownwinEnd = endWinTreewinLaunch = launchWin- // appCloseWait is how long a Windows app has to close by itself- // before it is ended, and appBackWait how long it has to come back+ // appCloseWait is how long a Windows app that still shows a window+ // has to close by itself before it is ended, and appBackWait how long+ // it has to come back. appTrayGrace is how long one whose windows have+ // all closed has to end by itself before it counts as staying in the+ // tray.appCloseWait = 10 * time.SecondappBackWait = 20 * time.Second+ appTrayGrace = time.SecondappPoll = 200 * time.Millisecond)@@ -307,12 +313,18 @@ func (a *Agent) RestartApp(ctx context.Context) error {if c.bundle != "" {return reopenBundle(ctx, a, c.bundle)}+ return a.restartWin(ctx, r, c)+}++// restartWin asks c's windows to close, ends it when it stays (in+// the tray, or past appCloseWait), opens it again and waits for it.+func (a *Agent) restartWin(ctx context.Context, r restartable, c appRunning) error {pids := make([]int, len(c.procs))for i, p := range c.procs {pids[i] = p.pid}_ = winClose(pids)- if !waitGone(ctx, r, appCloseWait) {+ if !waitClosed(ctx, r, appCloseWait) {if ctx.Err() != nil {return ctx.Err()}@@ -342,6 +354,42 @@ func (a *Agent) RestartApp(ctx context.Context) error {}}+// waitClosed waits, after its windows were asked to close, until r's app+// no longer runs: true when it ended by itself. An app that closed every+// window and still runs after appTrayGrace has gone to the tray, which no+// waiting ends (Claude Desktop 2.9939 on Windows hides its window in ~0.6s+// and keeps all nine processes), so it is false then, not after limit;+// limit is for an app still showing a window, which may be asking+// something.+func waitClosed(ctx context.Context, r restartable, limit time.Duration) bool {+ start := time.Now()+ end := start.Add(limit)+ for {+ c, ok := findRestartable(r)+ if !ok {+ return true+ }+ now := time.Now()+ if !now.Before(end) {+ return false+ }+ if now.Sub(start) >= appTrayGrace {+ pids := make([]int, len(c.procs))+ for i, p := range c.procs {+ pids[i] = p.pid+ }+ if !winShown(pids) {+ return false+ }+ }+ select {+ case <-ctx.Done():+ return false+ case <-time.After(appPoll):+ }+ }+}+// waitGone waits until r's app no longer runs, for at most limit.func waitGone(ctx context.Context, r restartable, limit time.Duration) bool {end := time.Now().Add(limit)diff --git a/internal/agent/apprestart_other.go b/internal/agent/apprestart_other.goindex 581e309ea..ba8bf7f53 100644--- a/internal/agent/apprestart_other.go+++ b/internal/agent/apprestart_other.go@@ -9,4 +9,5 @@ var errNotWindows = errors.New("only on Windows")func listWinProcs(string) []winProc { return nil }func closeWinProcs([]int) error { return errNotWindows }func endWinTree(int) error { return errNotWindows }+func winWindowsShown([]int) bool { return true }func launchWin(winProc) error { return errNotWindows }diff --git a/internal/agent/apprestart_test.go b/internal/agent/apprestart_test.goindex 6f78f72d0..0aae28083 100644--- a/internal/agent/apprestart_test.go+++ b/internal/agent/apprestart_test.go@@ -36,13 +36,16 @@ func restartSandbox(t *testing.T) string {wasWin, wasMac, wasFolders, wasRunning := restartOnWindows, restartOnMac, appFolders, runningwasQuit, wasOpen, wasQuitWait := appQuit, appOpen, appQuitWaitwasProcs, wasClose, wasEnd, wasLaunch, wasCloseWait, wasBackWait, wasPoll := winProcs, winClose, winEnd, winLaunch, appCloseWait, appBackWait, appPoll+ wasShown, wasGrace := winShown, appTrayGracet.Cleanup(func() {restartOnWindows, restartOnMac, appFolders, running = wasWin, wasMac, wasFolders, wasRunningappQuit, appOpen, appQuitWait = wasQuit, wasOpen, wasQuitWaitwinProcs, winClose, winEnd, winLaunch, appCloseWait, appBackWait, appPoll = wasProcs, wasClose, wasEnd, wasLaunch, wasCloseWait, wasBackWait, wasPoll+ winShown, appTrayGrace = wasShown, wasGrace})restartOnWindows, restartOnMac = false, falseappPoll = 5 * time.Millisecond+ winShown = func([]int) bool { return true }return home}@@ -209,6 +212,86 @@ func TestWorkBuddyRestartOnWindows(t *testing.T) {}}+// An app that closes its window to the tray (Claude Desktop on Windows+// hides it in ~0.6s and keeps every process; CyberCaius on Discord, 10-29:+// slower than quitting by hand) is ended once its windows are gone, not+// after the whole wait for one still showing a window. One that shows a+// window still is given that wait, and one that ends by itself in the+// grace is never ended.+func TestRestartEndsAppInTrayAtOnce(t *testing.T) {+ const exe = `C:\Program Files\WorkBuddy\WorkBuddy.exe`+ cases := []struct {+ name string+ shown func(since time.Duration) bool+ endsBy time.Duration // the app ends by itself this long after the close; 0 never+ want []string+ atLeast time.Duration+ under time.Duration+ }{+ {"tray", func(d time.Duration) bool { return d < 30*time.Millisecond }, 0,+ []string{"close 10 11", "end 10", "open " + exe}, 100 * time.Millisecond, 2 * time.Second},+ {"asking", func(time.Duration) bool { return true }, 0,+ []string{"close 10 11", "end 10", "open " + exe}, 3 * time.Second, 10 * time.Second},+ {"quits itself", func(d time.Duration) bool { return d < 30*time.Millisecond }, 60 * time.Millisecond,+ []string{"close 10 11", "open " + exe}, 0, 2 * time.Second},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ home := restartSandbox(t)+ restartOnWindows = true+ appCloseWait, appBackWait, appTrayGrace = 3*time.Second, time.Second, 100*time.Millisecond+ start := time.Now().Add(-time.Hour)+ alive := true+ var closed time.Time+ winProcs = func(name string) []winProc {+ if !closed.IsZero() && c.endsBy > 0 && time.Since(closed) >= c.endsBy {+ alive = false+ }+ if !alive || !strings.EqualFold(name, "WorkBuddy.exe") {+ return nil+ }+ return []winProc{+ {pid: 10, parent: 4, image: exe, start: start},+ {pid: 11, parent: 10, image: exe, start: start.Add(time.Second)},+ }+ }+ winShown = func([]int) bool { return closed.IsZero() || c.shown(time.Since(closed)) }+ var did []string+ winClose = func(pids []int) error {+ slices.Sort(pids)+ did = append(did, "close "+strings.Trim(fmt.Sprint(pids), "[]"))+ closed = time.Now()+ return nil+ }+ winEnd = func(pid int) error {+ did = append(did, fmt.Sprint("end ", pid))+ alive = false+ return nil+ }+ winLaunch = func(p winProc) error {+ did = append(did, "open "+p.image)+ alive, start, closed = true, time.Now(), time.Time{}+ return nil+ }+ a := workbuddy(home)+ if err := a.Field("provider").Set("magpie"); err != nil {+ t.Fatal(err)+ }+ began := time.Now()+ if err := a.RestartApp(context.Background()); err != nil {+ t.Fatal(err)+ }+ took := time.Since(began)+ if !slices.Equal(did, c.want) {+ t.Fatalf("did %q, want %q", did, c.want)+ }+ if took < c.atLeast || took >= c.under {+ t.Fatalf("took %v, want at least %v and under %v", took, c.atLeast, c.under)+ }+ })+ }+}+// Which Windows processes are each app's: Claude Desktop's claude.exe, not// Claude Code's; WorkBuddy's WorkBuddy.exe, not WorkBuddy AI's.func TestRestartAppsOnWindows(t *testing.T) {diff --git a/internal/agent/apprestart_windows.go b/internal/agent/apprestart_windows.goindex 93f9c71ab..2019932b7 100644--- a/internal/agent/apprestart_windows.go+++ b/internal/agent/apprestart_windows.go@@ -8,6 +8,7 @@ import ("path/filepath""strconv""strings"+ "sync""time""unsafe"@@ -83,6 +84,41 @@ func closeWinProcs(pids []int) error {return proc.Command("taskkill", args...).Run()}+// shownCallback is EnumWindows' callback, made once: Go has room for only+// so many. shownPids and shownSeen are its input and output, under shownMu.+var (+ shownMu sync.Mutex+ shownPids map[uint32]bool+ shownSeen bool+ shownCallback = windows.NewCallback(func(h windows.HWND, _ uintptr) uintptr {+ var pid uint32+ if _, err := windows.GetWindowThreadProcessId(h, &pid); err == nil && shownPids[pid] && windows.IsWindowVisible(h) {+ shownSeen = true+ return 0+ }+ return 1+ })+)++// winWindowsShown says whether any of pids has a visible top-level window,+// true when the windows can't be listed. An Electron app closed to the+// tray hides its window and keeps running.+func winWindowsShown(pids []int) bool {+ shownMu.Lock()+ defer shownMu.Unlock()+ shownPids = make(map[uint32]bool, len(pids))+ for _, p := range pids {+ shownPids[uint32(p)] = true+ }+ shownSeen = false+ if err := windows.EnumWindows(shownCallback, nil); err != nil && !shownSeen {+ // a callback that stops the walk makes EnumWindows return an+ // error too; any other error leaves it unknown+ return true+ }+ return shownSeen+}+// endWinTree ends pid and every process under it.func endWinTree(pid int) error {out, err := proc.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(pid)).CombinedOutput()