remote magpie: once magpie updates, the Remote magpies it uses update too

nnlrl_75403 on Discord: a magpie used as another's Remote magpie stayed on
its old version after the local one updated, and had to be updated by
hand on the other computer. Now nothing needs setting up:

- provider.KeepRemotesUpdated (started by the app's updater and by
  magpie serve) runs UpdateRemotes 30 s after start and hourly. A
  released build with automatic updates on reads each Remote magpie's
  version (GET /v1) and, when it is older, asks it through
  POST /v1/magpie/update?version=<v> with the provider's key, at most
  once in six hours per version. Off here, or a dev build: nothing asked.
- The remote updates as its own automatic update would: the app
  downloads and restarts once idle (updater.updateAsked → download,
  waitIdle); magpie serve puts the latest in where it runs from, one at
  a time, never elevated, and serveFollow restarts into it. Automatic
  updates or downloads off there: it answers "off" and stays.
- A copy that can't replace itself says why: a container (docker pull
  ghcr.io/yetone/magpie:latest), a package manager's (its command), a
  folder it can't write, a build from source. A magpie from before the
  route answers 404 ("too old"), a read-only or held key is "refused".
  The provider's row on the Providers page adds a short status to its
  line ("updating to v…" for 30 min, or "can't update itself" etc.),
  with the reason and the command in its tooltip. en/zh/zh-TW/ja/de.
- The route replaces the program, so it takes the Codex reset's
  admission: another machine only while shared, never a browser page,
  an enabled key with full access from loopback too (401 without one),
  read-only 403 gateway_key_read_only, held 403 gateway_key_held. It is
  in readOnlyRefused and the CORS route list.

App.js stays under TestCoreScriptBudget by cutting two comments; the
budget is not raised.

Run (on mote, at the tree committed here):
- gofmt -l internal/: clean. go vet of gateway, gui, cli, provider for
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/gui ./internal/cli ./internal/provider
  ./internal/gateway: gui and cli ok but for #5644's two settings tests
  (red on main since 6b7ee4a98, owned); provider and gateway were
  still running at the push, and go in the full run after it.
- Rebased on origin/main c7c05dcf2, again: gofmt, vet, the new tests,
  ReadOnlyKeyEveryRoute, CORS, TestCoreScriptBudget (not raised) and
  both GUI files 32 of 32: ok.
- New: TestRemoteUpdateNeedsAFullKey (no key from loopback, Origin null,
  an app scheme, *.localhost, a rebound Host, a foreign page with and
  without the full key, another machine with none or a wrong key,
  read-only and held keys, then not shared; the updater is never
  called until a full key asks, from LAN and loopback),
  TestRemoteMagpieAskedToFollow (UpdateRemotes against a real gateway:
  dev build, same and newer remote, NoAutoUpdate here, asked once per
  version, container answer kept, read-only key refused, a 404 magpie
  "old"), TestUpdateAskedByAnotherMagpie, TestRemoteUpdateNote,
  TestServeUpdateAsked.
- GUI: remote-update.test.cjs (new) and remote-self.test.cjs, Chromium
  and WebKit, 1100 and 420 wide, en/zh/ja/de: 32 of 32 ok, with every
  key checked in zh, zh-TW, ja and de. i18n-en-no-cjk ok. i18n-keys'
  "a plugin's words are its own" is red, the same on origin/main
  f8525323d (#5327/#5332, #5426, #5482); its other cases ok.

Broken by hand, each red, then put back: the handler's key check
(loopback without a key got 200 updating), its held-key check, the
route itself (404 = the old code), asking a remote that is current,
ignoring NoAutoUpdate here, asking again for the same version, the
app ignoring automatic updates off, the app never waiting to restart,
serve's single flight (2 downloads), serve's container answer.
The handler's own Origin and not-shared checks stay green when removed:
corsGuard and lanGuard refuse those first; they are kept as the Codex
reset keeps them.

Not tried: a real update of a real remote (a Docker magpie and an app
on another Mac) end to end; Windows and Linux runs of the new tests
(vet only); the full suite (run after the push).

Reported-by: nnlrl_75403
This commit is contained in:
yetone
2026-11-08 03:13:15 +08:00
parent ee8f4de36c
commit d32a7a70cb
19 changed files with 1206 additions and 13 deletions
+16
View File
@@ -2729,6 +2729,22 @@ while one is out is answered 409. Another magpie's Codex card uses this,
and so can an app reading `/v1/magpie/quotas/cards`, such as a DSH
provider plugin, with a key of full access.
When magpie updates, every Remote magpie it uses that runs an older
release is asked to update too: `POST /v1/magpie/update?version=<v>`,
sent with the provider's key a little after start and every hour, at most
once in six hours for a version. Nothing is set up for it. The remote
updates as its own automatic update would (the app restarts into the new
version once nothing is in flight; `magpie serve` puts it in where it runs
from and restarts once idle), or answers why it doesn't: `current`,
`off` (automatic updates or downloads are off there), or `unsupported`
with `why` `container`, `package` (with `manager` and `command`),
`not-writable` or `source`. The provider's row says what came of it. With
automatic updates off here, or a build that isn't a release, nothing is
asked. Like the Codex reset, it takes an enabled gateway key with full
access, from this computer too, and never answers a browser page: a
read-only key is refused 403 `gateway_key_read_only` and a held key 403
`gateway_key_held`.
An app of your own can read the Usage page's numbers too.
`GET /v1/magpie/usage?period=<today|week|month|all>` is the page's summary,
the same JSON as the window's `/api/usage` (`path` is left out for another
+18
View File
@@ -643,6 +643,24 @@ sends it without a key from loopback, `Origin: null`, an app scheme, a
read-only and held key, and expects nothing spent until the full key
asks.
`POST /v1/magpie/update?version=<v>` (`Server.remoteUpdate` in
[`remote_update.go`](../../internal/gateway/remote_update.go),
nnlrl_75403 on Discord) has this magpie update itself to its channel's
latest once `v` (the asking magpie's version) is newer than its own. It
replaces the program, so its admission is the Codex reset's: another
machine only while magpie is shared (`sharedWith`), never a browser
(`fromBrowser`), an enabled key with full access from loopback too (401
without one), a read-only key 403 `gateway_key_read_only` and a held key
403 `gateway_key_held`. The work is the updater's, set with `SetUpdater`
by the app (`updater.updateAsked`) and by `magpie serve`
(`serveUpdateAsked`); with none the answer is `unsupported`. It answers
a `provider.RemoteUpdate` (`state` updating, current, off or
unsupported with `why`) and its own `version`.
`TestRemoteUpdateNeedsAFullKey` sends it the same refused cases as the
Codex reset and expects the updater never called;
`TestRemoteMagpieAskedToFollow` runs `provider.UpdateRemotes` against a
real gateway.
A remote provider serves the conversation, token-counting, System One,
embeddings, rerank, Decisions, speech-to-text, image generation/edit and video
creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the
+23
View File
@@ -954,6 +954,29 @@ process. See `TestAnotherMagpiesUpdateRestartsThisOne`,
[`update_follow_test.go`](../../internal/gui/update_follow_test.go), and
`update-served-anew.test.cjs`.
A Remote magpie follows this one's version too (nnlrl_75403 on Discord).
`provider.KeepRemotesUpdated` (started with the updater, and by `magpie
serve`) runs `UpdateRemotes` 30 s after start and hourly: a released
build with automatic updates on asks each Remote magpie on an older
release (`GET /v1`) through `POST /v1/magpie/update` with the provider's
key, once in six hours for a version, and keeps the answer
(`RemoteUpdateOf`). On the other side `updater.updateAsked`
([`update_remote.go`](../../internal/gui/update_remote.go)) downloads
(`download`) and restarts once idle (`waitIdle`), or answers why not:
nothing newer, automatic updates or downloads off there (the user's
setting stands), or a copy it can't replace (`stuck`: container,
package with its command, a folder it can't write, a build from
source). `magpie serve`'s `serveUpdateAsked`
([`serve_update.go`](../../internal/cli/serve_update.go)) puts the
latest in where it runs from, one at a time and never elevated, and
`serveFollow` restarts into it. The provider's row on the Providers
page appends `remoteUpdate` (`remoteUpdateNote`: an English `say` and
`tip` the page translates) to its line: "updating to v…" for 30
minutes, or why it can't, with the command over it. See
`TestUpdateAskedByAnotherMagpie`, `TestRemoteUpdateNote`,
`TestServeUpdateAsked`, `TestRemoteMagpieAskedToFollow` and
`remote-update.test.cjs`.
See `TestRestartHandsTheGatewayOver` (the new version a second process,
a stream across the restart finishing whole, requests during it answered,
and the old one quitting only after its stream) and
+4
View File
@@ -1506,6 +1506,10 @@ func serve() error {
gateway.SetRestarter(follow.answer)
go follow.run(ctx)
}
// another magpie using this one updated (serve_update.go), and this
// one's own Remote magpies follow it
gateway.SetUpdater(serveUpdateAsked(follow))
go provider.KeepRemotesUpdated(ctx, version)
err := s.ListenAndServe(ctx)
if exe := follow.restartTo(); exe != "" {
// the plugin hosts end, waited for, first, as magpie web's
+102
View File
@@ -0,0 +1,102 @@
package cli
import (
"context"
"log"
"path/filepath"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// serveUpdating is an update serve was asked for and is putting in.
var serveUpdating atomic.Bool
// servePutIn downloads rel and puts it in where serve runs from, never
// asking for a password (nobody is there to type it); a var for tests.
var servePutIn = func(ctx context.Context, rel *update.Release, app, exe string) error {
if app != "" {
staged, err := update.Stage(ctx, rel, app)
if err != nil {
return err
}
return update.Install(staged, app)
}
staged, err := update.StageBinary(ctx, rel)
if err != nil {
return err
}
return update.InstallBinary(staged, exe)
}
// serveLatest is update.Latest; a var for tests.
var serveLatest = update.Latest
// serveUpdateAsked answers provider.RemoteUpdatePath for `magpie serve`,
// as the app's updater does (gui's updateAsked): another magpie using
// this one as its Remote magpie updated to want. The new version is put
// in where serve runs from, and serve restarts into it once the gateway
// is idle (serveFollow). Unattended, it never asks for a password: a
// folder it can't write is said, as is a container (whose image is
// pulled instead) and a package manager's copy. Follow nil is a serve
// that couldn't tell its own program, which wouldn't restart.
func serveUpdateAsked(follow *serveFollow) func(want string) provider.RemoteUpdate {
return func(want string) provider.RemoteUpdate {
switch {
case !update.Released(version):
return provider.RemoteUpdate{State: "unsupported", Why: "source"}
case !update.Newer(want, version):
return provider.RemoteUpdate{State: "current"}
}
if s := settings.Load(); s.NoAutoUpdate || s.NoAutoDownload {
return provider.RemoteUpdate{State: "off"}
}
app := update.Bundle()
exe, err := updateExecutable()
switch {
case follow == nil:
return provider.RemoteUpdate{State: "unsupported", Why: "not-writable"}
case app != "":
if update.Stuck(app) != "" || !update.Writable(filepath.Dir(app)) {
return provider.RemoteUpdate{State: "unsupported", Why: "not-writable"}
}
case err != nil:
return provider.RemoteUpdate{State: "unsupported", Why: "not-writable"}
default:
if p := updatePackagedBy(exe); p != nil {
return provider.RemoteUpdate{State: "unsupported", Why: "package", Manager: p.Name(), Command: p.Command()}
}
if !update.Writable(filepath.Dir(exe)) {
if updateInContainer() {
return provider.RemoteUpdate{State: "unsupported", Why: "container"}
}
return provider.RemoteUpdate{State: "unsupported", Why: "not-writable"}
}
}
if !serveUpdating.CompareAndSwap(false, true) {
return provider.RemoteUpdate{State: "updating"}
}
go func() {
defer serveUpdating.Store(false)
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()
rel, err := serveLatest(ctx)
if err != nil {
log.Println("update asked by a magpie using this one:", err)
return
}
if !update.Newer(rel.Version, version) {
return
}
if err := servePutIn(ctx, rel, app, exe); err != nil {
log.Println("update asked by a magpie using this one:", err)
return
}
log.Printf("updated to %s, asked by a magpie using this one; restarting once idle", rel.Version)
}()
return provider.RemoteUpdate{State: "updating"}
}
}
+120
View File
@@ -0,0 +1,120 @@
package cli
import (
"context"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// nnlrl_75403 on Discord: a `magpie serve` that another magpie uses as its
// Remote magpie is asked to update when that one has. It puts the latest
// in where it runs from, once at a time, and never asks for a password;
// in the Docker image, a package manager's copy or a folder it can't
// write, it says so instead.
func TestServeUpdateAsked(t *testing.T) {
dir := t.TempDir()
exe := filepath.Join(dir, "magpie")
if err := os.WriteFile(exe, []byte("magpie"), 0o755); err != nil {
t.Fatal(err)
}
wasV, wasX, wasC, wasP, wasPut, wasL := version, updateExecutable, updateInContainer, updatePackagedBy, servePutIn, serveLatest
t.Cleanup(func() {
version, updateExecutable, updateInContainer, updatePackagedBy, servePutIn, serveLatest = wasV, wasX, wasC, wasP, wasPut, wasL
})
version = "v0.1.100"
updateExecutable = func() (string, error) { return exe, nil }
updateInContainer = func() bool { return false }
updatePackagedBy = func(string) *update.Packaged { return nil }
release := make(chan struct{})
var puts atomic.Int32
var mu sync.Mutex
var putAt string
serveLatest = func(context.Context) (*update.Release, error) {
return &update.Release{Version: "0.1.200"}, nil
}
servePutIn = func(_ context.Context, rel *update.Release, app, at string) error {
puts.Add(1)
mu.Lock()
putAt = at
mu.Unlock()
<-release
return nil
}
ask := serveUpdateAsked(&serveFollow{exe: exe})
if got := ask("v0.1.100"); got.State != "current" {
t.Fatalf("same version: %+v", got)
}
if err := settings.Save(settings.Settings{NoAutoUpdate: true}); err != nil {
t.Fatal(err)
}
if got := ask("v0.1.200"); got.State != "off" {
t.Fatalf("updates off: %+v", got)
}
if err := settings.Save(settings.Settings{}); err != nil {
t.Fatal(err)
}
if got := serveUpdateAsked(nil)("v0.1.200"); got.State != "unsupported" || got.Why != "not-writable" {
t.Fatalf("no program to follow: %+v", got)
}
updatePackagedBy = func(string) *update.Packaged { return &update.Packaged{Manager: "pacman", Package: "magpie-bin"} }
if got := ask("v0.1.200"); got.State != "unsupported" || got.Why != "package" || got.Command != "yay -S magpie-bin" {
t.Fatalf("a package: %+v", got)
}
updatePackagedBy = func(string) *update.Packaged { return nil }
if puts.Load() != 0 {
t.Fatal("put in when it said it wouldn't")
}
// asked twice while the first is under way: one download
if got := ask("v0.1.200"); got.State != "updating" {
t.Fatalf("newer asker: %+v", got)
}
if got := ask("v0.1.200"); got.State != "updating" {
t.Fatalf("asked again: %+v", got)
}
for deadline := time.Now().Add(3 * time.Second); puts.Load() == 0 && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
}
time.Sleep(50 * time.Millisecond)
if n := puts.Load(); n != 1 {
t.Fatalf("%d downloads, want 1", n)
}
mu.Lock()
at := putAt
mu.Unlock()
if at != exe {
t.Fatalf("put in at %q, want %q", at, exe)
}
close(release)
for deadline := time.Now().Add(3 * time.Second); serveUpdating.Load() && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
}
if serveUpdating.Load() {
t.Fatal("still updating after the download ended")
}
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
return // a folder this user can't write takes a Unix non-root user
}
if err := os.Chmod(dir, 0o555); err != nil {
t.Fatal(err)
}
defer os.Chmod(dir, 0o755)
if got := ask("v0.1.200"); got.State != "unsupported" || got.Why != "not-writable" {
t.Fatalf("a folder it can't write: %+v", got)
}
updateInContainer = func() bool { return true }
if got := ask("v0.1.200"); got.State != "unsupported" || got.Why != "container" {
t.Fatalf("in a container: %+v", got)
}
if n := puts.Load(); n != 1 {
t.Fatalf("%d downloads, want 1", n)
}
}
+1
View File
@@ -248,6 +248,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"POST", "/_magpie/claude-mcp/tok", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`},
{"POST", provider.RemoteRefreshPath, ""},
{"POST", provider.RemoteCodexResetPath + "?user=me@example.com", ""},
{"POST", provider.RemoteUpdatePath + "?version=v0.1.9999", ""},
{"GET", "/v1/magpie/quotas", ""},
{"GET", "/v1/models", ""},
{"OPTIONS", "/v1/chat/completions", ""},
+2
View File
@@ -1011,6 +1011,8 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("GET "+GoroutinesPath, s.goroutineDump)
// a restart into the version magpie update put in (loopback only)
mux.HandleFunc("POST "+RestartPath, s.restartToUpdate)
// an update another magpie using this one asks for (a full-access key)
mux.HandleFunc("POST "+provider.RemoteUpdatePath, s.remoteUpdate)
mux.HandleFunc("GET /v1/magpie/omarchy", s.omarchyTheme)
mux.HandleFunc("OPTIONS /v1/magpie/omarchy", s.omarchyTheme)
mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat))
+2
View File
@@ -27,6 +27,8 @@ var readOnlyRefused = []string{
"POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath,
// a Codex reset, which can't be undone (#3850)
"POST " + provider.RemoteCodexResetPath,
// an update another magpie asks for
"POST " + provider.RemoteUpdatePath,
"GET /v1/magpie/route", "GET /v1/magpie/trace",
"GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath,
"POST " + RestartPath,
+57
View File
@@ -0,0 +1,57 @@
package gateway
import (
"log"
"net/http"
"strings"
"sync/atomic"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
var selfUpdater atomic.Pointer[func(want string) provider.RemoteUpdate]
// SetUpdater has provider.RemoteUpdatePath call f with the version the
// asking magpie runs; the gui's updater and magpie serve set it. Without
// one the answer is "unsupported".
func SetUpdater(f func(want string) provider.RemoteUpdate) {
if f == nil {
selfUpdater.Store(nil)
return
}
selfUpdater.Store(&f)
}
// remoteUpdate updates this magpie when another magpie using it as a
// Remote magpie has updated (provider.UpdateRemotes). It is the owner's
// to ask, as a Codex reset is: from another machine only while magpie is
// shared, always with an enabled gateway key of full access (none
// read-only, none held to a budget, models or accounts), and never from
// a web page, which a key put in a page could otherwise do.
func (s *Server) remoteUpdate(w http.ResponseWriter, r *http.Request) {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, "magpie is updated from another machine only when it is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries its API key")
return
}
if fromBrowser(r) {
writeError(w, provider.Chat, http.StatusForbidden, "magpie doesn't update itself when a web page asks")
return
}
who := access.Caller(r.Context())
if who.KeyID == "" || who.ReadOnly {
writeError(w, provider.Chat, http.StatusUnauthorized, "updating magpie takes an enabled magpie gateway key with full access (Gateway → Gateway keys), sent as Authorization: Bearer <key> or x-api-key, from this computer too")
return
}
if refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it doesn't update magpie: use a key with full access") {
return
}
want := strings.TrimSpace(r.URL.Query().Get("version"))
out := provider.RemoteUpdate{State: "unsupported", Why: "source"}
if f := selfUpdater.Load(); f != nil {
out = (*f)(want)
}
out.Version = Version
log.Printf("update to follow %q asked by gateway key %q from %s: %s %s", want, who.KeyName, r.RemoteAddr, out.State, out.Why)
writeJSON(w, http.StatusOK, out)
}
+250
View File
@@ -0,0 +1,250 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// asks counts what the updater set here was asked.
type asks struct {
mu sync.Mutex
want []string
out provider.RemoteUpdate
}
func (a *asks) updater(want string) provider.RemoteUpdate {
a.mu.Lock()
defer a.mu.Unlock()
a.want = append(a.want, want)
return a.out
}
func (a *asks) seen() []string {
a.mu.Lock()
defer a.mu.Unlock()
return append([]string(nil), a.want...)
}
func setUpdater(t *testing.T, out provider.RemoteUpdate) *asks {
t.Helper()
a := &asks{out: out}
SetUpdater(a.updater)
t.Cleanup(func() { SetUpdater(nil) })
return a
}
// nnlrl_75403 on Discord: once magpie here updates, the Remote magpie it
// uses updates too. POST /v1/magpie/update replaces the program there, so
// only the owner asks it: a gateway key of full access, from this computer
// or another while magpie is shared. Never a request with no key (a page
// or app the gateway lets in on loopback without one), a page with the
// key in it, a read-only key or a held one.
func TestRemoteUpdateNeedsAFullKey(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "")
keys, secrets := newCaller(t, "Full", "Read only", "Held")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("limit-key", access.Change{Key: keys[2].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
t.Fatal(err)
}
a := setUpdater(t, provider.RemoteUpdate{State: "updating"})
h := lanGuard(New().Handler())
path := provider.RemoteUpdatePath + "?version=v0.1.9999"
do := func(from, host, origin, secret string) (int, string) {
t.Helper()
r := httptest.NewRequest("POST", path, nil)
r.RemoteAddr = from
r.Host = host
if origin != "" {
r.Header.Set("Origin", origin)
r.Header.Set("Sec-Fetch-Site", "cross-site")
r.Header.Set("Sec-Fetch-Mode", "cors")
r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Safari/605.1.15")
}
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
const loop, lan, gw = "127.0.0.1:50123", "192.168.1.9:5000", "127.0.0.1:3425"
for _, c := range []struct {
why string
from, host, origin, secret string
}{
{"this computer, no key", loop, gw, "", ""},
{"a sandboxed frame (Origin null), no key", loop, gw, "null", ""},
{"an app's scheme, no key", loop, gw, "tauri://localhost", ""},
{"a *.localhost page, no key", loop, gw, "http://evil.localhost:8080", ""},
{"a rebound page (its own Host), no key", loop, "evil.example:3425", "", ""},
{"a foreign page, no key", loop, gw, "https://evil.example", ""},
{"a foreign page with the full key", loop, gw, "https://evil.example", secrets[0]},
{"another machine, no key", lan, gw, "", ""},
{"another machine, a wrong key", lan, gw, "", "sk-magpie-wrong"},
{"a read-only key", lan, gw, "", secrets[1]},
{"a read-only key, this computer", loop, gw, "", secrets[1]},
{"a held key", lan, gw, "", secrets[2]},
} {
if code, body := do(c.from, c.host, c.origin, c.secret); code < 400 || code == http.StatusNotFound || strings.Contains(body, `"updating"`) {
t.Errorf("%s: %d %s", c.why, code, body)
}
if got := a.seen(); len(got) != 0 {
t.Fatalf("%s asked the updater: %v", c.why, got)
}
}
if code, body := do(lan, gw, "", secrets[1]); code != http.StatusForbidden || !strings.Contains(body, ReadOnlyCode) {
t.Fatalf("read-only key: %d %s", code, body)
}
if code, body := do(lan, gw, "", secrets[2]); code != http.StatusForbidden || !strings.Contains(body, provider.KeyHeldCode) {
t.Fatalf("held key: %d %s", code, body)
}
for _, from := range []string{lan, loop} {
code, body := do(from, gw, "", secrets[0])
var out provider.RemoteUpdate
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.State != "updating" || out.Version != Version {
t.Fatalf("full key from %s: %d %s", from, code, body)
}
}
if got := a.seen(); len(got) != 2 || got[0] != "v0.1.9999" || got[1] != "v0.1.9999" {
t.Fatalf("asked %v", got)
}
// not shared on the network: another machine isn't let in, key or not
s := settings.Load()
s.LAN = false
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if code, body := do(lan, gw, "", secrets[0]); code < 400 || code == http.StatusNotFound {
t.Fatalf("not shared, another machine: %d %s", code, body)
}
if got := a.seen(); len(got) != 2 {
t.Fatalf("not shared, asked %v", got)
}
// nothing to update with (a test binary, a tool): said, not done
SetUpdater(nil)
code, body := do(loop, gw, "", secrets[0])
var out provider.RemoteUpdate
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.State != "unsupported" {
t.Fatalf("no updater: %d %s", code, body)
}
}
// The office's magpie updated; the home server's, its Remote magpie, is
// asked to follow through the provider's key, once a version, and only
// when it is behind. The row keeps what it answered.
func TestRemoteMagpieAskedToFollow(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "")
provider.ForgetRemoteUpdatesForTest()
t.Cleanup(provider.ForgetRemoteUpdatesForTest)
was := Version
t.Cleanup(func() { Version = was })
Version = "v0.1.100" // the remote's
keys, secrets := newCaller(t, "Office", "Viewer")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
a := setUpdater(t, provider.RemoteUpdate{State: "updating"})
srv := httptest.NewServer(lanGuard(New().Handler()))
defer srv.Close()
ctx := context.Background()
save := func(secret, at string) {
t.Helper()
if err := provider.Save(provider.Provider{ID: "home", Name: "Home", Preset: provider.RemoteMagpiePreset, Key: secret, Chat: at}); err != nil {
t.Fatal(err)
}
provider.ForgetRemoteUpdatesForTest()
}
t.Cleanup(func() { provider.Delete("home") })
// a build here that isn't a release asks nothing
save(secrets[0], srv.URL)
provider.UpdateRemotes(ctx, "dev")
if got := a.seen(); len(got) != 0 {
t.Fatalf("a dev build asked %v", got)
}
// the remote on the same version, or a newer one: not asked
for _, v := range []string{"v0.1.100", "v0.1.99"} {
provider.UpdateRemotes(ctx, v)
if got := a.seen(); len(got) != 0 {
t.Fatalf("%s asked %v", v, got)
}
if u, ok := provider.RemoteUpdateOf("home", time.Now()); ok {
t.Fatalf("%s: the row says %+v", v, u)
}
}
// automatic updates off here: the user keeps this magpie where it
// is, and its remotes with it
s := settings.Load()
s.NoAutoUpdate = true
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
provider.UpdateRemotes(ctx, "v0.1.200")
if got := a.seen(); len(got) != 0 {
t.Fatalf("updates off here, asked %v", got)
}
s.NoAutoUpdate = false
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
// behind: asked once with this version, not again for it
provider.UpdateRemotes(ctx, "v0.1.200")
provider.UpdateRemotes(ctx, "v0.1.200")
if got := a.seen(); len(got) != 1 || got[0] != "v0.1.200" {
t.Fatalf("asked %v, want v0.1.200 once", got)
}
if u, ok := provider.RemoteUpdateOf("home", time.Now()); !ok || u.State != "updating" || u.Version != "v0.1.200" {
t.Fatalf("the row: %+v %v", u, ok)
}
// it can't update itself: the row says why
a.mu.Lock()
a.out = provider.RemoteUpdate{State: "unsupported", Why: "container"}
a.mu.Unlock()
provider.ForgetRemoteUpdatesForTest()
provider.UpdateRemotes(ctx, "v0.1.200")
if u, ok := provider.RemoteUpdateOf("home", time.Now()); !ok || u.State != "unsupported" || u.Why != "container" {
t.Fatalf("a container: %+v %v", u, ok)
}
// a read-only key there: refused, the updater never asked
save(secrets[1], srv.URL)
n := len(a.seen())
provider.UpdateRemotes(ctx, "v0.1.200")
if u, ok := provider.RemoteUpdateOf("home", time.Now()); !ok || u.State != "refused" {
t.Fatalf("read-only key: %+v %v", u, ok)
}
if got := a.seen(); len(got) != n {
t.Fatalf("read-only key asked %v", got)
}
// a magpie from before the route: too old to be asked
old := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && r.URL.Path == "/v1" {
writeJSON(w, 200, map[string]any{"name": "magpie", "version": "v0.1.50"})
return
}
writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions")
}))
defer old.Close()
save(secrets[0], old.URL)
provider.UpdateRemotes(ctx, "v0.1.200")
if u, ok := provider.RemoteUpdateOf("home", time.Now()); !ok || u.State != "old" {
t.Fatalf("an old magpie: %+v %v", u, ok)
}
}
+6 -11
View File
@@ -6174,10 +6174,7 @@ function renderProvidersLoading() {
$("#excluded").replaceChildren();
}
// Providers switched off are kept apart, below the ones on, under a
// "Turned off (N)" fold that starts folded: among the rest they took the
// room of the ones in use (01huadalang on Discord). The fold is
// remembered, per viewer.
// Providers switched off fold below the ones on (01huadalang on Discord).
let offFolded = true;
try { offFolded = localStorage.getItem("magpie.offProvidersOpen") !== "1"; } catch {}
$("#foldOff").prepend(svg(CHEV_R, 11, 1.6));
@@ -6230,7 +6227,9 @@ function renderProviders(quiet) {
// accounts list says of each, not a green "signed in"
const inUse = (p.account?.logins || []).filter((l) => l.on || l.active);
const lapsed = inUse.length > 0 && inUse.every((l) => l.lapsed);
who.append(name, el("div", "sub", (p.account ? t(lapsed ? "{user} is signed out" : "signed in as {user}", { user: p.account.user }) : p.host) + " · " + models));
const sub = el("div", "sub", (p.account ? t(lapsed ? "{user} is signed out" : "signed in as {user}", { user: p.account.user }) : p.host) + " · " + models), ru = p.remoteUpdate;
if (ru) sub.append(" · ", Object.assign(el("span", "rup", t(ru.say, ru)), { title: t(ru.tip, ru) }));
who.append(name, sub);
const using = p.agents.filter((a) => a.current);
const uses = el("div", "uses");
for (const a of using) {
@@ -6301,12 +6300,8 @@ function renderProviders(quiet) {
if (dialog) openModal(dialog, quiet); else closeModal();
}
// providerHandle is an on row's logo, which is also its handle (#499):
// drag it to move the row among the ones on, Alt+↑/↓ moves it from the
// keyboard, and a click opens the row as a click anywhere on it does. The
// grip that says so is drawn in the row's margin on hover (app.css). The
// order is the one providers are tried in too: a model several serve goes
// to the higher one first.
// providerHandle is an on row's logo and its handle (#499): drag, or
// Alt+↑/↓, sets the order providers are tried in; a click opens the row.
let providerArranging = false;
function providerHandle(p, row) {
const b = el("button", "ag-handle pv-handle");
+52
View File
@@ -1712,6 +1712,19 @@ const I18N = {
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已关闭:不向 Agent 提供其模型,也不向它发请求。密钥和设置保留,开启即可恢复使用。",
"This magpie": "本机 magpie",
"can't update itself": "无法自行更新",
"updating to {v}": "正在更新到 {v}",
"This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight.": "本机 magpie 已更新,因此也请它更新到 {v}。它会在没有进行中的请求时重启到新版本。",
"automatic updates off": "已关闭自动更新",
"Automatic updates are turned off on that computer, so it stays on its version.": "那台电脑上关闭了自动更新,所以它保持当前版本。",
"update it there": "请在那台电脑上更新",
"That magpie is too old to be updated from here: update it on that computer once.": "那台 magpie 版本太旧,无法从这里更新:请在那台电脑上手动更新一次。",
"Updating it from here takes a gateway key with full access there; this provider's key is read-only or held.": "从这里更新它需要它那边一个拥有完全权限的网关密钥;此提供商的密钥是只读的或受限的。",
"It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "它运行在容器中:请拉取新镜像(docker pull ghcr.io/yetone/magpie:latest)并重新创建容器。",
"{manager} installed it there: update it with {manager}.": "它是由 {manager} 安装的:请用 {manager} 更新。",
"{manager} installed it there: update it with {cmd}": "它是由 {manager} 安装的:请运行 {cmd} 更新",
"It was built from source: update it the way it was built.": "它是从源码构建的:请按构建方式更新。",
"magpie can't replace itself where it runs on that computer: update it there.": "magpie 无法在那台电脑上替换自身:请在那台电脑上更新。",
"This is this magpie itself, used anyway: its models are listed twice, and a request through it passes here twice.": "这个远程 magpie 就是本机的 magpie。仍在使用:它的模型与本机自己的模型并列,经它的请求会两次经过本机 magpie。",
"This is this magpie itself, brought by sync from a computer that uses it. It is left out, so its models aren't listed twice; a request for one is served here.": "这个远程 magpie 就是本机的 magpie:是同步从使用本机的另一台电脑带过来的。它已被排除,模型不会重复列出;请求它的模型时直接由本机提供。",
"Use it anyway": "仍然使用",
@@ -6396,6 +6409,19 @@ const I18N = {
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已關閉:不向 Agent 提供其模型,也不向它發請求。金鑰和設定保留,開啟即可恢復使用。",
"This magpie": "本機 magpie",
"can't update itself": "無法自行更新",
"updating to {v}": "正在更新到 {v}",
"This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight.": "本機 magpie 已更新,因此也請它更新到 {v}。它會在沒有進行中的請求時重新啟動到新版本。",
"automatic updates off": "已關閉自動更新",
"Automatic updates are turned off on that computer, so it stays on its version.": "那台電腦上關閉了自動更新,所以它保持目前版本。",
"update it there": "請在那台電腦上更新",
"That magpie is too old to be updated from here: update it on that computer once.": "那台 magpie 版本太舊,無法從這裡更新:請在那台電腦上手動更新一次。",
"Updating it from here takes a gateway key with full access there; this provider's key is read-only or held.": "從這裡更新它需要它那邊一個擁有完整權限的閘道金鑰;此供應商的金鑰是唯讀的或受限的。",
"It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "它執行在容器中:請拉取新映像(docker pull ghcr.io/yetone/magpie:latest)並重新建立容器。",
"{manager} installed it there: update it with {manager}.": "它是由 {manager} 安裝的:請用 {manager} 更新。",
"{manager} installed it there: update it with {cmd}": "它是由 {manager} 安裝的:請執行 {cmd} 更新",
"It was built from source: update it the way it was built.": "它是從原始碼建置的:請依建置方式更新。",
"magpie can't replace itself where it runs on that computer: update it there.": "magpie 無法在那台電腦上取代自身:請在那台電腦上更新。",
"This is this magpie itself, used anyway: its models are listed twice, and a request through it passes here twice.": "這個遠端 magpie 就是本機的 magpie。仍在使用:它的模型與本機自己的模型並列,經它的請求會兩次經過本機 magpie。",
"This is this magpie itself, brought by sync from a computer that uses it. It is left out, so its models aren't listed twice; a request for one is served here.": "這個遠端 magpie 就是本機的 magpie:是同步從使用本機的另一台電腦帶過來的。它已被排除,模型不會重複列出;請求它的模型時直接由本機提供。",
"Use it anyway": "仍然使用",
@@ -11054,6 +11080,19 @@ const I18N = {
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} はまだ {model} を使っていますが、magpie はもう提供していません:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "オフ:エージェントにそのモデルは渡されず、リクエストも送られません。キーと設定は保持されます。オンにすると再び使えます。",
"This magpie": "この magpie",
"can't update itself": "自動で更新できません",
"updating to {v}": "{v} に更新中",
"This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight.": "この magpie が更新されたため、あちらにも {v} への更新を依頼しました。処理中のリクエストがなくなったら再起動します。",
"automatic updates off": "自動更新はオフ",
"Automatic updates are turned off on that computer, so it stays on its version.": "あちらのコンピューターでは自動更新がオフのため、現在のバージョンのままです。",
"update it there": "あちらで更新してください",
"That magpie is too old to be updated from here: update it on that computer once.": "あちらの magpie は古いため、ここからは更新できません。一度あちらのコンピューターで更新してください。",
"Updating it from here takes a gateway key with full access there; this provider's key is read-only or held.": "ここから更新するには、あちらでフルアクセスのゲートウェイキーが必要です。このプロバイダーのキーは読み取り専用か制限付きです。",
"It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "コンテナで動作しています。新しいイメージを取得し(docker pull ghcr.io/yetone/magpie:latest)、コンテナを作り直してください。",
"{manager} installed it there: update it with {manager}.": "{manager} でインストールされています。{manager} で更新してください。",
"{manager} installed it there: update it with {cmd}": "{manager} でインストールされています。{cmd} で更新してください",
"It was built from source: update it the way it was built.": "ソースからビルドされています。ビルドした方法で更新してください。",
"magpie can't replace itself where it runs on that computer: update it there.": "あちらのコンピューターでは magpie が自身を置き換えられません。あちらで更新してください。",
"This is this magpie itself, used anyway: its models are listed twice, and a request through it passes here twice.": "このリモート magpie はこの magpie 自身です。それでも使用中:モデルがこの magpie 自身のモデルと並んで表示され、これを通るリクエストはこの magpie を 2 回通ります。",
"This is this magpie itself, brought by sync from a computer that uses it. It is left out, so its models aren't listed twice; a request for one is served here.": "このリモート magpie はこの magpie 自身です:この magpie を使う別のコンピューターから同期で届きました。除外されているため、モデルは二重に表示されず、そのモデルへのリクエストはここで直接処理されます。",
"Use it anyway": "それでも使う",
@@ -15743,6 +15782,19 @@ const I18N = {
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} nutzt noch {model}, das magpie nicht mehr bereitstellt: {error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "Ausgeschaltet: Agenten erhalten seine Modelle nicht, und keine Anfrage geht an ihn. Schlüssel und Einstellungen bleiben erhalten; zum erneuten Verwenden einschalten.",
"This magpie": "Dieses magpie",
"can't update itself": "kann sich nicht selbst aktualisieren",
"updating to {v}": "wird auf {v} aktualisiert",
"This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight.": "Dieses magpie wurde aktualisiert, daher wurde jenes gebeten, ebenfalls auf {v} zu aktualisieren. Es startet neu, sobald nichts mehr läuft.",
"automatic updates off": "automatische Updates aus",
"Automatic updates are turned off on that computer, so it stays on its version.": "Auf jenem Computer sind automatische Updates ausgeschaltet, daher bleibt es bei seiner Version.",
"update it there": "dort aktualisieren",
"That magpie is too old to be updated from here: update it on that computer once.": "Jenes magpie ist zu alt, um von hier aktualisiert zu werden: Aktualisiere es einmal auf jenem Computer.",
"Updating it from here takes a gateway key with full access there; this provider's key is read-only or held.": "Um es von hier zu aktualisieren, braucht es dort einen Gateway-Schlüssel mit vollem Zugriff; der Schlüssel dieses Anbieters ist schreibgeschützt oder eingeschränkt.",
"It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "Es läuft in einem Container: Lade das neue Image (docker pull ghcr.io/yetone/magpie:latest) und erstelle den Container neu.",
"{manager} installed it there: update it with {manager}.": "{manager} hat es dort installiert: Aktualisiere es mit {manager}.",
"{manager} installed it there: update it with {cmd}": "{manager} hat es dort installiert: Aktualisiere es mit {cmd}",
"It was built from source: update it the way it was built.": "Es wurde aus dem Quellcode gebaut: Aktualisiere es so, wie es gebaut wurde.",
"magpie can't replace itself where it runs on that computer: update it there.": "magpie kann sich auf jenem Computer nicht selbst ersetzen: Aktualisiere es dort.",
"This is this magpie itself, used anyway: its models are listed twice, and a request through it passes here twice.": "Dieses Remote-magpie ist dieses magpie selbst. Es wird trotzdem genutzt: Seine Modelle stehen neben den eigenen dieses magpie, und eine Anfrage darüber läuft zweimal durch dieses magpie.",
"This is this magpie itself, brought by sync from a computer that uses it. It is left out, so its models aren't listed twice; a request for one is served here.": "Dieses Remote-magpie ist dieses magpie selbst: Die Synchronisierung hat es von einem Computer gebracht, der dieses nutzt. Es bleibt außen vor, damit seine Modelle nicht doppelt erscheinen; eine Anfrage nach einem davon wird gleich hier bedient.",
"Use it anyway": "Trotzdem nutzen",
+4
View File
@@ -283,6 +283,9 @@ type providerJSON struct {
// LibraryMCP: a Remote magpie whose router is a Library server, or
// is to be one (library.RemoteMCPOn)
LibraryMCP bool `json:"libraryMCP,omitempty"`
// RemoteUpdate: a Remote magpie's word on its last ask to follow
// this magpie's version (remoteUpdateNote)
RemoteUpdate *remoteUpdateJSON `json:"remoteUpdate,omitempty"`
// CapStop and CapCareful: how its accounts end at their caps
// (plugins#349), set on their own with capstop and capcareful
CapStop bool `json:"capStop,omitempty"`
@@ -1207,6 +1210,7 @@ func providersState() providersJSON {
remoteMCP = library.RemoteMCPOn()
}
info.LibraryMCP = remoteMCP[p.ID]
info.RemoteUpdate = remoteUpdateNote(p.ID, time.Now())
}
s.Providers = append(s.Providers, info)
}
+110
View File
@@ -0,0 +1,110 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// nnlrl_75403 on Discord: once magpie updates, the Remote magpies it uses
// are asked to update too. A Remote magpie's row says what came of it:
// updating to the version, or, where it can't, why, with what to run
// there over it (a container's image, a package manager's command). A row
// with nothing to say says nothing. In English, Chinese, Japanese and
// German, Chromium and WebKit, at 1100 and 420 wide.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const remote = (id, name, more = {}) => ({
id, name, preset: "remote-magpie", icon: "magpie", host: "192.168.1.20:3425", chat: "http://192.168.1.20:3425/v1", responses: "", anthropic: "", catalog: "", routing: "",
models: [{ id: "own/m1", name: "m1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: { set: true, masked: "mg-…a1b2" }, ready: true, ...more,
});
function serve(lang, list) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const said = {
en: { updating: "updating to v0.1.200", cant: "can't update itself", off: "automatic updates off", there: "update it there" },
zh: { updating: "正在更新到 v0.1.200", cant: "无法自行更新", off: "已关闭自动更新", there: "请在那台电脑上更新" },
ja: { updating: "v0.1.200 に更新中", cant: "自動で更新できません", off: "自動更新はオフ", there: "あちらで更新してください" },
de: { updating: "wird auf v0.1.200 aktualisiert", cant: "kann sich nicht selbst aktualisieren", off: "automatische Updates aus", there: "dort aktualisieren" },
};
// the keys internal/gui/update_remote.go sends
const strings = [
"can't update itself",
"updating to {v}",
"This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight.",
"automatic updates off",
"Automatic updates are turned off on that computer, so it stays on its version.",
"update it there",
"That magpie is too old to be updated from here: update it on that computer once.",
"Updating it from here takes a gateway key with full access there; this provider's key is read-only or held.",
"It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.",
"{manager} installed it there: update it with {manager}.",
"{manager} installed it there: update it with {cmd}",
"It was built from source: update it the way it was built.",
"magpie can't replace itself where it runs on that computer: update it there.",
];
const rows = [
remote("home", "Home", { remoteUpdate: { say: "updating to {v}", tip: strings[2], v: "v0.1.200" } }),
remote("nas", "NAS", { remoteUpdate: { say: "can't update itself", tip: strings[8] } }),
remote("arch", "Arch", { remoteUpdate: { say: "can't update itself", tip: strings[10], manager: "pacman", cmd: "yay -S magpie-bin" } }),
remote("lab", "Lab", { remoteUpdate: { say: "automatic updates off", tip: strings[4] } }),
remote("old", "Old", { remoteUpdate: { say: "update it there", tip: strings[6] } }),
remote("office", "Office"),
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of Object.keys(said)) {
test(`${engine} ${width} ${lang}: a Remote magpie's row says what came of asking it to update`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, rows));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider").first().waitFor();
const rup = (name) => page.locator(".row.provider", { hasText: name }).first().locator(".sub .rup");
const s = said[lang];
for (const [name, text] of [["Home", s.updating], ["NAS", s.cant], ["Arch", s.cant], ["Lab", s.off], ["Old", s.there]]) {
assert.equal(await rup(name).count(), 1, `${name} says something`);
assert.equal((await rup(name).textContent()).trim(), text, name);
const tip = await rup(name).getAttribute("title");
assert.ok(tip.length > 20, `${name}'s tip says why: ${tip}`);
}
assert.match(await rup("NAS").getAttribute("title"), /docker pull ghcr\.io\/yetone\/magpie:latest/);
assert.match(await rup("Arch").getAttribute("title"), /yay -S magpie-bin/);
assert.match(await rup("Arch").getAttribute("title"), /pacman/);
assert.match(await rup("Home").getAttribute("title"), /v0\.1\.200/);
assert.doesNotMatch(await rup("Arch").getAttribute("title"), /\{(manager|cmd)\}/);
assert.equal(await rup("Office").count(), 0, "a row with nothing to say says nothing");
// the line keeps within the row
const row = await page.locator(".row.provider", { hasText: "NAS" }).first().boundingBox();
const sub = await page.locator(".row.provider", { hasText: "NAS" }).first().locator(".sub").boundingBox();
assert.ok(sub.x >= row.x && sub.x + sub.width <= row.x + row.width + 1, `the line fits the row at ${width}`);
if (lang === "en") {
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
assert.deepEqual(missing, [], "every string has its translations");
}
assert.deepEqual(errors, []);
});
}
}
}
+5 -2
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
@@ -152,8 +153,10 @@ func updateDue(s settings.Settings, last, now time.Time) bool {
func (u *updater) start() {
u.place(runtime.GOOS, update.GUI)
gateway.SetRestarter(u.restartBeside) // magpie update in a terminal
go u.followReplaced(backendCtx) // the app's or magpie web's update (visamzh on X)
gateway.SetRestarter(u.restartBeside) // magpie update in a terminal
gateway.SetUpdater(u.updateAsked) // a magpie using this one updated
go provider.KeepRemotesUpdated(backendCtx, Version) // and this one's remotes
go u.followReplaced(backendCtx) // the app's or magpie web's update (visamzh on X)
if u.bundle != "" {
go update.ForgetOldStaging(u.bundle) // #3965
}
+91
View File
@@ -0,0 +1,91 @@
package gui
import (
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// updateAsked answers provider.RemoteUpdatePath: another magpie using
// this one as its Remote magpie updated to want (nnlrl_75403 on Discord).
// This one updates as its own automatic update would, downloading the
// latest and restarting into it once nothing would be cut short
// (waitIdle), or says why it doesn't: nothing newer, automatic updates
// or downloads turned off here (the user's to keep), or a copy it can't
// replace (a container's image, a package manager's, a folder it can't
// write, a build from source).
func (u *updater) updateAsked(want string) provider.RemoteUpdate {
switch {
case !update.Released(Version):
return provider.RemoteUpdate{State: "unsupported", Why: "source"}
case !update.Newer(want, Version):
return provider.RemoteUpdate{State: "current"}
}
if s := settings.Load(); s.NoAutoUpdate || s.NoAutoDownload {
return provider.RemoteUpdate{State: "off"}
}
u.mu.Lock()
restart, bundle, exe, stuck, packaged := u.autoRestart, u.bundle, u.exe, u.stuck, u.packaged
u.mu.Unlock()
if bundle == "" && exe == "" || restart == nil {
out := provider.RemoteUpdate{State: "unsupported", Why: stuck}
if stuck == "package" && packaged != nil {
out.Manager, out.Command = packaged.Name(), packaged.Command()
}
if out.Why == "" || out.Why == "translocated" || out.Why == "read-only" {
out.Why = "not-writable"
}
return out
}
u.download()
u.waitIdle(restart, false)
return provider.RemoteUpdate{State: "updating"}
}
// remoteUpdateJSON is a Remote magpie's row's word on its last ask to
// update (provider.UpdateRemotes): Say on the row, Tip over it, each an
// English key the page translates with the rest as its values.
type remoteUpdateJSON struct {
Say string `json:"say"`
Tip string `json:"tip"`
V string `json:"v,omitempty"`
Manager string `json:"manager,omitempty"`
Cmd string `json:"cmd,omitempty"`
}
// remoteUpdateNote is what the Remote magpie id's row says of its last
// ask to update, nil when nothing: one that is current, or not asked.
func remoteUpdateNote(id string, now time.Time) *remoteUpdateJSON {
u, ok := provider.RemoteUpdateOf(id, now)
if !ok {
return nil
}
j := &remoteUpdateJSON{Say: "can't update itself", V: u.Version, Manager: u.Manager, Cmd: u.Command}
switch u.State {
case "updating":
j.Say, j.Tip = "updating to {v}", "This magpie updated, so that one was asked to update to {v} too. It restarts into it once nothing is in flight."
case "off":
j.Say, j.Tip = "automatic updates off", "Automatic updates are turned off on that computer, so it stays on its version."
case "old":
j.Say, j.Tip = "update it there", "That magpie is too old to be updated from here: update it on that computer once."
case "refused":
j.Say, j.Tip = "update it there", "Updating it from here takes a gateway key with full access there; this provider's key is read-only or held."
default:
switch u.Why {
case "container":
j.Tip = "It runs in a container: pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container."
case "package":
j.Tip = "{manager} installed it there: update it with {manager}."
if u.Command != "" {
j.Tip = "{manager} installed it there: update it with {cmd}"
}
case "source":
j.Tip = "It was built from source: update it the way it was built."
default:
j.Tip = "magpie can't replace itself where it runs on that computer: update it there."
}
}
return j
}
+137
View File
@@ -0,0 +1,137 @@
package gui
import (
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// nnlrl_75403 on Discord: the magpie using this one as its Remote magpie
// updated, and asks this one to follow. It updates as its own automatic
// update would, restarting once nothing is in flight, or says why not:
// already there, the user's updates off, a container, a package
// manager's copy, a folder it can't write, a build from source.
func TestUpdateAskedByAnotherMagpie(t *testing.T) {
was := Version
t.Cleanup(func() { Version = was })
Version = "v0.1.100"
busy := &fakeBusy{}
busy.set(gateway.Busy{Requests: 1})
// a download under way: begin finds it, and the ask waits for it
u := &updater{state: "downloading", exe: "/opt/magpie/magpie", latest: &update.Release{Version: "v0.1.200"}}
quick(t, busy, u)
var restarts atomic.Int32
u.autoRestart = func() bool { restarts.Add(1); return true }
if got := u.updateAsked("v0.1.100"); got.State != "current" {
t.Fatalf("same version: %+v", got)
}
if got := u.updateAsked("v0.1.99"); got.State != "current" {
t.Fatalf("an older asker: %+v", got)
}
for _, s := range []settings.Settings{{NoAutoUpdate: true}, {NoAutoDownload: true}} {
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if got := u.updateAsked("v0.1.200"); got.State != "off" {
t.Fatalf("%+v: %+v", s, got)
}
if w, _ := u.waitingFor(); w {
t.Fatalf("%+v: a restart waits", s)
}
}
if err := settings.Save(settings.Settings{}); err != nil {
t.Fatal(err)
}
if got := u.updateAsked("v0.1.200"); got.State != "updating" {
t.Fatalf("newer asker: %+v", got)
}
if w, _ := u.waitingFor(); !w {
t.Fatal("no restart waits for the download")
}
u.mu.Lock()
u.state = "ready"
u.mu.Unlock()
time.Sleep(100 * time.Millisecond)
if restarts.Load() != 0 {
t.Fatal("restarted with a request in flight")
}
busy.set(gateway.Busy{Last: time.Now().Add(-time.Minute)})
eventually(t, "never restarted once idle", func() bool { return restarts.Load() == 1 })
Version = "dev"
if got := (&updater{exe: "/x"}).updateAsked("v0.1.200"); got.State != "unsupported" || got.Why != "source" {
t.Fatalf("a build from source: %+v", got)
}
Version = "v0.1.100"
restart := func() bool { return true }
for _, c := range []struct {
u *updater
why string
}{
{&updater{stuck: "container", autoRestart: restart}, "container"},
{&updater{stuck: "not-writable", autoRestart: restart}, "not-writable"},
{&updater{stuck: "translocated", autoRestart: restart}, "not-writable"},
{&updater{stuck: "package", packaged: &update.Packaged{Manager: "pacman", Package: "magpie-bin"}, autoRestart: restart}, "package"},
// magpie serve's place, with nothing that restarts it here
{&updater{exe: "/opt/magpie/magpie"}, "not-writable"},
} {
got := c.u.updateAsked("v0.1.200")
if got.State != "unsupported" || got.Why != c.why {
t.Errorf("%s: %+v", c.why, got)
}
if c.why == "package" && got.Manager == "" {
t.Errorf("package: no manager named: %+v", got)
}
if w, _ := c.u.waitingFor(); w {
t.Errorf("%s: a restart waits", c.why)
}
}
}
// The row of a Remote magpie says what its last ask came to, in words
// the page translates: updating for a while, or why it didn't, with the
// command a container or a package manager is updated by.
func TestRemoteUpdateNote(t *testing.T) {
provider.ForgetRemoteUpdatesForTest()
t.Cleanup(provider.ForgetRemoteUpdatesForTest)
now := time.Now()
if j := remoteUpdateNote("office", now); j != nil {
t.Fatalf("never asked: %+v", j)
}
cases := []struct {
out provider.RemoteUpdate
say, tip string
}{
{provider.RemoteUpdate{State: "updating", Version: "v0.1.200"}, "updating to {v}", "{v}"},
{provider.RemoteUpdate{State: "unsupported", Why: "container"}, "can't update itself", "docker pull ghcr.io/yetone/magpie:latest"},
{provider.RemoteUpdate{State: "unsupported", Why: "package", Manager: "Homebrew", Command: "brew upgrade magpie"}, "can't update itself", "{cmd}"},
{provider.RemoteUpdate{State: "unsupported", Why: "not-writable"}, "can't update itself", "update it there"},
{provider.RemoteUpdate{State: "off"}, "automatic updates off", "turned off"},
{provider.RemoteUpdate{State: "old"}, "update it there", "too old"},
{provider.RemoteUpdate{State: "refused"}, "update it there", "full access"},
}
for _, c := range cases {
provider.SetRemoteUpdateForTest("office", c.out)
j := remoteUpdateNote("office", now)
if j == nil || j.Say != c.say || !strings.Contains(j.Tip, c.tip) {
t.Errorf("%+v: %+v", c.out, j)
}
}
provider.SetRemoteUpdateForTest("office", provider.RemoteUpdate{State: "current"})
if j := remoteUpdateNote("office", now); j != nil {
t.Fatalf("current: %+v", j)
}
provider.SetRemoteUpdateForTest("office", provider.RemoteUpdate{State: "updating", Version: "v0.1.200"})
if j := remoteUpdateNote("office", now.Add(time.Hour)); j != nil {
t.Fatalf("updating, an hour on: %+v", j)
}
}
+206
View File
@@ -0,0 +1,206 @@
package provider
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"sync"
"time"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// A Remote magpie follows this one's version (nnlrl_75403 on Discord):
// once magpie here has updated, every Remote magpie it uses that is on an
// older release is asked to update itself too, as that magpie's own
// automatic update would, so the two don't drift apart and nobody has to
// go to the other computer. Nothing is set up for it: the provider's key
// is the owner's, and the remote takes the ask only with a gateway key of
// full access (gateway.remoteUpdate). A remote that can't update itself
// (Docker, a package manager's copy, a folder it can't write) says why,
// and the provider's row here shows it.
// RemoteUpdatePath has the gateway update this magpie to its channel's
// latest release, once it is newer than ?version= says the asker runs.
const RemoteUpdatePath = "/v1/magpie/update"
// RemoteUpdate is RemoteUpdatePath's answer, and what is kept here of a
// remote's last ask.
type RemoteUpdate struct {
// updating: it is being put in, and magpie restarts into it once
// idle; current: nothing newer to put in; off: automatic updates are
// turned off there; unsupported: it can't update itself (Why);
// old: a magpie from before RemoteUpdatePath; refused: the key isn't
// one of full access there
State string `json:"state"`
// Version is what the remote runs (as answered), or is updating to
// (kept here)
Version string `json:"version,omitempty"`
// Why it can't: container, package, not-writable, source
Why string `json:"why,omitempty"`
// Manager and Command, a package manager's copy: its name and what
// updates it
Manager string `json:"manager,omitempty"`
Command string `json:"command,omitempty"`
}
// remoteUpdateWait is how long a remote is waited for to take the ask:
// it answers once the download has started, not when it is done.
const remoteUpdateWait = 20 * time.Second
// AskRemoteUpdate asks the Remote magpie p to update itself, this magpie
// running version.
func AskRemoteUpdate(ctx context.Context, p Provider, version string) RemoteUpdate {
b, err := remoteBody(ctx, p, http.MethodPost, RemoteUpdatePath+"?"+url.Values{"version": {version}}.Encode(), remoteUpdateWait)
switch {
case err == nil:
var out RemoteUpdate
if json.Unmarshal(b, &out) != nil || out.State == "" {
return RemoteUpdate{State: "unknown"}
}
return out
case err.Error() == errRemoteNoShare:
return RemoteUpdate{State: "old"}
case errors.Is(err, errKeyHeld), err.Error() == errRemoteReadOnly, err.Error() == errRemoteKey, err.Error() == errRemoteNotShared:
return RemoteUpdate{State: "refused"}
}
return RemoteUpdate{State: "unknown"}
}
// RemoteVersion is the version the Remote magpie p answers GET /v1 with,
// "" when it can't be told.
func RemoteVersion(ctx context.Context, p Provider) string {
b, err := remoteBody(ctx, p, http.MethodGet, "/v1", RemoteHubWait)
if err != nil {
return ""
}
var info struct {
Name string `json:"name"`
Version string `json:"version"`
}
if json.Unmarshal(b, &info) != nil || info.Name != "magpie" {
return ""
}
return info.Version
}
// remoteUpdates is the last ask of each remote, by provider id.
var remoteUpdates struct {
sync.Mutex
m map[string]remoteUpdateAsked
}
type remoteUpdateAsked struct {
at time.Time
from string // the version this magpie ran when it asked
out RemoteUpdate
}
// remoteUpdateAgain is how long a remote that was asked isn't asked again
// for the same version; remoteUpdateShown, how long "updating" is shown.
const (
remoteUpdateAgain = 6 * time.Hour
remoteUpdateShown = 30 * time.Minute
)
// RemoteUpdateOf is what the Remote magpie id last answered an ask to
// update, when the row should say something of it: updating (for a
// while), or why it didn't.
func RemoteUpdateOf(id string, now time.Time) (RemoteUpdate, bool) {
remoteUpdates.Lock()
a, ok := remoteUpdates.m[id]
remoteUpdates.Unlock()
switch {
case !ok, a.out.State == "current", a.out.State == "unknown":
return RemoteUpdate{}, false
case a.out.State == "updating" && now.Sub(a.at) > remoteUpdateShown:
return RemoteUpdate{}, false
}
return a.out, true
}
// ForgetRemoteUpdatesForTest drops what remotes answered.
func ForgetRemoteUpdatesForTest() {
remoteUpdates.Lock()
remoteUpdates.m = nil
remoteUpdates.Unlock()
}
// SetRemoteUpdateForTest keeps out as id's last answer.
func SetRemoteUpdateForTest(id string, out RemoteUpdate) {
noteRemoteUpdate(id, "", out, time.Now())
}
func noteRemoteUpdate(id, from string, out RemoteUpdate, now time.Time) {
remoteUpdates.Lock()
if remoteUpdates.m == nil {
remoteUpdates.m = map[string]remoteUpdateAsked{}
}
remoteUpdates.m[id] = remoteUpdateAsked{at: now, from: from, out: out}
remoteUpdates.Unlock()
}
// UpdateRemotes asks every Remote magpie in use (on, not this one) on an
// older release than version to update itself, each at most once in
// remoteUpdateAgain for a version. Nothing is asked from a build that
// isn't a release, nor while automatic updates are off here: the user
// keeps this magpie where it is, and its remotes with it.
func UpdateRemotes(ctx context.Context, version string) {
if !update.Released(version) {
return
}
if s, err := settings.LoadChecked(); err != nil || s.NoAutoUpdate {
return
}
var wg sync.WaitGroup
for _, p := range remoteMagpies() {
if p.SelfAnswered() {
continue
}
remoteUpdates.Lock()
a, asked := remoteUpdates.m[p.ID]
remoteUpdates.Unlock()
if asked && a.from == version && time.Since(a.at) < remoteUpdateAgain {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
have := RemoteVersion(ctx, p)
if have == "" || !update.Released(have) {
return // unknown, or a build from source: its own to keep
}
if !update.Newer(version, have) {
noteRemoteUpdate(p.ID, version, RemoteUpdate{State: "current", Version: have}, time.Now())
return
}
out := AskRemoteUpdate(ctx, p, version)
if out.State == "updating" {
out.Version = version
}
log.Printf("remote magpie %s on %s, asked to update to %s: %s %s", remoteName(p), have, version, out.State, out.Why)
noteRemoteUpdate(p.ID, version, out, time.Now())
}()
}
wg.Wait()
}
// KeepRemotesUpdated runs UpdateRemotes a little after start (this magpie
// may just have updated) and every hour after, until ctx ends.
func KeepRemotesUpdated(ctx context.Context, version string) {
t := time.NewTimer(30 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
UpdateRemotes(ctx, version)
t.Reset(time.Hour)
}
}