Commit Graph
42 Commits
Author SHA1 Message Date
yetone 40cbdaa7e8 provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.

- AccountWindowAmounts keeps it per account and window (capId). An
  amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
  and NearCap. CapHeld and capReached hold the account once the window's
  count reaches the amount (past), and rest it as the percentage cap
  does: the next account takes the request. cappedError and the trace
  say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
  applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
  place (provider/windowcap with amount). It shows only on a window
  with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
  --amount <n|off>.

Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.

Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
  vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
  ./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
  TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
  420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
  earlier webkit run lost the amount test's page once ("Target page,
  context or browser has been closed"); it passed in 2 more full-file
  runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
  this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).

Reported-by: 9won_25273 (Discord)
2026-11-09 18:19:02 +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 3d0d790606 codex: the Codex app left on an account that runs out is restarted onto the one Codex is signed in to (nb5p on Discord)
nb5p has two ChatGPT accounts in magpie, B first. The Codex app showed A,
and once A ran out Send was grey for every model, magpie's and another
provider's too.

Cause: magpie's switch back to the first account (or to the account
Codex is kept signed in to) leaves the Codex app's app-server running
unless "Restart the Codex app to follow" is on. The app-server keeps the
account it started on (CodexAppStale), so the app stayed on A while
auth.json said B. magpie read only B, which had room, so nothing moved,
magpie never took over, and the app-server was never restarted: the app
greyed Send on A's allowed false for good.

Fix: on each full look of KeepOnAnAccountWithRoom,
restartCodexAppLeftOnSpent reads the account the app is left on, and
once that is held (codexHeld) marks a spent switch (codexAppSwitched
true), which codexAppStep restarts past the RestartApp tick, as a switch
off a used-up account already does. Once per app-server left.

Run (mote, at this tree):
- go test ./internal/provider -count=1: ok
- TestCodexAppLeftOnASpentAccountIsRestarted: user switches to A, magpie
  switches back to B and leaves the app running, A still has room
  (nothing ended), A runs out with B's room (app-server 7 ended), next
  look (not ended again).
Broken by hand:
- codexAppSwitched(true, false) commented out: red, "ended [], want the
  app-server left on the used-up account".
- the once-per-app-server check off: red, "restarted again: [7]".
Not tried: the real Codex app on a real account running out; the call
in KeepOnAnAccountWithRoom's loop is covered by reading, not by a test.
2026-11-05 07:51:09 +08:00
yetone dabb5722f8 claude: Claude Code routed through magpie stays signed in where the user put it when that account is spent
oreoft on Discord has two Claude accounts: A, the main one, whose sign-in
carries their claude.ai connectors (MCP), and B, a quota account. A's
allowance was used up. They set A first and signed in, B second, and
"跑着跑着" B came first again and became Claude Code's sign-in, and the
MCP broke. They set it back more than ten times.

Cause: the used-up switch (#208). KeepOnAnAccountWithRoom looks at
Claude Code's sign-in every minute or five; A is spent, so NextLogin
returns B and SwitchWhenSpent rewrites Claude Code's live credential to
B. The GUI's list puts the account in use first (loginsInOrder), so B
"moves to first". Each time the user signed A in again, the next look
moved it back.

Decision: when Claude Code's settings send its requests to magpie's
gateway (ANTHROPIC_BASE_URL is the gateway, whether it signs in with
magpie's key or keeps its claude.ai sign-in), NextLogin never moves its
sign-in off a spent account. The gateway already routes every request
to an account with room (it skips spent ones on its own), so moving the
sign-in served nothing and only took away what the user signed in as.
This keeps the user's choice and needs no setting.

Still switching, unchanged:
- not routed (Claude Code asks Anthropic as its own sign-in): the switch
  is the only thing that keeps it working (#208);
- "Only switch Claude Code's sign-in" (SwitchOnly): the gateway serves
  none of those accounts, so switching is all magpie is asked to do;
- the move back to the first account / the kept account
  (returnsToFirst, KeepLoginAs), which go toward the user's choice;
- `magpie accounts switch claude next` and the GUI's own switch.
- Codex is left as it is: the Codex app stops sending once its own
  account is out, so it needs the sign-in moved.

ClaudeThroughMagpie is a provider hook the agent package sets
(claudeRouted, the same check claudeIn's "routed" uses), like
CodexAppRoute.

Run (all on mote via mote-run):
- new TestClaudeRoutedThroughMagpieKeepsItsSignIn (sandbox HOME: A
  spent, B with room; routed: three looks, no switch, credential still
  A's; SwitchOnly: switches to B; not routed: switches to B) with
  TestClaudeSwitchedWhenSpent, TestClaudeSwitchOnly*, TestKeepLoginAs*,
  TestNextLogin*, TestClaudeSwitch*, TestNextInOrder, TestCodexDrain*:
  ok. New TestClaudeThroughMagpieReadsItsSettings (agent): ok.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; GOOS=linux go build -tags nogui;
  GOOS=windows go build: ok.
Broken by hand: with the NextLogin gate turned off ("if false && ..."),
TestClaudeRoutedThroughMagpieKeepsItsSignIn FAILs at line 80, "Claude
Code routed through magpie was signed in to b@example.com".
Not tried: real Claude accounts and a real Claude Code with claude.ai
connectors; Windows and Linux boxes. Full suite runs after the push.
A sign-in already moved to B stays on B until the user switches back
once.
2026-11-05 06:43:51 +08:00
yetone f177c36a9b provider: routed Until used up, Codex's sign-in stays on the account the requests went on to
WalterAIBuilder on X (11-04): two Codex accounts, A (Team, first) and B
(Plus), routed Until used up, affinity auto, stop at cap on. A used up
its 5h window (98% cap). Codex was signed in to B, then signed back in
to A once A had room, while B's week kept being spent until it was at
100%.

Cause: returnsToFirst (internal/provider/codex_switch.go) sent Codex's
sign-in back to the first account for every routing but Claude's and a
switch-only Codex's. Routed Until used up, the gateway keeps requests on
the account it moved to (routes.Drain, internal/routes/strategies.go),
and auto affinity keeps a conversation on whoever answered last while
the cache is warm (chatGPTCold, internal/gateway/affinity.go). So Codex
and the accounts list showed A in use, with B marked to go back from,
while requests through magpie stayed on B. The GUI note under Routing
also promised "back to the first" for drain. This is the hxy920830 rule
("not use one up, then the next") missing its Drain sibling.

Now, routed Until used up, Codex's sign-in stays on the account it moved
to till that one is used up too, the same as the requests. In order and
Smart still go back to the first. The Routing note has its own drain
text in en, zh, zh-TW, ja and de. The subsystem page says so.

Old data: a user signed back in to the first stays there. A user with a
return still pending stays on the next account until it is used up, and
the "First again" mark goes away.

Not changed (filing is the reviewer's call): a provider's own accounts
have no back-to-first under auto affinity (backToFirst and
backFromStandIn apply to groups only, inOrder := isGroup && ... in
internal/gateway/gateway.go). Routed In order, a conversation that moved
to the second account stays there after the first renews, for as long as
its cache is warm.

Run on mote (mote-run), at base 5957223d8 plus this change:
- go test ./internal/provider -count=1 -timeout 45m: ok (193.7s)
- GOOS=linux and GOOS=windows go vet ./internal/provider: ok; gofmt -l:
  clean
- node --test --test-concurrency=1 on the GUI tests account-return,
  keep-login, i18n-keys and routing-drain: 64 of 64 pass
Broken by hand: with "&& p.Routing != Drain" removed from
returnsToFirst, TestCodexDrainSignInStaysOnTheNext/drain fails ("first
marked to go back to: true, want false") and /order passes.
Not tried: real accounts; the whole GUI suite; Windows and Linux GUI; an
end-to-end gateway drain run together with a sign-in switch.
origin/main has since moved to d3c544ddf (3 commits); none of them
touch these files.
2026-11-04 14:28:02 +08:00
yetone 1af868a153 provider: a Codex app left on a used-up account restarts with Restart the app off too (atom0964)
v0.1.2826 (1dead5dc7) added Restart the Codex app when magpie switches
its account, off by default, so that atom0964's ChatGPT app stopped
relaunching at every switch magpie made between two Plus accounts. Its
guard in codexAppStep left the app-server running for every change
magpie made by itself, and that covered too much:

- the takeover in, where magpie becomes Codex's provider for its used-up
  account;
- the first look on a used-up account;
- magpie's switch off an account at 98% (SwitchWhenSpent).

The Codex app greys Send for every model while its signed-in account's
rate limit says not allowed, and reads the account only as its
app-server starts (ChatGPT.app 26.1013, 8b0132b3d). Left running, the
app stayed on the used-up account with Send grey, so neither magpie's
fallback nor the next account could serve it until the user restarted
it by hand. With the default off, that broke the takeover for every
user with a fallback.

Now those three restart the app-server tick or not (`needed` in
codexAppStep: `into || c.switched && c.spent`). The tick covers only
what the app works without: the switch back once the first account has
room, and Codex given its account back at the reset. The label, tooltip
and toasts say "switches its account back" in en, zh, zh-TW, ja and de.
The tooltip adds that a used-up account restarts the app anyway.
SwitchWhenSpent's stale-app log, RestartApp's comment and
agent-wiring.md say the same.

atom0964 will still see one restart when an account runs out. Send
needs it. The restarts at the switch back and at the reset are gone.

Run at the pushed head (on mote, rebased on c0d4f17a3):
- gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of
  provider and gui clean.
- go test -count=1 -timeout 45m ./internal/provider ./internal/davsync
  ./internal/backup: ok. ./internal/gui -run "Budget|I18n|Restart": ok
  (the core script budget holds with the longer strings, no raise).
- GUI (chromium + webkit, narrow and wide, en/zh/ja/de): restart-app,
  switch-only, i18n-keys, codex-accounts-via: 76/76.

Broken by hand: codexAppStep's guard without `!needed`:
TestCodexAppLeftRunningForMagpiesOwnChanges ("magpie switched off the
used-up account: ended [], want [60]") and
TestCodexAppFirstLookOnAUsedUpAccountRestarts go red.

Not tried: a real ChatGPT desktop app on a real used-up account (the
app-server end is stubbed); Windows, where an end is followed by
CodexAppReopen.
2026-11-03 16:55:23 +08:00
yetone 1dead5dc7b provider: magpie's own Codex account switches leave the Codex app running unless Restart the app is ticked (atom0964)
atom0964 on Discord (#help) has two ChatGPT Plus accounts in magpie, with
Codex always signed in to the first and Only switch Codex's sign-in both
off, on Smart routing. The Codex desktop app kept restarting by itself.
They tried several combinations of the ticks and it still did.

Why: with both off, SwitchWhenSpent signs Codex in to the next account at
98% and back to the first below 90%. Each switch was noted for the Codex
app (codexAppSpentSwitch), and KeepCodexAppOnItsProvider ended its
app-server once no turn ran; the ChatGPT app shows that as an error and
relaunches (#4550). With Codex kept on the first account there is no
switch, but the used-up takeover (magpie made Codex's provider for a
used-up account and given back once it has room; f37742e14 only limits
it to when another account can serve, which two accounts always can)
changed Codex's route, and that ended it too. So every combination
restarted the app.

What changed:
- Provider.RestartApp (restartApp), off by default, set by
  provider/restartapp (SetRestartApp, Codex only). This computer's own,
  like KeepLogin: Mirror keeps it and davsync's hash leaves it out.
- switchLoginBy(agent, user, byMagpie): SwitchWhenSpent marks its
  switch magpie's own (codexApp.auto). In codexAppStep, a change that is
  magpie's own (its switch, the takeover in or out, the first look at an
  app on a used-up account) ends nothing unless RestartApp is on; it
  logs why and the app follows once restarted. The switch notice's
  Restart, the Agents row's Restart, and uninstall are unchanged.
- Still restarted: a switch the user makes (Switch, the Agents row, the
  CLI), a Connect or Disconnect, failover written or taken out (any
  route change while the takeover state is unchanged), and a user's
  switch pending when magpie's comes.
- GUI: under Codex's accounts, with more than one on (or the tick set),
  "Restart the Codex app when magpie switches its account", with a tip
  and toasts in en, zh, zh-TW, ja and de. app.js paid for it with five
  account-row comments cut; TestCoreScriptBudget is not raised.
- docs/subsystems/agent-wiring.md says which changes restart the app.

Known edge: a takeover flip in the same 3s tick as a Connect is taken
as the Connect's (restarted), since the route changed by the user.

Run at the pushed head (on mote, rebased on b967b1620; then rebased on 2a19043af, a Library change touching none of these files, with the core budget checked again: 160 bytes under):
- gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of
  provider, gui, davsync clean.
- go test -count=1 -timeout 45m ./internal/provider ./internal/davsync
  ./internal/backup: ok. ./internal/gui: ok except
  TestMainWindowCorners/macOS_26_SDK, red alone on origin/main 694f4a6d6
  too (#3949). ./internal/cli: ok except TestEveryRouteHasACommandOrIsNamed
  on GET /api/context/reply (#5026).
- GUI (chromium + webkit, 1100 and 420 wide, en/zh/ja/de):
  restart-app (new), switch-only, claude-switch-only, keep-login,
  codex-accounts-via, account-arrange, i18n-keys: 110/110 and 94/94.
  account-arrange's webkit case went red once in a 5-file run on an
  aborted /api/lanes request; it passes alone on origin/main and at
  this head.

Broken by hand:
- codexAppStep's guard turned off: TestCodexAppLeftRunningForMagpiesOwnChanges
  and TestCodexAppFirstLookLeftRunning go red (ended [60]).
- SwitchWhenSpent marking its switch as the user's: TestCodexSwitchedWhenUsedUp
  goes red ("magpie's own switch is counted the user's").

Not tried: a real ChatGPT desktop app on a real used-up account (the
app-server end is stubbed as before); Windows, where the app is quit and
reopened (CodexAppReopen runs only after an end, so leaving it running
skips it too); no CLI command for the tick (switch-only has none either).
2026-11-03 16:34:30 +08:00
yetone ec104b8625 gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

Cause. At 90% or 98% of a window, smart routing's tier put the account
behind every account that still had room, whether or not it had ChatGPT
credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the
spent share in the same way. The account's credits were spent only once
every other account was used up, and the switch was a log line. The Use
credits switches that existed (on, and "Only after other accounts" from
699ddf152) were only on the Usage page and the panel. None of them meant
"stay on this account and spend its credits".

Change.
- A fourth credits mode, first: settings.CodexCreditsFirst. on, first,
  last and off are exclusive; one mode replaces another.
- routes.Seat.First: a first seat's tier is 0, so routing keeps it in
  front past its windows while it has credits. The trace records
  Weighed.CreditsFirst.
- NextLogin keeps Codex's own sign-in on such an account (spendsFirst).
- The POST /api/codex-credits handler takes "first". The general
  settings save keeps the stored value.
- The CLI: `magpie quota credits <account> first`.
- GUI. No new page and no new component, only the Use credits row that
  already exists:
  - 供应商 → Codex → 账号 ⋯ → 使用积分 → 「先用完积分再换账号」. The
    Providers ⋯ tools now carry the credits row too, which is where the
    reporter looked.
  - 用量 → Codex 账号卡 → 使用积分 → 「先用完积分再换账号」.
  - The menu-bar panel's folded line reads 「开,先于其他账号」.
  - The "First again once it has room" tag on a moved-off account now
    points to the switch in its title.
  - Strings are in en, zh, zh-TW, ja and de.
- "Only after other accounts" (gokoshiki, 699ddf152) is unchanged.
  Its off title now says what off means.
- Docs: docs/reference.md and docs/subsystems/gateway-routing.md.

Budgets: at this head app.js is 1,312,105 of 1,316,874 bytes, and
TestCoreScriptBudget passes (231 bytes under before the rebase). Comments
were condensed; no budget was raised.

Run on mote, at this tree (rebased on origin/main 9d08993c8; the rebase
moved the settings save into internal/settingsapi, which now carries
CodexCreditsFirst beside CodexCreditsLast):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/routes ./internal/settings ./internal/settingsapi
  ./internal/gui ./internal/cli at 9d08993c8+1: gateway, provider,
  routes, settings and settingsapi ok. Two reds, both filed:
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949.
  - internal/cli TestLibraryMCPHub, TempDir cleanup not empty: #4140.
  At the pre-rebase tree (da0005df8+1) internal/gui also had
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestColdTurnsTaken
  (#4510), red the same at da0005df8; both pass at this head.
- New tests:
  - internal/provider/codex_credits_first_test.go
  - internal/gateway/codex_credits_first_test.go (routing and the trace)
  - internal/gui/codex_credits_first_test.go (POST sequence, sandbox HOME)
  - internal/gui/tests/codex-credits-first.test.cjs: the Usage page and
    Providers ⋯ at 900 and 440px, and the panel at 360px; chromium and
    webkit, en zh zh-TW ja de. It also checks for no select, no stripe,
    the i18n keys, and that a click does not move the page.
- The whole GUI suite (make test-ui), at da0005df8+1 on mote at load
  66 to 213, in two parts (a wiped scratchpad cut the first log; its red
  titles were kept): 59 files with a red. 45 of them are red at
  origin/main da0005df8 too, each under an open issue: #4304 (mote
  umbrella), #4600, #4471, #4120, #4119, #4621, and per file balance-fix
  #4682/#4683, gui-ja #4580, page-width-steady #4541, phone-connect-menu
  #4706/#4707, quota-curve #4768, segs-press-redraw #4566, signin-proxy
  #4643/#1814, zhipu-team #4728, model-copy-id #4621 (red 4 of 4 on main).
- The 14 green at da0005df8 were run again at this tree. One was this
  change's: usage-curve-zoom-back. The Codex card's fourth credits line
  (366px, was 344) held the DeepSeek card beside it to 261px, so the
  "card grows" check at 1100px had no room. Its fixture now turns the
  Codex account's credits off, since the count of credits lines isn't
  what it tests; 20 of 20 pass.
- At this head (9d08993c8+1), on mote at load 75 to 84: codex-credits-first,
  codex-credits-last, codex-credits, routing-codex-credits-again,
  panel-options-fold, usage-curve-zoom-back, i18n-keys and the 13 files
  above: 232 tests, 227 pass. Each red has an open issue:
  - models-fold webkit en/zh, "ebody holds" after the click: #4071; red
    the same at 9d08993c8 (run there).
  - account-weight webkit, same "ebody holds": #4644 (red at
    da0005df8+1, green in this run).
  - routing-many-keys chromium de "2 keys in sight at the foot": #4082
    (under load; red again alone here, green at 9d08993c8 in one run).
  - signin-closes-sheet chromium en/zh: #2628 (green alone at this head
    in a second run).
  - signin-again and signin-port-blocked, red once at da0005df8+1 under
    load, pass at this head and at 9d08993c8.

- Rebased last onto 94f6f6092 (three commits; c0477aa72 changes the
  Codex Providers row): go test -run 'Budget|CodexCredits|SettingsSave'
  ./internal/gui ok, and codex-credits-first, codex-credits,
  codex-credits-last, providers-reset-use, i18n-keys and
  usage-curve-zoom-back: 92 of 92 pass.

Broken by hand, each red, then restored:
- spendsFirst forced false: the provider test is red.
- The gateway's l.first forced false: both gateway tests are red.
- codex-credits-first.test.cjs against origin/main's assets: red
  (TimeoutError on the switch).

Not tried:
- No real ChatGPT account with credits went past its window. The routing
  order and NextLogin are tested on fakes only.
- The Linux and Windows apps were not run.

go vet -tags nogui ./... with GOOS darwin, linux and windows on mote:
clean (cgo enum warnings only). gofmt -l on the changed Go files: clean.

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
2026-11-01 21:19:22 +08:00
yetone 9162277b91 routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.

Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).

Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
  through a rate limit, all used up, a seat gone, per pool, Forget,
  Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
  k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
  In order goes back to k1. Red without the Drained hook (request 3 went
  to k1). A rate limit comes back to k1; drain is saved on a provider and
  a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
  languages, 1100px and 420px, Chromium and WebKit; red on the old assets
  (20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
2026-11-01 09:53:50 +08:00
yetone 41b5c0f19a accounts: Claude Code stays on the account it moved to till that is spent too (hxy920830 on X)
hxy920830 on X wants Claude Code to use one account to 98%, move to the
next and use that one to 98%, not jump back the moment the first resets.
No setting gave that. NextLogin (#408) signed the agent back in to the
first account as soon as it was under 90% again, under every routing.
KeepLogin pins one account, In order goes back too, and switch only
went back as well.

Where the sign-in is what spends the accounts (Claude Code, whose own
requests never pass the gateway, and Codex under switch only), the
sign-in now stays on the account it moved to until that one is spent
or fails, then moves on to the next ticked account with room. It goes
back to the first only where the user said the first comes first:
routing In order, or KeepLogin. Codex through the gateway keeps going
back, because Smart routing sends its requests to the first account
(#209) and the sign-in follows it. This is returnsToFirst in
codex_switch.go. The return record is still written, so turning In
order on later goes back as before. An old record is ignored otherwise,
and its "First again" label (logins.go) is hidden. No user setting is
overridden: In order and KeepLogin keep their meaning.

GUI: the Routing note for Claude Code (and Codex under switch only) now
says it stays on the account till that one is 98% used too. The two
switch-only tooltips no longer promise going back. New and changed
strings are in zh, zh-TW, ja and de. app.js lost a 3-line comment so
the core script budget holds without a raise (core 1,531,108 of
1,533,105).

Run on mote at 94cd5edde (base d307aa648):
- go test -tags nogui -count=1 ./internal/provider/: ok. New test
  TestSignInStaysOnTheAccountMovedTo (claude, claude switch only, codex
  switch only stay; claude in order goes back).
- TestCoreScriptBudget and the gui package's budget tests: ok.
- go vet -tags nogui ./internal/provider/ ./internal/gui/ with GOOS
  darwin, linux and windows: clean. gofmt -l: clean.
- GUI, Chromium and WebKit: account-return, switch-only,
  claude-switch-only, i18n-keys, keep-login, routing-signin, gui-zh-tw,
  gui-de, gui-ja. 116/117 and 64/65 passed. The one red is gui-ja's
  "{agent} three times" string, red on origin/main dd7442f28 too (#4580).
- Full suite at the earlier base 76c130b29, -timeout 45m: provider ok.
  Reds, all already filed: TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514), TestCodexListTagNotKeptOverAFreshFile (#4216),
  TestUnroutedRequestShownThenAnswered (#4200). TestCoreScriptBudget
  failed by 41 bytes, fixed above. internal/gui hit its 45m timeout in
  TestUpdateInATerminalRestartsTheAppWithoutCuttingIt.

Broken by hand: with returnsToFirst forced to true,
TestSignInStaysOnTheAccountMovedTo (all three staying cases) and
TestCodexSwitchOnlyStillSwitchesTheSignIn went red. With the note forced
back to the "back to the first" text, the new account-return GUI test
went red in Chromium en and zh.

Not tried: a real Claude account moving and its first renewing (needs
two real windows to run out), runs on the Windows and Linux boxes, and
the full GUI suite at this head.
2026-11-01 05:23:58 +08:00
yetone 9fa11784db provider: a provider's proxy and off switch are read from providers.json as parsed once
A live magpie's heap profile (v0.1.2404, 53 minutes) allocated 3.6 GB of
its 33 GB in provider.load, a parse of the whole providers.json, mostly
for one field of one provider: storedPicks (its proxy, 1.73 GB) and
leftAlone (switched off or hidden, 1.24 GB), asked for each request and
each background look, then customIDs, keptAs, loginSwitching and
accountRemoved.

These six only read, so they now go through storedFile: filememo's
parse of the file, kept until its time or size changes (and its bytes,
written in the last two seconds), and dropped by every write magpie
makes (writePrivate's Forget). A file missing or not decoding goes the
way load goes, to its last good generation. What load's other callers
get is unchanged, as some of them edit what they read before a save.

TestStoredParsedOnceUntilTheFileChanges: 30 providers of 100 models.
storedPicks and leftAlone with the file unchanged take under 40
allocations (a parse is 3381); a provider switched off since is left
alone at once; another process's edit of the same size is seen; a
zeroed file still finds its providers. Broken by hand: storedFile
parsing each time, red (3386 allocations); a broken file read as none,
red.

Run at this tree on mote: gofmt clean; go vet ./internal/provider on darwin, linux and windows; go test -count=1 -timeout 45m ./internal/provider (ok 116.0s) ./internal/gateway (ok 613.2s).
2026-11-01 00:43:15 +08:00
yetone 01813c681a accounts: switch next takes accounts that are off too, as Use does (#4532)
`magpie accounts switch claude next` (v0.1.2376) took only accounts
switched On. An account the user signed in to themselves, picked up by
rememberLogins, starts off, so next said there was nothing to switch to
while the switch list and the GUI's Use took that same account
(StringKe). On is whether the gateway routes to an account beside the
one signed in, not whether the agent may be signed in to it, so
NextInOrder now takes every switchable account (no token, no home of
its own) that isn't the signed-in one and isn't spent, On or not.
NextLogin, the automatic switch when one is used up, still moves only
to accounts that are On; that is unchanged. reference.md and
providers-accounts.md say so.

Ran, at this tree on origin/main e90a635a9, through mote-run:
- go test ./internal/provider -run 'TestNext|TestSwitch': ok;
  TestNextTakesAccountsThatAreOff (codex and claude: accounts left
  off as picked up; next takes the first, then the second once the
  first is at 99; NextLogin doesn't move to an off one) and
  TestNextInOrder's new cases.
- go vet ./...; GOOS=linux (-tags nogui) and GOOS=windows go vet and
  go build: ok (at the pre-rebase head on 0379f2610; go vet ./...
  again at the rebased head).
- Full suite, go test -tags nogui -timeout 45m ./..., at the
  pre-rebase head: every package ok but internal/gui, red on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red the same on
  origin/main e90a635a9, run alone) and TestColdTurnsTaken (#4510,
  red only in full gui runs). After the rebase internal/provider and
  internal/gui ran whole again: provider ok, gui red on #4514 only.

Broke by hand: put the l.On filter back in NextInOrder.
TestNextInOrder and TestNextTakesAccountsThatAreOff went red ("codex
has no other account in magpie to switch to", wrong picks). Restored.

Not tried: a real Claude or Codex account, or the CLI command end to
end; the tests use sandbox fakes under a test HOME. Nothing here
touches ~/.claude or the Keychain.
2026-10-31 19:35:16 +08:00
yetone 15b83901ac accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch
to the next account", and when every account was past its line the
automatic switch stayed on the spent one, where cswap moves to the account
with the most room left.

- `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes
  the other accounts that are on in magpie, from the one after the account
  the agent is on, wrapping round: the first whose allowance is known and
  has room, else the one with the most room left, and says it is past its
  line. A saved Claude account not read yet is read first (readSpare), as
  the automatic switch's spares are. With no reading of any it refuses
  rather than guess; for any other agent it asks for the account by name.
- NextLogin (shared by Codex and Claude Code): when the account the agent
  is on is spent and every spare is past its line too, it moves to the
  spare with the most room left (roomLeft: the fullest stopping window's
  distance below the switch share, or the account's own cap when lower),
  when that has at least roomMargin (1 point) more than the one it is on,
  so two all but even accounts don't trade the agent each look. A held,
  failed or unknown reading is never moved to. One model's own window
  still counts for nothing, as before.
- docs: reference.md (the automatic switch and `next`; its "a Claude
  account magpie knows nothing of is not moved to" was stale since
  readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja
  start pages' command table, `magpie help`.

Run (on mote, sandbox HOME through the packages' TestMain):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (144s, 44s), at this change's tree before the next commit's edits.
- TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each
  over codex and claude with three accounts: green; red with the fallback
  taken out of NextLogin (the two "most room" cases, both agents) and with
  NextInOrder not starting after the signed-in account ("the one after
  it", both agents). The "none has more by the margin" case fails without
  roomMargin.
- Built the nogui binary and ran in a fresh sandbox HOME on mote:
  `accounts switch claude next --help` (prints the accounts help),
  `switch claude next` and `switch codex next` with no accounts ("has no
  other account that is on"), `switch gemini next` (asks for a name),
  `switch claude nxt` (no such account), `switch claude` (usage).
- gofmt -l clean. Cross-OS vet: run at the head of this stack.

Not tried: a real switch between real Claude or Codex accounts; the CLI
`next` with real saved accounts (the provider tests cover the choice).
2026-10-31 18:18:37 +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 cc81ad4ea1 codex: a Windows Codex app that starts no app-server after a switch is reopened (蛋仔 on Discord)
After magpie switched Codex's account, the Windows Codex app answered
every send with "Codex app-server process is not available" until it
was quit and opened again. The report said the app doesn't reconnect
after a clean exit. That is half right. The app (MSIX OpenAI.Codex
26.1021, an Electron ChatGPT.exe that spawns codex.exe app-server over
stdio) does start another, but only once the old one's stdout reaches
EOF and its exit has fired. On Windows a child of the app-server (an MCP
server, a tool command) inherits that pipe handle. A child left running
keeps the pipe open, so the app never sees the close, starts none, and
its send() throws. Reproduced on the Windows box with the real codex.exe
0.164 app-server plus an MCP server: stdout ended only when the MCP
server did, and at once when the tree was ended.

magpie took "the old pid is gone" as done in each place it restarts the
app-server. None of them checked that a new one came:
- codexAppStep (the switch watcher) now records the pids it ended and
  waits codexAppBackWait (30s) for another app-server. If none comes and
  the app still runs (CodexAppOpen), it quits and opens the app as the
  Agents row's Restart does (CodexAppReopen: restartWin by the
  OpenAI.Codex_2p2nqsd0c76g0!App AUMID, Windows only). Where it can't,
  the row says to (CodexAppStuck).
- RestartCodexApp (macOS Restart), RestartCodexAppWhenIdle (uninstall)
  and the switch notice's Restart (RestartSwitchedCodexApp, 46aa7e6b8)
  wait for a new app-server too, and reopen or say so the same way.
  RestartSwitchedCodexApp's own 20s codexAppBackWait went into the
  shared 30s one.
- recheckLeft no longer clears the "still on the old account" record
  while the app is open with no app-server.
- A turn stuck open when quota ran out mid-task (蛋仔's follow-up) held
  the restart for up to codexTurnWindow (30m), since an open turn in
  Codex's sessions meant "a task runs". A switch off a used-up account
  (SwitchWhenSpent) now marks it spent (codexAppSpentSwitch). After such
  a switch, a turn that has written no session file and sent nothing
  through magpie for codexTurnStuckAfter (2m) counts as stuck, and the
  app-server is restarted past it. Its next request would be refused on
  that account anyway. A tool still running in that turn is ended with
  it. A switch for any other reason waits for the turn as before.
macOS is never reopened unasked (a reopen opens a new window,
yoshi037070, 10-27). WSL needs nothing: WSL Codex has no desktop app, and
the Windows app's app-server runs on the Windows side.

Run (at this head unless said):
- mote: go test -timeout 45m ./... at 4cf444bc4, this change on
  origin/main 807048470. It was rebased on dca3e2d71 after (5 commits,
  none in codex_app*/codex_switch/codex_daemon), and the -run below was
  run again at the pushed head. Result: every package ok except gateway and gui, whose reds aren't this
  change's (it touches neither package). gateway: TestAntigravityTurn*
  x4 and TestCodexSpentGrokFailingIsTold, red the same on origin/main
  46aa7e6b8 (#4362), and TestUnroutedUnknownHoldAnsweredSooner, which
  passes alone 3 of 3 at this head (filed #4377). gui:
  TestMainWindowCorners (#3949).
- mote: provider and agent -run 'CodexApp|CodexDaemon|RestartCodex|
  RestartSwitched|CodexSwitched|CodexSessionsQuiet|Switch' ok; gofmt -l clean; GOOS=windows, linux,
  darwin go vet ./internal/agent ./internal/provider ok.
- win-run, the same -run: everything of mine passes. Two tests are red,
  TestCodexDaemonEnvIsTheTerminals and TestWorkBuddyRestartOnMac, the
  same on origin/main (#4115).
- Broken by hand, each red, then restored: the step's no-app-server
  branch, RestartCodexApp's not-back check, uninstall's reopen,
  recheckLeft's open check (4 provider tests); RestartSwitchedCodexApp
  without the reopen (TestRestartSwitchedCodexApp "reopened 0"); the
  codexWinApp matcher widened to \WindowsApps\OpenAI.
  (TestCodexAppReopenedOnWindows). The stuck-turn bypass taken out
  ("a turn stuck on the used-up account: ended []"), the spent mark not
  set (TestCodexSwitchedWhenUsedUp), and the bypass without its spent
  and quiet checks ("a turn open after a switch not for spend: ended
  [60]").
- Real Codex app on Windows (xiaomi-gpu, OpenAI.Codex 26.1021.3705.0,
  from a throwaway test, not committed, run as a scheduled task in the
  console session):
  - RestartCodexAppWhenIdle ended the real app-server, and the app
    started another within ~0.6s. codexAppBack saw it (left false).
  - codexAppReopen quit ChatGPT.exe 43832 and opened the app by its
    AUMID in 3.7s (main now 70060). A new app-server came 9.6s after.

Not tried:
- The stuck state itself in the real app: an MCP child really holding
  the app-server's stdout inside the Codex app. It was reproduced with
  codex.exe outside the app, and the reopen was run on a working app.
- A signed-in real account switch on Windows.
- The quota-mid-task hang with a real used-up account. Why the app sat
  on the turn wasn't reproduced. A plain usage_limit_reached refusal
  closes the turn (task_complete, as dd9828f2b found), so this covers a
  turn that stays open, whatever holds it.
- Whether a reopen loses an unsent draft.
- The macOS path with a real stuck app (it says to quit and reopen;
  nothing is reopened there).
2026-10-30 13:42:48 +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 ef2b2d1e3b provider, gui: switching only Codex's or Claude Code's sign-in moves it even when it is kept on one account (#1907, foobra; yifengz88611436 on X)
foobra's screenshot on #1907 (v0.1.1224 on) had both "Keep Codex
signed in to [the first account]" and "Only switch Codex's sign-in"
ticked. The account Codex was on had 0% of its five hours left and the
other had 100%. Codex stayed on the spent account, through a restart of
Codex Desktop and the CLI. With KeepLogin on, NextLogin never moves the
sign-in (#524), and switch-only sends nothing through the gateway. So the
pair meant that no account change ever happened, while the switch-only
tick says moving the sign-in is the one thing magpie does. Picking "the
first account" in the keep picker ticks KeepLogin too, so it is easy to
land in this state without meaning to.

Now Provider.keepsLogin() is KeepLogin && !SwitchOnly. loginSwitching,
keptAs (KeepLoginAs) and LoginRanks go by it, so under switch-only the
sign-in moves at the spent share and back once the first has room. That
holds whether the user kept the first account or one of their choosing,
and for Codex and Claude Code alike (switchedAgents). The saved
KeepLogin/KeepLoginAs is left as the user wrote it, and it holds again
once switch-only is unticked. SetKeepLogin(true) and SetKeepLoginAs
refuse while switch-only is on, because there they would do nothing.
GUI: the keep tick and picker are hidden while switch-only is on, and
keptLogin() and the Routing note treat KeepLogin as off then. The
Accounts hint for a switched sign-in said "the gateway moves on to the
next", which isn't true under switch-only. It now says "magpie moves on
to the next", which holds in both modes, in en, zh, zh-TW, ja and de.
app.js ends up 29 bytes smaller than origin/main, so TestCoreScriptBudget
holds without a raise (a first version had been 661 over).

Run (on mote unless said otherwise):
- TestSwitchOnlyMovesASignInKeptOnOne (Codex, kept on the first and on a
  chosen account) and TestClaudeSwitchOnlyMovesASignInKeptOnOne are new.
  With keepsLogin put back to plain KeepLogin by hand, all three cases
  are red ("switched to \"\""). With the change they are green.
- go test -run 'SwitchOnly|KeepLogin|KeptLogin|CodexLoginOrderedAndKept'
  on internal/provider, agent, gateway and davsync: ok at this head
  (rebased on accb951ab).
- keep-login.test.cjs has 4 new cases (switch-only with keep on the
  first or on spare, en and zh). With app.js put back to origin/main,
  4 of 12 are red in Chromium. The GUI files keep-login, switch-only,
  claude-switch-only, i18n-keys, agent-switch-accounts, pool-ends,
  account-return, routing-account-order and account-arrange gave
  185 of 186 in Chromium and WebKit, at base e863f520c. The one red was
  claude-switch-only "chromium 420 ja", where the element was detached
  before the test clicked anything, under load ~90. That file passed
  32 of 32 twice alone. Filed as #4344.
- After the hint and budget change: go test -run 'Budget|I18n'
  ./internal/gui ok; keep-login, i18n-keys and switch-only .test.cjs
  60 of 60 (Chromium and WebKit).
- gofmt -l is clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui
  and GOOS=windows go build are ok (at base e863f520c).
- The full go test ./... -timeout 45m follows this push, once mote is
  free; its result goes on #1907.

Not tried: a real ChatGPT or Claude account, and Codex Desktop itself.
Also not covered here: Claude Code not connected and switched by Make
first (cn_Vincentzyx on X). There, a saved Claude account has no usage
reading unless magpie has heard of it, so the switch can find no spare
with known room. That is a separate cause.
2026-10-30 11:44:40 +08:00
yetone 6e55914b6d provider: Codex accounts are read one at a time and renewed every 8 days, not all at once
owl (Discord #general) holds several ChatGPT accounts in magpie with
no agent wired and had three deactivated. Auditing what magpie sends
to OpenAI for such accounts found two bursts from one address that
the official Codex client never makes:

- KeepOnAnAccountWithRoom read /wham/usage for every saved Codex
  account, concurrently, every 5 minutes (every minute near the cap),
  though only the account Codex is on matters until it is spent.
  NextLogin now reads the account it is on and the one it goes back
  to, and the spares only once the one it is on is spent; CodexUsedUp
  reads the active account alone (codexReadingHeld only looks at it).
  The Claude side of the same loop gets the same rule.
- KeepLoginsAlive force-refreshed every idle saved ChatGPT sign-in
  once a day, all in the same hourly look, so after day one they were
  refreshed side by side for good. It now renews after 8 days (codex-rs
  TOKEN_REFRESH_INTERVAL in login/src/auth/manager.rs) and one account
  per hourly look, so they drift apart.

Not changed: headers, identity, originator, prompts. The refresh and
usage requests still go with Go's User-Agent and no originator, while
Codex sends codex_cli_rs and an originator; that is left for the
owner. The hourly /models list per saved account and the Usage page
reading every account when it is open are unchanged too.

Run (mote-run, at origin/main f5dd4e142 plus this change):
- gofmt -l internal/provider: clean
- go vet ./internal/provider (darwin), GOOS=linux -tags nogui,
  GOOS=windows: ok; earlier also ./internal/cli ./internal/gateway
- go test -count=1 -timeout 45m ./internal/provider ./internal/cli: ok
- go test -run of the 24 internal/gateway tests that reach NextLogin,
  CodexUsedUp or LoginUsageVia (allowance_stale, claude_renewed,
  codex_accounts, codex_app_out, quotas_remote): 24 PASS
- go test ./internal/agent: ok (before the stand-in copy fix below)
Broken by hand: with the old codex_switch.go, login_usage.go and
keepalive.go, TestCodexLookReadsTheActiveAccountOnly read all three
accounts in one look and TestKeepAliveRenewsOneALook failed on the 24h
interval; with keepAliveAtOnce = 0 it renewed both idle accounts in
one look.
Not tried: a real ChatGPT account; whether this traffic had anything
to do with owl's deactivations is not known.
2026-10-30 02:09:54 +08:00
yetone fb2e11e288 agent: a Codex sign-in OpenAI refused to refresh for good counts as none (#4308)
jjt on Discord: Codex's ChatGPT sign-in was revoked, and magpie's
models were gone from Codex until they signed in again.

Cause: Codex keeps a revoked sign-in's auth.json as it was and remembers
the permanent refresh failure in memory alone (codex-rs
login/src/auth/manager.rs). magpie read auth.json alone
(codexChatGPTKnown), counted the sign-in and wired Codex beside it
(openai_base_url, requires_openai_auth). There, Codex's /models went to
the gateway, which passed OpenAI's 401 token_revoked through, so the
picker had no magpie model; and every turn, magpie's models too, failed
at Codex 0.162.1's workspace routing discovery
(/backend-api/wham/accounts/check, 401).

Change:
- provider: codexRefresh tells a refusal Codex takes as permanent
  (request_chatgpt_token_refresh: refresh_token_expired, _reused or
  _invalidated, a 400 invalid_grant, or a 401 - here only a 401 that
  carries an error code, read as oauth/error.rs reads it). When magpie's
  own refresh of Codex's sign-in (codexTokenRenewing, from the usage read
  that KeepOnAnAccountWithRoom runs) is refused that way, and the store
  still holds that refresh token, codex-signin-gone.json keeps the Codex
  home -> sha256 of the refused refresh token (no token stored). A
  successful refresh forgets it. Writes Touch the catalog so the agents
  resync; the loop's noteCodexGoneNow notices a sign-in made again
  elsewhere within minutes.
- agent: codexChatGPTKnown reads such a sign-in as none
  (provider.CodexSignInGone), as v0.1.2087 did for forced_login_method =
  "api": magpie is Codex's provider without requires_openai_auth, the
  user's auth.json stays. A record that can't be read is unknown (as
  magpie last wired it). Signing in again gives another refresh token,
  which the record doesn't name: Sync writes requires_openai_auth back.
- gateway: codexModels doesn't pass a revoked /models answer
  (provider.SignInRevoked) through: it lists Codex's cached models and
  magpie's. The desk file does the same while the live list says revoked
  (CodexListRevoked). Any other refusal (token_expired, 5xx) is as before.
- docs: agent-wiring and gateway-routing.

Run:
- real codex 0.162.1 (app-server over stdio, and exec) on mote, sandbox
  HOME/CODEX_HOME, fake OpenAI (chatgpt_base_url,
  CODEX_REFRESH_TOKEN_URL_OVERRIDE, provider.CodexBase) answering 401
  token_revoked and refresh_token_invalidated; no real network.
  - Old wiring beside the dead sign-in, old gateway: model/list had no
    magpie model (jjt's case). With the gateway change: fake/m1 listed,
    but exec -m fake/m1 fails at workspace routing discovery (401), and
    account/read errors too - why the wiring change is needed.
  - Uncommitted e2e in the agent package with magpie's own written
    config: Set("fake/m1") wrote it beside the sign-in; magpie's
    LoginUsage("codex") then heard the refresh refused, Sync rewrote it
    to model_provider = "magpie", model_catalog_json, no
    requires_openai_auth. account/read: {"account":null,
    "requiresOpenaiAuth":false}; model/list: fake/m1 plus Codex's
    models; exec -m fake/m1 answered "hi from magpie"; auth.json byte
    for byte the same.
- Red on the old code (broken by hand): without the codexChatGPTKnown
  check TestCodexGoneSignInIsNoChatGPT is red; without the
  noteCodexSignInGone call TestCodexSignInGoneWhenRefusedForGood is red;
  with codexRefreshGone true for every failure TestCodexRefreshGoneRule
  is red; TestCodexModelListRevokedSignIn and
  TestCodexDesktopCatalogRevokedSignIn are red on the old gateway.
  Taking out the store re-check in noteCodexSignInGone leaves the tests
  green: a token Codex rotated meanwhile is already held by the hash
  comparison, and the re-check only saves a needless record, log line
  and resync. Not guarded on its own.
- via mote-run, at this commit rebased on origin/main 1f03d7546:
  gofmt -l clean; go vet ./internal/provider ./internal/agent
  ./internal/gateway for darwin, linux (-tags nogui) and windows ok;
  go test -timeout 45m -p 1 of the three: provider ok (92.3s), agent ok
  (192.1s), gateway ok (530.9s). The first full run had the new provider
  test red: run after the other Codex tests it read their cached logins
  and listed none; it now has the resetRevoked/rememberLogins setup its
  siblings use.
  Rebased after the run onto 05a6087e1 (access: key model scope) and
  8cbd0a9c9 (GUI loading bird); neither touches the Codex paths, and
  this push wasn't run again on them.

Not tried: the real Codex desktop app (ChatGPT.app); signing in again
with the real binary (the unit test writes a new auth.json); the
keychain credential store; magpie's left-alone mode, where magpie
doesn't refresh Codex's sign-in, so nothing is recorded there;
Codex homes on Windows and in WSL.
2026-10-30 01:40:48 +08:00
yetone a312bf3e38 codex: switching the ChatGPT account restarts the Codex app's app-server once no turn runs
zhibukaixinyao (Discord #help, 10-27) asked when Windows gets the
"restart Codex" step: the Windows GUI has no Restart button, so after an
account switch the Codex app kept sending on, and showing the limits of,
the account it started with until the user quit and reopened it.

noteCodexSwitch now hands the app-server pid it recorded as left on the
old account to codexApp's stale set, the same set a route change fills.
KeepCodexAppOnItsProvider's step ends it once Codex is idle and no turn is
open, and the app starts another that reads auth.json afresh. This covers
a switch made in the gateway's process: the GUI's switch and
SwitchWhenSpent. Together with 3aead9c62 (the Windows app's app-server is
found at all) this needs no restart on Windows, macOS or Linux.

Run (at 9bfe68048 + this change):
- TestCodexAppServerRestartedOnAccountSwitch (new): nothing ended with no
  switch, nothing while a turn is open, pid ended once idle after the
  switch and only once, CodexAppStale "" afterwards.
- go test -race -count=3 -run TestCodexApp ./internal/provider: ok.
- go test ./internal/provider ./internal/agent ./internal/cli (skipping
  #3632 and #3854's tests): provider ok, cli ok; agent red only on
  TestFolderVarsAreListed, red on main since e4552cca9 (#3884).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.

Broken by hand: with the codexAppAccountLeft call removed the new test is
red ("switched, idle: ended [], want [60]").

Not tried: a real account switch on the Windows box (the box's Codex app
isn't signed in to two ChatGPT accounts). A switch made from the
CLI runs in its own process and still only sets the notice; the running
gateway doesn't hear of it.
2026-10-27 18:03:58 +08:00
yetone 8b0132b3d2 codex: the Codex app sends again on every system as soon as magpie takes a used-up ChatGPT account over, and gets it back at the reset
Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540. The Codex app greys
Send for every model, magpie's too, while the ChatGPT account it is signed in
to is used up. Its composer's gate (ChatGPT.app 26.1013) reads authMethod
"chatgpt" plus rate limit allowed=false, and it asks account/read only when its
app-server starts. ef37b6fb7 (v0.1.1381) could fail in practice:
- (a) The reopen was macOS-only, ran once per time out, only from the GUI
  process. A Windows or Linux user, a magpie without its window, or a second
  time out stayed greyed.
- Switch-back: the app stayed on magpie (authMethod null, no cloud tasks or
  Log out) after the reset. Nothing restarted it.
- (c) Detection lag: the account was read every 5 minutes.
- The notice sat on the Providers page, not on Codex's Agents row.

Now:
- The gateway process (`provider.KeepCodexAppOnItsProvider`, every 3s, on
  every OS) ends the Codex app's own app-server each time `Agent.AppOut`
  flips, both ways. The app starts another at once and reads account/read
  afresh. Its window, threads and drafts stay.
- It never ends an app-server while a Codex request is in flight through
  magpie or ended in the last 10s (`Server.CodexBusy`, Codex's requests only),
  or while a session under the Codex home has a turn open (`codexTurnOpen`).
- It ends only the app's own app-server. That one runs on stdio; one another
  program starts with `--listen` is left alone (Miyi Helper runs one on this
  Mac). It must also run on magpie's Codex home (`proc.EnvOf`: ps -E on macOS,
  /proc on Linux; Windows can't tell).
- The exit is clean (`proc.End`: SIGTERM, or TerminateProcess with code 0 on
  Windows). The app shows any other exit as a crash.
- A listing that fails is taken up again at the next look. One that outlives
  3 ends, or is denied, makes the row say to quit and reopen.
- The active account is read every minute while it is held or a window is at
  90% or more (`codexLookEvery`).
- Codex's Agents row says "On magpie until <reset> · ChatGPT allowance used
  up". Hovering it, or opening the row, says what is off until then (cloud
  tasks, the usage meter, Log out) and that it all comes back on its own. In
  en, zh, zh-TW, ja and de.
- Removed: gui's keepCodexAppSending/codexAppOut, provider's episode
  bookkeeping, and the Providers-page notice.

Not changed, by design:
- A Codex own model that no magpie account serves stays as it is: magpie
  can't serve that turn.
- Account discovery off and "Only switch Codex's sign-in" (login=chatgpt) are
  the user's own choices, and are left alone.

Full suite green at cff1a9686 (on origin/main 6ce0f14b9), below. At
4541b3e97 (rebased on 430e3050d, which touched gateway.go, app.js and
i18n.js beside this) ran: gofmt -l, go build ./..., go vet on darwin,
linux (-tags nogui ./...) and windows; go test -run Codex ./internal/provider
./internal/agent ok; GUI codex-app-out (22 ok) and codex-app-stale (20 ok),
chromium and webkit. Pushed rebased on b92cb2f59 (two more commits,
neither in these files), built, not rerun.

Run at this commit (cff1a9686, on origin/main 6ce0f14b9), with a private
GOCACHE (another session ran go clean -cache mid-run):
- gofmt -l: clean. go build ./...: ok.
- go vet: darwin (touched packages); GOOS=linux -tags nogui ./...;
  GOOS=windows (touched packages).
- go test -count=1 -timeout 45m: internal/proc, internal/provider,
  internal/agent, internal/gateway, internal/gui all ok, skipping four
  tests red on main without this change, each already filed:
  TestUnreadLoginsWriteErrorsKeepCredentials (#3632, a synctest crash
  since 091153bf) and TestFetchAsksOneListOnceForTwoBasesOfIt,
  TestFetchUnionsProtocolListsWithoutChat, TestFetchAsksASharedBaseOnce
  (#3854, since 6eb510f78). All three of the latter fail the same at
  origin/main 6ce0f14b9 and at 353519f55 without this commit.
- GUI at cff1a9686, chromium and webkit, 231 cases ok: codex-app-out (5 languages, 980 and 440px),
  i18n-keys, gui-de/ja/zh-tw, codex-app-stale, codex-accounts-via,
  agent-stale-copies, agent-app-restart, agent-failover, agent-connect,
  agent-layout, agent-expand-steady, agent-connected-unfolded,
  agent-notice-lang and codex-signin-always.
- Windows box (cross-built test binaries): proc and provider's Codex app
  tests pass. TestEndExitsClean passes there and goes red with exit code 1.
- Broken by hand, each went red:
  - Codex-only busy: TestCodexBusy.
  - The 90% cadence: TestCodexLookEvery.
  - The retry after a failed listing: TestCodexAppServerUnknown.
  - The turn guard: TestCodexAppServerRestartedEachWay.
  - The --listen exclusion: TestCodexAppOwnServer.
  - Code 0 on Windows: TestEndExitsClean.
  - The row's notice: codex-app-out.test.cjs, 4 of 4.
- Real app: ChatGPT.app 26.1013 in a sandbox HOME/CODEX_HOME, with this
  build serving on 3492/3493. Codex was put on magpie as Sync does for a held
  account (model_provider = "magpie", codex.out in stash.json). OpenAI's usage
  reading to the app was never faked.
  - The first listing ran out at load ~200, so the timeout is now 30s. The
    next look ended the app-server, and the app started another 12s later.
    Its profile went from "Pro · Usage · Log out" to "magpie" with no reopen,
    and /api/state carried appOut.
  - Undoing it ended the app-server again, and the profile came back to Pro,
    Usage and Log out.
  - The owner's own ChatGPT app (its app-server on ~/.codex) was never
    touched.
- One webkit codex-app-out run at load 291 had one red subtest, name lost.
  It passed 3 of 3 alone and in two full webkit runs.

Not tried:
- The Windows Store app (not installed on the box), and a real Codex app
  on Linux.
- A real used-up account.
- A turn running in the real app while the switch happens (unit-tested
  only).
2026-10-27 15:57:41 +08:00
yetone 73d17f90ce codex: every CODEX_HOME folder's sessions count, its account renewed there
phantom3792 on X: with several ChatGPT accounts kept the way Codex
supports, magpie counted only the default profile's usage, and the
accounts added from the other profiles read no quota.

Codex's mechanism, from openai/codex at 970111f6cb62:
- One sign-in per folder. In codex-rs/login/src/auth/storage.rs the
  sign-in is $CODEX_HOME/auth.json, or the keychain item that
  compute_store_key(codex_home) names.
- Sessions live in the same folder. rollout/src/lib.rs writes sessions/
  and archived_sessions/ under codex_home.
- `--profile <name>` only lays $CODEX_HOME/<name>.config.toml over
  config.toml (config/src/loader/mod.rs), and the sign-in stays shared.
So a second account is Codex run with CODEX_HOME=~/.codex-work, and
magpie read only the folder it runs with.

There were two causes:
- Sessions: codexFiles() walked CodexDir() alone. The sessions list,
  traces and the usage ledger (sessions.Calls) never saw other folders'
  rollouts.
- Quota: an account added by importing another folder's auth.json is
  refreshed from magpie's copy. The import rotates the refresh token,
  which leaves two holders of one token, and whichever refreshes first
  signs the other out. The saved account goes "sign-in has expired" and
  its quota read fails.

The fix:
- appdir.CodexHomes finds the folders: CodexHome first, then folders
  named codex* or .codex* in the home folder or beside CodexHome, or
  one level down in one (~/.codex-profiles/work), that hold auth.json
  or sessions/.
- sessions: codexFiles and Dirs read every folder.
- provider: rememberLogins saves each folder's account with Home set
  to it (codexHomeLogins). The one ~/.codex is signed in to stays that
  folder's.
- renewSaved renews such an account where that folder's Codex keeps
  it (codexHeldIn, as heldByCodex does for ~/.codex). This one funnel
  covers quota, gateway, warm-up, keep-alive and revoked sign-ins.
  codexLoginAuth reads its expiry from the same place.
- switchSavedLogin, NextLogin's spares and forgetLogin leave such an
  account alone. Their errors name the folder and the
  CODEX_HOME=... codex command.
- docs/subsystems/providers-accounts.md gains a row.

Run (worktree at 42ab93551 plus this diff, sandbox HOME, pinned
caches, log kept whole):
- go test -tags nogui -timeout 45m ./internal/appdir/
  ./internal/sessions/ ./internal/provider/ ./internal/usage/
  ./internal/cli/: all ok.
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet on appdir, sessions and provider:
  clean. go vet -tags nogui ./internal/gui/: clean.

Rebased onto 13f907013, which changes internal/sessions only. At that
head, sessions and appdir passed in full, and provider -run 'TestCodex|Login'
passed.

Broken by hand, each red:
- codexOtherHomes returning nil: TestCodexOtherHomeAccountReadsQuota
  fails with the reporter's symptom ("sign-in has expired", refreshed
  with the copy's spent token).
- renewSaved without the home path: ~/.codex-work/auth.json is not
  renewed in place.
- switchSavedLogin without its refusal: ~/.codex/auth.json is
  rewritten to the other account.
- CodexDirs returning CodexDir alone: TestCodexOtherHomeSessionsCounted
  lists 1 session, not 2.

Not tried:
- A real second CODEX_HOME with real accounts. The fixtures copy the
  real auth.json shape and the rollout layout, not real tokens.
- A folder outside the home folder that isn't next to CODEX_HOME.
- Codex keeping the other folder's sign-in in the keychain (the reader
  is the same readCodexLogin per folder).
- An entry whose folder was signed out keeps Home and goes back to
  being refreshed from its copy.

Not done (#3530): Codex thread names (session_index.jsonl) and a
config sqlite_home are still read from CODEX_HOME only.
2026-10-25 07:42:13 +08:00
yetone ef37b6fb76 gateway: an exhausted ChatGPT account no longer greys Codex app's Send while magpie can serve the turn (MasterYi on Discord)
MasterYi (#help, 1563467829687222343): with magpie wired into the Codex
app, a used-up ChatGPT account greys the Send button, so the third-party
models joined in Codex's picker can't be used either.

Cause, as far as the app's bundled code (ChatGPT.app 26.1013.40934,
read-only) shows: Send is gated in the app itself. It needs
authMethod == "chatgpt", the /wham/usage reading (fetched by the app
straight from chatgpt.com, not through magpie) saying not allowed, and
no credits. authMethod is read as the app opens or on account/updated,
which the app-server sends only on login/logout, not on a config change.
So the gate lifts only when model_provider is magpie AND the app has been
opened again. #540 already made magpie the provider while out, but only
when a magpie model was the default; on one of Codex's own models
(joined), nothing changed.

What changed:
- A (agent/codex.go Sync): joined on one of Codex's own models and the
  account out (not Always ChatGPT, not magpie API), magpie becomes the
  provider on that model as magpie serves it (codex/<model>), the model
  kept in codex.out_own. Once the account has room, Codex is put back
  joined on that model. A model picked meanwhile stays the user's. With
  no ChatGPT account in magpie to serve it, nothing changes. New
  Agent.AppOut says magpie is the provider for a used-up sign-in.
- C (provider/codex_app_out.go): a usage_limit_reached rest on the
  active Codex account (gateway routing) or an x-codex-* window heard at
  100% (NoteCodexLimits) has the account read again at once
  (CodexMayBeUsedUp: active account only, at most every 20s, only
  while a KeepOnAnAccountWithRoom loop has made its first reading and
  still runs), not only on the 5-minute look. A first cut turned this
  on for good as the loop started; every gateway test's Serve starts
  it, so later gateway tests had accounts read again behind them, and
  TestCodexOwnModelMovesToNextAccount and
  TestCodexSpentMovesToNextGroupMember went red in the package run
  (green alone 3 of 3). Now a counter, up after the first minute's
  reading, down as the loop ends; the package run is green with it.
- B (gui/codex_app_out.go): the app open when the account ran out is kept
  by its app-server's pid (provider.CodexAppOut; a new pid means it
  reopened and read the provider, standing in for "authMethod is still
  chatgpt"). On macOS, every 10s, magpie reopens it through the Agents
  row's ReopenCodexApp when: AppOut, the account still out, the app is a
  copy from before the config change, no turn in flight through the
  gateway and none ended in the last 30s. At most once per time the
  account runs out, success or not.
  Drafts: the app's code keeps composer drafts in a persisted store
  (composer-prompt-drafts-v2, 250ms debounce, flushed on quit), and
  threads are server-side, so an unsent draft and open threads should
  survive the quit. Not watched in a real app.
- D (GUI): Codex's accounts say "The Codex app can't send on {user}'s
  used-up account": on macOS that magpie reopens it once no turn runs;
  off macOS (no reopen path) or once tried, to quit and reopen it.
  en, zh, zh-TW, ja, de.

Tests (each red on the code without its part, broken by hand):
- TestCodexOwnModelGoesThroughMagpieWhileUsedUp: red at "used up" with
  the out case off, at "allowance back" with the restore off.
  TestCodexOwnModelKeptOnChatGPT: Always ChatGPT stays.
- TestCodexMayBeUsedUpReadsAtOnce: red at "a window full: not read"
  with the NoteCodexLimits hook off. TestCodexAppOutEpisode.
- TestCodexUsedUpReplyAsksAtOnce (gateway): red, asked [], with the
  routing hook off.
- TestCodexAppOutReopenedOnce (gui, reopen stubbed): red at "a turn in
  flight" with the idle check off, and at "again" with the once checks
  off.
- codex-app-out.test.cjs: 40 of 40 (chromium, webkit; 900/480; five
  languages; both texts); 2 of 2 red with the notice's call site off.

What was run, at this tree:
- gofmt -l: none. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: exit 0.
- go test -tags nogui -timeout 45m: internal/agent ok (414s, before a
  comment-only reorder in Sync); internal/gateway ok (534s),
  internal/gui ok (78s), internal/provider ok (137s), after the
  live-check fix, at this tree before the previous commit's JS-only
  move (then with a budget raise since taken back); internal/gui
  again after the move.
- GUI (chromium, webkit), at this tree: codex-app-out, codex-app-stale,
  i18n-keys, gui-de, gui-ja, gui-zh-tw and the files reaching the
  previous commit's move: 164 of 164. Before the trim, every codex-*
  and account-* file: 447 of 448; the red, codex-predictions chromium
  ja 420 "picking a model scrolled the page", is #2624 and is red alone
  on origin/main 5a85a2a91 too (1 of 2); one codex-app-out case timed
  out launching chromium at load ~100 and passed on the rerun.
- TestCoreScriptBudget with the budgets unchanged: ok. The three Codex
  notices now share one box builder (codexNote), and the previous
  commit moved ledSaid out of app.js.

Not tried:
- No real Codex app was quit or reopened (the owner's live app is left
  alone); the reopen path is stubbed. Whether the reopened app's Send
  comes back, and whether a draft survives, is from reading its code.
- No real used-up account; the move was run in a sandbox HOME.
- The full suite: no suite lock on this machine, load ~75.
- A gateway served by another magpie process: the episode lives in the
  process that serves the gateway, so a GUI that doesn't serve it never
  reopens the app or shows the notice.
2026-10-24 17:38:50 +08:00
yetoneandggbdpq 58651568b3 agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they
didn't parse, and the next save wrote that emptiness over them. What
magpie had applied to each agent, the WSL distros and the WSL session
listing were lost with no copy. stash.json already kept a bad file aside
as .bad-<time>. Each of these now does the same through one helper,
lastgood.KeepUnparsed, instead of a copy per file:
- It does nothing when the file is missing or empty.
- When the file doesn't unmarshal into the reader's own type
  (lastgood.Into[T]), it copies the file aside (KeepBad).
- It stops the write when the copy can't be kept.

This also fixes the issue's claim about stash.json. Stash judged a file
with json.Valid, so `[]`, which a map reader takes as empty, was written
over unkept. Its failed copy was only logged, and the write went ahead
anyway. Both are fixed (TestUnreadStashArrayKeptAside), and
gateway-hidden.json uses the same helper.

Siblings found by going through every single-file JSON reader that takes
a bad file as empty and then writes it whole:
- stepfun-auth
- login-returns
- quota-history
- balance-history
- credits-daily
- Claude Desktop tiers
- plugin updates
- usage's computer id
- davsync's sync state

Each now keeps a bad copy. Caches that are rebuilt from the vendor are
left alone; docs/subsystems/providers-accounts.md lists them.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: on the code before this, these fail:
- the issue's applied_keep_test.go and wsl_keep_test.go
- TestUnreadStashArrayKeptAside
- TestUnreadStateKeptAside (10 subtests)
- the gateway, usage, davsync and plugin _keep tests
TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the
helper.

I dropped a test, "not written when it can't be kept", for stash. It passed
on the old code too, because a read-only folder also stops the atomic
write.

Not tried: a real WSL distro.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:26 +08:00
yetone 75cbc7e1e5 provider: a subscription switched off or removed makes no background requests, no claude auth status every minute (Riko on Discord)
Riko switched Claude off in Providers, and magpie still ran
`claude auth status --json` about every minute. Off only kept the
gateway from routing to it. Every page and request lists accounts,
which re-asked the CLI, and the background loops went on reading
allowances, renewing, switching, warming, checking in and fetching lists.
The same held for each sibling with a CLI or account check: Cursor
(`cursor-agent about`), Devin (`devin auth status`) and the rest.

What changed:
- left_alone.go: leftAlone(id), true for a provider that is Off or
  Hidden (account removed).
- account.go claudeIdentity and cli_identity.go get (Cursor, Devin): the
  CLI isn't asked; what it said last (memory or cli-identity.json) is
  served, so the account stays listed to switch on again.
- subscription_usage.go: claude, cursor and grok are checked as hidden
  before their account is looked up (the look-up ran the CLI).
- login_usage.go loginUsageAt, keepalive.go RenewLogins,
  codex_switch.go NextLogin, codex_warmup.go keepWarm: leftAlone where
  only accountRemoved (or nothing) was checked.
- models.go newDue: a provider that is off has no list fetched.
- checkin.go: each check-in account knows its card's provider; the loop
  skips one that is left alone, a press still checks it in (minimax,
  trae, qoder, workbuddy, plugin check-ins set it).
- docs/subsystems/providers-accounts.md says so.
Not covered: KeepPluginsListed lists every plugin at once in the host. A
Cursor switched off that was never asked who is signed in isn't listed
until switched on.

What was run:
- TestLeftAloneRunsNoCLI: fake claude, cursor-agent and devin on PATH log
  each run; with claude and cursor off and devin removed, All, Hidden,
  fetchSubscriptionUsage, LoginUsage, RenewLogins, SwitchWhenSpent and
  FetchNew run three times over stale caches and no CLI is run; switched
  back on, all three are asked again.
- Break check: with the source changes reverted it fails with
  "switched off or removed, the CLIs were run: [claude_auth_status_--json
  cursor-agent_about_--format_json devin_auth_status ...]"; with only the
  claude gate removed only claude is logged, with only cliIdentity's only
  cursor and devin.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway:
  ok (399s, 1271s).
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, under set -o pipefail.
2026-10-14 08:28:08 +08:00
yetone b1d8717107 provider: a switch of Claude Code's sign-in takes the account's own proxy into its env, and out again for one without (#1807)
kensenzhao signs Claude Code in to several accounts in direct mode and
gives each its own proxy in magpie (AccountProxies). Those proxies were
only ever honoured on what the gateway sends; Claude Code signed in to
its own subscription asks Anthropic itself, through the proxy its env
names, so a switch (by the user, or SwitchWhenSpent) left every account
on one route.

Decision: while the Claude subscription has a proxy for any of its
accounts, settings.json's env names the proxy of the account Claude Code
is signed in to: its own, else the subscription's (ProxyOfLogin, which
also covers the first account whose proxy is kept as the sub's, #1663).
None for "direct", and none for a SOCKS proxy, which Claude Code can't
use (logged). HTTPS_PROXY and HTTP_PROXY are written, with NO_PROXY set
to loopback so the gateway and local MCP servers are reached straight.
With no account proxy at all nothing is written: the subscription's
proxy alone was never Claude Code's, and turning it on now would change
every existing user's route unasked.

A proxy the user set themselves wins. magpie records the values it wrote
(claude-proxy-env.json beside providers.json) and a key is its own only
while it still holds that value; any proxy key that isn't (in either
case) means the route is the user's, so magpie writes none beside it and
takes out only its own. A NO_PROXY/no_proxy the user set stays. A
settings.json or record that can't be parsed is an error, never empty:
the file is left as it is.

It runs on every switch (switchLogin), on Save of the Claude
subscription (a proxy picked for the account it is on), and on the
gateway's 5-minute KeepOnAnAccountWithRoom tick (a sign-in made in
Claude Code itself). Claude Code reads its env as it starts, so running
sessions keep the old route; the log says which proxy new ones take.

Run: go test -tags nogui ./internal/provider (676s, ok) in a sandbox
HOME. TestClaudeSwitchTakesTheAccountsProxy fails with the sync call
taken out ("on b, HTTPS_PROXY = "", want b's proxy");
TestClaudeAccountProxyKeepsTheUsersOwn and ...EditedByTheUserStays fail
with the user-route check forced off, and EditedByTheUserStays with
ours() always true. gofmt -l clean; go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows; windows and linux builds.

Not tried: a real Claude Code session going through a real proxy after a
switch, and a remote LAN gateway's address isn't added to NO_PROXY.
2026-10-12 22:03:28 +08:00
yetone 4eb90b69f4 provider: after magpie switches Codex's account, Codex's accounts say the Codex app is still on the one before and to quit and reopen it (CavillZhang on X)
The Codex desktop app (ChatGPT.app 26.1007, bundled codex 0.162) reads
auth.json once, as its app-server starts. codex-rs AuthManager only
reloads it for the same account (reload_if_account_id_matches skips a
different one; a full reload is the app's own login/logout). So after
magpie's switch the running app keeps the spent account's token, its
webview reads /wham/usage with it (straight to chatgpt.com, which magpie
can't intercept), gets rate_limit.allowed=false, and hardBlocked stops
the composer in every thread with "You're out of Codex and Work usage".
Only quitting and reopening the app moves it.

magpie now notes, like the managed daemon, the app's own app-server
(…/CodexCLI.app/Contents/MacOS/codex … app-server, or the Windows Store
app's codex.exe) running at a switch and the account it holds, until that
process changes. Codex's accounts show "The Codex app is still signed in
as …; quit it and open it again" with Got it; `magpie accounts` and the
gateway log say the same.

Run: go test ./internal/provider ./internal/gui (TestCodexAppStale goes
red with the app not noted), the new GUI test in Chromium and WebKit, en
zh zh-TW ja de, 900 and 480px; findCodexApp against the owner's running
ChatGPT.app found its app-server; go vet darwin/linux(nogui)/windows,
go build.
2026-10-10 13:41:59 +08:00
yetone 62b1c995ff provider, codex: an account the Codex app holds is switched off whatever its windows read, and never switched to (CavillZhang on X: "out of Codex and Work usage", some accounts not switched)
A Business seat at its workspace owner's limit (rate_limit.allowed false,
no credits) reads, say, 40% on every window, so NextLogin never counted it
spent: Codex said "You're out of Codex usage" and magpie kept it there. It
could also move Codex onto, or back to, a held account.

NextLogin now treats SubscriptionQuota.Held (codexHeld) as spent: moved off
at any share, skipped as a spare, and not gone back to while held.

The test TestCodexHeldAccountSwitchedUnderTheShare was already on main,
unfinished and failing (swept into 34a59837 from a stalled session's
working tree); this finishes it: all held -> stays; a spare freed -> moved
to it; not back while the first is held; back once it has room. It fails on
the old NextLogin. go test provider, gateway; go vet darwin/linux/windows;
gofmt -l clean. Not tried with a real held Business seat.
2026-10-09 14:24:50 +08:00
yetone 34a598372c providers, gateway, gui, cli: each usage window of an account can have a cap of its own beside the account's (willz on Discord)
willz asked for a cap per window: a friend's account should stop at 50%
of its five hours, while its week has its own 40%. Until now an account
had one usage cap, the same share of every window.

What the user sees: the account's pill still sets the cap for all its
windows and stays the default. Each window's meter on the account's row
is now a button: a click opens the app's own menu headed "Cap for
<window>" with the account's cap, No cap on this window, 50–90%, and
Other… typed in place. A window with its own cap says it beside its
figure ("Cap 50%", or "No cap"), its mark sits there, and the account's
pill says "Caps by window" when only windows have caps. The account is
held while any window is past its own cap, and the row's note, the
gateway's 429 and the Routing trace name that window's cap. CLI:
magpie provider account-cap <id> <account> --window "5 hours" 50
(none: no cap on that window; default: back to the account's), and
`account-cap <id>` lists the overrides.

How: Provider.AccountWindowCaps (providers.json, by account and the
window's capId, its name in lower case; 1–99, or 100 for none) beside
AccountCaps. provider.WindowCaps gives a window its share (its own, else
the account's); Allowance.CapHeld and capReached judge each window by
its own share and report the fullest holding window's cap.
provider.HoldShare becomes HoldCaps, used by gateway capHeld (plan and
group filtering, cappedError, trace) and codex_backend's route-or-relay
choice; codex_switch's NextLogin moves the agent off at per-window caps.
QuotaWindow carries capId; Limit.name is exported as Limit.Name. A
config with no window caps reads and routes exactly as before
(TestSetWindowCap reads an old one). The meter is a span with
role=button, Enter/Space: a <button> as a flex item of the wrapping
meter line kept WebKit's row at its one-line height until the next
layout, so the row grew under the pointer at the first click.

Verified:
- go test -tags nogui ./... in a sandbox HOME: all ok. New
  TestWindowCapHeld and TestSetWindowCap (provider), TestWindowCapsHoldTheAccount
  through the real gateway (5h 60%/cap 50 goes to the spare; 20/30 under
  50/40 is used; 20/45 with the spare past its own cap is a 429 naming
  "past its 40% cap"), TestAccountCapCmd --window cases.
- Break check: with WindowCaps.Of ignoring the window's own share,
  TestWindowCapHeld fails ("5 hours at 60% of 50%: <nil>") and
  TestWindowCapsHoldTheAccount fails (the request is answered 200 by the
  capped account).
- internal/gui/tests/window-cap.test.cjs: Chromium and WebKit, 420 and
  1100 wide, en, zh, zh-TW, ja, de (60 tests): held note per window,
  marks, menu from the meter with no native select, keyboard, posts of
  50, typed 45, 100 and 0, no page scroll on a click, no sideways scroll,
  no left border stripes, every new string translated. With
  windowOwnCapOf returning 0 it fails.
- account-cap, gui-zh-tw, gui-ja, gui-de, i18n-keys pass; full GUI suite
  in both engines (483 files, concurrency 6): 4315 of 4323
  pass; the 8 that failed (library-servers-bulk, purpose-filter,
  routing-proxy, routing-zcode-blocked) touch no account row and all 32
  of their tests pass when run alone
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux and windows,
  and windows without the tag for ., internal/gui, internal/provider,
  internal/gateway; go build ./...
- Not tried in the real window with a live gateway or real accounts.

Docs: gateway-routing.md (HoldCaps, window caps, tests),
providers-accounts.md (AccountWindowCaps, tests), reference.md.
2026-10-09 12:00:26 +08:00
a2c3905368 provider, gateway: a usage window whose reset has passed is renewed on every path, and an account resting out of it is back once a reading finds it renewed (#1200)
* provider: a usage window whose reset has passed is renewed on every path, so a fresh Claude /usage reading at 100% a minute after its reset no longer counts the account spent or moves Claude Code off it

Claude Code's /usage gives a reset to the minute and can lag it, so a run
just after a reset can still say "100% used · resets <a minute ago>".
claudeWindows handed that fresh reading back raw while its cached and
header paths already went through elapsed, and usedPast judged Used
without looking at ResetsAt. NextLogin dropped passed windows only for a
Claude reading kept from before (AsOf) and only for the account the agent
is on, not for the account to go back to or the spares.

- claudeWindows: the fresh /usage path returns its windows as of now
  (elapsed), as the cached and header paths do. What is kept in
  claudeUsage stays as read.
- resetPassed is the one test for a window that has started again.
  usedPast, usedUp, UsedUp and BackAt take now and leave such a window out,
  for Codex and Claude Code alike; NextLogin's Claude-and-AsOf special case
  goes, since every account it looks at (on, back, spares) is now judged
  that way. capReached already was.
- quota_last's reading still decides whether a Codex hold came with a
  used-up window from the reading as it was read (usedUp at the zero time),
  so the hold ends when that window starts again, as before.
- magpie quota wait and the Codex expiring resets pass their own now, so
  quota wait no longer waits out a window that has already reset.
- docs/subsystems/providers-accounts.md says so, and that a reset /usage
  gives as a time alone ("resets 3pm") is read as its next one by
  claudeResetTime, which this change can't see as passed.

Verified under a temporary HOME with GOPATH, GOMODCACHE and GOCACHE
pinned: go vet ./..., go build, GOOS=linux go build -tags nogui and
GOOS=windows go build pass. go test -tags nogui ./... passes except
internal/gui's TestSetAnswersWhileDevinAndProvidersHang once in the full
run (set slow/slow-1 took 1.67s against its 1.5s limit, with other
sessions' suites running); it passed -race -count=20 on this branch and on
upstream/main, and internal/gui passed on its own. go test -race -count=20
on the new tests passes.

New tests (window_renewed_test.go) and what fails without the change:
- TestFreshClaudeReadingPastItsResetIsNotSpent: with the fresh path
  returning raw ws, "the session reads 100% (reset ... 14:20:00 UTC)". The
  control with its reset an hour away is spent and moves to the spare.
- TestNextLoginTakesAPassedResetAsRenewed (codex and claude): with usedPast
  and BackAt ignoring ResetsAt and the old AsOf drop back, NextLogin moves
  off an account whose full window reset a minute ago (fresh, and for Codex
  kept), won't move to a spare or back to the first whose full window has
  reset; the controls with resets an hour away are unchanged.
- TestUsedUpLeavesOutARenewedWindow: with BackAt and usedUp ignoring
  ResetsAt, "a window reset a minute ago stops the account".
TestClaudeUsageExpiredReadingDoesNotSwitchAccounts and TestCodexHeld* pass
unchanged. Not tried against a real Claude or Codex account here.

* provider, gateway, docs: a subscription account resting out of its window is back once a reading finds it renewed

A Claude account rested for a full five hours or week waited out the whole
rest (the time Claude Code's refusal named, or c.full), even when a new
/usage reading or the reset passing showed the window started again: only
a Codex reset spent and a key's reading ever told OnRenewed.

provider: Allowances, the reading routing goes by for every account,
keeps each account's last reading and when it was taken (usedCache.seen,
kept through a failed reading). A new reading that finds the account full
till sooner than the last (renewedFrom, the rule keyAllowances' keep uses
for keys) tells OnRenewed as the agent its usage is read under
(Account.UsageAgent: "claude", or "plugin:<id>" for a plugin-served
subscription) and the user. Scopes are the whole account, and each pool of
some models with the whole account's windows over it. A window used below
SpentShareOf its routing, or whose reset passed, is full no more; one full
with its reset unknown is full for good. Only windows in both readings
are compared. So a first, failed, alike or partial reading tells nothing,
nor does a five hours renewed inside a used-up week, nor two windows of
one name. Hooks are told after usedCache is unlocked and before the
reading's waiters are released. renewedNow drops the account's seen
reading so a spent reset is told once.

gateway: renewed lifts only an account's rests out of quota or by
"window"; a rest for a rate limit, credit, verification or a failure
stays, as a key's already did. Before, it only ran for a Codex reset spent;
now readings reach it for every subscription.

docs: providers-accounts (Allowance step, test list), gateway-routing
(account rests lifted by a reading, test lists), reference (when an
account runs out).

Verified: TestClaudeAccountToldRenewed (a fake /usage: 100% tells
nothing, 99% tells nothing, 3% tells once, more use doesn't tell again; a
kept window whose reset passes tells once), TestPluginAccountToldRenewed
(plugin:fakeco; a failed reading in between, a reset spent, and a reset
passed while the vendor still says 100%), TestRenewedFrom (table, including
the five hours inside a full week and same-named windows), and
TestClaudeAccountBackOnceItsWindowRenews (gateway: a Claude account resting
by "resets" is back once a reading shows 4%, another still full keeps its
rest). TestQuotaRestsUntilItsReset now checks a rate-limit and a backoff
rest survive renewed. Without the tell, all three renewal tests fail (told
[], still rests by resets); mutating each branch of renewedFrom/fullTill
fails TestRenewedFrom or the plugin test. Under a temporary HOME: go vet
./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build,
go test -tags nogui ./... and go test -race -count=20 (the gateway test also -count=50) on the new and
changed tests pass. Not tried with a real Claude account.

Not covered here: once a /usage run prints Claude's limit refusal,
claudeWindows returns that error until /usage or a header succeeds again,
so Allowances skips the account and the reset passing tells nothing. That
path is claudeWindows' own; the change making passed windows count as
renewed there lets this tell reach it.

* gateway: a Codex subagent's sealed task goes back to the Responses provider that answered its lead (a Sub2API relay of the ChatGPT backend), relayed as it came, instead of being refused before it is asked; the refusal names who sealed it (#1109)

Codex on Ultra with s2a/gpt-6-astra for both the lead and the subagent,
s2a a Sub2API relay: the relay's ChatGPT backend sealed the lead's
spawn_agent task, and magpie turned the subagent away because only a
Codex account counted as able to read it, telling a user already on a
magpie model to "use a Magpie-served model for the lead".

The provider that answered the lead (leadProvider, from the lead
thread's affinity in any scope) now reads it too when it is a key
provider serving the model on Responses; the task is relayed, even
when Codex offers web_search (it was translated, which dropped the
agent_message's encrypted_content). A subagent on another provider, or
whose lead magpie never answered, is still refused before anyone is
asked, with a message naming the lead's provider when known.

Verified: TestSealedTaskGoesBackToTheRelayThatSealedIt (lead and
subagent on s2a/gpt-6-astra, with Codex's web_search tool) fails without
the change with the old 400; without only the relay part it fails with
the ciphertext dropped from the upstream request.
TestSealedTaskRefusedByAnotherRelay covers a lead on s2b and an unknown
lead. go test -race ./internal/gateway, go vet ./..., GOOS=linux and
GOOS=windows builds pass.

* codexcat: a third-party entry for a model Codex has its own entry for (s2a/gpt-6-astra) says the same multi_agent_reasoning_effort, so Codex's Ultra sends xhigh for it as for OpenAI's gpt-6-astra instead of falling back to max (#1108)

Codex resolves Ultra to the entry's multi_agent_reasoning_effort, and to
max when the entry has none and lists max. magpie's entries never carried
the field, so the same model ran at max through a relay and at xhigh
through the ChatGPT account. The value is taken from Codex's own entry in
models_cache.json for the model's slug (after the provider prefix and a
dated snapshot suffix), only when the third-party entry offers Ultra and
the effort itself; models whose own entry says nothing (gpt-6-sol today)
keep Codex's max. The gateway's literal "ultra" -> max mapping is
unchanged: Codex sends the resolved effort, not "ultra".

TestUltraEffortAsCodexOwnEntry, built from the reporter's entries, fails
without the change ("s2a/gpt-6-astra: multi_agent_reasoning_effort <nil>,
want xhigh"). go test -race ./internal/codexcat ./internal/gateway
./internal/agent and go vet ./... pass in a sandbox HOME.

* gateway: a DeepSeek model whose Codex request is passed through as it is (OpenCode Go's deepseek-v4.1-flash) gets its reasoning back as reasoning_text, and is never asked without it (#1104)

Codex hands a reasoning item back as it got it; one from a turn magpie
translated, or another provider in a mixed group served, has only its
summary. Passed through to OpenCode Go's /responses, DeepSeek refused the
request with "The `reasoning_text` in the thinking mode must be passed back
to the API". That refusal names the input, so passthrough asked once more
without every unsealed reasoning item (withoutBareReasoning) and marked the
model as refusing them, which left the reasoning out of every later request.
For a model that wants its reasoning back (replaysReasoning, the predicate
#388's buildResponses uses), a reasoning item without reasoning_text now
gets its summary as one, and withoutBareReasoning is never applied to it.

TestDeepSeekReasoningPassedThrough plays OpenCode Go with the reporter's
error word for word. Without the change it fails ("reasoning_text sent =
\"\", want the summary"); with only the strip guards taken out it fails ("a
reasoning item with nothing in it was answered"). go test -race
./internal/gateway, -race -count=10 on the new test, and go vet ./... pass.

* agent: a catalog sync or a model pick keeps the keys a user or another tool added to magpie's provider block (Pi's providers.magpie.compat.sendSessionAffinityHeaders from pi-cache-optimizer) instead of writing the block whole (#1103)

syncJSON and Pi's writeMagpie set providers.magpie to a freshly built
object, so a key magpie doesn't write there was dropped on every sync.
theirsKept now merges magpie's block into what the file holds: keys magpie
writes are its own, objects in both are merged key by key, and anything
else (compat, an options key, Crush's extra_headers) stays. The model list
is still magpie's whole, so a model gone from the catalog leaves it, and a
sync with nothing new writes nothing.

The same goes for every agent that writes the block whole: Pi and OmO,
Aside, Pencil, OpenCode (and the agents built on it), OpenChamber, Crush
and Command Code.

Verified: TestPiKeepsTheirKeysInMagpiesProvider (the reporter's
compat.sendSessionAffinityHeaders: true in Pi's models.json, through
SyncCatalog and a pick) and TestOpenCodeAndCrushKeepTheirKeysInMagpiesProvider
fail without the change ("compat.sendSessionAffinityHeaders dropped by the
sync", "opencode sync") and pass with it. go test -race ./internal/agent
and go vet ./... pass in a sandbox HOME.

* providers: a SiliconFlow key's card says SiliconFlow retired its balance query and has no API in its place yet, and that the balance and vouchers are on its console, instead of "410 Gone: {...}" (#1094)

SiliconFlow stopped /v1/user/info on 2026-08-14 (release notes, 2026.08.11)
and answers it with 410 {"code":20092,"message":"This endpoint is
deprecated and is no longer available.","data":null}. Its docs and release
notes name no replacement yet ("new interfaces will be announced
separately"), and the balance given before 2025-12 became vouchers, seen
under 余额充值 → 代金券 on the console. So the card now says that and links
cloud.siliconflow.cn (cloud.siliconflow.com for the international site). A
key SiliconFlow refuses (401 30014 "Token is invalid.") is still said as it
came, and a 200 is still read.

TestSiliconFlowRetiredBalanceQuery replays the reporter's literal 410 body
for both hosts, plus the real 401 body and the documented 200; without the
change it fails with `410: true 410 Gone: {"code":20092,...}, want it
retired and https://cloud.siliconflow.cn named`. go test -race
./internal/provider and go vet ./... pass. Not tried with a real
SiliconFlow key (none on this machine); the 401 body was read from the
live endpoint with a dummy key.

* gui tests: routing-failed-open measures the 400's row once the live page has followed the newest request and drawn its story

In WebKit the live cases read the row's top as soon as the list was there,
before the page had followed the newest request and drawn its story above
the list (.rt-log grows 17 → 104px), so the row was 87px lower by the click
and "picking the request moved the page" failed — with the test's own
commit's assets too (d6096e2f), so it is the test's timing, not a
regression. The test now waits for the newest row to be pressed and the
story's steps, then for the row's top to hold still, before clicking.

Before: webkit en/zh live failed 2 of 2 (row 524 → 611). After: 8 of 8
(chromium and webkit, en and zh, live and kept day), three runs.

* gui tests: profile-confirm finds and measures the home chip in one call, so a list drawn again in between doesn't read as a chip at 0

Under load "closing them leaves the chip where it is: 0 → 259" failed in
both engines: the chip's top before opening its details read 0 while a probe
right after read it at 259. The locator found the chip, the profiles list
was drawn again from the state that came back (renderProfiles replaces the
chips), and the evaluate then measured the detached old chip, whose
bounding rect is all zeros. The chip never moved; the test's two-step
lookup raced the redraw. top() now finds the chip and measures it inside
one page.evaluate.

Eight copies at once (chromium and webkit, en and zh, window and panel):
before 9 and 15 of 80 failed in two runs; after 80 of 80 pass.

* usage: in a narrow window the Requests table's account column keeps room for both source badges, where it cut off "Subscription" (since fdcdb5af, #860)

fdcdb5af's tighter fit capped .led .where at 110px. The account cell's
source badges ("✓ Official" and "Subscription" in English, ~149px) don't
wrap and the cell hides its overflow, so at 440px the second badge was cut
off at the cell's edge. The 110px cap now goes on the account's name
(.where-name, still cut with an ellipsis); the column keeps the tight
fit's 160px cap, enough for the badges.

session-identity's "both badges share one row below the account at 440"
caught this only when the machine was loaded: it measured right after
setViewportSize, before ledFit's frame had applied the tighter fit, so on
an idle machine it saw the 1200px layout and passed. It now waits two
frames and 100ms first. With that wait, the test fails on fdcdb5af's
assets (en, chromium and webkit: badge right 457 > cell right 410) and
passes on fdcdb5af^ and with this change. ledger-*, usage-ledger* (incl.
usage-ledger-fit, #860's) and session-identity pass in chromium and
webkit: 90 of 90.

* gui tests: purpose-filter doesn't count WebKit's "ResizeObserver loop completed with undelivered notifications" as a page error

webkit en and zh failed in the full suite and under load with errors ==
['ResizeObserver loop completed with undelivered notifications.']. Traced
with every ResizeObserver callback logged per frame: picking a purpose
shrinks the Usage page from 100 rows, the click's hold (heldSizes in
app.js) gives the view room again before the paint, and the view's 8px
scrollbar coming back narrows #view-usage 1068 → 1060, so #ledWrap,
#ledChart, table.led and the Usage head are told a second time in the
same frame, past the loop's depth. The browser delivers that round on the
next frame; nothing is painted wrong. WebKit reports it as a page error,
Chromium doesn't. The test now ignores that one message, with the reason
beside it.

Eight WebKit copies at once: before, 1 to 3 of 6–8 failed with it; after,
16 of 16 pass.

* providers: an OpenCode Go or Zen provider saved with its chat URL alone sends GPT, Grok, Muse Spark and MiniMax on the API OpenCode serves them on, not chat, and "Model does not support this protocol" says which URL was asked (#1215)

The reporter's "OpenCode Go 1x" had only chat=https://opencode.ai/zen/go/v1
and no models.dev catalog (its native_endpoints were /v1/chat/completions
for every model). Go serves each model on one API of three, as models.dev's
per-model provider.npm says and OpenCode itself asks it (@ai-sdk/openai ->
/responses, @ai-sdk/anthropic -> /messages, the rest chat), so with chat the
only URL, gpt-6-luna, gpt-5.6-luna, grok-4.6/4.7, minimax-m2.7 and
muse-spark-1.2/1.3-contributor had nowhere else to go and Go answered 400
on all three of magpie's entry points.

- normalize fills in the other two of Zen's or Go's APIs (/v1 for chat and
  Responses, the root for Messages) and its catalog, only where the
  provider has none of its own (openCodeEndpoints); other hosts unchanged.
- ListedAPIs reads the per-model API from the list of the gateway the URL
  is at (opencode-go for /zen/go, opencode for /zen), whatever catalog was
  saved: Go and Zen serve MiniMax M2.7 on different APIs, and an import at
  /zen/v1 could be saved with opencode-go's.
- A wrong-endpoint error with no other API left now ends "(asked at <url>;
  <model> is served on /v1/responses, which <provider> has no URL for)".

Verified: TestOpenCodeGoModelsGoOnTheirOwnAPI (gateway, all 3 client APIs x
5 models through the handler) and TestOpenCodeEndpointsFilledIn fail without
the change with the reporter's exact "OpenCode Go 1x: Model does not support
this protocol."; TestOtherRelayKeepsItsOneAPI and the relay cases keep
other providers as they were. go test -tags nogui ./... green under a temp
HOME; go vet, go build, GOOS=linux/windows builds. Real upstream: probed
https://opencode.ai/zen/go/v1 with no key only (grok-4.7 is "not supported
for format oa-compat" on chat and "format anthropic" on messages, passes to
the key check on responses); no keyed request was made.

* gui: a routing group's rule by intent has its own entry, "Route by what it asks for" beside Add a rule, and a group whose effort Jev picks offers it under the classifier (CherryL1quor on X: 模型路由能不能用 jev,现在只有思考强度能用 jev)

An intent was one of a rule's seven conditions, so a reader who had Jev
picking the effort took it for that alone. "Route by what it asks for"
adds a rule with its intent box focused. Jev is picked as the classifier
when there is one, as the effort's Picked per turn already did, and the
classifier row shows at once, before anything is typed. Typing an intent
into any rule picks Jev too when no classifier is set. A group whose
effort Jev picks, with no intent yet, says under the classifier "It can
pick the model too: add a rule with an intent", which adds the same rule.
Translated in zh, ja and de.

routing-intent-entry.test.cjs (Chromium and WebKit, en and zh, 1100 and
440 wide) checks that both buttons stay inside the editor and that the
clicked one stays under the pointer as the rule comes in above it. It
also checks the focus, that Jev is picked, the save as
{use: b/flash, intent} with classifier typesafe/jev-latest, and the offer
under an effort-only Jev. It fails on the old assets (no such button).
gui-ja, gui-de, i18n-keys, click-scroll, routing-compact, -time, -save,
-save-blank, -effort-row, -effort-change, -levels, -days-fit and every
group-* suite pass (159 tests). Not tried with a real TypeSafe key.

* docs: Intent routing's setup names Route by what it asks for, Jev as the classifier with a TypeSafe provider, and the offer under a group whose effort Jev picks (en, zh, ja)

* proc: the login shell magpie asks for its PATH runs in a session of its own, so it can't take the terminal from magpie (DD on Discord: magpie web → zsh: suspended (tty input))

askShell ran `$SHELL -ilc` (and ReadCLI's zsh, bash and fish, for Settings › Command line; LoginPath for Library › RTK) in magpie's own session and process group. An interactive zsh puts itself in the terminal's foreground, so while it ran, magpie's group was in the background of the terminal it was started from: Ctrl-C no longer reached `magpie web`, and anything left in magpie's group that touched the terminal — the bash asked beside it, whose profile runs in magpie's group without job control, or another child — had the kernel send SIGTTIN to the whole group, stopping magpie ("zsh: suspended (tty input)"). Run with `&`, the user's own shell then got EIO reading the terminal and exited. A timeout also killed only the shell, leaving what its profile started holding the terminal.

The shell is now a probe (ProbeContext): it leads a session with no controlling terminal, and its timeout and EndProbes end its whole group. It still answers with its PATH and variables.

TestAskShellOwnSession (a fake shell answering with its process group; a real zsh still gives a PATH) fails without the change: "the login shell ran in magpie's process group …". Reproduced on a pty under an interactive zsh -f, temp HOME, MAGPIE_ADDR 127.0.0.1:47811, magpie web on 47812, ~/.zshrc `sleep 2`, ~/.bash_profile reading /dev/tty, GET /api/cli: the old build prints "zsh: suspended (tty input)  magpie web" in the foreground and "[1] + suspended (tty input)" with `&` (then "zsh: error on TTY read"); with a plain profile it loses the foreground (ps S+ → S). The fixed build stays S+ / running in both, and /api/cli still says zsh and bash are known. go vet -tags nogui ./..., GOOS=linux go build -tags nogui, GOOS=windows go build, and go test -tags nogui of internal/proc, internal/update, internal/library and internal/gui under a temp HOME pass; -race -count=10 of the new test passes. Not tried with DD's own profile, or on Linux.

* library: the skills market offers magpie's own magpie-quota skill first, marked official, so an agent can read what is left of every subscription, plan and key (magpie quota --json) and wait for allowance (magpie quota wait); it lives in magpie-community/plugins, and its card shows no installs or skills.sh link until skills.sh lists it (ttmouse on X: magpie quota works, suggested an official skill to go with it)

Verified: TestFeaturedSkills; market-featured-skill.test.cjs, Chromium and
WebKit, en/zh/ja/de at 520px, 8 pass (4 fail on the old library.js);
market-have and skill-online-local pass (34); a livemarket-tagged run of
InstallMarketSkill in a sandbox HOME fetched the real skill from GitHub
into the library; npx skills add magpie-community/plugins -l lists it.
go test ./...: all pass but TestSetAnswersWhileDevinAndProvidersHang
(2.8s under two other -count=5 suites); alone -count=5 passes.

* proc tests: TestAskShellOwnSession reads magpie's session with x/sys/unix, so the package's tests build on Linux (#1219)

bbf99143's test called syscall.Getsid, which Go's syscall package has on
macOS and the BSDs but not on Linux: go vet ./... (and every test run) on
Linux stopped at "undefined: syscall.Getsid", so the ubuntu Test job failed
at Vet on main and on every PR. golang.org/x/sys/unix, already required,
has Getsid on every Unix.

Verified: GOOS=linux, darwin, freebsd and android go vet ./internal/proc;
go test -run TestAskShellOwnSession ./internal/proc on macOS. Linux is run
by this PR's ubuntu job; there is no Linux machine here.

* library: a skill or server switched off for every agent is saved with "agents": [] not null, a check's finds beside skills on no agent come with [] too, and the Library page draws a find without its agents and says why when it can't draw a check's reply, where it threw on n.agents and went blank after Check for updates (#1217)

* library: installing a set of skills skips the ones in the way and installs the rest; the toast names the ones already in the library and the ones skipped (lc on Discord: 安装skills的时候,没有跳过已经安装的)

installFrom stopped the whole set at the first skill whose name was taken,
and returned before change saved library.json. The folders it had already
copied for the skills before that one stayed in the library's folder,
unlisted. Every later try then failed on the first of them with "the
library's folder already has a caveman-commit in it".

Now each skill is installed on its own (InstallSkills, InstallMarketSkill
and AddNewSkills, through installChange):
- the library lists it from the same source: had already (Result.Had),
  nothing written, so the user's edits stay;
- a folder in the library's folder holding exactly its files (not a link,
  sameTree, which counts a failed read as different): listed where it is,
  as had;
- another skill by that name, listed or only a folder, or a folder that
  can't be read: left as it is, in Result.Skipped with why;
- the rest are installed (Result.Installed). Only when nothing was
  installed or had does the change fail, with the first reason.
The GUI's toast and the TUI's line say how many were installed, the ones
already in the library and each one skipped with why.

Verified (temp HOME, pinned caches):
- go vet -tags nogui ./internal/library ./internal/tui ./internal/gui .;
  GOOS=windows go build and GOOS=linux go build -tags nogui of
  internal/library and internal/tui: clean
- go test -tags nogui ./internal/library ./internal/tui ./internal/gui: ok
- with the old skills.go, market.go and skillnew.go, TestInstallSetSkipsOneInTheWay,
  TestInstallListsItsOwnLeftoverFolder (fails with lc's exact "the library's
  folder already has a caveman-commit in it") and
  TestInstallSetSkipsAnotherByTheSameName FAIL; TestSkillsFromGitHub's
  reinstall now asserts Had
- skill-install-skip.test.cjs (Chromium + WebKit, en and zh at 440px) fails
  on the old library.js ("status ok", no names) and passes now; with
  gui-ja, gui-de and 11 library GUI files, 99/100 passed, and the one that
  failed (by-agent, Chromium, at load average ~150) passes 3 times in a row
  in both engines when run alone
- not tried in the real app, or with lc's library

* agent tests: Claude Code's haiku tier follows Claude Haiku 5.5 where a provider serves it beside Haiku 4.5 (Discord: using Haiku 5.5)

magpie keeps no list of Anthropic's models: the Claude subscription's list
is models.dev's "anthropic" provider (catalog.Provider, cached and
refetched daily), other providers' come from their own /v1/models, and the
code that knows Claude models (claudeLight, claudeEffortsFor,
claudeReadsTop, the gateway's adaptiveOnly) reads versions, not ids. So
claude-haiku-5-5 needs no entry: once a provider lists it, claudeLight
picks it over claude-haiku-4-5 and its dated id, and Claude Code is sent
every effort level for it, read from modelSettings only.

TestClaudeLightHaiku55 holds that, on an Anthropic-style provider and on a
router's dotted ids (anthropic/claude-haiku-5.5, as Vercel lists it). With
claudeLight's newest-first compare reversed it fails: claudeLight
("anth/claude-opus-5-5") = "anth/claude-haiku-4-5", want
"anth/claude-haiku-5-5". go vet -tags nogui and go test -tags nogui
./internal/agent pass under a temp HOME.

Not added: models.dev's anthropic provider doesn't list claude-haiku-5-5
yet (only Vercel's gateway does, released 2026-10-07), so the Claude
subscription won't offer it until models.dev does. No Bedrock id was given
or listed, so the Bedrock preset is unchanged. Not tried with a real
account.

* gui, tray, alerts, settings: magpie speaks Traditional Chinese (繁體中文) with Taiwan wording, picked on its own for a zh-TW, zh-HK or zh-Hant system

Settings → Language offers 繁體中文 beside 简体中文. On System, a
browser or OS locale of zh-TW, zh-HK, zh-MO or zh-Hant (zh_TW.UTF-8 too)
shows zh-TW; zh-CN, zh-SG and zh-Hans-HK keep Simplified. The tray menu
and quota alerts follow the same choice. Release notes fall back to
Simplified.

The zh-TW strings are generated from the zh strings with opencc
(cn→twp), then corrected to Taiwan wording: 設定, 檔案, 帳號, 伺服器,
預設, 閘道, 連接埠, 參數, 選單, 透過, 取得, 用戶端, 存取, 終端機, 「」
quotes. A quota window is 時段 and a context window stays 上下文視窗.
Number units use 萬/億, and #unitsRow is shown for zh-TW.

Verified:
- New gui-zh-tw.test.cjs, in Chromium and WebKit:
  - key parity, placeholders and tags against zh;
  - no Simplified characters;
  - the Taiwan words;
  - locale detection for each system tag;
  - <html lang>, nav labels, fmtN units, the picker;
  - Settings Language at 1000px and 440px.
  With the sysLocale zh-TW line removed, it fails. On the base assets,
  all 3 fail.
- gui-ja, gui-de and i18n-keys pass.
- go vet, and go test -tags nogui for ./internal/gui and
  ./internal/settings, pass. That includes the new zh-TW cases in
  TestTrayLang / TestTrayLabels / quota_alert_test, which fail without
  the zh-TW branches.

* gui: zh-TW gets the four strings added beside it — Route by what it asks for, its hint, and the skill install's already-in-the-library and skipped notes

* provider: moved Devin users get the plugin's 0.1.9, which sends a tool whose parameters have a root anyOf, oneOf or allOf as a plain object, so Devin's Claude models no longer answer 502 to Codex desktop's automation_update (#1196)

* gateway: the built-in Devin sends a tool whose parameters have a root anyOf, oneOf or allOf as a plain object, as the plugin's 0.1.9 does, so Devin's Claude models no longer answer 502 to Codex desktop's automation_update for users still on the built-in (#1196); provider.ObjectRoot keeps the root's and allOf's own required fields beside anyOf/oneOf branches, which only add the fields every branch requires (it used to intersect them away)

buildDevin folds every offered tool's parameters through objectSchema
(provider.ObjectRoot, as anthropic.go does for #646); a schema with no root
combinator goes byte for byte as it came.

TestBuildDevinObjectRoot builds from #1196's literal parameters with oneOf,
anyOf and allOf; without the devin.go change it fails ("oneOf: sent {...
oneOf ..."). TestObjectRootKeepsOwnRequired fails on the old ObjectRoot with
"required = [id n]" (allOf's "kind" dropped). Run: go test -tags nogui
./internal/gateway ./internal/provider (temp HOME, pinned caches), both ok;
GOOS=linux and GOOS=windows go vet -tags nogui on both packages, ok. Not
tried against a real Devin account.

* gui: the subscription windows' fit (stacked under the name or beside it) is decided on the next frame, not in its ResizeObserver's own call, so WebKit no longer reports a ResizeObserver loop as a page error (account-mask)

* context: magpie inspects the context window of every request, session and agent

The gateway reads each request's prompt into its parts (system prompt,
tools and MCP servers, memory, files, tool results, chat), measured
against the model's window and calibrated to the tokens the vendor
counted. Routing shows a request's window as a card: a 400-cell grid by
part, a hover naming what is largest in a cell, and the contents by part.
The Usage page's Context tab scores each agent out of 100 (cache reuse,
how lean it starts, how fast it grows, how reliably it answers), tags it
(lean, cache-friendly, mcp-heavy, compacts, near-full…), and draws each
session's growth with its latest request's card.

Older Safari (15) gets media-query and solid-colour fallbacks for the
card's container queries and color-mix.

* provider: Volcengine plans use their preset models instead of /models (xyenon) (#1216)

Coding Plan's /models returns Ark's general catalog, while Agent Plan's
returns 404. Skip their model-list requests and ignore old fetched lists,
including their protocol and key restrictions. Pay-as-you-go and an
explicit list URL still fetch normally; saved model choices stay intact.

Both plan endpoints were checked with real keys. TestVolcengineModelLists
fails without the no-list behavior and passes with it. Vet (gtk3) and
Linux GUI/CLI and Windows builds pass under a temporary HOME. The full
nogui suite passes except TestCodexArchivedSameSizeRewriteInvalidatesDiscovery
in sessions, also reproduced separately with -race -count=20.

Amp-Thread-ID: https://ampcode.com/threads/T-01a11791-db8b-7229-ade8-5e3600b835fc

Co-authored-by: Amp <amp@ampcode.com>

* gui tests: fold-show-grip measures Show and the picker once the fold's rows have slid in, in one read, and reads the grips from the page as drawn now

The fold's rows open with translateY(-10px) scale(.985) over .56s after a
staggered delay. The test read Show's box and the picker's box in two round
trips while the row still moved, so the second read landed lower (Show
355.7 vs picker 361.3): it failed in 3 of 4 runs alone, in either engine.
It now waits for the fold's animations to finish and reads both boxes in one
evaluate. The Usage page's cards are drawn again as its reads come in
(Chromium: three grips within 35ms of the first), so the grip's style and
the card, grip and logo boxes are read from the page in one call rather
than through a handle that may already be replaced. The hover-only grip is
unchanged.

* gui tests: api-key-theme finds where Settings' sharing On is in one read, so a #lanList drawn again in between doesn't read as no box

Settings opened on Network reads the settings twice (show("settings") and
load() after /api/state), and each draws #lanList again, 20-50ms apart.
The test waited for On, then asked its box in a second call; under load the
button it had found was already replaced, boundingBox() was null and the
test threw "Cannot read properties of null (reading 'y')". With #lanList
drawn again every 1ms for 600ms after it first shows, the old test fails
that way in Chromium and WebKit; this one passes.

* usage: a GLM Coding Plan key's card on bigmodel.cn or Z.ai shows its reset cards, five-hour and weekly, counted from customer-package-reset/list (targetType=PERSONAL) as the vendor's usage page counts them: only those still available; a list that can't be read shows none, never 0. Read only, never spent from magpie (#1191)

The list is asked with the plan's key, bare in Authorization, at the host its
term (subscription/list) is asked at, so open.bigmodel.cn and api.z.ai alike;
a ZCode account on the built-in gets the same. The tooltip says "The plan's
resets" for a person's own, "The team plan's" for a team's (ResetCredits.Team).

Tested: the reporter's literal reply (ids and times filled in, same shape)
in TestZhipuPersonalResets, TestPlanQuotas and TestZCodeAccounts, each
failing with the change reverted; reset-each-title in Chromium and WebKit,
en/zh/ja/de; a real Z.ai key through zhipuPersonalResets (1 five-hour,
1 weekly). Not tried: a real bigmodel.cn key.

* ci: the GTK and WebKitGTK install on Linux gives up after 15 minutes, where a stuck apt held main's Test run for 2.5 hours (b0d456c3) and every later push queued and was replaced behind it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* library tests: skillnew_test.go's imports are gofmt'd (Gofmt red on main since bb8a3e30, run 37693090857)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* davsync tests: the slow transfer's line is narrow both ways, so a download on macOS doesn't burst through the tuned-up buffers past the 300ms watchdog (TestSlowTransferIsNotCutShort red on macos-latest in main's run 37693090857: "took nothing for 300ms (GET)"; b1cba654 narrowed only the upload's way)

* plugin: a failed write to the plugin host ends the host before its caller hears of it, so a call freed by the failure finds the host already gone (TestHostWriterFailureWakesWaiters, red on macOS CI) (#1214)

* provider, gateway: a Claude /usage reset with no year is read within its window, so a reading a few days old no longer benches an account for a year (#1212)

* provider: a Claude reset read in the hour the clocks repeat, or the night they skip it, is the coming one, and a Dec 31 with no year read just after New Year is last year's

claudeResetTime turns /usage's reset text into the ResetsAt of the
"5 hours" and "7 days" windows, which smart routing orders accounts by and
rests a full account until.

- Where the clocks go back and read a time twice, time.Date gives either
  instant: the first west of UTC, the second east of it. Each reading is
  now considered (nextReading), and the one not yet past is taken.
  Before, at 2026-11-01 01:20 EST (the second 01:20), "Nov 1, 1:30am
  (America/New_York)" was 01:30 EDT, 50 minutes past, so a full window
  read as renewed; "1:30am" was 24h10m away instead of 10m. In Berlin at
  02:20 CEST on 2026-10-25, "2:30am" was 02:30 CET, 1h10m away instead of
  10m (Sydney and Lord Howe alike).
- A date with no year is in the first of last year, this year and next
  that is less than a day past, as the doc comment already said. Before,
  only this year and next were tried, so at 2027-01-01 00:00:05
  "Dec 31, 11:59pm" was 2027-12-31, 8760h away, and a 7-day window that
  had just renewed read as renewing in a year.
- A time alone the clocks skip today is the next day that has it,
  rebuilt from the clock read rather than from the normalized time.
  Before, the evening after New York skipped 02:00-02:59, "2:30am" was
  tomorrow's 1:30am; at 23:31 before Santiago skips midnight, "12:30am"
  was 23:30 that night, a minute past, instead of 00:30 the day after
  tomorrow.

What Claude Code prints, from the /usage formatter in the 2.1.290 binary:
every line of `claude -p /usage` carries a date, with the year only when
it isn't this one, so the New Year case needs /usage run just before
midnight and parsed after, and the repeated hour shows in the dated form.
Whether "at" or a comma joins date and time follows the platform's ICU,
and both are parsed. A time alone is the older form, which the TUI still
prints for the session within a day.

No other parser in internal/provider fills in a missing date or year:
zhipuTime and mimoTime read full dates in UTC+8, and the rest read
RFC3339 or Unix times.

Verified:
- TestClaudeResetTimeAroundClockChanges and TestClaudeResetTimeAtNewYear
  are new. With upstream's claudeResetTime put back, 15 rows fail, e.g.
  `"Nov 1, 1:30am (America/New_York)" at 2026-11-01 01:20:00 -0500 EST:
  2026-11-01 01:30:00 -0400 EDT true (in -50m0s)` and `"Dec 31, 11:59pm
  (America/New_York)" at 2027-01-01 00:00:05 -0500 EST: 2027-12-31
  23:59:00 -0500 EST true (in 8759h58m55s)`; the 16 controls pass. With
  the change, all pass, as does TestParseClaudeUsage, also with
  -race -count=20.
- An oracle that lists every instant a zone shows a clock at was swept
  over 518 zones, every transition 2025-2030, 85M calls: no deviation in
  anything Claude Code can print. What remains is Feb 29 in a non-leap
  year and dated times the clocks skip, both unchanged from upstream.
- Under a temporary HOME with GOPATH, GOMODCACHE and GOCACHE pinned:
  go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build, go test -tags nogui ./... all pass.
- Not run: claude -p /usage on a real account across a clock change or
  New Year.

* provider: a Claude reset further ahead than its window can reach is the one already past, so a /usage reading days old no longer rests an account for a year

claudeResetTime now gets the window's length (5 hours for "Current
session", 7 days for "Current week ...") and never reads a reset further
ahead than that plus claudeResetSlack (2h, for this machine's clock being
behind Anthropic's; Claude Code prints the reset from Anthropic's instant
with seconds dropped, so never later).

- A date with no year is in the first of last year, this year and next
  that is less than a day past and within the window. Before, it was the
  first less than a day past: read on Oct 5, a week's "Oct 1, 3pm" was
  2027-10-01, 8667h away, and routing (candidate.full, Allowance.Full)
  rested a full account that long. Now it is 2026-10-01.
- Where no year fits, the latest year where it is already past is taken,
  rather than dropping ResetsAt. The date read fine, and the window's
  length rules out every later year, so the reset has passed and the
  window has renewed, which is what elapsed() does with a past reset.
  Dropping it would keep a 100% window with no time to clear it: Pooled
  counts a full model window with no reset as out, so Opus on the account
  stayed refused until the next read, and the card showed 100% with no
  reset.
- A 5-hour window's date 6 days ahead ("Oct 11, 3pm" on Oct 5) is likewise
  last year's and reads as renewed; a week's keeps Oct 11.
- A time alone (the older form) is the next one within the window, else
  the latest day where it is already past: at noon, "11am" is today's for
  the session (was tomorrow's, 23h on) and tomorrow's for the week.
- A fresh /usage read now goes through elapsed() as a kept one does, so a
  reset it gives as past reads as renewed at once. Before, only the next
  look did, and the switch (NextLogin's usedPast) and quota alerts saw the
  fresh 100%.
- Dates with a year are unchanged.

Tests: TestClaudeResetTimeWithinItsWindow covers the cases above, the
inclusive bound (exactly span+slack is kept, a minute more is not, for a
date and a time alone), a week across New York's fall-back, and
claudeWindows' fresh and kept reads of a 4-day-old reset (Used 0, no
reset, Full zero). The DST rows and the other New Year rows pass
unchanged, at the week's length. Changed existing rows, each of which
asserted a reset further ahead than any window reaches: TestParseClaudeUsage's
"Current week (Opus) ... Jan 2 at 2pm" read Oct 1 (now 2026-01-02), the
#631 "Jan 2, 9:05am (UTC)" row (2026-01-02), and the New Year "Dec 30,
11pm" read Jan 1 01:00, 26h past (2026-12-30, not 2027-12-30). The #631
format rows are read on Oct 3 instead of Oct 1, so "Oct 9, 2:59pm" stays
within its week. Fixtures that gave a 5-hour session a reset the next day
(soon(1) at 3:30pm in claude_usage, claude_seats, claude_usage_switched;
claude_made_first in gateway; "Jul 20 at 10am" at midnight in
claude_scoped) now give one 3 hours on, as /usage would.

Fails without: with the bound removed and fresh reads not through
elapsed, TestClaudeResetTimeWithinItsWindow fails ("Oct 1, 3pm (UTC)" for
168h at 2026-10-05: 2027-10-01 15:00 (in 8667h), want 2026-10-01 15:00;
"Oct 11, 3pm (UTC)" for 5h: 2026-10-11 (in 147h), want 2025-10-11;
"read true: held until 2027-10-03 15:00"), as do TestParseClaudeUsage and
TestClaudeResetTimeAtNewYear on the changed rows. With the bound but
fresh reads not through elapsed, it fails with "read true: 5 hours
Used:100 ResetsAt:<4 days ago>".

Verified, under a temp HOME with GOPATH, GOMODCACHE and GOCACHE pinned:
go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go
build, go test -tags nogui ./... (all pass), and go test -race -count=20
-run 'TestClaudeResetTime|TestParseClaudeUsage' ./internal/provider.
Not run: claude /usage on a real account read days late. Unchanged: a
week's time alone read minutes after its reset still reads as tomorrow's
(at most a day).

* gateway: a subscription account that fails with a window full rests until it renews, but no more than 8 days, so a reset time read a year off no longer benches it for that year

restAfter's default branch (a failure that isn't credit, quota, a rate
limit or verification: a 502, a sign-in error) rests a subscription
account until its fullest window renews, by c.full(now). That time is
the vendor's reading, not the failure's: Claude Code's /usage text, read
by claudeResetTime, takes a date with no year for next year when it reads
it wrong, and the account then sat out ~365 days until the user noticed
and lifted it by hand. The failQuota branch of the same function already
holds every rest, window included, to longestQuota (a week's window and a
day over); the window rest here now takes the same bound:
min(t.Sub(now), longestQuota). A window renewing within 8 days rests
exactly as before.

Why longestQuota and not the full window's own Span: Allowance.Full
returns only the renewal time, so the call site doesn't know which window
was full or how long it runs; Span is zero where a reading doesn't say
(plugin windows may not); and a failure that isn't about quota must not
sit out longer than one that is, which the quota branch already caps at
8 days. Bounding by Span would only shorten a misread 5-hour window from
8 days to 5 hours, and would have to change the quota branch with it, so
it is left for a change of its own.

Siblings: restAfterMarked is the only place that stores a rest
(restingUntil). Its other branches are bounded already: failQuota by
longestQuota (resets in the body, the noted header, the window and
Retry-After alike), failRate by longestWait and longestRateRest, credit
and verify by constants; a key never takes the default branch's window
rest (c.p.Account != nil). Every other use of a window's reset (capHeld,
Allowance.Full/Renewal/Restarts/Pace in weighing, the sink condition) is
computed again from the latest reading on each request and stores
nothing. Not changed here: cappedError's soonest renewal still becomes
the agent's Retry-After uncapped, and a stored window rest isn't lifted
when a later reading corrects the time (only OnRenewed or a manual
Unrest does), so a bad reading can still bench an account for up to 8
days. Claude's parsing is fixed in the commit before this one, and a
Claude account's window rest is lifted by a renewed reading in #1200.

docs/subsystems/gateway-routing.md says so in the runtime path; its
gateway test list already takes the new test by its TestRouting prefix.

Verified under a temporary HOME with GOPATH, GOMODCACHE and GOCACHE
pinned: go vet ./..., go build, GOOS=linux go build -tags nogui and
GOOS=windows go build pass. TestRoutingHoldsAWindowRestToLongestQuota (new): a
Claude account whose window is full with ResetsAt a year out, failing
502, rests at most longestQuota; a control renewing in 3h rests 3h.
Without the change it fails: "window read a year off: rests
8759h59m59.999682292s by window (other), want at most 192h0m0s". It
passes with -race -count=20, with TestOrderedKeepsAnAccountAt98 and
TestQuotaRestsUntilItsReset. The routing reference's gateway test set
passes.

go test -tags nogui ./... ran with the machine at a load average of
~125 on 12 cores, and three packages failed there, none on this path:
internal/davsync timed out at 10m (it passes alone in 353s);
TestSetAnswersWhileDevinAndProvidersHang fails on e95852e3 too (4 of 20
with -race); TestQuietStreamsKeptAliveEveryProtocol/chat_mid-reply (a
keepalive written before the reply already passed) failed 6, then 1,
then 0 of 20 here with -race and 0 of 60 on e95852e3. Its provider is a
key that answers, so restAfter, the only code changed, never runs in it;
it is left for a change of its own, not called a flake.

* gui: a click made while the page is drawn again is kept: a Settings option pressed through a redraw is still picked, and a menu still loading opens at the redrawn button (#1211)

* gui: a Settings option pressed while the page is drawn again is still picked when let go on it

Every save's answer runs renderSettings(), which replaces each option
control. A second option pressed while the first one's save came back was
let go on a new button: down and up were on two nodes, the browser sent the
click to neither, and nothing was saved. Two quick clicks lost the second
one silently.

A capture-phase pointerdown/pointerup pair now clicks the new button when the
pressed one was taken out of the page and the pointer is let go on the same
option of the same control. The same control means the same place under the
nearest element with an id, among as many controls of its kind, in rows
alike by their data-*; a list drawn again with a row gone, come in or moved
above the pressed one is another control, and nothing is picked. Let go
anywhere else (dragged off to another option, or to another control) picks
nothing, as for any button. A click the browser sends after all is not
doubled. A tap is left to the browser, which clicks what is under the finger
as it lifts. It covers every segs() control, so every option on Settings.

segs-press-redraw.test.cjs, Chromium and WebKit, en/zh/ja/de, 900 and 440px
(42 tests): the probe (press Lightweight → On, renderSettings(), let go)
posts once; drag-offs post nothing; a plain click posts once; every option
control on every Settings tab (49 in English) pressed through a redraw
clicks its new self once; a Chromium tap through a redraw posts once; a
list drawn again with its rows changed picks nothing. Without the fix the
probe and the sweep get no click at all in both engines; without the touch
skip a tap posts twice; matching by place alone picks the row below.

* gui: a menu still loading when its button is drawn again opens at the redrawn button

openAgentModels kept the clicked button across its fetch and gave up when
a redraw had taken it off the page, so a click on Pick, Claude Desktop's
model menu or the models line was silently dropped whenever Agents was
drawn again while the list loaded: a periodic refresh, or the /api/state
re-read that closing a changed list queues (agent-models.test.cjs's
Escape-then-Pick was racing it). The loading record now holds the button,
the builders hold it to the button they draw (holdAgentModels, beside the
existing re-anchor of an open list), and the list opens at the current one.
A click on the redrawn button while it loads takes the click back, as one
on the first did.

The same await-then-open gap was in the two other menus that wait on a
fetch before opening:
- a gateway key's models badge dropped the click when the keys were drawn
  again during GET /api/caller-keys/models;
- the menu bar's allowances pill, opened while the allowances loaded and
  Settings was drawn again (another setting saved), came up in the window's
  corner at the dead pill and saved the other setting back as it was.
Both now open from the button drawn last, with what that drawing keeps.

Reproduced on the unfixed code with the new tests, which delay the fetch
and redraw during it: agent-models-redraw, gateway-key-models-redraw and
tray-usage-redraw, in Chromium and WebKit at a wide and a 560px width.
They pass after the fix, as do the agent-models, gateway-key and
tray-usages tests. Full GUI suite in both engines: 3503 of 3518 pass; the
15 failures are in 8 files outside these paths (account-mask,
panel-arrange, session-identity fail on upstream/main too; profile-confirm
is flaky there too; azure-endpoint, lightweight, purpose-filter and
routing-time failed only under the full run's load and pass alone on both).

---------

Co-authored-by: yetone <yetoneful@gmail.com>
Co-authored-by: XYenon <i@xyenon.bid>
Co-authored-by: Amp <amp@ampcode.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:24:44 +08:00
forever 8005f17551 provider, codex: a ChatGPT account at 100% with credits left keeps Codex signed in (#966)
* provider, codex: a ChatGPT account at 100% with credits left keeps Codex signed in — magpie becomes its provider only while the Codex app itself holds the account

magpie made itself Codex's provider (model_provider = "magpie", #540)
whenever any of the active ChatGPT account's windows read 100%. A Pro
account at 100% on its week with credits left keeps working in the Codex
app: the backend answers every turn (about 490 200s in one day's usage log
at 100%), yet magpie moved Codex off it, and as a provider without
requires_openai_auth the app lost its ChatGPT state ("Sign in to ChatGPT
to start a durable thread", no remote control).

CodexUsedUp now reads codexHeld, which mirrors the Codex app's own
composer block (ChatGPT.app webview bundle, hP and its helpers): the
backend says the account isn't allowed (rate_limit.allowed = false), it
has no credits (has_credits / unlimited), and it isn't a workspace still
within its overage (overage_limit_reached = false, no spend cap, an
ordinary rate_limit_reached). Window percent never decides it. Where the
app goes by what /wham/usage can't show (a statsig gate, the gpt-reserve
fallback, Team's reserve experiment that ignores overage), it counts as
held: a wrong move costs ChatGPT extras, a missed one every turn. A
reading kept through a failed read (keepLast) stops saying held once its
used-up window has started again, as its usage does. NextLogin's account
rotation and its thresholds are unchanged.

A user stuck on the old move (codex.out = 1) is put back beside the
sign-in by the next Sync, as #540 already does once the account has room.

Verification:
- TestCodexUsedUpIsWhatTheAppHolds (real /wham/usage replies, ids
  replaced) fails on the old trigger: 7 subcases, "CodexUsedUp = true,
  want false". Each workspace guard (spend cap, reason, overage, plan
  list, Team reserve) was mutated and fails its own subcase.
- TestCodexHeldKeptOnlyTillTheReset fails without the quota_last change.
- The real Pro account (7-day window 100%, ~28k credits, allowed false):
  CodexUsedUp true before, false after.
- go vet ./...; go build (darwin), GOOS=linux -tags nogui, GOOS=windows;
  go test -tags nogui ./... under a sandbox HOME; -race -count=20 on the
  new and related Codex tests.
- Not run: a live Codex app turn on an account truly held (none at hand),
  Windows/WSL runtime, GUI suites (no GUI change).

* provider: a Codex account at a spend cap or past its overage is held, credits or not; limit_reached counts as not allowed

codexHeld let credits through before the spend cap, so a Team seat at its
cap (spend_control.reached, allowed false) with has_credits read not held
and magpie left Codex on an account the backend refuses. The app's
readiness check (26.930.61225, app-primary) returns limited on
spend_control.reached or credits.overage_limit_reached before it looks at
credits, and treats rate_limit.limit_reached like allowed false; held now
reads the same. A spend cap with the rate limit still allowed (a
workspace's included usage) stays not held.
2026-10-06 14:50:39 +08:00
yetone 8e853a63e0 cleanup: staticcheck SA4006 — the GitHub token test now checks the status GET /api/settings answers (its code was read and dropped), and BackAt declares at rather than assigning a value every branch overwrites. The gui token test and provider tests pass; SA4006 is clean in gui and provider. 2026-10-06 06:39:17 +08:00
yetone ed79a72927 provider: a subscription account can be capped at a share of its usage windows, and routing treats it as used up there (Discord: hold a new Claude account at 70% of its five hours and its week to keep its ban risk down, and let magpie go on to the other accounts) — an account's cap (1–99, keyed by the provider id and the account in lower case, AccountCaps in providers.json beside AccountModels and AccountProxies) holds it once any window that applies to the model is at or past the cap and hasn't reset (Allowance.CapHeld; Aside windows and windows kept for another model are left out). One share for every window rather than one per window: the windows an account has differ by vendor (five hours and week for Claude and Codex, a month or a day for others, per-model weeks), the request was one figure for both, and a lower share for one window would be set by lowering the cap. The gateway's perKeyBarred moves a capped account to the candidates left out (barredOf marks it Capped with its use and when it is back, so the routing trace says "held at its 70% usage cap"), so groups, fallback, Ordered and Spread routing and the Codex/Claude Code switch list (NextLogin: a capped account is moved off, not returned to, and isn't a spare) all go on to the next account; a pinned capped account and a draw over only capped accounts answer 429. When every account that serves the model is capped, the client is turned away as when all are used up — 429 rate_limit_error with Retry-After at the soonest reset — and told the cap was reached, which accounts, at what use and cap, and how to lift it. A cap never spends a Codex reset: weekUsedUp, usedUp, BackAt and spendExpiringNow still go by ChatGPT's own 100%, so an account held at 80% with auto reset on is held and nothing is spent; a lone Codex account with a cap goes through serve() instead of being relayed as it came (codexAccounts), so the cap holds it. The Providers page shows a cap pill on each account's row (on hover until set) that opens the app's own menu — No cap, 50/60/70/80/90%, Other… (typed inline, focused without scrolling) — posting provider/accountcap; each window's bar gets a tick at the cap (from the right when the bar shows what is left), and an account held by its cap says so and until when. zh strings in i18n.js. CLI: magpie provider account-cap <id> [account [percent|off]] shows or sets caps. Tests: TestCapHeld, TestCapReached, TestParseCap; TestCapNeverSpendsACodexReset (80% windows, 70% cap: not used up, no reset due, routing held); TestCodexSwitchedAtCap (the active account at 75% with a 70% cap is switched off to the one at 20%, not back while capped, back once lifted; 100 and an unknown account refused); gateway TestAccountCapMovesOn (first account at 75% capped at 70%: the second is tried and the trace says 75/70; lifted: the first), TestAccountCapEveryAccount (429 rate_limit_error naming both caps, nothing sent, logged 429) and TestAccountCapSpendsNoCodexReset (one account at an 80% week, auto reset on: 429, nothing tried or spent; lifted: 200, nothing spent) — the three gateway tests fail with the cap check taken out; TestAccountCapCmd; account-cap.test.cjs (webkit, en and zh: pill, menu, Other…, No cap, cap ticks, held note, no <select>, no border stripes, no scroll on click). account-models, click-scroll, keep-login, codex-auto-reset, account-return, routing-blocked, routing-account-order, routing-quota-left, routing-auto-reset, routing-manual, quota-pools, quota-families and usage-accounts GUI tests pass in webkit. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried with real accounts; a cap acts on usage as last read, so a burst between reads can run a little past it. 2026-10-04 10:18:50 +08:00
yetone 9db0d155bc cli: magpie quota wait <provider|account> blocks until that subscription (any of its accounts) or that account has allowance again, then exits 0 (#720, thedavidweng: a long Codex task stopped when every account ran out, and nobody came back to it hours later; step 1 of the maintainer's plan, for until codex exec …; do magpie quota wait codex || break; done) — it reads the vendors itself as magpie quota does, gateway running or not (provider.Allotted: the subscriptions' and plans' readings, no key balances; AskUsage has each look wait for a new reading, and only a wait for Claude runs Claude Code's /usage, through AskClaudeUsage, which now calls it). An account has allowance when routing's usedUp says so (no window that stops it, every model, at 100%; exported as provider.UsedUp), and BackAt is when the last of those windows starts again. While all are used up it sleeps to the soonest reset plus 30s, at least a minute and at most ten, saying on stderr what it waits for and until when; an allowance it can't read (an error, or only the last reading kept in its place) is asked again after 1, 2, 4, 8 then every 10 minutes. A provider's accounts switched off or signed out in magpie are left out, as the agent is never moved to them; an account is named by its user, or <provider>/<user> when two subscriptions share it. --timeout <duration> exits 1 when it passes first, --quiet says nothing, an unknown name or flag exits 2 (main now honours an exitError's code) and Ctrl+C 130. The loop takes its reading, clock and sleep as functions: quota_wait_test.go runs it on a fake clock (already available → no sleep; used up → 10m, 10m, then to just past the reset; one account named ignores another's room; a reset under a minute away is a minute; --timeout ends at the deadline after its last look; unreadable usage backs off and the wait goes on once read; an untold reset is looked at every 10 minutes; an off account is passed over; Ctrl+C), plus resolving names and the usage errors. Help in magpie quota's and magpie's usage, and the README. go vet, builds (darwin, GOOS=linux, GOOS=windows), the new tests and ./internal/provider pass; not run against real accounts. 2026-10-04 06:12:51 +08:00
yetone 089f4f7d87 accounts: Codex or Claude Code can be kept signed in to any of its accounts, not only the first, while the gateway still tries them in their order (Koohoko on #524: 建议不只是支持始终登录"首选"账号,应该可以支持始终登录任一选定的账号。有时候首选只是为了按顺序先消耗它的额度,不一定是用户期望的常用登录账号) — making an account first did two things at once: the gateway tried it first (the account the agent is signed in to always stood ahead of the others, AlsoOn behind it), and Codex or Claude Code was signed in to it (SwitchLogin). "Keep {agent} signed in to the first account" (817a5f50) only stopped magpie moving the sign-in on, so a user who wanted one account's allowance spent first had to sign the agent in to it too. Now beside that tick is a pick, "Keep {agent} signed in to [the first account ▾ | each saved account]" ({agent} 始终登录 [首选账号 ▾]): picking one keeps Provider.KeepLoginAs (providers.json, kept across an editor Save like KeepLogin; POST provider/keeplogin with keepLoginAs) and signs the agent in to it at once, the order the gateway went by then — the one signed in to first — written as the accounts' own first, so the first stays first. While it is kept: the login switcher signs the agent back in to it whenever it is on another and never moves it off, however used up (NextLogin); a drag or Make first sets the order without a sign-in (arrangeLoginsAs), Make first posting provider/arrange; the gateway puts the account signed in to at its own place in that order, not first (perKeyBarred by Provider.LoginRanks), so In order spends the first's allowance first; InUseLogin (the tray's in-use account) is the first in use in the order. The rows keep their order, the first saying First and the one kept saying Signed in (已登录), an account not in use ticked on by its dot rather than a Use that would sign the agent in; the Routing note says the agent stays signed in to that account and requests go in the accounts' order. Picking "the first account", or unticking, lets it go and signs the agent in to the first again, so the one signed in to is the first once more. TestKeepLoginAsChosen (signed in to the chosen at once, the order kept, stays at 100%, moved off it goes back, a drag changes the order not the sign-in, the first's again when let go) and TestKeptLoginStandsAtItsPlace (through the gateway In order: kept on spare, the first, acct-1, is tried first; acct-2 without the change) are new; keep-login.test.cjs now also picks an account (the post, First and Signed in, Make first arranging, back to the first, every string's Chinese, the page not moving) and passes 8/8 in WebKit; account-return, routing-account-order, account-arrange and click-scroll pass in WebKit. No live agent config, keychain or vendor was touched. go vet ./internal/..., go build (darwin GUI), go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-02 23:30:54 +08:00
yetone 27f0e4ebdd codex: when the ChatGPT account runs out of its allowance after a magpie model was picked, magpie becomes Codex's provider, and goes back beside the sign-in when the allowance is back (#540: once the Codex 5-hour/weekly quota is used up, a third-party model through magpie sends nothing in new or old sessions; Dazzle-sys: the session was on the magpie model all along, the quota went elsewhere) — the Codex desktop app refuses to send for a ChatGPT account that is out of its allowance before any request is made, whichever model the turn is on, so a magpie model beside the sign-in (openai_base_url, ChatGPT mode) is blocked with it; Codex's open-source core and TUI only report a usage limit after a response, the block is the app's, keyed on the account. bd5bf422 made magpie the provider (model_provider = "magpie", model_catalog_json; the app-server's getAuthStatus then answers requires_openai_auth false, the app's API state) only when a model was picked while the account was already out, so an allowance running out later left Codex as it was. KeepOnAnAccountWithRoom now also looks, every 5 minutes, whether the active Codex account is out (CodexUsedUp, now read through LoginUsage's cache, fetched at most once a minute, as the agents' sync asks it on every catalog sync) and tells the agents' sync when that changes (noteCodexUsedUp → catalog.Touched); Codex's Sync then sets the magpie model again, which wires it as the provider while the account is out, marked codex.out in the stash, and puts it back beside the sign-in once the allowance is back, only where it was moved for that (a provider asked for with sign-in "api" stays). Threads started on Codex's own provider and reopened may still be held by the app; the Codex app may need a restart to take the new config. agent's TestMain stubs codexUsedUp so no test asks OpenAI. TestCodexRunsOutAfterPick (ChatGPT mode, then out: provider; out again: stays; back: beside the sign-in; api stays) fails without the change; TestNoteCodexUsedUp checks only a change is told. No request was made to OpenAI. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-02 16:48:26 +08:00
yetone 817a5f50d5 routing: In order keeps sending to the first account until it is used up or refused, and a tick keeps Codex or Claude Code signed in to the first account (#530: an account In order at 98% of its week, its five hours untouched, stopped getting requests; #524: "不允许切换首选账号的登录状态", the agent's own sign-in must stay on the account made first while the gateway still spreads requests) — since #209 magpie signs Codex and Claude Code in to the next ticked account with room once the one they are on reaches 98% (provider.SpentShare, the share Smart counts an account spent at), and since #408 back once the first is under 90%. The account the agent is signed in to is the one every routing tries first (the others stand behind it, AlsoOn), so In order the 98% switch put the second account ahead of the first, which is what #530 saw as the first being dropped; and the gateway counted an account at 98% as full whatever the routing, so a passing failure on it (a 502) rested it until its week renewed (39 hours there), not for the usual backoff. Now SpentShareOf gives 100 In order and 98 otherwise: the login switch moves the agent off an account In order only once a window of it is used up, the gateway's full (the rest after a failure, the quota rest's window) and affinity's "spent" go by the same share, and a vendor's 429 or usage-limit refusal still rests the account until it says it's back, as Smart does; a window used up is out, as before. Smart, In turn and Least used are unchanged. For #524, the subscription keeps KeepLogin (providers.json, beside Routing, kept across an editor Save; POST provider/keeplogin, only for Codex and Claude Code): with it on, magpie never moves the agent off the account it is signed in to, however used up, while the gateway still routes requests through magpie to the other ticked accounts; a pending return to the first (#408) still happens, that being the first. The tick sits at the foot of the Accounts list, under the rows where Make first is, shown only for Codex and Claude Code with more than one account on: "Keep {agent} signed in to the first account" / "{agent} 始终登录首选账号", its tooltip saying requests through magpie still go to the other ticked accounts. The Routing note follows it: kept, it says the agent stays signed in to the first whatever it has left; In order, that magpie moves it on once it is used up; otherwise the 98% wording as before. TestCodexLoginOrderedAndKept (In order stays at 98% and moves at 100%, back once renewed; Smart moves at 98%; kept, it stays at 100% and the setting survives a SetRouting; let go, it moves) and TestOrderedKeepsAnAccountAt98 (In order an account at 98% isn't full and a 502 rests it by backoff, Smart rests it to its week, a refusal rests it either way) fail without the change. keep-login.test.cjs (en and zh, Chromium and WebKit: the tick, its tooltip and Chinese strings, the post, the note when kept and In order, no tick with one account, the page doesn't move) fails without the UI and passes with it (12/12, Playwright 1.61); account-return, routing-account-order and account-arrange pass; click-scroll fails in Chromium here on origin/main too and passes in WebKit. No request was made to any vendor and no live agent config was touched. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestClaudeRunEndsWhenTheClientLeaves, TestClaudeAccountNamedAsItsLogin and TestClaudeIdentityServedWhileAsked failed once under the full run and pass alone). Turned on after magpie has moved the agent off the first, it goes back to it at once rather than once that has room again. 2026-10-02 15:48:16 +08:00
SadWood e0121f71b9 Preserve dated Claude usage when allowance is unavailable (#511)
* fix(provider): preserve dated Claude usage after unavailable reads

* fix: clarify cached Claude usage and preserve account return
2026-10-02 14:46:42 +08:00
yetone 74cb5dc1ae accounts: the account made first stays first — magpie signs Codex or Claude Code back in to it once it has room again (#408: 智能路由会自动把所使用账号设为首选) — since #208/#209 magpie signs the agent in to the next ticked account once the one it is on is 98% used, and left it there for good, so the account the user made first lost its place after its first spent window. magpie now keeps the account it moved off (login-returns.json beside logins.json) and signs the agent back in to it once that is below 90% (Smart's low share, so it doesn't flap) and still ticked; a switch the user makes meanwhile, in magpie or the agent, ends that. The Accounts list says it: the stand-in reads "First for now" (暂为首选), its title naming the one it goes back to, and that one "First again once it has room" (额度恢复后切回首选); the Routing note says magpie moves back. TestCodexSwitchedBackWhenItHasRoom and account-return.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; account-return, click-scroll, old-webkit, routing-signin pass. 2026-10-01 17:16:47 +08:00
yetone 0b7781ba18 providers: Claude Code is signed in to its next account once the one it is on is spent, as Codex is, and an account keeps its own affinity, backoff and usage across a switch (#208 Cyb3rN8: Claude Code 用自己的模型时,登录账号额度用满不会自动切换 · #209: Smart 选中的账号和 Claude Code 登录账号互不同步…切换登录账号还会把按 id 记的状态串到另一个账号上) — Claude Code on its own model asks Anthropic as the account it is signed in to, never through magpie, so with A spent its sessions got "You've hit your session limit" while the gateway had moved on to B. The Codex watcher (KeepCodexOnAnAccountWithRoom, now KeepOnAnAccountWithRoom, same place: started by the magpie serving the gateway, a minute in and every 5 minutes) now looks at Claude Code too: when the account it is signed in to is spent and another ticked account's allowance is known and has room, it is signed in to that one through SwitchLogin (credentials and .claude.json's oauthAccount), as Use on the Accounts page does; not when the Claude account was removed from magpie. The rule for #209: the sign-in follows Smart, not the other way round — it moves at the share Smart counts an account spent (provider.SpentShare = 98, which the gateway's usedShare now is), for Codex too (it moved at 100%). The Routing field of a Codex or Claude subscription with several accounts says so: routing picks the account for what comes through magpie; the agent on its own uses the one it is signed in to, moved on at 98%. Sessions already running keep the account they started with until restarted, as SwitchLogin says; routing Claude Code's own model through the gateway (the codexFailover way) is not done here. #209's second part was a real bug: the account the agent is on is the candidate "claude" and the others "claude@user", so a switch handed "claude" from A to B — a conversation A answered was kept on B and traced kept=true, and the Least used tokens and the backoff count followed the id. who(), routed.used and routed.failures are now keyed by restKey (provider@user, as rests already were); rest itself (group members, the trace) is unchanged. Tested with new TestClaudeSwitchedWhenSpent (sandbox HOME, keychain off, a fake usage endpoint: 97% stays, 98% signs Claude Code in to b — credentials and .claude.json — a stays ticked; on b it stays; both spent it stays), TestCodexSwitchedWhenUsedUp still passing, new TestLoginSwitchKeepsEachAccountItself (fails on main: the conversation went to b, kept) and new internal/gui/tests/routing-signin.test.cjs in Chromium and WebKit, en and zh; login-import and routing-kind GUI tests pass. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... pass (TestUserPath, TestClaudeAccountNamedAsItsLogin, TestClaudeIdentityServedWhileAsked and TestCodexVersion timed out at 5s under the full run's load and pass on their own). Not tested against real Claude accounts or a running Claude Code. 2026-09-29 18:56:33 +08:00
yetone 2eb5015df3 accounts: Codex is signed in to its next ChatGPT account when the one it is on has used its allowance up — the Codex app, knowing its account is out, may not send at all, so magpie's failover never saw the turn: now the magpie serving the gateway looks every five minutes and, with another of Codex's accounts on in magpie that has room, switches Codex to the first of those as the Accounts page would (the one out stays on, next in line); a Codex started after that is on it. An account rests by its user, so the one Codex is switched to doesn't take over the rest of the one it left. Asked on Discord 2026-09-26 21:32:42 +08:00