update: after an update on Windows one magpie is left, not two — a magpie running when another updated the binary (it runs on from magpie.exe.old) no longer downloads the update again to magpie.exe.new and swaps it in when it quits; it says a restart is all that is left. A magpie.exe.new that is magpie.exe over again is removed at start. The tray that found the gateway taken serves it once the magpie that had it is gone, checked every 15 s

This commit is contained in:
yetone
2026-09-26 14:30:16 +08:00
parent 6b39a69bf4
commit cb609d2cb4
9 changed files with 208 additions and 29 deletions
+6 -2
View File
@@ -121,8 +121,12 @@ func settingsState() settingsJSON {
var onDock func(bool)
// Handler serves the embedded UI and the JSON API.
// gw is the gateway this process serves, or nil when another magpie has it.
// gw is the gateway this process serves, or nil when another magpie has it
// (for now: see startBackend).
func Handler(w Windows, gw *gateway.Server) http.Handler {
if gw != nil {
served.Store(gw)
}
mux := http.NewServeMux()
mux.Handle("/", devPage(http.FileServer(http.FS(staticFS()))))
devRoutes(mux)
@@ -258,7 +262,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, state())
})
providerRoutes(mux, w, gw)
providerRoutes(mux, w)
importRoutes(mux)
usageRoutes(mux)
backupRoutes(mux, w)
+38 -9
View File
@@ -314,18 +314,18 @@ func Run(version string, showMain bool, link string) error {
return h.app.Run()
}
// served is the gateway this process serves, nil while another magpie
// has it.
var served atomic.Pointer[gateway.Server]
// 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), and the model lists kept warm.
// 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) {
if !gateway.Running() {
gw = gateway.New()
go func() {
if err := gw.ListenAndServe(context.Background()); err != nil {
log.Println("gateway:", err)
}
}()
}
gw = serveGateway()
go watchGateway()
// 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.
@@ -359,6 +359,35 @@ func startBackend() (gw *gateway.Server) {
return gw
}
var gatewayWatch = 15 * time.Second
// watchGateway takes the gateway up once the magpie that had it is gone.
func watchGateway() {
for {
time.Sleep(gatewayWatch)
if served.Load() == nil && !gateway.Running() {
serveGateway()
}
}
}
// serveGateway starts the gateway here when no magpie has it: the one
// started, or nil.
func serveGateway() *gateway.Server {
if gateway.Running() {
return nil
}
gw := gateway.New()
served.Store(gw)
go func() {
if err := gw.ListenAndServe(context.Background()); err != nil {
log.Println("gateway:", err)
served.CompareAndSwap(gw, nil) // another took the port first
}
}()
return gw
}
// singleInstance makes a second launch hand over to this one, off the Mac.
// The id covers the executable and the config dir, so a build elsewhere or
// a sandboxed HOME runs on its own.
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"encoding/json"
"net/http"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
@@ -12,7 +11,7 @@ import (
// the page lists them, keys masked, and posts back the ones the user
// picked; the keys are read again here, never sent to the page.
func importAppsRoutes(mux *http.ServeMux, gw *gateway.Server) {
func importAppsRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/importapps", func(rw http.ResponseWriter, r *http.Request) {
sources := provider.ImportSources()
for i := range sources {
@@ -37,6 +36,6 @@ func importAppsRoutes(mux *http.ServeMux, gw *gateway.Server) {
writeJSON(rw, struct {
Added []string `json:"added"`
State any `json:"state"`
}{added, providersState(gw)})
}{added, providersState()})
})
}
+9 -9
View File
@@ -221,7 +221,7 @@ func providerInfo(p provider.Provider, agents []*agent.Agent) providerJSON {
return out
}
func providersState(gw *gateway.Server) providersJSON {
func providersState() providersJSON {
agents := agent.Detected()
s := providersJSON{Providers: []providerJSON{}, Presets: []presetJSON{}, Excluded: []excludedJSON{}}
for _, x := range provider.Excluded() {
@@ -256,7 +256,7 @@ func providersState(gw *gateway.Server) providersJSON {
}
s.Gateway.Groups = append(s.Gateway.Groups, g)
}
if gw != nil {
if gw := served.Load(); gw != nil {
s.Gateway.Running, s.Gateway.Mine = true, true
s.Gateway.Calls = gw.Recent()
} else {
@@ -279,12 +279,12 @@ func ago(t time.Time) string {
}
}
func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
importAppsRoutes(mux, gw)
traceRoutes(mux, gw)
func providerRoutes(mux *http.ServeMux, w Windows) {
importAppsRoutes(mux)
traceRoutes(mux)
groupRoutes(mux)
mux.HandleFunc("GET /api/providers", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, providersState(gw))
writeJSON(rw, providersState())
})
// a picture for a provider, picked in the editor: kept by content before
// the provider is saved, which then points at it. The page sends it as
@@ -468,7 +468,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
http.NotFound(rw, r)
return
}
writeJSON(rw, providersState(gw))
writeJSON(rw, providersState())
})
// How much of its allowance each of an agent's accounts has used.
mux.HandleFunc("GET /api/login/usage", func(rw http.ResponseWriter, r *http.Request) {
@@ -500,7 +500,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
fail(rw, err)
return
}
writeJSON(rw, providersState(gw))
writeJSON(rw, providersState())
})
// A provider's several keys: add one, put one in use, name or remove it.
mux.HandleFunc("POST /api/keys/{action}", func(rw http.ResponseWriter, r *http.Request) {
@@ -545,7 +545,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
cancel()
}
}
writeJSON(rw, providersState(gw))
writeJSON(rw, providersState())
})
// Adding a subscription: magpie opens the vendor's sign-in in the
// browser and the window follows it until the account is in.
+45
View File
@@ -0,0 +1,45 @@
package gui
import (
"net"
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// A magpie that found the gateway taken serves it once the one that had it
// is gone (one left running from before an update, a magpie serve).
func TestGatewayTakenOver(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Setenv("MAGPIE_ADDR", ln.Addr().String())
other := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"name":"magpie"}`))
})}
go other.Serve(ln)
defer served.Store(nil)
if serveGateway() != nil {
t.Fatal("served over another magpie")
}
old := gatewayWatch
gatewayWatch = 50 * time.Millisecond
defer func() { gatewayWatch = old }()
go watchGateway()
time.Sleep(200 * time.Millisecond)
if served.Load() != nil {
t.Fatal("took the gateway while the other had it")
}
other.Close()
for deadline := time.Now().Add(5 * time.Second); served.Load() == nil || !gateway.Running(); time.Sleep(50 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("the gateway wasn't taken up")
}
}
}
+2 -1
View File
@@ -18,8 +18,9 @@ type traceJSON struct {
// traceRoutes serves the routing trace for the Gateway view to play: it
// waits up to 25 s for something to change after the seq it is given, so
// the page hears of a request as it happens.
func traceRoutes(mux *http.ServeMux, gw *gateway.Server) {
func traceRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/gateway/trace", func(rw http.ResponseWriter, r *http.Request) {
gw := served.Load()
out := traceJSON{TraceState: gateway.TraceState{Routes: []gateway.Route{}}, Mine: gw != nil}
if gw != nil {
after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
+29 -5
View File
@@ -5,6 +5,7 @@ import (
"errors"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"sync"
@@ -25,10 +26,11 @@ type updater struct {
state string // checking | latest | downloading | ready | available | source | error
latest *update.Release
err string
bundle string // the .app to replace, "" when not in one or stuck
stuck string // why the .app can't be replaced where it is (update.Stuck)
exe string // off the Mac: the binary to replace, "" when not writable
retry bool // error: the download failed, and may be tried again
bundle string // the .app to replace, "" when not in one or stuck
stuck string // why the .app can't be replaced where it is (update.Stuck)
exe string // off the Mac: the binary to replace, "" when not writable
self os.FileInfo // exe as this process started from it
retry bool // error: the download failed, and may be tried again
staged string
done int64 // downloading: bytes so far, of total (0 when unknown)
total int64
@@ -60,7 +62,9 @@ func (u *updater) start() {
} else if runtime.GOOS != "darwin" {
if exe, err := update.Executable(); err == nil && (update.Writable(filepath.Dir(exe)) || update.CanElevate()) {
u.exe = exe
update.RemoveOld(exe) // what the last updates on Windows moved aside
u.self, _ = os.Stat(exe)
update.RemoveOld(exe) // what the last updates on Windows moved aside
update.RemoveStaleNew(exe) // what a magpie left running downloaded again
}
}
go func() {
@@ -112,6 +116,13 @@ func (u *updater) run() {
case u.bundle == "" && u.exe == "":
u.state = "available" // the user fetches it from the release page
return
case u.replaced():
// another magpie put the update in already: a restart is all
u.state = "ready"
if u.onReady != nil {
go u.onReady(rel.Version)
}
return
}
u.state, u.done, u.total = "downloading", 0, 0
u.mu.Unlock()
@@ -145,6 +156,13 @@ func (u *updater) run() {
func (u *updater) install(ask bool) bool {
u.mu.Lock()
defer u.mu.Unlock()
if u.replaced() {
// another magpie updated the binary after this one started: it is
// in, and swapping this one's download in would move it aside (the
// download is left: it may be the other's, staged at the same name)
u.staged = ""
return true
}
if u.staged == "" {
return false
}
@@ -172,6 +190,12 @@ func (u *updater) install(ask bool) bool {
return true
}
// replaced is whether the binary was updated by another magpie since this
// one started, which runs on from where it was moved aside.
func (u *updater) replaced() bool {
return u.exe != "" && update.Replaced(u.exe, u.self)
}
func (u *updater) json() updateJSON {
u.mu.Lock()
defer u.mu.Unlock()
+42
View File
@@ -0,0 +1,42 @@
package update
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestReplacedAndStaleNew(t *testing.T) {
dir := t.TempDir()
exe := filepath.Join(dir, "magpie.exe")
os.WriteFile(exe, []byte("v1"), 0o755)
started, _ := os.Stat(exe)
if Replaced(exe, started) {
t.Fatal("replaced before anything happened")
}
// another magpie moves it aside and puts the new one in
os.Rename(exe, exe+".old")
os.WriteFile(exe, []byte("v2 build"), 0o755)
if !Replaced(exe, started) {
t.Fatal("not seen as replaced")
}
// the same size, a later time
os.WriteFile(exe, []byte("v1"), 0o755)
os.Chtimes(exe, time.Now(), started.ModTime().Add(time.Minute))
if !Replaced(exe, started) {
t.Fatal("a same-size update not seen")
}
// a .new that is exe over again goes; another stays
os.WriteFile(exe+".new", []byte("v1"), 0o755)
RemoveStaleNew(exe)
if _, err := os.Stat(exe + ".new"); !os.IsNotExist(err) {
t.Fatal("a .new the same as exe was kept")
}
os.WriteFile(exe+".new", []byte("v3"), 0o755)
RemoveStaleNew(exe)
if _, err := os.Stat(exe + ".new"); err != nil {
t.Fatal("a different .new was removed")
}
}
+35
View File
@@ -391,6 +391,41 @@ func RemoveOld(exe string) {
}
}
// Replaced reports whether exe is no longer the binary that was there when
// this process looked (started, from os.Stat): another magpie installed an
// update over it, and this one runs from where it was moved aside.
func Replaced(exe string, started os.FileInfo) bool {
now, err := os.Stat(exe)
return err == nil && started != nil && (now.Size() != started.Size() || !now.ModTime().Equal(started.ModTime()))
}
// RemoveStaleNew removes exe.new when it is exe over again: the update a
// magpie left running from before it downloaded once more.
func RemoveStaleNew(exe string) {
staged := exe + ".new"
a, err1 := os.Stat(exe)
b, err2 := os.Stat(staged)
if err1 != nil || err2 != nil || a.Size() != b.Size() {
return
}
if ha, hb := fileHash(exe), fileHash(staged); ha != "" && ha == hb {
os.Remove(staged)
}
}
func fileHash(path string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return ""
}
return hex.EncodeToString(h.Sum(nil))
}
// InstallBinaryAsAdmin is InstallBinary with the administrator's password.
func InstallBinaryAsAdmin(staged, exe string) error {
err := asAdmin("mv -f " + shellQuote(staged) + " " + shellQuote(exe))