Files
magpie/internal/tui/gateway.go
T
yetoneandrecih bfbc22e190 claude: an idle session is saved whenever the gateway ends or hands over (#7017)
recih: after magpie web restarted (an update's re-exec, or Quit and
start again) the next Claude turn replayed the whole conversation
instead of resuming its session. Web.Wait closed the page server and
never drained the gateway, so abortAll never ran and claude-shelf.json
was never written.

- Web.Wait drains the gateway (Close: page server, then stopServing)
  before the plugin hosts end and before update.Reexec.
- Desktop quit: OnShutdown calls stopServing.
- Signals: web, serve, the TUI and the app register their gateway with
  the signal handler (stopGatewayOnSignal). SIGINT, SIGTERM and SIGHUP
  drain it, sessions saved, before magpie dies of the signal. The return
  path waits for a drain the signal already started. The TUI and the
  app take SIGINT/SIGTERM themselves, but SIGHUP (the terminal closing)
  stays with magpie. runTUI, runGUI and runPanel now register
  tui.StopGateway and gui.StopServing for it (added in review).
- Handover: the successor answered a Claude turn before the predecessor
  had saved its shelf. The predecessor now serves
  GET /_magpie/claude-ready on its callback socket, answered once
  abortAll has run. A Claude turn on the successor waits for it.
  - The predecessor saves only after every request it holds has ended,
    of any provider, which can take up to handedOffDrain (15m).
  - Added in review: the wait is bounded by predecessorWait (90s, inside
    Claude Code's ten minutes for a reply). Past that, the turn goes on
    as before, as a replay, and no later turn waits
    (errPredecessorSlow).
  - loadShelf still reads a shelf written later, at the next turn with
    no session found.
  - A predecessor without the endpoint (404) keeps the old race.
- Sweep: sweepSessions removed session files older than idleLongest.
  That included a session kept for hours past a quota 429
  (keepForReset) and one moving from the shelf to a run.
  - Those are now protected: the shelf file, the in-memory shelf, the
    resuming set and active runs.
  - An unreadable shelf skips the sweep.
  - loadShelf and the sweep's snapshot are serialised by shelfFileMu.
    The bridge lock is held only for the shelf maps, never across the
    file's reads (added in review: the branch read the file under b.mu,
    which every Claude turn takes).

From recih's branch fix/web-restart-session-persistence (7a0261cc1,
fab0ea651), with the review's follow-ups. Not taken from the branch:
the .github/workflows/test.yml change (contributors.md: .github/ stops
for the maintainer), and the test-flake commits in other packages,
which are separate goals.

Red on origin/main 48fffb60c (the branch's tests, trimmed to what
compiles there), on mica:
- TestWebShutdownKeepsClaudeSession quit and restart: no
  claude-shelf.json ("Web.Wait did not keep the idle Claude session").
  Restart is a real Unix re-exec of the test binary with a fake claude.
- TestDesktopShutdownDrainsGateway.
- TestClaudeHandoverWaitsForSavedSession: "the successor answered
  before the predecessor saved its session".
- TestClaudeSweepKeepsQuotaSessions: 5 of 5 subtests swept the kept
  session.

Broken by hand: with runTUI's, runGUI's and runPanel's
stopGatewayOnSignal defer removed, TestHangupDrainsTheGatewayFirst
fails tui, app and panel ("SIGHUP never drained the gateway"), on
mote.
Run on mote at e4506887c (this stack on origin/main 7300be4d0):
go test -timeout 45m ./...: 101 packages ok, 2 FAIL, both open issues
that fail the same at 7300be4d0 on mote, where an ssh session forwards
127.0.0.1:3425 to a real magpie: internal/cli's
TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
TestUpdateFindsAMagpieThatWroteNoRecord (#6223), internal/gui's
TestLaneLimitRoutes (#5150). On mica: gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go
build, GOOS=linux go build -tags nogui, GOOS=windows go build all ok.
go test -race -count=2 of the new and touched tests in internal/gateway,
gui, plugin, tui ok on mote.
Not tried: a real desktop app quit or update with a real Claude
account; SIGHUP from a real terminal closing.

Rebased since. At dc507aefd on mote: go vet (darwin, GOOS=linux
-tags nogui, windows) ok; go test of internal/cli, tui, plugin,
gateway, gui, claudebridge ok but for the same #6223 and #5150 reds.
At 939fe31b6 (on origin/main 78b6d47cc) on mote: gofmt -l clean, the
three vets ok, the stack's tests with TestClaude* and
TestCoreScriptBudget ok in all six packages. Pushed on b400566f9 after
a clean rebase; the commits between touch no Go file this stack does.

Co-authored-by: recih <240406+recih@users.noreply.github.com>
2026-11-18 23:06:38 +08:00

111 lines
3.0 KiB
Go

package tui
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// The terminal serves the gateway while it is open, as the app does, when
// no magpie has it: in WSL with only magpie tui, the agents it connected to
// magpie asked an address nothing listened at, and Claude Code said
// ECONNREFUSED (gnayiab on X). Another magpie that has it (the app, magpie
// web, magpie serve) keeps it, and this one takes it up once that one is
// gone.
// gw is who serves the gateway, for the status line.
var gw struct {
here atomic.Bool // this process serves it
err atomic.Pointer[string] // why it couldn't, "" or nil when it could
}
// serving ends the gateway this terminal serves and waits for it to
// drain, while Run runs.
var serving atomic.Pointer[func()]
// StopGateway ends the gateway the terminal serves, its idle Claude
// sessions saved for the next magpie, and returns once it has drained: what
// the terminal closing (SIGHUP, which bubbletea doesn't handle) runs before
// magpie dies of it. Nothing when the terminal serves none.
func StopGateway() {
if f := serving.Load(); f != nil {
(*f)()
}
}
// gatewayWatch is how often the terminal looks for a gateway gone.
var gatewayWatch = 15 * time.Second
// serveGateway serves the gateway here until ctx ends whenever no magpie
// answers at its address, and returns a wait for the one it serves to have
// stopped.
func serveGateway(ctx context.Context) (wait func()) {
var wg sync.WaitGroup
try := func() {
if gw.here.Load() || gateway.Running() {
return
}
s := gateway.New()
up := make(chan error, 1)
gw.here.Store(true)
wg.Add(1)
go func() {
defer wg.Done()
err := s.ListenAndServe(ctx)
gw.here.Store(false)
if err != nil && ctx.Err() == nil {
msg := err.Error()
gw.err.Store(&msg)
}
up <- err
}()
// listening, or refused the port, in a moment
for i := 0; i < 20 && !gateway.Running(); i++ {
select {
case <-up:
return
case <-time.After(50 * time.Millisecond):
}
}
if gateway.Running() {
gw.err.Store(nil)
}
}
try()
wg.Add(1)
go func() {
defer wg.Done()
t := time.NewTicker(gatewayWatch)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
try()
}
}
}()
return wg.Wait
}
// gatewayStatus is the status line's word on the gateway when it has
// nothing else to say: served here, or why agents can't reach it.
func gatewayStatus() string {
if gw.here.Load() {
return sMuted.Render("● " + trf("gateway %s · served while magpie tui is open", gateway.URL()))
}
if e := gw.err.Load(); e != nil && *e != "" {
return sBad.Render("✗ ") + sText.Render(trf("gateway not running: %s", *e))
}
return ""
}
// gatewayGoneNote is said as the terminal quits having served the gateway.
func gatewayGoneNote() string {
return tr("magpie: the gateway stopped with magpie tui; agents connected to magpie reach it while magpie tui, magpie web or magpie serve runs")
}