diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index e0f03694f..9300e96ec 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -203,6 +203,8 @@ An OAuth account keeps a short-lived access token beside its refresh token, and A plugin's `auth.refresh` renews a sign-in only when something uses the account (a request, its models, its usage, its check-in) within its `refreshLead` of `expires`. An account left idle past its token's life lapsed, and for a vendor whose session dies with its token the user had to sign in again: OrcaTerm's WeChat token lives two hours, and its refresh after that answers `SESSION_EXPIRED` for good (#5080, orinsid, [magpie-community/plugins#675](https://github.com/magpie-community/plugins/issues/675)). So the magpie serving the gateway renews each such sign-in as it comes due (`KeepPluginsSignedIn` in [`plugin_keepalive.go`](../../internal/provider/plugin_keepalive.go), started beside `KeepPluginsListed`). It reads the due times from plugin-auth.json (`plugin.RenewAt`: `expires` less the lead the host reckons, `Provider.RenewLead`, listed with `Renews`), asks nothing and starts no host until one is due, and sleeps until the next, at most five minutes. A due sign-in is renewed through the host's own renewal (`keepSignedIn` → `renewal` in [`host.js`](../../internal/plugin/host.js)), the one a request makes: one at a time per account whoever asks, a request arriving meanwhile waiting for the same one, under the lock file every magpie process renews under, through the account's proxy. Only accounts switched on and not marked, of a plugin provider not switched off, hidden (`leftAlone`) or being moved, are kept. A renewal that fails marks nothing: it is held back a minute, doubled each time to half an hour, for that sign-in only; only the plugin's `signIn: "expired"` marks the account, as at a request. A plugin whose renewal costs the account something, or whose refresh token another client holds too, says `auth.keepAlive: false` and is renewed only when used. No plugin in magpie-community/plugins says so as of this change: their refreshes cost no quota, those that rotate a refresh token (Cline, Factory, Nous, SenseNova, CodeArts, Qoder, MiniMax) already rotate it at use, and the ones reading another app's sign-in (kimi-work's reference accounts, Raccoon's desktop) never refresh it. `TestKeepSignedInRenewsIdleSignIns` in [`plugin_keepalive_test.go`](../../internal/plugin/plugin_keepalive_test.go) runs the renewal fixture in a real host; `TestKeeperAsksOnlyWhatIsDue`, `TestKeeperBacksOffAFailedRenewal`, `TestKeeperHoldsWhatTheHostFindsNotDue` and `TestKeptSignInsAreTheOnesSwitchedOn` in [`plugin_keepalive_test.go`](../../internal/provider/plugin_keepalive_test.go) cover the loop and which accounts it keeps. +An account signed out while one of its hooks runs stays signed out. A hook that saves a sign-in through `client.auth.set` (a models list spending a rotating refresh token, as the fake plugin's `rot-` sign-ins do) saves nothing once the account it was called for is gone from plugin-auth.json: `inScope` in [`host.js`](../../internal/plugin/host.js) notes whether the account was signed in when the call began (`had`), and `auth.set` checks it under the file's lock, as `renewLocked` already did for a renewal. A sign-in's own steps (`signingIn`) are not held to it, since their account is new. Before this, a listing that started before a sign-out, or before a failed move took its accounts back out of the plugin (`putBack`), wrote the account in again, and the plugin kept an account of a move that failed (#5126, #5119). `TestSignOutOutlastsRunningHook` in [`signout_hook_test.go`](../../internal/plugin/signout_hook_test.go) holds the hook (`FAKE_MODELS_HOLD`) across the sign-out in a real host. + ## A model's free and rate magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true`, a $0 list price or the user counting its whole provider free (`Provider.CountFree`) (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 12c39cb15..1f54881f2 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1103,8 +1103,18 @@ function freshKey(provider) { } } -function inScope(provider, key, fn) { - return scope.run({ provider, key }, fn) +// inScope runs fn for provider's account key. had is whether the account +// was signed in as fn began: a hook's auth.set for one signed out while it +// ran (a models list spending a rotating token) doesn't sign it in again. +// A sign-in's steps (signIn) save whatever they are given. +function inScope(provider, key, fn, signIn = false) { + let had = false + if (!signIn) { + try { + had = key in readAuth() + } catch {} + } + return scope.run({ provider, key, had }, fn) } function whoOf(a) { @@ -1197,7 +1207,11 @@ function makeClient() { // tokens over the old; nothing is merged. It goes to the // account the request is for. const key = keyFor(id) + const s = scope.getStore() + const had = s?.provider === id && s.had const kept = await changeAuth((all) => { + // signed out while the hook ran: it stays signed out + if (had && !(key in all)) return false if (JSON.stringify(all[key]) === JSON.stringify(body)) return false all[key] = body }) @@ -2478,7 +2492,7 @@ function abortedSignIn() { // signingIn runs a plugin's sign-in step fn for key under proxy and // signal; it ends when signal aborts, whether fn does or not. function signingIn(signal, proxy, provider, key, fn) { - const step = via.run(proxy, () => inScope(provider, key, () => signInSignal.run(signal, fn))) + const step = via.run(proxy, () => inScope(provider, key, () => signInSignal.run(signal, fn), true)) return signal ? bounded(Promise.resolve(step), signal) : step } diff --git a/internal/plugin/signout_hook_test.go b/internal/plugin/signout_hook_test.go new file mode 100644 index 000000000..f059eb25b --- /dev/null +++ b/internal/plugin/signout_hook_test.go @@ -0,0 +1,84 @@ +package plugin + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// An account signed out while one of its hooks runs stays signed out: the +// hook's auth.set (a models list spending a rotating refresh token) lands +// after the sign-out and must not sign it in again (#5126: a failed move's +// account came back in the plugin this way). One not signed out keeps the +// token the hook saved. +func TestSignOutOutlastsRunningHook(t *testing.T) { + sandbox(t) + hold := filepath.Join(t.TempDir(), "hold") + t.Setenv("FAKE_MODELS_HOLD", hold) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + t.Cleanup(Settle) + signIn := func() string { + t.Helper() + k, err := Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": "rot-x", "access": "a", "expires": 9e15, "accountId": "x@fake"}) + if err != nil { + t.Fatal(err) + } + return k + } + // the hook comes, and waits + arrived := func() { + t.Helper() + for { + if _, err := os.Stat(hold + ".in"); err == nil { + return + } + select { + case <-ctx.Done(): + t.Fatal("the models hook never came") + case <-time.After(10 * time.Millisecond): + } + } + } + checked := func(key string) chan error { + done := make(chan error, 1) + go func() { + _, err := Check(ctx, "fakeco", key) + done <- err + }() + return done + } + + // signed out while the hook holds the token it is about to save + key := signIn() + done := checked(key) + arrived() + if err := SignOut(ctx, "fakeco", ""); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(hold, nil, 0o600); err != nil { + t.Fatal(err) + } + <-done + if a := Auths("fakeco"); len(a) != 0 { + t.Fatalf("the hook signed the account in again: %v", a) + } + + // not signed out: the token it spent is replaced by one it saved + key = signIn() + if err := <-checked(key); err != nil { + t.Fatal(err) + } + // (a listing the sign-in set off may spend it again too) + if a := Auths("fakeco"); !strings.HasPrefix(fmt.Sprint(a[key]["refresh"]), "rot-x+") { + t.Fatalf("the hook's renewed token wasn't kept: %v", a) + } +} diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index bf239fc81..916c7da10 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -370,6 +370,14 @@ export const FakePlugin = async ({ client }) => ({ // the vendor unreachable: the list kept, as Zed's plugin keeps it if (auth?.refresh === "r-unreachable") await fetch("http://127.0.0.1:9/models").catch(() => {}) if (auth?.type === "oauth" && auth.refresh?.startsWith("rot-")) { + // $FAKE_MODELS_HOLD: say the hook came ($FAKE_MODELS_HOLD.in), and + // spend the token only once that file is there + const hold = process.env.FAKE_MODELS_HOLD + if (hold) { + const fs = await import("node:fs") + fs.writeFileSync(hold + ".in", "") + while (!fs.existsSync(hold)) await new Promise((r) => setTimeout(r, 10)) + } await client.auth.set({ path: { id: ID }, body: { ...auth, refresh: auth.refresh + "+" } }) } // fake-1 costs the plan nothing, as a WorkBuddy model of x0.00