provider: Claude accounts can be set not to spend extra usage (baksili_ on X)

baksili_ on X asked for a way to keep magpie off Anthropic's paid extra
usage on Claude subscription accounts. magpie can't flip Anthropic's own
switch, so it holds the account itself.

Providers -> Claude -> Advanced has a new "Spend extra usage" row: On,
as before, by default (nothing changes for anyone who doesn't touch it).
Off saves claudeNoExtraUsage. While it is off, HoldCaps holds every
Claude account at 100% of any plan window with no cap of its own (the
same Credits hold a Codex account set not to spend its credits gets),
so a Claude account whose 5-hour or weekly window is used up gets no
requests until it renews and the other accounts take them. What its
plan has left is still used; a cap the user set lower still holds first.

A cap on an account's "Usage credits" window (its extra-usage spend,
set as an amount or a share on the usage card) now holds the account
the same way once that much extra usage is spent (Allowance.extraCapped,
called from CapHeld and NearCap). Before, aside windows carried no
amount, so an amount cap on one never held anything; allowanceOf now
gives aside limits their Amount, Of and Unit.

Every route that picks an account goes through capHeld, so the gateway,
groups and fallback obey it alike. Claude Code switching (NextLogin)
already moves off an account on overages. The warm-up sends a held,
used-up account nothing (codexWarmer.held / spentPast; claudeHeldFull
for Claude), since that request would be billed as extra usage. With
every account held, the client is told "has used up a usage window and
is set not to spend extra usage" and how to turn it back on, and the
call's record says "set not to spend extra usage" (Weighed.ExtraUsage).

Not done: Claude Code's hidden /limit-reset. It resets or buys limits
through endpoints Anthropic hasn't published, and calling them would be
mimicking Claude Code's client, which magpie doesn't do. A Claude Code
signed in on its own, not through magpie, still spends extra usage.

Run on mote at 5b0572ae3 + this change; rebased since on ce2ce86ab
(two gui commits on WebView2 and a GC read, no file in common), where
the gui budget tests passed again:
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/settings ./internal/settingsapi ./internal/gui: all ok
  (gateway 939s; the core script budget passes)
- GUI (node --test, Chromium and WebKit): claude-extra-usage-setting
  (en, zh, zh-TW, ja, de at 1100 and 420), provider-prefs,
  claude-lean-prompt-setting, i18n-keys, account-cap, claude-overages,
  quota-credits: 114 of 114
- gofmt -l: clean

Broken by hand (at the 7eecbcc56 base), each red, then restored:
- HoldCaps' claude case -> TestClaudeNoExtraUsageHoldsAtThePlan,
  TestClaudeNoExtraUsageHoldsTheAccount (gateway)
- extraCapped in CapHeld -> TestClaudeExtraUsageCapHoldsAtThePlan
- aside Amount/Of in allowanceOf -> TestAsideWindowAmountCapHolds,
  TestClaudeExtraUsageCapHoldsAtThePlan, TestClaudeHeldFull
- spentPast in warmNow -> TestWarmUpSendsAHeldAccountNothing
- capHeld's extra flag -> TestClaudeNoExtraUsageHoldsTheAccount
- the row left out of #claudeRunList -> claude-extra-usage-setting
  20 of 20 red

Not tried: a real Claude account on extra usage; the hold was checked
with /usage reads built from the CLI's shape, not a live account past
its plan. The full ./... suite was not run (mote and mica over their
load limits, two full suites queued on mote's suite.lock).
This commit is contained in:
yetone
2026-11-13 23:42:57 +08:00
parent ce2ce86ab4
commit d0fb3c0084
21 changed files with 565 additions and 33 deletions
File diff suppressed because one or more lines are too long
+1
View File
@@ -416,6 +416,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same `/plan` endpoints with the same `sk-tp-` keys (product/1823/130060, 130659), so they are one region, `plan` (a key saved on `enterprise` is on it, `regionAliases`/`RegionID`); 个人版 has no usage API, so a Guangzhou provider without a SecretId gets no card asking for one (`tcSharedRegion`), while Singapore's does. A Tencent Cloud provider saved at the old personal host `api.lkeap.cloud.tencent.com/plan/...` is moved to TokenHub's at load (`movedEndpoints`, `moveEndpoints` in `normalize`), with Responses added; one of no preset keeps the address its user typed, and an app imported at the old host lands on the plan. TokenHub's pay as you go has no plan and no card. A custom provider (no preset) at a Token Plan's or Ark plan's address is the user's own: its editor and Usage page ask it for no access key (`AsksAccessKey`) until one is saved on it, and its key goes as typed, `Authorization: Bearer` on chat and Responses (ysm119). The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here.
- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan.<region>.maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); the Qwen AI platform's (`qianwenaiapi.com`) and Qwen Cloud's plans have no read here (their console takes a browser sign-in, #5829). The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio.<region>.aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST <console>/cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `per<N><Hour|Day|Week|Month>Percentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user's key gets `BailianGateway.Team.NotAuthorised` until the main account grants what Alibaba's Token Plan docs ask for RAM users: the `AliyunTokenPlanReadOnlyAccess` and `AliyunBSSReadOnlyAccess` system policies (the `AliyunBailian*` and `AliyunModelStudio*` ones don't cover the Token Plan) and the Administrator or Subscribe Plan permission on Model Studio's Account Management page; the card and the editor's hint name all three (`aliRAMHint`, #6506). The same API serves the main account and RAM users; `bl` has no other route. Another refusal shows the console's `errorMsg`. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part.
- Whether a Codex account spends its credits (`CodexNoCredits` in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: `NextLogin` moves off an account at its routing's spent share, 100% at most, credits or not.
- Whether a Claude account spends Anthropic's extra usage past its plan (`ClaudeNoExtraUsage` in settings, one switch for every Claude account, opt-out: Spend extra usage in the Claude editor's Advanced, or `magpie settings set claudeNoExtraUsage off`) is the gateway's routing and the warm-up only; a cap on an account's Usage credits window holds that account the same way once its extra usage reaches it (`provider/claude_extra.go`). magpie can't turn extra usage off at Anthropic: a Claude Code signed in on its own, not through magpie, still spends it. `NextLogin` already moves Claude Code off an account on overages, as the Extra usage row reads 100 (`claudeOveragesWindow`, `usedPast`). Claude Code's hidden `/limit-reset` is not driven: it spends or resets limits through a flow Anthropic hasn't made public, and calling its endpoints would be Claude Code's client imitated.
- A Vertex AI provider's credentials are read only when a request is signed (`Sign`), so adding, listing and showing one ask Google nothing. With no `credentials` given and no file where Application Default Credentials are looked for, the request fails with `no Google credentials at <file>`, naming `gcloud auth application-default login` and the provider's credentials file as the ways to give it some. A `credentials` file that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (`signInAgain`): gcloud's Application Default Credentials with `gcloud auth application-default login`, adding `--impersonate-service-account=<account>` when the file impersonates one; a file under gcloud's `legacy_credentials/<account>/` with `gcloud auth login <account>`; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart.
- Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (`external_account`, `external_account_authorized_user`, refused by name); credentials whose `universe_domain` isn't `googleapis.com`; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL.
- `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key).
@@ -0,0 +1,63 @@
package gateway
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// baksili_ on X: with Extra usage off in magpie, a Claude account whose
// plan is used up is held at 100% as routing plans it (capHeld, which
// every account of a provider, group or fallback goes through), not
// sent a request Anthropic would bill as extra usage; one with room is
// not. With it on (the default) nothing holds it. Every account held,
// the client is told why in those words and how to go on, and the
// call's record says so.
func TestClaudeNoExtraUsageHoldsTheAccount(t *testing.T) {
fresh(t)
capUsage(t, map[string]float64{"full@example.com": 100, "room@example.com": 40})
p := provider.Provider{ID: "claude", Name: "Claude"}
acct := func(user string) provider.Provider {
return provider.Provider{ID: "claude", Name: "Claude", Account: &provider.Account{Agent: "claude", User: user}}
}
now := time.Now()
if h := capHeld(p, acct("full@example.com"), "claude-sonnet-5", now); h != nil {
t.Fatalf("held with Extra usage on: %+v", h)
}
if err := settings.Save(settings.Settings{ClaudeNoExtraUsage: true}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = settings.Save(settings.Settings{}) })
if h := capHeld(p, acct("room@example.com"), "claude-sonnet-5", now); h != nil {
t.Fatalf("held with its plan not used up: %+v", h)
}
h := capHeld(p, acct("full@example.com"), "claude-sonnet-5", now)
if h == nil || h.cap != 100 || !h.noCredits || !h.extra || h.back.IsZero() {
t.Fatalf("used up, not held at 100%% for its extra usage: %+v", h)
}
ws := barredOf([]candidate{{p: acct("full@example.com"), model: "claude-sonnet-5", rest: "claude#full@example.com", capped: h}}, p, false, provider.Anthropic, nil)
if len(ws) != 1 || !ws[0].ExtraUsage || !ws[0].NoCredits || ws[0].Capped != 100 {
t.Fatalf("traced: %+v", ws)
}
msg, back := cappedError("claude-sonnet-5", ws, now)
for _, want := range []string{"set in magpie not to spend extra usage", "has used up a usage window and is set not to spend extra usage", "claudeNoExtraUsage off"} {
if !strings.Contains(msg, want) {
t.Errorf("refusal %q lacks %q", msg, want)
}
}
if strings.Contains(msg, "credits (Usage") || back.IsZero() {
t.Errorf("refusal told as a Codex account's credits, or no wait: %q %v", msg, back)
}
if got := cappedRecord(ws); got != "every account held: set not to spend extra usage" {
t.Errorf("record %q", got)
}
// a Codex account set not to spend its credits beside it: both named
cw := ws[0]
cw.ExtraUsage, cw.Who = false, "codex@example.com"
if got := cappedRecord(append(ws, cw)); got != "every account held: set not to spend its credits or extra usage" {
t.Errorf("record of both %q", got)
}
}
+60 -21
View File
@@ -112,7 +112,9 @@ func (c candidate) unmasked() bool { return provider.UnmaskedBy(c.redact, c.p) }
// capHold is how an account is held at its usage cap: the cap of the
// fullest window at or past its own cap, that window's share used, and when the last such window
// renews (zero when one doesn't say). noCredits: it is a Codex account
// held at 100% as it is set not to spend its credits (cap is 100 then).
// held at 100% as it is set not to spend its credits (cap is 100 then),
// or with extra a Claude account as it is set not to spend extra usage
// (provider.ClaudeExtraUsage) or its extra usage is at its cap.
type capHold struct {
cap int
used float64
@@ -122,6 +124,7 @@ type capHold struct {
unit string
back time.Time
noCredits bool
extra bool
// unread: held by a careful provider as its usage can't be told, why
// (carefulDoubt), cap then the account's own
unread string
@@ -991,7 +994,8 @@ func ownRouting(p provider.Provider, g provider.Group) bool {
// capHeld is how the account acct of p is held at its usage cap for
// model at now — a window at or past its own cap, else the account's — or
// at 100% as a Codex account set not to spend its credits; nil when
// at 100% as a Codex account set not to spend its credits or a Claude
// account not to spend extra usage; nil when
// nothing holds it or every window is below its share. Its windows
// are those last read (allowances), as smart routing weighs them.
func capHeld(p, acct provider.Provider, model string, now time.Time) *capHold {
@@ -1021,7 +1025,7 @@ func capHeld(p, acct provider.Provider, model string, now time.Time) *capHold {
}
return nil
}
return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits, amount: h.Amount, count: h.Count, unit: h.Unit}
return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits, extra: h.Credits && a.Agent == "claude", amount: h.Amount, count: h.Count, unit: h.Unit}
}
// cappedError says why a request for model went nowhere when every account
@@ -1049,15 +1053,15 @@ func cappedError(model string, ws []Weighed, now time.Time) (string, time.Time)
return msg + "; and " + strings.Join(spends, "; ") + " (to use it, " + spendAdvice + ")", soonest
}
if unread(ws) {
return fmt.Sprintf("usage cap reached: every account that serves %q is held at the usage cap set on it in magpie, or held as its usage can't be told right now — %s. magpie reads it again at the next request and uses it once it is under its cap; %s, or turn off Check usage near the cap (Providers → the provider's accounts, or magpie provider pool <id> --careful off)", model, strings.Join(held, "; "), heldAdvice(capped, noCredits)), soonest
return fmt.Sprintf("usage cap reached: every account that serves %q is held at the usage cap set on it in magpie, or held as its usage can't be told right now — %s. magpie reads it again at the next request and uses it once it is under its cap; %s, or turn off Check usage near the cap (Providers → the provider's accounts, or magpie provider pool <id> --careful off)", model, strings.Join(held, "; "), heldAdvice(ws)), soonest
}
switch {
case !noCredits:
return fmt.Sprintf("usage cap reached: every account that serves %q is held at the usage cap set on it in magpie — %s. magpie uses it again once that window renews; %s", model, strings.Join(held, "; "), heldAdvice(capped, noCredits)), soonest
return fmt.Sprintf("usage cap reached: every account that serves %q is held at the usage cap set on it in magpie — %s. magpie uses it again once that window renews; %s", model, strings.Join(held, "; "), heldAdvice(ws)), soonest
case !capped:
return fmt.Sprintf("usage limit reached: every account that serves %q has used up its allowance and is set in magpie not to spend its credits — %s. magpie uses it again once that window renews; %s", model, strings.Join(held, "; "), heldAdvice(capped, noCredits)), soonest
return fmt.Sprintf("usage limit reached: every account that serves %q has used up its allowance and is set in magpie not to spend %s — %s. magpie uses it again once that window renews; %s", model, notSpent(ws), strings.Join(held, "; "), heldAdvice(ws)), soonest
}
return fmt.Sprintf("usage limit reached: every account that serves %q is held by magpie — %s. magpie uses it again once that window renews; %s", model, strings.Join(held, "; "), heldAdvice(capped, noCredits)), soonest
return fmt.Sprintf("usage limit reached: every account that serves %q is held by magpie — %s. magpie uses it again once that window renews; %s", model, strings.Join(held, "; "), heldAdvice(ws)), soonest
}
// checkpointCappedError is cappedError for a request whose native
@@ -1066,8 +1070,7 @@ func cappedError(model string, ws []Weighed, now time.Time) (string, time.Time)
// not because they are held too (#2517).
func checkpointCappedError(model string, cp checkpointWriter, ws []Weighed, now time.Time) (string, time.Time) {
held, soonest := heldReasons(ws, now)
capped, noCredits := heldBy(ws)
return fmt.Sprintf("usage limit reached on the one account this conversation can go to — %s. The conversation was compacted natively by %s, and only that key or account can read the compaction it sealed, so magpie doesn't send it to another account that serves %q, which would refuse it; the routing mode and how conversations stay don't change that. magpie uses it again once that window renews; %s, or start a new conversation", strings.Join(held, "; "), cp.Who, model, heldAdvice(capped, noCredits)), soonest
return fmt.Sprintf("usage limit reached on the one account this conversation can go to — %s. The conversation was compacted natively by %s, and only that key or account can read the compaction it sealed, so magpie doesn't send it to another account that serves %q, which would refuse it; the routing mode and how conversations stay don't change that. magpie uses it again once that window renews; %s, or start a new conversation", strings.Join(held, "; "), cp.Who, model, heldAdvice(ws)), soonest
}
// heldReasons is what holds each account of ws held at a share, and the
@@ -1088,6 +1091,9 @@ func heldReasons(ws []Weighed, now time.Time) ([]string, time.Time) {
}
if w.NoCredits {
s = fmt.Sprintf("%s (%s) has used up a usage window and is set not to spend its credits", w.Name, w.Who)
if w.ExtraUsage {
s = fmt.Sprintf("%s (%s) has used up a usage window and is set not to spend extra usage", w.Name, w.Who)
}
}
if w.Unread != "" {
s = fmt.Sprintf("%s (%s) is held, as %s and its provider is set to check usage near the cap", w.Name, w.Who, w.Unread)
@@ -1147,15 +1153,48 @@ func spendPeriod(period string, since *time.Time, now time.Time) string {
return "for today"
}
// heldAdvice is how to go on now past what heldBy says holds.
func heldAdvice(capped, noCredits bool) string {
switch {
case !noCredits:
// heldAdvice is how to go on now past what heldBy says holds, by what
// ws holds back from being spent: a Codex account's credits, a Claude
// account's extra usage, or both.
func heldAdvice(ws []Weighed) string {
capped, noCredits := heldBy(ws)
if !noCredits {
return "raise or lift the cap in magpie (Providers → the account's cap, or magpie provider account-cap)"
case !capped:
return "to go on now, if an account holds credits, let it spend them (Usage → the account's Use credits, or magpie quota credits <account> on)"
}
return "to go on now, raise or lift a cap (Providers → the account's cap, or magpie provider account-cap) or, if an account holds credits, let it spend them (Usage → the account's Use credits, or magpie quota credits <account> on)"
credits, extra := heldSpends(ws)
var let []string
if credits {
let = append(let, "if an account holds credits, let it spend them (Usage → the account's Use credits, or magpie quota credits <account> on)")
}
if extra {
let = append(let, "let a Claude account spend extra usage (Providers → Claude → Advanced → Spend extra usage on, or magpie settings set claudeNoExtraUsage off) or lift the cap on its Usage credits")
}
if !capped {
return "to go on now, " + strings.Join(let, ", or ")
}
return "to go on now, raise or lift a cap (Providers → the account's cap, or magpie provider account-cap) or " + strings.Join(let, ", or ")
}
// heldSpends says what the accounts of ws held at 100% are held from
// spending: a Codex account's credits, a Claude account's extra usage.
func heldSpends(ws []Weighed) (credits, extra bool) {
for _, w := range ws {
if w.Capped > 0 && w.NoCredits {
credits, extra = credits || !w.ExtraUsage, extra || w.ExtraUsage
}
}
return credits, extra
}
// notSpent names what heldSpends says ws's accounts don't spend.
func notSpent(ws []Weighed) string {
switch credits, extra := heldSpends(ws); {
case extra && credits:
return "its credits or extra usage"
case extra:
return "extra usage"
}
return "its credits"
}
// heldBy says what holds the accounts of ws held at a share: a usage cap
@@ -1176,9 +1215,9 @@ func checkpointCappedRecord(ws []Weighed) string {
case !noCredits:
return "native compaction's account at its usage cap"
case !capped:
return "native compaction's account held: set not to spend its credits"
return "native compaction's account held: set not to spend " + notSpent(ws)
}
return "native compaction's account held: at its usage cap or set not to spend its credits"
return "native compaction's account held: at its usage cap or set not to spend " + notSpent(ws)
}
// cappedRecord is the call's record of the same refusal as cappedError,
@@ -1194,9 +1233,9 @@ func cappedRecord(ws []Weighed) string {
case !noCredits:
return "every account at its usage cap"
case !capped:
return "every account held: set not to spend its credits"
return "every account held: set not to spend " + notSpent(ws)
}
return "every account held: at its usage cap or set not to spend its credits"
return "every account held: at its usage cap or set not to spend " + notSpent(ws)
}
// unread says whether one of ws is held as its usage can't be told
@@ -1245,7 +1284,7 @@ func barredOf(cs []candidate, q provider.Provider, fallback bool, from provider.
w := weighed(c, q, weighing{}, fallback, from)
w.Unlisted, w.Via = true, via
if h := c.capped; h != nil {
w.Capped, w.Used, w.NoCredits, w.Unread = h.cap, h.used, h.noCredits, h.unread
w.Capped, w.Used, w.NoCredits, w.ExtraUsage, w.Unread = h.cap, h.used, h.noCredits, h.extra, h.unread
w.CapAmount, w.CapCount, w.CapUnit = h.amount, h.count, h.unit
if sp := h.spend; sp != nil {
w.SpendCap, w.Spent, w.SpendPeriod = sp.usd, sp.spent, sp.period
+4
View File
@@ -417,6 +417,10 @@ type Weighed struct {
// NoCredits: held at 100% (Capped), a Codex account the user set not
// to spend its credits once its allowance is used up
NoCredits bool `json:"noCredits,omitempty"`
// ExtraUsage: beside NoCredits, a Claude account held so as it is set
// not to spend extra usage, or its extra usage is at the cap set on
// its Usage credits (provider.ClaudeExtraUsage)
ExtraUsage bool `json:"extraUsage,omitempty"`
// Unread: held (Capped) by a careful provider as its usage can't be
// told, why: not read yet, the read failed, or too old near its cap
// (provider.Provider.CapCareful)
+9 -3
View File
@@ -14399,7 +14399,8 @@ function windowCapMeter(m, p, user, w) {
if (amount) b.append(el("span", "aq-own", t("Cap {n}", { n: amountText(amount) })));
else if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own })));
const reset = m.title || (w.resetsAt ? resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString(intlLang())) : "");
b.title = [reset, amount ? t("{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change", { window: name, n: amountText(amount) })
b.title = [reset, w.extra && (amount || own && own < 100) ? t("Once this account has spent {n} of its extra usage, magpie sends it nothing past its plan: it is used until its plan runs out, then rests until the plan renews. Click to change", { n: amount ? amountText(amount) : own + "%" })
: amount ? t("{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change", { window: name, n: amountText(amount) })
: own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name })
: own ? t("{window} has a cap of its own: magpie counts this account as used up once {window} is at {n}%, until it renews. Click to change", { window: name, n: own })
: t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n");
@@ -21800,9 +21801,14 @@ function renderReplies(s, keep) {
const c = segRow("claudeLeanRow", t("Short Claude system prompt"),
t("A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk"),
onOff, s.claudeLeanPrompt ? "on" : "off", (v) => savePrefs({ ...keep, claudeLeanPrompt: v === "on" }));
// whether a Claude account past its plan is sent requests Anthropic
// bills as extra usage (on unless turned off)
const x = segRow("claudeExtraRow", t("Spend extra usage"),
t("Once a Claude account has used up its plan, Anthropic bills further requests as extra usage. Off, magpie sends the account nothing until its plan renews, and your other accounts take the requests"),
onOff, s.claudeNoExtraUsage ? "off" : "on", (v) => savePrefs({ ...keep, claudeNoExtraUsage: v === "off" }));
box.append(r, l);
// a Claude run's, in its provider's editor (PROV_PREFS)
$("#claudeRunList").replaceChildren(c);
$("#claudeRunList").replaceChildren(c, x);
$("#claudeRunList").classList.toggle("gw", gatewayMode);
$("#routeList").replaceChildren(f, a, k, $("#busyLoadRow"), $("#contextCapRow"));
}
@@ -22812,7 +22818,7 @@ function prefsKeep(s) {
redact: !!s.redact, redactPersonal: !!s.redactPersonal, redactKinds: s.redactKinds || {}, redactWords: s.redactWords || [], redactWordsAnyCase: !!s.redactWordsAnyCase, redactWordsWhole: !!s.redactWordsWhole, redactShape: !!s.redactShape, codexWarmup: s.codexWarmup || "",
claudeWarmup: s.claudeWarmup || "", codexWarmAt: s.codexWarmAt || "", claudeWarmAt: s.claudeWarmAt || "",
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, checkinAt: s.checkinAt || "", noStats: !!s.noStats, noUsageStats: !!s.noUsageStats, signInLinkOnly: !!s.signInLinkOnly,
replyModel: s.replyModel || "", noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null, retryAfterCap: s.retryAfterCap ?? null,
replyModel: s.replyModel || "", noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudeNoExtraUsage: !!s.claudeNoExtraUsage, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null, retryAfterCap: s.retryAfterCap ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayNoNumber: !!s.trayNoNumber, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", videoGen: s.videoGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd", totalCurrency: s.totalCurrency || "", trayCurrency: s.trayCurrency || "",
chineseUnits: !!s.chineseUnits, dayStart: s.dayStart || 0, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
+12
View File
@@ -543,6 +543,9 @@ const I18N = {
"As the vendor wrote it (glm-5.3-flash-202606), for every agent, groups included": "厂商写的原样(glm-5.3-flash-202606),对所有 agent,路由组也一样",
"Stop looping replies": "停止循环的回复",
"Short Claude system prompt": "精简 Claude 系统提示词",
"Spend extra usage": "花费额外用量",
"Once a Claude account has used up its plan, Anthropic bills further requests as extra usage. Off, magpie sends the account nothing until its plan renews, and your other accounts take the requests": "Claude 账号用完套餐后,Anthropic 会把之后的请求按额外用量计费。关闭后,magpie 在套餐恢复前不再向这个账号发请求,由你的其他账号接手",
"Once this account has spent {n} of its extra usage, magpie sends it nothing past its plan: it is used until its plan runs out, then rests until the plan renews. Click to change": "这个账号的额外用量花到 {n} 后,magpie 不再让它超出套餐:套餐用完前照常使用,之后等套餐恢复。点按可更改",
"Claude Code's interactive mode": "Claude Code 交互模式",
"Claude Code isn't installed on this computer": "这台电脑上没有安装 Claude Code",
"A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. On, a request runs as -p only when Anthropic refuses its agent's prompt there. Off runs every request as claude -p": "Claude 订阅像人一样以交互模式运行 Claude Code,套餐对每次请求的计量约为 -p 的一半。开启时,只有 Anthropic 在交互模式里拒绝了 Agent 的提示词,请求才走 -p。关闭则每个请求都以 claude -p 运行",
@@ -5803,6 +5806,9 @@ const I18N = {
"As the vendor wrote it (glm-5.3-flash-202606), for every agent, groups included": "廠商寫的原樣(glm-5.3-flash-202606),對所有 agent,路由組也一樣",
"Stop looping replies": "停止循環的回覆",
"Short Claude system prompt": "精簡 Claude 系統提示詞",
"Spend extra usage": "花費額外用量",
"Once a Claude account has used up its plan, Anthropic bills further requests as extra usage. Off, magpie sends the account nothing until its plan renews, and your other accounts take the requests": "Claude 帳號用完方案後,Anthropic 會把之後的請求按額外用量計費。關閉後,magpie 在方案恢復前不再向這個帳號送出請求,由你的其他帳號接手",
"Once this account has spent {n} of its extra usage, magpie sends it nothing past its plan: it is used until its plan runs out, then rests until the plan renews. Click to change": "這個帳號的額外用量花到 {n} 後,magpie 不再讓它超出方案:方案用完前照常使用,之後等方案恢復。點按可更改",
"Claude Code's interactive mode": "Claude Code 互動模式",
"Claude Code isn't installed on this computer": "這台電腦上沒有安裝 Claude Code",
"A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. On, a request runs as -p only when Anthropic refuses its agent's prompt there. Off runs every request as claude -p": "Claude 訂閱像人一樣以互動模式執行 Claude Code,方案對每次請求的計量約為 -p 的一半。開啟時,只有 Anthropic 在互動模式裡拒絕了 Agent 的提示詞,請求才走 -p。關閉則每個請求都以 claude -p 執行",
@@ -11031,6 +11037,9 @@ const I18N = {
"As the vendor wrote it (glm-5.3-flash-202606), for every agent, groups included": "ベンダーが書いたまま(glm-5.3-flash-202606)。どのエージェントにも、ルーティンググループでも",
"Stop looping replies": "ループする応答を止める",
"Short Claude system prompt": "Claude のシステムプロンプトを短く",
"Spend extra usage": "追加使用量を使う",
"Once a Claude account has used up its plan, Anthropic bills further requests as extra usage. Off, magpie sends the account nothing until its plan renews, and your other accounts take the requests": "Claude アカウントがプランを使い切ると、以降のリクエストは Anthropic により追加使用量として請求されます。オフにすると、プランが回復するまで magpie はそのアカウントに何も送らず、ほかのアカウントがリクエストを受けます",
"Once this account has spent {n} of its extra usage, magpie sends it nothing past its plan: it is used until its plan runs out, then rests until the plan renews. Click to change": "このアカウントの追加使用量が {n} に達すると、magpie はプランを超えて送りません。プランを使い切るまでは使い、その後はプランの回復を待ちます。クリックで変更",
"Claude Code's interactive mode": "Claude Code の対話モード",
"Claude Code isn't installed on this computer": "このコンピュータには Claude Code がインストールされていません",
"A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. On, a request runs as -p only when Anthropic refuses its agent's prompt there. Off runs every request as claude -p": "Claude サブスクリプションは人と同じように Claude Code を対話モードで実行し、プランはリクエストを -p の約半分として数えます。オンのときは、Anthropic が対話モードでエージェントのプロンプトを拒否したときだけ -p で実行します。オフにするとすべてのリクエストを claude -p で実行します",
@@ -16269,6 +16278,9 @@ const I18N = {
"As the vendor wrote it (glm-5.3-flash-202606), for every agent, groups included": "Wie der Anbieter ihn schreibt (glm-5.3-flash-202606), für jeden Agenten, auch bei Weiterleitungsgruppen",
"Stop looping replies": "Schleifende Antworten beenden",
"Short Claude system prompt": "Kurzer Claude-Systemprompt",
"Spend extra usage": "Zusätzliche Nutzung verbrauchen",
"Once a Claude account has used up its plan, Anthropic bills further requests as extra usage. Off, magpie sends the account nothing until its plan renews, and your other accounts take the requests": "Hat ein Claude-Konto seinen Plan aufgebraucht, rechnet Anthropic weitere Anfragen als zusätzliche Nutzung ab. Aus: magpie schickt dem Konto nichts, bis sein Plan sich erneuert, und deine anderen Konten übernehmen die Anfragen",
"Once this account has spent {n} of its extra usage, magpie sends it nothing past its plan: it is used until its plan runs out, then rests until the plan renews. Click to change": "Hat dieses Konto {n} seiner zusätzlichen Nutzung verbraucht, schickt magpie ihm nichts mehr über seinen Plan hinaus: Es wird genutzt, bis sein Plan aufgebraucht ist, und ruht dann, bis er sich erneuert. Klicken zum Ändern",
"Claude Code's interactive mode": "Interaktiver Modus von Claude Code",
"Claude Code isn't installed on this computer": "Claude Code ist auf diesem Computer nicht installiert",
"A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. On, a request runs as -p only when Anthropic refuses its agent's prompt there. Off runs every request as claude -p": "Ein Claude-Abo führt Claude Code wie ein Mensch im interaktiven Modus aus, wo der Plan eine Anfrage mit etwa der Hälfte von -p anrechnet. Ein: Eine Anfrage läuft nur dann als -p, wenn Anthropic dort den Prompt ihres Agenten ablehnt. Aus führt jede Anfrage als claude -p aus",
@@ -0,0 +1,105 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Claude subscription's editor (baksili_ on X: a Claude account past
// its plan goes on at Anthropic's extra usage, billed): Spend extra usage
// is On, as it always was, says what Off does, and Settings' search finds
// it; Off saves claudeNoExtraUsage with the rest of the settings kept, the
// page not moved by the click. In English, Simplified and Traditional
// Chinese, Japanese and German, 1100 and 420 wide.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { provPrefsProviders, openProvPrefs, inEditor, watchSettingsReads, settingsDrawn } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const words = {
en: { name: "Spend extra usage", off: "Off", on: "On", sub: "bills further requests as extra usage", risk: "other accounts take the requests" },
zh: { name: "花费额外用量", off: "关闭", on: "开启", sub: "按额外用量计费", risk: "由你的其他账号接手" },
"zh-TW": { name: "花費額外用量", off: "關閉", on: "開啟", sub: "按額外用量計費", risk: "由你的其他帳號接手" },
ja: { name: "追加使用量を使う", off: "オフ", on: "オン", sub: "追加使用量として請求", risk: "ほかのアカウントがリクエストを受けます" },
de: { name: "Zusätzliche Nutzung verbrauchen", off: "Aus", on: "An", sub: "als zusätzliche Nutzung ab", risk: "anderen Konten übernehmen die Anfragen" },
};
function serve(lang, saved) {
const settings = { lang, theme: "light", redact: true };
const state = { agents: [], profiles: [], settings };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/settings") {
if (r.request().method() === "POST") {
saved.push(JSON.parse(r.request().postData()));
Object.assign(settings, saved.at(-1));
}
return json(settings);
}
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json(provPrefsProviders(["claude"], { claude: "Claude Code" }));
if (url.pathname === "/api/claude/mode") return json({ tui: !settings.claudePrintMode, why: settings.claudePrintMode ? "off" : "" });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await r.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) for (const width of [1100, 420]) {
const w = words[lang];
test(`${engine} ${lang} ${width}: extra usage can be turned off`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const saved = [];
await page.route("**/*", serve(lang, saved));
await openProvPrefs(page, "claude");
const row = page.locator(".editor .prov-prefs #claudeRunList > #claudeExtraRow");
await inEditor(page, row);
assert.equal(await row.locator(".name").textContent(), w.name);
const sub = await row.locator(".sub").textContent();
assert(sub.includes(w.sub) && sub.includes(w.risk), sub);
for (const part of [".name", ".segs"]) {
const fit = await row.locator(part).first().evaluate((e) => {
const r = e.getBoundingClientRect();
return e.scrollWidth <= e.clientWidth + 1 && r.width > 0 && r.right <= innerWidth + 1;
});
assert(fit, `${part} fits at ${width}`);
}
const on = row.locator(".segs button", { hasText: w.on });
const off = row.locator(".segs button", { hasText: w.off });
assert.equal(await on.getAttribute("aria-pressed"), "true", "On at first");
const before = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]);
const b = await off.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
await page.waitForFunction(() => document.querySelector("#claudeExtraRow"));
for (let i = 0; i < 50 && !saved.length; i++) await page.waitForTimeout(50);
assert.equal(saved.length, 1, "saved once");
assert.equal(saved[0].claudeNoExtraUsage, true);
assert.equal(saved[0].claudeLeanPrompt, false, "the row beside it kept");
assert.equal(saved[0].redact, true, "the rest kept");
assert.equal(saved[0].lang, lang);
assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), before, "the click moved nothing");
// Settings has it no more, and its search leads to the editor
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=models");
await settingsDrawn(page);
assert.equal(await page.locator("#view-settings #claudeExtraRow").count(), 0, "not in Settings");
await page.locator("#setQ").fill(w.name);
const link = page.locator("#provPrefLinks .agent-pref-link", { hasText: w.name }).first();
await link.waitFor();
await link.locator("button").click();
await page.locator(".editor .prov-prefs #claudeExtraRow").waitFor();
assert.deepEqual(errors, []);
});
}
}
@@ -91,6 +91,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await openProvPrefs(page, "claude");
assert.equal(await box.locator("#claudeWarmList").count(), 1, "Claude's warm-up");
assert(await box.locator("#claudeRunList #claudeLeanRow").isVisible(), "Claude's short system prompt");
assert(await box.locator("#claudeRunList #claudeExtraRow").isVisible(), "Claude's extra usage");
assert.equal(await box.locator("#codexWarmList, #codexResetList").count(), 0);
await openProvPrefs(page, "workbuddy");
+28
View File
@@ -521,9 +521,13 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol
return nil
}
model = strings.ToLower(model)
caps = a.extraCapped(model, caps, now)
var h *CapHold
unknown, byCap := false, false
for _, l := range a.capLimits(model) {
if l.extra {
continue // held by extraCapped's 100%, not by itself
}
share, credits, amount := caps.limitShare(l.Name, l.Of, l.aside)
if !past(share, amount, l.Used, l.Amount) {
continue
@@ -558,6 +562,29 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol
return h
}
// extraCapped is caps with Credits set — the account held at 100% of any
// plan window with no cap of its own, as ClaudeNoExtraUsage holds it —
// when a counts model with a Claude account's extra usage (Limit.extra)
// at or past a cap the user set on it, not renewed since: what the plan
// has left is still used, and no more extra usage is spent.
func (a Allowance) extraCapped(model string, caps WindowCaps, now time.Time) WindowCaps {
if caps.Credits {
return caps
}
for _, l := range a.capLimits(model) {
if !l.extra {
continue
}
share, _, amount := caps.limitShare(l.Name, l.Of, l.aside)
if !past(share, amount, l.Used, l.Amount) || !l.Resets.IsZero() && !l.Resets.After(now) {
continue
}
caps.Credits = true
return caps
}
return caps
}
// NearCap says whether an allowance, as last known, has some window
// counting model within points of its own share of caps (or past it) at
// now, not renewed since: a careful provider reads such an account again
@@ -568,6 +595,7 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti
return false
}
model = strings.ToLower(model)
caps = a.extraCapped(model, caps, now)
for _, l := range a.capLimits(model) {
share, _, amount := caps.limitShare(l.Name, l.Of, l.aside)
if share <= 0 || l.Used < share-points && (amount <= 0 || l.Amount < amount) {
+31
View File
@@ -0,0 +1,31 @@
package provider
// Whether a Claude subscription account spends extra usage. Once a plan
// window that stops a Claude account (its 5 hours, its week) is used up,
// Anthropic goes on serving it on the account's extra usage — usage credits
// bought beyond the plan, when the account has it turned on — and bills it.
// magpie can't turn that off at Anthropic, so it holds back its own
// requests instead (baksili_ on X): with Settings' ClaudeNoExtraUsage on,
// routing holds such an account at 100% of any window with no cap of its
// own, as a Codex account set not to spend its credits is held
// (codex_credits.go), and the user's other accounts, groups and fallbacks
// take the request. The hold goes by magpie's latest reading, so a request
// in the minute after a window fills may still reach the account; and a
// Claude Code signed in to the account directly, not through magpie, is
// Anthropic's alone to bill. Claude Code's sign-in already moves off an
// account on its overages (usedPast counts the "Extra usage" window).
// Warm-ups (codex_warmup.go) send nothing to an account held so.
//
// The extra usage's own window, "Usage credits" (claudeExtraWindow), set
// aside from the allowance, also takes a cap of the user's: a share of its
// monthly limit, or an amount of its currency. Reached, it doesn't hold
// the account outright — the plan's own windows still have what they have
// — but holds it as the setting would, at 100% of a plan window, so no
// more extra usage is spent this month (Allowance.extraCapped).
import "github.com/yetone/magpie/internal/settings"
// ClaudeExtraUsage says whether magpie sends a Claude account requests
// once its plan is used up, for Anthropic to bill as extra usage: true
// unless the user turned it off.
func ClaudeExtraUsage() bool { return !settings.Load().ClaudeNoExtraUsage }
+184
View File
@@ -0,0 +1,184 @@
package provider
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// noExtraUsage turns Claude's Extra usage off (ClaudeNoExtraUsage) for
// the test.
func noExtraUsage(t *testing.T, off bool) {
t.Helper()
if err := settings.Save(settings.Settings{ClaudeNoExtraUsage: off}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = settings.Save(settings.Settings{}) })
}
// claudeRead is a Claude account's windows as /usage tells them: its five
// hours and week at the shares given, on overages once one is used up,
// with spent of its 50 USD of extra usage.
func claudeRead(five, week, spent float64, now time.Time) []QuotaWindow {
r5, r7 := now.Add(2*time.Hour), now.Add(3*24*time.Hour)
ws := []QuotaWindow{
{Name: "5 hours", Used: five, Span: 5 * time.Hour, ResetsAt: &r5},
{Name: "7 days", Used: week, Span: 7 * 24 * time.Hour, ResetsAt: &r7},
{Name: "Usage credits", Used: spent / 50 * 100, Aside: true, Extra: true, Amount: spent, Limit: 50, Unit: "USD"},
}
if five >= 100 || week >= 100 {
ws = append(ws, claudeOveragesWindow(ws))
}
return ws
}
// baksili_ on X: a Claude account past its plan goes on at Anthropic's
// extra usage, billed. With Extra usage off in magpie (off by default:
// nothing changes for anyone who didn't turn it off) every Claude account
// is held at 100% of a plan window, as a Codex account set not to spend
// its credits is, while what its plan has left is still used; a Codex
// account's credits are not touched by it.
func TestClaudeNoExtraUsageHoldsAtThePlan(t *testing.T) {
signIn(t)
now := time.Now()
p := Provider{ID: "claude"}
if !ClaudeExtraUsage() || HoldCaps(p, "claude", "c@example.com").Holds() {
t.Fatal("held by default")
}
full := allowanceOf(claudeRead(100, 40, 12, now), now)
if h := full.CapHeld("claude-sonnet-5", HoldCaps(p, "claude", "c@example.com"), now); h != nil {
t.Fatalf("held by default at 100%%: %+v", h)
}
noExtraUsage(t, true)
if ClaudeExtraUsage() {
t.Fatal("on, though turned off")
}
caps := HoldCaps(p, "claude", "c@example.com")
if share, credits := caps.Of("5 hours"); share != 100 || !credits {
t.Fatalf("held at %d (credits %v)", share, credits)
}
h := full.CapHeld("claude-sonnet-5", caps, now)
if h == nil || h.Cap != 100 || !h.Credits || h.Back.Before(now.Add(time.Hour)) {
t.Fatalf("used up, not held at 100%%: %+v", h)
}
if h := allowanceOf(claudeRead(60, 99, 0, now), now).CapHeld("claude-sonnet-5", caps, now); h != nil {
t.Fatalf("held with its plan not used up: %+v", h)
}
// a cap of the user's own still holds at it
capped := Provider{ID: "claude", AccountCaps: map[string]int{"c@example.com": 70}}
if h := allowanceOf(claudeRead(75, 20, 0, now), now).CapHeld("claude-sonnet-5", HoldCaps(capped, "claude", "c@example.com"), now); h == nil || h.Cap != 70 || h.Credits {
t.Fatalf("its own cap: %+v", h)
}
// Codex's credits are their own switch
if share, credits := HoldCaps(Provider{ID: "codex"}, "codex", "x@example.com").Of("5 hours"); share != 0 || credits {
t.Fatalf("a Codex account held at %d (credits %v)", share, credits)
}
}
// A cap on a Claude account's Usage credits (its extra usage) holds the
// account at 100% of its plan once that much extra usage is spent: never
// before its plan is used up, as the plan costs nothing more. Below the
// cap it goes on at its extra usage, as the vendor lets it.
func TestClaudeExtraUsageCapHoldsAtThePlan(t *testing.T) {
now := time.Now()
for _, c := range []struct {
name string
caps WindowCaps
five, spent float64
held, heldAtPlanOK bool
}{
{"amount reached, plan used up", WindowCaps{Amounts: map[string]float64{"usage credits": 20}}, 100, 20, true, false},
{"amount reached, plan has room", WindowCaps{Amounts: map[string]float64{"usage credits": 20}}, 60, 25, false, false},
{"amount not reached", WindowCaps{Amounts: map[string]float64{"usage credits": 20}}, 100, 19.5, false, false},
{"share reached, plan used up", WindowCaps{Windows: map[string]int{"usage credits": 40}}, 100, 20, true, false},
{"share not reached", WindowCaps{Windows: map[string]int{"usage credits": 40}}, 100, 15, false, false},
} {
al := allowanceOf(claudeRead(c.five, 30, c.spent, now), now)
h := al.CapHeld("claude-opus-5-5", c.caps, now)
if (h != nil) != c.held {
t.Errorf("%s: held %+v", c.name, h)
continue
}
if h != nil && (h.Cap != 100 || !h.Credits) {
t.Errorf("%s: held at %d (credits %v), want 100%% of the plan", c.name, h.Cap, h.Credits)
}
}
}
// An amount cap on a window set aside (WorkBuddy's credits beside its
// plan) holds the account once that much of it is used: the aside
// window's count reaches its cap, as a plan window's does.
func TestAsideWindowAmountCapHolds(t *testing.T) {
now := time.Now()
day := now.Add(5 * time.Hour)
al := allowanceOf([]QuotaWindow{
{Name: "Plan", Used: 20, Span: 24 * time.Hour, ResetsAt: &day},
{Name: "Credits", Used: 25, Aside: true, Amount: 250, Limit: 1000, Unit: "credits", ResetsAt: &day},
}, now)
caps := WindowCaps{Amounts: map[string]float64{"credits": 200}}
h := al.CapHeld("m", caps, now)
if h == nil || h.Amount != 200 || h.Count != 250 || h.Unit != "credits" || h.Credits {
t.Fatalf("250 of a 200 cap: %+v", h)
}
if h := al.CapHeld("m", WindowCaps{Amounts: map[string]float64{"credits": 300}}, now); h != nil {
t.Fatalf("250 of a 300 cap: %+v", h)
}
}
// The warm-up sends a held account nothing while it is used up: a
// request then would be billed as extra usage (Claude) or spend credits
// (Codex) the user set it not to spend. Its windows stay due, and go out
// once it has room again.
func TestWarmUpSendsAHeldAccountNothing(t *testing.T) {
now := time.Date(2026, 11, 13, 9, 0, 0, 0, time.UTC)
weekEnd := now.Add(2 * 24 * time.Hour)
q := SubscriptionQuota{Windows: []QuotaWindow{
{Name: "5 hours", Span: fiveHours}, // not started
win("7 days", week, 100, weekEnd),
}}
q.Windows = append(q.Windows, claudeOveragesWindow(q.Windows))
held, sent := true, 0
w := codexWarmer{path: filepath.Join(t.TempDir(), "w.json"), now: func() time.Time { return now },
usage: func(context.Context) map[string]SubscriptionQuota { return map[string]SubscriptionQuota{"a@x": q} },
send: func(context.Context, string) error { sent++; return nil },
held: func(string, SubscriptionQuota, time.Time) bool { return held },
expect: claudeWindowsExpected}
if rs := w.warmNow(context.Background(), "all", nil); sent != 0 || len(rs) != 0 {
t.Fatalf("held and used up: sent %d %+v", sent, rs)
}
held = false
if w.warmNow(context.Background(), "all", nil); sent != 1 {
t.Fatalf("not held: sent %d", sent)
}
}
// claudeHeldFull, the Claude warm-up's hold: Extra usage off, or the
// account's extra usage at the cap set on it.
func TestClaudeHeldFull(t *testing.T) {
home := claudeHome(t)
claudeSignIn(t, home, time.Now().Add(time.Hour))
now := time.Now()
q := SubscriptionQuota{Windows: claudeRead(100, 30, 30, now)}
if claudeHeldFull("c@example.com", q, now) {
t.Fatal("held with Extra usage on and no cap")
}
// saved as SetWindowAmount saves it, which wants the account's email
// from a /usage read this test has none of
if err := Save(Provider{ID: "claude", AccountWindowAmounts: map[string]map[string]float64{"c@example.com": {WindowCapID("Usage credits"): 25}}}); err != nil {
t.Fatal(err)
}
if !claudeHeldFull("c@example.com", q, now) {
t.Fatalf("30 USD past a 25 USD cap, not held: %+v", AccountCapsOf("claude", "c@example.com"))
}
if claudeHeldFull("d@example.com", q, now) {
t.Fatal("another account held by its cap")
}
noExtraUsage(t, true)
if !claudeHeldFull("d@example.com", q, now) {
t.Fatal("Extra usage off, not held")
}
}
+1 -1
View File
@@ -147,7 +147,7 @@ func claudeExtraWindow(lines []string) (QuotaWindow, bool) {
if err1 != nil || err2 != nil || limit <= 0 {
continue
}
return QuotaWindow{Name: "Usage credits", Used: math.Min(100, spent/limit*100), Aside: true,
return QuotaWindow{Name: "Usage credits", Used: math.Min(100, spent/limit*100), Aside: true, Extra: true,
Amount: spent, Limit: limit, Unit: strings.ToUpper(m[3])}, true
}
return QuotaWindow{}, false
+12 -1
View File
@@ -82,6 +82,17 @@ func ClaudeWarmed() map[string]time.Time { return codexWarmedIn(claudeWarmPath()
// while settings say to, each with one request send makes.
func KeepClaudeWindowsWarm(ctx context.Context, send func(ctx context.Context, configDir string) error) {
w := codexWarmer{path: claudeWarmPath(), now: time.Now, usage: claudeWarmUsage, send: warmClaudeLogin(send),
expect: claudeWindowsExpected, warmed: claudeWarmedNow}
expect: claudeWindowsExpected, warmed: claudeWarmedNow, held: claudeHeldFull}
keepWarm(ctx, "claude", w, func() (string, []string) { s := settings.Load(); return s.ClaudeWarmup, s.ClaudeWarmAts })
}
// claudeHeldFull says whether the Claude account user, read as q, is held at 100% of
// a used-up window rather than spending extra usage: set so for every
// account (ClaudeExtraUsage), or its extra usage at the cap set on its
// Usage credits (Allowance.extraCapped).
func claudeHeldFull(user string, q SubscriptionQuota, now time.Time) bool {
if !ClaudeExtraUsage() {
return true
}
return allowanceOf(q.Windows, now).extraCapped("", AccountCapsOf("claude", user), now).Credits
}
+9 -3
View File
@@ -117,10 +117,16 @@ func SetCodexCreditsMode(user, mode string) error {
// HoldCaps is the shares of its windows at which routing holds the
// account user of p, of agent, as used up: its usage cap and its windows'
// own (account_caps.go), and for a Codex account set not to spend its
// credits 100% of any window with no cap. Holds() is false when nothing
// holds it before the vendor does.
// credits, or a Claude account set not to spend extra usage
// (claude_extra.go), 100% of any window with no cap. Holds() is false
// when nothing holds it before the vendor does.
func HoldCaps(p Provider, agent, user string) WindowCaps {
c := p.CapsOf(user)
c.Credits = agent == "codex" && user != "" && !CodexCredits(user)
switch agent {
case "codex":
c.Credits = user != "" && !CodexCredits(user)
case "claude":
c.Credits = !ClaudeExtraUsage()
}
return c
}
+21 -1
View File
@@ -114,6 +114,19 @@ type codexWarmer struct {
// own, by name in lower case, "" for none: theirs in place of the ones
// warmNow is given (#957).
ownAt func() map[string]string
// held, when set, says an account is held at 100% of a used-up window
// rather than spending past it — a Codex account set not to spend its
// credits, a Claude account not to spend extra usage — by its reading
// q at now: it is sent nothing while used up (usedUp), as the vendor
// would bill the request past the plan (spentPast).
held func(user string, q SubscriptionQuota, now time.Time) bool
}
// spentPast says whether a request to q's account now would be billed
// past its plan, which the user set it not to be (held): a window that
// stops it is used up.
func (c codexWarmer) spentPast(user string, q SubscriptionQuota, now time.Time) bool {
return c.held != nil && usedUp(q, now) && c.held(user, q, now)
}
// atOf is the times of day user's 5-hour window starts at: its own, else
@@ -225,6 +238,12 @@ func (c codexWarmer) warmNow(ctx context.Context, which string, dayAts []string)
// the weekly windows wait for the day's start too, kept as they were
due = slices.DeleteFunc(due, func(name string) bool { return long[name] })
}
if len(due) > 0 && c.spentPast(user, q, now) {
// held, as a request would go on the credits or extra usage
// the user set it not to spend: the windows wait, due still
// (kept as they were, or the day's start not marked done)
due = nil
}
if len(due) > 0 {
r := CodexWarm{User: user, Windows: due}
err := c.send(ctx, user)
@@ -587,7 +606,8 @@ func SetCodexWarmAt(user, at string) error {
// codexWarmEvery after that, until ctx ends.
func KeepCodexWindowsWarm(ctx context.Context) {
w := codexWarmer{path: codexWarmPath(), now: time.Now, usage: codexWarmUsage, send: warmCodexLogin,
warmed: func(user string) { StaleAllowance("codex", user) }, ownAt: codexWarmAtOf}
warmed: func(user string) { StaleAllowance("codex", user) }, ownAt: codexWarmAtOf,
held: func(user string, _ SubscriptionQuota, _ time.Time) bool { return !CodexCredits(user) }}
keepWarm(ctx, "codex", w, func() (string, []string) { s := settings.Load(); return s.CodexWarmup, s.CodexWarmAts })
}
+1
View File
@@ -58,6 +58,7 @@ func TestQuotaSpanCarriesEveryWindowField(t *testing.T) {
"resetSecs": "made into resetsAt from the report's now",
"family": "the Usage page's grouping of per-model windows",
"credits": "routing's (Allowance.OnCredits)",
"extra": "routing's (Allowance.extraCapped)",
"capped": "the GUI's cap marks (WithCapped)",
"capsSome": "the GUI's cap marks (WithCapped)",
"capId": "the GUI's cap marks (WithCapped)",
+7 -1
View File
@@ -370,6 +370,10 @@ type Limit struct {
// account at (WindowCaps.own); it rides in pool, never in the
// allowance itself
aside bool
// extra is set beside aside on a Claude account's extra usage
// (QuotaWindow.Extra): its cap holds the account as
// ClaudeNoExtraUsage would (Allowance.extraCapped), not outright
extra bool
// ResetRunsOut is when the reset the account spends by itself before
// it runs out does (resetRunsOut): spent then, it starts this window
// again — at Restarts, which routing takes for the window's renewal
@@ -1341,7 +1345,9 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {
if !w.Aside || w.Text || w.Model != "" || w.PoolWindow() {
continue
}
al := Limit{Used: w.Used, Span: w.Span, Name: w.Name, Resets: resets(w), aside: true}
// with its count, so a cap of an amount of its unit holds too
al := Limit{Used: w.Used, Span: w.Span, Name: w.Name, Resets: resets(w), aside: true,
Amount: w.Amount, Of: w.Limit, Unit: w.Unit, extra: w.Extra}
for i := range a {
a[i].pool = append(a[i].pool, al)
}
+5
View File
@@ -101,6 +101,11 @@ type QuotaWindow struct {
// (Allowance.OnCredits); kept
// with the reading, so one shown from before still says it.
Credits bool `json:"credits,omitempty"`
// Extra is set on a Claude account's "Usage credits" window
// (claudeExtraWindow): the extra usage Anthropic bills past the plan,
// set aside. A cap the user sets on it holds the account at 100% of a
// plan window once reached (Allowance.extraCapped), never outright.
Extra bool `json:"extra,omitempty"`
// Capped is set, for the GUI only (WithCapped), on a window an
// account's usage cap counts: neither Aside nor unlimited. One model's
// own counts for that model (CapHeld), so it is marked like the rest.
+9
View File
@@ -494,6 +494,15 @@ type Settings struct {
// real Claude Code, its billing line and identity line kept; off, as by
// default, the run is the shape every Claude Code run has.
ClaudeLeanPrompt bool `json:"claudeLeanPrompt,omitempty"`
// ClaudeNoExtraUsage keeps magpie from sending a Claude subscription
// account a request once a plan window that stops it is used up,
// where Anthropic would go on on the account's extra usage (usage
// credits bought beyond the plan, baksili_ on X): routing holds it at
// 100% of that window, as a Codex account set not to spend its
// credits (CodexNoCredits), and the user's other accounts, groups and
// fallbacks take the request. Off, as by default, such an account is
// sent requests and Anthropic decides whether extra usage pays.
ClaudeNoExtraUsage bool `json:"claudeNoExtraUsage,omitempty"`
// ClaudePrintMode runs a Claude subscription's Claude Code as `claude
// -p` always. Off, as by default, a model request runs in Claude
// Code's interactive mode, as a person runs it, and never as -p: the
+1 -1
View File
@@ -45,7 +45,7 @@ var Keys = []string{
"codexWarmup", "claudeWarmup", "codexWarmAt", "claudeWarmAt", "codexWarmAts", "claudeWarmAts",
"workbuddyCheckin", "traeCheckin", "minimaxCheckin", "qoderCheckin", "checkinAt",
// models: replies, vision, images, search
"replyModel", "noLoopGuard", "claudeLeanPrompt", "claudePrintMode", "refusalRetries", "retryAfterCap",
"replyModel", "noLoopGuard", "claudeLeanPrompt", "claudeNoExtraUsage", "claudePrintMode", "refusalRetries", "retryAfterCap",
"vision", "visionEffort", "imageGen", "videoGen", "imageTimeout", "classifyTimeout",
// what every routing group does that says nothing of its own
"groupSink", "groupFirstToken", "groupPatience",