grokLoginUsage read each home with keepLast, so its reading carried no
readSeq: when the Usage page's whole-page read of the same account began
first and answered later, its older figure replaced what the per-home
read had just left in quotas.json, and the Usage page then showed that
older share as the "last read" fallback on the vendor's next hiccup.
grokLoginUsage now orders its read (quotaReading) and keeps it with
keepReading, as loginReading already does; loginReading's give-up branch
goes through the same helper. Built-in Grok only: a Grok moved to its
plugin is read as plugin:grok through loginReading, which was ordered
already.
Rebased onto main by the reviewer: main's grokLoginUsage now reads with
gctx (unheld for an account StaleAllowance marked), so the kept line is
keepReading(gctx, grokUsageAt(gctx, ...)); gctx carries the same order.
Run at 5b14ebf49 + this change, sandbox HOME, pinned module cache:
TestGrokPerHomeReadKeepsTheNewerReading fails without the change ("last
reading on disk is 10%, want the newer 80") with either half reverted
(keepLast back, or the quotaReading line dropped), passes with it, and
-race -count=20. gofmt -l clean; go vet ./..., GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./...; go build, linux nogui and windows
builds. go test -tags nogui ./... green except
TestCopilotSecretToolUsername under load average ~30, which passes 5/5
alone and is filed as #1627; gateway and agent rerun with a longer
-timeout after timing out under the same load, both ok. No real Grok
account was used.
Refs #1228. The original test fails with "a reading from before the ask
was kept". A temporary diagnostic measured identical UnixNano values for
the read's start and the later ask; that diagnostic is not shipped.
What changed:
- Count both whole-page and manual-card Claude asks with a generation.
Advance it under subscription then login cache locks, so publication
cannot check the old generation and then commit after the ask.
- Capture the generation before launching LoginUsage/SubscriptionUsage;
reject an older account read or leave the cards due for another read.
- Record each Claude /usage run's ask generation. Keep timestamps, the
zero sentinel, floor, idle behavior, saved-account scope and fallbacks.
- Document ordering and lock ownership in the providers/accounts design.
No tests, routing.go, account files or dependency versions changed.
Run on upstream 8f2a314cf9:
- Original test unchanged: count=50 passes (12.317s). Product-only stash
restores real red, count=30 (7.077s); pop then count=5 passes (2.137s).
- Expanded usage/header/saved-card paths race count=5 pass (122.691s),
Go 1.26.8 and installed MinGW gcc, external sandbox home/temp and
pinned Go caches.
- Provider nogui vet passes on Windows, Linux, Darwin. Windows default
build and Linux/Darwin nogui builds pass. gofmt and staged diff clean.
- Provider full package and full ./... were not rerun; real account,
GUI engines/languages, Darwin GUI build and cross-OS runtime not tried.
Targeted evidence only, not a claim of complete merge acceptance.
Generated-by: Factory Droid (GPT-6.1 Sol)
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
What changed, one fix for the class:
- ChatGPT and the other built-in subscriptions (#1793): ChatGPT answered
401 token_revoked on every request, request after request (~18 rows in
the reporter's log), because a refused sign-in was just "other" and
rested a while, then asked again. Now a 401 whose words say the sign-in
is gone (provider.SignInRevoked: token_revoked, token_invalidated,
invalid_grant, refresh_token_reused/invalidated/expired; never
token_expired, a 403, a 5xx or a network error) marks the account for
the credential it was sent with (a 12-byte hash of the header, never the
credential), in logins.json as Refused "revoked:<mark>" plus Lapsed.
A saved ChatGPT account is refreshed first, as Codex does on a 401; a
refresh that goes through marks nothing. The routing loop fails it as
failAuth (next member at once, no rest); forwardOnce answers its later
requests with magpie's own 401 without asking the vendor; compaction
on a magpie account (compactOn) picks a marked one last. Signed in anew
(upsertLogin with another credential, addSideLogin), refreshed, or a
request served, the mark is gone. Claude, Copilot and plugins keep
their own marks; a key's provider answering the same words rests as
before.
- Copilot (echo_ts): a built-in Copilot account whose GitHub token GitHub
refused (401/403 on the token exchange, the CLI stand-in or the usage
read) is marked lapsed on its own account (copilot_lapsed.go), unless a
working CLI stand-in serves; cleared when a token is served or it signs
in again. 5xx and network errors never mark it.
- GUI: such an account's row says Sign-in required with Sign in again
(Copilot's on its GHE.com host) and Remove, the reason on its allowance
line in the user's language (zh, zh-TW, ja, de added); the card says
Signed out once every account in use is.
- docs/subsystems: providers-accounts "A revoked sign-in", gateway-routing.
What was run (sandbox HOME, caches pinned, worktree only):
- go test -race on the new tests: provider TestSignInRevokedWords,
TestRevokedSideLoginMarkedTillSignedInAgain, TestRevokedCodexRefreshedFirst,
TestRevokedSignInLeavesOthersMarks, TestUpsertLoginKeepsRevokedMarkForTheSameSignIn,
TestCopilot* (7); gateway TestRevokedSignInPassedOverTillSignedInAgain
(fake ChatGPT backend, zstd, real routing: turn 1 asks acct-1 then
acct-2, turns 2-4 and after a restart acct-2 only with no rests, after a
new auth.json acct-1 again and the mark gone),
TestRevokedSignInNotCompactedOnAgain, TestRevokedWordsFromAKeyRestAsBefore.
- Broken by hand, each turned a test red: the forwardOnce short-circuit,
the failureOf clause, noteSignIn in codexUpstreamOn, compactOn's skip,
ServedSignIn, its in-memory delete, the 401-only check, refresh-first,
upsertLogin's keep and its sameAuth, sideLogins' Lapsed and
addSideLogin's clear; and the six Copilot breaks. GUI: the signedOut
and quotaError lines each turn revoked-signin-account red.
- GUI (Chromium and WebKit, 420 and 1100, en/zh/zh-TW/ja/de):
revoked-signin-account (new), copilot-signed-out-account (new), and the
account-*, claude-*, codex-*, plugin-*, quota-*, signin-*, routing-*,
usage-accounts* suites: 1605 pass, 7 fail. Six are WebKit
routing-group-fold/routing-sessions/routing-steady cases that fail the
same on a clean 9964535ad run alone (#1672, #1612, #1307, #1804); one,
signin-proxy Chromium de 380, timed out under load (load ~60-75) and
passed 2 of 2 after, filed as #1814.
- gofmt; go vet darwin, linux (nogui) and windows; linux and windows
builds. go test ./...: every package ok but gateway, where
TestOTelFastRequestTranscriptDiscovery and
TestOTelWaterfallIncludesUnbilledFallback failed under load (#1794);
both pass alone, -count=3.
Not verified: no real revoked ChatGPT or Copilot account was tried; the
words come from the reporter's screenshot and OpenAI's documented codes.
Codex's own relayed sign-in (not one of magpie's accounts) isn't marked:
Codex refreshes and signs itself in. The short-circuit in
codexUpstreamOn (compaction on a marked account, reached only when every
account is marked) has no test of its own; plugins are left to their
plugin.
A saved (not signed-in) Claude account's Usage card read nothing on
Refresh: claudeWindows only ever ran /usage for the account Claude Code
itself is signed in to, so the button did nothing for the rest.
Now the card's own refresh (RefreshUsage for that account, savedRefresh)
runs the real Claude Code's /usage with CLAUDE_CONFIG_DIR set to the
account's claudeSavedDir (readSavedClaudeUsage). magpie still never calls
Anthropic with the token itself, and Claude Code's own account is not
switched. The 30-second per-account floor holds, background reads keep
the last reading, and asks for every card (the Usage page opened, magpie
quota, magpie accounts) start no Claude Code per saved account: they keep
the last reading, or the "not read yet: refresh this account's card"
note.
Claude Code may refresh the account's token in that directory while it
runs, spending the old refresh token. So:
- inSavedClaudeDir holds a per-account RWMutex (claudeDirRun) for the run,
and switchSavedLogin takes it for writing first, so a switch never hands
Claude Code a copy the run has just spent;
- syncSavedClaude copies a rotated sign-in from the directory back into
logins.json right after the run, under savedTokenMu and loginsMu.
Two Claude Codes in one directory are kept from refreshing at once by
Claude Code's own lock file (2.1.296's refresh lock in its config dir).
A saved account's warm-up, which already ran in that directory, now goes
through inSavedClaudeDir too.
The plumbing (configDir through UsageClaudeVia, readClaudeUsage and the
gateway's claudeUsage, and TestClaudeUsageRunsInSavedAccountDirectory)
is from hhh2210's patch 043ee7d7, reviewed line by line. Its gate (any
explicit read reads every saved account) was narrowed to the card's own
refresh, and the lock and sync back are new.
Run: go test -tags nogui ./internal/provider ./internal/gateway . (sandbox
HOME, fake claude via UsageClaudeVia, no real token), gofmt -l, GOOS=linux
and GOOS=windows go vet on the three packages. Broken by hand, each red:
saved never read (all three new tests), any ask reads saved
(TestRefreshSavedClaudeUsage), switch not held and no sync back
(TestSavedClaudeUsageKeepsRotatedSignIn / SavesRotatedSignIn), run in ""
instead of the account's directory. Not tried with a real Claude Code
binary against a real saved account.
Co-authored-by: hhh2210 <hzy2210@gmail.com>
What changed: Settings → Privacy → Subscription accounts (On/Off),
`magpie accounts discovery [on|off]` and MAGPIE_NO_ACCOUNTS=1 turn off
account discovery. It stays on by default. While it is off, magpie reads
none of the agents' sign-ins: ~/.claude/.credentials.json, .claude.json's
account, ~/.codex/auth.json, Copilot's, Cursor's, Devin's, Kiro's,
Gemini's, ZCode's, Command Code's and OpenCode's files. It runs no
`security` / `secret-tool` for the Keychain or Secret Service, and asks no
agent CLI who is signed in. It serves no subscription. API-key providers,
middleware plugins and Pi extensions work as before.
Why: the reporter runs magpie on machines where reading other tools'
credentials isn't wanted. The owner delegated the call.
How: settings.NoAccountDiscovery (kept per computer by KeepOwn) and
settings.AccountDiscoveryOff(). The variable only ever turns discovery
off. The gates sit at every reader (readAccountFile, discoveryOff) and at
every route that reads or writes a sign-in, so a route that skips
Accounts still reads nothing:
- Accounts, All, Logins, usage, renewal, warm-up, session identities,
check-ins;
- switching, forgetting, SetLoginOn, StartSignIn, the imports;
- moves onto plugins.
The ones that write refuse with an error that names how to turn it back
on. On the agent side, Agent.Source and OpenCode's auth.json are gated,
and Codex wiring goes by magpie's stash instead of auth.json, so a
toggle never rewires Codex. logins.json and plugin-auth.json are left
untouched and serve again when discovery is turned back on. A change
applies at once (ForgetAccounts).
Docs: providers-accounts.md, README (en, zh-CN), and the site's CLI table
(en, zh, ja).
Run:
- TestAccountDiscoveryOffReadsNoSignIn (provider) and
TestAccountDiscoveryOffAgentsReadNoSignIn (agent). Every credential
path is a FIFO that records each open, and security, secret-tool,
claude, codex, cursor-agent, devin, kiro-cli, copilot and grok are fakes
on PATH. Both fail with the gate removed: they show the opens and
`security find-generic-password -s Claude Code-credentials`, among
others. Both pass with the gate in place.
- TestAccountDiscoverySetting and TestAccountsDiscoveryCmd.
- account-discovery.test.cjs: chromium and webkit, 900 and 360 wide,
en/zh/zh-TW/ja/de, 32/32. The neighbouring privacy, redact,
settings-sections and i18n-keys GUI tests: 49/49.
- The full `go test -tags nogui ./...`, gofmt -l, and go vet for darwin,
linux and windows on the touched packages.
Not tried: a real machine under fs_usage, and Linux and Windows at
runtime. The FIFO tests are !windows.
The reporter starts magpie at login with the proxy on "follow system
proxy". magpie comes up before the proxy app. With no system proxy set
yet, netproxy.For gives none, so magpie's own allowance reads went out
direct, from the user's real IP. That reading was then kept for up to
15s. A system proxy that is set but not listening fails the request
("proxyconnect ... connection refused"); it never falls back to direct.
Proxy freshness:
- netproxy.System re-reads a "none" reading after 2s (noneKeep) instead
of 15s (systemKeep, unchanged for a set proxy).
- The plugin host looks again every 2s while it has no proxy
(proxyLookNone), so a host started before the proxy app takes it soon.
- Catalog sync, the update check, plugin updates and token refresh all go
through netproxy.Func / Dispatch, so they use the current proxy too.
Settings -> Allowances -> "Allowance reads": Automatic (default, as
before) or When I ask (settings.QuotaReads = "asked",
POST /api/settings/quota-reads):
- These count as asking (provider.Asked): the Usage page opened or
refreshed (?asked=1), a card's refresh (RefreshUsage), magpie quota,
magpie accounts, magpie quota wait and the TUI's quotas.
- Every other read (quotaReading -> holdUnasked) carries netproxy.Hold.
netproxy.Func, Dispatch's choice proxies and the plugin host's calls
refuse a held request before it leaves.
- The readers return the last reading, dated (AsOf), or "not read yet".
That covers routing's Allowances / AwaitAllowance, the used-up switch,
the menu bar, alerts, Quotas/KeyBalances/PlanQuotas, Codex/Claude/
Cursor/Grok/Kiro usage and KeyAllowance.
- An account refused for its quota (StaleAllowance) or a key refused
(StaleKeyAllowance) is still read, once.
- Warm-up and check-in are unchanged.
- Strings are added in zh, zh-TW, ja and de. The docs are updated:
providers-accounts (Allowance row), provider-plugins (host proxy).
Run:
- go test -tags nogui ./... (sandbox HOME), gofmt -l, and go vet -tags
nogui on GOOS=linux/windows/darwin for ., netproxy, plugin, settings,
provider, gui and tui.
- New tests, each seen red by breaking the change by hand:
- TestSystemProxySetAfterStartIsTakenSoon and TestHeldRequestNeverLeaves
(netproxy).
- TestHostWithNoProxyLooksAgainSoon (plugin; red with 15s).
- TestAllowancesReadOnlyWhenAsked (red without the hold and without
markStaleRead), TestAllowancesReadByThemselvesByDefault and
TestKeyReadsOnlyWhenAsked (red without holdUnasked and without
unheld for a refused key).
- GUI quota-reads.test.cjs in Chromium and WebKit, at 900 and 360px, in
en/zh/zh-TW/ja/de.
- i18n-keys, gui-ja, gui-de, settings-sections, settings-groups,
currency, number-units and tray-bird.
Cause: TestClaudeAccountBackOnceItsWindowRenews (a2c39053) failed the
ubuntu race shard of run 37942751214. Its Cleanup's LoginUsageVia(nil)
wrote the package-level stand-in while a reading Allowances had started
(routing.go:419) was still reading it in loginUsageAt. Allowances reads
in the background on purpose and returns without waiting (only the very
first ask waits, and not for long), so a reading can outlast the caller,
and the test. The window: Allowances deletes c.loading before it tells
the renewed hooks, so the test's next poll can start another reading
just as the rest it waits on is lifted; the test ends with that reading
in flight. In production the stand-in is never set, so there is no
production race; the goroutine outliving its caller is the design (it is
bounded by its 30 s context).
Change: the stand-in is held for reading while it runs, and
LoginUsageVia takes it for writing, so it returns once no reading is
running through the one it replaces and none starts through it after.
That fixes every test that swaps it (gateway claude_renewed and
allowance_stale, provider routing, allowance_renewed,
codex_reset_deadline, window_renewed), not only the one that failed.
UsageClaudeVia's claudeCLIUsage is the same shape (tests swap it, and
Allowances' background reading of a Claude account reaches it through
readClaudeUsage), so it gets the same treatment; claude_usage_test's
restore goes through UsageClaudeVia. ProbeClaudeVia is left: a Claude
account test calls it synchronously, nothing reads it in the background.
Tests: login_usage_via_test.go holds a call through each stand-in and
checks the swap waits for it.
Run:
- Red before: with a 30 ms delay injected into loginUsageAt and before
Allowances tells the renewed hooks (not committed),
go test -race -count=20 -run TestClaudeAccountBackOnceItsWindowRenews
./internal/gateway/ printed 7 "WARNING: DATA RACE", the write at
login_usage.go:43 from the test's Cleanup and the read at
login_usage.go:63 from Allowances.func1, as on CI. Same injection with
this change: ok, no race. (-race -count=50 without the injection
passed on the old code too; the window is too narrow on this Mac.)
- The new tests with the swap made unsynchronised again: both FAIL
"swapped while a call was still running through the stand-in it
replaced"; with the change: PASS, -race -count=5.
- gofmt -l: nothing. go vet (darwin) ./internal/provider ./internal/gateway
./internal/gui; GOOS=linux and GOOS=windows go vet -tags nogui on the
same: clean.
- Under a temp HOME with pinned caches: go test -tags nogui
./internal/provider ./internal/gateway ok; go test -race
./internal/provider ok; go test -race -count=20 -run
'^(TestClaudeAccountBackOnceItsWindowRenews|TestAllowance.*)$'
./internal/gateway ok.
- go test -race -tags nogui ./internal/gateway (whole package, temp HOME):
ok in 635 s, no race.
* provider: a background reading of an account writes its quota history too
GET /v1/magpie/quotas/history was written only by the Usage page's
reads, so a magpie only ever serving other magpies - nobody opens its
Usage page - kept an empty history while its routing read each account
every few minutes.
When a login's fresh reading is kept, it is now noted in the history as
a page reading is, named for its account (a login's reading itself
carries no user); a read that failed is skipped, not told again. The
test is the reporter's story: a background LoginUsage, then the
history, no Usage page involved; it fails on main. Keys' background
readings (KeyAllowance) are not noted here - the page names a key's
history line by its key name, which routing's reading does not have.
Invited by yetone on #1317 after 137ebee8 closed the cards half of
Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>
#1313.
* provider: a LoginUsage batch notes its quota history once, off the request path
Per review on #1318: a kept reading per account meant N full
read/parse/write cycles of quota-history.json for N accounts, and the
write ran before close(r.done), so routing's waiters on a reading
waited on the disk, the writes serialized under quotaHistMu.
loginUsageAt now notes the batch once after wg.Wait(), each reading
named for its account, through noteHistory, whose write runs in its own
goroutine; a cached reading notes nothing new (its ReadAt is no newer)
and a failed one is skipped. Tests: several accounts cost one write
(TestBackgroundReadsNoteHistoryOnce) and a held write holds no waiter
(TestHistoryWriteHoldsNoWaiter).
Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>
* provider: note the batch's quota history synchronously
The detached write goroutine outlived its caller: it read Path() and
wrote quota-history.json after a test had returned, racing t.TempDir
removal and leaking into the next test's HOME (go test
./internal/provider red with the PR, green on main). Note synchronously
in loginUsageAt after wg.Wait(): every reading has completed and
released its in-flight marker by then, so no routing waiter is held.
Only the LoginUsage caller pays for one write per batch, and Allowances
already calls it from its own background goroutine.
TestHistoryWriteHoldsNoWaiter now holds the write during the first
LoginUsage and asserts a second caller on the same account answers from
the completed readings, with a timeout on the write-start wait.
Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>
---------
Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>
A stale oauth_token for octocat left in ~/.config/github-copilot/apps.json
was read before everything else, so its 401 Bad credentials left Copilot
with no models although the Copilot CLI was signed in to octocat and
worked; signing in again from magpie didn't help, since the new token was
let go as the editors' own account.
- copilotToken remembers an editor token whose trade GitHub refuses (401 or
403; tried again after an hour, or as soon as one trade works).
- copilotApp.session then uses the CLI's sign-in of the same login on the
same host, sent as the CLI sends it, and copilotLogin reads that sign-in
for the account from then on. A CLI signed in to another account is never
used in its place; the error names the editors' file, and that the CLI is
another account.
- The Usage card (loginQuota) reads the CLI's sign-in the same way when the
editor token gets 401.
- The device sign-in asks GitHub about the editors' token of the same account
first (copilotProbeEditor); refused, addCopilotLogin keeps magpie's token,
standing for the account. With a working editor token it is let go as
before.
- TestMain stubs copilotCLISecret, so no test reads the runner's keychain.
Tests: copilot_stale_editor_test.go (fake exchange, user and API servers,
temp HOME). Without the fix TestCopilotStaleEditorFallsBackToCLI and
TestCopilotStaleEditorNotAnotherAccount fail "Copilot is signed out (Bad
credentials); sign in to Copilot again", TestCopilotSignInKeptOverStaleEditor
lists octocat with the editors' gho_x, TestCopilotStaleEditorUsageReadsCLI
reads "Unauthorized". Not tried with a real stale apps.json or a real
Copilot CLI login.
* provider, codex: a ChatGPT account at 100% with credits left keeps Codex signed in — magpie becomes its provider only while the Codex app itself holds the account
magpie made itself Codex's provider (model_provider = "magpie", #540)
whenever any of the active ChatGPT account's windows read 100%. A Pro
account at 100% on its week with credits left keeps working in the Codex
app: the backend answers every turn (about 490 200s in one day's usage log
at 100%), yet magpie moved Codex off it, and as a provider without
requires_openai_auth the app lost its ChatGPT state ("Sign in to ChatGPT
to start a durable thread", no remote control).
CodexUsedUp now reads codexHeld, which mirrors the Codex app's own
composer block (ChatGPT.app webview bundle, hP and its helpers): the
backend says the account isn't allowed (rate_limit.allowed = false), it
has no credits (has_credits / unlimited), and it isn't a workspace still
within its overage (overage_limit_reached = false, no spend cap, an
ordinary rate_limit_reached). Window percent never decides it. Where the
app goes by what /wham/usage can't show (a statsig gate, the gpt-reserve
fallback, Team's reserve experiment that ignores overage), it counts as
held: a wrong move costs ChatGPT extras, a missed one every turn. A
reading kept through a failed read (keepLast) stops saying held once its
used-up window has started again, as its usage does. NextLogin's account
rotation and its thresholds are unchanged.
A user stuck on the old move (codex.out = 1) is put back beside the
sign-in by the next Sync, as #540 already does once the account has room.
Verification:
- TestCodexUsedUpIsWhatTheAppHolds (real /wham/usage replies, ids
replaced) fails on the old trigger: 7 subcases, "CodexUsedUp = true,
want false". Each workspace guard (spend cap, reason, overage, plan
list, Team reserve) was mutated and fails its own subcase.
- TestCodexHeldKeptOnlyTillTheReset fails without the quota_last change.
- The real Pro account (7-day window 100%, ~28k credits, allowed false):
CodexUsedUp true before, false after.
- go vet ./...; go build (darwin), GOOS=linux -tags nogui, GOOS=windows;
go test -tags nogui ./... under a sandbox HOME; -race -count=20 on the
new and related Codex tests.
- Not run: a live Codex app turn on an account truly held (none at hand),
Windows/WSL runtime, GUI suites (no GUI change).
* provider: a Codex account at a spend cap or past its overage is held, credits or not; limit_reached counts as not allowed
codexHeld let credits through before the spend cap, so a Team seat at its
cap (spend_control.reached, allowed false) with has_credits read not held
and magpie left Codex on an account the backend refuses. The app's
readiness check (26.930.61225, app-primary) returns limited on
spend_control.reached or credits.overage_limit_reached before it looks at
credits, and treats rate_limit.limit_reached like allowed false; held now
reads the same. A spend cap with the rate limit still allowed (a
workspace's included usage) stays not held.
OpenAI's Sign in with ChatGPT lets an open-source app on the user's machine use their ChatGPT plan through the public API: it registers itself on the way (client_id dynamic_agent_client, an ext_agent_host_id kept for this machine, agent_name_hint magpie), the callback brings the client id OpenAI issued, and the token (scope chatgpt.tokens.use.direct, resource https://api.openai.com/v1) is sent as a Bearer to api.openai.com/v1/responses. The new subscription, chatgpt-api ("ChatGPT API" in the add sheet, beside Codex's ChatGPT), signs in so in magpie (PKCE, a loopback callback on 1455 or any free port, the ID token's issuer, audience, nonce and expiry checked), keeps its accounts as the other in-magpie sign-ins do, refreshes under the issued client id (rotated refresh token, serialised; a refresh token OpenAI won't take again marks the account to sign in again), revokes it on sign-out, and lists the models /v1/models gives the token. Requests go with the agent's own instructions — no Codex prompt, no Codex headers; the Codex path is unchanged — stored nowhere and streamed, without the fields the API refuses for a ChatGPT token (max_output_tokens, temperature, prompt_cache_retention, …) and without hosted tools; a system message is a developer one. OpenAI's subscription_sharing_* refusals are said with what to do (the plan's usage at chatgpt.com/settings/usage, an ineligible account, a capability the token can't use). There is no usage meter: the token has no usage API.
Tested against fake OpenAI auth and API servers (TestChatGPTAPISignIn, …Refused, …Refresh, …Body, …Explain; gateway TestChatGPTAPIRequests over chat completions, messages and responses) and the add sheet in Playwright on Chromium and WebKit (chatgpt-api-sub.test.cjs); the gateway and GUI tests fail without the change. Not yet signed in with a real ChatGPT account: the consent page needs the account's owner. go vet, go build (GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
Order balance, plan and subscription reads before fetching, so a late
whole-page read or card refresh cannot overwrite a newer card reading.
Keep updates to the other cards and return the merged whole-page result.
Protect the last successful reading on disk too, so a later upstream
failure cannot restore the stale value. Add deterministic regressions
for overlapping reads, late errors and fallback after reloading the file.
PooledWindows is how the usage page shows an Antigravity account's windows:
a pool's 5-hour and weekly ones, named with their pool ("Gemini · 7 days"),
in place of the per-model windows drawing on it. dueAlerts, the CLI's
accountRows and QuotaReport walked the raw per-model windows instead: a
pool raised an alert for every model in it and again for its 7-day
window, "magpie accounts" and "magpie quota" (its --json and the
gateway's /v1/magpie/quotas with it) listed a row per model, and whether
a model's name carried the pool in front depended on the name's own
words ("Gemini 3 Flash" did, "Claude Opus 4.6 (Thinking)" didn't). All
three go through PooledWindows now — one alert per pool span, one cell
per pool window, the pool already in the name. A pool's weekly window is
aside (using it up doesn't stop the account) but is still told of; the
pools' 5-hour asides aren't. The alert key keeps its shape: the pooled
name in it keeps two pools apart, and a window with no pool keys as it
did, so what an earlier build already said isn't said again — the pool
suffix the last draft appended is gone.
QuotaReport's card assembly is quotaReport(subs, plans, balances, now),
which tests feed directly, and LoginUsageVia (as UsageClaudeVia) stands
in for LoginUsage's readings, so accountRows is testable too.
TestDueAlertsPoolWindows feeds dueAlerts the windows Antigravity really
reports (the shapes TestAntigravityQuotaPools records): every model's
own, then each pool's 5-hour and weekly ones. On the old code it fails
with six alerts where two belong, per model with the pool sometimes in
front; now the two weekly pools are told of once each, "Gemini · 7 days"
and "Claude & GPT · 7 days", their marks distinct, a second reading
saying nothing, and a mark an earlier build wrote of a window with no
pool still holding. TestQuotaReportPoolsAntigravity fails on the raw
windows with eight spans where four pooled ones belong; TestQuotaCell,
TestAccountRowsPoolsAntigravity and TestQuotaCell read pooled names.
QuotaSpan keeps its Pool for magpie quota --json.
go vet ./... and builds -tags nogui (windows, GOOS=linux, GOOS=darwin)
pass; go test -tags nogui -count=1 ./... under a temp HOME passes for
every package this touches (provider, the gateway and the CLI and TUI
packages among them) — agent, gateway, library and sessions fail a few
of their own tests on this Windows machine the same way on main, paths
and WSL probes its Linux and macOS runs don't see.
Co-authored-by: werldl517-cyber <werldl517-cyber@users.noreply.github.com>
* feat: add DimAgent subscription support
Add OAuth PKCE login with automatic and pasted callbacks, account management, model discovery, quota reporting and gateway integration. Safely rotate credentials during concurrent requests and preserve fresh tokens when updating model caches. Cover protocol, provider, GUI and callback behavior with regression tests.
* dimagent: a refresh hiccup inside the day's lead keeps the token that still runs
The fallback checked !dimagentNearExpiry, which is false whenever a refresh
runs at all, so a 5xx/timeout on /oauth/token failed every request for the
last 24h of a still-valid token. A 401/403 still lapses the account.
* dimagent: review tests (sign forwarding, parallel refresh once, hiccup in lead, LoginUsage)
* dimagent: signing in again takes the callback port from the sign-in it replaces
StartSignIn begins the new flow before it cancels the old one, so the new
flow's listen on 54321 failed (ignored) and the old listener then shut
down a second later: the browser's callback was refused and only pasting
could finish. The older DimAgent flow is now ended and its server closed
first, and the listen retried briefly while the port is let go.
* dimagent: the fake-upstream tests get a name of their own
---------
Co-authored-by: yetone <yetoneful@gmail.com>
* subscription: Qoder is a subscription you sign in to and route through — Qoder lists no public API, so magpie speaks the endpoint its own desktop client uses: api3.qoder.sh's agent_chat_generation SSE, wrapped in the COSY envelope the client signs with (an RSA-encrypted key and a signed request line), the body through the client's own base64 codec, and the account reached by Qoder's OAuth device flow (qoder.com -> a dt- device token -> a jt- job token that serves models and rotates from its refresh token). The protocol lives in internal/qoder (endpoints, codec, cosy, oauth, models, a credential store, and /api/v1/userinfo, asked with the device token at sign-in so the account is labelled by its email and name rather than a bare uid); provider/qoder.go is who is signed in, its models, and the sign-in; gateway/qoder.go turns a request into a Qoder body and reads the SSE back, folding tool calls and results the way the client does. It is offered as a single, risky subscription in the Providers page: Qoder has no public API for this, and may treat a request that isn't its own client's as third-party use — the tile says so and points at an account you can afford to lose. Tested: the codec, the COSY signing, the model list, the request body and a served round-trip against stubs, and live — a signed-in account answered a Pi request for qfmodel end to end. Not tested: the userinfo email/name path against a fresh real sign-in (the device token is short-lived), and multi-turn tool use against the real client's exact framing.
* subscription: Qoder uses the chosen model and keeps rotating tokens consistent
Qoder used qfmodel regardless of the caller's model, refreshed the same rotating token concurrently, and could return upstream failures as empty successful replies. Requests now use the selected account's enabled model key and complete model_config; unknown or disabled models are refused. Token checking, rotation and atomic persistence are serialized, each caller receives a separate credential, and a rotated pair is retained for a persistence retry if its disk write fails.
Accounts are kept in logins.json with multiple accounts, selection, secondary-account toggles, usage and removal, including the last account. The old qoder.json is migrated after a successful write. A sign-in generates one machine ID that the account keeps for subsequent requests; the OS and architecture follow the running platform. Login polling expires after 15 minutes.
Qoder's response path maps non-200 SSE envelope statuses to HTTP errors before output and terminal error events after streaming begins, including requests using magpie's search rounds. Tool-result headings stay beside their own results; normal EOF flushes pending text and emits a stop event even after tool calls. Thinking, effort and context settings follow the selected model (low/medium/high is the fallback when no effort levels are declared). Corrected the Chinese risk wording and account plan label, removed unused protocol fields and the unsupported China-client claim, and included ufec/CLIProxyAPI's MIT copyright and license. Codec and signature tests now have fixed expected answers instead of relying only on round trips or an absolute Windows capture path.
The shared relay in claude_subscription.go is unchanged. Its error-status propagation and handling of failures after partial non-streaming output are existing upstream issues outside this change; Qoder handles these failures in its own relayQoder response path.
Tested: Qoder, codec, COSY and shared stream-error regressions passed 20 consecutive runs, including eight concurrent requests refreshing once, persistence failure recovery, account migration and removal, sign-in and usage against local HTTP stubs, and error handling across Chat, Responses, Anthropic and Gemini. go vet ./..., the production build, JavaScript syntax checks and git diff --check pass. The complete Windows test run has the same 72 failing tests/subtests as HEAD, with no new failures; the existing Claude shell-client test still times out. Not tested against a live Qoder account. The race detector could not build because gcc is unavailable.
* subscription: Qoder keeps its rotating tokens, speaks tools in its own
API's way, and thinks at the effort each model declares
An aborted request could sign the account out. A refresh ran on the
request's own context, so one cancelled after Qoder had rotated the pair
but before its reply arrived dropped the new pair and left the spent one
saved: every later call failed with "qoder job token refresh: status 401"
until the account was signed in again. The failure wasn't recorded
either, so the account looked healthy in the app while every request
failed. Refreshing now runs on context.WithoutCancel with its own 20s
timeout, in provider/qoder.go and the device-token refresh in
qoder_usage.go, and a refresh Qoder refuses (401 or 403, either token)
marks the account lapsed: Qoder's job-token refresh returns a
JobTokenRefreshHTTPError with its status, as the device one did. Side
logins don't carry Lapsed out, so qoderLogins passes it on.
A refresh blocked every other subscription. Both held qoderMu and the
global loginsMu across the HTTP call, up to 20s — with a 2s refresh in
flight, Logins("workbuddy") blocked 1.9s. qoderMu still serializes read,
rotate and write-back so one pair is rotated once; loginsMu is taken only
to read (qoderLookup) and to write back (qoderPersist), and the write-back
re-reads logins.json, so a change made meanwhile is kept. migrateQoder
takes no lock when there's no legacy file to move, or listing Qoder's own
accounts would wait behind a refresh too.
Tool calls were carried as XML in the text with values magpie HTML-
escaped, so an argument reached the model as "x", the model took
to imitating the escaping, and a value it meant literally — "< b &&"
— was unescaped on the way back and corrupted. A call had no id while
its result said "Function result for call A". Qoder's endpoint serves
OpenAI's own tool calls: asked with a tools array it answers with
tool_calls carrying ids, and accepts assistant tool_calls plus a role:tool
turn named by tool_call_id. So they are sent and read that way now: no
XML contract in the prompt, no escaping on either side, and a result
paired with its call by the id Qoder sent. The XML splitter stays as a
fallback for a model that still writes a call in its text.
Effort was chosen from reasoning_efforts, a field no model lists, so
every model got the low/medium/high fallback: gfmodel, which offers only
high and max, was asked for medium and refused with "该模型始终思考,
不支持关闭思考", and xhigh was clamped to high. The levels and the
default come from thinking_config now — asked for nothing, or for a
level Qoder doesn't name, a model thinks at its own default; a model
that can't stop thinking thinks at its lowest when asked for none; one
that declares no levels is sent none. A model whose only thinking_config
is enabled now thinks, as it does in Qoder's own client. Upstream
failures carry the vendor's reason from details, which had been dropped.
Tested: go test ./... and go vet on the changed packages, and the darwin
and windows builds. New regressions cover a refresh outliving an aborted
request, a refused refresh lapsing the account, logins and a concurrent
write-back during a refresh in flight, tool turns paired by id, native
tools and streamed tool_calls, and effort defaults. Live, against a
signed-in account: two parallel calls and a follow-up call each got
their own result; a file written with "< b &&" kept them; gfmodel,
asked for nothing, answered at max; qfmodel's xhigh reached Qoder as
xhigh. Not tested: a refresh the upstream refuses for real, and models
the account isn't offered.
WorkBuddy (CodeBuddy Code's desktop app) keeps its signed-in session in
<shared data>/auth/workbuddy-desktop.info, plain JSON while credential
protection is off (its default); magpie reads that account, never writes
it, and skips it when the tokens are encrypted at rest. Further accounts
are signed in with WorkBuddy's own external-link flow (auth/state, then
auth/token polled until ready, then login/account) and kept in
logins.json. The plan is served OpenAI-compatibly at copilot.tencent.com
/v2 under the account's access token, with its id and domain in headers
(X-User-Id, X-Domain), exactly as WorkBuddy sends them; a near-expired
JWT is refreshed as WorkBuddy does, and a magpie-signed-in one's refresh
is written back beside it while WorkBuddy's own file is left untouched.
The models are its CLI agent's coding picks, and the credits come from
its resource summary as one window.
A card in Providers' subscription list signs in and shows the accounts;
the Provider is one of the account ids and joins the usage rollup.