serve, update: one magpie works the gateway; the service waits, the copy an update left stops (#4938)
ox01024's #4938, Bug 2. Two magpies did the gateway's work at once on a Mac: - launchd's com.yetone.magpie.serve ran `magpie serve` beside the app. It ran startUp (plugin Settle/Refresh, FoldCopies, Hold, the agent moves), the plugin host and every account's model fetch, then failed to bind, exited 1 and was started again 5s later: 6,035 times in two days, a 279MB serve.log, and logins.json.lock held against the app's requests until they went 504. - The copy an update left (.magpie-update/old) handed the socket over, hid, and lived on ~3h, its loops writing beside the new one. What changed: - cli: `magpie serve` (no --web) checks codexrelay.Leave, gateway.ServedBy and gateway.Taken before startUp, as the app's serveGatewayLocked does. While the port is held it prints one line and looks again every 15s, doing nothing else. Once the port is free it serves (serve_wait.go). It waits rather than exiting 0: under KeepAlive SuccessfulExit:false a clean exit would leave no service after the app quits. - gui: after a handover the old magpie's loops end with backendCtx: - library.KeepLinked (now takes a ctx), - provider.WatchQuotas, - the menu bar usage loop, - the updater's check/auto-restart loop. lighten lets its hidden webviews go as lightweight mode does, so their polls stop. quitBy exits it at handedOffDrain + 3m whatever holds its quit up (gateway.HandedOffDrain getter; exitNow stubbable). - docs/subsystems/gui-shell.md says both. Run at the pushed head on mote (mote-run): - gofmt -l internal/: nothing. go vet ./internal/{cli,gui,library,gateway}; GOOS=linux go vet -tags nogui and GOOS=windows go vet of the same: ok. - go test -count=1 -timeout 45m ./internal/cli ./internal/library ./internal/gui ./internal/gateway atbf05291e2+ this: cli and library ok. Two reds, both already filed: - gui TestMainWindowCorners/macOS_26_SDK (#3949). It is red the same on origin/main443e53d6b, run alone. - gateway TestCodexPoolSaysTheClientsVersion (#4807). It is red only in the full package run, and passes alone 5 of 5 at this head. - After rebasing on8819beeb0, on that head: the vets above; cli and library in full, ok; gui and gateway with -run for handover, handoff and lightweight, ok. - Sandbox HOME on mote, a fake app answering / as magpie 0.1.2770 on a private port (3593), `magpie serve` built from this tree beside it: alive after 8s at 0% CPU, nothing written under HOME, one standby line. 20s after the fake quit it served the port. The same with the old wait call removed: "magpie: listen tcp 127.0.0.1:3593: bind: address already in use", exit, and plugins.yml and lock files written first. Broken by hand, each red: - No wait before startUp: TestServeWaitsForTheGatewayBeforeStartingUp ("ran the start-up moves while another magpie served the gateway"). - KeepLinked ignoring its ctx: TestKeepLinkedEndsWithItsContext ("went on after its context ended"). - No quitBy in handover.run: TestRestartHandsTheGatewayOver ("has no deadline to quit by"). Not tried: - A real launchd service beside the real app, and a real update handover on a Mac. Neither was run: no live app or launchd. - The lighten change (needs Wails webviews) has no test. - Not done here: serve.log rotation, `magpie daemon install` beside a running app (#4887), the old copy's appPage port, and Bug 1 and Bug 3 (ggbdpq has Bug 1). cdredfox on Discord reports ~270% CPU after v0.1.2770. That fits this, but it is not confirmed as their cause.
This commit is contained in:
@@ -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`). On Windows, Wails reads the screens again on each display change (`WM_DISPLAYCHANGE`, and `WM_SETTINGCHANGE` for the work area) through `w32.GetAllScreens`, which makes a new Win32 callback each time; Go never frees one and throws past about 2000, killing the app and its gateway after hours of display changes (1111_13879 on Discord). `screensWndProc`, the app's `WndProcInterceptor`, takes those messages on Wails' main-thread window first and reads the screens with one callback made once (`allScreens`), then hands them to `Screen.LayoutScreens` as Wails would; see `TestScreensReadFarPastTheCallbackLimit`, `TestDisplayChangesAreReadOnWailsWindowOnly` (Windows) and `TestWailsScreensAreReadOnTheMainThreadWindow`, which fails when a Wails upgrade changes what that relies on. | [`app.go`](../../internal/gui/app.go), [`screens_windows.go`](../../internal/gui/screens_windows.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), 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) |
|
||||
| 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`. `magpie serve` (the service's, launchd's `com.yetone.magpie.serve` or systemd's) does the same beside a magpie serving or another program holding the port: before it moves or starts anything (`startUp`), it waits, looking every 15 s, and serves once the port is free (`awaitGatewayFree` in [`serve_wait.go`](../../internal/cli/serve_wait.go); `--web` excepted, which shows the other one). Before, it ran the start-up moves, the plugin host and every account's model fetch, failed to bind, exited 1 and was started again by the service, 6,035 times in two days with a 279MB serve.log and requests 504 behind it (#4938, `TestServeWaitsForTheGatewayBeforeStartingUp`). `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) |
|
||||
| Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.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) |
|
||||
@@ -747,6 +747,17 @@ then calls `beginHandover` instead of the relaunch-after-exit. The steps:
|
||||
second restart click while a handover is under way does nothing
|
||||
(`pending`).
|
||||
|
||||
Once handed over, the old one does nothing beside the new one but finish
|
||||
its requests (#4938): its loops end with its backend (`backendCtx`):
|
||||
the linked instruction sets' sync (`library.KeepLinked`), quota alerts
|
||||
(`provider.WatchQuotas`), the menu bar's usage and the update check and
|
||||
automatic restart (`updates.start`); its hidden pages are let go as in
|
||||
lightweight mode (`lighten`, so their polls stop); and it exits by the end
|
||||
of its drain and `quitGrace` (3 minutes) after, whatever holds its quit up
|
||||
(`quitBy`, `TestHandedOverQuitsByItsDeadline`). Before, a copy an update
|
||||
left lived on hidden for three hours, writing and fetching beside the new
|
||||
one.
|
||||
|
||||
Two magpies never show at once. On a Mac the old one lets go of its
|
||||
instance lock before it gives the socket (`releaseInstance`), so the new
|
||||
one's `runningAlready` takes it, and once the ack comes the old one hides
|
||||
|
||||
@@ -372,6 +372,12 @@ func run(args []string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
// magpie serve beside another magpie serving the gateway (the app, a
|
||||
// service, the copy an update left) waits for the port before it moves
|
||||
// or starts anything, rather than doing it all to fail to bind (#4938)
|
||||
if len(args) > 0 && args[0] == "serve" && plainServe(args[1:]) {
|
||||
awaitGatewayFree(gatewayFreeEvery)
|
||||
}
|
||||
startUp()
|
||||
// a provider added, edited or removed, or a list fetched anew, reaches
|
||||
// the model lists agents keep in files of their own, behind the save
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/codexrelay"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// gatewayFreeEvery is how often magpie serve, waiting for the gateway's
|
||||
// port (awaitGatewayFree), looks again: as often as the app does
|
||||
// (gui.gatewayWatch). A var for tests.
|
||||
var gatewayFreeEvery = 15 * time.Second
|
||||
|
||||
// plainServe says args are magpie serve's for the gateway alone: no
|
||||
// --web, whose page shows the gateway another magpie serves and so starts
|
||||
// beside it (gui.StartWeb), and nothing serveCmd refuses, which it says
|
||||
// at once.
|
||||
func plainServe(args []string) bool {
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch a := args[i]; {
|
||||
case a == "--tls-cert" || a == "--tls-key":
|
||||
i++
|
||||
case strings.HasPrefix(a, "--tls-cert="), strings.HasPrefix(a, "--tls-key="):
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// awaitGatewayFree returns once nothing holds the gateway's port, looking
|
||||
// every so often while another magpie serves it (the app, a second
|
||||
// service, the copy an update left finishing its requests) or another
|
||||
// program holds it. magpie serve waits here before it moves or starts
|
||||
// anything: started beside the app by the service (launchd's KeepAlive,
|
||||
// systemd's Restart), it used to run the start-up moves, start the plugin
|
||||
// host and fetch every account's models, fail to bind and exit 1, and be
|
||||
// started again 5s later, 6,035 times in two days in #4938: serve.log at
|
||||
// 279MB, and the logins lock held against the app's requests till they
|
||||
// went 504. Waiting, it does nothing until the port is free, and then
|
||||
// serves, as the app does beside a magpie serving (gui.watchGateway).
|
||||
func awaitGatewayFree(every time.Duration) {
|
||||
said := false
|
||||
for {
|
||||
// the Codex relay a magpie quitting left at the port lets go of
|
||||
// it for this one, as for the app (codexrelay)
|
||||
codexrelay.Leave()
|
||||
o := gateway.ServedBy()
|
||||
if !o.Running && !gateway.Taken() {
|
||||
if said {
|
||||
fmt.Println(green.Render("●"), "the gateway's port is free: this magpie serves it now")
|
||||
}
|
||||
return
|
||||
}
|
||||
if !said {
|
||||
said = true
|
||||
fmt.Println(amber.Render("!"), standbyLine(o))
|
||||
}
|
||||
time.Sleep(every)
|
||||
}
|
||||
}
|
||||
|
||||
// standbyLine says, once, why magpie serve waits: who has the port.
|
||||
func standbyLine(o gateway.Served) string {
|
||||
who := "another program has " + gateway.URL()
|
||||
if o.Running {
|
||||
who = "another magpie serves the gateway on " + gateway.URL()
|
||||
var about []string
|
||||
if o.Serves != "" {
|
||||
about = append(about, o.Serves)
|
||||
}
|
||||
if o.Version != "" {
|
||||
about = append(about, o.Version)
|
||||
}
|
||||
if o.Pid != 0 {
|
||||
about = append(about, fmt.Sprintf("pid %d", o.Pid))
|
||||
}
|
||||
if len(about) > 0 {
|
||||
who += " (" + strings.Join(about, ", ") + ")"
|
||||
}
|
||||
}
|
||||
return who + ": this one serves it once that one stops, and does nothing till then"
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #4938: the service's magpie serve, started by launchd beside the app
|
||||
// serving the gateway, ran the start-up moves, the plugin host and every
|
||||
// account's model fetch, failed to bind, exited 1 and was started again
|
||||
// 5s later, thousands of times. It now waits for the port before any of
|
||||
// that, and serves once the app has let it go.
|
||||
func TestServeWaitsForTheGatewayBeforeStartingUp(t *testing.T) {
|
||||
var asked atomic.Int32
|
||||
app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/" {
|
||||
asked.Add(1)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"name":"magpie","version":"0.1.2770","pid":4242,"serves":"app","window":true}`))
|
||||
}))
|
||||
defer app.Close()
|
||||
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(app.URL, "http://"))
|
||||
|
||||
wasEvery, wasStartUp := gatewayFreeEvery, startUp
|
||||
gatewayFreeEvery = 20 * time.Millisecond
|
||||
started := make(chan struct{})
|
||||
// the moves would be followed by serving: the test ends the run there
|
||||
startUp = func() {
|
||||
close(started)
|
||||
runtime.Goexit()
|
||||
}
|
||||
t.Cleanup(func() { gatewayFreeEvery, startUp = wasEvery, wasStartUp })
|
||||
|
||||
ended := make(chan struct{})
|
||||
go func() {
|
||||
defer close(ended)
|
||||
_ = run([]string{"serve"})
|
||||
}()
|
||||
|
||||
// the app is asked who serves, and asked again: magpie serve waits
|
||||
deadline := time.After(30 * time.Second)
|
||||
for asked.Load() < 3 {
|
||||
select {
|
||||
case <-started:
|
||||
t.Fatal("magpie serve ran the start-up moves while another magpie served the gateway")
|
||||
case <-deadline:
|
||||
t.Fatalf("the magpie serving was asked %d times in 30s", asked.Load())
|
||||
case <-time.After(5 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
t.Fatal("magpie serve ran the start-up moves while another magpie served the gateway")
|
||||
default:
|
||||
}
|
||||
|
||||
// the app quits: the port is free, and magpie serve goes on to serve
|
||||
app.Close()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("magpie serve didn't start up once the port was free")
|
||||
}
|
||||
<-ended
|
||||
}
|
||||
|
||||
// Only magpie serve for the gateway waits: --web shows the gateway another
|
||||
// magpie serves, and a mistyped flag is refused at once, not after the
|
||||
// app has quit.
|
||||
func TestPlainServe(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
args []string
|
||||
want bool
|
||||
}{
|
||||
{nil, true},
|
||||
{[]string{"--tls-cert", "c.pem", "--tls-key", "k.pem"}, true},
|
||||
{[]string{"--tls-cert=c.pem", "--tls-key=k.pem"}, true},
|
||||
{[]string{"--web"}, false},
|
||||
{[]string{"--web=127.0.0.1:3430"}, false},
|
||||
{[]string{"--tls-cert=c.pem", "--web"}, false},
|
||||
{[]string{"--lan"}, false},
|
||||
{[]string{"web"}, false},
|
||||
} {
|
||||
if got := plainServe(c.args); got != c.want {
|
||||
t.Errorf("plainServe(%q) = %v, want %v", c.args, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,10 @@ import (
|
||||
// been seen to keep, as `make dev`'s handover waits.
|
||||
var handedOffDrain = 15 * time.Minute
|
||||
|
||||
// HandedOffDrain is handedOffDrain: the app that handed the gateway over
|
||||
// quits by then and a little after, whatever holds it up (gui.quitBy).
|
||||
func HandedOffDrain() time.Duration { return handedOffDrain }
|
||||
|
||||
// shortDrain is how long the gateway's end waits for its requests when
|
||||
// nothing serves the port after it: a quit, or a restart that waits.
|
||||
var shortDrain = 2 * time.Second
|
||||
|
||||
+3
-2
@@ -563,8 +563,9 @@ func Run(version string, showMain bool, link string) error {
|
||||
}
|
||||
}
|
||||
// a set kept in a file of the user's (~/.agents/AGENTS.md) is
|
||||
// edited outside magpie: the agents get each change
|
||||
library.KeepLinked(30 * time.Second)
|
||||
// edited outside magpie: the agents get each change, until this
|
||||
// one has handed the gateway to the new version (#4938)
|
||||
library.KeepLinked(backendCtx, 30*time.Second)
|
||||
}()
|
||||
|
||||
// before the item is made, which starts as hidden as AppKit kept it
|
||||
|
||||
@@ -202,6 +202,10 @@ func (ho *handover) run() {
|
||||
}
|
||||
ho.offer.Withdraw()
|
||||
handedOver.Store(true)
|
||||
// and is gone by the end of its drain and a little after, whatever
|
||||
// holds its quit up: the copy an update left lived on hidden for
|
||||
// three hours in #4938, writing beside the new one
|
||||
quitBy(gateway.HandedOffDrain() + quitGrace)
|
||||
log.Printf("update: magpie %s (pid %d) serves the gateway now; this one finishes its requests and quits", c.Hello.Version, c.Hello.PID)
|
||||
if onHandedOver != nil {
|
||||
onHandedOver()
|
||||
@@ -216,6 +220,31 @@ func (ho *handover) run() {
|
||||
quit()
|
||||
}
|
||||
|
||||
// quitGrace is how long past the gateway's drain a magpie that handed it
|
||||
// over has to quit (quitBy), for what its end flushes; exitNow is
|
||||
// os.Exit, which tests stand in for.
|
||||
var (
|
||||
quitGrace = 3 * time.Minute
|
||||
exitNow = os.Exit
|
||||
)
|
||||
|
||||
// quitDeadline is the deadline quitBy set, nil before a handover.
|
||||
var quitDeadline atomic.Pointer[time.Timer]
|
||||
|
||||
// quitBy exits the process after d unless it has ended by then: a
|
||||
// magpie that handed the gateway over is hidden, serves nothing, and has
|
||||
// nothing left for anyone, and its quit waiting on something that never
|
||||
// comes left it running for hours (#4938).
|
||||
func quitBy(d time.Duration) {
|
||||
t := time.AfterFunc(d, func() {
|
||||
log.Printf("update: still running %s after handing the gateway over; exiting", d)
|
||||
exitNow(0)
|
||||
})
|
||||
if old := quitDeadline.Swap(t); old != nil {
|
||||
old.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// fallbackWait is how long a handover given up waits for the requests in
|
||||
// flight before restarting as before: the drain a handed-over gateway
|
||||
// gives them (gateway.handedOffDrain).
|
||||
|
||||
@@ -65,7 +65,13 @@ func handoverSandbox(t *testing.T, up string) *gateway.Server {
|
||||
}
|
||||
startExe = exe
|
||||
handoverHost.Store(true)
|
||||
oldExit := exitNow
|
||||
exitNow = func(int) { t.Error("the magpie that handed over was made to exit before its deadline") }
|
||||
t.Cleanup(func() {
|
||||
if d := quitDeadline.Swap(nil); d != nil {
|
||||
d.Stop()
|
||||
}
|
||||
exitNow = oldExit
|
||||
endBackend()
|
||||
serving.Wait()
|
||||
backendCtx, endBackend = context.WithCancel(context.Background())
|
||||
@@ -215,6 +221,10 @@ func TestRestartHandsTheGatewayOver(t *testing.T) {
|
||||
if !handedOver.Load() {
|
||||
t.Fatal("the new one serves, and this one doesn't know it handed over")
|
||||
}
|
||||
// and is gone by the end of its drain, whatever holds its quit up (#4938)
|
||||
if quitDeadline.Load() == nil {
|
||||
t.Fatal("the magpie that handed over has no deadline to quit by")
|
||||
}
|
||||
// the old one keeps its stream past the 2s an ordinary end gives
|
||||
// requests (gateway.shortDrain), and so doesn't quit yet
|
||||
select {
|
||||
@@ -324,3 +334,28 @@ func eventually2(t *testing.T, most time.Duration, what string, ok func() bool)
|
||||
}
|
||||
t.Fatal(what)
|
||||
}
|
||||
|
||||
// #4938: the copy an update left, hidden, lived on for three hours
|
||||
// beside the new version, its loops writing and fetching, because its
|
||||
// quit waited on something that never came. Past its drain and a little
|
||||
// more it exits, whatever holds the quit up.
|
||||
func TestHandedOverQuitsByItsDeadline(t *testing.T) {
|
||||
oldExit := exitNow
|
||||
exited := make(chan int, 1)
|
||||
exitNow = func(code int) { exited <- code }
|
||||
t.Cleanup(func() {
|
||||
if d := quitDeadline.Swap(nil); d != nil {
|
||||
d.Stop()
|
||||
}
|
||||
exitNow = oldExit
|
||||
})
|
||||
quitBy(20 * time.Millisecond)
|
||||
select {
|
||||
case code := <-exited:
|
||||
if code != 0 {
|
||||
t.Fatalf("exited %d, want 0", code)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the magpie that handed over never exited")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +215,10 @@ func (h *host) lighten() {
|
||||
<-h.ready
|
||||
var ticks [2]int // the main window's, the panel's
|
||||
for range time.Tick(lightEvery) {
|
||||
on := settings.Load().LightweightOn()
|
||||
// a magpie that handed the gateway to the new version lets its
|
||||
// hidden pages go as lightweight mode does: their polls kept it
|
||||
// asking for usage beside the new one while it drained (#4938)
|
||||
on := settings.Load().LightweightOn() || handedOver.Load()
|
||||
var let []*application.WebviewWindow
|
||||
h.winMu.Lock()
|
||||
application.InvokeSync(func() {
|
||||
|
||||
@@ -190,7 +190,9 @@ func (h *host) watchAlerts() {
|
||||
title, body := turnDoneText(trayLang(settings.Load().Lang, systemLang), agentName(t.Agent), t)
|
||||
n.sendAs(turnNotice, title, body)
|
||||
}
|
||||
provider.WatchQuotas(context.Background(), wake, func(a provider.QuotaAlert) {
|
||||
// until this one has handed the gateway to the new version,
|
||||
// which alerts from then on (#4938)
|
||||
provider.WatchQuotas(backendCtx, wake, func(a provider.QuotaAlert) {
|
||||
s := settings.Load()
|
||||
title, body := alertText(trayLang(s.Lang, systemLang), a, s.BalanceAlert, s.QuotaLeft, time.Now())
|
||||
n.send(title, body)
|
||||
|
||||
@@ -123,6 +123,10 @@ func (h *host) watchTrayUsage() {
|
||||
select {
|
||||
case <-wake:
|
||||
case <-time.After(next):
|
||||
case <-backendCtx.Done():
|
||||
// handed the gateway to the new version, whose icon
|
||||
// shows the usage now: this one's is hidden (#4938)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -144,7 +144,10 @@ func (u *updater) start() {
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(5 * time.Second) // let the app settle first
|
||||
for {
|
||||
// until this one has handed the gateway to the new version: the
|
||||
// copy an update left finishing its requests checks for, and
|
||||
// restarts into, nothing (#4938)
|
||||
for backendCtx.Err() == nil {
|
||||
u.mu.Lock()
|
||||
last := u.asked
|
||||
u.mu.Unlock()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -693,10 +694,15 @@ func SyncLinked() (*Result, error) {
|
||||
return changeInstructions(func(*Library) error { return nil })
|
||||
}
|
||||
|
||||
// KeepLinked runs SyncLinked, and Woken, every interval, for as long as
|
||||
// the app runs.
|
||||
func KeepLinked(interval time.Duration) {
|
||||
for {
|
||||
// KeepLinked runs SyncLinked, and Woken, every interval, until ctx ends:
|
||||
// the app's backend, which ends once it has handed the gateway to the
|
||||
// new version (gui/handover.go). Before, it ran for as long as the
|
||||
// process did, and the copy an update left finishing its requests went
|
||||
// on writing the agents' files beside the new one (#4938).
|
||||
func KeepLinked(ctx context.Context, interval time.Duration) {
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
for ctx.Err() == nil {
|
||||
if res, err := SyncLinked(); err != nil {
|
||||
log.Println("library: linked instructions:", err)
|
||||
} else if res != nil {
|
||||
@@ -706,6 +712,9 @@ func KeepLinked(interval time.Duration) {
|
||||
}
|
||||
// what was ticked for a stopped WSL distro's agents, once it runs
|
||||
keepWoken()
|
||||
time.Sleep(interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A set can be kept in a file of the user's own, ~/.agents/AGENTS.md that
|
||||
@@ -164,3 +166,41 @@ func TestLinkedSetCarried(t *testing.T) {
|
||||
t.Errorf("a carried file was taken: %q", l.instrSet("agents").File)
|
||||
}
|
||||
}
|
||||
|
||||
// #4938: the copy of the app an update left finishing its requests went
|
||||
// on syncing the linked sets into the agents' files every 30s, beside the
|
||||
// new version, for hours. KeepLinked keeps the agents up with the linked
|
||||
// file while its context lasts, and returns once it ends.
|
||||
func TestKeepLinkedEndsWithItsContext(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
cx := filepath.Join(h, ".codex/AGENTS.md")
|
||||
shared := filepath.Join(h, ".agents/AGENTS.md")
|
||||
write(t, shared, "Shared rules.\n")
|
||||
ok(t)(SaveInstructions(InstructionsChange{Agents: []string{"codex"}}))
|
||||
ok(t)(SaveInstructions(InstructionsChange{Create: &InstrSet{ID: "agents", Name: "Everyone", File: "~/.agents/AGENTS.md"}}))
|
||||
// the file as it is now, for the loop's first look to tell a change
|
||||
if _, err := SyncLinked(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
KeepLinked(ctx, 10*time.Millisecond)
|
||||
}()
|
||||
// a change made in the file reaches the agents while it runs
|
||||
write(t, shared, "Shared rules, changed.\n")
|
||||
for deadline := time.Now().Add(30 * time.Second); !strings.Contains(read(t, cx), "changed"); {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the linked file's change never reached codex")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("KeepLinked went on after its context ended")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user