From 699ddf1524a7e0aee6ea5c6bb3aafb3bf594aadc Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 22:55:26 +0800 Subject: [PATCH] gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord) gokoshiki wants a Codex subscription first, then an OpenAI API key, then the subscription's credits. Until now an account at 100% that holds credits either kept its place and spent them there (on) or was held (off). This adds a third way per account, "last": - settings: CodexCreditsLast []string, empty by default, so a setting saved before it keeps its order. provider.CodexCreditsLast, CodexCreditsMode and SetCodexCreditsMode(user, on|last|off); SetCodexCredits(on) still means "in its place" and clears last. - gateway: candidate.creditsLast is true for such an account once a window for the model is used up and it is going on its credits (a call ChatGPT counts in no window stays in its place). restLast orders ready, then resting, then those, and marks Weighed.CreditsLast. restLast runs over the asides too, so such an account goes behind a provider's reserves (Accounts at once, 2c6b7c063) as well. lastBehind keeps In turn's next turn (after), a new conversation's spread (leastHeld) and a subagent's lead (readyForNew) from bringing it forward, and a kept conversation moves off it to one not on its credits (Affinity.Why "credits"). - CLI: magpie quota credits [on|last|off]; alone it lists accounts set off and last. - API: POST /api/settings/codex-credits takes {user, on, last?}. - GUI: under a Codex account's Use credits, while on, a second switch "Only after every other account, key and fallback", in the Usage page's card and the tray panel's (both wrap it to its own line at 360 to 900px), and the panel's folded brief says "On, after everything else". The Routing page's trace says why such an account is behind (aside, the kept conversation's why, the row tag). zh, zh-TW, ja, de. creditsButton and the new switch share creditsSwitch, and the Codex options' comments in app.js were cut, so the core budget holds with no raise (1,532,664 of 1,533,105). - docs: reference.md (quota credits) and gateway-routing.md. Tests: - gateway: TestCodexCreditsLastAfterTheOthers (two accounts, In order: the one at 100% on its credits goes behind, the trace says so, and back in place when turned on), TestCodexCreditsLastAfterTheFallback (both accounts at 100% and set last: the API key the provider falls back to answers before either one's credits; with the credits in their place an account answers on them, as before), TestCodexCreditsLastNotKept (a kept conversation moves off it). All three red with creditsLast and lastBehind forced false. - provider: TestCodexCreditsLastMode. - gui: settings_keep_test carries CodexCreditsLast; tests/codex-credits-last.test.cjs (Chromium and WebKit, en zh zh-TW ja de; Usage at 900 and 440, the panel at 440 and 360, the folded brief, the Routing page's aside and why, every key in I18N). Red on the old assets (no .ar-credits-last). Run at this change on origin/main c76bcaea7, on mote (pushed on fd70def82, whose one commit since, fd70def82, changes only the Providers poll's Go files in internal/gui): gofmt clean; go vet of gateway, provider, gui, cli and settings ok; their tests ok but internal/gui's #4514 and #3949, both on main. The 8 commits between d6aa9cdf6 and c76bcaea7 touch none of this change's files. Run at this change on origin/main d6aa9cdf6, Go 1.26.8: - mote: gofmt -l clean; go vet ./..., and GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. go test -count=1 -timeout 45m ./...: 85 packages ok; internal/gui red only on TestSettingsSaveKeepsWhatIt DoesNotSend's SearchAll (#4514), TestMainWindowCorners (#3949) and TestColdTurnsTaken (#4510), all three on main. TestCoreScriptBudget passes. - WSL magpie-desktop, Playwright 1.62.0, both engines: codex-credits*, i18n-keys, gui-ja, gui-zh-tw, panel-options-fold, provider-at-once and every routing-* file: 2127 tests, 2064 pass. Every codex-credits and codex-credits-last test passed (26). The red files (gui-ja, 19 routing files) run again at this tree and at d6aa9cdf6, alike: 200 tests, 61 and 57 red. gui-ja is #4580; the routing reds are timeouts and waits, on both. The one file red at this tree only, routing-request-model (WebKit 420px "the model is cut"), is 5 of 5 green alone at both, and with six copies at once red at both (29 and 27 of 30 here, 28 and 27 of 30 at d6aa9cdf6): a fixed 150ms wait after a resize, filed as #4650. Nothing this change adds to Routing draws unless an account is set last (fixtures don't). - Earlier, at 3564eb04b (this change on 7428f3229), WSL: the whole GUI suite beside two other sessions' suites, 16944 tests, 16496 pass; its 102 red files again at that head and at 7428f3229, 444 and 425 red. The files red at the head only, run alone: view-open-wheel, usage-accounts, add-button, usage-ledger-open-settled 0 red; view-wheel-after-click, view-wheel-unheard and context-map (#3488) red alone at 7428f3229 too. mote, the credits and i18n files: 172 of 174, the two #4580 and a click timeout in quota-curve at load 148 (alone 30 of 30). Not tried: a real ChatGPT account at 100% with credits beside a real OpenAI key; the order is shown with the gateway's fake Codex backend. --- docs/reference.md | 10 +- docs/subsystems/gateway-routing.md | 1 + internal/cli/quota_cli.go | 51 ++-- internal/gateway/affinity.go | 26 ++- internal/gateway/codex_credits_last_test.go | 139 +++++++++++ internal/gateway/fallback.go | 25 +- internal/gateway/routing.go | 18 ++ internal/gateway/trace.go | 4 + internal/gui/api.go | 14 +- internal/gui/assets/app.css | 4 + internal/gui/assets/app.js | 80 +++---- internal/gui/assets/i18n.js | 20 ++ internal/gui/assets/plugins/routing/client.js | 10 +- internal/gui/assets/plugins/routing/i18n.js | 20 ++ internal/gui/core_budget_test.go | 2 +- internal/gui/settings_keep_test.go | 1 + .../gui/tests/codex-credits-last.test.cjs | 220 ++++++++++++++++++ internal/provider/codex_credits.go | 61 ++++- internal/provider/codex_credits_test.go | 41 ++++ internal/settings/settings.go | 10 + 20 files changed, 672 insertions(+), 85 deletions(-) create mode 100644 internal/gateway/codex_credits_last_test.go create mode 100644 internal/gui/tests/codex-credits-last.test.cjs diff --git a/docs/reference.md b/docs/reference.md index b5e4cea6f..acd4bf651 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2459,8 +2459,13 @@ reading of its windows, refreshed about every minute, shows one used up, the gateway holds it as used up till the window renews, and requests go to the other accounts, groups and fallbacks; with none left, the request gets a 429 saying why, unless the account spends its resets by itself and its week -is used up, when a reset is spent first. `magpie quota credits` lists the -accounts set not to spend them, `magpie quota credits ` says one's. +is used up, when a reset is spent first. `magpie quota credits +last` (or *Only after everything else* under *Use credits*) keeps the +credits but spends them last: once a window is used up, the account is +tried after every other account, key and fallback that isn't on its +credits, so the order goes subscription, then API key, then the credits. +`magpie quota credits` lists the accounts set not to spend them and those +that spend them last, `magpie quota credits ` says one's. It changes the gateway's routing only, never the account Codex is signed in to. The credits an account holds show beside its windows in `magpie quota`, `magpie accounts`, the Usage page and the menu bar panel. @@ -2968,6 +2973,7 @@ magpie quota # what is left of every subscription, plan and k magpie quota refresh codex # read Codex's cards again now (once per 30s) magpie quota wait codex # block until a Codex account has allowance again magpie quota credits me@example.com off # hold a ChatGPT account at its limit instead of spending credits +magpie quota credits me@example.com last # spend its credits only after every other account, key and fallback magpie tools # the tools magpie's MCP servers give agents, with their parameters magpie tools generate_image # one tool in full diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a7e99784f..486aca59d 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -218,6 +218,7 @@ recorded as a prediction failure (`noPrediction`). - In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones, a provider's fallback while the provider's own leads (`standsIn`) and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. - Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Weekly pace: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`. +- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873). - One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/` as a restarted Codex's goes) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. Each try is a `HandedOn` usage record and a try in the trace. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)). - A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before. diff --git a/internal/cli/quota_cli.go b/internal/cli/quota_cli.go index 18f18f886..1cd9ca052 100644 --- a/internal/cli/quota_cli.go +++ b/internal/cli/quota_cli.go @@ -18,7 +18,7 @@ const quotaUsage = `usage: magpie quota […] [--json] magpie quota reset [] [--card ] [--yes] magpie quota auto-reset [] [week|expiring] [on|off] magpie quota auto-reset lead [|default] - magpie quota credits [] [on|off] + magpie quota credits [] [on|last|off] magpie quota alert [|off] [--balance |off] magpie quota wait [--timeout ] [--quiet] magpie quota history […] [--days ] [--json] @@ -53,7 +53,11 @@ const quotaUsage = `usage: magpie quota […] [--json] goes to the other accounts, groups and fallbacks, or is refused with why (with auto-reset on, its week used up and no one else left, it spends a reset first). on, the default, lets the vendor answer on its credits then, so the task goes - on (with auto-reset's week on, a reset held is spent before the credits); alone it says which accounts don't spend theirs. + on (with auto-reset's week on, a reset held is spent before the credits); last spends + them too, but only after everything else: once a window is used up the account is + tried after every other account, key and fallback that isn't on its credits, so a + subscription, then an API key, then the credits. Alone it says which accounts don't + spend theirs and which spend them last. quota alert 80 has the magpie app notify when any window of a subscription or plan reaches 80% used, once each time the window runs (not windows set aside, such as on-demand spending); --balance 5 when a balance falls to 5 or under, in its own @@ -480,14 +484,15 @@ func resetUsedWhy(why string) string { return "used by hand" } -// quotaCreditsCmd: magpie quota credits [] [on|off] — -// whether the account spends its credits once its allowance is used up. +// quotaCreditsCmd: magpie quota credits [] [on|last|off] +// — whether the account spends its credits once its allowance is used +// up, and with last only after everything else. func quotaCreditsCmd(args []string) error { - user, set, on := "", false, false + user, mode := "", "" for _, a := range args { switch strings.ToLower(a) { - case "on", "off": - set, on = true, strings.EqualFold(a, "on") + case provider.CreditsOn, provider.CreditsLast, provider.CreditsOff: + mode = strings.ToLower(a) case "help", "-h", "--help": fmt.Println(quotaUsage) return nil @@ -498,35 +503,47 @@ func quotaCreditsCmd(args []string) error { user = a } } - if !set && user == "" { - off := settings.Load().CodexNoCredits - if len(off) == 0 { - fmt.Println(muted.Render("every Codex account spends its credits once its allowance is used up ·"), "magpie quota credits off") + if mode == "" && user == "" { + s := settings.Load() + off, last := s.CodexNoCredits, s.CodexCreditsLast + if len(off) == 0 && len(last) == 0 { + fmt.Println(muted.Render("every Codex account spends its credits once its allowance is used up ·"), "magpie quota credits last|off") return nil } for _, u := range off { fmt.Println(muted.Render("○"), u, muted.Render("doesn't spend its credits: held once magpie reads a window used up")) } + for _, u := range last { + if provider.CodexCreditsLast(u) { + fmt.Println(muted.Render("◐"), u, muted.Render("spends its credits only after every other account, key and fallback")) + } + } return nil } user, err := codexAccountNamed(user) if err != nil { return err } - if !set { - if provider.CodexCredits(user) { + if mode == "" { + switch provider.CodexCreditsMode(user) { + case provider.CreditsOn: fmt.Println(user, "spends its credits once its allowance is used up") - } else { + case provider.CreditsLast: + fmt.Println(user, "spends its credits once its allowance is used up, only after every other account, key and fallback") + default: fmt.Println(user, "doesn't spend its credits: once magpie reads a window used up it is held till it renews") } return nil } - if err := provider.SetCodexCredits(user, on); err != nil { + if err := provider.SetCodexCreditsMode(user, mode); err != nil { return err } - if on { + switch mode { + case provider.CreditsOn: fmt.Println(green.Render("✓"), user+":", "spends its credits once its allowance is used up, so a task goes on") - } else { + case provider.CreditsLast: + fmt.Println(green.Render("✓"), user+":", "spends its credits once its allowance is used up, but only after every other account, key and fallback that isn't on its credits") + default: fmt.Println(green.Render("✓"), user+":", "no longer spends its credits: once magpie reads a window used up, requests go to the other accounts till it renews") } return nil diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 948ff6266..eab83529b 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -117,8 +117,10 @@ type Affinity struct { // again at a new turn: backToFirst), "back" (a member of a group // routed any other way stood in for one listed ahead of it that // couldn't take the conversation, and a member ahead is ready first - // at a new turn: backFromStandIn), "strict" (Stays: Strict, kept - // whatever it is). + // at a new turn: backFromStandIn), "credits" (a Codex account gone + // onto its credits answered it, set to spend them only after + // everything else, and one not on its credits leads: lastBehind), + // "strict" (Stays: Strict, kept whatever it is). Why string `json:"why"` // Main is, for a conversation kept strictly on a provider's fallback, // the provider's own key or account that is ready again: it would have @@ -588,6 +590,12 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr a.Why = "reserve" case pl.order[at].Rest != nil: a.Why = "resting" + case lastBehind(pl.order, at): + // a Codex account gone onto its credits, which the user set to + // spend only after everything else (creditsLast): whatever it + // has cached, the conversation goes to one not on its credits, + // within a turn too, as that is what the credits would pay for + a.Why = "credits" case !a.Within && backToMain(pl.order, at): // a provider's fallback is its emergency path, not a place a // conversation stays: once one of the provider's own keys or @@ -813,7 +821,7 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can seat := func(c candidate) string { return c.who() + "/" + provider.WithMemberEffort(c.model, c.effort) } best := -1 for i, c := range cs { - if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || ready && i > 0 && !readyForNew(pl.order, i) { + if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) || ready && i > 0 && !readyForNew(pl.order, i) { continue } if best < 0 || held[seat(c)] < held[seat(cs[best])] { @@ -839,7 +847,7 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can // lowShare. func readyForNew(order []Weighed, i int) bool { w := order[i] - return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare) + return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare) && !lastBehind(order, i) } // standsIn says whether order[i] is a provider's fallback while one of the @@ -854,6 +862,14 @@ func standsIn(order []Weighed, i int) bool { return i < len(order) && order[i].Fallback && !order[0].Fallback } +// lastBehind says whether order[i] is a Codex account on its credits set +// to spend them last (Weighed.CreditsLast) while one that isn't leads: +// restLast put it behind every such one, and spreading a conversation or +// taking a turn never brings it forward past them. +func lastBehind(order []Weighed, i int) bool { + return i > 0 && i < len(order) && order[i].CreditsLast && !order[0].CreditsLast +} + // withLead puts first, for a subagent's conversation nobody has answered // yet (a key stickKey gave "|agent:"), the key or account its session's // lead is on, while that one is readyForNew: under spreadsSessions the @@ -903,7 +919,7 @@ func spreadsSessions(mode, routing string) bool { func after(cs []candidate, pl planned, at int) ([]candidate, planned) { for d := 1; d < len(cs); d++ { i := (at + d) % len(cs) - if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) { + if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) { continue // a turn goes round the keys routed over only } if i > 0 { diff --git a/internal/gateway/codex_credits_last_test.go b/internal/gateway/codex_credits_last_test.go new file mode 100644 index 000000000..a830836b0 --- /dev/null +++ b/internal/gateway/codex_credits_last_test.go @@ -0,0 +1,139 @@ +package gateway + +import ( + "net/http" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then +// the subscription's credits. An account at 100% that holds credits keeps +// its place by default (In order: asked first, and spends them); set to +// spend them last, the next account not on its credits is asked first, +// the account behind it, and the trace says why; turned on again it is +// back in its place. +func TestCodexCreditsLastAfterTheOthers(t *testing.T) { + codexSignedIn(t, "spare@example.com") + b := newResetBackend(t) // every account answers: the first on its credits + creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20}, "me@example.com") + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + again := func(want string) *Server { + t.Helper() + b.mu.Lock() + b.tried = nil + b.mu.Unlock() + srv := New() + code, body := resetPost(t, srv) + if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != want { + t.Fatalf("%d %s tried %q, want %q", code, body, tried, want) + } + return srv + } + again("acct-1") // in its place + + if err := provider.SetCodexCreditsMode("Me@Example.com", provider.CreditsLast); err != nil { + t.Fatal(err) + } + srv := again("acct-2") + rs := srv.Trace(t.Context(), 0, 0).Routes + if len(rs) == 0 || len(rs[0].Order) != 2 || rs[0].Order[0].Who != "spare@example.com" || rs[0].Order[0].CreditsLast || + rs[0].Order[1].Who != "me@example.com" || !rs[0].Order[1].CreditsLast || !rs[0].Order[1].Credits { + t.Fatalf("order %+v", rs) + } + + // below its windows' end it isn't on its credits: in its place still + creditsUsage(t, map[string]float64{"me@example.com": 60, "spare@example.com": 20}, "me@example.com") + again("acct-1") + + creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20}, "me@example.com") + if err := provider.SetCodexCredits("me@example.com", true); err != nil { + t.Fatal(err) + } + if provider.CodexCreditsLast("me@example.com") { + t.Fatal("on is in its place: last kept") + } + again("acct-1") +} + +// The credits come after a provider's fallback too: both accounts at 100% +// on their credits and set to spend them last, an API key the provider +// falls back to answers first; with the credits in their place, an +// account answers on them as before. +func TestCodexCreditsLastAfterTheFallback(t *testing.T) { + codexSignedIn(t, "spare@example.com") + b := newResetBackend(t) + creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 100}, "me@example.com", "spare@example.com") + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + fb := &keyed{} + serveOn(t, "spare", "kf", []string{"m2"}, fb) + p, _ := provider.Find("codex") + p.Fallback = []string{"spare/m2"} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + post := func() (int, string) { + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + return postAs(t, New(), "", `{"model":"codex/gpt-5.5","messages":[{"role":"user","content":"hi"}]}`) + } + code, body := post() + if tried, _ := b.seen(); code != 200 || tried != "acct-1" || len(fb.tried) != 0 { + t.Fatalf("in their place: %d %s, codex tried %q, fallback %v", code, body, tried, fb.tried) + } + for _, u := range []string{"me@example.com", "spare@example.com"} { + if err := provider.SetCodexCreditsMode(u, provider.CreditsLast); err != nil { + t.Fatal(err) + } + } + b.mu.Lock() + b.tried = nil + b.mu.Unlock() + code, body = post() + if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "from kf") || tried != "" { + t.Fatalf("last: %d %s, codex tried %q", code, body, tried) + } +} + +// A conversation an account on its credits answered, set to spend them +// last, isn't kept on it by its cache once one not on its credits leads; +// a turn going round, or a new conversation spread, never lands on it +// past that one either. +func TestCodexCreditsLastNotKept(t *testing.T) { + acct := func(u string) candidate { + return candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: u}}, model: "gpt-5.5", rest: "codex/" + u} + } + cs := []candidate{acct("spare@example.com"), acct("me@example.com")} + pl := planned{order: []Weighed{{Who: "spare@example.com"}, {Who: "me@example.com", Credits: true, CreditsLast: true}}} + h := http.Header{} + h.Set("x-claude-code-session-id", "credits-last-kept") + body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`) + _, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl) + answered(key, cs[1], 1, Usage{CacheRead: 50_000}) + t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() }) + got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl) + if got[0].rest != "codex/spare@example.com" || aff.Kept || aff.Why != "credits" { + t.Fatalf("first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why) + } + + // every one on its credits and last: kept where it was + both := planned{order: []Weighed{{Who: "spare@example.com", CreditsLast: true}, {Who: "me@example.com", CreditsLast: true}}} + got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, both) + if got[0].rest != "codex/me@example.com" || !aff.Kept { + t.Fatalf("all last: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why) + } + + // a turn after spare's goes round to spare again, not to me + if got, _ := after(append([]candidate(nil), cs...), planned{order: append([]Weighed(nil), pl.order...)}, 0); got[0].rest != "codex/spare@example.com" { + t.Fatalf("turn went to %s", got[0].rest) + } + if readyForNew(pl.order, 1) { + t.Fatal("a new conversation may go to the one on its credits") + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 637f0b7f3..e41143ad0 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1081,26 +1081,37 @@ func asideOf(cs []candidate, q provider.Provider, fallback bool, from provider.P return out } -// restLast moves those resting after a recent failure behind the rest. +// restLast moves those resting after a recent failure behind the rest, +// and a Codex account set to spend its credits last that has gone onto +// them (creditsLast) behind both, those in their own order. func restLast(out []candidate, pl planned) ([]candidate, planned) { if len(out) == 1 { if r, ok := restingOf(out[0]); ok { pl.order[0].Rest = &r // tried all the same: there is no other } + pl.order[0].CreditsLast = out[0].creditsLast(time.Now()) return out, pl } - var ready, resting []candidate - var wReady, wResting []Weighed + now := time.Now() + var ready, resting, last []candidate + var wReady, wResting, wLast []Weighed for i, c := range out { - if r, ok := restingOf(c); ok { + r, isResting := restingOf(c) + if isResting { pl.order[i].Rest = &r + } + switch { + case c.creditsLast(now): + pl.order[i].CreditsLast = true + last, wLast = append(last, c), append(wLast, pl.order[i]) + case isResting: resting, wResting = append(resting, c), append(wResting, pl.order[i]) - } else { + default: ready, wReady = append(ready, c), append(wReady, pl.order[i]) } } - pl.order = append(wReady, wResting...) - return append(ready, resting...), pl + pl.order = append(append(wReady, wResting...), wLast...) + return append(append(ready, resting...), last...), pl } // probeOne keeps, of the candidates resting after a failure, only the one diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index daea7d7f6..00923164f 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1734,6 +1734,24 @@ func spendsCredits(p provider.Provider, a provider.Allowance) bool { return p.Account != nil && p.Account.UsageAgent() == "codex" && a.OnCredits() && provider.CodexCredits(p.Account.User) } +// creditsLast: c is a Codex account on its credits (onCredits) that the +// user set to spend them only after everything else +// (provider.CodexCreditsLast), and by its last reading a window for the +// model is used up, where an account set not to spend them is held: it +// goes on on its credits now, so it is tried after every candidate that +// isn't (restLast), in its place among those that are. A call ChatGPT +// counts in no window (freeOnChatGPT) spends no credits, so it stays. +// Asked for gokoshiki on Discord: a subscription, then an API key, then +// the subscription's credits. +func (c candidate) creditsLast(now time.Time) bool { + acct := c.p.Account + if acct == nil || !provider.CodexCreditsLast(acct.User) || freeOnChatGPT(c.model, acct.Plan) { + return false + } + a, _ := c.allowance() + return spendsCredits(c.p, a) && a.CapHeld(c.model, provider.WindowCaps{Credits: true}, now) != nil +} + // allowance is the candidate's allowance as last known: a subscription // account's, or a key's own windows when magpie reads them (a sub2api // key's limits, provider.KeyAllowance). ok is false when it isn't known. diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index e3d34e530..9fbcfa395 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -341,6 +341,10 @@ type Weighed struct { // credits, and is let spend them: all but used up, it still answers, // and goes before those used up with nothing to go on with Credits bool `json:"credits,omitempty"` + // CreditsLast: such an account, on its credits now, that the user set + // to spend them only after everything else: tried after every + // candidate not on its credits (restLast) + CreditsLast bool `json:"creditsLast,omitempty"` // Rank: its place in its provider's own list of accounts or keys, the // order the provider's page shows and a drag sets (#217); routing may // weigh them in another diff --git a/internal/gui/api.go b/internal/gui/api.go index 300afb21d..85458b49a 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1525,6 +1525,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { in.CodexResetLead = cur.CodexResetLead // and how early before one expires (codex-reset-lead) // and which of them spend their credits, set there too in.CodexNoCredits = cur.CodexNoCredits + in.CodexCreditsLast = cur.CodexCreditsLast // and which only after everything else // and each Codex account's own daily warm-up (codex-warm-at below) in.CodexWarmAtOf = cur.CodexWarmAtOf // and the text size, which the keyboard changes too (text-size below) @@ -2050,11 +2051,13 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { writeJSON(rw, settingsState()) }) // whether a Codex account spends its credits once its allowance is - // used up, the Usage card's toggle, set on its own + // used up, the Usage card's toggle, set on its own, and with Last + // whether only after everything else (left as it is when not sent) mux.HandleFunc("POST /api/settings/codex-credits", func(rw http.ResponseWriter, r *http.Request) { var in struct { User string On bool + Last *bool } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) @@ -2064,7 +2067,14 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { fail(rw, fmt.Errorf("which Codex account?")) return } - if err := provider.SetCodexCredits(in.User, in.On); err != nil { + mode := provider.CreditsOff + if in.On { + mode = provider.CreditsOn + if (in.Last == nil && provider.CodexCreditsLast(in.User)) || (in.Last != nil && *in.Last) { + mode = provider.CreditsLast + } + } + if err := provider.SetCodexCreditsMode(in.User, mode); err != nil { fail(rw, err) return } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 4bd4212ed..7a879b76c 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1998,6 +1998,10 @@ body.panel .profiles #save { height: 25px; } /* the field's: the line keeps its .subscription-card.several .quota-credits + .subscription-account { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); } .pq-autoreset, .pq-credits { grid-column: 1 / -1; margin-top: 5px; padding-top: 7px; border-top: 1px solid var(--line-2); font-size: 11px; } .pq-resets + .pq-autoreset, .pq-autoreset + .pq-credits { margin-top: 5px; padding-top: 0; border-top: 0; } +/* spending them only after everything else, a line of its own under the + say while the credits are spent at all, its switch at the line's end */ +.quota-credits, .pq-credits { flex-wrap: wrap; row-gap: 3px; } +.ar-credits-last { flex-basis: 100%; } .ar-say { flex: 1; min-width: 0; line-height: 1.35; } .ar-say b { font-weight: 500; color: var(--fg-2); } .ar-used { display: block; margin-top: 2px; color: var(--faint); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 6bc0df9d0..84b096b39 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -17569,7 +17569,7 @@ function panelQuotaCard(q) { } if (credits) { if (policy) say.append(document.createTextNode(" · ")); - say.append(el("b", "", t("Use credits:")), document.createTextNode(" " + t(creditsOn(q) ? "On" : "Off"))); + say.append(el("b", "", t("Use credits:")), document.createTextNode(" " + t(creditsLast(q) ? "On, after everything else" : creditsOn(q) ? "On" : "Off"))); } row.append(say); card.append(row); @@ -17645,12 +17645,8 @@ function resetUseTitle(q) { + "\n" + t("This account's windows start again at once, as if none had been used. You're asked before anything is spent."); } -// A Codex account spending a reset by itself is a standing say of the -// account's, kept by its name (settings' codexAutoReset, the CLI's quota -// auto-reset): when its week is used up and no other account can answer, -// one a week at most, and the one about to run out unused shortly before -// it does. Off unless the user turns it on; nothing for an account with no -// name to keep it by. autoResetKept: the accounts that can have it. +// Whether a Codex account spends a reset by itself (codexAutoReset, the CLI's +// quota auto-reset), off unless turned on; only a named account can have it. const AUTO_RESET_KEPT = { codex: "codexAutoReset" }; function autoResetKept(q) { return !!(q.user && AUTO_RESET_KEPT[q.provider] && !q.resets?.byWindow); @@ -17659,10 +17655,8 @@ function autoResetOn(q) { const w = autoResetWhen(q); return w.week || w.expiring; } -// autoResetWhen: at which of the two times the account uses one by itself, -// each its own switch (#2078, alanwalk: Codex resets the week often enough -// that a used-up week is worth waiting out, while a card about to run out -// isn't); an account not kept to one (codexAutoResetOnly) uses one at both. +// autoResetWhen: the times it uses one by itself, a switch each (#2078); +// one not kept to one (codexAutoResetOnly) uses one at both. function autoResetWhen(q) { if (!autoResetKept(q) || !(state.settings?.[AUTO_RESET_KEPT[q.provider]] || []).includes(q.user.toLowerCase())) return { week: false, expiring: false }; return autoResetWhenOf(state.settings?.codexAutoResetOnly?.[q.user.toLowerCase()]); @@ -17688,9 +17682,7 @@ function autoResetStatus(user, w) { return t("{who} no longer uses a reset by itself", { who: user }); } -// autoResetRow is that say on an account's card, whether or not it holds a -// reset now, so it can be set ahead of one (#719): each of the two times it -// uses one on a line of its own, in words, with its switch (#2078). +// autoResetRow: that say on an account's card, each time on a line with its switch (#719, #2078). function autoResetRow(q, cls) { if (!autoResetKept(q)) return null; const on = autoResetOn(q); @@ -17714,11 +17706,8 @@ function autoResetRow(q, cls) { return row; } -// resetsUsedLine: the last of the account's resets magpie used, when and -// why, on a line of its own under the say; every one kept in its title. -// A reset gone from the card otherwise read the same whether magpie used -// it, the user did, or it ran out (foobra12 on Discord: 我发现刚才好像不小心 -// 自动给我使用了一张). Nothing when magpie used none. +// resetsUsedLine: the last reset magpie used, when and why; every one in its +// title (foobra12 on Discord). Nothing when magpie used none. function resetsUsedLine(q) { const used = q.resetsUsed || []; if (!used.length) return null; @@ -17738,11 +17727,8 @@ function autoResetTitle(on) { : "Off: this account's resets are used only by hand. Turned on, one is used by itself when its week is used up and no other account can answer, one a week at most, and the one about to run out {lead} before it does, if the account has been used, or at once when the account is held up until after then. Otherwise the five hours running out never uses one.", resetLeadVars()); } -// The reset about to run out is used this long before it does, for every -// account with "before one expires" on (settings' codexResetLead, the CLI's -// quota auto-reset lead; the owner, 10-30): half an hour unless set, and a -// value out of range is the half hour, as the gateway reads it. -// RESET_LEADS are the choices, in minutes. +// How long before a reset runs out it is used (codexResetLead; the owner, 10-30): +// half an hour unless set or out of range, as the gateway reads it. RESET_LEADS in minutes. const RESET_LEADS = [15, 30, 60, 120, 180, 360, 720, 1440]; function resetLeadMinutes(s = state?.settings) { const m = s?.codexResetLead; @@ -17753,10 +17739,7 @@ function resetLeadWords(m) { } const resetLeadVars = (s) => ({ lead: resetLeadWords(resetLeadMinutes(s)) }); -// autoResetBrief: an account in brief says it too, beside its name — the -// resets it holds and the say — with its switch: the account a week ran -// out on is the one not served, so the one shown in brief, and its switch -// only in full was lost (#801, ezdemo: 自动使用重置卡的开关的入口找不到了). +// autoResetBrief: the say and its switch beside an account's name in brief (#801). function autoResetBrief(q) { if (!autoResetKept(q)) return null; const on = autoResetOn(q); @@ -17771,9 +17754,7 @@ function autoResetBrief(q) { return s; } -// autoResetButton turns that on or off: a switch, its words beside it. With -// c (one of AUTO_RESET_CASES), at that time alone, the other kept; without, -// the brief's switch, at both: off when either is on, else on at both. +// autoResetButton: a switch; with c, that time alone, else both (the brief's). function autoResetButton(q, c) { const on = c ? autoResetWhen(q)[c.id] : autoResetOn(q); const b = el("button", "lib-switch auto-reset" + (on ? " on" : "")); @@ -17802,21 +17783,20 @@ function autoResetButton(q, c) { return b; } -// Whether a Codex account spends its credits once one of its windows is -// used up, a standing say of the account's kept by its name (settings' -// codexNoCredits, the CLI's quota credits): on unless the user turns it -// off. Off, routing holds the account as used up till the window renews, -// as a usage cap does at its share. creditsKept: the accounts that can -// have it. +// Whether a Codex account spends its credits once a window is used up +// (settings' codexNoCredits, on by default; off, routing holds it till the +// window renews), and spends them last (codexCreditsLast, gokoshiki). function creditsKept(q) { return !!(q.user && q.provider === "codex"); } function creditsOn(q) { return creditsKept(q) && !(state.settings?.codexNoCredits || []).includes(q.user.toLowerCase()); } +function creditsLast(q) { + return creditsOn(q) && (state.settings?.codexCreditsLast || []).includes(q.user.toLowerCase()); +} -// creditsRow is that say on an account's card, credits held or not, so it -// can be set ahead: what it does, in words, and the switch. +// creditsRow: that say on an account's card, its switches beside it. function creditsRow(q, cls) { if (!creditsKept(q)) return null; const on = creditsOn(q); @@ -17826,6 +17806,14 @@ function creditsRow(q, cls) { say.title = creditsTitle(on); row.dataset.user = q.user; row.append(say, creditsButton(q)); + if (on) { + const last = creditsLast(q); + const line = el("div", "ar-case ar-credits-last" + (last ? " on" : "")); + const words = el("span", "ar-case-say", t("Only after every other account, key and fallback")); + words.title = t(last ? "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off." : "Off: past its windows, it keeps its place and answers on its credits there."); + line.append(words, creditsSwitch(q, "credits-last", last, words.title, { on: true, last: !last }, t("Use credits") + " · " + words.textContent, last ? "{who} spends its credits when its windows run out" : "{who} spends its credits only after everything else")); + row.append(line); + } return row; } function creditsTitle(on) { @@ -17833,24 +17821,26 @@ function creditsTitle(on) { : "Off: once one of this account's windows is used up, by magpie's latest reading (refreshed about every minute), magpie holds it till the window renews, and requests go to your other accounts, groups and fallbacks rather than spending its credits. With none of them left, a request is refused with why, unless Auto-use resets is on and its week is used up: then a reset is used first."); } -// creditsButton turns that on or off: a switch, its words beside it. function creditsButton(q) { const on = creditsOn(q); - const b = el("button", "lib-switch use-credits" + (on ? " on" : "")); + return creditsSwitch(q, "use-credits", on, creditsTitle(on), { on: !on }, t("Use credits"), on ? "{who} no longer spends its credits: held when a window runs out" : "{who} spends its credits when its windows run out"); +} +function creditsSwitch(q, cls, on, title, body, label, said) { + const b = el("button", "lib-switch " + cls + (on ? " on" : "")); b.type = "button"; b.setAttribute("role", "switch"); b.setAttribute("aria-checked", String(on)); - b.setAttribute("aria-label", t("Use credits")); - b.title = creditsTitle(on); + b.setAttribute("aria-label", label); + b.title = title; b.append(el("i")); b.onclick = async (e) => { e.stopPropagation(); if (b.disabled) return; b.disabled = true; try { - prefs = await writingPrefs(api("settings/codex-credits", { user: q.user, on: !on })); + prefs = await writingPrefs(api("settings/codex-credits", { user: q.user, ...body })); state.settings = prefs; - status(t(on ? "{who} no longer spends its credits: held when a window runs out" : "{who} spends its credits when its windows run out", { who: q.user }), "ok"); + status(t(said, { who: q.user }), "ok"); renderQuotas(); } catch (err) { b.disabled = false; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e82745a55..74485fd7e 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2183,6 +2183,11 @@ const I18N = { "Use credits": "使用积分", "{who} no longer spends its credits: held when a window runs out": "{who} 不再使用积分:额度用尽即暂停使用", "{who} spends its credits when its windows run out": "{who} 额度用尽时将使用积分", + "Only after every other account, key and fallback": "仅在其他账号、密钥和备用都用不上时", + "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off.": "开:额度用尽后,排在所有其他账号、密钥和备用之后,最后才用它的积分。点击关闭。", + "Off: past its windows, it keeps its place and answers on its credits there.": "关:额度用尽后,仍按原位置在那里用积分回答。", + "{who} spends its credits only after everything else": "{who} 仅在其他都用不上时才使用积分", + "On, after everything else": "开,最后使用", "when its week runs out": "周额度用完时", "before one expires": "重置卡到期前", "{who} uses a reset by itself only when its week runs out": "{who} 仅在周额度用完时自动使用重置卡", @@ -6484,6 +6489,11 @@ const I18N = { "Use credits": "使用積分", "{who} no longer spends its credits: held when a window runs out": "{who} 不再使用積分:額度用盡即暫停使用", "{who} spends its credits when its windows run out": "{who} 額度用盡時將使用積分", + "Only after every other account, key and fallback": "僅在其他帳號、金鑰和備用都用不上時", + "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off.": "開:額度用盡後,排在所有其他帳號、金鑰和備用之後,最後才用它的積分。點擊關閉。", + "Off: past its windows, it keeps its place and answers on its credits there.": "關:額度用盡後,仍按原位置在那裡用積分回答。", + "{who} spends its credits only after everything else": "{who} 僅在其他都用不上時才使用積分", + "On, after everything else": "開,最後使用", "when its week runs out": "週額度用完時", "before one expires": "重置卡到期前", "{who} uses a reset by itself only when its week runs out": "{who} 僅在週額度用完時自動使用重置卡", @@ -10761,6 +10771,11 @@ const I18N = { "Use credits": "クレジットを使用", "{who} no longer spends its credits: held when a window runs out": "{who} はクレジットを使用しなくなりました:枠を使い切ったら停止します", "{who} spends its credits when its windows run out": "{who} は枠を使い切るとクレジットを使用します", + "Only after every other account, key and fallback": "他のアカウント・キー・フォールバックをすべて使った後のみ", + "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off.": "オン:枠を使い切ると、他のアカウント・キー・フォールバックのすべての後に試され、クレジットは最後に使われます。クリックでオフ。", + "Off: past its windows, it keeps its place and answers on its credits there.": "オフ:枠を使い切っても順番はそのままで、その位置でクレジットを使って応答します。", + "{who} spends its credits only after everything else": "{who} は他をすべて使った後のみクレジットを使用します", + "On, after everything else": "オン、最後に使用", "when its week runs out": "週の枠を使い切ったとき", "before one expires": "期限切れの前", "{who} uses a reset by itself only when its week runs out": "{who} は週の枠を使い切ったときだけリセットを自動使用します", @@ -15069,6 +15084,11 @@ const I18N = { "Use credits": "Credits nutzen", "{who} no longer spends its credits: held when a window runs out": "{who} verbraucht keine Credits mehr: angehalten, wenn ein Kontingent aufgebraucht ist", "{who} spends its credits when its windows run out": "{who} verbraucht Credits, wenn die Kontingente aufgebraucht sind", + "Only after every other account, key and fallback": "Erst nach allen anderen Konten, Schlüsseln und Fallbacks", + "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off.": "An: Sind die Kontingente aufgebraucht, kommt es nach allen anderen Konten, Schlüsseln und Fallbacks, die Credits werden zuletzt verbraucht. Klicken zum Ausschalten.", + "Off: past its windows, it keeps its place and answers on its credits there.": "Aus: Sind die Kontingente aufgebraucht, behält es seinen Platz und antwortet dort mit Credits.", + "{who} spends its credits only after everything else": "{who} verbraucht Credits erst nach allem anderen", + "On, after everything else": "An, zuletzt", "when its week runs out": "wenn die Woche aufgebraucht ist", "before one expires": "bevor einer abläuft", "{who} uses a reset by itself only when its week runs out": "{who} löst einen Reset nur noch automatisch ein, wenn die Woche aufgebraucht ist", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index ed341c9a8..3f6d197a0 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -716,6 +716,7 @@ function routingPage(part) { : t("{name} has one key on — nothing to choose between.", { name: f.name }); } if (f.rest) return t("Every one is resting after a failure, so {who}, first in line, is tried all the same.", { who: w }); + if (f.creditsLast) return t("Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.", { who: w }); if (f.fallback) { const name = r.order.find((x) => !x.fallback)?.name || r.provider; return t("{name} is resting, so its fallback {fb} goes first.", { name, fb: `${f.provider}/${f.model}` }); @@ -908,6 +909,11 @@ function routingPage(part) { // behind the first by a group's weights or its order, which take // each member whole: not by what x has left (Creat.wu: a group in // a group by weight, its accounts at 91%, read as passed over) + if (x.creditsLast && f0 && !f0.creditsLast) { + // behind everything not on its credits, as the user set it + out.push(t("{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.", { who: who(x) })); + continue; + } const by = !x.rest && !x.sunk && f0 ? memberSplit(r, f0, x) : null; if (by && smart(x) && (x.known ? group(x) === "low" : someKnown(x))) { if (!told.has(by.member)) { @@ -958,6 +964,7 @@ function routingPage(part) { case "resting": return t("{who} answered this conversation last, but it is resting, so the conversation moves.", { who: last }); case "spent": return t("{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.", { who: last }); case "reserve": return t("{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.", { who: last }); + case "credits": return t("{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.", { who: last, first: who(r.order[0]) }); case "gone": return t("{who} answered this conversation last, but it is no longer one to route to.", { who: last }); case "order": return t("{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.", { who: last, first: who(r.order[0]), n: a.turn }); case "main": return t("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.", { who: last, first: who(r.order[0]), n: a.turn }); @@ -2625,7 +2632,8 @@ function routingPage(part) { else if (w.free) s = t("free · costs nothing"); else if (w.known) { const soon = usedRenews(w); - s = !w.routing && w.used >= 98 && w.credits ? quota(w, "{n} used · on credits", "{n} left · on credits") + s = w.creditsLast && !r.order[0]?.creditsLast ? quota(w, "{n} used · on credits · after the others", "{n} left · on credits · after the others") + : !w.routing && w.used >= 98 && w.credits ? quota(w, "{n} used · on credits", "{n} left · on credits") : !w.routing && w.used >= 98 ? quota(w, "{n} used · all but used up", "{n} left · all but used up") : !w.routing && w.used >= 90 ? quota(w, "{n} used · kept for last", "{n} left · kept for last") : (b = behindWhy(r, w)) === "kept" ? quota(w, "{n} used · conversation kept on another", "{n} left · conversation kept on another") diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index d16ac3bf2..b2fa9effe 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -581,6 +581,9 @@ magpie.strings({ "Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "第 {n} 轮开始:亲和性仅在一轮内保持,路由重新决定。", "{who} answered this conversation last, but it is resting, so the conversation moves.": "此会话上次由 {who} 回答,但它在休息,已换账号。", "{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "此会话上次由 {who} 回答,但其额度将尽,已换账号。", + "Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.": "这里每个账号额度都已用尽、改用积分,且都设为最后使用积分,所以先试排第一的 {who}。", + "{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.": "{who} 额度已用尽、改用积分,且设为最后使用积分:排在所有其他账号、密钥和备用之后。", + "{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.": "此会话上次由 {who} 回答,但它现在在用积分,且设为最后使用积分,所以会话换到 {first}。", "{who} answered this conversation last, but it is no longer one to route to.": "此会话上次由 {who} 回答,但它已不可路由。", "{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此会话上次由 {who} 回答,但该组按顺序路由,排在它前面的 {first} 已恢复可用,所以第 {n} 轮回到 {first}。", "{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此会话上次由备用 {who} 回答,但提供商自己的 {first} 已恢复可用,所以第 {n} 轮回到它。", @@ -601,6 +604,8 @@ magpie.strings({ "{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.": "{who} 额度已用 {n},但仍可用 Credits 继续 —— 排在额度未用完的账号之后、额度用完且无 Credits 的账号之前。", "{n} used · on credits": "已用 {n} · 使用 Credits", "{n} left · on credits": "剩余 {n} · 使用 Credits", + "{n} used · on credits · after the others": "已用 {n} · 使用积分 · 排在最后", + "{n} left · on credits · after the others": "剩余 {n} · 使用积分 · 排在最后", "Every account is all but used up, so {who} goes first: it goes on on its credits, which the vendor spends once its allowance is used up.": "所有账号额度都几乎用尽,因此 {who} 排第一:额度用完后供应商会改扣其 Credits,可以继续使用。", "{n} left · kept for last": "剩余 {n} · 留到最后", "{n} left · renews in {d}": "剩余 {n} · {d}后重置", @@ -1212,6 +1217,9 @@ magpie.strings({ "Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "第 {n} 輪開始:親和性僅在一輪內保持,路由重新決定。", "{who} answered this conversation last, but it is resting, so the conversation moves.": "此會話上次由 {who} 回答,但它在休息,已換帳號。", "{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "此會話上次由 {who} 回答,但其額度將盡,已換帳號。", + "Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.": "這裡每個帳號額度都已用盡、改用積分,且都設為最後使用積分,所以先試排第一的 {who}。", + "{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.": "{who} 額度已用盡、改用積分,且設為最後使用積分:排在所有其他帳號、金鑰和備用之後。", + "{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.": "此會話上次由 {who} 回答,但它現在在用積分,且設為最後使用積分,所以會話換到 {first}。", "{who} answered this conversation last, but it is no longer one to route to.": "此會話上次由 {who} 回答,但它已不可路由。", "{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此會話上次由 {who} 回答,但該群組按順序路由,排在它前面的 {first} 已恢復可用,所以第 {n} 輪回到 {first}。", "{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此會話上次由備用 {who} 回答,但供應商自己的 {first} 已恢復可用,所以第 {n} 輪回到它。", @@ -1232,6 +1240,8 @@ magpie.strings({ "{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.": "{who} 額度已用 {n},但仍可用 Credits 繼續 —— 排在額度未用完的帳號之後、額度用完且無 Credits 的帳號之前。", "{n} used · on credits": "已用 {n} · 使用 Credits", "{n} left · on credits": "剩餘 {n} · 使用 Credits", + "{n} used · on credits · after the others": "已用 {n} · 使用積分 · 排在最後", + "{n} left · on credits · after the others": "剩餘 {n} · 使用積分 · 排在最後", "Every account is all but used up, so {who} goes first: it goes on on its credits, which the vendor spends once its allowance is used up.": "所有帳號額度都幾乎用盡,因此 {who} 排第一:額度用完後供應商會改扣其 Credits,可以繼續使用。", "{n} left · kept for last": "剩餘 {n} · 留到最後", "{n} left · renews in {d}": "剩餘 {n} · {d}後重置", @@ -1841,6 +1851,9 @@ magpie.strings({ "Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "ターン {n} の開始:アフィニティは 1 ターン内でのみ会話を保つため、ルーティングを新たに決めます。", "{who} answered this conversation last, but it is resting, so the conversation moves.": "この会話に前回応答したのは {who} ですが、休止中のため会話は移ります。", "{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "この会話に前回応答したのは {who} ですが、利用枠をほぼ使い切っているため会話は移ります。", + "Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.": "ここはすべて利用枠を使い切ってクレジットで続行中で、クレジットは最後に使う設定のため、先頭の {who} を先に試します。", + "{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.": "{who} は利用枠を使い切りクレジットで続行中ですが、クレジットは最後に使う設定のため、他のアカウント・キー・フォールバックのすべての後に試します。", + "{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.": "この会話に前回応答したのは {who} ですが、今はクレジットで続行中で、クレジットは最後に使う設定のため、会話は {first} に移ります。", "{who} answered this conversation last, but it is no longer one to route to.": "この会話に前回応答したのは {who} ですが、もうルーティング対象ではありません。", "{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "この会話に前回応答したのは {who} ですが、このグループは順番どおりにルーティングし、その前にある {first} が再び使えるため、ターン {n} は {first} に戻ります。", "{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "この会話に前回応答したのは代替の {who} ですが、プロバイダー自身の {first} が再び使えるため、ターン {n} はそちらに戻ります。", @@ -1861,6 +1874,8 @@ magpie.strings({ "{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.": "{who} は利用枠の {n} を使っていますが、クレジットで続けられます — 利用枠が残っているアカウントの後、使い切ってクレジットもないアカウントの前です。", "{n} used · on credits": "{n} 使用 · クレジット利用", "{n} left · on credits": "残り {n} · クレジット利用", + "{n} used · on credits · after the others": "{n} 使用 · クレジット利用 · 最後に試す", + "{n} left · on credits · after the others": "残り {n} · クレジット利用 · 最後に試す", "Every account is all but used up, so {who} goes first: it goes on on its credits, which the vendor spends once its allowance is used up.": "どのアカウントも利用枠をほぼ使い切っているため、{who} が先頭です。利用枠を使い切るとベンダーがクレジットを使うので、続けられます。", "{n} left · kept for last": "残り {n} · 最後に回す", "{n} left · renews in {d}": "残り {n} · {d} 後に更新", @@ -2472,6 +2487,9 @@ magpie.strings({ "Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "Runde {n} beginnt: Die Affinität hält eine Unterhaltung nur innerhalb einer Runde, daher entscheidet die Weiterleitung neu.", "{who} answered this conversation last, but it is resting, so the conversation moves.": "{who} hat diese Unterhaltung zuletzt beantwortet, pausiert aber, daher wechselt die Unterhaltung.", "{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber sein Kontingent ist fast aufgebraucht, daher wechselt die Unterhaltung.", + "Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.": "Alle hier haben ihr Kontingent aufgebraucht und laufen mit Credits weiter, die sie erst zuletzt verbrauchen sollen, daher geht {who} als Erstes in der Reihe vor.", + "{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.": "{who} hat sein Kontingent aufgebraucht und läuft mit Credits weiter, die es erst zuletzt verbrauchen soll: Es wird nach allen anderen Konten, Schlüsseln und Fallbacks versucht.", + "{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.": "{who} hat diese Unterhaltung zuletzt beantwortet, läuft aber jetzt mit Credits, die es erst zuletzt verbrauchen soll, daher wechselt die Unterhaltung zu {first}.", "{who} answered this conversation last, but it is no longer one to route to.": "{who} hat diese Unterhaltung zuletzt beantwortet, kommt aber für die Weiterleitung nicht mehr in Frage.", "{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber die Gruppe geht der Reihe nach vor und {first}, das davor steht, ist wieder bereit, daher geht Runde {n} zurück an {first}.", "{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet, aber {first} des Anbieters selbst ist wieder bereit, daher geht Runde {n} dorthin zurück.", @@ -2492,6 +2510,8 @@ magpie.strings({ "{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.": "{who} hat {n} seines Kontingents genutzt, macht aber mit seinen Credits weiter — vor denen, die aufgebraucht sind und nichts mehr haben, nach denen mit verbleibendem Kontingent.", "{n} used · on credits": "{n} genutzt · auf Credits", "{n} left · on credits": "{n} übrig · auf Credits", + "{n} used · on credits · after the others": "{n} genutzt · auf Credits · nach den anderen", + "{n} left · on credits · after the others": "{n} übrig · auf Credits · nach den anderen", "Every account is all but used up, so {who} goes first: it goes on on its credits, which the vendor spends once its allowance is used up.": "Alle Konten sind fast aufgebraucht, also kommt {who} zuerst: es macht mit seinen Credits weiter, die der Anbieter verbraucht, sobald sein Kontingent aufgebraucht ist.", "{n} left · kept for last": "{n} übrig · für zuletzt aufgespart", "{n} left · renews in {d}": "{n} übrig · erneuert sich in {d}", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 18f8c3b32..e2c0ace1a 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_316_874 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31); 1,316,874 with a package manager's magpie (the AUR's magpie-bin) naming the command that updates it in Settings' Version row and lighting no Update pill (shuhai on Discord), the core's own update row, which the tray panel reads too, its comments cut to one line, with no room added (10-31); Settings › Sync's Kept on this computer row (hayden4608 on Discord) raised it to 1,317,497, which is no bound; the 1,316,874 it had came back once later trims left app.js at 1,308,363 (10-31) - coreScriptBudget = 1_533_105 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01) + coreScriptBudget = 1_533_105 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01); a Codex account's credits spent only after every other account, key and fallback (gokoshiki on Discord) fit in it with the Codex options' comments in app.js cut down, no raise (11-01) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 31ccf41b4..18d28c5db 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -173,6 +173,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { CodexAutoResetOnly: map[string]string{"me@example.com": "expiring"}, CodexResetLead: 180, CodexNoCredits: []string{"me@example.com"}, + CodexCreditsLast: []string{"two@example.com"}, CodexWarmAtOf: map[string]string{"me@example.com": "09:00"}, TextSize: 125, UpdateSkip: "0.1.500", diff --git a/internal/gui/tests/codex-credits-last.test.cjs b/internal/gui/tests/codex-credits-last.test.cjs new file mode 100644 index 000000000..9a0e99a3f --- /dev/null +++ b/internal/gui/tests/codex-credits-last.test.cjs @@ -0,0 +1,220 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then +// the subscription's credits. Under a Codex account's Use credits, while +// it is on, a line of its own says "Only after every other account, key +// and fallback" with its switch: off until turned on, it posts +// settings/codex-credits with last for that account, says so, and turns; +// Use credits turned off takes the line away. The panel's card has it +// too, and its folded line says it. On the Routing page a request that +// went to another while the account was on its credits says why it was +// behind, and why the conversation moved. At narrow widths nothing is cut +// off or wider than its card, a click moves nothing, and no left-border +// accent. Every language, Chromium and WebKit; no backend, the API is +// faked here. +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 assets = path.resolve(__dirname, "../assets"); +const later = new Date(Date.now() + 3 * 864e5).toISOString(); +const now = new Date(); +const quotas = [ + { provider: "codex", name: "Codex", icon: "codex-color", user: "Me@example.com", plan: "Plus", lastServedAt: now.toISOString(), + windows: [{ name: "5 hours", used: 100, resetsAt: later }, { name: "7 days", used: 40, resetsAt: later }], + balance: "1.2K credits" }, +]; +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const at = new Date(now.getTime() - 60e3).toISOString(); +const key = { id: "openai", provider: "openai", name: "OpenAI", kind: "key", model: "gpt-5.5", fallback: true }; +const me = { id: "codex", provider: "codex", name: "Codex", kind: "account", who: "Me@example.com", model: "gpt-5.5", + known: true, used: 100, credits: true, creditsLast: true }; +const routes = [{ id: 7, seq: 7, time: at, agent: "codex", model: "gpt-5.5", provider: "codex", order: [key, me], + affinity: { why: "credits", last: "codex", at: new Date(now.getTime() - 120e3).toISOString() }, + tries: [{ id: key.id, model: "gpt-5.5", start: at, done: true, status: 200, ms: 400 }], done: true, status: 200, ms: 400 }]; + +function serve(lang, posts) { + let off = [], last = []; + const settings = () => ({ theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", trayUsages: ["codex"], trayUsageEvery: 3, codexNoCredits: off, codexCreditsLast: last }); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/settings/codex-credits") { + // as the server: off clears last, last left out keeps it + const body = req.postDataJSON(); + posts.push(body); + const who = body.user.toLowerCase(); + const wasLast = last.includes(who); + off = off.filter((u) => u !== who); + last = last.filter((u) => u !== who); + if (!body.on) off.push(who); + else if (body.last ?? wasLast) last.push(who); + return json(settings()); + } + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + const d = url.searchParams.get("day"); + return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] }); + } + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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 route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { line: "Only after every other account, key and fallback", on: (who) => `${who} spends its credits only after everything else`, brief: "Use credits: On, after everything else", + behind: "Me@example.com has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.", + moved: "Me@example.com answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to" }, + zh: { line: "仅在其他账号、密钥和备用都用不上时", on: (who) => `${who} 仅在其他都用不上时才使用积分`, brief: "使用积分: 开,最后使用", + behind: "Me@example.com 额度已用尽、改用积分,且设为最后使用积分:排在所有其他账号、密钥和备用之后。", + moved: "此会话上次由 Me@example.com 回答,但它现在在用积分,且设为最后使用积分,所以会话换到" }, + "zh-TW": { line: "僅在其他帳號、金鑰和備用都用不上時", on: (who) => `${who} 僅在其他都用不上時才使用積分`, brief: null, + behind: "Me@example.com 額度已用盡、改用積分,且設為最後使用積分:排在所有其他帳號、金鑰和備用之後。", + moved: "此會話上次由 Me@example.com 回答,但它現在在用積分,且設為最後使用積分,所以會話換到" }, + ja: { line: "他のアカウント・キー・フォールバックをすべて使った後のみ", on: (who) => `${who} は他をすべて使った後のみクレジットを使用します`, brief: null, + behind: "Me@example.com は利用枠を使い切りクレジットで続行中ですが、クレジットは最後に使う設定のため、他のアカウント・キー・フォールバックのすべての後に試します。", + moved: "この会話に前回応答したのは Me@example.com ですが、今はクレジットで続行中で、クレジットは最後に使う設定のため、会話は" }, + de: { line: "Erst nach allen anderen Konten, Schlüsseln und Fallbacks", on: (who) => `${who} verbraucht Credits erst nach allem anderen`, brief: null, + behind: "Me@example.com hat sein Kontingent aufgebraucht und läuft mit Credits weiter, die es erst zuletzt verbrauchen soll: Es wird nach allen anderen Konten, Schlüsseln und Fallbacks versucht.", + moved: "Me@example.com hat diese Unterhaltung zuletzt beantwortet, läuft aber jetzt mit Credits, die es erst zuletzt verbrauchen soll, daher wechselt die Unterhaltung zu" }, +}; + +const keys = [ + "Only after every other account, key and fallback", + "On: past its windows, it goes after every other account, key and fallback, so its credits are spent last. Click to turn it off.", + "Off: past its windows, it keeps its place and answers on its credits there.", + "{who} spends its credits when its windows run out", + "{who} spends its credits only after everything else", + "On, after everything else", + "Every one here has used up its allowance and goes on on its credits, set to spend them only after everything else, so {who}, first in line, goes first.", + "{who} has used up its allowance and goes on on its credits, which it is set to spend only after everything else: it is tried after every other account, key and fallback.", + "{who} answered this conversation last, but it is on its credits now, set to spend them only after everything else, so the conversation moves to {first}.", + "{n} used · on credits · after the others", "{n} left · on credits · after the others", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: a Codex account's credits spent only after everything else`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const open = async (url, viewport, posts) => { + const page = await (await browser.newContext({ viewport, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto(url); + return page; + }; + const wait = async (posts, n) => { for (let i = 0; i < 60 && posts.length < n; i++) await new Promise((r) => setTimeout(r, 50)); }; + const text = (loc) => loc.evaluate((e) => e.textContent.replace(/\s+/g, " ").trim()); + // a click: it posts, turns, says so, and moves nothing + const flip = async (page, row, posts, sel, want, body, said) => { + const b = page.locator(row + " " + sel); + const spot = () => b.evaluate((e) => [e.getBoundingClientRect().top, document.scrollingElement.scrollTop, ...[...document.querySelectorAll(".view")].map((v) => v.scrollTop)]); + const was = await spot(); + const n = posts.length; + await b.click(); + await wait(posts, n + 1); + assert.deepEqual(posts.at(-1), body); + await page.locator(row + " " + sel + `[aria-checked="${want}"]`).waitFor(); + assert.equal(await page.locator("#status").textContent(), said); + await page.waitForTimeout(200); + assert.deepEqual(await spot(), was, "the click moved the page"); + }; + // the line fits its card, its switch whole and on the line's end, + // the say's switch still by the say, and nothing cut off + const fits = (page, row, card) => page.evaluate(([row, card]) => { + const r = document.querySelector(row); + const c = r.closest(card).getBoundingClientRect(), b = r.getBoundingClientRect(); + const line = r.querySelector(".ar-credits-last"), s = line.querySelector(".credits-last").getBoundingClientRect(); + const main = r.querySelector(".use-credits").getBoundingClientRect(), say = r.querySelector(".ar-say").getBoundingClientRect(); + const words = line.querySelector(".ar-case-say"); + return b.right <= c.right + 0.5 && s.right <= c.right + 0.5 && s.width >= 27 && s.height >= 15 + && main.top < say.bottom && s.top >= main.bottom - 0.5 && words.scrollWidth <= words.clientWidth + 1; + }, [row, card]); + + for (const width of [900, 440]) { + const posts = []; + const page = await open("http://magpie.test/?view=usage", { width, height: 760 }, posts); + const row = '.quota-credits[data-user="Me@example.com"]'; + await page.locator(row + " .ar-credits-last").waitFor(); + assert.equal(await text(page.locator(row + " .ar-credits-last")), w.line); + const sw = page.locator(row + " .credits-last"); + assert.equal(await sw.getAttribute("role"), "switch"); + assert.equal(await sw.getAttribute("aria-checked"), "false", "in its place until set"); + assert(await sw.getAttribute("title")); + assert.equal(await page.locator(row + " .use-credits").count(), 1); + assert(await fits(page, row, ".subscription-card"), `the line fits the card at ${width}px`); + await flip(page, row, posts, ".credits-last", true, { user: "Me@example.com", on: true, last: true }, w.on("Me@example.com")); + assert(await page.locator(row + " .ar-credits-last.on").count(), 1); + assert(await fits(page, row, ".subscription-card"), `the line, on, fits the card at ${width}px`); + const back = await page.evaluate(() => t("{who} spends its credits when its windows run out", { who: "Me@example.com" })); + await flip(page, row, posts, ".credits-last", false, { user: "Me@example.com", on: true, last: false }, back); + // Use credits off: no line, as nothing is spent at all + await page.locator(row + " .use-credits").click(); + await wait(posts, 3); + assert.deepEqual(posts.at(-1), { user: "Me@example.com", on: false }); + await page.locator(row + ' .use-credits[aria-checked="false"]').waitFor(); + assert.equal(await page.locator(row + " .ar-credits-last").count(), 0); + const border = await page.evaluate(() => [...document.querySelectorAll(".quota-credits, .quota-credits *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1)); + assert.deepEqual(border, [], "no left-border accent"); + await page.context().close(); + } + + // the menu bar panel's card, at its own width and narrower, and its + // folded line + for (const width of [440, 360]) { + const posts = []; + const panel = await open("http://magpie.test/?mode=panel", { width, height: 640 }, posts); + const row = '.pq-credits[data-user="Me@example.com"]'; + await panel.locator('#ptabs [data-ptab="usage"]').click(); + await panel.locator(row + " .ar-credits-last").waitFor(); + await panel.waitForFunction(() => !quotasLoading); + assert(await fits(panel, row, ".pq-card"), `the line fits the panel's card at ${width}px`); + await flip(panel, row, posts, ".credits-last", true, { user: "Me@example.com", on: true, last: true }, w.on("Me@example.com")); + assert(await fits(panel, row, ".pq-card"), `the line, on, fits the panel's card at ${width}px`); + const id = await panel.locator(row).evaluate((r) => r.closest(".pq-card").dataset.card); + const card = `#panelQuota .pq-card[data-card="${id}"]`; + await panel.locator(card + " .pq-opts-fold").click(); + const brief = panel.locator(card + " .pq-opts-brief .ar-say"); + await brief.waitFor(); + const said = await text(brief); + const want = w.brief || (await panel.evaluate(() => t("Use credits:") + " " + t("On, after everything else"))); + assert(said.endsWith(want), said); + await panel.context().close(); + } + + // the Routing page says why the account went behind the key, and why + // the conversation moved + const routing = await open("http://magpie.test/?view=routing", { width: 1100, height: 760 }, []); + await routing.locator(".rt-days .rt-day").nth(1).click(); + await routing.locator(".rt-req").first().click(); + await routing.waitForTimeout(300); + const steps = await routing.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => l.textContent)); + assert(steps.some((s) => s.includes(w.behind)), JSON.stringify(steps)); + assert(steps.some((s) => s.includes(w.moved)), JSON.stringify(steps)); + if (lang !== "en") { + const missing = await routing.evaluate(([keys, lang]) => keys.filter((k) => !I18N[lang][k]), [keys, lang]); + assert.deepEqual(missing, [], `every string has its ${lang}`); + } + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/codex_credits.go b/internal/provider/codex_credits.go index b3cdc46ed..f3972439e 100644 --- a/internal/provider/codex_credits.go +++ b/internal/provider/codex_credits.go @@ -21,6 +21,7 @@ package provider // (the gateway's autoReset) where a cap never does. import ( + "fmt" "slices" "github.com/yetone/magpie/internal/settings" @@ -32,13 +33,63 @@ func CodexCredits(user string) bool { return !slices.Contains(settings.Load().CodexNoCredits, accountKey(user)) } -// SetCodexCredits turns that on or off for user. -func SetCodexCredits(user string, on bool) error { +// CodexCreditsLast says whether the Codex account user, which spends its +// credits, spends them only after everything else: once a usage window is +// used up, routing tries it after every account, key and fallback not on +// its credits (gateway's creditsLast) rather than in its place. Off unless +// the user set it, so a setting saved before it keeps its order. +func CodexCreditsLast(user string) bool { user = accountKey(user) s := settings.Load() - s.CodexNoCredits = slices.DeleteFunc(s.CodexNoCredits, func(u string) bool { return u == user }) - if !on && user != "" { - s.CodexNoCredits = append(s.CodexNoCredits, user) + return user != "" && slices.Contains(s.CodexCreditsLast, user) && !slices.Contains(s.CodexNoCredits, user) +} + +// Ways a Codex account spends its credits, for SetCodexCreditsMode. +const ( + CreditsOn = "on" // in its place, the default + CreditsLast = "last" // after everything else + CreditsOff = "off" // never: held when a window is used up +) + +// SetCodexCredits turns that on or off for user. On is in its place: +// it clears "last" too. +func SetCodexCredits(user string, on bool) error { + if on { + return SetCodexCreditsMode(user, CreditsOn) + } + return SetCodexCreditsMode(user, CreditsOff) +} + +// CodexCreditsMode is how user spends its credits: CreditsOn, +// CreditsLast or CreditsOff. +func CodexCreditsMode(user string) string { + switch { + case !CodexCredits(user): + return CreditsOff + case CodexCreditsLast(user): + return CreditsLast + } + return CreditsOn +} + +// SetCodexCreditsMode sets how user spends its credits: CreditsOn, +// CreditsLast or CreditsOff. +func SetCodexCreditsMode(user, mode string) error { + if mode != CreditsOn && mode != CreditsLast && mode != CreditsOff { + return fmt.Errorf("credits: %q is not on, last or off", mode) + } + user = accountKey(user) + s := settings.Load() + not := func(u string) bool { return u == user } + s.CodexNoCredits = slices.DeleteFunc(s.CodexNoCredits, not) + s.CodexCreditsLast = slices.DeleteFunc(s.CodexCreditsLast, not) + if user != "" { + switch mode { + case CreditsOff: + s.CodexNoCredits = append(s.CodexNoCredits, user) + case CreditsLast: + s.CodexCreditsLast = append(s.CodexCreditsLast, user) + } } return settings.Save(s) } diff --git a/internal/provider/codex_credits_test.go b/internal/provider/codex_credits_test.go index ce56929d2..e3e95248c 100644 --- a/internal/provider/codex_credits_test.go +++ b/internal/provider/codex_credits_test.go @@ -101,6 +101,47 @@ func TestCodexCreditsSwitch(t *testing.T) { } } +// Spending credits last is a third way, kept by account whatever its +// case: set, the account still spends them (nothing holds it), and off +// or on clears it; a mode not known is refused, nothing written. +func TestCodexCreditsLastMode(t *testing.T) { + signIn(t) + if CodexCreditsMode("me@example.com") != CreditsOn || CodexCreditsLast("me@example.com") { + t.Fatal("last before it was set") + } + if err := SetCodexCreditsMode(" Me@Example.com ", CreditsLast); err != nil { + t.Fatal(err) + } + s := settings.Load() + if !slices.Equal(s.CodexCreditsLast, []string{"me@example.com"}) || len(s.CodexNoCredits) != 0 { + t.Fatalf("kept last %v, off %v", s.CodexCreditsLast, s.CodexNoCredits) + } + if !CodexCreditsLast("ME@example.com") || !CodexCredits("me@example.com") || CodexCreditsMode("me@example.com") != CreditsLast || CodexCreditsLast("other@example.com") { + t.Fatal("read back wrong") + } + if share, _ := HoldCaps(Provider{ID: "codex"}, "codex", "me@example.com").Of("5 hours"); share != 0 { + t.Fatalf("held at %d: last still spends them", share) + } + if err := SetCodexCreditsMode("me@example.com", "sometimes"); err == nil || !CodexCreditsLast("me@example.com") { + t.Fatalf("a mode not known: %v", err) + } + if err := SetCodexCredits("me@example.com", false); err != nil { + t.Fatal(err) + } + if s := settings.Load(); len(s.CodexCreditsLast) != 0 || CodexCreditsMode("me@example.com") != CreditsOff { + t.Fatalf("off kept last: %v", s.CodexCreditsLast) + } + if err := SetCodexCreditsMode("me@example.com", CreditsLast); err != nil { + t.Fatal(err) + } + if err := SetCodexCredits("me@example.com", true); err != nil { + t.Fatal(err) + } + if s := settings.Load(); len(s.CodexCreditsLast)+len(s.CodexNoCredits) != 0 || CodexCreditsMode("me@example.com") != CreditsOn { + t.Fatalf("on kept last: %v", s.CodexCreditsLast) + } +} + // A reset spent starts an account's windows again: what was read of them // before is forgotten, so what holds the account at a share of them (its // cap, its credits not spent) holds it no more, and they are read again diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 1bb84a44f..f1c9a50a0 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -300,6 +300,12 @@ type Settings struct { // groups and fallbacks, where by default the vendor answers on its // credits (see provider.CodexCredits). CodexNoCredits []string `json:"codexNoCredits,omitempty"` + // CodexCreditsLast are the ChatGPT accounts (lower-case) that spend + // their credits only after everything else: once a usage window is + // used up, routing tries the account after every account, key and + // fallback not on its credits, instead of in its place. Not one of + // CodexNoCredits: an account set not to spend them is held. + CodexCreditsLast []string `json:"codexCreditsLast,omitempty"` // WorkBuddyCheckin presses WorkBuddy's daily check-in (签到) for each // signed-in WorkBuddy (China) account once a Beijing day, claiming the // credits it gives while its event runs. @@ -2076,6 +2082,10 @@ func saveOwn(s Settings, recording, reads bool) error { s.CodexNoCredits[i] = strings.ToLower(u) } s.CodexNoCredits = ids(s.CodexNoCredits) + for i, u := range s.CodexCreditsLast { + s.CodexCreditsLast[i] = strings.ToLower(u) + } + s.CodexCreditsLast = ids(s.CodexCreditsLast) s.TrayUsage = "" if len(s.TrayUsages) > 0 { s.TrayUsage = s.TrayUsages[0]