1ccacad63281094de8a3372d5a507d38f9969e5c
44
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ffc69f0244 |
codex: an account can keep its access token only, never renewed (EastonXvii on X)
A Codex account can now be imported, or ticked later, as "Access token only". magpie uses the access token it was given and never refreshes it. The refresh token is never spent or rotated, so another computer signed in to the same ChatGPT account stays signed in. - Every renewal of a saved account goes through renewSaved. For an access-only account it calls accessOnlyToken, which hands out the token until it runs out and never calls codexRefresh. That covers requests, usage reads, the idle read, models, resets, warm-up, the 401 recovery and the keep-alive, which also skips such accounts. - Once the token runs out, the account is marked Lapsed with refreshRefused. The provider editor shows "Access expired" and "Import again", which opens the import with the tick set. A new import or sign-in replaces the entry and clears both. - Such an account is never switched into Codex, since Codex would renew it. That applies to switchable, switchSavedLogin, NextLogin, keep-as and signInToFirst. The live or held account can't be made access-only (errAccessOnlyHeld). Its row says "magpie only". - Import: ImportCodexAccessOnly accepts files that have only an access token, refuses an expired token or a missing id_token, and makes no refresh call. CLI: `magpie accounts import codex --access-only`, `magpie accounts access-only codex <email> [on|off]`. GUI: the import box tick, the row tick and POST /api/login/access-only|renewed. - The core scripts stay within budget: app.js is smaller than main's. This change's own comments and nine sign-in/import comment blocks were cut, with no raise. Run (on mote): - gofmt -l clean; go vet for darwin, linux (nogui) and windows ok. - go test ./internal/provider ./internal/cli ./internal/gui ok. - GUI files in chromium and webkit, en and zh: codex-access-only (new), login-import, account-return, i18n-keys, account-row-line, agent-switch-accounts and signin-paste-import: 64/64 at the final tree. In an earlier grouped run, signin-paste-import failed once on its Import button's wait. It then passed 6/6 alone and in the rerun. Broken by hand: - With the renewSaved branch and the keep-alive skip taken out, TestCodexAccessOnlyNeverRefreshed went red: the keep-alive renewed the account. TestCodexAccessOnlyRunOutLapses went red too: a run-out token was handed out. - With the branch and the import path taken out, a forced renewal went through and an expired-token import was "added". Both tests went red. Not tried: a real ChatGPT account, so I did not check that another computer stays signed in. No Windows run, since nothing here differs by OS. |
||
|
|
40d39e1176 |
provider: Codex's account is read every 30 minutes while Codex sits idle
dludream on Discord: with Codex signed in, magpie asked chatgpt.com every
five minutes, 288 times a day, used or not, and they worry about ban
risk. KeepOnAnAccountWithRoom read the account Codex is signed in to
(/wham/usage, through SwitchWhenSpent, CodexUsedUp and the app-left
restart) on every full look, every loginSwitchEvery.
Now a full look reads Codex's accounts only when codexDue says so:
- while no Codex session file was written in 30 minutes
(codexSessionsQuiet over CODEX_HOME/sessions) and the account isn't
near out, the next read is codexIdleLookEvery (30m) later;
- a session written again makes the next full look (5 minutes at most)
read it;
- near out or held, it is codexNearOutEvery (1m) as before;
- a sessions folder that can't be read counts as written, so the
cadence stays 5 minutes.
Claude's looks, the proxy sync and noteCodexGoneNow keep their cadence.
Requests magpie sends on the account keep its windows current from the
reply headers (NoteCodexLimits), so routing doesn't lean on the poll.
docs/reference.md says the new cadence.
Run at this tree (origin/main
|
||
|
|
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)
|
||
|
|
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.
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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
|
||
|
|
1af868a153 |
provider: a Codex app left on a used-up account restarts with Restart the app off too (atom0964)
v0.1.2826 ( |
||
|
|
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; |
||
|
|
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 |
||
|
|
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
|
||
|
|
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 |
||
|
|
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). |
||
|
|
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 |
||
|
|
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). |
||
|
|
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
|
||
|
|
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
|
||
|
|
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, |
||
|
|
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.
|
||
|
|
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 |
||
|
|
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
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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
|
||
|
|
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> |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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
|
||
|
|
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.
|
||
|
|
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 (
|
||
|
|
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. |
||
|
|
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. | ||
|
|
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. | ||
|
|
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.
|
||
|
|
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.
|
||
|
|
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.
|
||
|
|
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. | ||
|
|
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 |
||
|
|
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. | ||
|
|
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. | ||
|
|
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 |