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 on2b067434d): - 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/main0c3163804: 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/main0c3163804: 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 on6f3dfc282, 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).
178 lines
5.9 KiB
Go
178 lines
5.9 KiB
Go
package gui
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/agent"
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/codexrelay"
|
|
"github.com/yetone/magpie/internal/filememo"
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// served is the gateway this process serves, nil while another magpie
|
|
// has it.
|
|
var served atomic.Pointer[gateway.Server]
|
|
|
|
// backendCtx ends the gateway this process serves (stopServing).
|
|
var backendCtx, endBackend = context.WithCancel(context.Background())
|
|
|
|
// serving is the gateway this process serves, until it has finished.
|
|
var serving sync.WaitGroup
|
|
|
|
// stopServing stops this process's gateway taking requests and returns
|
|
// once those in flight have finished.
|
|
func stopServing() {
|
|
endBackend()
|
|
serving.Wait()
|
|
}
|
|
|
|
// startBackend starts what serves the page and the agents: the gateway,
|
|
// unless another magpie has it (then that one serves and this one only
|
|
// shows its status, and gw is nil — until that one is gone: a magpie left
|
|
// running from before an update, a magpie serve in a terminal), and the
|
|
// model lists kept warm.
|
|
func startBackend() (gw *gateway.Server) {
|
|
gateway.Window = true // the routing this process serves is shown on its page
|
|
gw = serveGateway()
|
|
go watchGateway(backendCtx, gatewayWatch)
|
|
// the usage log parsed now, not when the tray panel first asks for
|
|
// today's calls (CyberCaius)
|
|
go func() {
|
|
// its files looked at once a second, as the warm-up's (#1665)
|
|
defer filememo.Hold()()
|
|
usage.ReadAhead()
|
|
}()
|
|
// Codex's background app-server, restarted when it has the list from
|
|
// before a change and no codex session is on it (luci)
|
|
go agent.KeepCodexDaemonCurrent(backendCtx)
|
|
// the compactions magpie made in Codex's threads written as Codex's
|
|
// own, so a thread goes on when Codex talks to OpenAI itself
|
|
go agent.KeepCodexRolloutsPortable(backendCtx)
|
|
// Model lists are fetched, never compiled in: whatever the agents can see
|
|
// comes from the models.dev catalog plus each vendor's own /models answer.
|
|
// Keep both halves warm without making the user click anything.
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
if catalog.Stale() {
|
|
if err := catalog.Sync(ctx); err != nil {
|
|
log.Println("catalog:", err)
|
|
}
|
|
}
|
|
cancel()
|
|
// A signed-in agent's list exists only at the vendor; fill it in the
|
|
// first time so the picker never shows a stale snapshot.
|
|
provider.FetchNew(20 * time.Second)
|
|
// lists an older magpie wrote into agents' files, without what
|
|
// it has learnt since (context windows, providers added)
|
|
agent.SyncCatalog()
|
|
// and fetched again each day it stays open, for new models' prices
|
|
catalog.KeepFresh()
|
|
}()
|
|
return gw
|
|
}
|
|
|
|
// gatewayWatch is how often a magpie without the gateway looks for it gone.
|
|
const gatewayWatch = 15 * time.Second
|
|
|
|
// watchGateway takes the gateway up once the magpie that had it is gone,
|
|
// looking every so often until ctx ends: a watch that outlived it would
|
|
// start a gateway after this one has stopped serving.
|
|
func watchGateway(ctx context.Context, every time.Duration) {
|
|
t := time.NewTicker(every)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
}
|
|
gatewayMu.Lock()
|
|
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()
|
|
}
|
|
}
|
|
|
|
// takenSaid: the log has said the gateway's port is taken by one that
|
|
// doesn't answer, said once until it is free again.
|
|
var takenSaid atomic.Bool
|
|
|
|
// gatewayMu keeps one start of the gateway here at a time: the watch's,
|
|
// a restart's, a take-over's (takeover.go).
|
|
var gatewayMu sync.Mutex
|
|
|
|
// servedRun ends the gateway this process serves, and is closed once it
|
|
// has, for a restart; under gatewayMu.
|
|
var servedRun struct {
|
|
stop context.CancelFunc
|
|
done chan struct{}
|
|
}
|
|
|
|
// serveGateway starts the gateway here when no magpie has it: the one
|
|
// started, or nil.
|
|
func serveGateway() *gateway.Server {
|
|
gatewayMu.Lock()
|
|
defer gatewayMu.Unlock()
|
|
return serveGatewayLocked()
|
|
}
|
|
|
|
func serveGatewayLocked() *gateway.Server {
|
|
// handing over, the one there is this one's predecessor, which lets go
|
|
// once this one listens beside it
|
|
// so is the one that handed this one its socket, still finishing its
|
|
// requests on it (gui/handover.go)
|
|
if !gateway.Handover && !gateway.Inherited() {
|
|
// 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 !otherServes(o) {
|
|
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
|
|
// second listen only fails (K.Liu on Discord: magpie web beside
|
|
// the service logged "bind: address already in use")
|
|
if gateway.Taken() {
|
|
if !takenSaid.Swap(true) {
|
|
log.Printf("gateway: %s is taken but doesn't answer as magpie yet; this magpie serves the gateway once it is free", gateway.URL())
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
takenSaid.Store(false)
|
|
gatewayOther.Store(nil)
|
|
gw := gateway.New()
|
|
served.Store(gw)
|
|
serving.Add(1)
|
|
ctx, stop := context.WithCancel(backendCtx)
|
|
done := make(chan struct{})
|
|
servedRun.stop, servedRun.done = stop, done
|
|
go func() {
|
|
defer serving.Done()
|
|
defer close(done)
|
|
defer stop()
|
|
if err := gw.ListenAndServe(ctx); err != nil {
|
|
log.Println("gateway:", err)
|
|
served.CompareAndSwap(gw, nil) // another took the port first
|
|
}
|
|
}()
|
|
return gw
|
|
}
|