gui: an app takes the gateway over from its older copy once idle, and says any other version serving it (matrix0487)

matrix0487 on Discord: after an update, pi said 404 'magpie knows no
model "kimi/k3.1-pro" ... add a provider in magpie first'. The app had
written pi a model its older gateway didn't know, and updating the
gateway fixed it. A magpie that finds another one serving the gateway
used to log it and wait for that one to quit (watchGateway took the
port only once nothing answered). Only the Gateway page said so.

Now (otherServes, gateway_older.go):
- An older released copy of the app (it says serves app or tray, and a
  pid) is this app's predecessor. Once its /v1/magpie/concurrency says
  nothing is in flight (gateway.ServedBusy; unknown is never idle),
  the app quits it the way the Gateway page's button does
  (quitMagpieOnPort: a magpie only, by its program) and serves the
  gateway. A stream through it runs to its end first. watchGateway
  looks again every 15s while another serves. At most three times a
  run; a quit that fails is left to the button.
- Any other one (magpie serve or the service, magpie web, a TUI, a
  newer magpie, a build of its own) is left running. /api/state
  carries it as gatewayOther, and the Agents page says it above the
  list with what to do, plus the take-over button for an older one
  (gatewaySkewLine, in plugins/gateway/client.js so app.js stays under
  its budget). A dev build of this magpie says nothing. New strings in
  zh, zh-TW, ja and de.

How the reporter's older gateway outlived the update isn't known: they
never said whether one ran separately. A failed handover leaves the
old app serving for up to 15m, and a magpie serve left running is
another source. Both are covered now: the first is replaced, and the
second is said.

Known gap: a request that starts between the idle read and the quit
gets the older app's short drain. A socket handover between two
running apps (no gap) is not built.

Run on mote at 0f8ea30bb (this change on 2b067434d):
- go vet for internal/gui and internal/gateway, also GOOS=linux
  -tags nogui and GOOS=windows; gofmt -l clean.
- go test -count=1 -timeout 45m ./internal/gui ./internal/gateway:
  gateway ok. gui has two reds, the same on origin/main 0c3163804:
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners/macOS_26_SDK (#3949).
- GUI subset, Chromium and WebKit: gateway-*, agent-layout, agents-*,
  getting-started, i18n-keys, gui-ja/de/zh, panel-arrange, panel-fold:
  411 pass. Two reds, the same on origin/main 0c3163804:
  gateway-caller-keys chromium en (#3797) and gui-ja (#4580). Passing: the new gateway-skew.test.cjs (en and zh at 380px, the
  button POSTs take-over and the line goes).
- Real app on mote, sandbox HOMEs, port 3591, update feed pointed
  nowhere:
  - origin/main built as 0.1.2400 ran `magpie app`, and this head
    built as 0.1.2500 ran `magpie app` beside it. The new one logged
    "an older copy of this app ... with nothing in flight; quitting
    it" and served 0.1.2500 on the port 2s later. The old process was
    gone.
  - The same with the old one as `magpie serve`: it was left running,
    and the new one logged that it serves, older.

Red on origin/main: TestAppReplacesItsOlderGatewayOnceIdle ("the
older copy of the app still serves the gateway", 17s).

Again at the pushed head (this change on 6f3dfc282, mote): vet darwin, linux
nogui and windows; TestCoreScriptBudget (the core is 1,533,104 of
1,533,105: main's #4652 took the room, so app.js's hook line lost its
comment, no raise), TestAppReplacesItsOlderGatewayOnceIdle,
TestGatewaySkew*, TestGatewayFixQuitsOnlyAMagpie,
TestGatewayServedByAnOlderMagpie: ok. gateway-skew, i18n-keys, gui-zh,
gui-de: 11 of 11 pass.

Broken by hand, each red:
- quit without waiting for idle: "quit with a request in flight"
- replaceable() false: "still serves the gateway"
- any serves replaceable: TestGatewaySkewOfAnotherIsSaidNotQuit, the
  serve holder quit
- the Agents hook removed: gateway-skew.test.cjs red in both langs

Not tried: the whole GUI suite (mote was running another session's
full suite), a real app with a real agent stream in flight during the
take-over (the Go test holds a stream through a fake), Windows and
Linux apps (the replace path needs handoverHost, set by the app's Run
on every OS, but it was tried on macOS only).
This commit is contained in:
yetone
2026-11-01 11:43:56 +08:00
parent 6f3dfc282f
commit 90c02326bb
14 changed files with 687 additions and 7 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ three.
| Part | Responsibility | Source |
| --- | --- | --- |
| 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) |
| 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), and `watchGateway` looks at it again every 15 s (`gatewayWatch`). A magpie of another version there (`otherServes` in `gateway_older.go`) is told the page as `gatewayOther` in `/api/state` and said over the Agents list (`gatewaySkewLine` in `plugins/gateway/client.js`), in the panel and the window: pi got 404 for a model the newer app had written it while an older copy of the app kept the gateway, and only the Gateway page said so (matrix0487 on Discord). An older released copy of the app (`serves` app or tray, with a pid) is this app's own predecessor: once its `/v1/magpie/concurrency` says nothing is in flight (`gateway.ServedBusy`; unknown is never idle) the app quits it as the Gateway page's button does (`quitMagpieOnPort`, a magpie only) and serves the gateway, so no stream is cut; at most three times a run (`replaceMost`), and a quit that fails is left to the button. Any other (magpie serve or the service, `magpie web`, a TUI, a newer magpie, a build of its own) is left running, with what to do; a dev build of this magpie says nothing. A request that starts between the idle read and the quit gets the older app's short drain. See `TestAppReplacesItsOlderGatewayOnceIdle`, `TestGatewaySkewOfAnotherIsSaidNotQuit` and `gateway-skew.test.cjs`. `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), [`gateway_older.go`](../../internal/gui/gateway_older.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. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. 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; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) |
| The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) |
+35
View File
@@ -356,6 +356,41 @@ func ServedBy() Served {
return Served{Running: true, Window: info.Window, Version: info.Version, Pid: info.Pid, Serves: info.Serves}
}
// ServedBusy is what the magpie serving the gateway has in flight, as its
// /v1/magpie/concurrency tells it: agent requests (those waiting for a
// slot among them) and Claude Code turns waiting on their caller's tools.
// ok is false when it doesn't say (a magpie from before 3b6ca0557, a
// refusal, no answer in time): unknown, which is never idle.
func ServedBusy() (n int, ok bool) {
c := &http.Client{Timeout: 700 * time.Millisecond}
res, err := c.Get(URL() + "/v1/magpie/concurrency")
if err != nil {
return 0, false
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return 0, false
}
b, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if err != nil {
return 0, false
}
var out struct {
Object string `json:"object"`
Requests *int `json:"requests"`
Waiting *int `json:"waiting"`
Tools *int `json:"tools"`
}
if decodeJSON(b, &out) != nil || out.Object != "concurrency" || out.Requests == nil || out.Tools == nil {
return 0, false
}
n = *out.Requests + *out.Tools
if out.Waiting != nil && *out.Waiting > *out.Requests {
n += *out.Waiting - *out.Requests
}
return n, true
}
// Taken reports whether anything accepts connections at the gateway's
// address, whether or not it answers ServedBy's question in time: a
// magpie busy starting, or slow on a small server, still holds the port.
+6
View File
@@ -317,6 +317,9 @@ type stateJSON struct {
// started card's first step ("add a model source") is done once
// there is one, agents found or not
Served int `json:"served"`
// GatewayOther is a magpie of another version serving the gateway in
// this one's place, which the Agents page says (gateway_older.go)
GatewayOther *gatewaySkew `json:"gatewayOther,omitempty"`
}
// unlistedJSON is a model of a provider kept for routing groups, and the
@@ -2783,6 +2786,9 @@ func state() stateJSON {
s.Unlisted = unlistedModels()
s.CLIBehind = cliBehind()
s.ConfigBlocked = configBlocked()
if served.Load() == nil {
s.GatewayOther = gatewayOther.Load()
}
for _, e := range provider.Served() {
if e.Group == "" {
s.Served++
+3
View File
@@ -4388,6 +4388,9 @@ body.window .row.agent.gone > .ag-conn { margin-left: auto; }
/* 「接入」 in the window: a row says whether the agent goes through magpie —
a line under its name, a link that opens it, its switch */
.ag-lead { margin: 0 2px 12px; font-size: 12.5px; color: var(--fg-2); }
/* a magpie of another version serving the gateway (plugins/gateway gatewaySkewLine) */
.gw-skew { margin: 0 0 12px; }
.gw-skew .gw-skew-err { color: var(--fg-2); }
.ag-lead b { font-weight: 600; color: var(--fg); }
.ag-lead.welcome { margin: 0 0 12px; padding: 16px 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--card); }
.ag-lead .ag-lead-h { display: block; font-size: 14px; margin-bottom: 4px; }
+1
View File
@@ -457,6 +457,7 @@ function renderAgents() {
list.replaceChildren();
homeAgentPrefRows(); // an opened row's, back in the page (ysm119)
agentsLead(list);
self.gatewaySkewLine?.(list);
if (!state.agents.length) {
const e = el("div", "empty-state");
e.append(el("b", "", t("No agents found")), el("span", "", t("Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here.")));
+48
View File
@@ -2580,6 +2580,18 @@ const I18N = {
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Agent 的请求经 magpie {v} 发出,不含当前版本的修复。在这里关闭它,当前版本会立即接管网关。",
"Quit magpie {v} and take over": "关闭 magpie {v} 并接管网关",
"Quitting magpie {v}…": "正在关闭 magpie {v}…",
"magpie {v}, an older copy of this app, still serves the gateway": "更旧的 magpie {v}(这个应用的旧副本)仍在提供网关",
"This magpie ({mine}) takes it over once its {n} request in flight finishes; until then agents' requests go through magpie {v}.": "当前 magpie({mine})会在它手上的 {n} 个请求完成后接管网关;在此之前,Agent 的请求仍经 magpie {v} 发出。",
"This magpie ({mine}) takes it over once its {n} requests in flight finish; until then agents' requests go through magpie {v}.": "当前 magpie({mine})会在它手上的 {n} 个请求完成后接管网关;在此之前,Agent 的请求仍经 magpie {v} 发出。",
"This magpie ({mine}) takes it over once it has no request in flight; until then agents' requests go through magpie {v}.": "当前 magpie({mine})会在它没有进行中的请求时接管网关;在此之前,Agent 的请求仍经 magpie {v} 发出。",
"This magpie ({mine}) takes it over in a moment.": "当前 magpie({mine})马上接管网关。",
"The gateway is served by magpie {v}, older than this app ({mine})": "网关由 magpie {v} 提供,比这个应用({mine})旧",
"It runs as magpie serve, in a terminal or as the service. Agents' requests go through it without this version's fixes, and models set up here may not reach them. Update that magpie and start it again (magpie daemon restart, for the service), or quit it here and this app serves the gateway.": "它以 magpie serve 运行,在终端里或作为后台服务。Agent 的请求经它发出,不含当前版本的修复,这里设置的模型也可能用不了。请更新那个 magpie 并重新启动它(后台服务用 magpie daemon restart),或在这里关闭它,由这个应用提供网关。",
"Agents' requests go through it without this version's fixes, and models set up here may not reach them. Quit it here and this app serves the gateway at once.": "Agent 的请求经它发出,不含当前版本的修复,这里设置的模型也可能用不了。在这里关闭它,这个应用会立即接管网关。",
"The gateway is served by magpie {v}, newer than this app ({mine})": "网关由 magpie {v} 提供,比这个应用({mine})新",
"Agents' requests go through it, and what this app writes for them may not match it. Update this magpie, or quit the newer one there.": "Agent 的请求经它发出,这个应用为它们写的设置可能与它不匹配。请更新当前 magpie,或在那边关闭较新的那个。",
"The gateway is served by magpie {v}, a different build from this app ({mine})": "网关由 magpie {v} 提供,与这个应用({mine})不是同一个构建",
"Agents' requests go through it, and what this app writes for them may not match it. Quit it there for this app to serve the gateway.": "Agent 的请求经它发出,这个应用为它们写的设置可能与它不匹配。请在那边关闭它,由这个应用提供网关。",
"Restart gateway": "重启网关",
"Start gateway": "启动网关",
"Restarting the gateway…": "正在重启网关…",
@@ -6864,6 +6876,18 @@ const I18N = {
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Agent 的請求經 magpie {v} 發出,不含目前版本的修復。在這裡關閉它,目前版本會立即接管閘道。",
"Quit magpie {v} and take over": "關閉 magpie {v} 並接管閘道",
"Quitting magpie {v}…": "正在關閉 magpie {v}…",
"magpie {v}, an older copy of this app, still serves the gateway": "較舊的 magpie {v}(這個應用程式的舊副本)仍在提供閘道",
"This magpie ({mine}) takes it over once its {n} request in flight finishes; until then agents' requests go through magpie {v}.": "目前的 magpie({mine})會在它手上的 {n} 個請求完成後接管閘道;在此之前,Agent 的請求仍經 magpie {v} 發出。",
"This magpie ({mine}) takes it over once its {n} requests in flight finish; until then agents' requests go through magpie {v}.": "目前的 magpie({mine})會在它手上的 {n} 個請求完成後接管閘道;在此之前,Agent 的請求仍經 magpie {v} 發出。",
"This magpie ({mine}) takes it over once it has no request in flight; until then agents' requests go through magpie {v}.": "目前的 magpie({mine})會在它沒有進行中的請求時接管閘道;在此之前,Agent 的請求仍經 magpie {v} 發出。",
"This magpie ({mine}) takes it over in a moment.": "目前的 magpie({mine})馬上接管閘道。",
"The gateway is served by magpie {v}, older than this app ({mine})": "閘道由 magpie {v} 提供,比這個應用程式({mine})舊",
"It runs as magpie serve, in a terminal or as the service. Agents' requests go through it without this version's fixes, and models set up here may not reach them. Update that magpie and start it again (magpie daemon restart, for the service), or quit it here and this app serves the gateway.": "它以 magpie serve 執行,在終端機裡或作為背景服務。Agent 的請求經它發出,不含目前版本的修復,這裡設定的模型也可能無法使用。請更新那個 magpie 並重新啟動它(背景服務用 magpie daemon restart),或在這裡關閉它,由這個應用程式提供閘道。",
"Agents' requests go through it without this version's fixes, and models set up here may not reach them. Quit it here and this app serves the gateway at once.": "Agent 的請求經它發出,不含目前版本的修復,這裡設定的模型也可能無法使用。在這裡關閉它,這個應用程式會立即接管閘道。",
"The gateway is served by magpie {v}, newer than this app ({mine})": "閘道由 magpie {v} 提供,比這個應用程式({mine})新",
"Agents' requests go through it, and what this app writes for them may not match it. Update this magpie, or quit the newer one there.": "Agent 的請求經它發出,這個應用程式為它們寫的設定可能與它不相符。請更新目前的 magpie,或在那邊關閉較新的那個。",
"The gateway is served by magpie {v}, a different build from this app ({mine})": "閘道由 magpie {v} 提供,與這個應用程式({mine})不是同一個建置",
"Agents' requests go through it, and what this app writes for them may not match it. Quit it there for this app to serve the gateway.": "Agent 的請求經它發出,這個應用程式為它們寫的設定可能與它不相符。請在那邊關閉它,由這個應用程式提供閘道。",
"Restart gateway": "重啟閘道",
"Start gateway": "啟動閘道",
"Restarting the gateway…": "正在重啟閘道…",
@@ -11168,6 +11192,18 @@ const I18N = {
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "エージェントのリクエストは magpie {v} を経由し、そのバージョンの方法で送られるため、このバージョンの修正が反映されません。ここで終了すると、すぐにこちらがゲートウェイを引き継ぎます。",
"Quit magpie {v} and take over": "magpie {v} を終了して引き継ぐ",
"Quitting magpie {v}…": "magpie {v} を終了しています…",
"magpie {v}, an older copy of this app, still serves the gateway": "古い magpie {v}(このアプリの古いコピー)がまだゲートウェイを提供しています",
"This magpie ({mine}) takes it over once its {n} request in flight finishes; until then agents' requests go through magpie {v}.": "この magpie({mine})は、処理中の {n} 件のリクエストが終わるとゲートウェイを引き継ぎます。それまでエージェントのリクエストは magpie {v} を経由します。",
"This magpie ({mine}) takes it over once its {n} requests in flight finish; until then agents' requests go through magpie {v}.": "この magpie({mine})は、処理中の {n} 件のリクエストが終わるとゲートウェイを引き継ぎます。それまでエージェントのリクエストは magpie {v} を経由します。",
"This magpie ({mine}) takes it over once it has no request in flight; until then agents' requests go through magpie {v}.": "この magpie({mine})は、処理中のリクエストがなくなるとゲートウェイを引き継ぎます。それまでエージェントのリクエストは magpie {v} を経由します。",
"This magpie ({mine}) takes it over in a moment.": "この magpie({mine})がまもなくゲートウェイを引き継ぎます。",
"The gateway is served by magpie {v}, older than this app ({mine})": "ゲートウェイは magpie {v} が提供しており、このアプリ({mine})より古いバージョンです",
"It runs as magpie serve, in a terminal or as the service. Agents' requests go through it without this version's fixes, and models set up here may not reach them. Update that magpie and start it again (magpie daemon restart, for the service), or quit it here and this app serves the gateway.": "magpie serve として、ターミナルかサービスで動いています。エージェントのリクエストはそこを経由するため、このバージョンの修正が反映されず、ここで設定したモデルが使えないことがあります。その magpie を更新して起動し直す(サービスなら magpie daemon restart)か、ここで終了するとこのアプリがゲートウェイを提供します。",
"Agents' requests go through it without this version's fixes, and models set up here may not reach them. Quit it here and this app serves the gateway at once.": "エージェントのリクエストはそこを経由するため、このバージョンの修正が反映されず、ここで設定したモデルが使えないことがあります。ここで終了すると、すぐにこのアプリがゲートウェイを引き継ぎます。",
"The gateway is served by magpie {v}, newer than this app ({mine})": "ゲートウェイは magpie {v} が提供しており、このアプリ({mine})より新しいバージョンです",
"Agents' requests go through it, and what this app writes for them may not match it. Update this magpie, or quit the newer one there.": "エージェントのリクエストはそこを経由するため、このアプリが書いた設定と合わないことがあります。この magpie を更新するか、新しい方をそちらで終了してください。",
"The gateway is served by magpie {v}, a different build from this app ({mine})": "ゲートウェイは magpie {v} が提供しており、このアプリ({mine})とは別のビルドです",
"Agents' requests go through it, and what this app writes for them may not match it. Quit it there for this app to serve the gateway.": "エージェントのリクエストはそこを経由するため、このアプリが書いた設定と合わないことがあります。このアプリでゲートウェイを提供するには、そちらで終了してください。",
"Restart gateway": "ゲートウェイを再起動",
"Start gateway": "ゲートウェイを起動",
"Restarting the gateway…": "ゲートウェイを再起動しています…",
@@ -15483,6 +15519,18 @@ const I18N = {
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Anfragen der Agenten laufen über magpie {v} und werden so gesendet, wie es sie sendet – ohne die Korrekturen dieser Version. Beenden Sie es hier, dann übernimmt diese Version den Zugangspunkt sofort.",
"Quit magpie {v} and take over": "magpie {v} beenden und übernehmen",
"Quitting magpie {v}…": "magpie {v} wird beendet…",
"magpie {v}, an older copy of this app, still serves the gateway": "magpie {v}, eine ältere Kopie dieser App, stellt den Zugangspunkt noch bereit",
"This magpie ({mine}) takes it over once its {n} request in flight finishes; until then agents' requests go through magpie {v}.": "Diese magpie-Version ({mine}) übernimmt ihn, sobald seine {n} laufende Anfrage fertig ist; bis dahin laufen die Anfragen der Agenten über magpie {v}.",
"This magpie ({mine}) takes it over once its {n} requests in flight finish; until then agents' requests go through magpie {v}.": "Diese magpie-Version ({mine}) übernimmt ihn, sobald seine {n} laufenden Anfragen fertig sind; bis dahin laufen die Anfragen der Agenten über magpie {v}.",
"This magpie ({mine}) takes it over once it has no request in flight; until then agents' requests go through magpie {v}.": "Diese magpie-Version ({mine}) übernimmt ihn, sobald es keine laufende Anfrage mehr hat; bis dahin laufen die Anfragen der Agenten über magpie {v}.",
"This magpie ({mine}) takes it over in a moment.": "Diese magpie-Version ({mine}) übernimmt ihn gleich.",
"The gateway is served by magpie {v}, older than this app ({mine})": "Der Zugangspunkt wird von magpie {v} bereitgestellt, älter als diese App ({mine})",
"It runs as magpie serve, in a terminal or as the service. Agents' requests go through it without this version's fixes, and models set up here may not reach them. Update that magpie and start it again (magpie daemon restart, for the service), or quit it here and this app serves the gateway.": "Es läuft als magpie serve, in einem Terminal oder als Dienst. Anfragen der Agenten laufen darüber – ohne die Korrekturen dieser Version, und hier eingerichtete Modelle erreichen sie womöglich nicht. Aktualisieren Sie dieses magpie und starten Sie es neu (magpie daemon restart für den Dienst), oder beenden Sie es hier, dann stellt diese App den Zugangspunkt bereit.",
"Agents' requests go through it without this version's fixes, and models set up here may not reach them. Quit it here and this app serves the gateway at once.": "Anfragen der Agenten laufen darüber – ohne die Korrekturen dieser Version, und hier eingerichtete Modelle erreichen sie womöglich nicht. Beenden Sie es hier, dann übernimmt diese App den Zugangspunkt sofort.",
"The gateway is served by magpie {v}, newer than this app ({mine})": "Der Zugangspunkt wird von magpie {v} bereitgestellt, neuer als diese App ({mine})",
"Agents' requests go through it, and what this app writes for them may not match it. Update this magpie, or quit the newer one there.": "Anfragen der Agenten laufen darüber, und was diese App für sie schreibt, passt womöglich nicht dazu. Aktualisieren Sie dieses magpie, oder beenden Sie das neuere dort.",
"The gateway is served by magpie {v}, a different build from this app ({mine})": "Der Zugangspunkt wird von magpie {v} bereitgestellt, einem anderen Build als diese App ({mine})",
"Agents' requests go through it, and what this app writes for them may not match it. Quit it there for this app to serve the gateway.": "Anfragen der Agenten laufen darüber, und was diese App für sie schreibt, passt womöglich nicht dazu. Beenden Sie es dort, damit diese App den Zugangspunkt bereitstellt.",
"Restart gateway": "Zugangspunkt neu starten",
"Start gateway": "Zugangspunkt starten",
"Restarting the gateway…": "Zugangspunkt wird neu gestartet…",
@@ -135,6 +135,75 @@ function gatewayFixSays(o) {
return t("The gateway couldn't be served here: {error}", p);
}
// gatewaySkewLine: a magpie of another version serves the gateway in this
// one's place (gui/gateway_older.go). matrix0487 on Discord: the app wrote pi
// a model its older gateway didn't know, pi said 404 "add a provider in
// magpie first", and only the Gateway page told of the older magpie. Said
// over the Agents list, in the panel and the window, until it is gone: an
// older copy of the app is taken over by itself once idle; any other is
// the user's to update or quit, here with the Gateway page's own button.
let gwSkewFix = { busy: false, err: "", pid: 0 };
function gatewaySkewLine(list) {
let box = $("#gwSkew");
const o = state.gatewayOther;
if (!o || !o.version) {
if (box) box.hidden = true;
return;
}
if (!box) {
box = el("div", "gw-skew");
box.id = "gwSkew";
($("#agentsLead") || list).before(box);
}
box.hidden = false;
if (gwSkewFix.pid !== (o.pid || 0)) gwSkewFix = { busy: false, err: "", pid: o.pid || 0 };
const p = { v: o.version, mine: o.mine, n: o.busy || 0 };
let head, why, quit = false;
if (o.replacing) {
head = t("magpie {v}, an older copy of this app, still serves the gateway", p);
why = o.busy > 0
? t(o.busy === 1 ? "This magpie ({mine}) takes it over once its {n} request in flight finishes; until then agents' requests go through magpie {v}." : "This magpie ({mine}) takes it over once its {n} requests in flight finish; until then agents' requests go through magpie {v}.", p)
: o.busy < 0
? t("This magpie ({mine}) takes it over once it has no request in flight; until then agents' requests go through magpie {v}.", p)
: t("This magpie ({mine}) takes it over in a moment.", p);
} else if (o.older) {
head = t("The gateway is served by magpie {v}, older than this app ({mine})", p);
why = o.serves === "serve"
? t("It runs as magpie serve, in a terminal or as the service. Agents' requests go through it without this version's fixes, and models set up here may not reach them. Update that magpie and start it again (magpie daemon restart, for the service), or quit it here and this app serves the gateway.", p)
: t("Agents' requests go through it without this version's fixes, and models set up here may not reach them. Quit it here and this app serves the gateway at once.", p);
quit = true;
} else if (o.newer) {
head = t("The gateway is served by magpie {v}, newer than this app ({mine})", p);
why = t("Agents' requests go through it, and what this app writes for them may not match it. Update this magpie, or quit the newer one there.", p);
} else {
head = t("The gateway is served by magpie {v}, a different build from this app ({mine})", p);
why = t("Agents' requests go through it, and what this app writes for them may not match it. Quit it there for this app to serve the gateway.", p);
}
const card = el("div", "deprecation");
card.setAttribute("role", "note");
const body = el("div", "dep-body");
body.append(el("div", "dep-head", head), el("p", "dep-why", why));
if (gwSkewFix.err) body.append(el("p", "dep-why gw-skew-err", gwSkewFix.err));
card.append(el("span", "dep-dot"), body);
if (quit) {
const acts = el("div", "dep-acts");
const b = el("button", "text action", gwSkewFix.busy ? t("Quitting magpie {v}…", p) : t("Quit magpie {v} and take over", p));
b.disabled = b.classList.toggle("busy", gwSkewFix.busy);
b.onclick = async () => {
gwSkewFix = { busy: true, err: "", pid: o.pid || 0 };
gatewaySkewLine(list);
let out;
try { out = await api("gateway/take-over", {}); } catch (e) { out = { reason: "error", error: e.message }; }
gwSkewFix = { busy: false, err: out?.ok ? "" : gatewayFixSays(out || {}), pid: o.pid || 0 };
try { state = await api("state"); } catch {}
renderAgents();
};
acts.append(b);
card.append(acts);
}
box.replaceChildren(card);
}
// The status card: the gateway's mark, its state and what it does, and the
// button that fixes what stands in its way.
const GW_GLYPH = '<svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="14" height="5" rx="1.5"/><rect x="3" y="11" width="14" height="5" rx="1.5"/></g><circle class="led" cx="6.2" cy="6.5" r="1.1"/><circle class="led" cx="6.2" cy="13.5" r="1.1"/></svg>';
+11 -5
View File
@@ -13,7 +13,6 @@ import (
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/update"
"github.com/yetone/magpie/internal/usage"
)
@@ -95,7 +94,9 @@ func watchGateway(ctx context.Context, every time.Duration) {
case <-t.C:
}
gatewayMu.Lock()
if ctx.Err() == nil && served.Load() == nil && !gateway.Running() {
if ctx.Err() == nil && served.Load() == nil {
// gone, or an older copy of the app done with its requests
// (otherServes): served here; else looked at again next time
serveGatewayLocked()
}
gatewayMu.Unlock()
@@ -134,11 +135,15 @@ func serveGatewayLocked() *gateway.Server {
// the Codex relay a magpie quitting left at the port (codexrelay)
// lets go of it, finishing the turns it streams
codexrelay.Leave()
// another magpie serving it: said on the page when its version
// isn't this one's, and quit when it is an older copy of the app
// with nothing in flight (gateway_older.go)
if o := gateway.ServedBy(); o.Running {
if update.Newer(gateway.Version, o.Version) {
log.Printf("gateway: magpie %s serves %s, older than this one (%s); agents' requests go through it until it quits", o.Version, gateway.URL(), gateway.Version)
if !otherServes(o) {
return nil
}
return nil
// the relay the one quit may have left at the port
codexrelay.Leave()
}
// a magpie too busy to answer the question in time (a small
// server, one starting), or another program, has the port: a
@@ -152,6 +157,7 @@ func serveGatewayLocked() *gateway.Server {
}
}
takenSaid.Store(false)
gatewayOther.Store(nil)
gw := gateway.New()
served.Store(gw)
serving.Add(1)
+135
View File
@@ -0,0 +1,135 @@
package gui
import (
"log"
"strings"
"sync/atomic"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/update"
)
// A magpie of another version keeping the gateway's port sends every
// agent's request its own way, while this one writes the agents' settings
// (matrix0487 on Discord: the app wrote pi a model its older gateway
// didn't know, and pi said 404 "add a provider in magpie first"). Before,
// this magpie only logged it and waited for that one to quit, and only
// the Gateway page said so. Now:
//
// - an older copy of the app (it says it serves as "app" or "tray", a
// released version both) is this app's own predecessor: this one
// takes the gateway over from it once it has no request in flight
// (gateway.ServedBusy), quitting it as the Gateway page's button does
// (quitMagpieOnPort: only a magpie of this user's, by its program),
// so no request is cut off; looked at again every gatewayWatch;
// - any other (magpie serve, a service, magpie web, a TUI, a newer
// magpie, a build of its own) is someone's to quit or update: it is
// left running and the Agents page says so, with what to do
// (gatewayOther, in /api/state).
// gatewaySkew is a magpie of another version serving the gateway, as the
// page is told it.
type gatewaySkew struct {
Version string `json:"version"` // the other's
Mine string `json:"mine"` // this magpie's
Serves string `json:"serves,omitempty"`
Pid int `json:"pid,omitempty"`
// Older: it is older than this one; Newer: newer; neither, a build
// the two can't be ordered by (one of its own)
Older bool `json:"older,omitempty"`
Newer bool `json:"newer,omitempty"`
// Replacing: this app takes the gateway over from it once it is idle;
// Busy is what it has in flight meanwhile, -1 when it doesn't say
Replacing bool `json:"replacing,omitempty"`
Busy int `json:"busy,omitempty"`
// Stuck: why quitting it didn't go (gatewayFixJSON's Reason); this
// one stops trying, and the page offers the button instead
Stuck string `json:"stuck,omitempty"`
}
// gatewayOther is the magpie of another version serving the gateway, nil
// while none does (this one serves it, or one of the same version).
var gatewayOther atomic.Pointer[gatewaySkew]
// replacedOlder counts the older apps this one has quit to serve the
// gateway; past replaceMost something starts them again (a login item
// pointing at an old copy), and they are left to the user.
var replacedOlder atomic.Int32
const replaceMost = 3
// bare is a version without the v a tag has.
func bare(v string) string { return strings.TrimPrefix(v, "v") }
// skewOf is how the magpie o serving the gateway differs from this one,
// nil when it doesn't (the same version, or one that doesn't say).
func skewOf(o gateway.Served) *gatewaySkew {
mine := gateway.Version
if o.Version == "" || bare(o.Version) == bare(mine) || !update.Released(mine) {
// a build of this magpie's own (make dev) beside the installed
// one is its developer's to know about
return nil
}
return &gatewaySkew{
Version: bare(o.Version), Mine: bare(mine), Serves: o.Serves, Pid: o.Pid,
Older: update.Newer(mine, o.Version), Newer: update.Newer(o.Version, mine),
}
}
// replaceable is whether this magpie takes the gateway over from o by
// itself: this is the app, and o an older release of it.
func replaceable(o gateway.Served, sk *gatewaySkew) bool {
return handoverHost.Load() && sk != nil && sk.Older && update.Released(o.Version) &&
(o.Serves == "app" || o.Serves == "tray") && o.Pid > 0 &&
replacedOlder.Load() < replaceMost
}
// otherServes, under gatewayMu with this one serving nothing, looks at the
// magpie o that serves the gateway: what the page is told of it, and, for
// an older copy of the app with no request in flight, quits it. True when
// it was quit and the port is free for this one.
func otherServes(o gateway.Served) bool {
sk := skewOf(o)
before := gatewayOther.Load()
if sk == nil {
gatewayOther.Store(nil)
return false
}
if before != nil && before.Stuck != "" && before.Pid == sk.Pid {
sk.Stuck = before.Stuck // tried; the button is the user's now
} else if replaceable(o, sk) {
sk.Replacing = true
n, ok := gateway.ServedBusy()
if !ok {
n = -1
}
sk.Busy = n
if n == 0 {
log.Printf("gateway: magpie %s (pid %d), an older copy of this app, serves %s with nothing in flight; quitting it for this one (%s) to serve", sk.Version, sk.Pid, gateway.URL(), sk.Mine)
out := quitMagpieOnPort(o.Version)
if out.OK {
replacedOlder.Add(1)
gatewayOther.Store(nil)
return true
}
log.Printf("gateway: magpie %s wasn't quit (%s %s); it keeps the gateway", sk.Version, out.Reason, out.Error)
sk.Replacing, sk.Busy, sk.Stuck = false, 0, out.Reason
}
}
if before == nil || before.Version != sk.Version || before.Pid != sk.Pid {
how := "older than this one"
switch {
case sk.Newer:
how = "newer than this one"
case !sk.Older:
how = "a build other than this one"
}
next := "until it quits"
if sk.Replacing {
next = "until this one takes it over, once it has no request in flight"
}
log.Printf("gateway: magpie %s (%s, pid %d) serves %s, %s (%s); agents' requests go through it %s", sk.Version, sk.Serves, sk.Pid, gateway.URL(), how, sk.Mine, next)
}
gatewayOther.Store(sk)
return false
}
+171
View File
@@ -0,0 +1,171 @@
package gui
import (
"bufio"
"context"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// resetSkew forgets what the tests' fakes left of another magpie seen
// serving the gateway (set by gateway_skew_test.go).
var resetSkew = func() {}
// skewHome gives the test a home and a gateway port of its own, this
// magpie the version mine and the app's handover host, and stops the
// gateway it comes to serve when it ends.
func skewHome(t *testing.T, mine string) string {
t.Helper()
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
addr := "127.0.0.1:" + strconv.Itoa(freePort(t))
t.Setenv("MAGPIE_ADDR", addr)
was, wasHost := gateway.Version, handoverHost.Load()
gateway.Version = mine
handoverHost.Store(true)
served.Store(nil)
resetSkew()
waits := []*time.Duration{&quitWait, &killWait, &startWait}
olds := []time.Duration{quitWait, killWait, startWait}
quitWait, killWait, startWait = 3*time.Second, 2*time.Second, 5*time.Second
t.Cleanup(func() {
gatewayMu.Lock()
if served.Load() != nil && servedRun.stop != nil {
servedRun.stop()
<-servedRun.done
}
served.Store(nil)
gatewayMu.Unlock()
gateway.Version = was
handoverHost.Store(wasHost)
for i, w := range waits {
*w = olds[i]
}
resetSkew()
})
return addr
}
// startFakeMagpie runs the test binary, named magpie, as another magpie
// of version v holding the gateway's port, started as serves says; ended
// is closed once it has ended.
func startFakeMagpie(t *testing.T, addr, v, serves string) (ended chan struct{}) {
t.Helper()
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
name := "magpie"
if runtime.GOOS == "windows" {
name += ".exe"
}
bin := filepath.Join(t.TempDir(), name)
if runtime.GOOS == "windows" || os.Link(self, bin) != nil {
b, err := os.ReadFile(self)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bin, b, 0o755); err != nil {
t.Fatal(err)
}
}
cmd := exec.Command(bin, "-test.run=^$")
cmd.Env = append(os.Environ(), "MAGPIE_TEST_FAKE_GATEWAY="+addr, "MAGPIE_TEST_FAKE_VERSION="+v, "MAGPIE_TEST_FAKE_SERVES="+serves)
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
ended = make(chan struct{})
go func() { cmd.Wait(); close(ended) }()
t.Cleanup(func() { cmd.Process.Kill(); <-ended })
for deadline := time.Now().Add(10 * time.Second); gateway.ServedBy().Version != v; time.Sleep(50 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatalf("the fake magpie %s didn't answer", v)
}
}
return ended
}
// matrix0487 on Discord: after an update the app kept the gateway an older
// copy of it served, said so nowhere but the Gateway page, and pi got 404
// for a model the newer app had written it. Now the app takes the gateway
// over from its older copy by itself, once that one has no request in
// flight: an agent's stream through it runs to its end, and then this one
// serves the gateway.
func TestAppReplacesItsOlderGatewayOnceIdle(t *testing.T) {
addr := skewHome(t, "0.1.2500")
ended := startFakeMagpie(t, addr, "0.1.2400", "app")
// an agent's reply streaming through the older one
lines := make(chan int, 1)
go func() {
res, err := http.Get("http://" + addr + "/stream")
if err != nil {
lines <- -1
return
}
defer res.Body.Close()
n := 0
for sc := bufio.NewScanner(res.Body); sc.Scan(); {
if strings.HasPrefix(sc.Text(), "line ") {
n++
}
}
lines <- n
}()
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
if res, err := http.Get("http://" + addr + "/v1/magpie/concurrency"); err == nil {
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if strings.Contains(string(b), `"requests":1,`) {
break
}
}
if time.Now().After(deadline) {
t.Fatal("the stream never started")
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go watchGateway(ctx, 100*time.Millisecond)
// while it streams, it is left serving
select {
case n := <-lines:
if n != 20 {
t.Fatalf("the stream through the older magpie was cut at %d lines of 20", n)
}
case <-ended:
t.Fatal("the older magpie was quit with a request in flight")
case <-time.After(15 * time.Second):
t.Fatal("the stream never ended")
}
// then it is quit, and this one serves the gateway
select {
case <-ended:
case <-time.After(15 * time.Second):
t.Fatal("the older copy of the app still serves the gateway")
}
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) {
if served.Load() != nil && gateway.ServedBy().Version == "0.1.2500" {
break
}
if time.Now().After(deadline) {
t.Fatalf("not served here after the older one quit: %+v", gateway.ServedBy())
}
}
}
+75
View File
@@ -0,0 +1,75 @@
package gui
import (
"context"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
func init() {
resetSkew = func() {
replacedOlder.Store(0)
gatewayOther.Store(nil)
}
}
// A magpie of another version serving the gateway that isn't an older
// copy of this app (magpie serve, a newer magpie, a build of its own) is
// someone else's to quit: it is left running, and the page is told what
// it is, for the Agents page to say so.
func TestGatewaySkewOfAnotherIsSaidNotQuit(t *testing.T) {
for _, c := range []struct {
name, v, serves string
older, newer bool
}{
{"serve", "0.1.2400", "serve", true, false},
{"newer", "0.1.2600", "app", false, true},
{"own build", "0.1.2400-3-gabcdef1", "app", true, false},
} {
t.Run(c.name, func(t *testing.T) {
addr := skewHome(t, "0.1.2500")
ended := startFakeMagpie(t, addr, c.v, c.serves)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go watchGateway(ctx, 50*time.Millisecond)
var sk *gatewaySkew
for deadline := time.Now().Add(5 * time.Second); sk == nil; time.Sleep(20 * time.Millisecond) {
sk = gatewayOther.Load()
if time.Now().After(deadline) {
t.Fatal("the page isn't told of it")
}
}
select {
case <-ended:
t.Fatal("quit a magpie that isn't an older copy of this app")
case <-time.After(500 * time.Millisecond):
}
if sk.Version != c.v || sk.Mine != "0.1.2500" || sk.Serves != c.serves || sk.Older != c.older || sk.Newer != c.newer || sk.Replacing || sk.Pid == 0 {
t.Fatalf("told %+v", sk)
}
if served.Load() != nil {
t.Fatal("served beside it")
}
if got := state().GatewayOther; got == nil || got.Version != c.v {
t.Fatalf("state's gatewayOther: %+v", got)
}
})
}
}
// A copy of this very version serving the gateway (a second process of
// it) is not a skew; nor does a dev build of this magpie say one.
func TestGatewaySkewNotForTheSameOrADevBuild(t *testing.T) {
was := gateway.Version
defer func() { gateway.Version = was }()
gateway.Version = "0.1.2500"
if sk := skewOf(gateway.Served{Running: true, Version: "v0.1.2500", Serves: "app", Pid: 9}); sk != nil {
t.Fatalf("the same version: %+v", sk)
}
gateway.Version = "0.1.2500-4-g0123abc"
if sk := skewOf(gateway.Served{Running: true, Version: "0.1.2400", Serves: "app", Pid: 9}); sk != nil {
t.Fatalf("a dev build: %+v", sk)
}
}
+25 -1
View File
@@ -1,6 +1,7 @@
package gui
import (
"fmt"
"io"
"net"
"net/http"
@@ -9,6 +10,7 @@ import (
"path/filepath"
"runtime"
"strconv"
"sync/atomic"
"testing"
"time"
@@ -17,14 +19,36 @@ import (
// fakeOlderGateway is the test binary run as another process holding the
// gateway's port and answering as magpie 0.1.550 would, until it is ended.
// MAGPIE_TEST_FAKE_VERSION and MAGPIE_TEST_FAKE_SERVES make it another
// version, started another way: then it also says its pid, streams
// /stream as an agent's reply (20 lines, 100ms apart) and tells
// /v1/magpie/concurrency how many of those are in flight, as a magpie
// since 3b6ca0557 does.
func fakeOlderGateway(addr string) {
ln, err := net.Listen("tcp", addr)
if err != nil {
os.Exit(3)
}
version, serves := os.Getenv("MAGPIE_TEST_FAKE_VERSION"), os.Getenv("MAGPIE_TEST_FAKE_SERVES")
var streams atomic.Int32
http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"name":"magpie","version":"0.1.550","models":3}`)
switch {
case version == "":
io.WriteString(w, `{"name":"magpie","version":"0.1.550","models":3}`)
case r.URL.Path == "/stream":
streams.Add(1)
defer streams.Add(-1)
for i := range 20 {
fmt.Fprintf(w, "line %d\n", i)
w.(http.Flusher).Flush()
time.Sleep(100 * time.Millisecond)
}
case r.URL.Path == "/v1/magpie/concurrency":
fmt.Fprintf(w, `{"object":"concurrency","data":{},"requests":%d,"waiting":0,"tools":0,"active":[]}`, streams.Load())
default:
fmt.Fprintf(w, `{"name":"magpie","version":%q,"models":3,"pid":%d,"serves":%q}`, version, os.Getpid(), serves)
}
}))
}
+2
View File
@@ -83,6 +83,8 @@ func keptFile(s stateJSON) stateFile {
s.Settings = settings.Settings{}
// and what is told once: a notice, a file recovered after a crash
s.Notice, s.Connected, s.Recovered = "", nil, nil
// and the magpie serving the gateway now, which the next start asks
s.GatewayOther = nil
return stateFile{Version: Version, State: s}
}
+105
View File
@@ -0,0 +1,105 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A magpie of another version serving the gateway (matrix0487 on Discord:
// pi got 404 for a model the newer app had written it, and only the Gateway
// page named the older magpie) is said over the Agents list: an older copy
// of the app being taken over once idle, an older magpie serve or app with
// the Gateway page's button, a newer one, a build of its own. In English
// and Chinese, in both engines, at the panel's width, with nothing cut off.
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");
function fixture(lang, other, posts) {
let gone = false;
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/gateway/take-over" && req.method() === "POST") {
posts.push(url.pathname);
gone = true;
return json({ ok: true });
}
if (url.pathname === "/api/state") return json({
agents: [{ id: "pi", name: "pi", path: "/test/models.json", icon: "pi", wired: true, fields: [] }],
profiles: [], settings: { lang, theme: "light" },
...(gone || !other ? {} : { gatewayOther: other }),
});
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], 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 base = { version: "0.1.2400", mine: "0.1.2500", pid: 4242 };
const cases = {
en: [
{ other: { ...base, serves: "app", older: true, replacing: true, busy: 2 }, head: "magpie 0.1.2400, an older copy of this app, still serves the gateway", why: /once its 2 requests in flight finish/, quit: false },
{ other: { ...base, serves: "app", older: true, replacing: true, busy: 1 }, head: "magpie 0.1.2400, an older copy of this app, still serves the gateway", why: /once its 1 request in flight finishes/, quit: false },
{ other: { ...base, serves: "serve", older: true }, head: "The gateway is served by magpie 0.1.2400, older than this app (0.1.2500)", why: /magpie serve.*magpie daemon restart/, quit: true },
{ other: { ...base, serves: "app", older: true, stuck: "denied" }, head: "The gateway is served by magpie 0.1.2400, older than this app (0.1.2500)", why: /Quit it here and this app serves the gateway at once/, quit: true },
{ other: { ...base, version: "0.1.2600", serves: "app", newer: true }, head: "The gateway is served by magpie 0.1.2600, newer than this app (0.1.2500)", why: /Update this magpie/, quit: false },
{ other: { ...base, version: "0.1.2400-3-gabcdef1", serves: "app" }, head: "The gateway is served by magpie 0.1.2400-3-gabcdef1, a different build from this app (0.1.2500)", why: /Quit it there/, quit: false },
],
zh: [
{ other: { ...base, serves: "app", older: true, replacing: true, busy: -1 }, head: "更旧的 magpie 0.1.2400(这个应用的旧副本)仍在提供网关", why: /没有进行中的请求时接管网关/, quit: false },
{ other: { ...base, serves: "serve", older: true }, head: "网关由 magpie 0.1.2400 提供,比这个应用(0.1.2500)旧", why: /magpie serve.*magpie daemon restart/, quit: true },
{ other: { ...base, version: "0.1.2600", serves: "app", newer: true }, head: "网关由 magpie 0.1.2600 提供,比这个应用(0.1.2500)新", why: /请更新当前 magpie/, quit: false },
],
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: another magpie's version serving the gateway is said on the Agents page`, async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch());
t.after(() => browser.close());
const errors = [];
for (const c of [...cases[lang], { other: null }]) {
const posts = [];
const context = await browser.newContext({ viewport: { width: 380, height: 640 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, c.other, posts));
await page.goto("http://magpie.test/");
await page.locator('.row.agent[data-id="pi"]').waitFor();
const box = page.locator("#gwSkew");
if (!c.other) {
// none: nothing is said
assert.equal(await box.count() ? await box.isVisible() : false, false, "a skew said with none");
await context.close();
continue;
}
await box.waitFor();
assert.equal((await box.locator(".dep-head").textContent()).trim(), c.head);
assert.match(await box.locator(".dep-why").first().textContent(), c.why);
// above the list, the whole text readable, and nothing sideways
const [skewY, listY] = await page.evaluate(() => [document.querySelector("#gwSkew").getBoundingClientRect().top, document.querySelector('.row.agent[data-id="pi"]').getBoundingClientRect().top]);
assert(skewY < listY, "said under the list");
assert(await box.evaluate((b) => [...b.querySelectorAll(".dep-head,.dep-why")].every((e) => e.scrollWidth <= e.clientWidth + 1)), "cut off");
assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page scrolls sideways");
const button = box.locator("button");
assert.equal(await button.count(), c.quit ? 1 : 0, "the button's there only for an older magpie this app can quit");
if (c.quit) {
await button.click();
// the take-over is asked for, and once it's done the line goes
await box.waitFor({ state: "hidden" });
assert.deepEqual(posts, ["/api/gateway/take-over"]);
}
await context.close();
}
assert.deepEqual(errors, []);
});
}
}