Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
agents: Restart a desktop app that started before magpie's change, after asking
yetoned08b6118bd60
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 103b9a7ad..18d7b1da6 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -20,6 +20,7 @@ something else shows up as drift.| 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) || 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. 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. 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`). `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/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.mdindex decea538d..f77d39f97 100644--- a/docs/subsystems/gui-shell.md+++ b/docs/subsystems/gui-shell.md@@ -13,7 +13,7 @@ three.| --- | --- | --- || Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). | [`app.go`](../../internal/gui/app.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) || Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go) |-| API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |+| API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) || Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) || The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) || Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |diff --git a/internal/agent/apprestart.go b/internal/agent/apprestart.gonew file mode 100644index 000000000..de85b5d80--- /dev/null+++ b/internal/agent/apprestart.go@@ -0,0 +1,378 @@+package agent++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/desktopdir"+ "github.com/yetone/magpie/internal/edit"+ "github.com/yetone/magpie/internal/provider"+)++// Claude Desktop and WorkBuddy read what magpie writes for them as they+// start (微雨南山 and stones on Discord, 10-24: a provider added showed up+// there only after a restart). Claude Desktop asks the gateway for its+// models once, at start. WorkBuddy 5.6's app.asar watches models.json only+// when the file was there at start, and the watch is on the file itself,+// so a rewrite by rename leaves it watching the old one. While such an app+// runs on what it read before magpie's last change, its Agents row offers+// a Restart. magpie never restarts one unasked: the button asks first, in+// magpie's own dialog, and only then quits the app as its own Quit does+// and opens it again. The Codex app on macOS has its own Restart on its+// stale-copy line (codex_app.go), behind the same question.++// restartable is how one such app is found running: its macOS bundle (an+// id and the names it is installed under), and on Windows its executable's+// name with a test of a process's image path that says it is the app's.+type restartable struct {+ mac desktopApp+ winExe string+ win func(image string) bool+}++// claudeDesktopApp is Claude Desktop's bundle (Claude 2.7032's Info.plist:+// com.anthropic.claudefordesktop, executable Claude).+var claudeDesktopApp = desktopApp{id: "com.anthropic.claudefordesktop", names: []string{"Claude.app"}}++// restartApps are the agents whose desktop app the Agents row restarts.+// macOS: Claude.app, WorkBuddy.app and WorkBuddy AI.app (both run an+// executable named Electron). Windows: Claude Desktop is claude.exe, from+// Squirrel's %LOCALAPPDATA%\AnthropicClaude (a claude.exe stub beside+// app-<version>\claude.exe) or its MSIX (desktopdir's Claude_… and+// AnthropicPBC.Claude_…), never Claude Code's claude.exe elsewhere;+// WorkBuddy is C:\Program Files\WorkBuddy\WorkBuddy.exe (5.6.2, seen on+// the Windows box). WorkBuddy AI's Windows build wasn't to hand, so it has+// no Restart there. None of them ships a Linux app.+var restartApps = map[string]restartable{+ "claude-desktop": {mac: claudeDesktopApp, winExe: "claude.exe", win: func(image string) bool {+ return winBase(image, "claude.exe") && (winHas(image, `\AnthropicClaude\`) || winHas(image, `\WindowsApps\Claude_`) || winHas(image, `\WindowsApps\AnthropicPBC.Claude_`))+ }},+ "workbuddy": {mac: workbuddyApp, winExe: "WorkBuddy.exe", win: func(image string) bool {+ return winBase(image, "WorkBuddy.exe") && !winHas(image, `WorkBuddy AI`) && !winHas(image, `WorkBuddy-AI`)+ }},+ "workbuddy-ai": {mac: workbuddyAIApp},+}++func winBase(image, name string) bool {+ i := strings.LastIndexAny(image, `\/`)+ return strings.EqualFold(image[i+1:], name)+}++func winHas(image, part string) bool {+ return strings.Contains(strings.ToLower(image), strings.ToLower(part))+}++// restartOnWindows and restartOnMac say which system this is; vars so a+// test runs either.+var (+ restartOnWindows = runtime.GOOS == "windows"+ restartOnMac = runtime.GOOS == "darwin"+)++// winProc is a process running on Windows: its id, its parent's, its+// image's full path, when it started, and its AppUserModelID when it is a+// packaged (Store or MSIX) app's.+type winProc struct {+ pid, parent int+ image string+ start time.Time+ aumid string+}++// 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.+var (+ winProcs = listWinProcs+ winClose = closeWinProcs+ 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 = 10 * time.Second+ appBackWait = 20 * time.Second+ appPoll = 200 * time.Millisecond+)++// appRunning is r's app as it runs here: when it started, and on macOS its+// bundle, on Windows its processes and the one the rest hang off.+type appRunning struct {+ since time.Time+ bundle string+ procs []winProc+ main winProc+}++// findRestartable is r's app running here, if it is.+func findRestartable(r restartable) (appRunning, bool) {+ if restartOnWindows {+ if r.win == nil {+ return appRunning{}, false+ }+ var ps []winProc+ for _, p := range winProcs(r.winExe) {+ if r.win(p.image) {+ ps = append(ps, p)+ }+ }+ if len(ps) == 0 {+ return appRunning{}, false+ }+ mine := map[int]bool{}+ for _, p := range ps {+ mine[p.pid] = true+ }+ // the main process is the one whose parent isn't the app's:+ // Electron's helpers hang off it+ c := appRunning{procs: ps, main: ps[0], since: ps[0].start}+ top := false+ for _, p := range ps {+ if p.start.Before(c.since) {+ c.since = p.start+ }+ if !mine[p.parent] && (!top || p.start.Before(c.main.start)) {+ c.main, top = p, true+ }+ }+ return c, true+ }+ if !restartOnMac || r.mac.id == "" {+ return appRunning{}, false+ }+ for _, b := range macBundles(r.mac) {+ exe := bundleExecutable(b, r.mac.id)+ if exe == "" {+ continue+ }+ ps := running("^" + regexp.QuoteMeta(filepath.Join(b, "Contents", "MacOS", exe)) + "( |$)")+ if len(ps) == 0 {+ continue+ }+ up := ps[0].up+ for _, p := range ps[1:] {+ up = max(up, p.up)+ }+ return appRunning{since: time.Now().Add(-up), bundle: b}, true+ }+ return appRunning{}, false+}++// bundleExecutable is the CFBundleExecutable of the bundle at b when its+// Info.plist says it is id's, "" otherwise.+func bundleExecutable(b, id string) string {+ info, err := os.ReadFile(filepath.Join(b, "Contents", "Info.plist"))+ if err != nil {+ return ""+ }+ got := plistIDRe.FindSubmatch(info)+ exe := plistExeRe.FindSubmatch(info)+ if got == nil || exe == nil || strings.TrimSpace(string(got[1])) != id {+ return ""+ }+ return strings.TrimSpace(string(exe[1]))+}++// AppRun is a desktop app running on what it read before magpie's last+// change to it: when it started, for the row to offer a Restart.+type AppRun struct {+ Since time.Time `json:"since"`+}++// AppBehind is the agent's desktop app when it runs here and started+// before magpie last changed what it reads at start; nil when it isn't+// running, has started since, or magpie doesn't restart it here. Only for+// an agent connected to magpie, or one disconnected from it in magpie:+// those are the changes magpie made.+func (a *Agent) AppBehind() *AppRun {+ r, ok := restartApps[a.ID]+ if !ok || a.WSL != "" {+ return nil+ }+ if !a.Wired() && !a.Disconnected() {+ return nil+ }+ files, reads := a.appReads()+ if len(files) == 0 {+ return nil+ }+ c, ok := findRestartable(r)+ if !ok {+ return nil+ }+ changed := a.changedAt(files, reads)+ if changed.IsZero() || !c.since.Before(changed.Add(-time.Second)) {+ return nil+ }+ return &AppRun{Since: c.since}+}++// appReads are the files the agent's desktop app reads magpie's part from+// at start, and that part. Claude Desktop: deploymentMode, the profile+// applied and magpie's profile, with the models the gateway lists it.+// WorkBuddy: its models.json.+func (a *Agent) appReads() (files []string, reads func() string) {+ switch a.ID {+ case "claude-desktop":+ ps := desktopSetsHere()+ for _, p := range ps {+ files = append(files, p.config, p.config3p, p.meta, p.prof)+ }+ return files, func() string {+ var b strings.Builder+ for _, p := range ps {+ m, _ := edit.GetJSON(p.config, "deploymentMode")+ m3, _ := edit.GetJSON(p.config3p, "deploymentMode")+ id, _ := edit.GetJSON(p.meta, "appliedId")+ prof, _ := edit.Read(p.prof)+ b.WriteString(m + "\n" + m3 + "\n" + id + "\n")+ b.Write(prof)+ b.WriteString("\n")+ }+ shown, _ := provider.CatalogFor(a.ListsFor())+ for _, e := range shown {+ b.WriteString(e.ID + "\n")+ }+ return b.String()+ }+ case "workbuddy", "workbuddy-ai":+ return []string{a.Path}, func() string {+ c, _ := edit.Read(a.Path)+ return string(c)+ }+ }+ return nil, nil+}++// desktopSetsHere are Claude Desktop's folders on this computer.+var desktopSetsHere = func() []desktopPaths {+ home, _ := os.UserHomeDir()+ return desktopSets(desktopdir.OS, home, os.Getenv)+}++// restarting holds one restart per agent at a time, so a second click+// waits for the first instead of quitting the app it just opened.+var restarting sync.Map++// What a Restart that didn't go through says, in the reader's language+// (tNotice): an app not on the old settings any more was quit or+// restarted meanwhile.+var (+ noticeRestartNotHere = newNotice("magpie doesn't restart {agent} on this computer.")+ noticeRestartCurrent = newNotice("{agent} isn't running on the old settings any more.")+ noticeRestartAsk = newNotice("magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.")+ noticeRestartStillOpen = newNotice("{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.")+ noticeRestartStillThere = newNotice("{agent} is still running. Quit it, then open it again.")+ noticeRestartNoOpen = newNotice("{agent} quit, but didn't open again. Open it yourself.")+)++func restartErr(n notice, a *Agent) error { return errors.New(n.say("agent", a.Name)) }++// RestartApp quits the agent's desktop app and opens it again, so it reads+// what magpie wrote. Only the Agents row's Restart calls it, after the+// user confirmed, and only an app AppBehind lists is quit. macOS: asked to+// quit as ⌘Q does, every process of its bundle waited for; one still open+// then (it may be asking something) is left, never forced, and not opened+// a second time. Windows: its windows are asked to close; an app still+// running then (Electron apps stay in the tray) is ended with its tree.+func (a *Agent) RestartApp(ctx context.Context) error {+ r, ok := restartApps[a.ID]+ if !ok || a.WSL != "" {+ return restartErr(noticeRestartNotHere, a)+ }+ mu, _ := restarting.LoadOrStore(a.ID, &sync.Mutex{})+ mu.(*sync.Mutex).Lock()+ defer mu.(*sync.Mutex).Unlock()+ if a.AppBehind() == nil {+ return restartErr(noticeRestartCurrent, a)+ }+ c, ok := findRestartable(r)+ if !ok {+ return restartErr(noticeRestartCurrent, a)+ }+ if c.bundle != "" {+ return reopenBundle(ctx, a, c.bundle)+ }+ pids := make([]int, len(c.procs))+ for i, p := range c.procs {+ pids[i] = p.pid+ }+ _ = winClose(pids)+ if !waitGone(ctx, r, appCloseWait) {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if err := winEnd(c.main.pid); err != nil || !waitGone(ctx, r, appCloseWait) {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ return restartErr(noticeRestartStillThere, a)+ }+ }+ if err := winLaunch(c.main); err != nil {+ return restartErr(noticeRestartNoOpen, a)+ }+ end := time.Now().Add(appBackWait)+ for {+ if _, ok := findRestartable(r); ok {+ return nil+ }+ if !time.Now().Before(end) {+ return restartErr(noticeRestartNoOpen, a)+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ 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)+ for {+ if _, ok := findRestartable(r); !ok {+ return true+ }+ if !time.Now().Before(end) {+ return false+ }+ select {+ case <-ctx.Done():+ return false+ case <-time.After(appPoll):+ }+ }+}++// reopenBundle quits the app at bundle, as ⌘Q does, waits for every+// process under it to end and opens it again (codex_app.go's way).+func reopenBundle(ctx context.Context, a *Agent, bundle string) error {+ if err := appQuit(ctx, bundle); err != nil {+ return restartErr(noticeRestartAsk, a)+ }+ pat := regexp.QuoteMeta(bundle + "/Contents/")+ end := time.Now().Add(appQuitWait)+ for len(running(pat)) > 0 {+ if time.Now().After(end) {+ return restartErr(noticeRestartStillOpen, a)+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(appPoll):+ }+ }+ if err := appOpen(ctx, bundle); err != nil {+ return restartErr(noticeRestartNoOpen, a)+ }+ return nil+}diff --git a/internal/agent/apprestart_other.go b/internal/agent/apprestart_other.gonew file mode 100644index 000000000..581e309ea--- /dev/null+++ b/internal/agent/apprestart_other.go@@ -0,0 +1,12 @@+//go:build !windows++package agent++import "errors"++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 launchWin(winProc) error { return errNotWindows }diff --git a/internal/agent/apprestart_test.go b/internal/agent/apprestart_test.gonew file mode 100644index 000000000..0d3bf5933--- /dev/null+++ b/internal/agent/apprestart_test.go@@ -0,0 +1,275 @@+package agent++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "regexp"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// restartSandbox is a home with a provider in it and WorkBuddy found by its+// folder; the system is said to be neither macOS nor Windows until a test+// says which.+func restartSandbox(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))+ t.Setenv("WORKBUDDY_CONFIG_DIR", "")+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil {+ t.Fatal(err)+ }+ os.MkdirAll(filepath.Join(home, ".workbuddy"), 0o755)+ os.WriteFile(filepath.Join(home, ".workbuddy", "models.json"), []byte(`[]`), 0o600)+ notOnMac(t)+ 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+ 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+ })+ restartOnWindows, restartOnMac = false, false+ appPoll = 5 * time.Millisecond+ return home+}++// macApp puts a bundle with id and executable exe at dir/name, as an+// installer leaves it.+func macApp(t *testing.T, dir, name, id, exe string) string {+ t.Helper()+ b := filepath.Join(dir, name)+ os.MkdirAll(filepath.Join(b, "Contents", "MacOS"), 0o755)+ os.WriteFile(filepath.Join(b, "Contents", "Info.plist"), []byte(`<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict>+ <key>CFBundleExecutable</key>+ <string>`+exe+`</string>+ <key>CFBundleIdentifier</key>+ <string>`+id+`</string>+</dict></plist>`), 0o644)+ return b+}++// WorkBuddy on a Mac: its row offers a Restart only while WorkBuddy.app+// runs on a models.json older than magpie's last write of it, and the+// Restart quits it as ⌘Q does, waits for it to end, and opens it again.+// One that doesn't end is said and not opened a second time.+func TestWorkBuddyRestartOnMac(t *testing.T) {+ home := restartSandbox(t)+ apps := filepath.Join(home, "Applications")+ bundle := macApp(t, apps, "WorkBuddy.app", "com.tencent.workbuddy.mac", "Electron")+ // WorkBuddy AI's bundle is another app: never WorkBuddy's+ macApp(t, apps, "WorkBuddy AI.app", "com.workbuddy.workbuddy-ai", "Electron")+ restartOnMac = true+ appFolders = func() []string { return []string{apps} }+ alive, up := true, time.Hour+ var pats []string+ running = func(pat string) []runningProc {+ pats = append(pats, pat)+ ps := []runningProc{+ {up, bundle + "/Contents/MacOS/Electron"},+ {up, bundle + "/Contents/Frameworks/WorkBuddy Helper.app/Contents/MacOS/WorkBuddy Helper --type=gpu-process"},+ }+ var out []runningProc+ for _, p := range ps {+ if alive && regexp.MustCompile(pat).MatchString(p.cmd) {+ out = append(out, p)+ }+ }+ return out+ }+ a := workbuddy(home)++ if a.AppBehind() != nil {+ t.Fatal("offered a Restart for WorkBuddy not connected to magpie")+ }+ if err := a.Field("provider").Set("magpie"); err != nil {+ t.Fatal(err)+ }+ got := a.AppBehind()+ if got == nil {+ t.Fatalf("no Restart for WorkBuddy started an hour before magpie wrote its models (asked %q)", pats)+ }+ if d := time.Since(got.Since); d < 59*time.Minute || d > 61*time.Minute {+ t.Fatalf("since %v ago", d)+ }+ if !slices.ContainsFunc(pats, func(p string) bool { return strings.Contains(p, `WorkBuddy\.app/Contents/MacOS/Electron`) }) {+ t.Fatalf("not asked by the bundle's executable: %q", pats)+ }++ // reopened since: nothing to offer+ up = 0+ if a.AppBehind() != nil {+ t.Fatal("offered a Restart for WorkBuddy started after the change")+ }+ // not running: nothing to offer+ up, alive = time.Hour, false+ if a.AppBehind() != nil {+ t.Fatal("offered a Restart for WorkBuddy not running")+ }+ alive = true++ var did []string+ appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); alive = false; return nil }+ appOpen = func(_ context.Context, b string) error { did = append(did, "open "+b); alive, up = true, 0; return nil }+ if err := a.RestartApp(context.Background()); err != nil {+ t.Fatal(err)+ }+ if want := []string{"quit " + bundle, "open " + bundle}; !slices.Equal(did, want) {+ t.Fatalf("did %q, want %q", did, want)+ }+ if a.AppBehind() != nil {+ t.Fatal("still offered after the restart")+ }+ // a second Restart, from a page that hadn't caught up: nothing is quit+ did = nil+ if err := a.RestartApp(context.Background()); err == nil || len(did) > 0 {+ t.Fatalf("restarted an app on the current settings: %v, %q", err, did)+ }++ // an app that doesn't end (it asks something): said, never opened again+ up = time.Hour+ appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); return nil }+ appQuitWait = 50 * time.Millisecond+ err := a.RestartApp(context.Background())+ if err == nil || err.Error() != noticeRestartStillOpen.say("agent", "WorkBuddy") {+ t.Fatalf("err %v", err)+ }+ if want := []string{"quit " + bundle}; !slices.Equal(did, want) {+ t.Fatalf("did %q, want %q", did, want)+ }+}++// WorkBuddy on Windows: its main process is the one whose parent isn't+// WorkBuddy's, its windows are asked to close, and when it stays in the+// tray it is ended with its tree before it is opened again.+func TestWorkBuddyRestartOnWindows(t *testing.T) {+ home := restartSandbox(t)+ restartOnWindows = true+ appCloseWait, appBackWait = 50*time.Millisecond, time.Second+ const exe = `C:\Program Files\WorkBuddy\WorkBuddy.exe`+ start := time.Now().Add(-time.Hour)+ alive := true+ winProcs = func(name string) []winProc {+ if !alive || !strings.EqualFold(name, "WorkBuddy.exe") {+ return nil+ }+ return []winProc{+ {pid: 11, parent: 10, image: exe, start: start.Add(time.Second)},+ {pid: 10, parent: 4, image: exe, start: start},+ {pid: 12, parent: 10, image: exe, start: start.Add(2 * time.Second)},+ // the international build, never WorkBuddy's+ {pid: 20, parent: 4, image: `C:\Program Files\WorkBuddy AI\WorkBuddy.exe`, start: start.Add(-time.Hour)},+ }+ }+ var did []string+ winClose = func(pids []int) error {+ slices.Sort(pids)+ did = append(did, "close "+strings.Trim(fmt.Sprint(pids), "[]"))+ 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 = true, time.Now()+ return nil+ }+ a := workbuddy(home)+ if err := a.Field("provider").Set("magpie"); err != nil {+ t.Fatal(err)+ }+ got := a.AppBehind()+ if got == nil || !got.Since.Equal(start) {+ t.Fatalf("behind: %+v, want since %v", got, start)+ }+ if err := a.RestartApp(context.Background()); err != nil {+ t.Fatal(err)+ }+ if want := []string{"close 10 11 12", "end 10", "open " + exe}; !slices.Equal(did, want) {+ t.Fatalf("did %q, want %q", did, want)+ }+ if a.AppBehind() != nil {+ t.Fatal("still offered after the restart")+ }+}++// 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) {+ cases := []struct {+ id, image string+ want bool+ }{+ {"claude-desktop", `C:\Users\u\AppData\Local\AnthropicClaude\app-2.9939.2\claude.exe`, true},+ {"claude-desktop", `C:\Users\u\AppData\Local\AnthropicClaude\claude.exe`, true},+ {"claude-desktop", `C:\Program Files\WindowsApps\Claude_1.0.0.0_x64__pzs8sxrjxfjjc\app\claude.exe`, true},+ {"claude-desktop", `C:\Program Files\WindowsApps\AnthropicPBC.Claude_1.0.0.0_x64__fnn82j28hfe8t\app\Claude.exe`, true},+ {"claude-desktop", `C:\Users\u\.local\bin\claude.exe`, false},+ {"claude-desktop", `C:\Users\u\AppData\Roaming\npm\node_modules\@anthropic-ai\claude-code\bin\claude.exe`, false},+ {"claude-desktop", `C:\Users\u\AppData\Local\AnthropicClaude\Update.exe`, false},+ {"workbuddy", `C:\Program Files\WorkBuddy\WorkBuddy.exe`, true},+ {"workbuddy", `C:\Program Files\WorkBuddy AI\WorkBuddy.exe`, false},+ {"workbuddy", `C:\Program Files\WorkBuddy\resources\cli\codebuddy.exe`, false},+ }+ for _, c := range cases {+ if got := restartApps[c.id].win(c.image); got != c.want {+ t.Errorf("%s %s: %v, want %v", c.id, c.image, got, c.want)+ }+ }+ if restartApps["workbuddy-ai"].win != nil {+ t.Error("WorkBuddy AI's Windows build isn't known, yet it has a matcher")+ }+ if _, ok := restartApps["codex"]; ok {+ t.Error("the Codex app has its own Restart (codex_app.go)")+ }+}++// A change no file's time shows (Claude Desktop's models, from the+// gateway's catalog) is put at when it is first seen, not at the files'+// last write: a Desktop started between the two still read the old list.+func TestChangedAtWithoutAWrite(t *testing.T) {+ restartSandbox(t)+ f := filepath.Join(t.TempDir(), "config.json")+ os.WriteFile(f, []byte("{}"), 0o600)+ old := time.Now().Add(-2 * time.Hour)+ os.Chtimes(f, old, old)+ a := &Agent{ID: "changed-at-test"}+ list := "a"+ reads := func() string { return list }+ if got := a.changedAt([]string{f}, reads); !got.Equal(old) {+ t.Fatalf("first seen: %v, want the file's %v", got, old)+ }+ if got := a.changedAt([]string{f}, reads); !got.Equal(old) {+ t.Fatalf("again: %v, want %v", got, old)+ }+ list = "a b"+ before := time.Now()+ got := a.changedAt([]string{f}, reads)+ if got.Before(before) {+ t.Fatalf("changed with no write: %v, want now (after %v)", got, before)+ }+ if again := a.changedAt([]string{f}, reads); !again.Equal(got) {+ t.Fatalf("moved on a second read: %v, then %v", got, again)+ }+ // a change with a write is at the write, as before+ list = "a b c"+ later := time.Now().Add(time.Hour)+ os.Chtimes(f, later, later)+ if got := a.changedAt([]string{f}, reads); !got.Equal(later) {+ t.Fatalf("with a write: %v, want %v", got, later)+ }+}diff --git a/internal/agent/apprestart_windows.go b/internal/agent/apprestart_windows.gonew file mode 100644index 000000000..93f9c71ab--- /dev/null+++ b/internal/agent/apprestart_windows.go@@ -0,0 +1,127 @@+//go:build windows++package agent++import (+ "errors"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"++ "github.com/yetone/magpie/internal/proc"+)++var procGetApplicationUserModelID = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetApplicationUserModelId")++// listWinProcs lists the processes named exe, case aside, from a Toolhelp+// snapshot: no child process, no WMI. One whose image can't be read+// (another user's) is left out. Nothing in a test binary testenv isolated.+func listWinProcs(exe string) []winProc {+ if proc.Isolated() || exe == "" {+ return nil+ }+ snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)+ if err != nil {+ return nil+ }+ defer windows.CloseHandle(snap)+ var out []winProc+ e := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))}+ for err = windows.Process32First(snap, &e); err == nil; err = windows.Process32Next(snap, &e) {+ if e.ProcessID == 0 || !strings.EqualFold(windows.UTF16ToString(e.ExeFile[:]), exe) {+ continue+ }+ if p, ok := readWinProc(e.ProcessID); ok {+ p.parent = int(e.ParentProcessID)+ out = append(out, p)+ }+ }+ return out+}++func readWinProc(pid uint32) (winProc, bool) {+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)+ if err != nil {+ return winProc{}, false+ }+ defer windows.CloseHandle(h)+ buf := make([]uint16, windows.MAX_LONG_PATH)+ n := uint32(len(buf))+ if err := windows.QueryFullProcessImageName(h, 0, &buf[0], &n); err != nil {+ return winProc{}, false+ }+ p := winProc{pid: int(pid), image: windows.UTF16ToString(buf[:n])}+ var created, exited, kernel, user windows.Filetime+ if windows.GetProcessTimes(h, &created, &exited, &kernel, &user) == nil {+ p.start = time.Unix(0, created.Nanoseconds())+ }+ if procGetApplicationUserModelID.Find() == nil {+ id := make([]uint16, 256)+ l := uint32(len(id))+ if r, _, _ := procGetApplicationUserModelID.Call(uintptr(h), uintptr(unsafe.Pointer(&l)), uintptr(unsafe.Pointer(&id[0]))); r == 0 {+ p.aumid = windows.UTF16ToString(id)+ }+ }+ return p, true+}++// closeWinProcs asks the processes to close, as their windows' close does+// (taskkill without /F posts WM_CLOSE); one with no window ignores it.+func closeWinProcs(pids []int) error {+ if len(pids) == 0 {+ return nil+ }+ args := make([]string, 0, 2*len(pids))+ for _, pid := range pids {+ args = append(args, "/PID", strconv.Itoa(pid))+ }+ return proc.Command("taskkill", args...).Run()+}++// 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()+ return cmdErr(out, err)+}++// launchWin opens the app main was again: a packaged app by its+// AppUserModelID through the shell, as its Start menu tile does; Squirrel's+// Claude through the claude.exe stub beside its app-<version> folders, which+// starts the newest; anything else by its image.+func launchWin(main winProc) error {+ if main.aumid != "" {+ return shellOpen("explorer.exe", `shell:AppsFolder\`+main.aumid)+ }+ exe := main.image+ if dir := filepath.Dir(exe); strings.HasPrefix(strings.ToLower(filepath.Base(dir)), "app-") {+ if stub := filepath.Join(filepath.Dir(dir), filepath.Base(exe)); isFile(stub) {+ exe = stub+ }+ }+ if _, err := os.Stat(exe); err != nil {+ return err+ }+ return shellOpen(exe, "")+}++func shellOpen(file, args string) error {+ f, err := windows.UTF16PtrFromString(file)+ if err != nil {+ return err+ }+ var a *uint16+ if args != "" {+ if a, err = windows.UTF16PtrFromString(args); err != nil {+ return err+ }+ }+ if err := windows.ShellExecute(0, nil, f, a, nil, windows.SW_SHOWNORMAL); err != nil {+ return errors.New("couldn't open " + file + ": " + err.Error())+ }+ return nil+}diff --git a/internal/agent/connectinfo.go b/internal/agent/connectinfo.goindex e8f40f498..e44866127 100644--- a/internal/agent/connectinfo.go+++ b/internal/agent/connectinfo.go@@ -151,8 +151,9 @@ var running = listRunning// changedAt is when magpie last changed what the agent reads at start. It// is kept in the stash with a digest of what that was, so neither the// agent's own writes to the same files nor magpie starting again move it;-// a change first seen is put at the files' latest write. Zero when the-// files aren't there.+// a change first seen is put at the files' latest write, or at now when+// no file was written since the last one. Zero when the files aren't+// there.func (a *Agent) changedAt(files []string, reads func() string) time.Time {var mod time.Timefor _, f := range files {@@ -166,10 +167,15 @@ func (a *Agent) changedAt(files []string, reads func() string) time.Time {sum := sha256.Sum256([]byte(reads()))digest := hex.EncodeToString(sum[:8])key := a.ID + ".started"- if was, at, ok := strings.Cut(stashLoad()[key], " "); ok && was == digest {- if n, err := strconv.ParseInt(at, 10, 64); err == nil {- return time.Unix(0, n)- }+ was, at, ok := strings.Cut(stashLoad()[key], " ")+ n, err := strconv.ParseInt(at, 10, 64)+ if ok && err == nil && was == digest {+ return time.Unix(0, n)+ }+ // a change no file's time shows (Claude Desktop's models are the+ // gateway's, not a file's) is put at when it is first seen+ if ok && err == nil && !mod.After(time.Unix(0, n)) {+ mod = time.Now()}stash(map[string]string{key: digest + " " + strconv.FormatInt(mod.UnixNano(), 10)})return moddiff --git a/internal/agent/main_test.go b/internal/agent/main_test.goindex ba95273a7..f3a85851c 100644--- a/internal/agent/main_test.go+++ b/internal/agent/main_test.go@@ -1,6 +1,7 @@package agentimport (+ "context""encoding/json""errors""os"@@ -41,6 +42,15 @@ func TestMain(m *testing.M) {// nor where this Mac's Spotlight has an app (DeepSeek Harness.app// outside /Applications, #2325)spotlightApps = func(string) []string { return nil }+ // a desktop app's Restart never quits or opens one of this machine's+ // (the Codex app, Claude Desktop, WorkBuddy the developer runs); the+ // restart tests stand in for each step+ appQuit = func(context.Context, string) error { return errors.New("no app is quit in a test") }+ appOpen = func(context.Context, string) error { return errors.New("no app is opened in a test") }+ winProcs = func(string) []winProc { return nil }+ winClose = func([]int) error { return errors.New("no app is closed in a test") }+ winEnd = func(int) error { return errors.New("no app is ended in a test") }+ winLaunch = func(winProc) error { return errors.New("no app is opened in a test") }// Aside's default is changed through the aside binary, which answers for// the account the developer is actually running: a test that picks a// model would change the real Aside's default, and the running one woulddiff --git a/internal/agent/workbuddy.go b/internal/agent/workbuddy.goindex 16ae90602..8132f616e 100644--- a/internal/agent/workbuddy.go+++ b/internal/agent/workbuddy.go@@ -13,8 +13,10 @@ package agent// "reasoning":{"supportedEfforts":[…],"canDisableThinking":…,"defaultEffort":…}}]//// WorkBuddy shows them in its picker as "custom-local:<id>", and asks url-// for model <id>, with reasoning_effort, under Bearer apiKey. It watches the-// file and picks a change up without a restart. The model is picked per+// for model <id>, with reasoning_effort, under Bearer apiKey. 5.6's+// app.asar watches the file only when it was there at start, and the watch+// is on the file itself, so a rewrite can go unseen until a restart; the+// Agents row offers one (apprestart.go). The model is picked per// task in WorkBuddy's window, not in a file, so what magpie sets is whether// its models are in that picker. Its requests say "CLI/<ver> WorkBuddy/<ver>",// so they are told apart by their key.@@ -46,16 +48,22 @@ func workbuddy(home string) *Agent {if dir == "" {dir = filepath.Join(home, ".workbuddy")}- return workbuddyBuild("workbuddy", "WorkBuddy", dir, []string{"work-buddy"}, desktopApp{id: "com.tencent.workbuddy.mac", names: []string{"WorkBuddy.app"}})+ return workbuddyBuild("workbuddy", "WorkBuddy", dir, []string{"work-buddy"}, workbuddyApp)}// workbuddyAI is WorkBuddy AI, the international build, in ~/.workbuddy-ai.// WORKBUDDY_CONFIG_DIR is WorkBuddy's (workbuddy above): both builds would// read a folder it names, which that agent writes already.func workbuddyAI(home string) *Agent {- return workbuddyBuild("workbuddy-ai", "WorkBuddy AI", filepath.Join(home, ".workbuddy-ai"), []string{"workbuddy-intl", "workbuddyai"}, desktopApp{id: "com.workbuddy.workbuddy-ai", names: []string{"WorkBuddy AI.app"}})+ return workbuddyBuild("workbuddy-ai", "WorkBuddy AI", filepath.Join(home, ".workbuddy-ai"), []string{"workbuddy-intl", "workbuddyai"}, workbuddyAIApp)}+// workbuddyApp and workbuddyAIApp are the two builds' bundles.+var (+ workbuddyApp = desktopApp{id: "com.tencent.workbuddy.mac", names: []string{"WorkBuddy.app"}}+ workbuddyAIApp = desktopApp{id: "com.workbuddy.workbuddy-ai", names: []string{"WorkBuddy AI.app"}}+)+// workbuddyOnMac says whether WorkBuddy is found by its app bundle, as on a// Mac; a var so a test forces either OS.var workbuddyOnMac = func() bool { return runtime.GOOS == "darwin" }diff --git a/internal/gui/api.go b/internal/gui/api.goindex b01c57525..684102a2b 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -214,6 +214,10 @@ type agentJSON struct {// StaleCopies: those copies, each with what it is and when it// started, for the opened row to say which is left to reopen and howStaleCopies []agent.StaleCopy `json:"staleCopies,omitempty"`+ // AppRestart: its desktop app (Claude Desktop, WorkBuddy) running on+ // what it read before magpie's last change, for the row's Restart+ // (agent.AppBehind)+ AppRestart *agent.AppRun `json:"appRestart,omitempty"`// Joined: connected with its own models still in its list (Codex// signed in with ChatGPT, agent.Agent.Join)Joined bool `json:"joined,omitempty"`@@ -982,6 +986,22 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {}writeJSON(rw, c)})+ // quits the agent's desktop app and opens it again, so it reads what+ // magpie wrote: the row's Restart, after the user said yes to it+ mux.HandleFunc("POST /api/agents/restart/{id}", func(rw http.ResponseWriter, r *http.Request) {+ a, err := agent.Find(r.PathValue("id"))+ if err != nil {+ fail(rw, err)+ return+ }+ ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)+ defer cancel()+ if err := a.RestartApp(ctx); err != nil {+ fail(rw, err)+ return+ }+ writeJSON(rw, state())+ })// what disconnecting an agent changes in its files, line by line, for// the dialog asking it (agent.DisconnectPreview); its files when the// preview can't be had@@ -2395,6 +2415,7 @@ func state() stateJSON {aj.Source = a.Source()aj.Failover = a.FailingOver != nil && a.FailingOver()}+ aj.AppRestart = a.AppBehind()if a.Import != nil {aj.Import = a.Import()if a.Added != nil {diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex 00882760a..3fc7d4754 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -634,6 +634,11 @@ body.panel #agents > .row .ag-handle::before { left: -8px; }.ag-fix:active { transform: scale(.96); }.ag-fix:focus-visible { outline: 1.5px solid var(--drift); outline-offset: 1px; }.ag-fix.busy { pointer-events: none; opacity: .7; }+/* a desktop app to restart for magpie's change (agent.AppBehind): the+ row's waiting colour, not a fault's */+.ag-fix.ag-restart { background: color-mix(in srgb, var(--amber) 13%, transparent); color: var(--amber); }+.ag-fix.ag-restart:hover { background: color-mix(in srgb, var(--amber) 22%, transparent); }+.ag-fix.ag-restart:focus-visible { outline-color: var(--amber); }/* the accounts that keep an agent going through magpie for failover (#1385) */.ag-acc { display: inline-flex; align-items: center; flex: none; height: 20px; padding: 0 8px; border: 1px solid var(--line); border-radius: 999px; background: var(--card); color: var(--fg-2); font: inherit; font-size: 11.5px; line-height: 1; cursor: pointer; transition: background-color .15s, color .15s; }.ag-acc:hover { background: var(--pill); color: var(--fg); }@@ -708,6 +713,9 @@ body.panel .ag-fix { position: absolute; left: 20px; top: calc(50% + 1px); widthbody.panel .ag-fix:hover { background: var(--drift); filter: brightness(1.08); }body.panel .ag-fix svg { width: 9px; height: 9px; }body.panel .ag-fix span { display: none; }+/* the panel's Restart stays on its line, its word left to the hover */+body.panel .ag-fix.ag-restart { position: static; width: auto; height: 18px; padding: 0 5px; background: color-mix(in srgb, var(--amber) 13%, transparent); color: var(--amber); box-shadow: none; }+body.panel .ag-fix.ag-restart:hover { filter: none; background: color-mix(in srgb, var(--amber) 22%, transparent); }.row.drifted .field[data-key="model"] { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--drift) 38%, transparent); }/* the line over each kind of folded agent: hidden by hand, or nothing set */diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex af679dc5b..8b2b17a0b 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -67,7 +67,6 @@ let showAllAgents = false; // the agents no one has set anything on, folded awaylet showHiddenAgents = false; // under them, the ones hidden by hand: a fold of their own, shut until askedlet period = "today"; // usage windowlet usage = null; // last usage summary-let usageHidOpen = false; // the Usage page's hidden agents shown under their linelet pick = null; // { agent, field, options, items, cursor, anchor }let editing = null; // provider id being edited; { preset } or { custom: true } for a new onelet draft = null; // the editor's working copy@@ -610,6 +609,8 @@ function renderAgents() {row.classList.add("drifted");if (!kind) who.append(driftFix(a));}+ // an app started before magpie's last change (the panel's row)+ else if (!kind && a.appRestart) who.append(appRestart(a));// the CLI's version, and an update when one is out (#202); the panel's// name column has no room for itif (mode !== "panel") who.append(cliTag(a));@@ -1330,6 +1331,7 @@ function connectLine(a, kind) {else if (src === "key") say(t("Not connected · now on an API key of its own"));else if (src.startsWith("providers:")) say(t("Not connected · now has {n} providers of its own", { n: src.slice(10) }));else say(t("Not connected · {agent} uses its own settings", { agent: a.name }));+ if (a.appRestart) line.append(appRestart(a));return line;}if (a.native) {@@ -1343,6 +1345,11 @@ function connectLine(a, kind) {return line;}line.classList.add("on");+ if (a.appRestart) {+ say(t("Connected · restart {agent} to use it", { agent: a.name }), "wait");+ line.append(appRestart(a));+ return line;+ }if (staleNow(a)) {if (a.id === "claude") say(t("Connected · new sessions take it"));else {@@ -1831,13 +1838,17 @@ function daemonRestart() {return go;}+// asked first: what runs in the app stops+const confirmRestart = (name) => confirmAction(t("Restart {agent}?", { agent: name }), t("magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.", { agent: name }), t("Restart"));+// appReopen is the Restart beside the Codex app left on the old list: magpie-// quits it, as ⌘Q does, and opens it again+// asks, then quits it, as ⌘Q does, and opens it againfunction appReopen(bundle) {const go = el("button", "ag-quiet accent", t("Restart"));go.type = "button";go.title = bundle;go.onclick = async () => {+ if (!(await confirmRestart(t("The Codex app")))) return;go.disabled = true;go.classList.add("busy");try {@@ -1854,6 +1865,31 @@ function appReopen(bundle) {return go;}+// appRestart: a desktop app running on what it read before magpie's last+// change (agent.AppBehind) is quit and opened again+function appRestart(a) {+ const go = el("button", "ag-fix ag-restart");+ go.type = "button";+ go.title = t("{agent} started {when}, before magpie's last change, and reads it only as it starts", { agent: a.name, when: ago(a.appRestart.since) });+ go.setAttribute("aria-label", t("Restart {agent}", { agent: a.name }));+ go.append(svg(REAPPLY, 11, 1.8), el("span", "", t("Restart")));+ go.onclick = async (e) => {+ e.stopPropagation();+ if (!(await confirmRestart(a.name))) return;+ go.disabled = true;+ go.classList.add("busy");+ try {+ state = await api("agents/restart/" + a.id, {});+ renderAgents();+ status(t("{agent} restarted", { agent: a.name }));+ } catch (err) {+ if (go.isConnected) { go.disabled = false; go.classList.remove("busy"); }+ status(tNotice(err.message), "err");+ }+ };+ return go;+}+// connectPanel: a connected agent's row, openedfunction connectPanel(a, { fields, fieldBtn }) {const box = el("div", "ag-exp");@@ -7207,51 +7243,6 @@ function archiveBodyPanel(label, part, id, key = id) {return callBodyPanel(label, part.body, cut, id, key);}-// A call the archive kept, by "<date>/<id>": read back when asked, and its-// file downloaded, drawn again by redraw as it is read — under a request's-// row on the Usage page (the Gateway page's recent calls show their own-// bodies, and no longer the archive's copy as well).-function archivePanel(name, id, redraw) {- const box = el("section", "call-archive");- const [date, aid] = name.split("/");- const got = archivedCalls.get(name);- const head = el("div", "call-body-head");- head.append(el("span", "call-body-label", t("Request archive")), el("code", "call-archive-id", name), el("span", "grow"));- box.append(head);- const dl = el("button", "text call-archive-dl", t("Download"));- dl.onclick = (ev) => { ev.stopPropagation(); downloadArchive(name, dl); };- if (!got || got.busy || got.error) {- const b = el("button", "text", t(got?.busy ? "Fetching…" : "Fetch from archive"));- b.disabled = !!got?.busy;- b.onclick = (ev) => {- ev.stopPropagation();- archivedCalls.set(name, { busy: true });- redraw();- api(`archive?date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`)- .then((a) => archivedCalls.set(name, a))- .catch((e) => archivedCalls.set(name, { error: t(e.message) }))- .finally(redraw);- };- head.append(b);- if (got?.error) box.append(el("div", "call-archive-err", got.error));- else head.append(dl); // one not in the bucket has nothing to download- return box;- }- head.append(el("span", "call-body-truncated call-archive-note", t("Secrets taken out")), dl);- if (got.large) {- box.append(el("p", "call-archive-big", t("This archive is {size}, too large to show here. Download it to read it.", { size: got.bytes > 0 ? fmtBytes(got.bytes) : t("very large") })));- return box;- }- const grid = el("div", "call-details");- grid.append(- headersPanel(t("Request Headers"), `${got.request.method || ""} ${got.request.path || ""}`.trim(), got.request.headers),- headersPanel(t("Response Headers"), got.response.status ? `HTTP ${got.response.status}` : "", got.response.headers),- archiveBodyPanel("Request Body", got.request, undefined, id + "|archive|req"),- archiveBodyPanel("Response Body", got.response, id + "|archive"),- );- box.append(grid);- return box;-}// An agent's model field, and whether any of its options come from provider p.function modelField(a) {@@ -22092,7 +22083,6 @@ let maskSum = null; // the summary Insights › Masking read last: itsconst maskValues = new Map(); // placeholder → what it stood for, as this magpie told itconst maskKindName = (k) => MASK_KINDS[k] ? t(MASK_KINDS[k]) : k;const maskByName = (b) => MASK_BY[b] ? t(MASK_BY[b]) : b;-const stillMotion = calm;// a kind's colour is its place in the summary's ranking, so the bar, the// legend, the chips and the records say a kind in one colourfunction maskColor(k) {@@ -22106,13 +22096,6 @@ function maskShape(head, len) {const rest = Math.max(1, Math.min((len || 0) - [...head].length, 8));return head + "•".repeat(rest);}-// the providers' names, read once when Settings opened before any page-// that loads them-let maskProv = null, maskProvAsked = false;-function maskWho(id, kind) {- const x = kind === "agent" ? state.agents?.find((a) => a.id === id) : (providers || maskProv)?.providers?.find((p) => p.id === id);- return { name: x?.name || id || t("Unknown"), icon: x?.icon };-}function maskDot(k) {const d = el("span", "mo-dotc");d.style.background = maskColor(k);diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 53907b7ed..4b4313cbf 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1804,6 +1804,19 @@ const I18N = {"Restart": "重启","Codex's background service restarted": "Codex 的后台服务已重启","The Codex app reopened": "Codex 应用已重新打开",+ "Restart {agent}?": "重启 {agent}?",+ "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie 会退出 {agent} 并重新打开,让它读取新设置。其中正在运行的任务会停止。",+ "The Codex app": "Codex 应用",+ "{agent} started {when}, before magpie's last change, and reads it only as it starts": "{agent} {when}启动,早于 magpie 的最近一次更改;它只在启动时读取设置",+ "Restart {agent}": "重启 {agent}",+ "{agent} restarted": "{agent} 已重启",+ "Connected · restart {agent} to use it": "已连接 · 重启 {agent} 后生效",+ "magpie doesn't restart {agent} on this computer.": "magpie 无法在这台电脑上重启 {agent}。",+ "{agent} isn't running on the old settings any more.": "{agent} 已不在使用旧设置运行。",+ "magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.": "magpie 无法让 {agent} 退出。请自行退出,然后重新打开。",+ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.": "{agent} 仍然开着,可能在窗口里等你回答。请在那里回答,或退出它,然后重新打开。",+ "{agent} is still running. Quit it, then open it again.": "{agent} 仍在运行。请退出它,然后重新打开。",+ "{agent} quit, but didn't open again. Open it yourself.": "{agent} 已退出,但没有重新打开。请自行打开。","{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登录信息,读自其自身文件;在那里退出登录,此供应商随之消失。","Models": "模型","Endpoints": "端点",@@ -5734,6 +5747,19 @@ const I18N = {"Restart": "重啟","Codex's background service restarted": "Codex 的後臺服務已重啟","The Codex app reopened": "Codex 應用已重新打開",+ "Restart {agent}?": "重新啟動 {agent}?",+ "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie 會結束 {agent} 並重新打開,讓它讀取新設定。其中正在執行的工作會停止。",+ "The Codex app": "Codex 應用",+ "{agent} started {when}, before magpie's last change, and reads it only as it starts": "{agent} {when}啟動,早於 magpie 的最近一次變更;它只在啟動時讀取設定",+ "Restart {agent}": "重新啟動 {agent}",+ "{agent} restarted": "{agent} 已重新啟動",+ "Connected · restart {agent} to use it": "已連接 · 重新啟動 {agent} 後生效",+ "magpie doesn't restart {agent} on this computer.": "magpie 無法在這台電腦上重新啟動 {agent}。",+ "{agent} isn't running on the old settings any more.": "{agent} 已不在使用舊設定執行。",+ "magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.": "magpie 無法讓 {agent} 結束。請自行結束,然後重新打開。",+ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.": "{agent} 仍然開著,可能在視窗裡等你回答。請在那裡回答,或結束它,然後重新打開。",+ "{agent} is still running. Quit it, then open it again.": "{agent} 仍在執行。請結束它,然後重新打開。",+ "{agent} quit, but didn't open again. Open it yourself.": "{agent} 已結束,但沒有重新打開。請自行打開。","{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登入資訊,讀自其自身檔案;在那裡退出登入,此供應商隨之消失。","Models": "模型","Endpoints": "端點",@@ -9641,6 +9667,19 @@ const I18N = {"Restart": "再起動","Codex's background service restarted": "Codex のバックグラウンドサービスを再起動しました","The Codex app reopened": "Codex アプリを開き直しました",+ "Restart {agent}?": "{agent} を再起動しますか?",+ "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie は {agent} を終了してから開き直し、新しい設定を読み込ませます。その中で実行中の作業は止まります。",+ "The Codex app": "Codex アプリ",+ "{agent} started {when}, before magpie's last change, and reads it only as it starts": "{agent} は{when}に起動しており、magpie の最後の変更より前です。設定は起動時にのみ読み込まれます",+ "Restart {agent}": "{agent} を再起動",+ "{agent} restarted": "{agent} を再起動しました",+ "Connected · restart {agent} to use it": "接続済み · {agent} を再起動すると反映されます",+ "magpie doesn't restart {agent} on this computer.": "このコンピュータでは magpie は {agent} を再起動できません。",+ "{agent} isn't running on the old settings any more.": "{agent} はもう古い設定で動いていません。",+ "magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.": "magpie は {agent} に終了を求められませんでした。自分で終了してから開き直してください。",+ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.": "{agent} はまだ開いています。ウインドウで何か尋ねているかもしれません。そこで答えるか終了してから、開き直してください。",+ "{agent} is still running. Quit it, then open it again.": "{agent} はまだ動いています。終了してから開き直してください。",+ "{agent} quit, but didn't open again. Open it yourself.": "{agent} は終了しましたが、開き直せませんでした。自分で開いてください。","{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} のサインイン(そのファイルから読み込み)。そちらでサインアウトするとこのプロバイダは消えます。","Models": "モデル","Endpoints": "エンドポイント",@@ -13578,6 +13617,19 @@ const I18N = {"Restart": "Neu starten","Codex's background service restarted": "Hintergrunddienst von Codex neu gestartet","The Codex app reopened": "Codex-App neu geöffnet",+ "Restart {agent}?": "{agent} neu starten?",+ "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie beendet {agent} und öffnet es erneut, damit es die neuen Einstellungen liest. Was darin gerade läuft, wird angehalten.",+ "The Codex app": "Die Codex-App",+ "{agent} started {when}, before magpie's last change, and reads it only as it starts": "{agent} wurde {when} gestartet, vor der letzten Änderung von magpie, und liest sie nur beim Start",+ "Restart {agent}": "{agent} neu starten",+ "{agent} restarted": "{agent} neu gestartet",+ "Connected · restart {agent} to use it": "Verbunden · {agent} neu starten, um es zu nutzen",+ "magpie doesn't restart {agent} on this computer.": "magpie kann {agent} auf diesem Computer nicht neu starten.",+ "{agent} isn't running on the old settings any more.": "{agent} läuft nicht mehr mit den alten Einstellungen.",+ "magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.": "magpie konnte {agent} nicht zum Beenden auffordern. Beenden Sie es selbst und öffnen Sie es dann erneut.",+ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.": "{agent} ist noch geöffnet; es fragt vielleicht etwas in seinem Fenster. Antworten Sie dort oder beenden Sie es, und öffnen Sie es dann erneut.",+ "{agent} is still running. Quit it, then open it again.": "{agent} läuft noch. Beenden Sie es und öffnen Sie es dann erneut.",+ "{agent} quit, but didn't open again. Open it yourself.": "{agent} wurde beendet, aber nicht erneut geöffnet. Öffnen Sie es selbst.","{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "Die Anmeldung von {agent}, aus dessen eigenen Dateien gelesen. Melden Sie sich dort ab, verschwindet dieser Anbieter.","Models": "Modelle","Endpoints": "Endpunkte",@@ -15825,6 +15877,12 @@ const NOTICES = ["{file} sets {var}, so Claude Code sends its requests to {cloud}, not to magpie: take it out there to go through magpie.","{var} is set in your shell's environment, so Claude Code started there sends its requests to {cloud}, not to magpie: take it out of your shell's profile to go through magpie.","~/.dsh/settings.yaml sets its own DeepSeek endpoint or key, which dsh puts over magpie's; clear it in dsh's Models page to go through magpie.",+ "magpie doesn't restart {agent} on this computer.",+ "{agent} isn't running on the old settings any more.",+ "magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.",+ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.",+ "{agent} is still running. Quit it, then open it again.",+ "{agent} quit, but didn't open again. Open it yourself.",];// The active language: a ?locale= URL parameter wins, then the saveddiff --git a/internal/gui/assets/plugins/redact/page.js b/internal/gui/assets/plugins/redact/page.jsindex 7870b26c4..7bc4ae131 100644--- a/internal/gui/assets/plugins/redact/page.js+++ b/internal/gui/assets/plugins/redact/page.js@@ -1,10 +1,18 @@// Insights › Masking's code (client.js has its markup and hooks): run after-// app.js, whose masking helpers it shares (maskWho, maskTip, maskColor,+// app.js, whose masking helpers it shares (maskTip, maskColor,// maskShape, maskValue: Settings' Try it and the masked calls' badges use// them too). What a placeholder stood for is in this magpie's memory alone,// never on disk, so after a restart it is gone; so is the text a request// went out with (/api/masking/sent), kept for the newest requests only.+const stillMotion = calm;+// the providers' names, read once when the page opened before any page+// that loads them+let maskProv = null, maskProvAsked = false;+function maskWho(id, kind) {+ const x = kind === "agent" ? state.agents?.find((a) => a.id === id) : (providers || maskProv)?.providers?.find((p) => p.id === id);+ return { name: x?.name || id || t("Unknown"), icon: x?.icon };+}// what a request was, beside a chat (gateway's noteMasked)const MASK_WHAT = { search: "Web search", image: "Image", video: "Video", decide: "System One", embeddings: "Embeddings", audio: "Audio" };// maskDayName: Today, Yesterday or the date a masked request went ondiff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.jsindex 0903f340d..28ee2a875 100644--- a/internal/gui/assets/plugins/usage/page.js+++ b/internal/gui/assets/plugins/usage/page.js@@ -1,6 +1,54 @@// The Usage page's code (client.js has its markup and hooks): run after// app.js, whose helpers and state it shares, and before start.js shows the// first page.+let usageHidOpen = false; // the hidden agents shown under their line+// A call the archive kept, by "<date>/<id>": read back when asked, and its+// file downloaded, drawn again by redraw as it is read — under a request's+// row on the Usage page, and under a Routing trace's (plugins/routing draws+// it once this file has loaded; the Gateway page's recent calls show their+// own bodies, and no longer the archive's copy as well).+function archivePanel(name, id, redraw) {+ const box = el("section", "call-archive");+ const [date, aid] = name.split("/");+ const got = archivedCalls.get(name);+ const head = el("div", "call-body-head");+ head.append(el("span", "call-body-label", t("Request archive")), el("code", "call-archive-id", name), el("span", "grow"));+ box.append(head);+ const dl = el("button", "text call-archive-dl", t("Download"));+ dl.onclick = (ev) => { ev.stopPropagation(); downloadArchive(name, dl); };+ if (!got || got.busy || got.error) {+ const b = el("button", "text", t(got?.busy ? "Fetching…" : "Fetch from archive"));+ b.disabled = !!got?.busy;+ b.onclick = (ev) => {+ ev.stopPropagation();+ archivedCalls.set(name, { busy: true });+ redraw();+ api(`archive?date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`)+ .then((a) => archivedCalls.set(name, a))+ .catch((e) => archivedCalls.set(name, { error: t(e.message) }))+ .finally(redraw);+ };+ head.append(b);+ if (got?.error) box.append(el("div", "call-archive-err", got.error));+ else head.append(dl); // one not in the bucket has nothing to download+ return box;+ }+ head.append(el("span", "call-body-truncated call-archive-note", t("Secrets taken out")), dl);+ if (got.large) {+ box.append(el("p", "call-archive-big", t("This archive is {size}, too large to show here. Download it to read it.", { size: got.bytes > 0 ? fmtBytes(got.bytes) : t("very large") })));+ return box;+ }+ const grid = el("div", "call-details");+ grid.append(+ headersPanel(t("Request Headers"), `${got.request.method || ""} ${got.request.path || ""}`.trim(), got.request.headers),+ headersPanel(t("Response Headers"), got.response.status ? `HTTP ${got.response.status}` : "", got.response.headers),+ archiveBodyPanel("Request Body", got.request, undefined, id + "|archive|req"),+ archiveBodyPanel("Response Body", got.response, id + "|archive"),+ );+ box.append(grid);+ return box;+}+const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]];// The reader's time zone, which magpie reads the period's days, the chart'sdiff --git a/internal/gui/tests/agent-app-restart.test.cjs b/internal/gui/tests/agent-app-restart.test.cjsnew file mode 100644index 000000000..86c1db5a4--- /dev/null+++ b/internal/gui/tests/agent-app-restart.test.cjs@@ -0,0 +1,139 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// 微雨南山 and stones on Discord: WorkBuddy, Claude Desktop and the Codex app+// read magpie's settings only as they start. A row whose app started before+// magpie's last change has a Restart; it asks in magpie's own dialog, and+// only then quits the app and opens it again. Cancel quits nothing. Every+// language, both engines, the window wide and narrow and the tray panel. No+// backend, the API is faked here.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const days = (n) => new Date(Date.now() - n * 86400e3).toISOString();+const model = (value) => [{ key: "model", label: "model", value, options: [{ value: "deepseek-v4", label: "DeepSeek V4", ref: "deepseek/deepseek-v4", note: "DeepSeek · via magpie" }] }];+const workbuddy = { id: "workbuddy", name: "WorkBuddy", icon: "generic", path: "/fixture/models.json", wired: true, fields: model("deepseek-v4"), appRestart: { since: days(1) } };+// disconnected in magpie, the app still runs on magpie's settings+const claude = { id: "claude-desktop", name: "Claude Desktop", icon: "generic", path: "/fixture/claude", wired: false, fields: model(""), appRestart: { since: days(1) } };++const words = {+ en: { restart: "Restart", cancel: "Cancel", line: "Connected · restart WorkBuddy to use it", done: "WorkBuddy restarted", still: "WorkBuddy is still open; it may be asking something in its window." },+ zh: { restart: "重启", cancel: "取消", line: "已连接 · 重启 WorkBuddy 后生效", done: "WorkBuddy 已重启", still: "WorkBuddy" },+ "zh-TW": { restart: "重啟", cancel: "取消", line: "已連接 · 重新啟動 WorkBuddy 後生效", done: "WorkBuddy 已重新啟動", still: "WorkBuddy" },+ ja: { restart: "再起動", cancel: "キャンセル", line: "接続済み · WorkBuddy を再起動すると反映されます", done: "WorkBuddy を再起動しました", still: "WorkBuddy" },+ de: { restart: "Neu starten", cancel: "Abbrechen", line: "Verbunden · WorkBuddy neu starten, um es zu nutzen", done: "WorkBuddy neu gestartet", still: "WorkBuddy" },+};+const stillOpen = "WorkBuddy is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.";++function serve(lang, calls, fail) {+ let agents = [workbuddy, claude];+ return async (route) => {+ const url = new URL(route.request().url());+ const json = (data, status = 200) => route.fulfill({ status, json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ const st = () => ({ agents, profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname.startsWith("/api/agents/restart/")) {+ const id = url.pathname.split("/").pop();+ calls.push(route.request().method() + " " + id);+ if (fail) return json({ error: stillOpen }, 409);+ agents = agents.map((a) => (a.id === id ? { ...a, appRestart: undefined } : a));+ return json(st());+ }+ if (url.pathname === "/api/state") return json(st());+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await route.fulfill({ body: await fs.readFile(file), contentType });+ };+}++const row = (id) => `.row.agent[data-id="${id}"]`;++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of Object.keys(words)) {+ const w = words[lang];+ for (const [mode, width] of [["", 980], ["", 440], ["panel", 440]]) {+ test(`${engine} ${lang} ${mode || "window"} ${width}px: Restart asks, then restarts the app`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await browser.newPage({ viewport: { width, height: 800 } });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ const calls = [];+ await page.route("**/*", serve(lang, calls));+ await page.goto("http://magpie.test/" + (mode ? "?mode=" + mode : "?view=agents"));+ const go = page.locator(`${row("workbuddy")} .ag-restart`);+ await go.waitFor();+ assert.equal(await go.getAttribute("aria-label"), lang === "en" ? "Restart WorkBuddy" : await go.getAttribute("aria-label"));+ assert.doesNotMatch(await go.getAttribute("aria-label"), /\{\w+\}/);+ assert.doesNotMatch(await go.getAttribute("title"), /\{\w+\}/);+ assert.ok((await go.getAttribute("title")).includes("WorkBuddy"));+ if (!mode) {+ assert.equal((await go.textContent()).trim(), w.restart);+ assert.ok((await page.locator(`${row("workbuddy")} .ag-st-t`).textContent()).includes(w.line));+ }+ // not connected in magpie, Claude Desktop still runs on its settings+ await page.locator(`${row("claude-desktop")} .ag-restart`).waitFor();+ const box = await go.boundingBox();+ assert.ok(box.x >= 0 && box.x + box.width <= width, "past the window: " + JSON.stringify(box));+ const side = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert.ok(side <= 1, "scrolls sideways: " + side);++ // asked first; Cancel and Escape quit nothing+ await go.click();+ const ask = page.locator("dialog.action-confirm[open]");+ await ask.waitFor();+ assert.ok((await ask.locator("h2").textContent()).includes("WorkBuddy"));+ assert.doesNotMatch(await ask.textContent(), /\{\w+\}/);+ assert.equal((await ask.locator("button.primary").textContent()).trim(), w.restart);+ await ask.locator("button", { hasText: w.cancel }).click();+ await ask.waitFor({ state: "detached" });+ await go.click();+ await ask.waitFor();+ await page.keyboard.press("Escape");+ await ask.waitFor({ state: "detached" });+ assert.deepEqual(calls, []);++ await go.click();+ await ask.locator("button.primary").click();+ await page.locator(`${row("workbuddy")} .ag-restart`).waitFor({ state: "detached" });+ assert.deepEqual(calls, ["POST workbuddy"]);+ assert.equal(await page.locator("#status").textContent(), w.done);+ assert.equal(await page.locator(`${row("claude-desktop")} .ag-restart`).count(), 1, "only the app asked for");+ assert.deepEqual(errors, []);+ });+ }++ test(`${engine} ${lang}: a restart that fails says why, in the reader's language`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await browser.newPage({ viewport: { width: 980, height: 800 } });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ const calls = [];+ await page.route("**/*", serve(lang, calls, true));+ await page.goto("http://magpie.test/?view=agents");+ const go = page.locator(`${row("workbuddy")} .ag-restart`);+ await go.click();+ await page.locator("dialog.action-confirm[open] button.primary").click();+ await page.waitForFunction(() => document.querySelector("#status").classList.contains("err"));+ const said = await page.locator("#status").textContent();+ assert.ok(said.includes("WorkBuddy"), said);+ if (lang === "en") assert.equal(said, stillOpen);+ else assert.notEqual(said, stillOpen, "not translated");+ assert.equal(await go.isDisabled(), false, "the button comes back for another try");+ assert.deepEqual(calls, ["POST workbuddy"]);+ assert.deepEqual(errors, []);+ });+ }+}diff --git a/internal/gui/tests/agent-stale-copies.test.cjs b/internal/gui/tests/agent-stale-copies.test.cjsindex 5ba0ec43d..6ab4f4f82 100644--- a/internal/gui/tests/agent-stale-copies.test.cjs+++ b/internal/gui/tests/agent-stale-copies.test.cjs@@ -194,7 +194,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",}// the Codex app's line has a Restart of its own (the owner, 10-23): magpie-// quits the app named by its bundle and opens it again+// asks, then quits the app named by its bundle and opens it again+const appName = { en: "The Codex app", zh: "Codex 应用", "zh-TW": "Codex 應用", ja: "Codex アプリ", de: "Die Codex-App" };+const cancelSays = { en: "Cancel", zh: "取消", "zh-TW": "取消", ja: "キャンセル", de: "Abbrechen" };const reopened = { en: "The Codex app reopened", zh: "Codex 应用已重新打开", "zh-TW": "Codex 應用已重新打開", ja: "Codex アプリを開き直しました", de: "Codex-App neu geöffnet" };for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {@@ -227,7 +229,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",assert.equal((await go.textContent()).trim(), restartSays[lang]);const box = await go.boundingBox();assert.ok(box.x + box.width <= width, "past the window");+ // asked first, in magpie's own dialog (微雨南山 and stones): Cancel+ // quits nothingawait go.click();+ const ask = page.locator("dialog.action-confirm[open]");+ await ask.waitFor();+ assert.ok((await ask.locator("h2").textContent()).includes(appName[lang]), await ask.locator("h2").textContent());+ await ask.locator("button", { hasText: cancelSays[lang] }).click();+ await ask.waitFor({ state: "detached" });+ assert.deepEqual(asked, []);+ await go.click();+ await ask.locator("button.primary").click();await page.waitForFunction((r) => !document.querySelector(r + " .ag-stale-copy"), row);assert.deepEqual(asked, [{ bundle: "/Applications/Codex.app" }]);assert.equal(await page.locator("#status").textContent(), reopened[lang]);