Files
magpie/internal/gui/gatewaypause.go
T
yetone e8fbee60ea gui: pause the gateway without quitting magpie (me2seeks on X)
Disconnect and quit was the only way to stop the gateway, and it quits
magpie too. Pause does the same without the quit, from the tray's Pause
Gateway (Resume Gateway while paused), Settings › General › Gateway
(On/Paused, the app's only) and the Gateway page's Resume gateway, all
through POST /api/gateway/pause.

- Pause disconnects each connected agent as its row's Disconnect does
  (its own settings put back), keeps their ids in gateway-paused.json in
  the config folder, and stops the listener with requests in flight
  drained. An agent that can't be disconnected keeps the gateway serving,
  those before it connected again, and is named in the status line.
- While paused, serveGatewayLocked serves nothing: not the 15s watch, a
  port change nor a handover; a magpie started again stays paused. A
  pause file that can't be read counts as paused.
- Resume serves again and connects the agents the pause disconnected.
  A port held by something else keeps the pause and says what holds it.
  The Gateway page's Start/Restart, connecting an agent and picking one
  of magpie's models for it resume too.
- quitask's wired list and the pause share wiredOf.
- Strings in en, zh, zh-TW, ja, de. gui-shell.md documents it.

Run (mote was unreachable for the later runs; the Windows box instead):
- mote, before the rebase: go vet ./internal/gui; go test -run
  'TestGatewayPause|TestGatewayResumes|TestTray|TestGatewayFix|TestQuit'
  ./internal/gui: ok.
- at this tree on b46f23ffa: win-run go vet ./internal/gui ok; wsl-run
  go vet -tags nogui ./internal/gui ok; gofmt -l clean.
- win-run go test -count=1 ./internal/gui: the pause and tray tests ok;
  8 reds, each the same on origin/main d4b4a188e run alone on Windows
  and filed (#4115 %AppData% import rows, #5928 ~\ paths, #2107/#3649
  TestGatewayHeldByAContainer).
- wsl-run GUI (chromium + webkit): gateway-pause (5 languages x 1000/420),
  settings-general, gateway-takeover, i18n-keys, i18n-en-no-cjk: 51/52.
  The red is gateway-takeover webkit en's dark-mode case, red 1 of 2 on
  untouched origin/main too: #5942.
- rebased on 401187300: win-run go test -run 'Budget|TestGatewayPause|
  TestGatewayResumes|TestTray|TestQuit' ./internal/gui ok; wsl-run go vet
  -tags nogui ./internal/gui ok; gofmt clean. darwin vet not rerun after
  the rebase (mote refused SSH).

Broken by hand: serveGatewayLocked without its pausedNow check, and the
rollback's reconnect skipped: TestGatewayPauseAndResume ("served while
paused") and TestGatewayPauseRollsBack ("codex not connected again")
went red; green again restored.

Not tried: the real app's tray on a desktop, a real agent's config
round-trip (the Go tests fake the agents; Disconnect/connect are the
rows' own code), an agent wired from the CLI while the app is paused
(it doesn't resume), the whole GUI suite, the full Go suite (started after the tag).
2026-11-10 19:36:24 +08:00

243 lines
7.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gui
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"sync"
"sync/atomic"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/settings"
)
// Pausing the gateway (me2seeks on X): told the gateway runs while magpie
// does, the user quit magpie with Disconnect and quit to have it stopped,
// and asked for a switch. Pause, from the tray's menu, Settings › General
// or the Gateway page, does what Disconnect and quit does without the
// quit: each connected agent is disconnected as its row's Disconnect does
// (its own settings put back, so it works without magpie), then the
// gateway stops listening. Resume serves it again and connects the agents
// that were connected at the pause. The pause is kept in
// gateway-paused.json, this computer's alone (no backup or sync carries
// it), so a magpie started again, or one updated, stays paused, and
// nothing starts the gateway meanwhile (serveGatewayLocked): not the
// watch for a gateway gone, a port change, the Gateway page's Start
// (which resumes) nor a handover. Connecting an agent, or picking one of
// magpie's models for it, while paused resumes: the agent would otherwise
// point at a gateway that isn't there, the 502s of quitask.go. It is the
// app's own: magpie web is a server whose job is the gateway.
// pausable says this process may pause its gateway: the app's (Run).
var pausable atomic.Bool
// pauseMu keeps one pause or resume at a time.
var pauseMu sync.Mutex
// onPaused tells the tray's menu the gateway was paused or resumed; set
// by the process that has the tray.
var onPaused func()
// pauseFile is gateway-paused.json: the agents connected at the pause,
// which a resume connects again.
type pauseFile struct {
Agents []string `json:"agents"`
}
func pausePath() string { return filepath.Join(settings.Dir(), "gateway-paused.json") }
// gatewayPaused says whether this process's gateway is paused, and the
// agents to connect again on resume. A file that is there but can't be
// read or parsed is a pause whose agents aren't known: only magpie writes
// it, and a gateway started on a bad read would serve agents put back on
// their own settings.
func gatewayPaused() (bool, []string) {
if !pausable.Load() {
return false, nil
}
b, err := os.ReadFile(pausePath())
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
var f pauseFile
if err == nil {
err = json.Unmarshal(b, &f)
}
if err != nil {
log.Println("gateway pause:", err)
}
return true, f.Agents
}
// pausedNow is gatewayPaused's first answer.
func pausedNow() bool { p, _ := gatewayPaused(); return p }
// pauseJSON is how a pause or resume went: Paused is the state after it;
// Agent and Error say which agent couldn't be disconnected, or connected
// again, and why; Fix is a resume's gateway that couldn't listen.
type pauseJSON struct {
Paused bool `json:"paused"`
Agents []string `json:"agents,omitempty"`
Agent string `json:"agent,omitempty"`
Error string `json:"error,omitempty"`
Fix *gatewayFixJSON `json:"fix,omitempty"`
}
// pause hooks, vars for the tests: the agents connected now, whether one
// is, and an agent's Disconnect and connect.
var (
pauseWired = func() []*agent.Agent { return wiredOf(agent.Detected()) }
pauseIsWired = func(a *agent.Agent) bool { return a.Wired() }
pauseDisconnect = func(a *agent.Agent) error { return a.Disconnect() }
pauseConnect = func(a *agent.Agent) error { _, err := a.ConnectHow(); return err }
pauseFind = agent.Find
)
// wiredOf is those of as with magpie in their config.
func wiredOf(as []*agent.Agent) []*agent.Agent {
var out []*agent.Agent
for _, a := range as {
if a.Wired() {
out = append(out, a)
}
}
return out
}
// pauseGateway disconnects every connected agent and stops the gateway
// this process serves. An agent that can't be disconnected leaves the
// gateway serving, with those disconnected before it connected again.
func pauseGateway() pauseJSON {
pauseMu.Lock()
defer pauseMu.Unlock()
if p, ids := gatewayPaused(); p {
return pauseJSON{Paused: true, Agents: ids}
}
if !pausable.Load() {
return pauseJSON{Error: "only the app pauses its gateway"}
}
var done []*agent.Agent
ids := []string{}
for _, a := range pauseWired() {
if err := pauseDisconnect(a); err != nil {
for _, b := range done {
if err := pauseConnect(b); err != nil {
log.Printf("gateway pause: %s not connected again: %v", b.ID, err)
}
}
return pauseJSON{Agent: a.Name, Error: err.Error()}
}
done = append(done, a)
ids = append(ids, a.ID)
}
b, _ := json.Marshal(pauseFile{Agents: ids})
err := os.MkdirAll(filepath.Dir(pausePath()), 0o755)
if err == nil {
err = edit.WriteAtomic(pausePath(), b)
}
if err != nil {
for _, b := range done {
_ = pauseConnect(b)
}
return pauseJSON{Error: err.Error()}
}
gatewayMu.Lock()
stopServedLocked()
gatewayMu.Unlock()
log.Printf("gateway: paused; %d agents disconnected", len(ids))
if onPaused != nil {
onPaused()
}
return pauseJSON{Paused: true, Agents: ids}
}
// stopServedLocked stops the gateway this process serves and waits until
// it has; under gatewayMu.
func stopServedLocked() {
gw := served.Load()
if gw == nil {
return
}
if servedRun.stop != nil {
servedRun.stop()
<-servedRun.done
}
served.CompareAndSwap(gw, nil)
}
// resumeGateway serves the gateway again and connects the agents the pause
// disconnected. A gateway that can't listen keeps the pause, with what
// holds the port. An agent that can't be connected is said; the rest are.
func resumeGateway() pauseJSON {
pauseMu.Lock()
defer pauseMu.Unlock()
p, ids := gatewayPaused()
if !p {
return pauseJSON{}
}
if err := os.Remove(pausePath()); err != nil && !errors.Is(err, fs.ErrNotExist) {
return pauseJSON{Paused: true, Agents: ids, Error: err.Error()}
}
gatewayMu.Lock()
out := startHere()
gatewayMu.Unlock()
if !out.OK {
b, _ := json.Marshal(pauseFile{Agents: ids})
_ = edit.WriteAtomic(pausePath(), b)
return pauseJSON{Paused: true, Agents: ids, Fix: &out}
}
res := pauseJSON{Agents: ids}
var errs []error
for _, id := range ids {
a, err := pauseFind(id)
if err != nil || pauseIsWired(a) {
continue // gone since, or connected by hand meanwhile
}
if err := pauseConnect(a); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", a.Name, err))
if res.Agent == "" {
res.Agent = a.Name
}
}
}
if len(errs) > 0 {
res.Error = errors.Join(errs...).Error()
}
log.Printf("gateway: resumed; %d agents connected again", len(ids)-len(errs))
if onPaused != nil {
onPaused()
}
return res
}
// resumeOnWire resumes a paused gateway once an agent was put on it.
func resumeOnWire(a *agent.Agent) {
if a != nil && pausedNow() && pauseIsWired(a) {
resumeGateway()
}
}
// gatewayPauseRoutes: POST /api/gateway/pause {"on": true|false}.
func gatewayPauseRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/gateway/pause", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
On bool `json:"on"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if in.On {
writeJSON(rw, pauseGateway())
} else {
writeJSON(rw, resumeGateway())
}
})
}