magpie icon indicating copy to clipboard operation
magpie copied to clipboard

Sign-ins sync (`WithSignIns` / `signIns:true`) copies single-use rotating refresh tokens to a second computer, where both machines race to refresh and the loser is signed out for good

Open skalitz-wolf opened this issue 4 weeks ago • 7 comments

What happens

A MiniMax Code account (@magpie-community/opencode-minimax-auth, both minimax-code and minimax-code-global) needs a fresh device sign-in roughly once a day once sign-ins are included in magpie's sync. It does not recover on its own: logins.json marks the account lapsed, plugin-auth.json still holds the old tokens, and every auth.refresh, provider.models and daily check-in keeps failing until a human signs in again.

The same happens to a Qoder account over the same period. Accounts whose credentials are long-lived (zcode, workbuddy) are unaffected.

This is not "the vendor's access token is short-lived". Short expires_in is expected and the plugin is built for it: auth.refresh with refreshLead = 10 min renews ahead of expiry, and a 401 force-refreshes and retries. The failure is that the refresh itself is refused.

Why

MiniMax Code (and Qoder / Trae) spend a refresh token once: a refresh returns a new refresh token and invalidates the old one. Replaying the old one answers HTTP 400 invalid_grant. The plugin treats exactly that as fatal:

const signedOut = (e) => e instanceof OAuthError && e.code === "invalid_grant" && e.httpStatus === 400
// -> new SignInExpired(site)  ("this MiniMax Code account is signed out; sign in again")

MiniMax's own client serialises this with a cross-process lock plus a generation counter. In magpie:

  1. WithSignIns / signIns:true deliberately puts plugin-auth.json into the sealed backup so that "another computer comes out signed in" (internal/backup/signins_carry_test.go). That is a sensible feature for copyable credentials (API keys, long-lived JWTs, zcode's self-contained JSON state).
  2. For a single-use refresh token, copying means two owners of one token. It is not a copy, it is a race. Both machines call auth.refresh at expires - refreshLead — and magpie calls auth.refresh for every plugin account on startup, whether the account is used or not — so the second machine spends the token even if it never sends a single request to that provider.
  3. The loser gets invalid_grant, is marked signed out, and there is no self-heal: fresh() can only recover if a newer refresh token has already reached its auth store, and sync does not bring it back in time (it runs on autoEvery: 60).
  4. Re-signing in on the winner produces a new generation, sync carries it over, and the cycle repeats on the next token lifetime — hence "about once a day".

Auto-restart (autoRestart: true, hourly update checks) makes this worse: each restart starts a new plugin host that re-reads the store, and the plugins only deduplicate refreshes within one process (renewing / renewed maps in index.mjs). There is no cross-process lock.

Evidence (all credentials redacted; only token fingerprints compared)

When (UTC+8) What
before 2026-11-04 19:45 No minimax errors at all in app.log (log starts 10-31); remote sync backups up to 10-20 contain no signIns section
2026-11-04 19:45 Sign-ins sync enabled (sync.json: keys:true, signIns:true, autoEvery:60); the account is re-signed in at the same instant
2026-11-04 20:47 First auth.refresh: this MiniMax Code account is signed out; sign in again — about an hour later
2026-11-04 23:06 First remote backup carrying signIns.plugins['minimax-code']
2026-11-05 00:00, 11-06 00:00 Daily check-ins still succeed (+400, streak 2 and 3), so the chain stayed alive between re-logins
2026-11-06 15:25:14 auth.refresh fails again — exactly 10 minutes before the stored expires of 15:35:14, i.e. the scheduled refreshLead renewal, not a natural expiry
2026-11-06 15:25 → 11-07 10:41 The same error every ~30-60 min, ~90 times; all check-ins fail

The sealed sync backups show two different refresh-token fingerprints for the same account (one in the 11-04 backup, another in the 11-07 backup / local plugin-auth.json), i.e. the credential really did change generations inside the sync path. A second computer is active on the same sync target during those days (its usage data runs through 11-06) although it never issues a single request to minimax-code — consistent with magpie renewing every account on startup.

Corroboration: the Qoder account reports qoder job token refresh: status 401 continuously over the same window; zcode/workbuddy accounts, whose refresh tokens are long-lived, never do. The dividing line is "does the refresh token rotate", not "is the account synced".

Minimal repro

  1. Two computers share one WebDAV sync target, both with signIns:true (WithSignIns) and autoEvery:60; both run the minimax-code plugin.
  2. Sign in to MiniMax Code on A; let sync carry the sign-in to B (or restore a keyed backup with sign-ins on B).
  3. Leave both magpie instances running. Startup on B already calls auth.refresh for the account it never uses.
  4. At expires - refreshLead, both spend the same refresh token. One rotates to a new generation; the other gets 400 invalid_grant → SignInExpired → lapsed, with no recovery short of a device sign-in.
  5. Re-sign in on A, sync, repeat on the next lifetime.

Suggested fix

In order of how local the change is:

  1. Let a credential declare that it cannot be shared. A plugin-side flag on the auth (e.g. rotating: true / nonTransferable: true, alongside refreshLead) that WithSignIns, restore and sync honour: exclude those accounts by default, or at least warn in the UI that "this sign-in cannot be shared with another computer". A per-account / per-provider "this computer only" switch would fit the same shape as the per-agent switches in #4648. This keeps the VPS-restore feature that motivated WithSignIns intact for everyone else.
  2. Make sync generation-aware. Track a per-account credential fingerprint, accept only a newer generation, never write an older one back, and surface a divergence instead of silently replacing. Today a stale generation can be restored over a live one.
  3. Self-heal on invalid_grant in the host. Before declaring a plugin sign-in lapsed, re-read the auth store / re-fetch from sync once and retry with the newer token if one appeared. The plugin already has this path (now.refresh !== a.refresh), but nothing delivers the newer generation to it. Related: #5080 covers renewing idle accounts on a timer; this is the other half — renewing them from two places at once. #1674 (a read-only CLI rewriting logins.json over a refreshed token, no lock) is the same class of hazard on the built-in store.

Workaround in use

Turn signIns off on both computers, keep the rotating-token accounts signed in on one machine only, and sign in once more there. Verified hypothesis so far: if the account survives several token lifetimes with sync off, the server's short expires_in is not the cause.

Environment

magpie 0.1.3214, Windows; @magpie-community/opencode-minimax-auth 0.2.3; @magpie-community/opencode-qoder-auth; WebDAV sync with signIns:true, keys:true, autoEvery:60; autoRestart:true, updateEvery:60.

Related: #5080, #1674, #3927, #4917.

skalitz-wolf avatar Nov 07 '26 03:11 skalitz-wolf

Correction after checking the current source and the live remote backup. Please disregard one part of the report above.

I wrote that sync restores a stale generation over a live one, i.e. mirrors the sign-ins as a whole. That is wrong. Current internal/davsync/davsync.go merges sign-ins per account (provider.MergeSignIns → provider.ApplySignIns(plan), "merged one by one, the later renewed of each account staying"), and provider.RestoreSignIns is documented as not writing over a sign-in renewed later on this machine. So fix 2 in the report (make sync generation-aware) is partly already implemented upstream.

What I can actually measure: I fetched the sealed backup from the sync server and compared it with this computer's plugin-auth.json, fingerprints only. Both hold the same MiniMax Code generation, with the same expiry, and it is already expired. There is no newer generation anywhere in the sync path to recover from, so the self-heal path ("the losing machine fetches the winner's new token") has no source; a device sign-in is required.

The main observation stands: a single-use rotating refresh token replicated to two places, plus proactive auth.refresh on every host, produces HTTP 400 invalid_grant and a permanent signed-out state. But the reason recovery fails is not an older generation being restored — it is that no newer generation was ever produced and propagated. Fix 3 (self-heal on invalid_grant by re-reading the auth store) should be read in that light: it only helps if something else has already put a newer generation there.

Happy to add a reproduction with two machines running a minimal relay if that would be more useful than the timeline.

skalitz-wolf avatar Nov 07 '26 08:11 skalitz-wolf

take

ggbdpq avatar Nov 07 '26 14:11 ggbdpq

@yetone a sign-in whose refresh token is good once ends up on every computer that syncs, and the vendor lets only one of them keep it — @skalitz-wolf's report (and their correction comment, which this fix takes as its starting point: the per-account merge already keeps the later generation, so the hazard is the copying itself, not an older generation coming back).

Root cause: WithSignIns / signIns:true collects every plugin sign-in (provider.CollectSignIns, internal/provider/signins_carry.go:212) into the sealed backup, so a credential the vendor spends once — MiniMax Code and Qoder rotate the refresh token on every renewal — becomes a two-owner token. Each computer renews it as it comes due (the gateway's keep-alive, internal/provider/plugin_keepalive.go; the host serialises renewals per machine with a lock file, internal/plugin/host.js lockRenew, but two computers share no lock), the loser's refresh answers invalid_grant, the account is marked signed-out for good, and the sync path holds no newer generation to come back from — a device sign-in is the only way out, until the next token lifetime repeats the race.

The fix, following the reporter's own analysis ("let a credential declare that it cannot be shared"): the auth hook declares rotating beside keepAlive and refreshLead; the host passes it in the providers' row (internal/plugin/host.js rowOf), and the carry path honours it — CollectSignIns leaves such sign-ins out of what a backup or a sync carries, and SignIns.records leaves out what an older backup or sync already carried, so MergeSignIns neither puts one in nor pushes one up, and RestoreSignIns applies none. The tradeoff, on purpose: a rotating sign-in is one computer's own — each computer signs in to such a provider itself, and the VPS-restore feature keeps working for every credential that is copyable. Nothing is deleted: local sign-ins are untouched, and a copy already on the server falls out of the carried set by the usual removal on the next sync of each computer.

patch: provider, plugin: a sign-in whose refresh token rotates is never carried (#5583) — git am applies it as is; SHA-256 first 16: 56deb94189b2a15d
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Sat, 7 Nov 2026 22:19:04 +0800
Subject: [PATCH] provider, plugin: a sign-in whose refresh token rotates is
 never carried (#5583)

A plugin whose vendor spends a refresh token once (the auth hook's
rotating) signs one computer in. Carried by a backup or a sync, the
second computer becomes the token's second owner: both renew it as it
comes due, the vendor turns the loser away (invalid_grant), and with no
newer generation anywhere in the sync path only a device sign-in brings
the account back (#5583, skalitz-wolf).

The auth hook declares rotating beside keepAlive and refreshLead; the
host passes it in the providers' row, and CollectSignIns leaves such
sign-ins out of what a backup or a sync carries, MergeSignIns and
RestoreSignIns leave out what an older backup or sync already carried.
Each computer signs in to such a provider itself; the local sign-ins
are untouched, and a copy already on the server falls out of the
carried set by the usual removal, on the next sync of each computer.

Tests: TestCollectSignInsLeavesARotatingSignInOut,
TestMergeSignInsDoesNotTakeARotatingSignInIn,
TestRestoreSignInsLeavesARotatingSignInOut (red before, green after;
go test ./internal/provider/ ./internal/backup/ ./internal/davsync/
-tags nogui; go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui,
GOOS=windows go build).

Generated-by: GLM-5.3-Flash (ZCode)
---
 internal/plugin/host.js                 |   4 +
 internal/plugin/providers.go            |   6 ++
 internal/provider/signins_carry.go      |  57 +++++++++++--
 internal/provider/signins_carry_test.go | 105 ++++++++++++++++++++++++
 4 files changed, 165 insertions(+), 7 deletions(-)

diff --git a/internal/plugin/host.js b/internal/plugin/host.js
index 2bc993b3d..ddfe26735 100644
--- a/internal/plugin/host.js
+++ b/internal/plugin/host.js
@@ -2483,6 +2483,10 @@ function rowOf(id, a, keys, stored, p, own) {
     // long before expires (keepSignedIn)
     renews: keepsAlive(a.auth),
     renewLead: keepsAlive(a.auth) ? leadOf(a.auth) : 0,
+    // the vendor spends a refresh token once: renewed, the old one is
+    // refused (invalid_grant). magpie never carries such a sign-in to
+    // another computer (#5583)
+    rotating: a.auth.rotating === true,
     options: optionsOf(a.auth),
     decide: p.decide === true,
     searches: p.searches === true,
diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go
index da5184e57..f4335a268 100644
--- a/internal/plugin/providers.go
+++ b/internal/plugin/providers.go
@@ -150,6 +150,12 @@ type Provider struct {
 	// 5 minutes when not said), as the host reckons it (RenewAt).
 	Renews    bool  `json:"renews,omitempty"`
 	RenewLead int64 `json:"renewLead,omitempty"`
+	// Rotating is the auth hook declaring that the vendor spends a refresh
+	// token once (auth.rotating): renewed, the old one is refused
+	// (invalid_grant). Two computers holding a copy would race to renew it
+	// and the loser is signed out for good, so its sign-ins are never
+	// carried by a backup or a sync (provider.CollectSignIns, #5583).
+	Rotating bool `json:"rotating,omitempty"`
 	// Options are the switches the plugin declares for the provider
 	// (auth.options, #2038), as the host checked them
 	Options []Option `json:"options,omitempty"`
diff --git a/internal/provider/signins_carry.go b/internal/provider/signins_carry.go
index 1ca2af3e9..c1172a13a 100644
--- a/internal/provider/signins_carry.go
+++ b/internal/provider/signins_carry.go
@@ -18,7 +18,14 @@ package provider
 //     over. Codex's auth.json is written, temp-and-rename, only when Codex
 //     is signed out here and the user hasn't removed its account; Claude
 //     Code's keychain is never touched: a saved Claude account is served
-//     by the gateway as it is.
+//     by the gateway as it is;
+//   - a plugin whose auth hook says rotating (the vendor spends a refresh
+//     token once: renewed, the old one answers invalid_grant) is never
+//     carried at all — a copy on a second computer would race this one to
+//     renew it, and the vendor would turn the loser away for good, with
+//     no newer generation anywhere to come back from (#5583). It stays
+//     signed in on the computer that signed in, and one carried by a
+//     backup or a sync made before the plugin said so is left out here.
 
 import (
 	"bytes"
@@ -146,7 +153,9 @@ func credTime(auth json.RawMessage, renewed time.Time) time.Time {
 
 // records are s's sign-ins by id. Two of one id (accounts told apart here
 // in a way that doesn't carry) are left out both: neither is put over the
-// other, nor anything here.
+// other, nor anything here. A plugin whose provider says its refresh
+// token rotates (Rotating, the auth hook's rotating) is left out too:
+// its sign-in is one computer's alone (#5583).
 func (s *SignIns) records() map[string]signInRec {
 	out := map[string]signInRec{}
 	if s == nil {
@@ -168,12 +177,33 @@ func (s *SignIns) records() map[string]signInRec {
 		}
 		add(signInRec{id: loginRecID(l), hash: credHash(l.Auth), at: credTime(l.Auth, l.Renewed), login: &l})
 	}
-	for k, raw := range s.Plugins {
-		var at time.Time
-		if ms := plugin.AuthExpires(raw); ms > 0 {
-			at = time.UnixMilli(ms)
+	if len(s.Plugins) > 0 {
+		rotating := rotatingPlugins()
+		for k, raw := range s.Plugins {
+			if rotating[plugin.ProviderOf(k)] {
+				continue // a refresh token the vendor spends once (#5583)
+			}
+			var at time.Time
+			if ms := plugin.AuthExpires(raw); ms > 0 {
+				at = time.UnixMilli(ms)
+			}
+			add(signInRec{id: pluginRecID(k, raw), hash: credHash(raw), at: at, key: k, raw: raw})
+		}
+	}
+	return out
+}
+
+// rotatingPlugins are the ids of the plugins whose auth hook says their
+// refresh tokens rotate (Rotating): a sign-in of theirs is never carried,
+// so no computer holds a copy of a token the vendor lets be spent once
+// (#5583). A plugin not listed (not asked yet) is taken not to: only what
+// a plugin says of its own is believed.
+func rotatingPlugins() map[string]bool {
+	out := map[string]bool{}
+	for _, p := range plugin.Cached() {
+		if p.Rotating {
+			out[p.ID] = true
 		}
-		add(signInRec{id: pluginRecID(k, raw), hash: credHash(raw), at: at, key: k, raw: raw})
 	}
 	return out
 }
@@ -222,6 +252,19 @@ func CollectSignIns() (*SignIns, error) {
 		return nil, fmt.Errorf("the plugins' sign-ins can't be read: %w", err)
 	}
 	s := &SignIns{Plugins: pl}
+	// a plugin whose refresh token rotates is left out: its sign-in is one
+	// computer's alone, never a backup's or a sync's to copy (#5583)
+	if len(s.Plugins) > 0 {
+		rotating := rotatingPlugins()
+		for k := range s.Plugins {
+			if rotating[plugin.ProviderOf(k)] {
+				delete(s.Plugins, k)
+			}
+		}
+		if len(s.Plugins) == 0 {
+			s.Plugins = nil
+		}
+	}
 	live, _, lerr := readCodexLogin(codexHome(), false)
 	for _, l := range ls {
 		if !carried(l) {
diff --git a/internal/provider/signins_carry_test.go b/internal/provider/signins_carry_test.go
index edfeaa672..4da746594 100644
--- a/internal/provider/signins_carry_test.go
+++ b/internal/provider/signins_carry_test.go
@@ -10,6 +10,7 @@ import (
 	"time"
 
 	"github.com/yetone/magpie/internal/plugin"
+	"github.com/yetone/magpie/internal/settings"
 )
 
 // Sign-ins in a backup or a sync (qianxunji and curtinp118 on Discord:
@@ -320,3 +321,107 @@ func TestApplySignInsKeepsWhatChangedSinceTheMerge(t *testing.T) {
 		t.Fatalf("written over: %s", ls[0].Auth)
 	}
 }
+
+// A plugin whose vendor spends a refresh token once (the auth hook's
+// rotating) signs one computer in: carried to a second, both renew it as
+// it comes due, and the vendor turns the loser away for good, with no
+// newer generation anywhere in the sync path to come back from (#5583,
+// skalitz-wolf). Its sign-in is never carried.
+func declaresRotating(t *testing.T) {
+	t.Helper()
+	t.Setenv("MAGPIE_BUN", "") // nothing here runs a plugin
+	write := func(name string, v any) {
+		b, _ := json.Marshal(v)
+		os.MkdirAll(settings.Dir(), 0o700)
+		if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil {
+			t.Fatal(err)
+		}
+	}
+	minimax, kiro := "@magpie-community/opencode-minimax-auth", "@example/opencode-kiro-auth"
+	write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": minimax}, {"spec": kiro}}})
+	plugin.UseCached([]plugin.Provider{
+		// the vendor spends a refresh token once: two computers holding a
+		// copy race to renew it (#5583)
+		{ID: "minimax-code", Spec: minimax, Renews: true, Rotating: true},
+		{ID: "kiro", Spec: kiro},
+	})
+	t.Cleanup(func() { plugin.UseCached(nil) })
+}
+
+func writePluginAuth(t *testing.T, m map[string]any) {
+	t.Helper()
+	b, _ := json.Marshal(m)
+	if err := os.MkdirAll(filepath.Dir(plugin.AuthPath()), 0o700); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(plugin.AuthPath(), b, 0o600); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestCollectSignInsLeavesARotatingSignInOut(t *testing.T) {
+	signIn(t)
+	declaresRotating(t)
+	writePluginAuth(t, map[string]any{
+		"minimax-code": map[string]any{"type": "oauth", "access": "m", "refresh": "r1", "expires": 3000, "accountId": "[email protected]"},
+		"kiro":         map[string]any{"type": "oauth", "access": "k", "refresh": "r", "expires": 3000, "accountId": "[email protected]"},
+	})
+	s, err := CollectSignIns()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, ok := s.Plugins["minimax-code"]; ok {
+		t.Fatal("a rotating sign-in is carried: the second computer becomes the token's second owner (#5583)")
+	}
+	if _, ok := s.Plugins["kiro"]; !ok {
+		t.Fatal("a plain sign-in stopped being carried")
+	}
+}
+
+func TestMergeSignInsDoesNotTakeARotatingSignInIn(t *testing.T) {
+	signIn(t)
+	declaresRotating(t)
+	remote := &SignIns{Plugins: map[string]json.RawMessage{
+		"minimax-code": json.RawMessage(`{"type":"oauth","access":"m","refresh":"r2","expires":5000,"accountId":"[email protected]"}`),
+		"kiro":         json.RawMessage(`{"type":"oauth","access":"k","refresh":"r","expires":5000,"accountId":"[email protected]"}`),
+	}}
+	_, plan, hashes := MergeSignIns(nil, remote, nil) // a computer joining
+	for _, r := range plan.put {
+		if r.key == "minimax-code" {
+			t.Fatal("a rotating sign-in is put in here: the token's second owner (#5583)")
+		}
+	}
+	if _, ok := hashes["plugin|minimax-code|[email protected]"]; ok {
+		t.Fatal("a rotating sign-in goes up")
+	}
+	if _, ok := hashes["plugin|kiro|[email protected]"]; !ok {
+		t.Fatal("a plain sign-in stopped going up")
+	}
+}
+
+func TestRestoreSignInsLeavesARotatingSignInOut(t *testing.T) {
+	signIn(t)
+	declaresRotating(t)
+	writePluginAuth(t, map[string]any{
+		"kiro": map[string]any{"type": "oauth", "access": "k", "refresh": "r", "expires": 3000, "accountId": "[email protected]"},
+	})
+	s := &SignIns{Plugins: map[string]json.RawMessage{
+		// a backup made before the plugin said so, or on a magpie older
+		// than the flag
+		"minimax-code": json.RawMessage(`{"type":"oauth","access":"m","refresh":"r2","expires":5000,"accountId":"[email protected]"}`),
+	}}
+	r, err := RestoreSignIns(s)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if r.Added != 0 {
+		t.Fatalf("a backup's rotating sign-in is put in: the token's second owner (#5583): %+v", r)
+	}
+	m, err := plugin.AuthEntries()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, ok := m["minimax-code"]; ok {
+		t.Fatal("a rotating sign-in was written to plugin-auth.json")
+	}
+}
-- 
2.50.1 (Apple Git-155)

Branch with the commit: fix/5583-davsync-signins-token (head 683aa128c166bdc9092ceced09811457c68e773a), rebased onto current upstream/main (970a86ff3); on a fresh checkout git am applies clean.

Check Result
TestCollectSignInsLeavesARotatingSignInOut (new) red before the fix, pass after
TestMergeSignInsDoesNotTakeARotatingSignInIn (new) red before the fix, pass after
TestRestoreSignInsLeavesARotatingSignInOut (new) red before the fix, pass after
sign-ins carry neighbours (TestMergeSignInsTheLaterRenewedStays, TestMergeSignInsRemovedOnlyWhenTheOtherSideRemovedIt, TestRestoreSignInsNeverWritesAnOlderTokenOver, TestApplySignInsPlugins, …) pass
go test ./internal/provider/ -tags nogui -timeout 25m -count=1 ok (120s), zero failures
go test ./internal/backup/ ./internal/davsync/ -tags nogui -count=1 ok (6s / 42s), zero failures
go test ./internal/plugin/ -tags nogui -count=1 1 failure: TestHostToldTheGatewayAddress — host_addr_test.go:78, the known port race (the plugin is told a gateway port that already moved); fails the same on upstream/main checked this round, not caused by this patch
targeted -race (carry family) pass
-race on ./internal/backup/ ./internal/davsync/ pass
-race on ./internal/provider/ 1 failure: TestPluginCheckinAsksAgainAtUntil reports a DATA RACE between a test writing a global (plugin_checkin_test.go:744) and a leaked plugin-host catalog goroutine; reproduced on the parent commit, pre-existing
gofmt -l on the changed files prints nothing
go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./... clean
go build; GOOS=linux go build -tags nogui; GOOS=windows go build clean
Ablation reverting internal/provider/signins_carry.go alone turns the three new tests red with the reported shape (the rotating sign-in is carried, put in and restored); restored, green
Re-verified on upstream/main 970a86ff3 rebased twice this round as the tip moved (8373aaf14a → 784113472d → 970a86ff3); the package tests, vet and builds above were re-run on the final head

Not verified: the two-computer race itself on real machines and real MiniMax Code / Qoder accounts — NOT-RUNNABLE here (needs two computers on one WebDAV target and the vendor's own refusal behaviour); that face stays with @skalitz-wolf. Also: the flag does nothing until a plugin declares it — @magpie-community/opencode-minimax-auth 0.2.3 and the Qoder plugin keep today's behaviour until their auth hooks add rotating (a companion change in the plugin packages, not in magpie). With rotating undeclared, everything carries exactly as before.

Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.

Generated-by: GLM-5.3-Flash (ZCode)

ggbdpq avatar Nov 07 '26 14:11 ggbdpq

Thanks @ggbdpq for writing this up — the root-cause analysis matches what I measured, and a rotating declaration on the auth hook is the right primitive. I'm not asking you to change the patch; the tradeoff is explicit and reasonable for many users. I'm replying as the reporter of #5583 to put one constraint on the record for @yetone.

The reason I filed this is the opposite of "fine, I'll sign in on each computer": I sign in at home and expect the account to be there at the office — exactly what WithSignIns was added for. A per-computer device sign-in is the cost I was trying to remove. I'm happy to accept an occasional 401 plus a short automatic recovery; I'm not happy to give up the sync itself.

There is a third option between "copy the credential so two owners race" and "never carry it": carry it as one generation chain rather than two independent credentials.

  1. On invalid_grant, don't give up for good. renewLocked records unrenewed.gone and stops retrying until the credentials on disk change — but changed() already clears that. Re-reading the auth store, or doing one fetch, before declaring a sign-in dead would recover automatically once another computer has pushed the newer generation. This alone removes the daily manual login.
  2. Push a renewed generation promptly instead of waiting for the 60-minute sync; that propagation gap is a large part of why there was "no newer generation to come back from" in my measurements.
  3. Optionally, a cross-computer lease so only one host renews — that removes even the 401.

I have a small userland plugin doing (1) and (2): a WebDAV generation relay that puts the newer generation back through client.auth.set, with signIns left on for all the other subscriptions. So this is a working workaround, not a hypothetical. The real two-machine race is being verified tomorrow and I'll post the log here; @ggbdpq's "Not verified" note applies to me too.

One more data point for the comparison: this proposal also needs a companion change in the community plugins (rotating is undeclared in 0.2.3 today), so a generation-aware carry is not obviously more upstream work than never carrying.

Concretely: could rotating be a policy (carry: never | relay) with never as the safe default, plus a re-check before a sign-in is declared dead? Happy to test a branch on two machines. If magpie ends up taking the "never carried" direction I'll retire my relay — I'd just like the option that keeps cross-computer sync to be considered first.

skalitz-wolf avatar Nov 08 '26 14:11 skalitz-wolf

@skalitz-wolf thanks for putting the constraint on the record. Signing in at home and finding the account already at the office is exactly what WithSignIns exists for — I'm counting that as a requirement in the evidence chain, not a preference to trade away.

One clarification: your generation chain and the current patch aren't competing — they're tiers of one policy on the same rotating primitive: carry: never (what the patch ships, the safe default) and carry: relay (your generation-chain carry, which your relay plugin already proves works in userland). Whether rotating graduates from a boolean to that policy is @yetone's call; if it goes the relay direction, I'm glad to build the follow-up patch.

Your point 1 is worth doing under either tier, because it doesn't depend on the carry form at all: re-reading the auth store (or making one fetch) before a sign-in is declared dead — with changed() already clearing unrenewed.gone, the latch isn't the obstacle — removes the daily manual login whether carrying is never or relay.

Your two-machine logs tomorrow are the key data for either direction; waiting on those.

(AI disclosure: drafted with AI assistance; I've read the full thread and stand behind it.)

ggbdpq avatar Nov 08 '26 14:11 ggbdpq

Shipped in v0.1.3363 (8a7f77cb7): the safe default, on @ggbdpq's rotating primitive.

What changed: a plugin sign-in whose vendor spends a refresh token once is never carried by Sync, a backup or a Restore, so it has only one owner. MiniMax Code (minimax-code, minimax-code-global) and Qoder (qoder, qoder-cn) are covered now. magpie knows them itself, because the plugins don't declare rotating yet; that companion change is magpie-community/plugins#884.

What it costs you: you sign in to those two on each computer. Every other sign-in syncs as before. A copy already on the server stops being carried and drops out the usual way.

On your relay proposal: the carry: relay tier (one generation chain, plus re-reading the store before a sign-in is declared dead) isn't in this release. It needs a design of its own, and your two-machine logs would decide it, so this stays open for that.

yetone avatar Nov 09 '26 04:11 yetone

Measured on 0.1.5452 (both ends), plugin @magpie-community/[email protected]. This is not a bug report — it's the shipped behaviour confirmed end-to-end, plus one measurement the discussion above doesn't have: what carry: never costs on a headless second machine, and what the user is shown while it happens.

Setup: Windows 11 desktop → fnOS NAS over WebDAV, signIns: true, autoEvery: -1. Two providers in play, both Huawei Cloud: CodeArts and OfficeAce. Four accounts of each on the desktop.

What sync actually carried

Check Result
Sender plugin-auth.json 97 sign-ins
Server copy magpie.magpie-backup (opened with the passphrase) signIns.logins 0, signIns.plugins 83
codearts / officeace keys in the server copy none
Sender sync-state.json → signIns hash map 83 ids, no codearts/officeace
Set difference: 97 − 83 14, from exactly 5 providers: codearts 4, officeace 4, workbuddy 3, workbuddy-ai 2, nous-portal 1

Two things worth having on record:

  1. The drop happens at collection, on the sender. The ids are absent from sync-state.json's own map, so the receiver never saw them and MergeSignIns can't be implicated. Anyone chasing a "lost account" should look there first — it answers "sender dropped it" vs "receiver merged it away" without touching the server.
  2. The filter is exact. All 14 excluded sign-ins are type: oauth of a provider in rotatesKnown; the 52 carried oauth sign-ins and all 31 api ones went through untouched. Nothing was dropped for any other reason, and both providers also declare rotating: true in index.mjs, so the declaration and the hardcoded list agree. (That agreement is why the count is reproducible across runs instead of drifting when the plugin host's list isn't loaded yet.)

What it costs when the second machine has no browser

The receiving NAS runs magpie serve --web=0.0.0.0:3430; it has no desktop browser. Before the work, it held 1 CodeArts account and 4 OfficeAce accounts — each signed in on the NAS itself, i.e. exactly the "sign in on each computer" cost @yetone described, paid per account.

Getting the remaining 3 there is possible without a browser, but it's manual per account: POST /api/plugin-signin returns the vendor URL and the loopback callback port; that port belongs to the NAS, so the page the browser ends on won't load on the desktop. What works is relaying the landing address — POST /api/signin/{id}/callback {URL} with the address the browser ended on (the web UI's paste field does the same thing). Three accounts meant three Huawei logins, each one with its callback relayed. All 4 + 4 then read real quotas through magpie accounts, so they're live, not stubs.

So carry: never is defensible, but for a headless home server the cost isn't "one extra sign-in", it's "N extra sign-ins, each through a callback relay the UI only half-documents". That's the tier @skalitz-wolf and @ggbdpq were describing, measured rather than argued.

The part I'd call a real gap: nothing says it happened

Sync reported success. magpie webdav / preview said nothing about sign-ins staying behind. The only signal was an account count that didn't match, which reads as a bug — it's why I filed this as "magpie or plugin?" before reading the source. Two small things would have saved that:

  • magpie webdav and preview: name the sign-ins kept for being rotating ("3 of 4 codearts stay here: their vendor spends a refresh token once"), the way it already names what it replaced.
  • signins_carry.go has the list in hand at that point (rotatingPlugins()), so it's a reporting change, not a policy one.

And a policy ask, if rotating is going to graduate: a deliberate opt-in for the retire-the-old-machine case (signInsInclude= / a carry: never | relay switch), since a user who is about to sign out on the sender does want the token moved — that's the reporter's original use case, and right now there is no way to say so.

striver8 avatar Dec 03 '26 06:12 striver8