From bfbc22e190edffc3739a9ca80b0c27e6ee382e2d Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 18 Nov 2026 20:04:49 +0800 Subject: [PATCH] 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> --- docs/subsystems/claude-subscription-bridge.md | 30 +++- docs/subsystems/gui-shell.md | 42 +++++ internal/cli/gui_on.go | 6 + internal/cli/main.go | 5 + internal/cli/providers_cli.go | 4 + internal/cli/signal_gateway.go | 29 +++ internal/cli/signal_gateway_test.go | 53 ++++++ internal/cli/signal_hangup_test.go | 66 +++++++ internal/cli/signals.go | 29 ++- internal/cli/web_cli.go | 2 + .../gateway/claude_handover_resume_test.go | 168 ++++++++++++++++++ internal/gateway/claude_persist.go | 92 ++++++++-- .../gateway/claude_recovery_sweep_test.go | 92 ++++++++++ internal/gateway/claude_subscription.go | 42 ++++- internal/gateway/gateway.go | 13 +- internal/gateway/handover.go | 78 +++++++- internal/gui/app.go | 1 + internal/gui/backend.go | 10 ++ internal/gui/shutdown_gateway_test.go | 56 ++++++ internal/gui/web.go | 15 +- internal/gui/web_shutdown_unix_test.go | 165 +++++++++++++++++ internal/tui/gateway.go | 14 ++ internal/tui/tui.go | 3 + 23 files changed, 976 insertions(+), 39 deletions(-) create mode 100644 internal/cli/signal_gateway.go create mode 100644 internal/cli/signal_gateway_test.go create mode 100644 internal/cli/signal_hangup_test.go create mode 100644 internal/gateway/claude_handover_resume_test.go create mode 100644 internal/gateway/claude_recovery_sweep_test.go create mode 100644 internal/gui/shutdown_gateway_test.go create mode 100644 internal/gui/web_shutdown_unix_test.go diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 86abd13d8..48f7a3de8 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -1909,8 +1909,17 @@ hold it. turn](#a-run-that-ended-during-a-turn-6528)), and when a saved session is discarded (`removeSession`). `sweepSessions` removes those a stopped gateway left in magpie's own - work folder's project, once older than `idleLongest`; a caller's folder + work folder's project, once older than `idleLongest` plus a minute; a caller's folder is never swept (`clientWorkDir`). + A session still in the persisted shelf, the in-memory shelf, an active run, + or the transfer from shelf to run (`resuming`) is protected. This includes + quota waits longer than an hour. `loadShelf` removes the file and publishes + its entries under `shelfFileMu`, which the sweep's snapshot holds too; + the bridge lock is taken for the shelf alone, never across the file's + reads. An + unreadable or unknown-version shelf skips the destructive sweep. + `TestClaudeSweepKeepsQuotaSessions`, `TestClaudeSweepUnknownShelfLeavesFiles`. + - Claude Code's temp files for the session, the images it was given: `/claude-//` (`claudeTempDir`, not on Windows). They are removed with the session @@ -2251,6 +2260,25 @@ written then). A conversation a client rewrote (`looseTurn`) is not kept, and a run in a turn or parked on tool results at the stop is not either. `TestClaudeIdleRunSurvivesARestart`, `TestClaudeShelfFileUnreadableFallsBackToReplay`. +The successor can accept before the old gateway saves this file. Before +starting a Claude subscription turn, `awaitPredecessorSessions` waits for +`GET /_magpie/claude-ready` on the private callback socket. The old gateway +answers only after `abortAll` has saved and ended its runs, which follows +every request it holds, of any provider. The wait is bounded by +`predecessorWait` (90s, inside Claude Code's ten minutes for a reply): past +it, or on a failed wait, the turn goes on as it did before the wait, a +replay, and no later turn waits (`errPredecessorSlow`, +`TestClaudeHandoverWaitIsBounded`); `loadShelf` still reads a shelf written +later, at the next turn no session is found for. Only a caller gone +returns an error. Other providers and MCP callbacks continue. A removed socket means the old +process has finished; a 404 permits older versions without this endpoint, +whose handover retains the previous race. +`TestClaudeHandoverWaitsForSavedSession` checks the resumed turn; +`TestClaudeHandoverReadiness` and `TestClaudeHandoverReadinessCompatibility` +check readiness, cancellation and older predecessors. Web/serve signal +exits and desktop shutdown now wait for this gateway shutdown too (see +[GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)). + ### A turn refused for the account's limit A turn Anthropic refuses for the account's limit before any of its reply diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 87c8e4b23..572919117 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -1229,6 +1229,48 @@ Windows has no SCM_RIGHTS for a listening socket in this form, and for the gateway to be idle (#577). `make dev` keeps its own handover, a new backend listening beside the old one (`gateway.Handover`, `devBackend`). +Before `magpie web` returns from Quit or re-executes for an update, +`Web.Wait` stops its page server and waits for its own gateway to finish +(`stopServing`). That shutdown saves the idle Claude sessions for the +[next start to resume](claude-subscription-bridge.md#a-restart-to-update), +before the plugin hosts end and the process is replaced. Without the wait, +Web updates skipped the saved-session index and replayed the conversation +on its next turn (recih). A gateway served by another magpie is left alone. +`TestWebShutdownKeepsClaudeSession` exercises Quit and a real Unix re-exec, +then checks that the next turn resumes the session with only its new message. + +The same drain runs on desktop `OnShutdown`, before update installation, +including normal Quit, Windows restart and a failed Unix handover. Web and +`serve` commands register their gateway with the CLI signal handler +(`stopGatewayOnSignal`): SIGINT, SIGTERM and SIGHUP wait for the gateway +before flushing the indexes and preserving the signal's exit status. The +`serve` return path joins a signal already shutting it down, so main cannot +exit or re-exec midway through saving. `stopServing` also prevents the +background watch from starting a gateway after shutdown begins. +`TestSignalWaitsForGatewayShutdown` holds the drain for each signal; +`TestDesktopShutdownDrainsGateway` checks the native callback's ordering +without starting a desktop in a headless test. + +Accepting the handed-over socket is not proof that Claude sessions are +saved. The successor waits on the predecessor's Unix callback endpoint +`GET /_magpie/claude-ready` before serving a Claude subscription turn. It +answers after `abortAll`; other providers and forwarded tool callbacks +continue during the drain. The predecessor saves only once every request +it holds has ended, of any provider, so a turn waits `predecessorWait` +(90s) at most and then goes on, replaying what the shelf would have +resumed, as every turn after it does (`errPredecessorSlow`); a shelf +written later is still read at the next turn no session is found for. A +cancelled wait returns 503 to the caller already gone. A predecessor +without this endpoint (404) keeps the old handover behavior; the ordering +guarantee applies when the predecessor includes this change. + +The terminal closing (SIGHUP) is left to magpie by Wails and bubbletea +(`ownSignals`), so `runGUI`, `runPanel` and `runTUI` register the gateway +they serve with the signal handler (`stopGatewayOnSignal`: +`gui.StopServing`, `tui.StopGateway`), and it drains, the idle Claude +sessions saved, before magpie dies of the signal. +`TestHangupDrainsTheGatewayFirst`. + `magpie update` in a terminal restarts the app the same way (gaubeebangeel on X: an agent the gateway serves ran the update at 4am, and the app ran on as the old version until it was quit and reopened, diff --git a/internal/cli/gui_on.go b/internal/cli/gui_on.go index 0e85f6e2d..1997c4474 100644 --- a/internal/cli/gui_on.go +++ b/internal/cli/gui_on.go @@ -15,6 +15,8 @@ const hasGUI = true // runGUI starts the desktop app, writing its log to a file (startLog). func runGUI(showMain bool, link string) error { startLog("app") + // SIGHUP, which Wails leaves to magpie, drains the gateway first + defer stopGatewayOnSignal(guiStop)() return openApp(showMain, link) } @@ -46,6 +48,7 @@ func runUninstallWindow() error { // of the one already running. func runPanel() error { startLog("panel") + defer stopGatewayOnSignal(guiStop)() // as runGUI's return openPanel() } @@ -67,3 +70,6 @@ var startLog = func(how string) { log.Println("log:", err) } } + +// guiStop is gui.StopServing; a var so tests can stand in for it. +var guiStop = gui.StopServing diff --git a/internal/cli/main.go b/internal/cli/main.go index 9c30ff7d1..845d23cd2 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -275,12 +275,17 @@ func Main(v string) { // runTUI runs the TUI, which quits on Ctrl+C and SIGTERM itself once it // has started; it asks CLIs first, and a signal then ends those. func runTUI() error { + // the terminal closing (SIGHUP) drains the gateway it serves first + defer stopGatewayOnSignal(tuiStop)() return tuiRun(ownSignals) } // tuiRun is tui.Run; a var so tests can stand in for it. var tuiRun = tui.Run +// tuiStop is tui.StopGateway; a var so tests can stand in for it. +var tuiStop = tui.StopGateway + // syncAgentsOnChange sets what a catalog change (a provider or group // saved, a vendor's list fetched anew) does: the model lists agents keep // in files of their own are brought up to date behind the save, which diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index fa59005b5..68748c0cf 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -1790,7 +1790,11 @@ func serve() error { go provider.KeepRemotesUpdated(ctx, version) // the models a Remote magpie's agents are on, as the app follows them go agent.KeepFollowingRemote(ctx, 30*time.Second) + drained := make(chan struct{}) + finish := stopGatewayOnSignal(func() { stop(); <-drained }) err := s.ListenAndServe(ctx) + close(drained) + finish() if exe := follow.restartTo(); exe != "" { // the plugin hosts end, waited for, first, as magpie web's // reexec does (#3285) diff --git a/internal/cli/signal_gateway.go b/internal/cli/signal_gateway.go new file mode 100644 index 000000000..7bdb8b0dc --- /dev/null +++ b/internal/cli/signal_gateway.go @@ -0,0 +1,29 @@ +package cli + +import ( + "sync" + "sync/atomic" +) + +// A command that owns a gateway drains it before the signal handler exits. +// Its return path waits for a signal already handling that drain, so main +// cannot exit (or re-exec) before the handler has finished saving state. +type signalGateway struct { + stop func() + done chan struct{} +} + +var exitGateway atomic.Pointer[signalGateway] + +func stopGatewayOnSignal(stop func()) func() { + g := &signalGateway{stop: stop, done: make(chan struct{})} + exitGateway.Store(g) + var once sync.Once + return func() { + once.Do(func() { + if !exitGateway.CompareAndSwap(g, nil) { + <-g.done + } + }) + } +} diff --git a/internal/cli/signal_gateway_test.go b/internal/cli/signal_gateway_test.go new file mode 100644 index 000000000..6dc449423 --- /dev/null +++ b/internal/cli/signal_gateway_test.go @@ -0,0 +1,53 @@ +//go:build !windows + +package cli + +import ( + "sync" + "syscall" + "testing" + "time" +) + +func TestSignalWaitsForGatewayShutdown(t *testing.T) { + for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP} { + t.Run(sig.String(), func(t *testing.T) { + died := deaths(t, sig) + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unhold := func() { once.Do(func() { close(release) }) } + finish := stopGatewayOnSignal(func() { close(entered); <-release }) + defer finish() + defer unhold() + endProbesOnSignal() + send(t, sig) + select { + case <-entered: + case got := <-died: + t.Fatalf("died of %v before draining the gateway and saving its sessions", got) + case <-time.After(5 * time.Second): + t.Fatal("signal never reached gateway shutdown") + } + select { + case got := <-died: + t.Fatalf("died of %v while gateway shutdown was held", got) + default: + } + + returned := make(chan struct{}) + go func() { finish(); close(returned) }() + select { + case <-returned: + t.Fatal("command returned while the signal was still draining") + case <-time.After(20 * time.Millisecond): + } + unhold() + diesOf(t, died, sig) + select { + case <-returned: + case <-time.After(5 * time.Second): + t.Fatal("command did not join completed signal shutdown") + } + }) + } +} diff --git a/internal/cli/signal_hangup_test.go b/internal/cli/signal_hangup_test.go new file mode 100644 index 000000000..46ba8bed1 --- /dev/null +++ b/internal/cli/signal_hangup_test.go @@ -0,0 +1,66 @@ +//go:build !windows && !nogui + +package cli + +import ( + "syscall" + "testing" + "time" +) + +// The terminal closing (SIGHUP) is left to magpie by bubbletea and by Wails +// (ownSignals keeps it), so magpie tui and the app drain the gateway they +// serve, its idle Claude sessions saved, before magpie dies of it: they +// died first, and the next magpie had no session to resume (#7017). +func TestHangupDrainsTheGatewayFirst(t *testing.T) { + oldRun, oldTUI, oldGUI, oldApp, oldPanel := tuiRun, tuiStop, guiStop, openApp, openPanel + t.Cleanup(func() { tuiRun, tuiStop, guiStop, openApp, openPanel = oldRun, oldTUI, oldGUI, oldApp, oldPanel }) + logs := startLog + startLog = func(string) {} + t.Cleanup(func() { startLog = logs }) + + // run is the command as it runs, once it has taken SIGINT and SIGTERM + // back + for name, open := range map[string]func(run func() error) error{ + "tui": func(run func() error) error { + tuiRun = func(ready func()) error { ready(); return run() } + return runTUI() + }, + "app": func(run func() error) error { + openApp = func(bool, string) error { ownSignals(); return run() } + return runGUI(false, "") + }, + "panel": func(run func() error) error { + openPanel = func() error { ownSignals(); return run() } + return runPanel() + }, + } { + t.Run(name, func(t *testing.T) { + died := deaths(t, syscall.SIGHUP) + stopped := make(chan struct{}) + stop := func() { + select { + case got := <-died: + t.Errorf("died of %v before the gateway drained", got) + default: + } + close(stopped) + } + tuiStop, guiStop = stop, stop + endProbesOnSignal() + err := open(func() error { + send(t, syscall.SIGHUP) + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("SIGHUP never drained the gateway") + } + diesOf(t, died, syscall.SIGHUP) + return nil + }) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/internal/cli/signals.go b/internal/cli/signals.go index b5af80d59..57ff8fac4 100644 --- a/internal/cli/signals.go +++ b/internal/cli/signals.go @@ -18,8 +18,8 @@ import ( // endProbesOnSignal: the probes magpie asks a CLI with lead a session of // their own (proc.ProbeContext), so Ctrl+C in the terminal, the terminal // closing or a service manager's SIGTERM reach magpie and not them, and -// magpie ending on the signal left them to init. They are ended first, and -// magpie then dies of the signal. A command that waits on Ctrl+C itself +// magpie ending on the signal left them to init. An owned gateway drains +// and saves its sessions, probes end, and magpie then dies of the signal. A command that waits on Ctrl+C itself // (interruptContext) is left to finish its own way, its probes ended all the // same; the app and the TUI, which quit on SIGINT and SIGTERM their own way, // take those back (ownSignals). A signal magpie was started ignoring (nohup, @@ -41,19 +41,30 @@ func endProbesOnSignal() { // asked before the probes are ended, which can take a moment // the command may spend finishing, and stop asking handled := s == os.Interrupt && interrupts.Load() > 0 - proc.EndProbes() if !handled { - provider.FlushServed() // a gateway's last answers, noted and not yet written - gateway.FlushSticks() // and who answered which conversation - // and the session index, or the next start reads every - // file a scan read since the last save again - savedWithin(sessionsSaved, saveOnSignal) - die(s) + finishSignalGateway(s) + } else { + proc.EndProbes() } } }(onSignal) } +func finishSignalGateway(s os.Signal) { + g := exitGateway.Swap(nil) + if g != nil { + defer close(g.done) + g.stop() + } + proc.EndProbes() + provider.FlushServed() // a gateway's last answers, noted and not yet written + gateway.FlushSticks() // and who answered which conversation + // and the session index, or the next start reads every + // file a scan read since the last save again + savedWithin(sessionsSaved, saveOnSignal) + die(s) +} + // saveOnSignal bounds how long a signal waits for the session index to be // written: a long history's takes a second or two, and a signal is asked to // end magpie now. diff --git a/internal/cli/web_cli.go b/internal/cli/web_cli.go index 295565858..8cfcfb2c0 100644 --- a/internal/cli/web_cli.go +++ b/internal/cli/web_cli.go @@ -88,6 +88,7 @@ func webCmd(args []string) error { if err != nil { return err } + defer stopGatewayOnSignal(w.Close)() if !w.ServesGateway() { // another magpie has the gateway (the service, magpie serve, the // app): this page shows its settings and accounts, read from the @@ -248,6 +249,7 @@ func serveCmd(args []string) error { if err != nil { return err } + defer stopGatewayOnSignal(w.Close)() public := advertisedURL() fmt.Println(green.Render("●"), "magpie gateway on", bold.Render(gateway.URL())) fmt.Println(muted.Render(" OpenAI "), public+"/v1/chat/completions", muted.Render("·"), public+"/v1/responses") diff --git a/internal/gateway/claude_handover_resume_test.go b/internal/gateway/claude_handover_resume_test.go new file mode 100644 index 000000000..e181b968c --- /dev/null +++ b/internal/gateway/claude_handover_resume_test.go @@ -0,0 +1,168 @@ +//go:build darwin || linux + +package gateway + +import ( + "context" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// The successor starts serving before the predecessor finishes draining. +// A turn received then must wait for the saved session, not replay history. +func TestClaudeHandoverWaitsForSavedSession(t *testing.T) { + h := newResumeHarness(t) + h.ask("rules A", "a1") + old := h.s + before := h.runs() + dir, err := os.MkdirTemp("/tmp", "mready-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + sock := filepath.Join(dir, "cb") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + asked := make(chan struct{}) + release := make(chan struct{}) + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/_magpie/claude-ready" { + http.NotFound(w, r) + return + } + close(asked) + select { + case <-release: + w.WriteHeader(http.StatusNoContent) + case <-r.Context().Done(): + } + })} + go srv.Serve(ln) + defer srv.Close() + var once sync.Once + unhold := func() { once.Do(func() { close(release) }) } + defer unhold() + ForwardCallbacks(sock) + defer ForwardCallbacks("") + h.s = New() + t.Cleanup(h.s.subscription.abortAll) + done := make(chan struct{}) + go func() { defer close(done); h.ask("rules A", "a1", "a2") }() + select { + case <-asked: + old.subscription.abortAll() + unhold() + case <-done: + t.Fatal("the successor answered before the predecessor saved its session") + case <-time.After(10 * time.Second): + t.Fatal("the successor neither waited for the saved session nor answered") + } + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("the successor did not resume after the save") + } + resumed := h.runStartedSince(before) + if !strings.Contains(resumed, "--resume ") || !strings.Contains(resumed, "\ntold ") || strings.Contains(resumed[strings.Index(resumed, "\ntold "):], "a1") { + t.Fatalf("the successor replayed the conversation instead of resuming: %s", resumed) + } +} + +func TestClaudeHandoverReadiness(t *testing.T) { + dir, err := os.MkdirTemp("/tmp", "mready-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + sock := filepath.Join(dir, "cb") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + s := New() + go s.ServeCallbacks(ln) + ForwardCallbacks(sock) + defer ForwardCallbacks("") + // A cancelled wait must not mark the predecessor ready. + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + if err := awaitPredecessorSessions(ctx); err == nil { + t.Fatal("unfinished predecessor was ready") + } + close(s.sessionsSaved) + ctx, cancel = context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := awaitPredecessorSessions(ctx); err != nil { + t.Fatal(err) + } +} + +func TestClaudeHandoverReadinessCompatibility(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusServiceUnavailable} { + t.Run(http.StatusText(status), func(t *testing.T) { + dir, err := os.MkdirTemp("/tmp", "mready-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + sock := filepath.Join(dir, "cb") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) })} + go srv.Serve(ln) + defer srv.Close() + ForwardCallbacks(sock) + defer ForwardCallbacks("") + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + err = awaitPredecessorSessions(ctx) + if (err == nil) != (status == http.StatusNotFound) { + t.Fatalf("status %d: %v", status, err) + } + }) + } +} + +// A predecessor still draining other providers' long replies holds a Claude +// turn predecessorWait at most, and none after it: the turn goes on (a +// replay) instead of waiting out a 15-minute drain past its client's +// timeout, or being refused. +func TestClaudeHandoverWaitIsBounded(t *testing.T) { + dir, err := os.MkdirTemp("/tmp", "mready-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + sock := filepath.Join(dir, "cb") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + s := New() // its sessions never saved: still draining + go s.ServeCallbacks(ln) + ForwardCallbacks(sock) + defer ForwardCallbacks("") + old := predecessorWait + predecessorWait = 50 * time.Millisecond + defer func() { predecessorWait = old }() + if err := awaitPredecessorSessions(context.Background()); err != errPredecessorSlow { + t.Fatalf("a predecessor past predecessorWait: %v, want errPredecessorSlow", err) + } + predecessorWait = time.Hour + began := time.Now() + if err := awaitPredecessorSessions(context.Background()); err != nil || time.Since(began) > 5*time.Second { + t.Fatalf("the next turn waited again (%v, %s)", err, time.Since(began)) + } +} diff --git a/internal/gateway/claude_persist.go b/internal/gateway/claude_persist.go index d8200f700..68a7c5f0b 100644 --- a/internal/gateway/claude_persist.go +++ b/internal/gateway/claude_persist.go @@ -129,9 +129,15 @@ func (b *subscriptionBridge) keepShelf() { } // loadShelf puts the saved sessions an earlier gateway left on the shelf, -// when the file changed since this one looked (b.mu not held). A file that -// can't be read whole is unknown: nothing is taken from it. +// when the file changed since this one looked (b.mu not held: it is taken +// for the shelf only). A file that can't be read whole is unknown: nothing +// is taken from it. func (b *subscriptionBridge) loadShelf() { + // the file and the shelf change together for the sweep (keptSessions): + // its entries are never in neither; b.mu is held only for the shelf, + // not for the file's reads, as every Claude turn waits on it + shelfFileMu.Lock() + defer shelfFileMu.Unlock() path := shelfPath() fi, err := os.Stat(path) if err != nil { @@ -149,23 +155,24 @@ func (b *subscriptionBridge) loadShelf() { if json.Unmarshal(data, &f) != nil || f.Version != shelfFileVersion { return } + var saved []*savedSession + for _, e := range f.Entries { + if s := e.saved(); s != nil { + saved = append(saved, s) + } + } // taken away: what a run goes on with from here is not what it says if os.Remove(path) != nil { return } - for _, e := range f.Entries { - s := e.saved() - if s == nil { - continue - } - b.mu.Lock() + b.mu.Lock() + defer b.mu.Unlock() + for _, s := range saved { if b.shelf[s.key] != nil { - b.mu.Unlock() continue } b.shelf[s.key] = s b.shelfTimer(s) - b.mu.Unlock() } } @@ -307,3 +314,68 @@ func (b *subscriptionBridge) keepForReset(run *subscriptionRun, req *Request, ow b.mu.Unlock() log.Printf("claude: a turn refused for the account's limit leaves its conversation's session, cut before the turn, for the turn asked again until %s", heldClock(s.until, now)) } + +// shelfFileMu is held while the shelf file is read for what it keeps +// (keptSessions) and while its entries move to the shelf (loadShelf). +var shelfFileMu sync.Mutex + +// resumed ends the protection while a saved session changes owners. +func (b *subscriptionBridge) resumed(s *savedSession) { + b.mu.Lock() + delete(b.resuming, s) + b.mu.Unlock() +} + +// keptSessions includes sessions waiting for quota resets, even if their +// transcripts have not changed for hours. An unreadable shelf is unknown: +// leave the files alone rather than destroy the only resumable history. +func (b *subscriptionBridge) keptSessions() (map[string]bool, bool) { + shelfFileMu.Lock() // loadShelf moves none from the file to the shelf meanwhile + defer shelfFileMu.Unlock() + kept := make(map[string]bool) + add := func(dirs []string, session string) { + for _, dir := range dirs { + kept[filepath.Join(dir, session+".jsonl")] = true + } + } + data, err := os.ReadFile(shelfPath()) + if err != nil && !os.IsNotExist(err) { + return nil, false + } + if err == nil { + var f shelfFile + if json.Unmarshal(data, &f) != nil || f.Version != shelfFileVersion { + return nil, false + } + for _, entry := range f.Entries { + if s := entry.saved(); s != nil { + add(s.sessions, s.session) + } + } + } + b.mu.Lock() + defer b.mu.Unlock() + save := func(s *savedSession) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.gone { + add(s.sessions, s.session) + } + } + for _, s := range b.shelf { + save(s) + } + for s := range b.resuming { + // taken marks it gone just before the run publishes its session id. + // The transfer owns the file until resumed releases this pin. + s.mu.Lock() + add(s.sessions, s.session) + s.mu.Unlock() + } + for _, r := range b.runs { + r.mu.Lock() + add(r.sessions, r.sessionID) + r.mu.Unlock() + } + return kept, true +} diff --git a/internal/gateway/claude_recovery_sweep_test.go b/internal/gateway/claude_recovery_sweep_test.go new file mode 100644 index 000000000..acde0319d --- /dev/null +++ b/internal/gateway/claude_recovery_sweep_test.go @@ -0,0 +1,92 @@ +package gateway + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +// An account can wait for its quota longer than the ordinary idle hour. +// Starting another conversation after a restart must not sweep its kept +// transcript away, whether the index is still on disk or already loaded. +func TestClaudeSweepKeepsQuotaSessions(t *testing.T) { + for _, state := range []string{"disk", "loaded", "resuming", "transferred", "running"} { + t.Run(state, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + dir := filepath.Join(t.TempDir(), "projects", "work") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-2 * idleLongest) + for _, id := range []string{"kept", "expired"} { + path := filepath.Join(dir, id+".jsonl") + if err := os.WriteFile(path, []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + } + entry := shelfEntry{Session: "kept", Sessions: []string{dir}, Key: "conversation", At: old, Until: time.Now().Add(time.Hour)} + b, err := json.Marshal(shelfFile{Version: shelfFileVersion, Entries: []shelfEntry{entry}}) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(shelfPath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(shelfPath(), b, 0o600); err != nil { + t.Fatal(err) + } + bridge := newSubscriptionBridge() + t.Cleanup(bridge.abortAll) + if state != "disk" { + bridge.loadShelf() + } + if state == "resuming" || state == "transferred" { + saved := bridge.shelf[entry.Key] + saved.gone = state == "transferred" + delete(bridge.shelf, entry.Key) + bridge.resuming = map[*savedSession]bool{saved: true} + defer saved.timer.Stop() + } + if state == "running" { + bridge.shelf[entry.Key].timer.Stop() + delete(bridge.shelf, entry.Key) + bridge.runs["active"] = &subscriptionRun{sessionID: entry.Session, sessions: entry.Sessions} + defer func() { + // Seeing the file disappear does not synchronize with + // the sweeper's reads of the bridge's maps. + bridge.mu.Lock() + delete(bridge.runs, "active") + bridge.mu.Unlock() + }() + } + bridge.sweepSessions([]string{dir}) + eventually(t, "the expired session wasn't swept", func() bool { + _, err := os.Stat(filepath.Join(dir, "expired.jsonl")) + return os.IsNotExist(err) + }) + if _, err := os.Stat(filepath.Join(dir, "kept.jsonl")); err != nil { + t.Fatalf("the session kept until the quota resets was swept: %v", err) + } + }) + } +} + +func TestClaudeSweepUnknownShelfLeavesFiles(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := os.MkdirAll(filepath.Dir(shelfPath()), 0o700); err != nil { + t.Fatal(err) + } + for _, data := range []string{`{`, `{"version":999}`} { + if err := os.WriteFile(shelfPath(), []byte(data), 0o600); err != nil { + t.Fatal(err) + } + if _, known := newSubscriptionBridge().keptSessions(); known { + t.Fatal("unreadable shelf allowed a destructive sweep") + } + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index a2798d423..85a6ce53b 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -77,14 +77,15 @@ import ( ) type subscriptionBridge struct { - mu sync.Mutex - runs map[string]*subscriptionRun // callback token → run - calls map[string]*subscriptionRun // tool_use id → run - idle map[string]*subscriptionRun // conversation so far (turnKey) → run - shelf map[string]*savedSession // conversation so far (turnKey) → its saved session - baseURL string - sweep sync.Once - swept sync.Map // Claude Code's project folders sweepSessions went through + mu sync.Mutex + runs map[string]*subscriptionRun // callback token → run + calls map[string]*subscriptionRun // tool_use id → run + idle map[string]*subscriptionRun // conversation so far (turnKey) → run + shelf map[string]*savedSession // conversation so far (turnKey) → its saved session + resuming map[*savedSession]bool // taken off the shelf, not yet owned by a run + baseURL string + sweep sync.Once + swept sync.Map // Claude Code's project folders sweepSessions went through // lost is why each run that had a conversation ended, by that // conversation (convKey), and lostCalls by the tool calls it waited // on or was last handed results for, for the log of a request that @@ -2855,16 +2856,24 @@ func (b *subscriptionBridge) unshelve(req *Request, owner string) *savedSession } } delete(b.shelf, key) + if s != nil { + if b.resuming == nil { + b.resuming = make(map[*savedSession]bool) + } + b.resuming[s] = true + } b.mu.Unlock() if s == nil { return nil } s.timer.Stop() if !s.cachePrefix.accepts(req.cacheTail()) { + b.resumed(s) s.discard() return nil } if behind && !s.cutBehind() { + b.resumed(s) s.discard() return nil } @@ -3526,10 +3535,14 @@ func (b *subscriptionBridge) sweepSessions(dirs []string) { continue } go func() { + kept, known := b.keptSessions() + if !known { + return + } entries, _ := os.ReadDir(dir) for _, e := range entries { sid, ok := strings.CutSuffix(e.Name(), ".jsonl") - if !ok || e.IsDir() { + if !ok || e.IsDir() || kept[filepath.Join(dir, e.Name())] { continue } if fi, err := e.Info(); err == nil && time.Since(fi.ModTime()) > idleLongest+time.Minute { @@ -7230,6 +7243,14 @@ func (b *subscriptionBridge) whyCallsLost(req *Request) string { func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, usage *Usage) (int, string) { defer s.bridgeTurn()() + if err := awaitPredecessorSessions(r.Context()); err != nil { + if r.Context().Err() != nil { + return http.StatusServiceUnavailable, "waiting for the previous gateway to save Claude sessions: " + err.Error() + } + // what would have been resumed is replayed, as before the wait: a + // turn is not refused for the gateway it was handed over from + log.Printf("claude: going on without the previous gateway's saved sessions: %v", err) + } owner := p.ID if p.Account != nil { owner += "\x00" + p.Account.User @@ -7250,6 +7271,9 @@ func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, // a run let go past idleMost left its session for this turn, or // the run whose calls another request answered first has it from := s.subscription.unshelve(req, owner) + if from != nil { + defer s.subscription.resumed(from) + } if from == nil { from = req.branch } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a6a9a6136..a774d1cfc 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -553,6 +553,7 @@ type Server struct { // refused as signed for another conversation (thinking_bound.go) refusedThinking map[string]bool subscription *subscriptionBridge + sessionsSaved chan struct{} // closed after the predecessor has persisted its Claude sessions // imageStore is the image MCP server's jobs and images (image_mcp.go) imageStore imageMCPStore // browser is the Magpie Browser extensions connected (browser.go) @@ -660,11 +661,12 @@ func New() *Server { // (netproxy.HTTP1, which provider/codex_http1.go sets); a vendor's // redirect is followed to its own origin only, so its key goes // nowhere else (provider.KeepsCredentials) - client: &http.Client{Transport: rpmTransport{upstreamTransport()}, CheckRedirect: provider.KeepsCredentials}, - unfit: make(map[string]bool), - subscription: newSubscriptionBridge(), - debug: os.Getenv("MAGPIE_DEBUG") != "", - sightFile: sightsPath(), + client: &http.Client{Transport: rpmTransport{upstreamTransport()}, CheckRedirect: provider.KeepsCredentials}, + unfit: make(map[string]bool), + subscription: newSubscriptionBridge(), + sessionsSaved: make(chan struct{}), + debug: os.Getenv("MAGPIE_DEBUG") != "", + sightFile: sightsPath(), } s.loadSights() return s @@ -1003,6 +1005,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error { log.Printf("gateway: ending before image descriptions could all be saved; the next start may describe them again") } s.subscription.abortAll() + close(s.sessionsSaved) provider.FlushServed() // what answered last, kept for the next start and the CLI flushSticks() // who answered which conversation, for the next start or the magpie handed over to // the MCP servers the hub started end with the gateway diff --git a/internal/gateway/handover.go b/internal/gateway/handover.go index b7f0504e9..5529f5d6a 100644 --- a/internal/gateway/handover.go +++ b/internal/gateway/handover.go @@ -3,6 +3,7 @@ package gateway import ( "context" "errors" + "fmt" "io" "log" "net" @@ -12,6 +13,7 @@ import ( "os" "strconv" "sync" + "syscall" "time" ) @@ -277,9 +279,17 @@ func (u *unreadConns) wait(ctx context.Context) { // this process started (claudeMCPPath): their MCP helper calls the // gateway's port, which the magpie this one handed it to now serves, and // that one passes on the calls of runs it doesn't have (ForwardCallbacks). +// It also lets the successor wait until Claude sessions have been saved. // It returns once ln is closed. func (s *Server) ServeCallbacks(ln net.Listener) error { mux := http.NewServeMux() + mux.HandleFunc("GET /_magpie/claude-ready", func(w http.ResponseWriter, r *http.Request) { + select { + case <-s.sessionsSaved: + w.WriteHeader(http.StatusNoContent) + case <-r.Context().Done(): + } + }) mux.HandleFunc("POST "+claudeMCPPath+"{token}", s.subscription.mcpCall) err := (&http.Server{Handler: mux, ReadHeaderTimeout: 30 * time.Second}).Serve(ln) if errors.Is(err, net.ErrClosed) || errors.Is(err, http.ErrServerClosed) { @@ -293,7 +303,8 @@ func (s *Server) ServeCallbacks(ln net.Listener) error { // when there is none. var predecessorCallbacks struct { sync.Mutex - sock string + sock string + ready bool } // ForwardCallbacks has a tool call for a Claude Code run this process @@ -303,6 +314,7 @@ var predecessorCallbacks struct { // "" stops it. func ForwardCallbacks(sock string) { predecessorCallbacks.Lock() + predecessorCallbacks.ready = false predecessorCallbacks.sock = sock predecessorCallbacks.Unlock() } @@ -360,3 +372,67 @@ func (s *Server) Addr() string { } return s.ln.Addr().String() } + +// A successor accepts requests before its predecessor finishes draining. +// Only Claude turns wait: resuming before the shelf is written replays history. +// The predecessor saves its shelf once every request it holds has ended, of +// any provider, up to handedOffDrain; a Claude turn waits for that at most +// predecessorWait, then goes on as it did before the wait (a replay, for a +// conversation the shelf would have resumed), and so does every turn after +// it: errPredecessorSlow. A shelf written later is still read, at the next +// turn no session here is found for (loadShelf). +func awaitPredecessorSessions(ctx context.Context) error { + predecessorCallbacks.Lock() + sock, ready := predecessorCallbacks.sock, predecessorCallbacks.ready + predecessorCallbacks.Unlock() + if sock == "" || ready { + return nil + } + asker := ctx + ctx, cancel := context.WithTimeout(ctx, predecessorWait) + defer cancel() + markReady := func() { + predecessorCallbacks.Lock() + if predecessorCallbacks.sock == sock { + predecessorCallbacks.ready = true + } + predecessorCallbacks.Unlock() + } + transport := &http.Transport{DisableKeepAlives: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", sock) + }} + defer transport.CloseIdleConnections() + req, err := http.NewRequestWithContext(ctx, "GET", "http://predecessor/_magpie/claude-ready", nil) + if err != nil { + return err + } + resp, err := (&http.Client{Transport: transport}).Do(req) + if err != nil { + if asker.Err() == nil && ctx.Err() != nil { + markReady() + return errPredecessorSlow + } + // The callback listener goes away only after the old gateway drains. + if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.ECONNREFUSED) { + return err + } + } else { + resp.Body.Close() + // Older versions have no readiness endpoint. Preserve their handover. + if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("predecessor returned %s", resp.Status) + } + } + markReady() + return nil +} + +// predecessorWait is how long a Claude turn waits for the predecessor's +// saved sessions; a var so tests can shorten it. Well inside Claude Code's +// own ten minutes for a reply. +var predecessorWait = 90 * time.Second + +// errPredecessorSlow: the predecessor had not saved its sessions within +// predecessorWait, and no turn waits for it any more. +var errPredecessorSlow = errors.New("the previous gateway is still draining") diff --git a/internal/gui/app.go b/internal/gui/app.go index dd7f58541..4bf063090 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -446,6 +446,7 @@ func Run(version string, showMain bool, link string) error { // so do the threads. OnShutdown: func() { unhookNoActivate() + stopServing() proc.EndProbes() if handedOver.Load() { return diff --git a/internal/gui/backend.go b/internal/gui/backend.go index 1c9c5c23a..937bb190c 100644 --- a/internal/gui/backend.go +++ b/internal/gui/backend.go @@ -29,10 +29,17 @@ var serving sync.WaitGroup // stopServing stops this process's gateway taking requests and returns // once those in flight have finished. func stopServing() { + gatewayMu.Lock() endBackend() + gatewayMu.Unlock() serving.Wait() } +// StopServing is stopServing, for a signal Wails doesn't handle (SIGHUP: +// the terminal the app was started from closing), so the gateway drains and +// saves its idle Claude sessions before magpie dies of it. +func StopServing() { stopServing() } + // 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 @@ -136,6 +143,9 @@ func serveGateway() *gateway.Server { } func serveGatewayLocked() *gateway.Server { + if backendCtx.Err() != nil { + return nil + } // paused by the user (gatewaypause.go): nothing serves it until resumed if pausedNow() { return nil diff --git a/internal/gui/shutdown_gateway_test.go b/internal/gui/shutdown_gateway_test.go new file mode 100644 index 000000000..d45c4f531 --- /dev/null +++ b/internal/gui/shutdown_gateway_test.go @@ -0,0 +1,56 @@ +package gui + +import ( + "go/ast" + "go/parser" + "go/token" + "testing" +) + +// Wails may terminate without returning to Run (macOS). Its shutdown +// callback itself must drain the gateway, including a non-handover update. +// The Web shutdown integration test exercises the shared drain and resume; +// this guard covers the native callback even in a headless test build. +func TestDesktopShutdownDrainsGateway(t *testing.T) { + f, err := parser.ParseFile(token.NewFileSet(), "app.go", nil, 0) + if err != nil { + t.Fatal(err) + } + found := false + ast.Inspect(f, func(n ast.Node) bool { + kv, ok := n.(*ast.KeyValueExpr) + if !ok { + return true + } + key, ok := kv.Key.(*ast.Ident) + if !ok || key.Name != "OnShutdown" { + return true + } + fn, ok := kv.Value.(*ast.FuncLit) + if !ok { + return true + } + for _, stmt := range fn.Body.List { + if _, branch := stmt.(*ast.IfStmt); branch { + break + } + e, ok := stmt.(*ast.ExprStmt) + if !ok { + continue + } + call, ok := e.X.(*ast.CallExpr) + if !ok { + continue + } + name, ok := call.Fun.(*ast.Ident) + if ok && name.Name == "stopServing" { + found = true + break + } + } + return false + }) + if !found { + t.Fatal("desktop shutdown does not wait for the gateway to save Claude sessions") + } +} diff --git a/internal/gui/web.go b/internal/gui/web.go index 4e551a876..273431e7a 100644 --- a/internal/gui/web.go +++ b/internal/gui/web.go @@ -157,7 +157,7 @@ func (w *Web) ServesGateway() bool { return served.Load() != nil } func (w *Web) Wait() error { <-w.quit time.Sleep(200 * time.Millisecond) // the answer to the Quit gets out - w.srv.Close() + w.Close() if !webReexec.Load() { return nil } @@ -165,13 +165,20 @@ func (w *Web) Wait() error { if err != nil { return err } - // the plugin hosts end, waited for, first: one still running at the - // exec is a child nothing waits for after it, under this - // pid from then on (#3285) + // End and reap plugin hosts before replacing this process (#3285). plugin.EndHosts() return update.Reexec(exe, os.Args[1:], append(os.Environ(), webRunKey+"="+w.key)) } +// Close stops the web page and waits for this process's gateway to save its sessions. +func (w *Web) Close() { + w.srv.Close() + // The gateway keeps idle Claude sessions as it ends. Wait for that + // before returning or replacing this process, or the next turn has + // to replay the whole conversation instead of resuming its session. + stopServing() +} + // webKeyMin is the shortest MAGPIE_WEB_KEY taken: it is all that stands // between the network and the keys behind the page. const webKeyMin = 16 diff --git a/internal/gui/web_shutdown_unix_test.go b/internal/gui/web_shutdown_unix_test.go new file mode 100644 index 000000000..16373541f --- /dev/null +++ b/internal/gui/web_shutdown_unix_test.go @@ -0,0 +1,165 @@ +//go:build darwin || linux + +package gui + +import ( + "context" + "encoding/json" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/testenv" +) + +// recih: Web.Wait re-executed magpie without ending its gateway, so an +// idle Claude session never reached the shelf and the next turn replayed +// the entire conversation. Exercise Wait, including its real Unix exec, +// with a local Claude Code stand-in that records what it is told. +func TestWebShutdownKeepsClaudeSession(t *testing.T) { + if n := len(os.Args); n >= 4 && os.Args[n-4] == "web-shutdown-child" { + webShutdownChild(t, os.Args[n-3], os.Args[n-2], os.Args[n-1]) + return + } + for _, mode := range []string{"quit", "restart"} { + t.Run(mode, func(t *testing.T) { + home := t.TempDir() + testenv.SetHome(t, home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("MAGPIE_ADDR", "127.0.0.1:0") + config := filepath.Join(home, ".claude") + t.Setenv("CLAUDE_CONFIG_DIR", config) + write := func(path string, value any) { + t.Helper() + b, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + if err = os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(path, b, 0o600); err != nil { + t.Fatal(err) + } + } + write(filepath.Join(config, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{ + "accessToken": "test-token", "refreshToken": "test-refresh", "expiresAt": time.Now().Add(24 * time.Hour).UnixMilli(), "subscriptionType": "max", + }}) + write(filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{ + "emailAddress": "web-restart@example.com", "accountUuid": "web-restart", + }}) + if err := settings.Save(settings.Settings{ClaudePrintMode: true}); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + testenv.Program(t, filepath.Join(dir, "claude"), webShutdownClaude) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, self, "-test.run=^TestWebShutdownKeepsClaudeSession$", "-test.v", "--", "web-shutdown-child", mode, "before", home) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%s: %v\n%s", mode, err, out) + } + }) + } +} + +func webShutdownChild(t *testing.T, mode, phase, home string) { + t.Helper() + if phase == "after" { + if _, err := os.Stat(filepath.Join(settings.Dir(), "claude-shelf.json")); err != nil { + t.Fatalf("Web.Wait did not keep the idle Claude session before %s: %v", mode, err) + } + } + provider.ForgetAccounts() + gw := serveGateway() + if gw == nil { + t.Fatal("test gateway did not start") + } + t.Cleanup(stopServing) + eventually(t, "test gateway did not listen", func() bool { return gw.Addr() != "" }) + msgs := `[{"role":"user","content":"first-turn"}]` + if phase == "after" { + msgs = `[{"role":"user","content":"first-turn"},{"role":"assistant","content":"ok"},{"role":"user","content":"next-turn"}]` + } + c := &http.Client{Timeout: 10 * time.Second} + res, err := c.Post("http://"+gw.Addr()+"/v1/messages", "application/json", strings.NewReader( + `{"model":"claude/claude-sonnet-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":`+msgs+`}`)) + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(res.Body) + res.Body.Close() + if err != nil || res.StatusCode != 200 || !strings.Contains(string(body), "ok") { + t.Fatalf("Claude turn: %d %s, %v", res.StatusCode, body, err) + } + if phase == "after" { + b, err := os.ReadFile(filepath.Join(home, "claude-resumed")) + if err != nil { + t.Fatalf("next turn did not resume the saved Claude session: %v", err) + } + if !strings.Contains(string(b), "next-turn") || strings.Contains(string(b), "first-turn") { + t.Fatalf("resumed Claude was told more than the new turn: %s", b) + } + return + } + w := &Web{srv: &http.Server{}, quit: make(chan struct{}), key: "0123456789abcdef0123456789abcdef"} + close(w.quit) + webReexec.Store(mode == "restart") + // Reexec passes these arguments to this test binary, now as the new + // magpie. No production process or installed binary is restarted. + os.Args[len(os.Args)-2] = "after" + if err := w.Wait(); err != nil { + t.Fatal(err) + } + if mode == "restart" { + t.Fatal("the Unix restart returned without replacing the process") + } + if _, err := os.Stat(filepath.Join(settings.Dir(), "claude-shelf.json")); err != nil { + t.Fatalf("Web.Wait did not keep the idle Claude session before quit: %v", err) + } + backendCtx, endBackend = context.WithCancel(context.Background()) + served.Store(nil) + webShutdownChild(t, mode, "after", home) +} + +const webShutdownClaude = `#!/bin/sh +if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"web-restart@example.com","subscriptionType":"max"}'; exit 0; fi +sid=s$$ +resumed= +prev= +for a in "$@"; do + if [ "$prev" = "--resume" ]; then sid=$a; resumed=1; fi + prev=$a +done +proj=$(pwd -P | sed 's/[^A-Za-z0-9]/-/g') +mkdir -p "$CLAUDE_CONFIG_DIR/projects/$proj" +file="$CLAUDE_CONFIG_DIR/projects/$proj/$sid.jsonl" +echo '{"type":"system","subtype":"init","session_id":"'$sid'"}' +while read -r line; do + case $line in *'"type":"control_request"'*) + id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/') + echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}' + continue ;; + esac + printf '%s\n' "$line" >> "$file" + if [ -n "$resumed" ]; then printf '%s\n' "$line" >> "$HOME/claude-resumed"; fi + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' +done +` diff --git a/internal/tui/gateway.go b/internal/tui/gateway.go index 5e0fc19a4..5b71371d5 100644 --- a/internal/tui/gateway.go +++ b/internal/tui/gateway.go @@ -22,6 +22,20 @@ var gw struct { 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 diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 41707c89d..11caff484 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -170,6 +170,9 @@ func Run(ready func()) error { } ctx, stop := context.WithCancel(context.Background()) wait := serveGateway(ctx) + halt := func() { stop(); wait() } + serving.Store(&halt) + defer serving.Store(nil) _, err := tea.NewProgram(m, tea.WithAltScreen()).Run() served := gw.here.Load() stop()