provider: a Remote magpie's cards are passed on down a chain of magpies

yuyong_id (Discord) chains three magpies through Remote: magpie1 has a
Codex subscription, magpie2 uses magpie1, magpie3 uses magpie2. magpie2
showed magpie1's Codex card; magpie3 showed none.

Cause: since 8c71cd27f a magpie told only its own cards
(CachedCards kept From == "") and the receiver skipped any card it was
told with a From (remoteCards). So no card from a remote, of any
provider, reached a third magpie; Codex wasn't special. Antigravity and
DeepSeek showing at magpie3 means magpie2 has those accounts itself
(not checked with the reporter).

Fix:
- CachedCards passes on the cards it already holds from each Remote
  magpie (passedOnCards, from the 30s cache: it asks no remote, and a
  held remote's cards stay home).
- Each card told carries Via, the magpies (catalog.Self) it passed
  through; a receiver leaves out a card that comes back to it or has
  passed more than MaxVia magpies (catalog.Loops, the same rule as
  magpie_via for models).
- Refresh on a passed-on card ("m1/codex" at magpie2) goes to
  RefreshUsage, which asks that remote again, instead of a 400.
- Sibling: the status line (KeptQuotaReport, /v1/magpie/quotas?kept=1)
  read CachedCards too, so a magpie's own Remote cards were missing
  from it; now there.
- A held key still sees only own cards (quotaScope unchanged).
- Codex's resets stay with the magpie next door only, as before.
- catalog.Self becomes a func with SetSelfForTest, so one test process
  can play magpie2 and then magpie3.

Run on mote at b9cdac0c6 (rebased on origin/main 8a7f77cb7):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build ./...: ok.
- New TestRemoteChainPassesOnCards (magpie1 fake -> this gateway as
  magpie2 -> magpie3 reading it: Codex, Antigravity, GLM plan and a
  DeepSeek balance arrive, named "Codex · M1 · M2", Via [m1 m2],
  refresh reaches magpie1, a looped card is dropped),
  TestKeptReportHasRemoteCards and the updated TestRemoteMagpieCards,
  with TestRemoteMagpie*, TestRemoteSelf, Quota* and TestCachedCards:
  ok; -race -count=3 on the new and changed ones: ok.
- On origin/main with only these tests (and the Via field / Self func
  they compile against): all three FAIL. magpie3 gets just the
  "nothing read on that magpie yet" stand-in for magpie2, the kept
  report is empty, and the third magpie's card is nil.
- Full suite (-tags nogui -timeout 45m ./... under the suite lock):
  cut short when mote closed the connection, before any package
  reported. Rerunning at the pushed head.
- Rebased again onto origin/main e0f6eda64 (gateway changed): go vet
  of gateway, provider and catalog and the same targeted tests: ok on
  Linux (wsl-run magpie-desktop, -tags nogui); mote was refusing ssh.

Not tried: three real magpies on separate machines.
Not changed: a passed-on card's quota history (#5747).

Reported-by: yuyong_id (Discord)
This commit is contained in:
yetone
2026-11-09 12:47:12 +08:00
parent e0f6eda641
commit 08a42c40ff
7 changed files with 292 additions and 16 deletions
File diff suppressed because one or more lines are too long
+26 -1
View File
@@ -5,6 +5,7 @@ import (
"encoding/hex"
"slices"
"sync"
"sync/atomic"
)
// Two magpies can each be the other's Remote magpie (cdredfox on Discord:
@@ -35,12 +36,31 @@ const MaxVia = 8
// Self is this run of magpie's name in magpie_via: random, made up once a
// run, and told only to a magpie that asks for its list.
var Self = sync.OnceValue(func() string {
func Self() string {
if s := selfForTest.Load(); s != nil {
return *s
}
return self()
}
var self = sync.OnceValue(func() string {
b := make([]byte, 8)
rand.Read(b)
return hex.EncodeToString(b)
})
// selfForTest stands for Self while a test plays another magpie
// (SetSelfForTest).
var selfForTest atomic.Pointer[string]
// SetSelfForTest has Self be s, for a test that plays several magpies
// in one process one after another, until the returned func puts it
// back.
func SetSelfForTest(s string) (restore func()) {
was := selfForTest.Swap(&s)
return func() { selfForTest.Store(was) }
}
// loops reports whether a model another magpie lists by way of via leaves
// this magpie and comes back to it.
func loops(via []string) bool {
@@ -50,6 +70,11 @@ func loops(via []string) bool {
return len(via) > 1 && slices.Contains(via, Self())
}
// Loops reports whether what another magpie passes on by way of via (a
// model's magpie_via, a quota card's Via) leaves this magpie and comes
// back to it, or has passed through more magpies than MaxVia.
func Loops(via []string) bool { return loops(via) }
// ViaHere is the magpie_via a model goes out with in this magpie's list
// to another: the way it came here by, when it came from another magpie,
// then this one.
+6 -2
View File
@@ -1207,8 +1207,12 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
return
}
id, user := r.URL.Query().Get("provider"), r.URL.Query().Get("user")
if strings.Contains(id, "/") || provider.IsRemoteCard(id) { // a card this magpie has from another: not passed on
writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads only its own cards again")
// a card this magpie has from a Remote magpie of its own, which it
// passes on (provider.CachedCards), is read again there; the card
// standing for that remote itself, and any other id with a "/", is
// none this magpie tells
if remote := provider.IsRemoteCard(id); strings.Contains(id, "/") && !remote || remote && !strings.Contains(id, "/") {
writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads again only the cards it tells")
return
}
// a key told only some cards (#2216) has only those read again: a
+191
View File
@@ -0,0 +1,191 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// yuyong_id on Discord: magpie1 holds a Codex (ChatGPT) sign-in, magpie2
// uses magpie1 as a Remote magpie, and magpie3 uses magpie2. magpie2
// showed magpie1's Codex card; magpie3 showed none of it, as magpie2
// told another magpie only the cards of its own accounts. Every kind of
// card magpie1 tells comes through to magpie3 now, named after both
// magpies; a refresh pressed at magpie3 reaches magpie1; a card that
// comes round to a magpie it went through is left out.
func TestRemoteChainPassesOnCards(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
// magpie1, as its gateway answers (CachedCards): its own cards, each
// with the way it came by, magpie1 alone
var mu sync.Mutex
var refreshes []string
m1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("x-api-key") != "sk-magpie-m1" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.Method + " " + r.URL.Path {
case "GET " + provider.RemoteCardsPath:
case "POST " + provider.RemoteRefreshPath:
mu.Lock()
refreshes = append(refreshes, r.URL.Query().Get("provider")+"|"+r.URL.Query().Get("user"))
mu.Unlock()
default:
w.WriteHeader(http.StatusNotFound)
return
}
io.WriteString(w, `{"object":"list","data":[
{"provider":"codex","name":"Codex","icon":"codex-color","plan":"plus","user":"a@x.com","kind":"subscription","via":["m1"],
"windows":[{"name":"5h","used":37,"resetSecs":3600},{"name":"Week","used":12,"resetSecs":86400}],"resets":{"count":1}},
{"provider":"antigravity","name":"Antigravity","icon":"antigravity","user":"g@x.com","kind":"subscription","via":["m1"],
"windows":[{"name":"Gemini","used":5}]},
{"provider":"zhipu","name":"GLM Coding","kind":"plan","via":["m1"],"windows":[{"name":"5h","used":10}]},
{"provider":"deepseek","name":"DeepSeek","kind":"balance","balance":"¥12.00","via":["m1"],"windows":[]}]}`)
}))
defer m1.Close()
// magpie2: this process's gateway, magpie1 its Remote magpie
gw := httptest.NewServer(lanGuard(New().Handler()))
defer gw.Close()
if err := provider.Save(provider.Provider{ID: "m1", Name: "M1", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m1", Chat: m1.URL}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
// magpie2's Usage page reads magpie1's cards, as reported
var m2Codex bool
for _, q := range provider.RemoteCards(ctx) {
m2Codex = m2Codex || q.Provider == "m1/codex" && q.User == "a@x.com"
}
if !m2Codex {
t.Fatal("magpie2 doesn't show magpie1's Codex card")
}
m2Self := catalog.Self()
get := func(path string) []byte {
t.Helper()
res, err := http.Get(gw.URL + path)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
t.Fatalf("%s: %d %s", path, res.StatusCode, b)
}
return b
}
// what magpie2 tells magpie3, through its real handler
told := get(provider.RemoteCardsPath)
// magpie3: another magpie, with magpie2 as its Remote magpie, told
// what magpie2's gateway told
defer catalog.SetSelfForTest("m3")()
m2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method+" "+r.URL.Path != "GET "+provider.RemoteCardsPath {
w.WriteHeader(http.StatusNotFound)
return
}
w.Write(told)
}))
defer m2.Close()
if err := provider.Save(provider.Provider{ID: "m2", Name: "M2", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m2", Chat: m2.URL}); err != nil {
t.Fatal(err)
}
byID := map[string]provider.SubscriptionQuota{}
for _, q := range remoteOnly(provider.RemoteCards(ctx)) {
byID[q.Provider] = q
}
c, ok := byID["m2/m1/codex"]
if !ok || c.Name != "Codex · M1 · M2" || c.From != "M2" || c.User != "a@x.com" || c.Kind != "subscription" ||
len(c.Windows) != 2 || c.Windows[0].Used != 37 || c.Windows[1].Used != 12 {
t.Fatalf("magpie1's Codex card at magpie3: %+v (all: %+v)", c, byID)
}
// a reset is spent on the magpie next door only (UseRemoteCodexReset)
if c.Resets != nil {
t.Errorf("a reset two magpies away is offered: %+v", c.Resets)
}
if !slices.Equal(c.Via, []string{"m1", m2Self}) {
t.Errorf("the Codex card came by %v, want [m1 %s]", c.Via, m2Self)
}
// every kind passes on alike
for id, kind := range map[string]string{"m2/m1/antigravity": "subscription", "m2/m1/zhipu": "plan", "m2/m1/deepseek": "balance"} {
if q, ok := byID[id]; !ok || q.Kind != kind {
t.Errorf("%s at magpie3: %+v", id, q)
}
}
if q := byID["m2/m1/deepseek"]; q.Balance != "¥12.00" {
t.Errorf("magpie1's DeepSeek balance at magpie3: %+v", q)
}
// magpie2's own stand-in for magpie1, and its key's limit there, are
// its own business with magpie1
var cards []provider.SubscriptionQuota
json.Unmarshal(told, &struct {
Data *[]provider.SubscriptionQuota `json:"data"`
}{&cards})
for _, q := range cards {
if q.Provider == "m1" || q.GatewayKey != nil {
t.Errorf("magpie2 told magpie3 its own card of magpie1: %+v", q)
}
}
// a refresh pressed at magpie3 is read again at magpie1, by magpie2
res, err := http.Post(gw.URL+provider.RemoteRefreshPath+"?provider=m1/codex&user=a@x.com", "", nil)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
mu.Lock()
got := slices.Clone(refreshes)
mu.Unlock()
if res.StatusCode != 200 || !slices.Equal(got, []string{"codex|a@x.com"}) {
t.Errorf("magpie3's refresh of m1/codex: %d, magpie1 asked %v", res.StatusCode, got)
}
// a card that went through this magpie before is left out: magpie3
// told a card that came m3 → m2 shows nothing of it
told = []byte(`{"object":"list","data":[{"provider":"m2/codex","name":"Codex · M2","from":"M2","kind":"subscription","user":"loop@x.com","via":["m3","m2x"],"windows":[]}]}`)
provider.ForgetRemoteCardsForTest()
for _, q := range provider.RemoteCards(ctx) {
if q.User == "loop@x.com" {
t.Errorf("a card that came back round: %+v", q)
}
}
}
// magpie2's status line (GET /v1/magpie/quotas?kept=1, KeptQuotaReport)
// is told its Remote magpie's cards as last read, as its Usage page shows
// them: a magpie whose Codex is another's had none on its status line.
func TestKeptReportHasRemoteCards(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
m1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"object":"list","data":[{"provider":"codex","name":"Codex","user":"a@x.com","kind":"subscription","via":["m1"],"windows":[{"name":"5h","used":37}]}]}`)
}))
defer m1.Close()
if err := provider.Save(provider.Provider{ID: "m1", Name: "M1", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m1", Chat: m1.URL}); err != nil {
t.Fatal(err)
}
provider.RemoteCards(context.Background())
r := httptest.NewRequest("GET", "/v1/magpie/quotas?kept=1", nil)
r.RemoteAddr = "127.0.0.1:5000"
w := httptest.NewRecorder()
lanGuard(New().Handler()).ServeHTTP(w, r)
var got struct {
Data []provider.Quota `json:"data"`
}
json.Unmarshal(w.Body.Bytes(), &got)
for _, q := range got.Data {
if q.Provider == "m1/codex" && q.From == "M1" && len(q.Windows) == 1 && q.Windows[0].Used == 37 {
return
}
}
t.Fatalf("kept report: %d %s", w.Code, w.Body)
}
+47 -5
View File
@@ -105,8 +105,11 @@ const errRemoteUnreachable = "couldn't reach the remote magpie"
// CachedCards is the Usage page's cards as this magpie last read them,
// each with its kind, for another magpie to show: no vendor is asked,
// whatever their age, and another magpie's cards shown here aren't
// passed on.
// whatever their age. The cards a Remote magpie gave this one, as last
// read from it (passedOnCards), are passed on too, so a magpie that
// uses this one sees the accounts behind it as well (yuyong_id on
// Discord: a third magpie in a chain had none of the first's Codex
// cards). Each card carries the way it came by, this magpie last (Via).
//
// The cards are the page's with what was read of the same accounts and
// keys behind it since (cards_kept.go): a magpie serving only other
@@ -146,10 +149,36 @@ func CachedCards(now time.Time) []SubscriptionQuota {
for _, q := range g.qs {
if q.From == "" {
q.Kind = g.kind
q.Via = catalog.ViaHere(nil)
out = append(out, q)
}
}
}
return append(out, passedOnCards()...)
}
// passedOnCards are the cards of each Remote magpie this one uses, as
// last read from it (remoteCards, at most 30 seconds old while anything
// here shows them): no remote is asked, so a chain of magpies, or two
// that are each the other's Remote, never asks along itself. A remote
// read nothing from, or holding this magpie's key (errKeyHeld), passes
// on nothing; the card standing for the remote itself and its keys'
// limits (remoteKeyCards) are this magpie's own business with it.
func passedOnCards() []SubscriptionQuota {
var out []SubscriptionQuota
for _, p := range remoteMagpies() {
c := &remoteCardCache
c.Lock()
r := c.m[remoteCardsID(p)]
c.Unlock()
if r.held {
continue
}
for _, q := range namedRemoteCards(p, r.cards) {
q.Via = catalog.ViaHere(q.Via)
out = append(out, q)
}
}
return out
}
@@ -266,9 +295,22 @@ func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuot
}
return []SubscriptionQuota{{Provider: p.ID, Name: name, Icon: "magpie", Kind: "subscription", From: name, Windows: []QuotaWindow{}, Error: msg}}
}
out := make([]SubscriptionQuota, 0, len(r.cards))
for _, q := range r.cards {
if q.From != "" || q.Provider == "" {
return namedRemoteCards(p, r.cards)
}
// namedRemoteCards is cards, as the remote magpie p told them, named for
// this computer. A card p has from a magpie behind it (its own Remote
// magpie, yuyong_id on Discord: magpie3 → magpie2 → magpie1, and
// magpie3 had magpie1's Codex card from nobody) comes with the way it
// came by (Via) and is named after it ("Codex · magpie1 · magpie2",
// "magpie2/magpie1/codex"); one whose way leaves this magpie and comes
// back to it (two magpies each the other's Remote) is left out, as a
// model listed that way is (catalog.Loops).
func namedRemoteCards(p Provider, cards []SubscriptionQuota) []SubscriptionQuota {
name := remoteName(p)
out := make([]SubscriptionQuota, 0, len(cards))
for _, q := range cards {
if q.Provider == "" || catalog.Loops(q.Via) {
continue
}
q.Provider = p.ID + "/" + q.Provider
+16 -7
View File
@@ -11,6 +11,8 @@ import (
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// fakePeer is another magpie's gateway as RemoteCards asks it: its kept
@@ -102,8 +104,10 @@ func remoteQuotaHome(t *testing.T, peer http.Handler) {
// 莫 on Discord: a computer whose providers are another's magpie showed
// no quota at all. It now shows the other magpie's cards, named with it
// and kept apart from its own by id, in their kinds; what a card's
// buttons would do to this computer's accounts is left off, and a card
// the other magpie has from a third isn't passed on.
// buttons would do to this computer's accounts is left off. A card the
// other magpie has from a third is shown too, named after both
// (yuyong_id on Discord), with no reset to spend from here; one that has
// been through this magpie before is left out (a loop).
func TestRemoteMagpieCards(t *testing.T) {
peer := &fakePeer{cards: []SubscriptionQuota{
{Provider: "codex", Name: "Codex", Icon: "codex", User: "a@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}},
@@ -111,7 +115,9 @@ func TestRemoteMagpieCards(t *testing.T) {
{Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}},
Resets: &ResetCredits{Count: 2, ByWindow: true}},
{Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00"},
{Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home"},
{Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home", User: "b@x.com", Via: []string{"home-self", "office-self"},
Windows: []QuotaWindow{{Name: "5h", Used: 20}}, Resets: &ResetCredits{Count: 1}},
{Provider: "back/codex", Name: "Codex · Back", Kind: "subscription", From: "Back", User: "c@x.com", Via: []string{catalog.Self(), "office-self"}},
}}
remoteQuotaHome(t, peer)
ctx := context.Background()
@@ -139,10 +145,14 @@ func TestRemoteMagpieCards(t *testing.T) {
if b := find(balances, "office/deepseek"); b == nil || b.Balance != "¥12.00" {
t.Errorf("balance: %+v", balances)
}
h := find(subs, "office/home/codex")
if h == nil || h.Name != "Codex · Home · Office" || h.From != "Office" || h.User != "b@x.com" || len(h.Windows) != 1 || h.Windows[0].Used != 20 || h.Resets != nil {
t.Errorf("a third magpie's card: %+v", h)
}
for _, qs := range [][]SubscriptionQuota{subs, plans, balances} {
for _, q := range qs {
if strings.Contains(q.Provider, "home") {
t.Errorf("a third magpie's card passed on: %+v", q)
if strings.Contains(q.Provider, "back") {
t.Errorf("a card that came back through this magpie: %+v", q)
}
}
}
@@ -233,8 +243,7 @@ func TestRemoteMagpieUnreachable(t *testing.T) {
}
// The cards told to another magpie are this one's as last read: nothing
// is read for it, however old they are, and another magpie's aren't
// passed on.
// is read for it, however old they are.
func TestCachedCardsAskNobody(t *testing.T) {
azureHome(t)
c := &subscriptionUsageCache
+5
View File
@@ -240,6 +240,11 @@ type SubscriptionQuota struct {
// From is the remote magpie a card is that one's (remote_quotas.go),
// by its name here; "" for this computer's own.
From string `json:"from,omitempty"`
// Via is the magpies (catalog.Self) a card told another magpie
// passed through, the one that read it first, this one last
// (CachedCards): the receiver leaves out a card that comes back to
// it (catalog.Loops). Only between magpies; nil here.
Via []string `json:"via,omitempty"`
// LastServedAt is when the account, plan or key last answered a
// request through this computer's gateway, nil when it hasn't in the
// last 30 days (served.go); set by Quotas, never cached.