agent: a Windows app closed to the tray is ended at once on Restart, not after 10s

CyberCaius on Discord (10-29): magpie's Restart of Claude Desktop on
Windows is slower than quitting and opening it by hand. The cause:
RestartApp asks the app's windows to close (taskkill without /F), then
waited up to appCloseWait (10s) for every claude.exe to end. Claude
Desktop on Windows hides its window to the tray in ~0.6s and keeps all
its processes, so every Restart sat out the whole 10s before ending the
tree.

waitClosed now also watches the windows (winShown, EnumWindows +
IsWindowVisible over the app's pids): once every window is hidden and
the app still runs appTrayGrace (1s) after the close, it is in the tray
and its tree is ended at once. An app still showing a window (a
question) keeps the full appCloseWait, and one that ends by itself in
the grace is never ended. When the windows can't be listed, it is
treated as shown (the old wait). The Windows part of RestartApp moved
into restartWin, unchanged otherwise.

Measured on the Windows box (xiaomi-gpu, Squirrel Claude Desktop
4.29.0, run in the interactive session through a scheduled task), the
real restartWin path through a test binary, 3 runs each:
  before (tray grace off): returned 10.87-11.10s, window back 11.4-11.7s
  after: returned 1.88-2.16s, window back 2.4-2.8s
A forced kill and relaunch by hand: ~1.6s. A PowerShell emulation of the
old path on 2.9939.2 earlier: WM_CLOSE hid the window at 0.6s, 9
processes stayed, all gone only after the 10s kill (12.3s total).

Run:
- TestRestartEndsAppInTrayAtOnce (new): tray / asking / quits-itself.
  With the winShown check removed by hand, the tray case went red
  (took 3.01s, want under 2s).
- mote: go test ./internal/agent -count=1 -timeout 45m: ok (174s).
- win-run: TestRestartEndsAppInTrayAtOnce, TestWorkBuddyRestartOnWindows,
  TestRestartAppsOnWindows pass. The -run Restart|ChangedAt|WorkBuddyOwnSave
  set has TestWorkBuddyOwnSaveAfterStartIsNoChange red on Windows, red
  the same on untouched origin/main 5be581a1c (3 of 3); filed in #4115.
- mote: gofmt -l, go vet ./internal/agent for darwin, linux (-tags
  nogui) and windows: clean.

Not tried: the MSIX (Store) Claude build, and WorkBuddy on Windows with
the real app.
This commit is contained in:
yetone
2026-10-29 22:25:36 +08:00
parent 87c68c98c5
commit 172e65c80b
5 changed files with 174 additions and 6 deletions
+1 -1
View File
@@ -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) |
+53 -5
View File
@@ -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 = listWinProcs
winClose = closeWinProcs
winShown = winWindowsShown
winEnd = endWinTree
winLaunch = 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.Second
appBackWait = 20 * time.Second
appTrayGrace = time.Second
appPoll = 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)
+1
View File
@@ -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 }
+83
View File
@@ -36,13 +36,16 @@ func restartSandbox(t *testing.T) string {
wasWin, wasMac, wasFolders, wasRunning := restartOnWindows, restartOnMac, appFolders, running
wasQuit, wasOpen, wasQuitWait := appQuit, appOpen, appQuitWait
wasProcs, wasClose, wasEnd, wasLaunch, wasCloseWait, wasBackWait, wasPoll := winProcs, winClose, winEnd, winLaunch, appCloseWait, appBackWait, appPoll
wasShown, wasGrace := winShown, appTrayGrace
t.Cleanup(func() {
restartOnWindows, restartOnMac, appFolders, running = wasWin, wasMac, wasFolders, wasRunning
appQuit, appOpen, appQuitWait = wasQuit, wasOpen, wasQuitWait
winProcs, winClose, winEnd, winLaunch, appCloseWait, appBackWait, appPoll = wasProcs, wasClose, wasEnd, wasLaunch, wasCloseWait, wasBackWait, wasPoll
winShown, appTrayGrace = wasShown, wasGrace
})
restartOnWindows, restartOnMac = false, false
appPoll = 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) {
+36
View File
@@ -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()