Files
magpie/internal/gateway/restart.go
T
yetone e6b851b0fe update: magpie update in a terminal restarts the app with its gateway handed over
gaubeebangeel on X has an agent run the magpie upgrade at 4am and had
to give that agent its own provider: magpie couldn't serve it through
the upgrade.

Cause: `magpie update` put the new version in and printed "quit and
reopen magpie to use it" (a .app) or "updated to X" (a binary). The
running app never restarted, so the agent (or the user) had to restart
it by hand, and a plain restart closes the port and drops streams.

Measured before, on mote, a sandbox HOME `magpie serve` with a fake
upstream streaming 61 chunks at 100ms, restarted by SIGTERM + start:
- the stream was cut at chunk 15 of 61 (unexpected EOF); SIGTERM to exit
  took ~18ms, no drain;
- requests during the restart: 289 answered, 5 refused over 87ms.

Now `magpie update`, once the new version is in, POSTs it to the
running app's /v1/magpie/restart (gateway/restart.go). It is answered
only to a program on this computer over loopback; a LAN caller, a page
(Origin / Sec-Fetch) and another Host get 403. The updater's
restartBeside (gui/update_beside.go) restarts only when its own exe was
the one replaced (replaced() now also compares a .app's binary,
bundleExe), takes the version as ready without the feed, and runs the
same restart as Settings' AutoRestart: at once when it cuts nothing
short, else through waitIdle. On macOS and Linux that restart is the
existing SCM_RIGHTS handover, so the port never closes and in-flight
streams finish in the old process. The command prints what happened:
restarting (handing the gateway over), waiting for N requests, another
copy (current), magpie serve (unsupported), not running, or too old
(404: the first update into this version still needs a manual
restart).

Tests:
- TestUpdateInATerminalRestartsTheAppWithoutCuttingIt (darwin, linux):
  a stream through the gateway, the exe rewritten, magpie update's ask
  answered "restarting" with handover; the successor serves a request
  while the stream runs, the stream ends whole, the old one quits only
  after it. Red by hand with the route removed ("magpie update's ask:
  404").
- TestUpdateOfAnotherCopyLeavesTheAppBe, TestRestartAskedOnlyFromThisComputer
  (refused cases never reach the restarter), TestUpdateAsksTheRunningMagpieToRestart
  (each reply, a 404 magpie, none running).

Run at this tree:
- rebased on bdc1617be, at this head on mote: gofmt -l clean;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...;
  go test -run 'TestUpdate|TestRestartHandsTheGatewayOver|TestHandoverNotMade'
  ./internal/gui ./internal/cli and -run 'TestRestartAsked|TestReadOnlyKey'
  ./internal/gateway: ok
- before the rebase (88ecae173), mote: go test -count=1 ./internal/gui ./internal/cli ./internal/gateway:
  gateway ok (535s), cli ok; gui FAIL only on filed reds: the real-window AppKit
  tests killed at their deadline on mote (#4125, #2645) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), both red the same
  run alone at 88ecae173, and TestColdTurnsTaken (#4510, a race in
  full gui runs, not touched here)
- wsl-run (magpie-desktop, -tags nogui): TestRestartHandsTheGatewayOver,
  TestUpdateInATerminal..., TestUpdateOfAnother...: ok
- mote: gofmt -l clean; go vet gui/gateway/cli; GOOS=linux go vet -tags
  nogui ./...; GOOS=windows go vet ./...: ok

Not tried: the real GUI app end to end with a real `magpie update`
against a published release; Windows (no handover there: the restart
waits for an idle gateway and the port closes while the new version
starts, #4521); `magpie serve` / the daemon, which has no handover and
says to restart it the way it was started.
2026-10-31 11:39:04 +08:00

84 lines
3.1 KiB
Go

package gateway
import (
"encoding/json"
"io"
"log"
"net/http"
"sync/atomic"
"github.com/yetone/magpie/internal/provider"
)
// RestartPath is where `magpie update`, once it has put a new version in,
// asks the magpie serving the gateway to restart into it
// (gaubeebangeel on X: an agent served by magpie runs the update at 4am,
// and the app stayed on the old version until someone quit and reopened
// it, which cut whatever the agents had in flight). The app restarts the
// way its own update does: on a Mac or Linux it hands the gateway to the
// new version, so the request that ran the update, and every other,
// goes on. Loopback only, from a program, never a page.
const RestartPath = "/v1/magpie/restart"
// RestartReply is what RestartPath answers.
type RestartReply struct {
// restarting: at once; waiting: once what a restart would cut short
// (Busy) is done; current: this magpie wasn't the one updated (another
// copy, or nothing put in); unsupported: this magpie (magpie serve)
// doesn't restart itself, and is restarted the way it was started
State string `json:"state"`
// Version is this magpie's, the one restarting
Version string `json:"version"`
// Handover: the new version takes the gateway over while this one
// finishes its requests (Busy is then the Claude subscription's turns)
Handover bool `json:"handover,omitempty"`
Busy *Busy `json:"busy,omitempty"`
}
var restarter atomic.Pointer[func(version string) RestartReply]
// SetRestarter has RestartPath call f with the version `magpie update`
// put in; the gui's updater sets it. Without one the answer is
// "unsupported".
func SetRestarter(f func(version string) RestartReply) {
if f == nil {
restarter.Store(nil)
return
}
restarter.Store(&f)
}
// restartRefused says why r may not restart this magpie, "" when it may:
// as heapRefused, only a program on this computer calling localhost or a
// loopback address, never another machine, a page, or another Host.
func restartRefused(r *http.Request) string {
switch {
case !local(r):
return "magpie restarts to update only when a program on this computer asks, over loopback: run magpie update there"
case fromBrowser(r):
return "magpie doesn't restart when a web page asks: run magpie update in a terminal"
case !loopbackHost(r.Host):
return "magpie restarts to update only on a call to localhost or a loopback address, not " + r.Host + ": run magpie update"
}
return ""
}
func (s *Server) restartToUpdate(w http.ResponseWriter, r *http.Request) {
if why := restartRefused(r); why != "" {
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why)
writeError(w, provider.Chat, http.StatusForbidden, why)
return
}
var in struct {
Version string `json:"version"`
}
json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in)
reply := RestartReply{State: "unsupported", Version: Version}
if f := restarter.Load(); f != nil {
reply = (*f)(in.Version)
reply.Version = Version
}
log.Printf("restart to update to %q asked from %s: %s", in.Version, r.RemoteAddr, reply.State)
writeJSON(w, http.StatusOK, reply)
}