Commit Graph
154 Commits
Author SHA1 Message Date
yetone a06872dec8 caps: a wallet window's spend is counted, so a cap holds it (#5770)
A window that tells only what is left (QuotaWindow.Balance: AStudio
0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until
it was empty, so an account cap never tripped on it. 9won capped an
AStudio account at 4 and it spent over 1,000 credits past it.

magpie now counts what such a wallet spends (wallet_spend.go). Each
plugin reading's balance is set against the one before: a fall is
spent, a rise (top-up, daily grant) is not. The count runs over the
window's own period when it tells a reset, else the local day: a
wallet never renews, and a cap reached for good would switch the
account off with no time it comes back; the ask was "N a day". Spend
before a period's first reading, or across a gap between periods, is
unknown and not counted; spentSince says when counting began. The
counts are kept in wallet-spend.json beside providers.json, so a
restart doesn't lose them.

Every wallet window carries spent and spentSince. On an account with a
usage cap (WindowCaps.Holds) it also reads as amount spent of limit
(spent plus what is left), and used that share. A cap by share then
holds it in routing (allowanceOf takes the fields as they are) and on
the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap,
which skipped a window with no total: 9won's "at most 300 a day" on a
wallet now holds (magpie provider account-cap ... --window 通用积分
--amount 300). An uncapped wallet is unchanged:
balance alone, routed by Allowance.Left. A cap just set is judged from
the next reading. holdsBounds leaves wallets out: there is no whole to
reckon "holds" from.

Tests, each red on the old code (broken by hand where they compile):
- TestPluginWalletCapHolds: real plugin host, fake plugin, wallet
  10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the
  uncapped account untouched. Red with the plugin_usage.go hook
  removed (Used 0, Spent nil).
- TestWalletSpendCounted: falls counted, top-ups not, a restart reads
  the count back, the next local day and a told reset start over
  (UTC+8 fixed zone), failed and share readings left alone.
- TestWalletCapHolds: account cap 4, the window's own cap 4, and an
  amount cap of 700 (not held at 650 spent, held at 750).
- TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change
  (a wallet reckoned a 500-token whole).

Run on mote at this tree on f8186c691. Rebased under it after: 7000b23b8
(GUI files only) and 36ddd5761 (internal/sessions only) (lockf ~/suite.lock
mote-run):
- go test ./internal/provider -run 'Wallet|Cap|Amount' -count=1: ok
- go test ./internal/usage -run TestWindowHolds -count=1: ok
- gofmt -l .: clean
- go vet ./... for darwin and windows, and for linux with -tags nogui:
  ok
Pushed and tagged at once, per the owner's rule. The full go test ./...
-timeout 45m runs after the push and any red gets filed.

Not changed: the GUI. A wallet meter still shows "{n} left". A capped
one shows "At its cap" from used. The meter's Amount... item still
needs a total and a unit, so an uncapped wallet doesn't offer it yet
(follow-up). A Text window (a balance that isn't
a number) still can't be capped by share.

Reported-by: 9won (Discord)
2026-11-09 19:23:13 +08:00
yetone 08a42c40ff 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)
2026-11-09 12:47:12 +08:00
yetone aa3d11d5b7 kimi: a key's booster wallet is read, and a key spending it isn't rested to the month (#5721)
apple_test_src on X (#5721): a Kimi Code key at 98.85% of its month was
rested until the month renews, while Kimi still served it from its
booster wallet. magpie never read the wallet.

readKimiCode now reads booster_wallet (or boosterWallet). A BOOSTER wallet
with an amount over 0 adds an "Extra usage" row: amountLeft, in cents x 1e6,
in the currency of monthlyChargeLimit, else monthlyUsed, else USD. When
something is left, the plan windows are marked Credits. The gateway's full()
then doesn't count a key on its booster as full at the month's 98%. A 429
quota refusal rests it as any refusal does, not until the month renews.
A wallet that is empty, of another type or missing changes nothing.

Tests: TestReadKimiCodeBooster runs on the reporter's literal body
(testdata/kimi-booster-5721.json, where 0 is left: no Credits) and on the
same body with amountLeft injected (snake and camel case). A GIFT wallet
and amount 0 add nothing. TestKimiKeyOnItsBoosterIsNotRestedToTheMonth:
a key with booster left isn't full and its 429 rests it under 24h; a
spent key is still rested by its window.

Run on mote: gofmt -l clean; GOOS=linux and GOOS=windows go vet of
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 -timeout 45m: both ok (154.9s, 951.7s).
Broken by hand: routing.go reverted turns the gateway test red ("a key
on its booster counts as full at the month's 98%"); dropping the Credits
marking turns the provider test red.
Not tried: a real Kimi key with booster balance left (the reporter's
body has 0 left).
2026-11-09 05:06:48 +08:00
yetone b684308c61 provider: an allowance or usage read a test leaves running ends with it (#3174)
TestClaudeAccountServesModelsListedSinceItsFetch went red in full
internal/provider runs under load (macOS CI at 5849b47ca, run
42448627522; mote; WSL): find(All(), "claude") came back empty right
after claudeSignIn.

Cause: the test before it in file order, TestClaudeAllSignedOutStaysListed,
ends with InUseLogin("claude"), whose loginRoom asks Allowances. Allowances
starts its read in a goroutine and waits for it only firstWait (3s); under
load the read runs on past the test. It reads the logins (Logins ->
liveLogin -> claudeCredential) with whatever HOME is set by then: the next
test's, after claudeHome forgot the credential cache and before
claudeSignIn wrote the sign-in. It caches "no credential" in the one
global slot for 10s, and the next test's All() is served that miss, so
there is no Claude row. skygunner's -race run on #3174 named the same
path (isolate's write against an Allowances read from that test).
SubscriptionUsage (with a stale copy to serve) and KeyAllowance leave
their reads running the same way; an instrumented full run saw all three
store into the credential cache from goroutines no test waited for.

Fix: those three reads start through goRead, which counts them
(readsOut). isolate, which every account test goes through, waits for
them before it resets anything and again as the test's last cleanup,
and fails the test if one still runs a minute later (a read gives up
after 30s). TestReadLeftOutEndsWithItsTest leaves an Allowances read
out past firstWait and checks it ended with its subtest.

Not taken: the patches offered on #3174 (ggbdpq, skygunner) forget the
credential cache after claudeSignIn's write. That hides this one victim's
symptom while the read keeps running into the next test's home and its
other caches (usedCache, logins), so the cause is left.

Run on mote (darwin arm64, go1.26.8):
- pinned repro (throwaway test, deleted): an Allowances read left out
  past a 10ms firstWait reading claudeCredential in a loop, then the
  victim; on 691a10446 the victim was red 3 of 5 with the issue's
  output (claude_models_test.go:52 ... Account:<nil>} false).
- with the fix: the repro, TestReadLeftOutEndsWithItsTest and the victim
  -count=10 -race ok.
- broken by hand (goRead as a bare go f()): TestReadLeftOutEndsWithItsTest
  red 5 of 5 ("ran on after its test"), the victim red 4 of 5.
- go test ./internal/provider -count=3 -shuffle=on (seed
  1794116678624149000): one red, TestCodexSubagentModelsKept's
  allocation ratio (filed as #5435, output added there); all else ok.
- go vet ./internal/provider on darwin, GOOS=linux -tags nogui and
  GOOS=windows: clean. gofmt -l clean.
- full suite: `lockf /Users/yetone/suite.lock go test -timeout 45m ./...` on mote at this tree (base 691a10446): every package ok, no reds (internal/provider 201s, internal/gateway 978s, internal/agent 379s). A first attempt was cut off when mote rebooted.
- after rebasing onto origin/main a5c97cd83 (which changed internal/provider): `go test ./internal/provider -count=2 -shuffle=on` on mote, seed 1794163393889037000: only TestCodexSubagentModelsKept red, the allocation count already filed as #5435.

Not tried: the loaded CI schedule itself (the repro stands in for it);
Windows and Linux test runs of the package.

Fixes #3174
2026-11-09 02:47:26 +08:00
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00
yetone c57a5f7f58 gateway: a vendor's redirect to another origin is sent no provider key
Go's http.Client follows up to 10 redirects to any host, https to http
included, and on a hop to another domain drops only Authorization,
Cookie and WWW-Authenticate. So a vendor (or anything answering at its
URL) that redirected elsewhere got x-api-key, x-goog-api-key, api-key
and a provider's own headers sent there; Authorization too when only
the port differed, and all of them in the clear on an https to http
hop on the same host.

The class is fixed where the requests leave:
- provider.KeepsCredentials is a CheckRedirect that follows a redirect
  only to the request's own origin (scheme, host, port; or http to
  https on the same host and default ports), at most 10, and gives any
  other 3xx back as the answer (http.ErrUseLastResponse).
- provider.Keyed(c) is a copy of c with c's own CheckRedirect, then
  KeepsCredentials. Provider.do, the choke point of every p.Do, sends
  through it, and every http.DefaultClient.Do in internal/provider that
  carries a credential is Keyed(http.DefaultClient).Do. A copy per
  call, since netproxy.Install sets the default client's transport at
  run time. Left alone: Grok's public download, Antigravity's version
  URL and cline.go's unsigned read.
- the gateway's client (s.client, every vendor call), the Codex relay's
  and the Codex websocket's take KeepsCredentials, and so does
  chatgpt_api's siwcClient.

The native route needs nothing more: the vendor's 3xx comes back to
the caller as it came, Location included, and the caller decides.
Translated routes don't follow either, rather than following with
credentials stripped: it is the rule search_api.go had already (#1580),
no vendor magpie speaks to was found redirecting its API to another
origin, a stripped request elsewhere would only fail with a confusing
401, and the vendor-URL downloads (video, images) are fetched unsigned
through vendorClient, so they are not affected.

Tests: TestRedirectKeepsTheKeyAtItsOrigin (307 and 302 elsewhere with
Authorization, x-api-key, x-goog-api-key, api-key and a custom header;
a same-origin redirect followed with every key; three clients),
TestRedirectNeverDowngrades (an https vendor's redirect to http on its
own host and port), TestSameOrigin, TestKeyedKeepsTheClientsRule,
TestNativeRedirectKeepsTheKey (Anthropic and Gemini providers with an
own header) and TestChatRedirectKeepsTheKey.

Broken by hand: with Provider.do back on client.Do and s.client
without CheckRedirect, the thief got every key header, /away answered
200, the https vendor's /plain was followed (400 from the TLS port
spoken to in http), the native route's claudeish and gem answered the
thief's {"stolen":true} with Authorization, X-Api-Key and
X-Relay-Secret sent there, and the chat route sent Api-Key,
Authorization and X-Relay-Secret to it. TestSameOrigin and
TestKeyedKeepsTheClientsRule don't depend on the wiring and passed.

Run on mote at the pushed head 883690a0b (this commit and the next,
on origin/main 9a0aab32c): gofmt -l clean, go vet, GOOS=windows go vet
and GOOS=linux -tags nogui go vet all clean. go test ./... -timeout 45m
-count=1: 84 packages ok, including internal/gateway. 3 red, each filed
and none in this change's path:
- TestMainWindowCorners/macOS_26_SDK (gui, macOS 27, #3949)
- TestRenewLoginsKeepsClaudeReading (provider, #5481). It is red 3 of 3
  at the base 49c9491b7 without either commit.
- TestHostEndedEndsWhatItsPluginStarted/own_end (plugin, a 30s wait in
  a full run; passes 3 of 3 alone at this head, #5515)
This commit alone, at its first base 49c9491b7, ran the same way with
TestUnroutedHeldReportSaved (gateway, #4300) red besides.
Rebased then onto origin/main 303a31dd6 (which fixed #5481) and run
again at that tree: gofmt and the three vets clean, and internal/gateway,
internal/provider, internal/plugin and internal/netproxy all ok.
Rebased on 19c45d5d4, which changes gateway.go (kept_error), Codex's
usage_limit_reached, Cursor's mover min, sessions and the GUI; ran
gofmt, go vet ./internal/..., GOOS=windows go vet of gateway and
provider, and go test ./internal/gateway ./internal/provider: both ok.
Rebased on 94d4866b5, which changes only internal/sessions; ran gofmt,
go vet of gateway, provider and sessions, and this change's own tests
(-run Redirect|DropsProxyIdentity|SameOrigin|Keyed): ok.
Rebased on cd77c725d, which changes only internal/provider's check-in;
ran gofmt, go vet of gateway and provider, and this change's own
tests again: ok.
Not tried: a real vendor's redirect (none found that does), and the
plugin host's fetch (host.js; Bun follows redirects by default), which
is filed as #5508.
2026-11-06 19:50:18 +08:00
yetone fb4632ee0c agent, provider: Codex's polls and the usage quotas read what is kept
Heap profile diff of the live magpie (v0.1.2906, /v1/magpie/heap, two
idle minutes with the window open: 269 MB allocated):
- ownCodex found the codex provider through provider.All, a copy of every
  provider, on each look (~9 MB). Its picks are now kept per stamp
  (codexPicks, stampedLists), read only.
- Codex's model and effort fields copied magpie's whole model list on
  each Options call, every poll of the effort field (~11 MB). They read
  sharedModels, the list kept, which they only read.
- visibleQuotas built every provider's offered models to narrow Gemini's
  and Antigravity's quotas (~20 MB). exposedIDs builds the providers
  asked only.

Run (mote, at this tree):
- gofmt -l internal, go vet ./..., GOOS=windows and GOOS=linux go vet
  ./internal/agent/ ./internal/provider/: clean
- go test -count=1 -timeout 45m ./... (all three commits' tree): 85
  packages ok, internal/gateway 748s, internal/provider 193s. Two red:
  internal/gui's TestMainWindowCorners/macOS_26_SDK, mote's macOS 27
  (#3949, filed before, untouched here), and internal/agent's
  TestCodexEffortOptionsReadTheKeptList, whose bar counted the
  environment's copy (see the effort test's comment), fixed in its test.
- then go test -count=1 -timeout 45m ./internal/agent/ with that fix:
  ok (200.1s)

Broken by hand:
- codexPicks through provider.Find again: 285 allocations, red
  (TestCodexOwnModelsFollowPicks, bar 20).
- the effort field on magpieModels again: 199896 bytes a look past
  its StampNow's 1712, red (TestCodexEffortOptionsReadTheKeptList, bar
  20000). The test takes the look's StampNow off: os.Environ copies the
  environment, and each t.Setenv before it in the package made that
  longer (an Unsetenv leaves its slot), ~56 KB a look in the whole
  package; run alone it is 1.7 KB.
- exposedIDs without the ids check: "other" built, red
  (TestExposedIDsBuildsOnlyTheProvidersAsked).

Not tried: the numbers on the live app after this build; that profile
is taken once it is released.
2026-11-06 12:48:51 +08:00
yetone 77031d5817 claude usage: a /usage panel with no window is no window started, and a failure says why
koohoko5924 (Discord #help, v0.1.3057, macOS): a Claude Enterprise
account with a five-hour window only. A manual refresh took ~5s and
gave the card no window and the error "Claude Code's usage showed no
usage figures: ▐▛███▜▌ … magpie-claude-work…": Claude Code's banner,
not a reason.

Claude Code 2.1.316's Usage tab (gi) draws a window only once
Anthropic's answer has it non-null, and a window is null until the
request that starts it. An idle 5h-only account's panel loads with
the session's cost, maybe the plan's credit bar, and no window. The
helper told that panel's words, joined from the top of the screen, and
the card took them as a failure with the banner first.

- claudetui: a panel that loaded (tabs, Session/Total cost, nothing
  loading, refreshing, stale or failed, no gateway Spend limit) with no
  "Current session"/"Current week" is told as NoUsageWindow ("No usage
  window has started"). The provider reads that as no window started:
  no error, the unstarted 5h window as for any account.
- claudetui: the two rate-limit errors gi draws ("Claude is temporarily
  limiting requests to the usage page (not your usage limit)…",
  "Usage endpoint is rate limited until …") are failures to load, like
  "Failed to load usage data": retried once, then told as an error with
  the panel's own "Error: …" text, never the banner. A panel with no
  window and no error is told from its tabs on, the session's cost
  lines left out.
- provider: "(not your usage limit)" no longer reads as an account
  refused (claudeDenied, at every place claudeUsageDenied judged a
  reading: the CLI parse, codex_switch, quota_last, subscription_usage).
  Counts ("Last 7d · 403 requests …") are taken out wherever they sit in
  a line before that check, as the panel's words come on one line now.
  A no-figures error keeps every line (600 runes), not the first clipped
  at 120.

Tests are built from 2.1.316's own strings (ko/gi/hi in the bundled
cli.js), drawn on the helper's 200x50 grid row by row. Guessed: the
exact bytes of a real Enterprise panel (not captured; no such account
here) and the credit bar's layout.

Run (mote, at this tree): go test ./internal/claudetui ./internal/provider
-run 'Usage|Claude|Shim|Quota|Codex' ok; go vet for claudetui, provider,
gateway; GOOS=linux -tags nogui and GOOS=windows go vet; gofmt -l clean.

Broken by hand (each red, then restored):
- the NoUsageWindow case off: TestShimReadsUsageWithNoWindow red in all
  three panels (told the panel's words as success);
- the provider's claudeNoWindow branch off: TestClaudeUsageNoWindowStarted
  red ("showed no usage figures: No usage window has started");
- claudeDenied back to claudeUsageDenied: TestClaudeUsageWhyKept red
  ("read as an account refused");
- usageFailed back to "Failed to load usage data" and the whole screen as
  the reason: TestShimToldWhyUsageFailed red in all three (the banner as
  the reason; the rate-limit panels told as no window), TestUsageNoWindow
  red.

Not tried: a real Claude Enterprise account; a real rate-limited panel.
2026-11-06 06:30:23 +08:00
yetone 814a625a24 usage: the top refresh reads saved Claude accounts again (#5380)
The tray panel's Allowances refresh said "Allowances refreshed" but a
saved, non-active Claude account kept its old reading: claudeWindows runs
Claude Code's /usage for a saved account only under savedRefresh, which
only that account's own card refresh sets.

Now a refresh of every allowance by hand asks usage/quotas?asked=1&all=1
(AskEveryClaudeUsage). It marks its ask generation in claudeEveryAsked,
and for claudeEveryFor (2 minutes) each saved account not read since is
read as its card's refresh would, under the same due check, the
30-second per-account floor and the same running holds. Opening the
Usage page or the Allowances tab (?asked=1 alone), the timed refresh and
every background read are unchanged, so nothing polls more. Callers:
the panel's top refresh (refreshPage "allowances"), the Usage page's
refresh and sidebar reload (refreshUsage -> loadQuotas("all")),
Routing's Read allowances, and the TUI's r. loadQuotas no longer lets a
lesser load on its way (an opening's asked read) swallow a Refresh.

Siblings: saved Codex accounts are already read anew on every asked
whole read (loginReading over HTTP after AskUsage clears the cache), so
Codex is unaffected. PlanQuotas and KeyBalances keep their 1-minute cache
on an asked read; left as is. The core scripts' budget is not raised:
the ~140 bytes are paid for by two loadQuotas/quotasOpened comments cut.

Run (mote, at 807341cdc on origin/main 5666cb049; rebased onto
505534992 after, which touches only internal/plugin and internal/proc;
the core script budget rechecked at the pushed head, 193 bytes under):
- go test ./internal/provider/ ./internal/gui/ ./internal/tui/ ok
  (TestMainWindowCorners/macOS_26_SDK red on mote's macOS 27, #3949;
  green when run with the -run set at the pushed head)
- go vet the three packages; GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of them ok; go vet provider+tui in WSL ok; gofmt -l
  clean
- GUI, Chromium and WebKit, en+zh: refresh-page, claude-usage-asked,
  usage-refresh, routing-read-allowances, allowance-open-read,
  quota-refresh-order, usage-refresh-flight all pass. A wider set of 119
  files (quota*, panel-quota*, usage-*, allowance*, routing-read/account,
  menu-*, tray-*, i18n-keys) has reds in 6 files, identical at the parent
  commit and filed: i18n-keys #5332, menu-input-scroll #3402,
  tray-cell-click #5215, usage-agents-hide #3414, usage-fold #3415,
  usage-ledger #5048.
- New TestRefreshEveryReadsSavedClaude: an opening's ask runs nothing
  for saved accounts; a top refresh reads each anew; an unasked read and
  a plain asked read after it don't; rapid refreshes keep the floor; the
  every-ask lapses after claudeEveryFor.

Broken by hand: dropping "|| every" from claudeWindows' read turns
TestRefreshEveryReadsSavedClaude red ("top refresh read no allowance of
saved max@x.com"); the panel's refreshPage back on loadQuotas(true)
turns refresh-page's panel subtests red in both engines.

Not tried: a real saved Claude account's /usage run from the real tray
panel (the test fakes Claude Code's /usage per account directory); the
full GUI suite; the de/ja/zh-TW GUI runs (no string changed).
2026-11-06 00:35:39 +08:00
yetone 51bdc985bc provider: a cap set on a window a plugin later sets aside still holds; WorkBuddy min 0.2.24 (ferock on Discord)
WorkBuddy 0.2.24 stops an account by a new "Total credits" window (the
plan's credits and the extra ones together) and sets "Credits" and
"Extra credits" aside, so the Routing page reads every account the same,
its plan's credits spent or not. Routing skipped every window set aside,
caps included, so a cap the user had set on "Credits" would have stopped
holding the account: magpie's change overriding the user's value.

Now a window set aside, not a pool's or one model's, rides in each
limit's pool (allowanceOf), as a pool's windows do, and holds the
account at a cap set on that window itself (WindowCaps.own), never at the
account's cap or a Codex credits hold, which never reached it before.
WithCapped marks such a window Capped with OwnCap, so the GUI shows the
mark and the "at its cap" note for it, counts no account cap on it
(windowCapOf), and offers its meter as a button only while it has a cap
of its own, to change or lift it; no new cap on a window set aside.
app.js grows 48 bytes, inside the core budget (no raise).

Run (mote): go test ./internal/provider (ok) and ./internal/gui
(TestCoreScriptBudget ok); window-cap, window-cap-pool and account-cap
GUI tests, both engines, 420/1100, five languages: 136 pass.
internal/gui's TestMainWindowCorners/macOS_26_SDK (#3949) and
i18n-keys "a plugin's words are its own" (#5327, #5332) are red the same
on origin/main a9b1877cf, files this change doesn't touch.
Broken by hand: allowanceOf without the set-aside loop,
TestAsideWindowKeepsItsOwnCap red ("the user's 50% cap on Credits, at
60%, no longer held: <nil>"); app.js without the meter's ownCap guard,
window-cap 20 of 80 red (the new test in every engine, width and
language).
Not tried: a real WorkBuddy account with a cap on Credits; the whole GUI
suite (the full Go suite runs after the tag).
2026-11-05 18:22:56 +08:00
yetone 4a9cfb52e5 usage: a plugin account told by its balance alone is drawn over time
corddis_114 on Discord: SenseTime Raccoon's (商汤小浣熊) usage card had no
trend chart like the other cards. The Raccoon plugin tells a "Credits"
window when its bills add up to the balance, and only `balance: "N
credits"` with no window when they don't. A window's share is kept in
quota-history.json and drawn; a balance was kept (balance-history.json,
balanceTrend) only for API keys' balance cards, from KeyBalances. A
subscription or plugin card's balance was never recorded, so such a card
had no curve at all.

noteCardHistory, called where SubscriptionUsage and a card's refresh
note a read, keeps each window's share as before and, for a card with a
balance and no windows, its balance, and sets the card's balanceTrend, so
the Usage page draws "Balance over time" for it as for a key. A card with
windows keeps its windows' curve alone (its balance isn't recorded). The
keep-alive's keepCardRead is unchanged (Claude cards have windows).

Run (mote, at 8e97e26d6 + this change; after the rebase on 7661a0aa7,
the TestBalance|TestQuotaHist|TestPluginUsage run again ok):
- go test -count=1 ./internal/provider/ ok (166s); go vet for darwin,
  linux and windows on internal/provider ok; gofmt -l clean.
- node --test internal/gui/tests/balance-curve.test.cjs: 6/6, chromium
  and webkit, en and zh; a Raccoon-shaped card (user, plan, windows [],
  "5900 credits", three points) draws its curve.
Broken by hand: noteCardHistory without its noteBalanceHistory call:
TestBalanceOnlyCardHasTrend red ("wallet's trend = <nil>").
Not tried: a real Raccoon account (none here); which branch corddis's
account takes is not known. An account on the window branch already
had a curve. Full suite and GUI suite not run before push.
2026-11-05 00:14:14 +08:00
yetone 0ebe6c72c9 providers: each account row in the editor has its own Check in now, when the check-in reaches it and it isn't in today (xwoffice_91592 on Discord)
xwoffice_91592 asked for 立即签到 on each account in the provider editor
sheet (Trae CN, a plugin's subscription, one row per account with its
Credits line). The editor's rows read GET /api/login/usage, which carried
no check-in. It now passes those cards through provider.LoginCheckins,
which marks them as the Usage page's cards are (WithCheckins: checkins,
checkinBy, checkin, checkinOff) and adds checkinKey, the account's key
in its vendor's check-in (markCheckins sets it).

The row's button is Settings' Check in now for one account (xiaowu_95660),
not a fork. ciAcctFill in checkinnow.js presses ciNowSend with
{key, user} and checkinBy, so the same POST /api/usage/checkin-account,
the same status-line success and failure, then the row's usage is read
again. When to show it is checkinDue, taken out of checkinRow so the
Usage card's press and the row decide alike: the check-in reaches it, it
isn't off, and it isn't in today (a failed day, an "again" answer, or a
Qoder campaign not open yet still count as due). It sits at the end of
the account's usage line, small (.ci-acct), and wraps whole there rather
than being cut. app.js is 51 bytes smaller (comments cut); checkinnow.js
is lazy and not in the core.

Run (mote, worktree at origin/main 14f6d10de plus this):
- go test -run 'TestLoginCheckins|TestTraeCheckin|TestPluginCheckin|Checkin'
  ./internal/provider/: ok. GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/gui/ ./internal/provider/: ok. gofmt -l clean.
- New editor-checkin-account.test.cjs: 4 Trae CN accounts (due, in
  today, failed today, no check-in), en zh zh-TW ja de, 1000/560 desktop
  and 390 web, chromium and webkit: ok. It checks the translated label and
  tooltip, the placement (not cut, no sideways scroll), the press body
  {by, key}, the status line, the re-read, and that nothing scrolls.
- The editor-*, account-*, checkin-*, plugin-checkin,
  qoder-checkin-recheck, usage-card-* and i18n-keys files, both engines:
  634 of 635 ok. The red is account-eye's Usage card in chromium zh-TW,
  '' !== 'none', which is #5052; run alone it passed 30/30 twice.
- TestCoreScriptBudget: red at 1,533,950 > 1,533,802, which is #5139 (red
  on main at 1,534,001 before this); this change lowers it by 51.
- Rebased on c03dee7e3 (no core script or check-in file changed there):
  editor-checkin-account, i18n-keys and checkin-now-account, both
  engines, 28 of 28 ok; the Checkin provider tests ok; budget the same
  1,533,950.
- Broken by hand: no CheckinKey in markCheckins made
  TestLoginCheckinsPressOneAccount red.

Not tried: a real Trae CN account, WebView2 or WebKitGTK. The whole GUI
suite hadn't run before the push: another session's whole suite held
mote.
2026-11-04 18:49:11 +08:00
yetone 17154e1654 provider: a Claude account not used in five hours shows its 5-hour window unused, not missing (motui9535)
motui9535 (Discord #feedback, v0.1.2909, screenshot): of three Team
accounts the preferred one showed 7 days 17% and 7 days · Fable 30% and
no 5-hour window; the two others showed all three. Anthropic leaves a
window out (null) while it hasn't started (claudeWindowsExpected says as
much for the warm-up), so Claude Code's /usage has no "Current session"
line for an account nobody used in the last five hours, and the card
took the missing line as no window at all. The aggregate's 5 hours
(100%) then averaged only the two other accounts.

A whole /usage reading (claudeWindows, the one place the active and the
saved accounts' readings are kept) now gets the 5-hour window it leaves
out as not started: 0% used, no reset, first, as Claude Code orders
them (claudeKindOrder, taken out of NoteClaudeLimits). A header heard
later replaces it as before. Only the 5-hour window: a reading that
tells any window tells the week. parseClaudeUsage is unchanged
(TestClaudeUsageWeeklyOnly still holds that the parser makes none up);
TestClaudeSwitchWeeklyOnly's card now has the unstarted 5-hour window.

Run (mote, at this tree):
- go test ./internal/provider: ok (132.9s)
- go test -run 'Claude|Usage|Quota' ./internal/gateway ./internal/cli ./internal/gui: ok
- go vet ./internal/provider on darwin, linux (-tags nogui), windows; gofmt -l clean
Broken by hand: without the claudeWithUnstarted call,
TestClaudeUnstartedSessionShownUnused is red: windows ["7 days" "7 days
· Fable"], motui's shape.
Not tried: a real Claude account's /usage with an unstarted session (the
null comes from claudeWindowsExpected's note and the screenshot); no GUI
test, the cards draw every window /api/usage/quotas gives and the change
is in what it gives; Windows/Linux runs.
2026-11-04 16:47:45 +08:00
yetone f0b99745ed provider: a Codex account is held on allowed false alone, as the 26.1029 app's Send gate reads it (xiaoq6285)
xiaoq6285 (Discord, Codex App 26.1029 on Windows, Plus, model_provider =
"magpie", requires_openai_auth = true) answered 40cfd32b0: "但是5小时也得算的
我就是5小时用完了 周额度还有" - their 5h window was used up with the week
open, and Send was grey.

What the app greys Send on, read from the bundles:
- ChatGPT.app 26.1029.61003 (the macOS build of the reporter's version,
  from persistent.oaistatic.com/codex-app-prod/appcast.xml), async chunk
  "a6kU": the composer gate returns open unless
  "n.rate_limit?.allowed!==!1" fails, i.e. it greys only on allowed
  false (then lets credits and a workspace within its overage through, and
  a window redeemed with a reset). The composer's sendBlocked is that gate
  or a model-scoped additional_rate_limits entry for the selected model.
- OpenAI.Codex 26.1027.3384 on the Windows box (app-primary lV,
  composer-content TN) and ChatGPT.app 26.1021: the same.
- The app keeps a window of an allowed account at 1% or more left
  ("Math.max(100-e,+(!0===t))"), so allowed true with 100% reads as room.

What the backend says at a used-up 5h window: the real Team reply in
testdata (codex_usage_team_spend_cap.json) has 5h at 100%, the week at
63%, and allowed false, limit_reached true.

So the reporter's case is allowed false, which codexHeld held before
40cfd32b0 and still does; no 5h rule is needed. 40cfd32b0's two new
held cases (allowed not said with limit_reached or a window at 100%;
allowed true with every window at 100%) are readings the app still sends
for, so holding them only took the app out of ChatGPT (#996) for nothing.
codexAtLimit is allowed false again. A new subcase pins the reporter's
shape (Plus, 5h at 100%, week open, allowed false, no credits: held).

Why Send stayed grey with requires_openai_auth still written is not
explained by the rule: with allowed false and no credits magpie holds
it. Left open: their reading, their magpie log, and whether a
model-scoped limit (additional_rate_limits, which magpie doesn't read)
was what greyed it.

Run on mote: go test -count=1 -timeout 45m ./internal/provider
./internal/agent ok (172s, 334s); go vet ./internal/provider native, GOOS=windows
and GOOS=linux ok; gofmt -l clean. Broken by hand: with origin/main's
subscription_usage.go and these tests, TestCodexUsedUpIsWhatTheAppHolds
fails on "limit reached, allowed not said", "window at 100%, allowed not
said" and "every window at 100% but allowed" (CodexUsedUp = true, want
false).
Not tried: the real 26.1029 app with a used-up account, a real Plus
/wham/usage reading at a used-up 5h window (the Team one is the only real
one), a Windows run.
2026-11-04 14:38:48 +08:00
yetone 40cfd32b0b provider: a Codex account with no credits and every window at 100% counts held though allowed isn't false (xiaoq6285)
xiaoq6285 (Discord, magpie 0.1.2891, Codex App 26.1029, Windows): a used-up
Plus account, no credits, 用量 showing it used up, config.toml with
model_provider = "magpie" and requires_openai_auth = true, Send grey until
Codex was switched off in magpie. Banked resets and paid credits were ruled
out (codexHeld reads neither resets nor, here, any credits). What is left is
a reading that doesn't say allowed false: codexHeld needed exactly that, so
CodexUsedUp stayed false and Sync kept requires_openai_auth, which makes the
app read the account's rate limit and grey Send.

codexAtLimit now holds: allowed false (as before); allowed not said with
limit_reached or a window at 100%; allowed true with every reported window
at 100%. Credits and the workspace-overage exemptions are unchanged and
still run after it.

Why the two cases that were false stay narrow: a7c4e5ddd (#996) pinned
"limit_reached but allowed, no credits" to not held, because the composer
gate (hP / hardBlocked in 26.930) reads allowed alone and the app still
sent; holding such an account only takes the app out of ChatGPT (durable
threads, remote control, cloud tasks, its usage meter) for nothing. That
cost is real, so allowed true still stands unless no window has room: a 5h
window at 100% with the week open is not held (new case). The case
"limit_reached, allowed not said" does flip to held.

Not known: the reporter's actual reading (allowed true or missing, never
seen) or the 26.1029 gate (its bundle isn't on any test box; 26.1021 is).
If their reading says allowed false with no credits this changes nothing
for them.

Run on mote: go test -timeout 45m ./internal/provider ./internal/agent ok
(194s, 346s); GOOS=linux, GOOS=windows and native go vet on both ok; gofmt -l
clean. Broken by hand: with the old subscription_usage.go and the new tests,
TestCodexUsedUpIsWhatTheAppHolds fails on "limit_reached, allowed not said,
no credits" and "every window at 100% but allowed, no credits".
Not tried: the real 26.1029 app, a real used-up reading, Windows run.
2026-11-04 12:41:11 +08:00
yetone b0174e7615 usage: a ChatGPT card says why its allowance can't be read, and a ChatGPT API account says where it shows
hmy on Discord: five ChatGPT accounts each said only "暂时无法获取额度"
(Allowance unavailable). danzi002 on Discord: accounts added through the
API never show usage, ones added as ChatGPT do.

What changed:
- Codex's usage read (codexWindows) now words its failure
  (codex_usage_words.go): a Cloudflare challenge names the proxy/VPN
  address as the usual cause; any other HTTP answer names its status and
  what ChatGPT said; a network error says chatgpt.com couldn't be
  reached; a reply magpie can't decode says so. The error still unwraps
  to accountStatusError, so expiry and passing logic is unchanged.
- A ChatGPT API account (chatgpt-api) was read as a Codex account: a
  saved one said "chatgpt-api accounts can't be used side by side", the
  one in use read Codex's own sign-in ("Codex is signed out", or another
  account's allowance under its name). OpenAI's API tells no plan usage,
  so its row now says so, names chatgpt.com/settings/usage (SeeAt) and
  says the same account added as ChatGPT shows it here.
- GUI quotaError translates each of these (en, zh, zh-TW, ja, de), and
  "not read yet" (errNotAsked) gets its own words. The generic fallback
  now reads "Allowance unavailable — hover for why"; the row's tooltip
  has always been the raw error. Comments in app.js were shortened to
  stay under TestCoreScriptBudget, which is not raised.
- docs/subsystems/providers-accounts.md describes the words.

Endpoint: the real wham/usage read of the owner's accounts in a sandbox
HOME copy (read-only, ~/.codex untouched) answered 200 and parsed, so
the endpoint itself is not broken; the "error decoding response body"
work is another session's and is not touched here.

Run (on mote; provider and gui again at the pushed head, rebased on
18c69aa46; 2251ca1ce, new under it, changed app.js and the budget):
- gofmt -l clean; GOOS=linux -tags nogui and GOOS=windows go vet of
  provider and gui clean.
- go test -timeout 45m ./...: ok except TestEveryRouteHasACommandOrIsNamed
  (#4826, red on origin/main 2251ca1ce too), TestMainWindowCorners (#3949,
  red on main too) and TestCodexPoolSaysTheClientsVersion (#4807, red in
  the full run, ok alone here and on main). At the pushed head:
  provider ok, gui ok but TestMainWindowCorners (#3949), core budget ok.
- GUI: chatgpt-usage-why.test.cjs (new; chromium and webkit, 560 and
  390, en/zh/zh-TW/ja/de, each row's words, its status code, the raw
  tooltip, no overflow) and the six tests whose generic line changed.
  The whole GUI suite was not run before this push: another session's
  full suite held mote. The change adds no API call and no layout, only
  words; the whole suite runs after the push and its reds get issues.

Broken by hand:
- codexWindows returning the bare err: TestCodexUsageSaysWhy and
  TestCodexLoginUsageSaysCloudflare red.
- the GUI ChatGPT patterns removed: chatgpt-usage-why 0/2.
- the chatgpt-api branch off: TestChatGPTAPIUsageSaysWhere red, the
  row read "Codex is signed out; run codex login".

Not tried: a real Cloudflare challenge (the fixture is the start of its
page as Cloudflare serves it, not hmy's bytes, which magpie hasn't got); a real ChatGPT API account (none signed in here); making a
ChatGPT API account's usage readable, since its token is for
api.openai.com and OpenAI shows plan usage only on chatgpt.com.
2026-11-02 20:04:32 +08:00
yetone 2251ca1ce9 providers: a ChatGPT account's row says when its paid plan ends (danzi002)
danzi002 on Discord (#general, 11-02): 「codex 账号什么是可以加一个 plus
账号到期时间」. The Usage page, the tray panel, the TUI and `magpie
quota` have shown "Until …" for the signed-in Codex account since
d8200dfe5. The Providers → Codex editor's account rows showed only
"ChatGPT Plus", for every account, saved ones included.

Now each Codex and ChatGPT API account in /api/providers carries
`until`, from its own sign-in's id token claim
https://api.openai.com/auth → chatgpt_subscription_active_until (no new
network call). The row puts "Until Nov 19" on the line under its name,
beside its allowance, the whole date and time in its tooltip.
- Codex: the sign-in Codex holds when it holds that account (through
  readCodexLogin, which it refreshes), else logins.json's copy.
- ChatGPT API: its saved id token, then its access token.
- No claim, an unparsable one, or a date gone by: nothing shown, never
  a guess. A real Pro token issued today carried an until weeks in the
  past (its last_checked was older still): OpenAI updates the claim now
  and then, so a past date says nothing true about the plan.
- chatgptUntil is the one reader; codexUntil (the usage card) uses it.

The core scripts' budget is not raised: two account-row comments in
app.js were cut to pay for the line (1,533,739 of 1,533,802).

Checked on real tokens (key names only, read-only from
~/.config/magpie/logins.json): the auth claim's keys are
chatgpt_account_id, chatgpt_plan_type, chatgpt_subscription_active_start,
chatgpt_subscription_active_until, chatgpt_subscription_last_checked,
chatgpt_user_id, groups, localhost, organizations, user_id; the until is
RFC3339 with +00:00. The tests' claims are written in that shape.

Run at this tree on mote (macOS 27):
- gofmt -l internal: nothing.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gui
  ./internal/tui .: provider, tui and root ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 only, the same
  on main). TestCoreScriptBudget ok.
- go vet ./internal/provider ./internal/gui; GOOS=linux go vet -tags
  nogui; GOOS=windows go vet: ok.
- New TestCodexLoginUntil (signed-in and saved accounts, a past date, no
  claim, the JSON the GUI reads) and TestSIWCLoginUntil: ok.
- New account-plan-until.test.cjs: Chromium and WebKit, 1000, 560 and a
  390 phone browser, en zh zh-TW ja de; the date is whole, inside its
  row, translated, the first line stays one line, no sideways scroll.
- GUI files account-*, codex-*, i18n-keys, lane-limit, login-*,
  providers-*: 892 of 894 ok. The two reds are codex-auto-reset webkit
  de 1100 and 420 ("the click moved the page", Usage page), red the same
  way run alone at origin/main e156fdd03 on mote (#4790).

Rebased on origin/main e156fdd03 (three mover-min commits since the
base): ./internal/provider and TestCoreScriptBudget run again there, ok.

Broken by hand: dropping lg.Until's assignment in loginsNow turns
TestCodexLoginUntil red; dropping the line in siwcLoginList turns
TestSIWCLoginUntil red; dropping the aq.append in renderAccounts turns
account-plan-until red in both engines.

Not tried: a Codex account held in another home (codexHeldIn) has no
test; no real ChatGPT API account's token was read, so its claim is
assumed from the Codex one; no Team plan token was seen; the real app
was not opened, only Playwright's Chromium and WebKit.
2026-11-02 19:41:05 +08:00
ggbdpqandyetone ca1fc43fc9 provider: quota history draws no line for a plugin's aside window that says no share (#4825)
ggbdpq's patch (gua2100 on Discord), reviewed and landed with an
end-to-end test and a doc line.

What changed
- quotaOfPlugin marks an aside window that leaves `used` out, with no
  count to reckon one from, as noShare. pointOf refuses such a window,
  so the history no longer draws a flat 100%-left line for it. The card
  still shows the row as before.
- noShare is unexported and so lost on JSON. Cards restored from the
  cache have AsOf set, and noteQuotaHistory skips them, so this never
  matters.
- Review changes: TestAsideWindowWithoutUsedDrawsNoLine now also runs
  the windows through noteQuotaHistory and QuotaHistories in a sandbox
  HOME, and wants lines [Bonus Weekly] only.
  docs/subsystems/providers-accounts.md says such a window isn't kept.

Run at the pushed head (on mote, base 4d55a0a02)
- go test -race ./internal/provider passes for the touched tests, and
  the provider package passes.
- The full suite, gofmt and the cross-OS vet are as recorded in the
  #4824 netproxy commit. The only reds are #4826 and #4807, neither in
  provider.

Broken by hand: with noShare removed from pointOf, the test is red:
"On-demand/Points: history point true, want false" and "history lines
[Bonus On-demand Points Weekly], want [Bonus Weekly]".

Not tried: a real plugin reporting such a row, or the chart in a
browser. A wallet Balance window draws the same flat line; that is
#4831, not this commit.

Co-authored-by: yetone <yetoneful@gmail.com>
2026-11-02 09:11:30 +08:00
yetone 16ce5ed232 usage: an account whose longer window is used up adds no headroom to the all-accounts sum (#4791)
hayden4608 (Discord) and handong66 (#4791) have four Codex accounts. Three
show 5 hours 100% left with 7 days 0% left, and one shows 5 hours 0% left
with 7 days 22% left. The All accounts strip read "5 hours 75% left", but
none of those three can spend its 5 hours until its week starts again.
The right figure is 0%.

mergeQuotas (quotaall.js) is the one place that sums windows across
accounts. It feeds the Usage page's strip, the tray panel's strip and the
Routing groups' line. The native menu-bar tray, the TUI, the CLI and
/v1/magpie/quotas show one account at a time and are unchanged. The GUI's
JSON doesn't carry Aside, Model or the matches, so the call is made in Go.
provider.WithHeldWindows marks a window heldBy another window of the same
account when that other window:
- stops the account for every model, by routing's rule: not aside, no
  model, no matches, used >= 100, reset not passed, and not Codex credits
  that go on; and
- starts again after this one (by reset times, else by span).
So 7 days used up holds 5 hours, but 5 hours used up doesn't hold a week
with 22% left. /api/usage/quotas and its refresh apply it. mergeQuotas
counts a held share window as 100 used and a held counted one as its
limit, and the strip's tooltip says how many were counted that way
(en/zh/zh-TW/ja/de). The account cards still show the vendor's own figure.

Run on mote (macOS) at this head's parent tree:
- go vet for darwin, linux (nogui) and windows: ok; gofmt -l: none.
- go test -count=1 ./internal/provider ./internal/gui, before the
  quota_span leftOut line and an i18n comment fix. The provider package's
  only red was TestQuotaSpanCarriesEveryWindowField, which wanted heldBy
  named, and it is now named. internal/gui's only red was
  TestMainWindowCorners/macOS_26_SDK, which is #3949.
- GUI, chromium and webkit, every language, 440px and 360px: quota-*,
  usage-* (all-accounts, merge, accounts, fold, refresh and more),
  panel-usage/quota/switch-accounts/balance-order, routing-quota-left,
  routing-group, tray-usage, i18n-keys, gui-de/ja/zh-tw, old-webkit:
  704 of 707. The reds were i18n-keys (a quoted "All accounts" in
  window_held.go's comment, fixed here) and usage-fold's "17
  subscriptions and 29 accounts" in both engines, which is #4790 and is
  red at origin/main too (see below).
At the pushed head, rebased on eb3b9376e, on mote: gofmt none, vet ok.
internal/provider ok. internal/gui is red only on TestMainWindowCorners
(#3949). GUI usage-merge, usage-all-accounts, i18n-keys and usage-fold,
both engines: 44 of 46. The 2 reds are usage-fold's 29 accounts, which
fail the same at origin/main eb3b9376e on mote (noted on #4790).

Broken by hand, each red, then restored (cmp):
- Go, no HeldBy set: both TestHeldWindows tests red (a, b, c not held).
- Go, outlasts always true: red on d and on "a week that starts again
  first".
- JS, held forced false: usage-merge plus all 5 languages of
  usage-all-accounts red in chromium, showing the reporter's
  "5 hours · 75% left".

Not tried: real accounts. The issue names no provider; Codex is assumed
from the cards' 5 hours / 7 days. Not done: marking a card as held by its
week, the reporter's optional second ask. Not written: a handler-level
test that /api/usage/quotas carries heldBy. Not run on Linux or Windows.
2026-11-02 03:46:01 +08:00
yetone 94f6f60925 tray: every window a card reports can be picked alone for the menu bar, Cursor's Grok Bot too (CrazyJal on X)
CrazyJal on X (tweet 2116833523604886006): Settings > Usage > Menu bar
windows, Cursor's pill had no choice for the Grok Bot window alone.

Why: the picker offered only the windows the menu bar shows unpicked
(trayWindows), which leaves out every window set aside. The Cursor
plugin reports Grok Bot aside (so it doesn't stop Cursor's models), so
it was never offered. And kinds were only a span ("7d"): Grok Bot and a
weekly plan's Weekly are both 7 days, as are Antigravity's two pools, so
two windows shared one kind, the GUI showed one of them, and picking it
picked both. The plugin reports the window fine; nothing changes there.

Fix (the class, every provider): trayChoices lists every window of a
card that the menu bar can say as a percent (trayCounted): the usual
ones first, then the rest (money aside, one model's window, Grok Bot),
marked TrayExtra and shown only when picked. Every choice has a kind of
its own: a usual window keeps its span's kind where it is the only one
of that span (so existing picks like claude:["5h"] keep working);
another of that span, and every extra, gets its model or name after it
("7d:grok bot", "7d:gemini · 7 days"). Unpicked, every card shows what
it showed before. The Settings pill offers the extras, and drops a pick
only when it is empty or exactly the usual windows.

Run (mote, at this tree, committed then as 0750aa783, on origin/main 15b035eef):
- go test -count=1 ./internal/gui ./internal/provider ./internal/settings:
  provider ok, settings ok; gui red only on TestMainWindowCorners,
  red the same on origin/main 15b035eef on mote (filed #3949).
- GOOS=windows go vet ./internal/gui ./internal/provider: ok. gofmt -l clean.
- win-run go test ./internal/gui -run 'TestTray|TestWithTrayKinds': ok.
- GUI (Chromium + WebKit, en/zh/zh-TW/ja/de, narrow): tray-windows 20/20;
  with i18n-keys, old-webkit, tray-usages, tray-totals, tray-cost,
  tray-logos, tray-inuse: every one ok but tray-windows' new subtest
  before its names were read through t() (fixed, then 20/20).
- No size budget touched; traywindows.js is loaded only with the menu bar.

Broken by hand: trayChoices without the extras -> TestWithTrayKinds and
TestTrayWindowsPickAside red; the old save rule (v.length < ws.length)
-> tray-windows red in every language.

Not tried: a real Cursor account in the real menu bar (the fixture is the
plugin's own window shape, index.mjs botUsage: aside, 7 days); the Linux
gui package (wsl-run lacks webkitgtk-6.0 headers to build it). A user who
picked "7d" on a card with two 7-day usual windows (Antigravity's pools)
falls back to every window and picks again; that pick was ambiguous before.

Rebased on c0477aa72 (app.js, Providers reset rows; nothing in common)
and run again at the pushed head on mote: go test ./internal/gui -run
'Budget|Tray|Size' ok; tray-windows + i18n-keys (both engines, every
language) 24/24.
2026-11-01 21:10:48 +08:00
yetone 7b6b7492a9 claude: an account on overages is read with its windows and switched off (#4532)
Claude Code's /usage line "You are currently using your overages to
power your Claude Code usage…" was in claudeUsageDenied, so the whole
reading became an error: the card lost its windows, and NextLogin, which
stays on an account it can't read, left Claude Code billing overages
while other accounts had room (StringKe's audit, item 3).

Now the line is no error. The windows under it are read as usual, and a
Text row "Extra usage" with Used 100 is added (claudeOveragesWindow), so
usedPast/roomLeft count the account spent and the switch moves off it.
The row ends when the last used-up window renews (the time Claude Code
says it switches back), else at the next reading. Routing skips Text
rows, so the gateway's own account choice is unchanged. The GUI says the
row "In use" in the reader's language (quotaText; a plugin's text row
keeps its display as it came). The overages case is out of
TestClaudeUsageFailureDoesNotHideAccountErrors: it was the bug.

Run (mote):
- TestClaudeUsageOverages, TestClaudeSwitchOffOverages: red on the old
  claude_usage_cli.go (an error; switched to ""), red with the row's Used
  set to 0 by hand, green now.
- go test -tags nogui ./internal/provider -run
  'Claude|Usage|NextLogin|Next|Switch' ok.
- GUI: claude-overages (new, 5 languages, chromium + webkit) red 8 of 10
  on the old app.js (en passes there), green now; with quota-text-row,
  quota-name-translated, i18n-keys, usage-no-reading: 40 pass.
- go vet darwin/linux/windows; gofmt clean.

Not tried: a real account on overages; the text is Claude Code
2.1.316's string table, and the windows under it are what StringKe
describes.
2026-11-01 15:16:00 +08:00
9097687a31 gui: Hide accounts leaves the user's own account names and plans in sight (#3656)
With Hide accounts (账号打码) on, the name a user gave an account
(#1515) was blurred like the account, so faketrader's several
Antigravity accounts couldn't be told apart; and an Antigravity
account whose value is "Google" blurred "Google" of its plan
"Google AI Pro" on Usage and on the Providers row. The name the user
gave an account is shown text, not an identity. The account is.

- provider: a card's Alias says whether it is the user's own name
  (SubscriptionQuota.Named, set by withAccountNames from
  AccountNameOf), since Alias is also a plugin's name for an account
  (PluginUserOf, a masked phone, #4416) or a seat's key plan, and the
  Usage page and tray panel may have no /api/providers to tell them
  apart. labelProvider is AccountLabelOf's "plugin:" lookup, shared.
- app.js names(): the user's own names (accountNames) and named
  aliases are no longer accounts to hide; accountUsers, an unnamed
  alias and a seat still are (noteAccounts keeps an alias without
  named).
- app.js mask(): labels are scoped by element, never by value
  (LESSONS: scope an exemption by where the value sits). In
  .own-name, .plan, .acct-plan (the Providers row's plan pill, new
  class), .model-value and .subscription-head > b only an address is
  hidden; a plan's and a model's tooltip too (TIPS). The own name's
  tooltip ("name · account") is masked in full.
- .own-name is set only where the text is the user's own: the
  editor's rename span when it has one (else it shows the raw
  account and stays hidden), Usage's quota-alias and the panel's
  pq-user when q.named.

From skygunner's patch (95c0511 on 19253f67), changed:
- Its .acct-who .rename exemption showed a raw non-email account
  (the rename span shows the account when it has no name of the
  user's). Now only an own-name span is exempt.
- Its [title]:not(LABELS) skipped those elements' tooltips
  altogether, so the address in "alias · user" (quota-alias, rename)
  went unmasked. Tooltips are masked; only a plan's or model's hides
  just an address.
- Dropping every alias from names() would have shown a plugin's name
  for an account (#4416 came after the patch's base). Named tells
  the user's own apart.
- The n.data.length < 2 skip the patch removed is kept.
- Its test is rewritten on the new fixtures: an unnamed plugin
  alias, an address in a plan, the editor with and without an own
  name, the panel, a model value, tooltips.

account-alias.test.cjs and account-eye.test.cjs said Hide accounts
hides the user's own name; they now say it stays in sight, the
accounts still hidden. account-alias brings the window's page to the
front before clicking #usageMask, and the panel's before waiting on
it: behind the panel's page it gets no
frames and the click waited for one, red 5 times in 2 runs at
fb3942ee6 (#2984's account-alias half), 0 in 100 after.

Not changed: the tray panel card's tooltip is one string of account
and plan, so a plan word that equals an account's value is still
hidden there (#4677). OpenCode Zen's "Signed in as <account>"
in the issue's screenshot is the raw account, hidden as before.

Core scripts: app.js's own comments in the masking module are cut, so
the core is 742 bytes under its budget at the pushed head (no raise).

What was run:
- At this on 4c815ac2a, on mote (then rebased onto 39bade71d, whose 8
  commits change only i18n.js and plugins/gateway/settings.js; the
  budget measured again, 742 under): gofmt -l; go vet
  of provider, gui, usageapi; go test -tags nogui ./internal/provider
  ./internal/usageapi ok; TestCoreScriptBudget ok; the 19 masking GUI
  files (account-*, mask-*, masking-records, privacy-*, provider-mask,
  provider-unmasked, routing-masking, window-mask, click-scroll,
  i18n-keys), both engines: 539/540. The red was account-alias's
  panel wait behind the window's page, fixed by the panel bringToFront
  above. account-alias + account-mask-alias-plan after it: 4 runs,
  159/160 (one red in "renamed in place", whose body this change doesn't
  touch, #4749). account-alias 6 more runs: 120/120 here, 117/120 on
  origin/main 90c02326b (#2984).
- account-mask-alias-plan: 20/20 on the fix (Chromium, WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420), 20/20 red at fb3942ee6 (the alias is
  masked); red with the plan selectors taken out of LABELS by hand.
  account_plugin_user_test red with Named always false by hand.
- At 4eeba1ca6 (this on 90c02326b): go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./..., go build for darwin,
  linux (nogui) and windows: ok. go test -tags nogui ./... on the
  Linux box: every package ok except internal/agent (8 install tests
  red the same on origin/main there, #4033, #3548) and internal/gui
  (TestSettingsSaveKeepsWhatItDoesNotSend, red on main, #4514;
  TestColdTurnsTaken on mote once, #4510). The whole GUI suite on the
  Linux box, 6 wide: 16857 pass, 491 fail in 100 files, none of them
  the masking files but account-every-reset; being run against
  origin/main to sort.

Co-authored-by: skygunner <84759+skygunner@users.noreply.github.com>
Co-authored-by: vincent <vincent@users.noreply.github.com>
Co-authored-by: Fake Trader <9635792+faketrader@users.noreply.github.com>
2026-11-01 15:15:08 +08:00
yetone fbb1b36d1f provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read b48881f50 and 42c49e74d and left three notes on #4532
(issuecomment-6540015427). All three hold against the code:

1. Only accounts that were on were kept alive (claudeKeptAlive needed
   l.On). An account switched off as a reserve is still a sign-in the
   user kept for later, and Codex's keep-alive already renews saved
   ChatGPT sign-ins on or off. A run of Claude Code's /usage every eight
   days costs one local run and asks Anthropic nothing magpie doesn't
   already ask, so off accounts are kept too. Setup-token and signed-out
   accounts still aren't. The keep-alive never switches an account on.

2. The run's /usage reading was dropped (`_, err :=
   readSavedClaudeUsage`). The run now goes through the account's
   reading, the way a card's refresh reads a saved account:
   renewClaude forgets the account's minute-cached reading and calls
   loginReading with a keepingAlive ctx (asked, so nothing is held).
   claudeWindows runs Claude Code for it as for savedRefresh, past the
   30-second floor (the keep-alive is an hour apart at most), and keeps
   it in claudeUsage. loginReading keeps it beside the account and on
   disk (keepReading), and the new keepCardRead puts it on the account's
   card in the Usage cache with its history and the menu bar told, the
   way refreshCards does. A card the Usage page doesn't have isn't added.
   The run's own error comes back through the ctx, not the kept reading,
   so a failure is still told apart from a reading kept from before. This
   path doesn't bump the global ask generation, so Claude Code's own
   account isn't read again because of it.

3. A failed run held the hourly slot: still due, and with one renewal a
   look, the accounts after it never had theirs. A renewal that fails, for
   Claude and for Codex (the same loop had the same gap), now waits
   keepAliveRetry (6 hours, in memory) before the hourly look tries it
   again, and doesn't take the look's turn meanwhile. `magpie accounts
   refresh` (every 0) still tries it at once. A success clears it.

The help text, refreshAccounts' comment and providers-accounts.md say so.

Run on mote at 82b45888a plus this change: go test -timeout 45m
-count=1 ./internal/provider/... ./internal/cli/... ok; go test -race
-count=10 -run 'TestRenewLogins|WeeklyOnly|TestClaudeUsage'
./internal/provider ok; gofmt -l clean; GOOS=linux go vet -tags nogui,
GOOS=windows go vet and go vet of ./internal/provider/...
./internal/cli/... clean.

Broken by hand, each on mote:
- l.On put back in claudeKeptAlive: TestRenewLoginsKeepsSavedClaudeSignedIn
  ("renewed what wasn't due" with team@ missing), TestRenewLoginsKeepsClaudeReading,
  TestRenewLoginsFailedWaitsItsTurn and TestRenewLoginsLeavesClaudeSetupToken
  fail.
- renewClaude back to `_, err := readSavedClaudeUsage(...)`:
  TestRenewLoginsKeepsClaudeReading fails ("the account's reading: false").
- renewWaiting taken out of the loop: TestRenewLoginsFailedWaitsItsTurn
  fails at look 2 (the failed account took the turn again).

Not tried: real accounts and real Claude Code (fake runner, sandbox
HOME). The back-off is in memory, so a restarted magpie tries a failed
account on its first look. Codex's back-off is covered only through the
shared loop; there's no Codex-specific test for it.
2026-10-31 14:40:03 +08:00
yetone 7d4a631480 tray: pick which of a subscription's windows the menu bar shows (StrikingRaw on X)
Claude Pro's menu bar card drew its 5-hour and 7-day windows as two
small stacked numbers, and the user wanted one of them alone. Settings ›
Usage › Menu bar windows (under Allowances in the menu bar) lists a pill
per ticked subscription with two or more windows ("Claude Code · All
windows"), opening the app's menu: All windows, then each window. The
choice is settings.TrayWindows, by provider id (every account of it, the
in-use "|*" card too) and by window kind from the span ("5h", "1d", "7d",
"month", "15m", "name:<name>" when the span is unknown), so a vendor
reordering windows changes nothing. Unset shows every window as before;
a pick whose windows are all gone shows every window again, never an
empty card. Only the bar's rows and the Linux label are filtered; the
tooltip still says every window. One row draws at mpRowFont's 11pt
single-row size. Hidden on Windows (its tray shows no text). Per
computer through KeepOwn. The GUI learns kinds from trayKind on
/api/usage/quotas (withTrayKinds; model and aside windows get none). The
row's code is a lazily imported traywindows.js, so the core script
budget is not raised (app.js +4 lines for the call and the prefs keep).

Run:
- mote (macOS): go test -run 'TrayWindow|TrayUsage|WithTrayKinds|
  CoreScriptBudget|AppScript|TrayImage' ./internal/gui/ ok;
  ./internal/settings/ ok; davsync TestSync ok. TestTrayImageOneWindow
  draws through AppKit: Claude's card one line ("42%"), both windows two;
  the PNGs were looked at.
- mote: gofmt -l empty; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./... ok; go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build ok.
- magpie-desktop (Linux VM), --test-concurrency=1, BROWSER=chromium and
  webkit: tray-windows (en, zh, zh-TW, ja, de; picking All; hidden on
  Windows / single-window / no cards; 360px narrow), i18n-keys,
  old-webkit, tray-usages, tray-logos, tray-cost, quota-pace: 43/43 each.
After rebasing on ec5571d6f: the focused Go run above, davsync and vet of
the touched packages ok on mote; tray-windows, i18n-keys, old-webkit,
tray-usages 27/27 in chromium and webkit on the Linux VM.
Broken by hand: the row filter in trayCardText off -> TestTrayWindowsPicked
and TestTrayImageOneWindow red; trayWindows out of prefsKeep ->
tray-windows.test.cjs red in every language. Restored, green.
Not run: the full Go suite (owner: ship each verified fix at once; mote
was at load 20-27 under another session's full GUI suite) and the whole
GUI suite. The GUI ran on the Linux VM because mote's browsers crash or
hang under that load (#4125; TestTrayCellClickReleasedPanel is red the
same way on origin/main c84c3e1c0 there).
Not tried: the live app's real menu bar with a signed-in Claude account
(the AppKit drawer was exercised in-process instead); Linux tray label
on a real desktop.
2026-10-30 23:14:08 +08:00
yetone 2ff75161dc switch: Claude Code near out or refused for its limit is moved on within a minute (#4443)
In switch-only mode, Claude Code asks Anthropic directly, so magpie learns
the active account is out only from a `claude -p /usage` read. That read was
due 5 to 15 minutes (claudeUsageWait) after the last one, and
KeepOnAnAccountWithRoom looked at Claude's sign-in only every 5 minutes.
Codex already had a 1-minute near-out cadence; Claude had none. mydosu's
account read 4% left at 12:16:15, which is under Smart's 98% threshold, so
it was rightly not moved then. It burnt through within the 5-minute gap,
and Claude Code refused for about 1.5 minutes until a hand switch, while
the other account had 100% left.

Changed:
- While Claude has an account to move to, the loop looks at its sign-in
  every claudeLookEvery (1 min) between the full looks (claudeLookDue).
- Near out (an all-model window at 90% or more, codexNearShare), the
  active account's /usage is due a minute after the last read instead of
  at its 5-15 minute wait (claudeWaitOf).
- When Claude Code writes its own rate_limit refusal ("You've hit your …
  limit": error "rate_limit", isApiErrorMessage) into a session in
  ~/.claude/projects/*/*.jsonl, the next look reads /usage at once and
  marks the reading stale (StaleAllowance). Only the bytes appended since
  the last scan are read (at most 1MB per session per scan). The first
  scan only marks where the sessions end. The refusal is a cue for the
  read, not a switch by itself: the transcript doesn't say which account
  was refused.
- Cost per minute: Logins("claude") plus leftAlone. With a spare, also a
  stat of each session file and a read of the appended bytes. /usage runs
  every minute only while the account is near out and in use, or after a
  refusal (30s floor still applies).

Run:
- New tests: TestClaudeNearOutIsReadEveryMinute,
  TestClaudeRefusalInSessionReadsAtOnce, TestScanClaudeLimits,
  TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut. Pass under -race
  -count=3 on mote, with TestClaudeSwitchOnly* and TestClaudeUsage*.
- Broken by hand, each red: no near-out wait ->
  TestClaudeNearOutIsReadEveryMinute ("switched to \"\""); no refusal due
  -> TestClaudeRefusalInSessionReadsAtOnce; no in-between look in the loop
  -> TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut (still on pro@x.com
  at its 1-minute deadline).
- Windows (xiaomi-gpu, win-run): the new and Claude tests pass. The whole
  internal/provider package has 13 reds there, and all 13 fail the same way
  run alone at origin/main d99e213f5: #2808 (keychain, SavedButSignedOut),
  #4115 (CodexDaemonEnv, CodexListTag), and #4446, filed now
  (TestCodexSignInKnown, TestGitOnDisk*).
- mote at eaa2eeb29 (this commit on fa427216a): gofmt -l clean; go vet
  (nogui, GOOS=linux nogui, GOOS=windows); go build for darwin, linux and
  windows; go test -tags nogui -count=1 -timeout 45m ./... exit 0, every
  package ok (gateway 672s, agent 268s, provider 173s).
- Rebased on 4 commits (gateway, plugin, provider/codex_models; none
  touch these files), at the pushed tree on mote: go vet (nogui, linux,
  windows), darwin and windows builds, internal/provider ok (213s) and
  internal/gateway ok (716s).

Not tried: a real Claude account running out, and a real Claude Code
session on Windows writing its refusal. The refusal line's format was
checked read-only against real local transcripts. No UI added.
2026-10-30 22:05:12 +08:00
yetone 8ebf9cbea9 claude: add an account from a setup-token (CLAUDE_CODE_OAUTH_TOKEN)
sfss5362 on X asked "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". It didn't work
before: cleanClaudeEnv strips the variable everywhere, and the import
flow needs a refresh token and an email.

A Claude account can now be added from the token `claude setup-token`
prints. In the window: the sign-in's "Use a setup-token instead…" and
the accounts list's "Add an account by setup-token…", which post to
POST /api/signin/claude-token.

The token is kept in logins.json as {"setupToken":…}. The real Claude
Code gets it in CLAUDE_CODE_OAUTH_TOKEN, and only for runs in that
account's own config directory (inClaudeDir via
provider.ClaudeDirToken). It never goes on the command line or into a
log. magpie never asks Anthropic anything with it. The bridge, the
sdk-cli entrypoint and the weighting are unchanged.

What such a token can't do: it has the inference scope only.
- Claude Code's `auth status` gives no email or plan. The account is
  named "Claude setup-token <6 hex of its hash>".
- Its /usage prints the API cost view. /usage is never run for it, so
  its allowance is unknown (errClaudeSetupToken, which `passing` keeps
  as saying nothing about the account), not zero. Windows heard on
  real replies still fill it in.
- Its config directory holds no .credentials.json, so Claude Code has
  no sign-in to fall back to if the token is refused.
- Claude Code itself is never signed in to it. addLogin, switchLogin,
  putClaudeLogin, SetKeepLoginAs, NextLogin and signInToFirst all pass
  it over. Its row shows Remove and "magpie only", and the switch menu
  leaves it out.
New strings are in zh, zh-TW, ja and de. Docs: providers-accounts.md
and claude-subscription-bridge.md.

Run:
- mote: gofmt -l (clean); go vet ./internal/...; GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of provider, gateway and gui; go
  build ./...
- mote: go test of provider and gateway, -run on SetupToken, Claude
  usage, warm-up, saved, account, logins, switch and keep-login: ok.
- New tests, with a fake claude binary in a sandbox HOME:
  - TestClaudeSetupTokenAccount, TestClaudeSetupTokenSignsClaudeCodeInToNothing,
    TestClaudeSetupTokenAllowanceUnknown and TestCheckClaudeSetupToken
    in provider;
  - TestClaudeSetupTokenReachesItsOwnRunsOnly in gateway: the token
    reaches only its account's run, not "" or another dir, even with
    the shell's CLAUDE_CODE_OAUTH_TOKEN=leaked, and never in args;
  - claude-setup-token.test.cjs: Chromium on mote and WebKit on
    xiaomi-gpu, each in en, zh, zh-TW, ja and de.
- GUI files the change reaches (signin-link, signin-web-blocked,
  signin-closes-sheet, revoked-signin-account, account-eye,
  account-row-line, i18n-keys and the new one): 73/73 on xiaomi-gpu
  Chromium.
- On mote, 33 account, sign-in and i18n files had 96 reds. mote was
  overloaded by another session's full GUI suite. Six of those files
  fail 58 of 64 the same way at origin/main dafe4af82 there, and pass
  on xiaomi-gpu. WebKit on mote timed out on the untouched
  copilot-ghe.test.cjs too.

Size: app.js was 2,885 bytes over its budget after the rebase. The
new comments were cut, and the budgets were raised to the measured sizes
(app.js 1,317,705, core 1,539,423) with no room added, as
core_budget_test.go says. After the rebase onto origin/main 969868ccd,
these were run on mote at this head: TestCoreScriptBudget and the
SetupToken tests ok, and claude-setup-token plus i18n-keys in Chromium
9/9.

Broken by hand (each went red):
- without the token line in inClaudeDir, the gateway test;
- with addLogin allowed to sign Claude Code in, two provider tests;
- with /usage run for a token account, AllowanceUnknown ("told no
  allowance").
- With switchLogin's guard removed, the tests stay green, because
  putClaudeLogin still refuses.

Not tried: a real setup-token against Anthropic. The full Go and GUI
suites will be run after the push.
2026-10-30 14:50:44 +08:00
yetone d31710c71d provider: the switch off a spent Claude account reads saved accounts it has no reading of (cn_Vincentzyx on X)
cn_Vincentzyx on X: Claude Code not connected to magpie, only its
sign-in switched ("Only switch Claude Code's sign-in"), the accounts in
the order Settings' Make first gave them. The account Claude Code was on
ran out and it was never moved. ef2b2d1e3 (#1907) let switch-only move
a sign-in kept on one account; this is the other half.

Cause: NextLogin moves on only to a spare whose allowance is known and
not spent. A saved (not signed-in) Claude account's reading comes from
claudeWindows(ctx, user, false), which runs Claude Code's /usage for it
only on a card refresh (savedRefresh) and otherwise returns what was
kept, or errClaudeSaved when nothing was. Under switch-only no request
of a saved account passes the gateway (KeptToAgent), so
NoteClaudeLimits never hears of it either. A spare Claude Code wasn't
signed in to since (and with no reading on disk in last_quotas) was
"not read yet" on every look, and the switch never found one with
room.

Now, once the account Claude Code is on is spent, NextLogin reads such
a spare (no reading, or a read that failed for a reason other than the
account's own) through readSpare: the existing saved-account path,
Claude Code's own /usage run in the account's directory
(readSavedClaudeUsage), the same run a card refresh makes. Spares are
taken in order, one at a time, and reading stops at the first with
room. claudeWindows lets this read through (spareRead) only while it
has no windows for the account: once, then again only after
claudeUsageWait (5-15 min) while its read keeps failing, and never
under the 30s floor or while allowances are read only when asked
(holding). Nothing about how Claude Code is run, or the requests'
entrypoint, is changed.

Codex: its saved spares are read through their saved tokens
(savedLoginToken + wham/usage) in the same someLoginUsage call, with no
seen-in-use condition, so it had no such gap
(TestCodexSwitchOnlyStillSwitchesTheSignIn covers a spare magpie never
read before).

Run (mote, at this tree, rebased on c941e0877):
- TestClaudeSwitchOnlyReadsUnreadSpares (new) green, -count=3.
- go test ./internal/provider -count=1 -timeout 45m: ok (129s)
- gofmt -l clean; go vet ./internal/provider for darwin, linux, windows.

Broken by hand:
- NextLogin's readSpare call disabled: the new test is red
  (got ""→"" ok=false, the old behaviour).
- claudeWindows' spare gate reduced to spareRead(ctx) alone (no
  ws/wait check): red, "a spare run again on the next look".

Not tried: a real account switch with the reporter's accounts; this was
run in sandbox HOMEs with a stand-in for Claude Code's /usage only. With
Settings > Usage > Allowance reads at "When I ask", nothing is read in
the background, the switch included, as before: an unread spare stays
unknown there.
2026-10-30 13:11:36 +08:00
yetone d3898ca8d3 provider: ChatGPT account calls go with Codex's headers, and saved accounts are listed once a day
Two follow-ups of 6e55914b6's audit of what magpie sends OpenAI for
idle saved Codex accounts (owl, Discord #general: three ChatGPT accounts
deactivated). Product call made by the session the owner delegated
product calls to; mimicking the official client is allowed for every
vendor but Claude Code. Identity, base_instructions and prompts are not
touched.

- Headers. GET /backend-api/wham/usage, /wham/rate-limit-reset-credits,
  POST .../consume and POST auth.openai.com/oauth/token (live and saved
  sign-ins, and the sign-in's code exchange) went with Go's
  "Go-http-client/1.1" and no originator. They now carry Codex's
  originator and User-Agent through codexClientHeaders, the part of
  codexSign that /codex/models and /responses already used. No version
  header on them: codex-rs sends it with model requests only
  (login/src/auth/default_client.rs default_headers is originator +
  User-Agent; backend-client/src/client.rs adds auth headers).
- Refresh body. codex-rs (main f32b6cfd and rust-v0.165.0,
  login/src/oauth/client.rs refresh, auth/manager.rs
  request_chatgpt_token_refresh) sends JSON client_id, grant_type,
  refresh_token and refresh_reason, and no scope. magpie sent
  scope "openid profile email" and no reason. It now sends codex-rs's
  fields: proactive_expiry near expiry, unauthorized_recovery after a
  401 (stale token), scheduled from the 8-day keep-alive, forced for an
  import or a revoked-sign-in check. The code exchange's form already
  matched exchange_code; only its headers changed.
- Model lists. The active Codex account's /codex/models fetch (hourly
  KeepAccountsListed, FetchNew, Refresh) also fetched every switched-on
  saved account's list each time. codexFetchSaved now asks one with no
  list at once, and the others once a day, one per call, oldest asked
  first; a failed ask is remembered so a deactivated account doesn't go
  first every hour. The active account's list is unchanged.

Docs: providers-accounts.md says both.

Tests (codex_quiet_test.go), each red on the old behaviour (broken by
hand: wham/refresh/exchange headers removed, scope back, the age check
and the one-a-look cap removed, the keep-alive's reason dropped, and
separately the failed-ask memory skipped):
- TestCodexAccountCallsGoAsCodex counts the requests to a fake (usage 1,
  credits 1, consume 1, token 2) and checks User-Agent/originator on
  each and the refresh body's keys. Old: Go-http-client/1.1, "" and
  scope in the body.
- TestCodexRefreshSaysWhy: scheduled, forced, unauthorized_recovery.
  Old: no reason.
- TestSavedCodexListsOnceADay: 2 asks on the first look, 0 an hour on,
  1 then 1 a day on, 0 again, and 0 within the day while failing. Old:
  2 on every look; without the memory, a failing one asked again.

Run (mote-run, at origin/main 9b4d0bda8 plus this change, the tree
pushed unless the rebase below names a newer base):
- gofmt -l internal/provider: clean
- go vet ./internal/{provider,agent,cli,gateway} on darwin, GOOS=linux
  -tags nogui and GOOS=windows: ok
- go test -count=1 -timeout 45m ./internal/provider ./internal/agent
  ./internal/cli ./internal/gateway: all ok (118s, 199s, 44s, 562s)
Not tried: a real ChatGPT account (none touched, per the session's
rules), so OpenAI's answer to the new headers and the scope-less
refresh is known only from codex-rs doing the same. The Sign in with
ChatGPT API path (auth.openai.com/api/accounts/oauth/token, chatgpt_api.go)
is another client and is left as it was. Refresh in the GUI also lists
saved accounts by the once-a-day rule now.
2026-10-30 02:28:10 +08:00
yetone c3b0484a96 usage: keys of one account show its balance once (mimi)
mimi on Discord (#feedback): "同一个网站,添加多个key时,余额会重复展示" -
a site's keys 1-A031-Pro, 2-S009-Plus and 3-S010-Team-2 each showed the
account's $8.39 and its own curve.

KeyBalances still reads, keeps and charts every key on its own. What
changed is what the Usage page draws:
- balanceRead says whether the reading is the account's (balanceAccountWide),
  going by the source, not the vendor's name:
  - account-wide: a balance token (new-api /api/user/self, sub2api
    /api/v1/user/profile, AiHubMix), a known host's account query
    (DeepSeek, Moonshot, OpenRouter credits, SiliconFlow, StepFun, ...),
    and sub2api /v1/usage when its mode is "unrestricted" (wallet or the
    group's subscription, per sub2api's gateway_handler.go Usage);
  - per key: AiHubMix's /dashboard/billing/remain, new-api's
    /api/usage/token, sub2api in quota_limited mode, any other Balance
    URL the user named.
- Two such keys of one provider with the same amount are one account only
  when their balances moved together: the same latest change (from and
  to), first read within balanceHistGap. Two accounts with the same
  amount stay apart until one is spent from; keys whose amounts differ
  are never one. SharedBalance (the first key's name) says so in
  /api/usage/quotas, magpie quota --json and /v1/magpie/quotas.
- Refreshing a shared card reads every key it stands for (sharesAskedCard),
  so it stays one card. The history is read outside the cache's lock.
- The Usage page draws them as one row, one balance, one curve, with
  "+2 keys" beside the key and the keys on hover; the head's sum counts
  the account once. The code is in plugins/usage/page.js, so app.js is 9
  bytes smaller than before; no budget raised.

Run (mote-run, at the pre-rebase base d50f84c9f):
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok. gofmt -l: clean.
- go test -tags nogui -timeout 45m ./...: every package ok except
  internal/gui's TestCoreScriptBudget (app.js 676 bytes over; fixed by
  moving the code into the Usage plugin, then ok) and internal/update's
  TestRelaunchOpenTriedAgain (TempDir cleanup under load, #3881; 3 of 3 ok
  alone).
- go test -race on internal/provider's balance tests: ok.
- GUI, both engines, en and zh: 122 files (balance-*, usage-*, quota-*,
  tray-*, panel-*, gui-ja/de/zh-tw, i18n-keys, key-balance-card,
  routing-wallet-balance, ...): 1637 pass, 42 fail in 6 files, all the
  same at base a05b37353 run alone and all filed (#3679 quota-refresh-
  order, #3404 quota-count-wrap, #3414 usage-agents-hide, #3415
  usage-fold, #3104 usage-ledger, #3897 i18n-keys "Runs as"). After the
  move into the plugin, 17 of those files again: only #3897's red.

Broken by hand, each red:
- SharedBalance never set (the old code): "after they moved together".
- Shared on equal amount alone: "first reading" ("other" merged).
- Every query taken as account-wide: quota'd and new-api token keys
  merged.
- No sharesAskedCard: the shared card's refresh didn't read sk-plus.
- keyCards without sharedBalances: usage-shared-balance red in all four
  (chromium/webkit x en/zh).

Not tried: a real sub2api or new-api account (fake server with sub2api's
literal replies). A key's balance is shown once only after the account's
next change is seen by every key, not on the first read. Multi-currency
balances (DeepSeek "$ · ¥") and balances with parts are never shared.
2026-10-28 10:52:46 +08:00
yetone 8bade6c5e2 provider: a plugin's usage window can be a prepaid wallet's balance (#3950)
SuperMagic's accounts (mycf_711's magicrew plugin) are prepaid wallets of
points with no total. A plugin can now send a usage window as
{name, balance: 6291, unit: "积分"} with no used or limit.

- host.js passes a finite balance on (at least 0), anything else as null.
  plugin.UsageWindow.Balance and provider.QuotaWindow.Balance are *float64.
- quotaOfPlugin keeps the figure and does not make the window Text or
  Aside, so routing knows the account with no Used invented. allowanceOf
  copies it into Limit.Balance; an empty wallet counts as used up.
  Allowance.Left(model) is the least balance of the windows that count
  the model.
- weighRouted fills routes.Seat.Left and Seat.LeftIn (the account's
  provider and unit). Smart, pace and usage (least used) put the seat
  with more left first where they would otherwise tie (byLeft), only
  when every seat with a balance shares one LeftIn: balances in two
  units or two providers are never compared. Tiers still come first.
- The Usage card, the Routing page (Weighed.Balance: the small row's
  text, no bar, a why sentence, the account list), magpie accounts and
  the status line show the figure, "6,291 积分 left", never a share.
- Docs: provider-plugins (new section), gateway-routing,
  providers-accounts, plugin-runtime, host.js typings and the site's
  plugins page (en, zh, ja).

Run, at base f13aafa87, on mote:
- go test -tags nogui -timeout 45m ./...: 72 packages ok; red were
  TestQuotaSpanCarriesEveryWindowField (this change's: its fixture now
  sets Balance, green after), and on the unchanged base too
  TestWSLColdPlaceOpensNothing (#3924), TestFetchAsksASharedBaseOnce and
  two siblings (#3854), TestTUIFetchesSubscriptionModels (#3919), all
  fixed on main since and run again after the rebase; and
  TestPluginStreamsPastTheBudgetWait (#3946), green alone on both.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/..., go
  build ./..., gofmt -l: clean.
- New tests: TestPluginWalletBalanceIsAReading, TestAllowanceLeftIsTheLeastBalance,
  TestPluginHostPassesABalanceOn (through real Bun and host.js),
  TestWalletsGoByWhatTheyHaveLeft, TestWalletLeftWithinItsTier,
  TestWalletWithMoreLeftGoesFirst, TestQuotaCell's balance cases;
  usage-wallet-balance.test.cjs and routing-wallet-balance.test.cjs,
  34 of 34 in Chromium and WebKit, en zh zh-TW ja de, 1100/900/420/390px.
- GUI: every quota*, usage*, panel*, routing*, i18n* and tray* file (220
  files, 2928 tests), concurrency 4: 130 red, in 21 files. Those 21 files
  run again on an unchanged base copy and on this change, concurrency 2:
  the same 19 files red on both (126 and 131), the differing subtests
  being routing-rule-remove / rules-line / intent-entry flaps that go
  both ways. Each is filed (#3679, #2115, #3410, #3404, #3411, #3897,
  #1905, #3096, #3593, #3408, #3409, #3799, #3789, #3412, #3947, #3415,
  #3414, #1345); routing-story-shrinks had none and is #3954.

After rebasing on origin/main 833f51adc, on mote: Linux and Windows vet,
go build, gofmt clean; go test -tags nogui of internal/routes, provider,
gateway, cli, plugin, gui (the script budgets), agent and tui: all ok;
the two wallet GUI files and i18n-keys: 37 of 38, the red being
i18n-keys' "Runs as" (#3897, not this change).

Broken by hand, each red then restored: quotaReport's Balance copy
removed (TestQuotaSpanCarriesEveryWindowField red); byLeft always nil (routes and
gateway tests red); host.js's balance line removed (host test red);
quotaOfPlugin's balance copy removed (provider tests red); app.js and
client.js at base (both GUI files 34 of 34 red, "0% used" / "已用 0%").

Not tried: a real SuperMagic account or the magicrew plugin (it isn't
in the community repo; it needs to send balance), Windows and Linux
GUI apps, and the WebKitGTK app.
2026-10-28 08:28:56 +08:00
yetone 2e165fe9da usage: credits a day for every credit-based subscription, pool by pool (#3321)
The Usage page's credits a day (#568) counted WorkBuddy alone: its
allow-list named the provider, and it read one "Credits" window's display.
moxuanchen asked for it on every subscription that sells credits, and
tnt1223 asked again on Discord.

A window is now counted by what it is, not whose it is: a meter whose unit
or name says credits (credits, 积分, 積分, 点数) or money (usd/$, cny/¥,
eur/€), with a used and a total, read from the plugin's amount/limit, or
else from its display ("x / y", units, currency signs, thousands
separators, compact k/M/万, e-notation, a trailing "· note" cut). A share
alone, a text row, an unlimited, family or aside window (when the card has
another), a card with an error or an old reading is not counted; of
several same-unit windows over a span (OpenDesign's 5 hours and Week) the
longest is. Each window keeps its own ledger, keyed provider|user|window,
so Qoder's Credits and Add-on credits don't mix; the card carries daily
(the first) and moreDaily (the rest), each with its window and, for money,
its unit. WorkBuddy's ledger under the old provider|user key still shows,
and moves to its Credits window's key on the next reading. A total that
drops counts nothing that day, never a negative.

GUI: a card shows a row per pool, named after the window when it has
several; money says "Spent per day" in the unit's currency. Strings in
zh, zh-TW, ja and de.

Not changed: API-key plan cards (PlanQuotas) aren't passed through the
ledger; ZCode's buckets carry no unit, so only one named "Credits" counts.

Run:
- go test ./internal/gui ./internal/usageapi (-timeout 45m): ok.
  ./internal/provider dies in TestUnreadLoginsWriteErrorsKeepCredentials
  with "close of synctest channel from outside bubble" (#3632, red on
  origin/main, filememo.Forget); with that test skipped: ok. New TestCreditWindowShapes (22 plugin window
  shapes from the plugins repo's packages, plus Copilot's premium
  requests not counted), TestDailyCreditsEveryVendor (Trae CN with no
  display, Qoder's two pools, CodeArts' aside buckets, OpenDesign's
  spans, resets, errors, Command Code's dollars),
  TestDailyCreditsKeptBefore (an old WorkBuddy ledger shown before and
  after a reading, then moved).
- GUI credit-days.test.cjs, chromium and webkit: the WorkBuddy cases and
  a new one at 360px in en, zh, zh-TW, ja, de (Trae CN, Qoder's two
  pools named, Cursor's On-demand spent in $, no sideways scroll);
  i18n-keys, gui-zh-tw, gui-ja, gui-de, quota-pools, quota-credits,
  plan-credits, usage-accounts, panel-usage, quota-name-translated,
  credits-run-out: 57/57 ok.
- gofmt -l clean; go vet darwin, GOOS=linux/windows -tags nogui ok.
- Real use: magpie built from this tree in a sandbox HOME, the fake
  plugin (a copy of internal/plugin/testdata/fake) signed in with a key,
  two windows read from a file: Credits 100/1000 then 137.5/1000, and
  Add-on credits "5 / 50 credits" then "9 / 50 credits". The card
  showed "37.5 today" and "4 today", one row per pool, at 900px and
  360px; credits-daily.json held fakeco|api key|Credits and
  fakeco|api key|Add-on credits. Credits then dropped to 2/1000: the day
  stayed 37.5.

Broken by hand: with origin/main's credits_daily.go the three new Go
tests and TestDailyCredits fail (14 shapes "counted false", [null]
days, the old key not moved); with origin/main's app.js the new GUI
case fails in all five languages.

Not tried: a real account of any vendor other than the fake plugin;
Windows and Linux GUIs.

Reported by moxuanchen.
2026-10-27 11:27:43 +08:00
yetone 1dfa284840 usage: a plugin's row of text alone shows its text, not "· 100% left"
AutoClaw's 积分余额, Cline's balance, Cursor's Auto + Composer note and
the other plugin rows that are only words come to magpie as a window set
aside with a display and nothing counted (used 0, no amount, no limit).
Every surface read that used 0 as a share: the usage card said
"1,234 积分 · 100% left" (or "· 0% used") beside an empty meter, the
panel drew an empty ring, the TUI an empty bar, `magpie accounts` and
`magpie quota` "积分余额 0% (1,234 积分)", and the status line
"积分余额 0%".

provider: QuotaWindow.Text (json "text") marks such a row in
quotaOfPlugin: aside, a display, used/amount/limit all 0. Aside is
required: Cursor's On-demand "$0 / $20" isn't set aside and is a real
0%. QuotaSpan carries it to /api/quotas.
GUI (app.js): quotaText gives the display alone; the account row's
meter, the Usage page's track and the panel's rings leave the row out;
a panel card with only such rows shows their text on its line, as an
Unlimited card does. The tray's menu-bar text already skips aside rows.
TUI quotaCell, the CLI's quotaCell (accounts, quota) and statuslineCard
write the name and the text.

app.js stays under its budget (1,322,289, not raised; now 1,322,275):
to make room, the 8 copies of Math.max(0, Math.min(100, x)) are one
to100(x), and 8 one-line [..].filter(Boolean).join("\n") tooltips are
tipLines(..). Same results; the GUI files below cover those callers.

Readings cached before this release have no text flag and show as
before until the account is read again (a minute's cache, or Refresh).

Run, at this commit's tree (rebased on origin/main 9dc7d6eb8):
- internal/gui/tests/quota-text-row.test.cjs (new): a text row alone
  and beside a counted window, through accountQuota, panelQuotaCard,
  quotaWindows and quotaText; chromium and webkit, en and zh: 4 of 4.
- the GUI files the change reaches (quota*, usage*, panel*, tray*,
  profile*, plugin-plan, plugin-quota*, plugin-panels, api-key-usage,
  claude-usage, gateway-key-quotas, glm/opencode-go quota errors,
  routing-quota-left, gui-de/ja/zh-TW, i18n-keys; 114 files, both
  engines, 4 wide, load 130 to 200): 1433 of 1467. The reds, rerun
  alone here and with 9dc7d6eb8's own app.js: quota-count-wrap (webkit,
  #3404 #2228), usage-agents-hide (#3414 #2276), usage-checkin's Qoder
  tab (webkit, #2549), usage-fold (#3415 #2163) and usage-ledger's
  return-to-live (#3104) fail the same at both; api-key-usage failed
  once 4 wide and passes alone at both (#3589).
- go test -timeout 45m ./internal/gui/ ./internal/cli/ ./internal/tui/
  ./internal/provider/: ok (TestCoreScriptBudget included).
- gofmt -l internal/ clean; go vet on darwin, linux (nogui) and windows
  for provider, cli, tui (and gui on darwin): clean.
Broken by hand:
- app.js at HEAD under the new GUI test: red, quotaText gave
  "1,234 积分 · 0% used" / "1,234 积分 · 已用 0%".
- quotaOfPlugin's Text line removed: TestPluginTextRowIsText red.
- the CLI's quotaCell at HEAD: TestQuotaCell red ("积分余额 0% (1,234 积分)");
  statuslineCard at HEAD: red ("autoclaw-plugin 积分余额 0% 5h 40%").
- the TUI's quotaCell at HEAD: TestTextQuotaCell red
  ("积分余额 ░░░░░░░░ 1,234 积分 · 0% used").
Not tried: a real AutoClaw, Cline, Cursor, Factory or ZCode account in
the app (fixtures follow the plugins' own window shapes); the full
`go test ./...` and the whole GUI suite; the Linux and Windows apps.
2026-10-25 17:26:38 +08:00
yetone bf2e067ef6 gateway: a Codex account with credits is asked again at its allowance's edge, never benched (豆子, Zhenzhen)
Two Discord reports about ChatGPT accounts left to spend their credits
(the default):
- 豆子: an account whose allowance is used up but which still holds
  credits got a long rest. It should go ahead of accounts with neither.
- Zhenzhen: a Pro lite account ran out mid-session and the running
  session failed with "usage exhausted", while a new session worked.

The cause: when a window fills, ChatGPT can answer that turn 429
usage_limit_reached before it spends the credits, and serve the next
turn on them. magpie took the 429 as quota. On the routed path it
rested the account until the window renewed (candidate.full drove
those rests). On the relay (Codex's own sign-in) it passed the 429 to
Codex, which ended the session.

- /wham/usage's credits (has_credits with a balance over 0, or
  unlimited) are now read into QuotaWindow.Credits, Limit.Credits and
  Allowance.OnCredits.
- Routed path: a 429 quota refusal from such an account (and one let
  spend them, CodexCredits) is asked again at once, once per request,
  before a reset is looked at (creditsAgain, Try.Credits). If it is
  refused again, it rests fallbackCooldown (Rest.By "credits") and its
  usage is read again. full() is zero for it, so a full window rests it
  nowhere else (spendsCredits).
- Relay: the same ask-again, once (relayOnCredits).
- Order: Smart, Pace and Least used put a credits account first of the
  98%+ tier (Seat.Credits, spentBefore). That is after accounts with
  allowance left and ahead of those with nothing left.
- Routing page: says why such an account went first or where it waits,
  tells the asked-again try ("{n} used · on credits"), and the "credits"
  rest. Strings in zh, zh-TW, ja and de.
- Not a plugin path: Codex has no plugin.

Zhenzhen's suggestion to switch to credits early (~3% left) was weighed
and not done: the vendor spends credits only once the allowance is used
up, so switching early only wastes what is left. Retrying at the edge
keeps the running session alive. Codex identity, base_instructions and
prompts are untouched.

Tests, each red on the old code (the GUI test against the old
client.js, the Go ones with spendsCredits/relayOnCredits forced false
or the old strategies.go):
- TestCodexCreditsAskedAgainAtTheEdge: relayed, routed, set not to
  spend. Fake ChatGPT backend that refuses the edge turn and then
  serves on credits.
- TestCodexCreditsNoLongRest: refused again gets a rest of at most
  fallbackCooldown; a 500 gets backoff; no credits keeps the long rest.
- TestCodexCreditsFirstOfTheSpent (gateway) and TestCreditsFirstOfTheSpent
  (routes, Smart/Pace/LeastUsed).
- TestCodexCreditsBalance gains the onCredits column.
- routing-codex-credits-again.test.cjs: en/zh/ja/de, Chromium and
  WebKit, 8/8.

Run at this head (rebased on origin/main e96d577f2):
- gofmt -l clean.
- go vet ./... on darwin, linux (-tags nogui) and windows.
- go test -tags nogui -timeout 45m ./...: 69 packages ok, exit 0.
- GUI: routing-*.test.cjs, panel-routing-*, codex-credits, plan-credits
  and i18n-keys (103 files, both engines), before the rebase. 1251 of
  1253 passed at load ~50-70. The two reds each pass alone (3 of 3):
  routing-effort-change, filed as #3376, and routing-model-rest, #2115.

Not tried:
- The real ChatGPT backend. The 429 at the edge is inferred from
  Zhenzhen's report; no account was run out live.
- The live x-codex-credits-* response headers are not read.
- A workspace plan still within its overage is not treated as on
  credits.
- Affinity between two credits accounts is unchanged.
2026-10-23 20:11:17 +08:00
yetoneandggbdpq 3b8bcc3654 provider: a ChatGPT token the backend calls expired before its exp is refreshed once and read again (willz on Discord, #2973)
willz on Discord (macOS, v0.1.1330): two saved Team Codex accounts showed
only "Unauthorized". /backend-api/wham/usage answered 401 "authentication
token has expired. Please try refreshing it." while each access token's
JWT exp was still ahead, so codexToken and savedLoginToken handed the
same token back on every read, and on every request, until the account
was signed in again. #2973 is the same 401 on the request path.

What changed
- SignInExpired (codex_expired.go) tells such a 401 by its words:
  token_expired, "authentication token is/has expired", "Please try
  refreshing it". It never matches refresh_token_expired, which is a
  revoked sign-in. accountJSON now keeps the first 4KB of a refusal's
  body on accountStatusError for it.
- Refreshes are keyed on the token that was turned away:
  codexTokenRenewing(dir, stale) for Codex's own sign-in and
  renewSavedLoginFrom(user, stale) for a saved one. Under the lock that
  signing waits on, each reads its store afresh. If the store holds
  another token by then (renewed by Codex or by another reply), that
  token is used and no refresh is spent, so two replies for one token
  spend one rotation. Otherwise they refresh. Codex's own sign-in is
  written back through codexStore.write (temp and rename, every other
  field kept). A saved one goes through writeLogins and only its own
  row is changed; nothing is matched by name.
- The usage read (codexWindowsRenewing) refreshes once on such a 401 and
  reads once more, never again. It is used by loginQuota (saved and
  current accounts), codexSubscriptionUsage, and the reset spenders
  through codexUserWindows (autoreset, expiring, stillExpiring), which
  read the same windows with the same tokens.
  - A refresh that is refused shows its own words on the card: a saved
    account is marked lapsed, "add the account again to use it"
    (savedRefreshFailed); Codex's own says "run codex login".
  - A token that was refreshed and is still called expired says "sign in
    to this account again" (errCodexStillExpired).
  - A refresh that got no answer is shown as that, not as signed out.
- Request path: noteSignIn renews the account a request went with
  (NoteExpiredSignIn, at most 20s, through Account.renew, which is set
  on Codex's own account and each saved one). Nothing is marked. The
  request fails over as a 401 did before, and the next one goes with
  the new token.
- Docs: providers-accounts.md ("A token called expired") and
  gateway-routing.md.

The request-path hook and its gateway tests (codex_refresh_401_test.go,
taken as written) are ggbdpq's patch on #2973. Here they rest on the
stale-keyed refresh. The patch's forced refresh skipped the fresh
keychain read, so it could spend a refresh token Codex had already
rotated.

Tests
- TestCodexUsageRenewsTokenCalledExpired: a saved and a current account,
  both with an hour left, get 401 token_expired. Each is refreshed once,
  read once more, and kept where it lives (auth.json in the sandbox
  HOME, logins.json). A second read refreshes nothing.
- TestCodexUsageExpiredOnce: a refused refresh says to sign in again; a
  token still called expired is read no third time.
- TestCodexUsageOther401NotRenewed, TestSignInExpiredWords,
  TestNoteExpiredSignIn (two replies for one token make one refresh).
- ggbdpq's TestCodexExpired401RefreshesLogin and
  TestCodexOther401DoesntRefresh.

Run at 482d6707a (this change) (rebased on 8ef9fc578):
- gofmt -l internal clean; go vet ./... (darwin), GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./... clean
- set -o pipefail; go test -tags nogui -timeout 45m -count=1 ./... in a
  sandbox HOME, log teed: every package ok (69 ok, no FAIL), provider
  221.1s, gateway 574.4s, agent 434.4s. No other full suite was running
  (another session's gateway-only run was).
Broken by hand: with codexWindowsRenewing's retry and NoteExpiredSignIn
turned off (the old behaviour), TestCodexUsageRenewsTokenCalledExpired,
TestCodexUsageExpiredOnce, TestNoteExpiredSignIn and
TestCodexExpired401RefreshesLogin are red. The card read "Unauthorized",
the reporter's words, and the gateway test's sign-in was "renewed 0
times, want once". The new tests passed under -race.
Not tried:
- the real ChatGPT backend or a real Team account; the live ~/.codex and
  logins.json are off limits to this session;
- a keychain-stored Codex sign-in (the fresh keychain read is the
  existing codexToken path, run here only through file stores);
- Windows and Linux beyond go vet.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-23 18:15:15 +08:00
yetone c483feadfd usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X)
ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示".

Cause, two parts:
- An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source,
  so KeyBalances skipped it without a word and the Usage page drew no card.
  OpenCode has no balance a key can read. In sst/opencode,
  packages/console/app/src/lib/inference-proxy.ts serves only the model
  routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and
  /zen/v1/billing all 404, and billing.mdx shows the credits only in the
  console (Overview -> Credits, to owners and admins). No endpoint was
  invented.
- planQuotaSourceOf matched only /zen/go. models.dev now gives Go as
  opencode.ai/inference/go/openai/v1, so a Go provider saved there got no
  plan card at all. openCodeGateway() now tells go/zen/other (custom is
  the user's own) for both URL shapes, and Go at either one reads
  https://opencode.ai/zen/go/v1/usage.

What changed:
- A Zen key's card now carries errOpenCodeNoBalance and seeAt
  (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key
  its balance — see Zen's credits in the OpenCode console, Overview →
  Credits", with an "Open the console ↗" button. That is one button with
  the needsAccessKey "Open settings" one (#1821), so the bytes stay small.
- A provider with its own BalanceURL is still asked that URL.
- Strings are in zh, zh-TW, ja and de.
- coreScriptBudget: rebased onto f76201a84, whose 1,469,000 already
  holds the card (~390 bytes; the tray panel draws it too); unchanged.
  TestCoreScriptBudget re-run after the rebase: ok.
- Plugins: there is no OpenCode built-in mover, and this is a
  key provider, so the change is all in magpie.

Run, all on this tree (HEAD 94919109c):
- Old code: TestOpenCodeZenSaysItTellsNoBalance (adapted), TestPlanQuotaSource,
  TestPlanQuotas and opencode-zen-balance.test.cjs all fail on a detached
  HEAD checkout; they pass here.
- Real use, in a sandbox (go build -tags dev, sandbox HOME, ports
  3486/3487, never the live config), with the owner's OpenCode key copied
  read-only:
  - /api/usage/quotas gives the Zen variant the new error and seeAt.
  - Both Go providers (/zen/go and /inference/go) request the usage URL and
    show the vendor's real 401 "This API key has expired". The owner's key
    is expired, so no live Go reading was seen. There's no Zen account with
    credit either, so the console page itself wasn't checked against a
    balance.
  - A Playwright screenshot shows the card. Clicking the button posted
    /api/open with the console URL.
- go test -p 4 ./... -timeout 45m: every package ok except these.
  - internal/agent timed out at 45m under load; alone it is ok in 1184s
    (#2723, #2544).
  - gateway TestClaudeAccountsSpentFallBackToCodex and
    TestMaxRPMWaitsForRoomInTheMinute pass alone -count=3 (#2858/#2859,
    #1791).
  - gui TestCoreScriptBudget was mine; fixed above.
- gofmt -l clean. go vet: darwin all; GOOS=windows provider and gui;
  GOOS=linux provider (gui needs cgo/wails for linux).
- GUI, chromium + webkit, en/zh/zh-TW/ja/de at 900 and 420px, 2 workers.
  The full suite was stopped at ~416 tests (load 160-500). Its reds were
  in agent-*/account-* files, which this doesn't touch (#1544, #1949).
  - The targeted set passed: quota-*, balance-*, key-balance-card,
    opencode-*, usage-access-key-card, gui-de/ja/zh-tw, i18n-keys,
    panel-usage, panel-balance-order, panel-quota-refresh, tray-usages,
    usage-quota-head, glm/plugin-quota-error, gateway-key-quotas,
    usage-remote-cards, usage-card-refresh and deprecated-subscriptions.
  - Exceptions: gateway-key-quotas (ja launch timeout) and panel-usage
    (zh) were red under load and pass alone.
  - quota-name-translated and quota-count-wrap (webkit) are red alone
    here and on origin/main f76201a84, with the same asserts. That is
    #2228, commented.
2026-10-19 13:42:21 +08:00
yetone be62bcf79e provider: Command Code's built-in is retired; its plugin serves it
commandcode-plan joins retiredBuiltins (migrate.go): PluginServes is true
for it moved or not, and @magpie-community/opencode-commandcode-auth does
its sign-in, models, requests and usage.

Removed
- Sign-in: the StartSignIn case (startCommandCodeSignIn, the Studio
  callback, cmdOrigins, cmdWhoamiWait, commandCodeCallback/Keep) and the
  pasted-key branch (commandCodeKey, cmdSignedIn).
- Accounts: commandCodeAccount, cmdProvider, cmdSide, cmdLoginList,
  switch/on/forget (switchCommandCodeLogin, setCommandCodeLoginOn,
  forgetCommandCodeLogin, commandCodeAlsoOn), the Logins case, and the
  per-login usage (cmdLoginQuota, cmdQuota, the perLogin fetch). The
  Logins("") list keeps {CommandCodePlanID, nil} so its order holds.
- The Go plan's path: CommandCodeGenerate, cmdGoModels/cmdGoFetch/
  cmdGoRefused, cmdModels, cmdFree/cmdMarkFree, cmdPlansSeen's built-in
  users (cmdRemember, cmdPlanKnown, cmdPlanNow), CommandCodeOutputOf, and
  the account's generate field.
- asksOwnBackend's Command Code case.
- Gateway: the cmdGenerate/serveCommandCode dispatch and countOn's
  cmdGoing clause; internal/gateway/commandcode.go (the /alpha/generate
  translator) deleted.
- Built-in-only tests: gateway commandcode_test.go and
  commandcode_place_test.go, TestBillingLineLeftOutOnCommandCode;
  provider commandcode_go_test.go, commandcode_go_models_test.go,
  commandcode_free_test.go, TestCommandCodePlan,
  TestCommandCodeSignInWhoamiDown, TestCommandCodeSignInAgainToRemovedOwn,
  TestCommandCodeSignInPastedKey.
- Docs: Command Code out of gateway-routing.md's bridge lists (the
  2xx check, structured output, tool images, the billing line).

Kept, and why
- The mover and what it reads: cmdAuth, cmdOwn, cmdWho, cmdLogin,
  cmdSaved, cmdLogins (migrate_side.go, plugin_accounts.go).
- cmdAPI/cmdStudio (plugin_usage.go's moved card), cmdKeysURL
  (pluginsignin_paste.go), the plan and credit readers (cmdPlans,
  cmdPlanOf, cmdPlanName, cmdWindows, cmdLeft, cmdQuotaOf, cmdTime,
  cmdSubscription, cmdKeyWindows, cmdKeyPlanID): the keyed preset
  "commandcode", planquota.go, balance.go and qoder_usage.go use them.
- CommandCodeMaxOutput (models.go caps the plugin's "commandcode-plan"
  models with it), estimatedMoved, chat.go's plugin host cases, the
  gateway parity tests, and the PLUGIN-SERVED notice in
  commandcode_plan.go, now in the retired wording.

Tests whose meaning changed
- TestLoopbackSignInsTakePastedAddress no longer starts Command Code's
  built-in sign-in; the plugin's (TestLoopbackPorts) says its key is
  posted, never pasted as an address.
- The Go plan's free-model marks (TestCommandCodeFreeModels) were the
  built-in's alone; the keyed preset never marked them.

Run (worktree magpie-wt-rt-a, on top of 9a64c4025)
- gofmt -l internal: clean
- go vet -tags nogui ./... (darwin, GOOS=linux, GOOS=windows): clean
- staticcheck U1000 on ./internal/...: no declaration unused that wasn't
  unused at HEAD
- go test -tags nogui -count=1 ./internal/provider/ -run
  'CommandCode|commandcode|Migrat|Move|Moved|Retir|SignIn|AsksOwnBackend|
  SideLogin|Logins|Unmoved|Paste|Loopback|Account|PlanQuota|Balance|
  FetchNew|FetchingNew|LeftAlone|Identit|Order': ok (100s)
- same, -run 'Usage|Card|Quota|Discovery|Exposed|Models|Output': ok
- ./internal/gateway/ -run 'CommandCode|commandcode|Plugin|Parity|Moved|
  BillingLine|Search|ShapeFallback|GroupFails|CountTokens|Count|Format|
  ToolImage|Cursor|Connect': ok (117s)
- ./internal/cli/ ./internal/gui/ -run 'CommandCode|commandcode|Plugin|
  Retired|Moved|SignIn|Login': ok
- Not run: whole packages, the full suite, the GUI node suite (the
  machine is loaded; the parent runs those).
2026-10-17 23:11:01 +08:00
yetone 07a445f42b provider: Devin's built-in is retired; its plugin serves it
"devin" joins retiredBuiltins, as Zed (c0605abc2) and Grok (60ecd598c)
did. @magpie-community/opencode-devin-auth serves it, moved or not.

Removed:
- Sign-in: the PKCE localhost listen and callback branch in signin.go,
  devinExchange/devinExchangeURL. The exchange is Codex's alone again.
- Accounts: devinAccount and devinProvider in the account list, and the
  Logins, switch, on and forget cases (devinSide, devinLoginList,
  switchDevinLogin, setDevinLoginOn, forgetDevinLogin, removeDevinHome,
  addDevinLogin, devinAlsoOn). "devin" keeps its place in Logins("") with
  a nil list.
- Usage: devin_usage.go whole (perLogin fetch, usageLogins, loginQuota).
  devinUsageVersion moved to devin_images.go, which still uses it.
- asksOwnBackend's "devin".
- Gateway: attempt()'s serveDevin dispatch and the Devin translator
  (serveDevin, askDevin, buildDevin, decodeDevin, the Gemini schema and
  tool-description rewriting, the call-id helpers). gateway/devin.go is
  now connect_pb.go and keeps only the protobuf and Connect framing that
  cursor.go uses.
- Tests of the built-in alone: gateway devin_test, devin_gemini_schema,
  devin_sampling and devin_tool_ids; provider devin_usage_test,
  devin_cli_signed_out_test, TestDevinSignIn, TestDevinSeveralAccounts,
  TestSignInInstallsMissingCLI, TestDevinSignInUnseen, the Devin case of
  the required-tools test, and TestDevinSplitParallelCallsKeepTheirResults.

Kept, because the plugin, the devin agent or the move uses them:
- The mover, devinLogins, devinIdentity/devinStatus, DevinAuthAt,
  devinCredentialsAt, newDevinHome, devinCommand/devinProxy.
- DevinFamilies, DevinVariant and models.go's p.ID == "devin" shaping
  (the plugin's provider id is "devin" too). internal/agent/devin.go
  reads the families.
- The installer's "devin" case: the plugin's sign-in installs the CLI.
- The PLUGIN-SERVED notices in devin.go, devin_accounts.go and
  devin_images.go, reworded as retired.

Also fixed:
- cliIdentities no longer lists devinStatus. No look at the accounts
  asks it now, so it stayed unsettled, and FetchNewBehind told every page
  that lists were on their way (TestFetchingNewOnceStarted went red).
- 60ecd598c (Grok) left TestFetchingNewForgottenWhileListed red: its
  hook was GrokExecutable in the account listing. It and
  TestFetchNewListsAgainForAnAnswerWhileListing now hook kiroCLIDB,
  which is read after Cursor's account. Retiring Kiro will need another
  hook.

Tests whose meaning changed:
- TestSignInInstallFails and TestSignInCanceledWhileInstalling go
  through StartPluginSignIn("devin"), the plugin's install of the CLI.
- TestDevinCLIGoesThroughItsProxy seeds both accounts in logins.json
  instead of signing one in. The sign-in's proxy is covered by
  TestPluginSignInGoesThroughItsProxy.
- TestLeftAloneRunsNoCLI no longer expects `devin auth status` when the
  subscription is switched on.
- TestFetchingNewOnceStarted's unanswered CLI is Cursor's.
- devinRawID moved to anthropic_call_ids_test.go. A Devin call id is
  checked as safeCallID("dv_", ...).

Run:
- gofmt -l internal: clean.
- go vet -tags nogui ./... on darwin, GOOS=linux and GOOS=windows: clean.
- staticcheck U1000 on provider and gateway: no Devin leftovers.
- go test -tags nogui -count=1 -run '^(every test in provider, cli and
  gateway that names Devin|TestFetchNew.*|TestFetchingNew.*|
  TestLeftAlone.*|.*Identit.*)$' ./internal/provider ./internal/cli
  ./internal/gateway: ok.
- -run 'Migrat|Move|Moved|Retir|SignIn|AsksOwnBackend|SideLogin|Logins|
  Unmoved|Install|Proxy|Account' ./internal/provider: ok.
- -run 'Devin|Required|Split|CallID|Cursor|Connect|Parity|ToolImage|
  Format|BillingLine' ./internal/gateway: ok.
- -run 'Devin|Plugin|Retired|Moved' ./internal/gui ./internal/agent: ok.
- Not run: the whole packages, the full suite, the GUI node suite (the
  machine is loaded).
2026-10-17 23:11:01 +08:00
yetone 2927a161ef provider: Grok's built-in is retired; its plugin serves it
Grok ("grok") joins Zed in retiredBuiltins. It is served by
@magpie-community/opencode-grok-auth, moved or not.

Removed, the built-in's own paths:
- the sign-in (startGrokSignIn) and the per-account homes it made;
- the Logins/switch/on/forget cases and the alsoOn branch;
- grokAccount and the account list entry;
- the usage fetch (grokSubscriptionUsage, grokLoginUsage, the windows);
- the model list (grokModels, grokContextModels, the window labels);
- the token refresh, the headers, the version probe, and routing's usage
  clearing.
grok_usage_test.go is deleted, along with the six built-in-only tests in
grok_test.go and the four in grok_accounts_test.go.

Kept, because something still uses them:
- grokLogins and readGrokCredential, for the mover (migrate_side.go);
- grokBody, for the plugin's request bodies;
- GrokHome, the CLI install (pluginRunsCLI) and GrokBase;
- the gateway's grok draw, video, search and namespace code. It asks
  PluginProvider()=="grok" too.
Each remaining grok file has a PLUGIN-SERVED notice.

Fixes the retirement needed:
- movedAgent asks Moved again, not PluginServes. A retired Grok that is
  not moved yet still records the CLI's own sign-in, so the move takes it.
  TestMoveGrok fails without this: only the second account moved.
- In Logins(""), a retired built-in keeps its place, with no list. Grok's
  and Zed's accounts list where the built-ins' stood. Without this,
  TestAllLoginsMovedKeepTheirPlace fails ("[zed grok]").

Tests whose meaning changed:
- The gateway's grokSignedIn now serves Grok through the fake plugin
  moved onto "grok". It proxies to provider.GrokBase, read per request
  and refused unless loopback, so no test reaches the network. It names
  127.0.0.1 in fetchPrivate, because the vendor's own host is now the
  fake's.
- TestVideoContentAtPrivateAddressNotFetched clears that setting. Without
  the clear it fails with "200 secret-bytes".
- TestGrokAccountDraws checks the plugin's Authorization only. The real
  plugin's headers are the plugin repo's to test.
- The Grok cases in TestVideosRedacted and TestMediaRedactedErrors reach
  their echo through GrokBase (grokEcho).
- TestVideoModelByItsBareName's chat model is the fake's fake-1.
- TestGrokPluginSearchesItself expects "grok", not grok-plugin.
- TestGrokHideOwnSignIn is removed: hiding the CLI's own sign-in was the
  built-in's ForgetLogin.
- grok_accounts_test.go keeps test-only newGrokHome and addGrokLogin
  fixtures for the mover's tests.

Run in the worktree:
- gofmt -l internal: empty.
- go vet -tags nogui ./... on darwin, GOOS=linux and GOOS=windows: clean.
- go test -tags nogui -count=1 -run
  'Private|Grok|grok|CallerUsageVideos|GatewayKeyModelsHoldTheImageAndVideoLists|RemoteMagpie|Video|Redact'
  ./internal/gateway: ok.
- go test -tags nogui -count=1 -run
  'Grok|grok|Migrat|Move|Moved|Retired|Retir|SignIn|AsksOwnBackend|SideLogin|Hide|OwnRow|Logins|Unmoved'
  ./internal/provider ./internal/cli: ok, ok.
- go test -tags nogui -count=1 -run 'Grok|grok|Plugin|Retired|Moved'
  ./internal/gui: ok.

Not run: the full suite, the GUI node suite, and a real Grok account.
The machine is under heavy load.
2026-10-17 23:11:01 +08:00
yetone 6da19bf181 provider: Factory's built-in is retired; its plugin serves it
"factory" joins retiredBuiltins: every Factory account is served by
@magpie-community/opencode-factory-auth, and the hourly MoveRetiring
moves the ones still on the built-in.

Removed: the built-in's sign-in (factory_signin.go, WorkOS's device
flow), keeping the sign-in (renew, lapse, org reconcile and mend,
headers, factoryGet), its provider and account (factoryProvider,
factoryAccount, factoryAlsoOn), its login list, switch, on/off and
forget, its usage card (factoryLoginQuota), droid's prompt and body
rewriting (factory_client.go), and its rows in signin.go, logins.go,
logins_on.go, login_usage.go, subscription_usage.go and account.go.
zcodeDecode/Encode, kept in zcode.go only for factory_client.go, go
with it. An API key always goes to the plugin now (factoryAddKey), and
`magpie accounts import factory` keeps saying to add it with accounts
add factory; its dead import branches are gone.

Kept: the mover and what it reads (factoryLogins, factorySaved,
factoryCreds, factoryMu); ImportFactoryKeys, factory_key.go and
factoryWhoami, for "Use an API key instead"; droid's model table with
factoryAPIs and factoryCore, since the plugin's provider is named
"factory" (account.go APIs, FactoryGemini and servedByFactory still
answer for it); factoryAPI for the moved provider's host
(builtinHost); factory_usage.go's limits reader behind
FactoryAllowanceForTest, which the gateway's pool tests use; the
gateway's "factory" lists (estimatedMoved, the account check), as the
Zed commit kept zed's; the parity tests.

Tests:
- git rm'd, built-in only: factory_test.go (sign-in, refresh, accounts,
  orgs), factory_client_test.go, gateway factory_agents_test.go
  (droid's line on every wire, the generate route to chat) and
  factory_think_off_test.go (TestPluginThinkingOff covers the plugin);
  TestFactoryAPIKey, TestFactoryKeyAgainReadsUsageAfresh,
  TestFactoryServesModelsAddedSinceItsFetch, TestUserAgentAccountUntouched
  (TestUserAgentFor still covers an account's User-Agent).
- Changed meaning: TestGeminiEmptyReplyIsAnError,
  TestGeminiEmptyRepliesAskedAgain and TestGeminiImageModelReturnsItsImage
  used Factory's generate route as a fake-able Gemini upstream; they now
  use a Gemini API of the user's own (saveGem), the same decoder, and the
  image test checks :streamGenerateContent instead of /api/llm/g/v1/generate.
  TestMovedShowsBuiltinHost's first check is now a plain plugin
  (fakeco), and a retired Factory with no migration record shows
  api.factory.ai. TestFactoryAPIKeyMoved checks factoryLogins() is empty
  instead of the removed factoryLookup. factorySite/factoryJSON moved
  into factory_key_test.go.

Run in this worktree:
  gofmt -l internal: nothing
  go vet -tags nogui ./internal/provider ./internal/gateway ./internal/cli
    ./internal/gui, GOOS=darwin, linux, windows: clean
  staticcheck -checks U1000 -tests=false (darwin, windows) on
    internal/provider: nothing new
  go test -tags nogui -count=1 -run 'Factory|Gemini|PaymentRequired|
    ResetsInWords|UserAgent|UsedWindow|Vertex|PayloadTooLarge|UsageCache|
    AnthropicImage|ThinkingOff|Moved|Retired|Mover|Migrat|Move|
    SayTheirPlugin|Allowance|Discovery|ClaudeModels|GrokPrice|
    LoopbackSignIns|AsksOwnBackend|SideLogin|Import|Accounts|ZCode|MiMo'
    on the four packages: ok (all four); TestFactoryAPIKeyMoved ran with
    Bun (PASS), not skipped.
Not run: whole packages, the full suite, the GUI suite (machine load
~300). Not tried with a real Factory account. docs/subsystems not
changed, as for Zed.
2026-10-17 23:11:00 +08:00
yetone 09b9ae8c02 provider: ZCode's built-in is retired; its plugin serves it
"zcode" joins retiredBuiltins, as zed and mimo-app did: every ZCode
account is served by @magpie-community/opencode-zcode-auth, and the
hourly MoveRetiring moves the ones still on the built-in.

Removed: the built-in's sign-in (startZCodeSignIn, the team sign-in and
its route/key caches), Start Plan (zcode_start.go and its blocked hint,
which account.go Explain and test.go EdgeBlocked named), its client and
prompt (zcode_client.go, zcode_prompt.json), the models list
(zcode_models.go), the OS place readers (zcode_os_*.go), and its rows in
signin.go, logins.go (list, switch, forget), logins_on.go,
login_usage.go, subscription_usage.go and account.go. Tests that covered
only that code are git rm'd (zcode_accounts, _blocked, _client,
_device, _place, _quota, _start, _startmodels) with TestZCodeAccounts,
TestZCodeTeamSignIn, TestZCodeTeamNoSeat and TestZCodeFetchModels.

Kept: the mover (migrate_zcode.go) and what it reads (zcodeLogins,
zcodeSaved, the credential store readers, zcode_device.go's
zcodeDeviceMid); zcodeOwn, the plugin's own account; the Zhipu plan and
team-seat readers planquota.go uses (zcode_team.go, zcodeCall/Get);
zcodeDecode/Encode, moved into zcode.go because factory_client.go uses
them; the gateway's zcode countOn condition and zcode_blocked_test.go
(which builds its Provider directly), as the Zed commit kept zed's; the
StartSignInAt site parameter (generic); plugin_accounts and
account_seats cases; the parity tests.

Tests whose meaning changed: TestZCodePlanKeyFromConfig and
TestZCodeOwnTeam keep only their zcodeOwn checks (the quota, Start Plan
server, provider/Sign/LoginUsage parts were the built-in's).
TestZhipuKeyTeamWindows builds the team key directly instead of signing
in through the removed team sign-in. zcodeTestJWT moved to zcode_test.go
for migrate_movers_c_test.go.

Run in this worktree:
  gofmt -l internal: nothing
  go vet -tags nogui ./internal/provider ./internal/gateway ./internal/cli
    ./internal/gui, GOOS=darwin, linux, windows: clean
  staticcheck -checks U1000 -tests=false (darwin, windows) on
    internal/provider: nothing new (only the pre-existing unused ones)
  go test -tags nogui -count=1 -run 'ZCode|Zcode|Zhipu|Migrat|Move|Moved|
    Retired|LoopbackSignIns|AsksOwnBackend|Mover|SayTheirPlugin|SideLogin|
    PlanKey' ./internal/provider ./internal/gateway ./internal/cli
    ./internal/gui: ok (all four)
Not run: whole packages, the full suite, the GUI suite (machine load
~300). Not tried with a real ZCode account.
2026-10-17 23:11:00 +08:00
yetone 30fcbf684b provider: Xiaomi MiMo's built-in is retired; its plugin serves it
mimo-app joins retiredBuiltins (migrate.go), the way Zed did in
c0605abc2. @magpie-community/opencode-mimo-auth serves sign-in, refresh,
models, requests and usage.

Removed: the built-in's sign-in (mimo_signin.go), its usage fetch
(mimo_usage.go), its tests (mimo_test.go, built-in only), and its
cases in signin.go begin(), logins_on.go (SetLoginOn and alsoOn),
logins.go (Logins, the side list, switch, forget), login_usage.go
(builtinLogins, quota), subscription_usage.go and account.go. MiMo had
no gateway dispatch of its own.

Kept: mimo.go holds the PLUGIN-SERVED notice ("mimo-app" and the
package name, for TestMovedBuiltinsSayTheirPlugin), MiMoID, mimoCreds,
mimoSaved and mimoLogins, which migrate_mimo.go's mover and
migrate_movers_test.go still read. The GUI's MiMo account label stays
for plugin accounts.

Run in this worktree:
  gofmt -l internal                                  (nothing)
  go vet -tags nogui ./internal/provider ./internal/gateway
    ./internal/cli ./internal/gui                    ok; also GOOS=linux,
                                                     GOOS=windows: ok
  go test -tags nogui -count=1 -run 'MiMo|Mimo|Migrat|Move|Moved|
    Retired|LoopbackSignIns|AsksOwnBackend|Mover|SayTheirPlugin'
    ./internal/provider ./internal/gateway ./internal/cli ./internal/gui
                                                     ok (all four)
Not run: whole packages, the full suite, the GUI node suite (machine
load ~300).
2026-10-17 23:11:00 +08:00
yetone b7ceb53fe4 provider: WorkBuddy's built-in is retired; its plugin serves it
workbuddy and workbuddy-ai join retiredBuiltins, as Zed did in c0605abc2
and Qoder in 43cc3171d. @magpie-community/opencode-workbuddy-auth serves
both, moved or not.

Removed (built-in only):
- provider: workbuddy_models.go (the model list); in workbuddy.go the
  sign-in, token renewal, usage/credits reading, request signing and the
  site's model fetch; the WorkBuddy cases in account.go (Accounts),
  logins_on.go, logins.go (list/switch/forget), login_usage.go,
  subscription_usage.go and signin.go; WorkBuddyBaseForTest, now unused.
- The built-in tests: workbuddy_test, workbuddy_signin_test,
  workbuddy_accounts_test, workbuddy_ai_test, workbuddy_body_test,
  workbuddy_enterprise_test, workbuddy_free_test, workbuddy_names_test,
  workbuddy_spare_free_test, workbuddy_refused_test (provider), and
  gateway/workbuddy_refused_test.

Kept, and why:
- migrate_workbuddy.go (the mover) with what it reads: wbSite, wbCreds,
  wbOwn/wbAuthPath (the desktop's file, sent as a marker), wbLogins,
  wbTokens (back drops a renewed pair).
- workbuddy_checkin.go: the daily check-in now walks the plugin's
  accounts only and sends through the plugin's fetch (a.via); wbCallVia,
  wbNum and the site's api() serve it, and plugin_usage's host.
- WBRestricted/WBRestrictedHint: the gateway reads the plugin's 11140 by
  them. textOnly: applied to the plugin's lists.
- draw_workbuddy and search_workbuddy in the gateway: they serve the
  plugin's provider. The PLUGIN-SERVED notice in workbuddy.go.
- The WorkBuddy agent target (internal/agent) is untouched.

Tests changed in meaning:
- TestFetchNewAccount, TestFetchNewRetriedSoon and
  TestFetchingNewOnceStarted used WorkBuddy as the built-in signed in;
  they use Codex now (codexSignedIn, codexListedAt), same assertions.
- TestFetchPlanWithoutList uses local models; TestWorkBuddyFetchModels,
  TestWorkBuddyAIGLMIsTextOnly and TestOwnStoreSignInAgainDropsTheReading
  (WorkBuddy case) are gone with the code.
- Check-in: TestWorkBuddyCheckinSignedIn is gone; the fixture's account
  is a plugin account signing through via; PluginUnderItsOwnID became
  TestWorkBuddyCheckinPluginAccounts (plugin accounts listed, a built-in
  login left out). TestCheckinAccountsListed reads a moved plugin.
- TestWorkBuddyMover seeds the desktop's logins.json row: retired, the
  built-in no longer writes it, and an existing user's row is what moves
  (red without the row).
- Gateway: the WorkBuddy draw and search tests run through the fake
  plugin (besideFake), without the built-in's header checks;
  TestWorkBuddySearchesForItsModels folded into
  TestWorkBuddyPluginSearches (refusal and search-off checks kept);
  TestLoopEndsWorkBuddysReply is the plugin route only;
  TestWorkBuddyRestrictedRestsHours lost its built-in translation case.

Run:
- gofmt -l internal: empty
- go vet -tags nogui ./...; GOOS=linux and GOOS=windows the same: clean
- go test -tags nogui -count=1 -timeout 45m -run 'WorkBuddy|workbuddy|Checkin|CheckIn|FetchNew|FetchingNew|FetchPlan|Migrat|migrat|Mover|Moved|Retired|Retire|SignIn|Plugin|Draw|Search|Loop|Redact|Restricted|Images|TextOnly|Qoder|BuiltinsSay|AsksOwn|Loopback' ./internal/provider ./internal/gateway ./internal/cli ./internal/gui ./internal/qoder
  first run: gateway, cli, gui ok; provider red on TestWorkBuddyMover
  (above); after the fix provider ok (99s).
- Not run: whole packages, the full suite, the GUI node suite.
2026-10-17 23:11:00 +08:00
yetone 761556a0cc provider: Qoder's built-in is retired; its plugin serves it
qoder and qoder-cn join retiredBuiltins, as Zed did in c0605abc2.
@magpie-community/opencode-qoder-auth serves both, moved or not.

Removed (built-in only):
- gateway: the Qoder dispatch in gateway.go and gateway/qoder.go (the
  translator), with its tests (qoder_test, qoder_busy_test, qoder_cn_test).
- provider: qoder_usage.go; the Accounts() loop, builtinLogins case and
  loginQuota branch, the Logins/side-list/switch/forget cases, SetLoginOn
  and alsoOn, the sign-in case, the subscription_usage fetch, and qoder
  in asksOwnBackend; qoderLogins(); the built-in tests (qoder_test,
  qoder_cn_test, qoder_free_test).
- internal/qoder: codec, cosy, models, oauth, usage, userinfo, ids, store
  and their tests.

Kept, and why:
- migrate_qoder.go (the mover) and the legacy qoder.json migration it
  reaches through qoderLoginsOf. It now reads a pair with qoderSaved.
- qoder_checkin.go: the check-in walks plugin accounts (heldPlugins).
- internal/qoder/endpoints.go: the provider keys, Site/SiteOf, the
  Credential the mover reads and NewMachineID, with the notice.
- The PLUGIN-SERVED notice in provider/qoder.go and internal/qoder.
- gateway's relayStatus/retryAfterOn, which commandcode.go uses, moved to
  relay_status.go; the tests' qoderRoundTrip is now roundTripFunc
  (roundtrip_test.go), no change in meaning.

Tests changed in meaning:
- TestOwnStoreSignInAgainDropsTheReading lost its qoder case.
- New TestQoderLegacyFileMoves: a legacy qoder.json moves through the
  mover and is removed. Red when migrateQoder is skipped (tried by hand).

Run (machine load ~300, so narrow by request):
- gofmt -l internal: empty
- go vet -tags nogui ./...; GOOS=linux and GOOS=windows the same: clean
- go test -tags nogui -count=1 -timeout 45m -run 'Qoder|qoder|Migrat|migrat|Mover|Moved|Retired|SignIn|AsksOwnBackend|Plugin|Afresh|Checkin' ./internal/provider ./internal/gateway ./internal/cli ./internal/gui ./internal/qoder
  provider ok 114s, gateway ok 201s, cli ok 18s, gui ok 12s, qoder no tests
Not run: the whole packages, the full suite, the GUI node suite.
2026-10-17 23:11:00 +08:00
yetone e405315d79 provider: Cursor's built-in is retired; its plugin serves it
"cursor" joins retiredBuiltins (migrate.go), so PluginServes("cursor")
holds moved or not, and the built-in's code goes, as Zed's did in
c0605abc2 and Kiro's in the commit before this.

Removed:
- gateway/cursor.go (the Connect/protobuf translator) and its tests
  (cursor_test, cursor_conversation_test, cursor_maxmode_test,
  cursor_precision_test, cursor_stepusage_test), and gateway.go's
  Account.Agent == "cursor" dispatch to serveCursor;
- provider/cursor_usage.go (the usage card, cursorToken, cursorKeychain)
  and provider/cursor_picker.go, with their tests;
- from cursor.go: the built-in account (cursorAccount), its model list
  through `cursor-agent models` (cursorModels, parseCursorModels,
  cursorModelL), its sign-in (startCursorSignIn, cursorLinkWhole,
  cursorLoginUUID), the API client version (CursorClientVersion,
  cursorVersionFallback, cursorVersionRe) and the token refresh
  (CursorToken, cursorRefresh, tokenExpiry);
- StartSignIn's "cursor" case (signin.go), the usage fetch
  (subscription_usage.go), the login-list case and quota (login_usage.go)
  and the account (account.go);
- "cursor" from Native (provider.go) and asksOwnBackend (modelprefs.go).

Kept, because the mover, the plugin paths or other code need them:
- cursor.go's PLUGIN-SERVED notice (TestMovedBuiltinsSayTheirPlugin);
  cursorIdentity, cursorStatus, parseCursorAbout, readCursorToken,
  cursorTokenOf, cursorKeychainToken and cursorAuthFile: migrate_side.go
  and plugin_accounts.go ask whose account the agent is through them;
- cursorLoginURL (grok.go and claude_signin.go use it), cursorContext and
  withCursorContexts (the plugin's model contexts), CursorExecutable and
  isCursorAgent (the Cursor agent itself);
- cursor_models.go whole: CursorBase (agent/legacy.go), CursorVariants
  (groupfast.go, the plugin's fast pick), cursorPicks and the collapse
  (provider.go, models.go);
- accountIDs, builtinOrder, models.go's "cursor" live branch and
  servedByCursor, as Zed's and Kiro's commits left theirs. The live
  collapse and cursorPicks now only ever meet a built-in list, which a
  retired Cursor never has; they are left for a cleanup of their own.
- gateway/cursor_local_models_test.go (the Cursor agent, not the
  built-in) and the gateway's plugin_*_test.go parity tests.

Tests changed in meaning:
- cursor_signin_test.go became cli_signin_test.go: its two generic
  runCLISignIn tests stay (grok's), TestCursorSignInJoinsAWrappedLink
  goes with cursorLinkWhole.
- cursor_test.go keeps parseCursorModels as a test helper (the old
  parser, for the collapse tests' fixtures); TestParseCursorModels,
  TestCursorClientVersion, TestTokenExpiry and TestCursorLegacyPicks go,
  and cursor_names_test.go's TestCursorAvailableNames: they tested the
  built-in account's list and picks. Cursor's plugin lists its own
  picker models with their efforts (index.mjs), so magpie's collapse
  never runs for it; moving the two tests onto the plugin showed that.
- TestFetchNewWaitsForASlowSignIn (#1789) and
  TestFetchNewListsAgainForAnAnswerWhileListing (#1147) are gone: both
  were about a CLI account whose models `cursor-agent models` lists,
  and no built-in left lists its models through its CLI.
- internal/gui/providers_fetching_unix_test.go
  (TestProvidersAnswerWhileListsComeIn, #541) is gone: its slow vendor
  was the built-in's `cursor-agent models`. The guarantee (the
  Providers page answers while an account's list comes in) has no test
  now; re-homing it onto an HTTP-listed account (Antigravity, Copilot)
  needs exported test hooks and is left as a follow-up.
- TestNative drops its Cursor case; TestLeftAloneRunsNoCLI fakes and
  expects claude and devin only; isolate() and
  TestAccountDiscoveryOffReadsNoSignIn no longer set cursorKeychain
  (cursorTokenOf reads the Keychain on macOS only, as before).
- Dropped as built-in only: the Cursor case of the required-tools test,
  TestCodexToolImageCursor, TestCursorSplitParallelCallsKeepTheirResults.

Run at this tree (load ~300, so narrow runs only):
- gofmt -l internal: clean
- go vet -tags nogui ./... ; GOOS=linux and GOOS=windows the same: ok
- staticcheck -tags nogui -checks U1000 ./internal/provider/: clean;
  with -tests=false over provider and gateway: nothing Cursor or Kiro
- go test -tags nogui -count=1 -run 'Cursor|Kiro|Migrat|Mov|Retired|
  SignIn|AsksOwnBackend|Plugin|HandOver|NoWayBack|Adopt|Hide|
  RequiredTools|ToolImage|Split|Discovery|Account|Isolat' over
  provider, gateway, cli, gui: gateway ok 446s, cli ok 67s, gui ok 51s;
  provider failed TestCursorAvailableNames, TestCursorLegacyPicks,
  TestFetchNewWaitsForASlowSignIn (above) and
  TestSetUpstreamNameRefusesAnAccountBackend (Kiro's, fixed in that
  commit)
- every other test naming "cursor" or cursor-agent, by name, over the
  same four packages: gateway and cli ok; TestNative,
  TestLeftAloneRunsNoCLI, TestFetchNewListsAgainForAnAnswerWhileListing
  and TestProvidersAnswerWhileListsComeIn failed (above)
- after the changes: gofmt clean, vet ok on all three; -run 'Cursor|
  Kiro|Migrat|Mov|Retired|SignIn|AsksOwnBackend|Plugin|HandOver|
  NoWayBack|Adopt|Hide|Discovery|Account|Native|LeftAlone|SetUpstream|
  FetchNew|Hold|DailyCredits|NotSignedIn|ModelTest|Providers': provider
  ok 141s, gui ok 21s, cli ok 22s (gateway untouched since its ok run)
Not run: the whole packages, the full suite, the GUI node suite.
2026-10-17 23:11:00 +08:00
yetone 615732af65 provider: Kiro's built-in is retired; its plugin serves it
"kiro" joins retiredBuiltins (migrate.go, now one entry a line), so
PluginServes("kiro") holds moved or not, and the built-in's code goes,
as Zed's did in c0605abc2.

Removed:
- gateway/kiro.go (the CodeWhisperer translator) and its tests, and
  gateway.go's Account.Agent == "kiro" dispatch to serveKiro;
- provider/kiro_signin.go and its test: StartSignIn's "kiro" case, the
  AWS Location redirect in the pasted-address handler, kiroFlow and its
  callback branches in signin.go;
- the built-in account (kiroAccount, kiroProvider, kiroAcct), its model
  list (kiroModels, kiroModelList, KiroModel), its usage card
  (kiroQuotaAt, kiroLimits.windows, kiroLoginQuota, the fetch in
  subscription_usage.go), and its login-list, switch, on/off, forget and
  also-on cases (logins.go, logins_on.go, login_usage.go, account.go);
- "kiro" from Native (provider.go) and asksOwnBackend (modelprefs.go).

Kept, because the mover, the plugin paths or other built-ins need them:
- kiro.go's sign-in readers (readKiroAt, readKiroCLI, readKiroIDE,
  kiroCred), KiroAuthOf with its refresh and profile lookup, and
  kiroUsageLimits: kiroOwnUser (plugin_accounts.go) and addKiroLogin
  (the legacy-file adoption kiroLogins runs) ask Kiro whose account it
  is through them;
- kiro_accounts.go's homes and kiroLogins, plus kiroSaved/readKiroFile
  (moved there from kiro_signin.go), which migrate_kiro.go reads and
  writes; side_logins.go and cards_kept.go's Kiro key are untouched;
- the Save branch that keeps a key on "kiro": the mover takes it;
- newUUID and joinNonEmpty moved from gateway/kiro.go to gateway/uuid.go
  (Devin and others use them), and the said() test helper to
  gateway/said_test.go;
- kiro_accounts.go's PLUGIN-SERVED notice (TestMovedBuiltinsSayTheirPlugin).

Tests changed in meaning:
- TestKiroMover: retired, the agent's own sign-in (kiro-cli's or the
  IDE's) is the plugin's to read (movedAgent, since cfa262509), so it no
  longer goes in the move; the test now says so, and the own marker's
  way back is checked with a literal marker.
- TestKiroBuilderIDListsItsModels became
  TestKiroBuilderIDTakesItsServiceProfile: the model list is gone, the
  Builder ID profile KiroAuthOf finds (for whose-account) is still
  checked; TestKiroBuilderIDFoundByKirosAnswer checks the profile, not
  the models.
- Dropped as built-in only: TestKiroModelList, TestKiroAccount,
  TestKiroLimits' windows half, TestSaveKeepsKirosKey's account check,
  TestKiroHideOwnSignIn, TestKiroHideOnlySignIn, TestCodexToolImageKiro,
  the Kiro case of the required-tools test, the kiro sign-in test file,
  and "kiro" from TestLoopbackSignInsTakePastedAddress.
- TestSetUpstreamNameRefusesAnAccountBackend set up a Kiro account as
  its account backend; Kiro is no longer one, so it now signs Claude in
  (still in asksOwnBackend) and gives "claude/*", checking the refusal
  is the own-account one. Found by a later wider run (the regexp above
  didn't reach it); go test -run '^TestSetUpstreamName' ok 6s.
- kiro_test.go's reader tests call readKiroAt(key, "") where they
  called readKiro(key) (same result with no magpie-signed accounts).

Run at this tree (load ~300, so narrow runs only):
- gofmt -l internal: clean (after formatting said_test.go)
- go vet -tags nogui ./... ; GOOS=linux and GOOS=windows the same: ok
- go test -tags nogui -count=1 -run 'Kiro|Migrat|Mov|Retired|SignIn|
  AsksOwnBackend|Plugin|HandOver|NoWayBack|Adopt|Hide|RequiredTools|
  ToolImage' ./internal/provider ./internal/gateway ./internal/cli
  ./internal/gui: gateway ok 266s, cli ok 24s, gui ok 25s; provider
  failed TestKiroMover (the own sign-in, above), fixed, then
  provider ok 145s (go vet ./internal/provider ok first)
Not run: the whole packages, the full suite, the GUI node suite.
2026-10-17 23:11:00 +08:00
yetone 21252f6a2c provider: Zed's built-in is retired; its plugin serves it
The first built-in taken out (the owner, 10-16: 陆续把内置Provider下线掉,
一定要下线完毕). @magpie-community/opencode-zed-auth serves Zed for
everyone now; built-in accounts not moved yet are moved by the hourly
loop, or from the Providers list's line (the commit before).

Removed: the built-in's sign-in (zed_signin.go and its loopback paste
branch), usage (zed_usage.go), its login list, switch, forget and
account cases, its own-backend case in asksOwnBackend, the gateway's
serveZed and zed.go, internal/zed, and the tests of only those.

Kept, because the mover and the plugin path use them: zed.go's
credential and login readers (migrate_zed.go's move), zed_body.go
(plugins.go), and Zed in accountIDs, side_logins, cards_kept,
plugin_usage's movedCards, the gateway's estimatedMoved and the CLI's
account names, which name the plugin's accounts too. Zed the editor as
an agent (internal/agent, the library's MCP target) is untouched.

Tests changed: TestMovedBuiltinQuiet is TestRetiredBuiltinQuiet (no Zed
card, its sign-in refused, the move still offered with the account);
TestZedMoveCarriesItsModels compares the models without internal/zed;
TestLoopbackSignInsTakePastedAddress and asksOwnBackend's set lose Zed.
AGENTS.md and gateway-routing.md no longer name Zed's built-in client.

Run on this tree over af08ecb27's parent tree:
- go test -tags nogui ./... -count=1 -timeout 90m: 64 packages ok,
  internal/gui red only in TestCoreScriptBudget (the Move line; the
  budget is raised in af08ecb27). Rebased onto it:
  go test -tags nogui ./internal/gui -count=1: ok.
- Earlier on wt6 before the three fixes: provider red in
  TestAsksOwnBackendAgreesWithTheGatewayDispatch and
  TestLoopbackSignInsTakePastedAddress (Zed still named), fixed here.
- gofmt -l internal: nothing; GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: clean.
- GUI: retired-move, plugin-move, deprecation-notice and
  deprecated-subscriptions, both engines, en and zh: 20 pass.
2026-10-17 23:10:59 +08:00
yetone 0f1666b387 provider: a built-in can be retired, its plugin serving it moved or not, and its unmoved accounts get a Move line
The owner (10-16) wants every deprecated built-in taken out of magpie,
one at a time. This is the ground for that; it retires nothing yet.

- retiredBuiltins / BuiltinRetired(id) in migrate.go name a built-in
  whose code is gone. Only an id with a mover can be retired.
- PluginServes(id) is Moved(id) or retired. Every gate that asked
  Moved(id) asks it now: sign-in, Factory keys, usage, logins, cards,
  forget, accounts, check-ins, plugin sign-in, the CLI's accounts and
  providers, the GUI's account label.
- A retired row's move.state is plugin, and its id is in onPlugins
  once the plugin is installed.
- /api/providers lists a retired subscription's built-in accounts that
  haven't moved in `unmoved` (MoveCandidate, now with the failed move's
  error and why). The GUI shows a quiet line over the Providers list
  for each, with Move / Try again (unmovedLine), in en, zh, zh-TW, ja
  and de.
- AGENTS.md and docs/subsystems/provider-plugins.md say what a retired
  built-in is.

Run at 270aa1c9c with this change:
- go test -tags nogui ./... -count=1 -timeout 90m: 66 packages ok.
- gofmt -l internal: nothing. GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: clean.
- GUI, both engines, en and zh: retired-move (new, 4/4), plugin-move,
  deprecation-notice, deprecated-subscriptions, plugin-move-unserved,
  plugin-movable-review, i18n-keys: 39 pass.
- TestRetiredBuiltinIsThePlugins -count=20 (it picks a mover at random).

The Move line is the Providers list's own, not a page that could be a
plugin. It took the core's scripts to 1,427,218 bytes, which the budget
main raised in 81313b912 (1,447,000, issue 2612) already holds;
TestCoreScriptBudget passes.

Broken by hand: retired-move goes red with unmovedLine not appended;
TestRetiredBuiltinIsThePlugins goes red with BuiltinRetired's Movable
check dropped.
2026-10-17 23:10:59 +08:00
yetone 1bc61b66d7 provider: DeepSeek's balance says its granted and topped-up parts under the total (#2511)
wwcraft_ on Discord asked for DeepSeek's 赠金 apart from what was topped
up. /user/balance gives each currency's granted_balance and
topped_up_balance beside total_balance; the card's main figure stays the
total, and the two parts are told under it as secondary detail, the way a
balance's other parts already show (no new layout). The GUI's card and
menu bar panel, the TUI's quota page and `magpie quota` say them, labels
in every language (en, zh, zh-TW, ja, de). A reply without the parts, or one
with nothing granted, reads as before.

Real reply, read once from the owner's DeepSeek key on 10-16:
{"currency":"CNY","total_balance":"134.13","granted_balance":"34.14",
"topped_up_balance":"99.98"}. Fed through readDeepSeek/readDeepSeekSplit:
"¥134.13", Granted ¥34.14, Topped up ¥99.98.

Run (at b07b518e7, this commit plus #2512's on origin/main 63be47717):
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok.
- go test -timeout 45m ./... with pipefail, sandbox HOME: 63 packages ok,
  provider, tui, cli, gui and usage among them. agent, gateway and library
  hit the 45m timeout at machine load ~270 on 14 cores; the tests running
  at the panic were 1s-1m14s old (TestCodexLoginAPI,
  TestLoopGuardLeavesOrdinaryRepliesAlone, TestZedMCP), not a hang. Rerun
  alone: library ok (1295s); agent and gateway timed out at 45m again, and
  ok with -timeout 150m: agent ok (5529s); gateway red only in TestIntentClassifierGroup (#1813), TestMaxRPMWaitsForRoomInTheMinute (#1791) and TestMaxRPMGroupPrefersMemberWithRoom (#2520), known timing reds under load, each passing alone here -count=3 (19s).
- GUI, Chromium and WebKit: balance-parts (DeepSeek's parts, en and zh,
  panel too) 4/4. Every GUI file touching balances, usage, sessions or
  i18n (176 files, 4 at a time): red only in model-id-space (#2536),
  provider-advanced-fold (#2552) and one provider-detect-draft case.
  The first two fail on origin/main 63be47717 run alone. The third was
  page.goto's 5s load timeout in the parallel run; run alone it passes
  20/20 three times here and on main, and this diff doesn't touch the
  provider editor (app.js changes are the balance card and the Usage
  ranking only).
- Broken by hand: dropping readDeepSeekSplit from DeepSeek's source
  turns TestDeepSeekBalanceSplit red (gift's split = "").
- Rebased onto origin/main ba132d68b (13 commits; chat.go, gateway.go, app.js, i18n.js among theirs): gofmt and go vet ./internal/... clean; Credits/DeepSeek/Balance/Ledger/RowFlags tests in usage, gateway, provider, cli, tui ok; plan-credits 12/12, balance-parts 4/4, i18n-keys 3/3 in both engines.
2026-10-16 20:11:33 +08:00
yetone 2944e7e0b5 usage: a plugin's failed allowance read says the plugin's reason on the card, not only in its tooltip (太陽と向日葵 on Discord, aqiu817/magpie-sensenova#1)
SenseNova (日日新) has no built-in in magpie: the reporter's balance comes
from the community plugin github:aqiu817/magpie-sensenova, whose usage hook
signs in to platform.sensenova.cn with the console account typed at
sign-in and reads /lite/console/v1/tokenplan/pool-usage; the API key can't
read it. When that sign-in fails the plugin returns its reason in
usage.error, the host passes it on intact (usageOf keeps balance, windows
and error), and magpie showed only "暂时无法获取额度" with the reason in a
hover title, which a Docker web GUI user never sees.

Now a SubscriptionQuota whose Error is the plugin's own usage.error carries
pluginError, and quotaError(err, q) says "Allowance unavailable: {why}"
with the reason's first line (cut at 160 characters) on the provider
editor's account row, the Usage page's card and the tray's card. magpie's
own errors (not signed in, no such plugin, a host or transport failure)
and every error quotaError already words keep their wording. New string
in en, zh, zh-TW, ja and de.

The likely cause on the plugin's side, read from SenseNova's console JS
and not tried with an account: its password login takes the 用户名 (6–24
letters or digits); a phone number signs in by SMS code only, and the
plugin's prompt asks for "手机号 / 邮箱". That fix belongs in the plugin's
repo; nothing was posted there.

Run (sandbox HOME under the scratchpad, GOCACHE/GOMODCACHE pinned):
- go test -run TestPluginUsage$ ./internal/provider: ok. With
  q.PluginError's assignment commented out it fails:
  "plugin_usage_test.go:89: fakeco: plugin error = false, a@fake's = false".
- internal/gui/tests/plugin-quota-error.test.cjs (new), chromium and
  webkit x en, zh, zh-TW, ja, de: 10/10. With origin/main's app.js it
  fails in every language: "row: Allowance unavailable", "row: 暂时无法获取额度", ...
- GUI, both engines: plugin-quota-error, glm-quota-error, balance-fix,
  copilot-signed-out-account, opencode-go-quota-error,
  quota-balance-error, quota-curve, plugin-signed-out-account,
  revoked-signin-account, usage-remote-cards, usage-access-key-card,
  usage-card-refresh, usage-remote-key-limits, gui-de, gui-ja,
  gui-zh-tw, i18n-keys: 223/223 each; after the move onto a1f7b8c13 the
  first and the language guards plus builtins: 24/24 each.
- GUI, both engines, every usage-*, panel-*, tray-*, quota-*, account-*
  and plugin-* file (126) at load 230-330 from other sessions: 742/758
  chromium, 743/758 webkit. The reds are in plugin-market, plugin-move,
  quota-count-wrap, quota-name-translated, usage-agents-hide,
  usage-curve-zoom-back and usage-fold; run alone, serially, they fail
  the same on an origin/main a1f7b8c13 copy of internal/gui (12 and 13
  failures there, 14 and 13 here; usage-fold flips both ways on each,
  3 runs apiece). Not filed in this commit.
- gofmt -l: nothing. GOOS=darwin, linux, windows go vet -tags nogui
  ./...: clean, before and after the move onto a1f7b8c13.
- go test -tags nogui -timeout 45m ./... at a1f7b8c13 + this change:
  62 ok; internal/agent and internal/gateway failed on "no space left on
  device" (the disk filled from other sessions), and rerun at once they
  passed (agent 755s, gateway 897s).

Not tried: a real SenseNova account (none used, no credentials entered),
what SenseNova answers a phone number at /v1/auth/nova/login, the tray
panel's card in the real app, and Docker.

Full suite: go test -tags nogui -timeout 45m ./... 64/64 packages ok (agent and gateway on a rerun after a full disk)
2026-10-15 23:08:05 +08:00
yetoneandDony2050 7dc5cd8f08 provider: Codex keeping its sign-in in the macOS keychain is read and written there (#2367, Dony2050)
Codex 0.162 with cli_auth_credentials_store = "keyring" or "auto" saves
its ChatGPT sign-in to the keychain and deletes auth.json. magpie read
only auth.json, so it hid the Codex provider and every saved account.
Adapted from Dony2050's fcebfc322 (fix/codex-macos-keychain). The changes
from that branch are below.

What Codex does (codex-rs at rust-v0.162.1: login/src/auth/storage.rs,
config/src/types.rs, features/src/lib.rs). The item is service "Codex
Auth", account "cli|" plus the first 16 hex digits of the SHA-256 of the
canonicalised CODEX_HOME. Its value is auth.json's JSON on one line.
keyring reads only the item. auto reads the item, and falls back to
auth.json when there is no item or the item can't be loaded. Saves follow
the same order. With [features] secret_auth_storage on (the default on
Windows), keyring and auto use Codex's encrypted storage instead.

internal/provider/codex_store.go is now the one reader and writer:
- A keychain interface. The real one runs `security` the way Claude Code's
  item is read (keychainText, proc.CommandContext, 10s bound; errors carry
  no argv or output). Tests get a fake (isolate, CodexKeychainForTest).
- readCodexLogin follows Codex's rules on macOS. keyring with no item is
  signed out. keyring with a refused read is unknown (codexStoreError),
  never signed out. With the encrypted storage, on Linux and on Windows,
  keyring and ephemeral are unknown and auto is auth.json. A config.toml
  that doesn't parse reads auth.json as before.
- Reads are kept 10s, a refusal 10 minutes, and only one `security` ask
  runs at a time. Each read can be a Keychain prompt, and codexToken runs
  on every request.
- A refresh writes the rotated tokens back where they came from, with
  unknown fields kept, after re-reading the item.
- saveCodexLogin (switch, first sign-in) re-reads the store first. It
  refuses when the store couldn't be read, when config.toml doesn't parse,
  for ephemeral, and for a store magpie doesn't read. It never deletes
  auth.json; Codex cleans that up itself.
- deleteCodexLogin (signing the last account out) removes the item, then
  auth.json, as `codex logout` does.
- Routed through it: codexAccount, codexToken (it now takes the home dir),
  liveLogin, CodexAPIKeySignedIn, codexLoginAuth, the usage card's
  codexUntil, session identities, switchSavedLogin, addLogin, forgetLogin,
  and agent's codexChatGPT/Source (provider.CodexSignIn).
- savedButSignedOut now says what was found (codexSignedOutWhy): nothing
  in the item, an item macOS wouldn't give (allow it, or use file), or a
  store magpie doesn't read here (use file). This replaces ed6e27f5f's
  codexCredentialsStore and its single "magpie doesn't read the keychain"
  text.

Changed from fcebfc322: secret_auth_storage is honoured (the branch would
read and write the wrong item); there is no second keychain package; reads
are cached and a denial backs off (the branch spawned `security` on every
read); auth.json is not deleted after every keychain write; auto falls back
to the file only when there is no item; the tests use an interface fake on
every OS instead of a darwin-only PATH fake; codexChatGPT keeps its
meaning; a malformed config.toml doesn't hide a file sign-in.

Run (in the wt-2367 worktree, sandbox HOMEs only, no real keychain or
`security` run, nothing under ~/.codex):
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux and windows:
  clean.
- go test -p 1 -tags nogui ./internal/provider: ok (293s).
  ./internal/agent: ok (1291s). An earlier agent run hit the disk filling
  up (ENOSPC from other sessions' builds); it was rerun with room.
  ./internal/gateway -run 'Codex|Login|Account': ok (261s).
- Broken by hand. The keychain never read (keychainItem false):
  TestCodexSignedInInKeychain, TestCodexKeychainRefreshWritesItem,
  TestCodexKeychainSwitch, TestCodexKeychainAskedSeldom,
  TestCodexKeychainSignOut and TestSavedButSignedOut go red. saveCodexLogin
  ignoring a refused read: TestCodexKeychainSwitch red ("switched over a
  sign-in the keychain wouldn't give"). No cache:
  TestCodexKeychainAskedSeldom red (20 asks for 20 reads). agent's
  codexChatGPT reading auth.json only: TestCodexSignInInKeychain red.
- Not tried: an item Codex itself wrote. Codex writes it through
  keyring-rs, and its ACL may trust only codex, so macOS may prompt the
  first time magpie reads it, and Codex may prompt after magpie rewrites
  it (`add-generic-password -U`). An unanswered prompt is killed at 10s
  and reads as unknown. The reporter is asked to confirm on #2367, which
  stays open.

Landing: this goes on top of ed6e27f5f (in this worktree as its
cherry-pick 66cdde294) and replaces that commit's message.

Co-authored-by: Dony2050 <88673296+Dony2050@users.noreply.github.com>

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00