gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)

jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

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

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

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

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

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

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

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

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

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
This commit is contained in:
yetone
2026-11-01 21:19:22 +08:00
parent 8826a15ea4
commit ec104b8625
24 changed files with 675 additions and 86 deletions
+11 -4
View File
@@ -2476,10 +2476,16 @@ 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 <account>` 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 quota credits <account> first` (or *Before moving to another
account* under *Use credits*, on the Usage card or under the account's ⋯
in its provider's editor) spends them before moving on: by default magpie
sends requests to an account with room once one is nearly used up, and
signs Codex in to it; with first, while the account holds credits, it keeps
its place in the order and Codex stays signed in to it. First and last are
one or the other. `magpie quota credits` lists the accounts set not to
spend them and those that spend them first or last, `magpie quota credits
<account>` says one's. Off and last change 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.
An account can have a name of your own, for telling apart seats the vendor
@@ -2992,6 +2998,7 @@ 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 quota credits me@example.com first # spend its credits before moving to another account
magpie tools # the tools magpie's MCP servers give agents, with their parameters
magpie tools generate_image # one tool in full
+1
View File
@@ -220,6 +220,7 @@ recorded as a prediction failure (`noPrediction`).
- 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 <account> 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 <account> 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`.
- A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits <account> first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.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/<model>` 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<<n`, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a `holdWriter` with its reasoning let through (`thinkingShown`), kept alive past `keepHeldAfter` across the tries (one `keptAlive`), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (`codexFallsBack`; never a compaction) goes on to them (`codexFallBack`: the turn served as `codex/<model>` 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.
+21 -9
View File
@@ -18,7 +18,7 @@ const quotaUsage = `usage: magpie quota [<provider>…] [--json]
magpie quota reset [<codex account>] [--card <n>] [--yes]
magpie quota auto-reset [<codex account>] [week|expiring] [on|off]
magpie quota auto-reset lead [<minutes or hours, like 30m or 3h>|default]
magpie quota credits [<codex account>] [on|last|off]
magpie quota credits [<codex account>] [on|first|last|off]
magpie quota alert [<percent>|off] [--balance <amount>|off]
magpie quota wait <provider|account> [--timeout <duration>] [--quiet]
magpie quota history [<provider|account>…] [--days <n>] [--json]
@@ -56,8 +56,10 @@ const quotaUsage = `usage: magpie quota [<provider>…] [--json]
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.
subscription, then an API key, then the credits. first spends them before moving
on: while the account holds credits, routing keeps it where it was and Codex stays
signed in to it, instead of going to an account with room. Alone it says which
accounts don't spend theirs and which spend them first or 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
@@ -484,14 +486,15 @@ func resetUsedWhy(why string) string {
return "used by hand"
}
// quotaCreditsCmd: magpie quota credits [<codex account>] [on|last|off]
// quotaCreditsCmd: magpie quota credits [<codex account>] [on|first|last|off]
// — whether the account spends its credits once its allowance is used
// up, and with last only after everything else.
// up, with first before moving to another account, and with last only
// after everything else.
func quotaCreditsCmd(args []string) error {
user, mode := "", ""
for _, a := range args {
switch strings.ToLower(a) {
case provider.CreditsOn, provider.CreditsLast, provider.CreditsOff:
case provider.CreditsOn, provider.CreditsFirst, provider.CreditsLast, provider.CreditsOff:
mode = strings.ToLower(a)
case "help", "-h", "--help":
fmt.Println(quotaUsage)
@@ -505,14 +508,19 @@ func quotaCreditsCmd(args []string) error {
}
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 <account> last|off")
off, first, last := s.CodexNoCredits, s.CodexCreditsFirst, s.CodexCreditsLast
if len(off) == 0 && len(first) == 0 && len(last) == 0 {
fmt.Println(muted.Render("every Codex account spends its credits once its allowance is used up ·"), "magpie quota credits <account> first|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 first {
if provider.CodexCreditsFirst(u) {
fmt.Println(muted.Render("◑"), u, muted.Render("spends its credits before moving to another account"))
}
}
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"))
@@ -528,6 +536,8 @@ func quotaCreditsCmd(args []string) error {
switch provider.CodexCreditsMode(user) {
case provider.CreditsOn:
fmt.Println(user, "spends its credits once its allowance is used up")
case provider.CreditsFirst:
fmt.Println(user, "spends its credits once its allowance is used up, before moving to another account")
case provider.CreditsLast:
fmt.Println(user, "spends its credits once its allowance is used up, only after every other account, key and fallback")
default:
@@ -541,6 +551,8 @@ func quotaCreditsCmd(args []string) error {
switch mode {
case provider.CreditsOn:
fmt.Println(green.Render("✓"), user+":", "spends its credits once its allowance is used up, so a task goes on")
case provider.CreditsFirst:
fmt.Println(green.Render("✓"), user+":", "spends its credits before moving to another account: routing and Codex's sign-in stay on it while it holds credits")
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:
+4 -4
View File
@@ -641,7 +641,7 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr
// its cache as before; within a turn it stays, and Stays:
// Session or Strict, the user's own, keep it where it is
a.Why = "back"
case at > 0 && pl.order[at].Known && pl.order[at].Used >= provider.SpentShareOf(cs[at].p.Routing):
case at > 0 && pl.order[at].Known && pl.order[at].Used >= provider.SpentShareOf(cs[at].p.Routing) && !pl.order[at].CreditsFirst:
// all but used up, and put behind another: first still — the
// one key or account it has (#1016), or every one used up — it
// doesn't move
@@ -761,7 +761,7 @@ func standsInFor(c candidate, cs []candidate, order []Weighed) bool {
}
for _, w := range order {
if w.ID == o.rest && w.Model == o.model && w.Fixed == o.effort {
if w.Rest != nil || w.Known && w.Used >= provider.SpentShareOf(o.p.Routing) {
if w.Rest != nil || w.Known && w.Used >= provider.SpentShareOf(o.p.Routing) && !w.CreditsFirst {
return true
}
break
@@ -852,10 +852,10 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
// readyForNew says whether order[i], behind order[0], is one routing would
// put a new conversation on: not resting, nor a key for another protocol,
// nor a fallback while the provider's own model leads, nor used past
// lowShare.
// lowShare unless it spends its credits first (Weighed.CreditsFirst).
func readyForNew(order []Weighed, i int) bool {
w := order[i]
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare) && !lastBehind(order, i) && !busyBehind(order, i)
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare && !w.CreditsFirst) && !lastBehind(order, i) && !busyBehind(order, i)
}
// standsIn says whether order[i] is a provider's fallback while one of the
@@ -0,0 +1,79 @@
package gateway
import (
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// jojonas_xyz on X: an account's allowance ran out and magpie went on to
// another of the user's accounts, where they may have wanted its credits
// spent. Routed Smart, the default, an account all but used up waits
// behind every one with room, credits or not; set to spend its credits
// first, a window it uses up doesn't move it: it keeps the place an
// account with room has, low (90%) or used up, and the trace says it is
// so. Set back on (in its place), it waits behind again.
func TestCodexCreditsFirstKeepsItsPlace(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")
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-2") // Smart: the one with room first
if err := provider.SetCodexCreditsMode("Me@Example.com", provider.CreditsFirst); err != nil {
t.Fatal(err)
}
srv := again("acct-1")
rs := srv.Trace(t.Context(), 0, 0).Routes
if len(rs) == 0 || len(rs[0].Order) != 2 || rs[0].Order[0].Who != "me@example.com" || !rs[0].Order[0].CreditsFirst ||
rs[0].Order[1].Who != "spare@example.com" || rs[0].Order[1].CreditsFirst {
t.Fatalf("order %+v", rs)
}
// low, not used up yet: it stays too
creditsUsage(t, map[string]float64{"me@example.com": 95, "spare@example.com": 20}, "me@example.com")
again("acct-1")
// with no credits to go on with, it waits behind as before
creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20})
again("acct-2")
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)
}
again("acct-2")
}
// Routed Until used up, the pool goes on from an account once a window of
// it is used up; set to spend its credits first, it stays on it.
func TestCodexCreditsFirstDrainStays(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20}, "me@example.com")
if err := provider.SetRouting("codex", provider.Drain); err != nil {
t.Fatal(err)
}
if err := provider.SetCodexCreditsMode("me@example.com", provider.CreditsFirst); err != nil {
t.Fatal(err)
}
b.mu.Lock()
b.tried = nil
b.mu.Unlock()
code, body := resetPost(t, New())
if tried, _ := b.seen(); code != 200 || tried != "acct-1" {
t.Fatalf("%d %s tried %q", code, body, tried)
}
}
+5 -3
View File
@@ -1960,8 +1960,9 @@ type left struct {
amount, of float64
unit string
// credits: a Codex account that goes on on its credits once its
// allowance is used up (spendsCredits)
credits bool
// allowance is used up (spendsCredits); first: one set to spend them
// before another account (provider.CodexCreditsFirst)
credits, first bool
// bal is a prepaid wallet's balance in balUnit (Allowance.Left,
// #3950); balIn says whose wallet it is, provider and unit, and is
// empty when no balance was told: routes.Seat.LeftIn
@@ -2042,6 +2043,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
rs := a.Restarts(now)
l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit,
restarts: rs, dueRestart: !rs.IsZero() && due.Equal(rs), credits: spendsCredits(c.p, a)} // one not known counts as unused
l.first = l.credits && provider.CodexCreditsFirst(c.p.Account.User)
if b, bu, has := a.Left(c.model); has {
// a wallet's figure is weighed only against the same
// provider's in the same unit (routes.Seat.LeftIn)
@@ -2068,7 +2070,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
pace = provider.FreshPace
}
seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts),
Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits,
Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits, First: l.first,
Left: l.bal, LeftIn: l.balIn, Spent: spentRest(c)}
}
routed.Unlock()
+5 -1
View File
@@ -349,6 +349,10 @@ type Weighed struct {
// the user's settings.BusyLoad, so it was tried after every ready
// candidate that isn't (restLast)
Busy float64 `json:"busy,omitempty"`
// CreditsFirst: such an account (Credits) the user set to spend its
// credits before another account: all but used up, it keeps its
// place, new conversations and kept ones included
CreditsFirst bool `json:"creditsFirst,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
@@ -510,7 +514,7 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from
w.Kind = "provider"
}
if l, ok := wg.lefts[c.allowanceKey()]; ok {
w.Known, w.Used, w.Renews, w.Pace, w.Credits = true, l.used, l.renews, l.pace, l.credits
w.Known, w.Used, w.Renews, w.Pace, w.Credits, w.CreditsFirst = true, l.used, l.renews, l.pace, l.credits, l.first
if !l.fullest.IsZero() {
ur := l.fullest
w.UsedRenews = &ur
+12 -4
View File
@@ -1875,9 +1875,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
// 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
User string
On bool
Last *bool
First *bool
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
@@ -1887,11 +1888,18 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
fail(rw, fmt.Errorf("which Codex account?"))
return
}
// on alone keeps first or last as it was; either said sets it,
// and one account has one of them
mode := provider.CreditsOff
if in.On {
mode = provider.CreditsOn
if (in.Last == nil && provider.CodexCreditsLast(in.User)) || (in.Last != nil && *in.Last) {
switch was := provider.CodexCreditsMode(in.User); {
case in.Last != nil && *in.Last:
mode = provider.CreditsLast
case in.First != nil && *in.First:
mode = provider.CreditsFirst
case in.Last == nil && in.First == nil && (was == provider.CreditsLast || was == provider.CreditsFirst):
mode = was
}
}
if err := provider.SetCodexCreditsMode(in.User, mode); err != nil {
+5 -2
View File
@@ -2026,8 +2026,11 @@ body.panel .profiles #save { height: 25px; } /* the field's: the line keeps its
.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%; }
.quota-credits, .pq-credits, .acc-credits { flex-wrap: wrap; row-gap: 3px; }
.ar-credits-last, .ar-credits-first { flex-basis: 100%; }
/* and under a Codex account's ⋯ on Providers, a line of its own after
the rest (jojonas_xyz on X) */
.acc .acc-tools > .acc-credits { order: 1; flex-basis: 100%; display: flex; align-items: flex-start; gap: 8px; min-width: 0; margin-top: 2px; color: var(--muted); font-size: 11px; }
.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); }
+34 -36
View File
@@ -13160,6 +13160,11 @@ function renderAccounts(a, p) {
const capFor = (w) => windowCapOf(p, l.user, w);
// how many requests it has out at once, and waiting (#892)
if (p) pill(laneLimitPill(p, l.user, p.id + "@" + String(l.user).toLowerCase(), l.user));
// its credits, as on its Usage card (jojonas_xyz on X)
if (a.agent === "codex" && !sub?.plugin && !unusable(l)) {
const c = creditsRow({ provider: "codex", user: l.user }, "acc-credits");
if (c) tools.append(c);
}
const held = capHeldOf(quota?.[l.user], capFor);
if (held) line.append(capHeldNote(held, held.cap, several, direct));
line.append(el("span", "grow"));
@@ -13209,7 +13214,7 @@ function renderAccounts(a, p) {
const forget = forgetOf(true);
if (l === back) {
const again = el("span", "using", t("First again once it has room"));
again.title = t("magpie signs {agent} back in to this account once it has room again", { agent: a.agentName });
again.title = t("magpie signs {agent} back in to this account once it has room again", { agent: a.agentName }) + (a.agent === "codex" ? " " + t("To spend its credits first: ⋯ › Use credits › Before moving to another account.") : "");
line.append(again);
}
if (kept) {
@@ -16064,16 +16069,9 @@ function byUsageOrder(list) {
return list.map((q, i) => [q, i]).sort(([a, i], [b, j]) => rank(a) - rank(b) || i - j).map(([q]) => q);
}
// keyCards puts a key's balance on its plan's card (#1658, MizuIro-H): a
// Command Code key is told both its plan's 5-hour and weekly windows and
// its credits, and read apart they were two cards of one name, "Command
// Code" twice. As a subscription's credits beside its windows (Command
// Code's own), the balance is the plan card's row under the windows. The
// same key: one of the plan's name, or with the plan of a provider's one
// key unnamed, that provider's one balance. A balance that failed or
// stands in for one that did is left its own card, which says so. The
// balance's card id goes with it (balanceCard), for a menu bar cell
// that opens it.
// keyCards puts a key's balance on its plan's card, a row under the
// windows, rather than a second card of one name (#1658); one that failed
// keeps its own card. balanceCard is its id, for the menu bar.
function keyCards(list) {
list = sharedBalances(list);
const plan = (q) => q.windows?.length && !q.balance && !q.error;
@@ -16091,15 +16089,9 @@ function keyCards(list) {
return gone.size ? list.filter((q) => !gone.has(q)).map((q) => merged.get(q) || q) : list;
}
// packUsage lays the Usage page's cards out in columns, each as tall as
// itself, the next going to the column that ends highest (#860). The order
// reads left to right and stays the page's, for dragging, Alt+arrows and a
// screen reader. As many 260px columns as fit, unless one fewer leaves much
// less empty for a page not much taller; decided again when the cards
// change or the width fits another count. A card growing only packs them
// again, so what was clicked stays put as the scrollbar comes and goes.
// Each column's last card reaches down to the tallest column's end, so the
// bottoms line up (ikunbots on X).
// packUsage lays the Usage cards in 260px columns, the next card to the
// column that ends highest, the order still the page's (#860); each
// column's last reaches the tallest's end (ikunbots on X).
const USAGE_MIN = 260, USAGE_GAP = 7;
let usagePacked = null, usagePackFrame = 0;
function packUsage() {
@@ -17515,12 +17507,8 @@ function panelQuotaCard(q) {
: i || w.members ? ringName(w) + " " + resetClock(at) : resetText(at);
}).join(" · ")
: ws.some((w) => w.used > 0) ? "" : t("Not used yet"));
// The first window's own pace as well, in the line already about its
// deadline: the thin line under it has no room for what it only hints at,
// and a card with no readings of that window has nothing to say (#2079).
// Only while that line is drawn (curves on), and only when the deadline
// the line names is that window's alone: after "Resets 14:26 · Weekly Oct 31"
// it would read as the week's.
// the first window's own pace too, while its line is drawn and the
// deadline named is that window's alone (#2079)
const line = quotaRange !== "off" && begun.length === 1 && begun[0] === ws[0] && !ws[0].tiers ? quotaWindowLine(q, ws[0]) : null;
const pace = line ? quotaEtaText(line, Date.now()) : "";
if (pace) say.append(el("span", "pq-pace", " · " + pace));
@@ -17595,7 +17583,7 @@ function panelQuotaCard(q) {
}
if (credits) {
if (policy) say.append(document.createTextNode(" · "));
say.append(el("b", "", t("Use credits:")), document.createTextNode(" " + t(creditsLast(q) ? "On, after everything else" : creditsOn(q) ? "On" : "Off")));
say.append(el("b", "", t("Use credits:")), document.createTextNode(" " + t(creditsLast(q) ? "On, after everything else" : creditsFirst(q) ? "On, before another account" : creditsOn(q) ? "On" : "Off")));
}
row.append(say);
card.append(row);
@@ -17803,9 +17791,8 @@ function autoResetButton(q, c) {
return b;
}
// 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).
// A Codex account's credits: spent (codexNoCredits, on by default), last
// (codexCreditsLast, gokoshiki) or first (codexCreditsFirst, jojonas_xyz on X).
function creditsKept(q) {
return !!(q.user && q.provider === "codex");
}
@@ -17815,6 +17802,9 @@ function creditsOn(q) {
function creditsLast(q) {
return creditsOn(q) && (state.settings?.codexCreditsLast || []).includes(q.user.toLowerCase());
}
function creditsFirst(q) {
return creditsOn(q) && !creditsLast(q) && (state.settings?.codexCreditsFirst || []).includes(q.user.toLowerCase());
}
// creditsRow: that say on an account's card, its switches beside it.
function creditsRow(q, cls) {
@@ -17827,12 +17817,18 @@ function creditsRow(q, cls) {
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);
// one of first and last at most
const first = creditsFirst(q), last = creditsLast(q);
const line = (cls, on, say, title, body, said) => {
const l = el("div", "ar-case " + cls + (on ? " on" : ""));
const words = el("span", "ar-case-say", t(say));
words.title = t(title);
l.append(words, creditsSwitch(q, cls.slice(3), on, words.title, body, t("Use credits") + " · " + words.textContent, on ? "{who} spends its credits when its windows run out" : said));
row.append(l);
};
line("ar-credits-first", first, "Before moving to another account", first ? "On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off."
: "Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.", { on: true, first: !first }, "{who} spends its credits before moving to another account");
line("ar-credits-last", last, "Only after every other account, key and fallback", 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 answers on its credits when Routing comes to it.", { on: true, last: !last }, "{who} spends its credits only after everything else");
}
return row;
}
@@ -17861,6 +17857,8 @@ function creditsSwitch(q, cls, on, title, body, label, said) {
prefs = await writingPrefs(api("settings/codex-credits", { user: q.user, ...body }));
state.settings = prefs;
status(t(said, { who: q.user }), "ok");
// under an account's ⋯ on Providers, that list again
if (b.closest(".acc")) renderProviders();
renderQuotas();
} catch (err) {
b.disabled = false;
+28 -4
View File
@@ -2198,7 +2198,13 @@ const I18N = {
"{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.": "关:额度用尽后,仍按原位置在那里用积分回答。",
"Off: past its windows, it answers on its credits when Routing comes to it.": "关:额度用尽后,轮到它时用积分回答。",
"Before moving to another account": "先用完积分再换账号",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.": "开:额度用尽后,只要还有积分,它就保持原位置,Codex 也保持登录在它上面。点击关闭。",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.": "关:额度将尽时,让位给还有额度的账号,Codex 的登录也一起切过去。点击开启。",
"{who} spends its credits before moving to another account": "{who} 将先用完积分再换账号",
"On, before another account": "开,先于其他账号",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.": "如想先用完它的积分:⋯ › 使用积分 › 先用完积分再换账号。",
"{who} spends its credits only after everything else": "{who} 仅在其他都用不上时才使用积分",
"On, after everything else": "开,最后使用",
"when its week runs out": "周额度用完时",
@@ -6549,7 +6555,13 @@ const I18N = {
"{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.": "關:額度用盡後,仍按原位置在那裡用積分回答。",
"Off: past its windows, it answers on its credits when Routing comes to it.": "關:額度用盡後,輪到它時用積分回答。",
"Before moving to another account": "先用完積分再換帳號",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.": "開:額度用盡後,只要還有積分,它就保持原位置,Codex 也保持登入在它上面。點擊關閉。",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.": "關:額度將盡時,讓位給還有額度的帳號,Codex 的登入也一起切過去。點擊開啟。",
"{who} spends its credits before moving to another account": "{who} 將先用完積分再換帳號",
"On, before another account": "開,先於其他帳號",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.": "如想先用完它的積分:⋯ › 使用積分 › 先用完積分再換帳號。",
"{who} spends its credits only after everything else": "{who} 僅在其他都用不上時才使用積分",
"On, after everything else": "開,最後使用",
"when its week runs out": "週額度用完時",
@@ -10876,7 +10888,13 @@ const I18N = {
"{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.": "オフ:枠を使い切っても順番はそのままで、その位置でクレジットを使って応答します。",
"Off: past its windows, it answers on its credits when Routing comes to it.": "オフ:枠を使い切った後は、順番が来たときにクレジットで応答します。",
"Before moving to another account": "別のアカウントに移る前に使う",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.": "オン:枠を使い切っても、クレジットがある間は順番と Codex のサインインを保ちます。クリックでオフ。",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.": "オフ:枠がほぼ尽きると、余裕のあるアカウントに譲り、Codex のサインインも移ります。クリックでオン。",
"{who} spends its credits before moving to another account": "{who} は別のアカウントに移る前にクレジットを使います",
"On, before another account": "オン、他のアカウントより先",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.": "先にクレジットを使うには:⋯ › クレジットを使用 › 別のアカウントに移る前に使う。",
"{who} spends its credits only after everything else": "{who} は他をすべて使った後のみクレジットを使用します",
"On, after everything else": "オン、最後に使用",
"when its week runs out": "週の枠を使い切ったとき",
@@ -15234,7 +15252,13 @@ const I18N = {
"{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.",
"Off: past its windows, it answers on its credits when Routing comes to it.": "Aus: Sind die Kontingente aufgebraucht, antwortet es mit Credits, wenn es an der Reihe ist.",
"Before moving to another account": "Bevor ein anderes Konto drankommt",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.": "An: Sind die Kontingente aufgebraucht, behält es seinen Platz und die Anmeldung von Codex, solange es Credits hat. Klicken zum Ausschalten.",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.": "Aus: Fast aufgebraucht, macht es einem Konto mit Spielraum Platz, auch für die Anmeldung von Codex. Klicken zum Einschalten.",
"{who} spends its credits before moving to another account": "{who} verbraucht Credits, bevor ein anderes Konto drankommt",
"On, before another account": "An, vor anderen Konten",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.": "Um zuerst seine Credits zu verbrauchen: ⋯ › Credits nutzen › Bevor ein anderes Konto drankommt.",
"{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",
+47
View File
@@ -0,0 +1,47 @@
package gui
import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// jojonas_xyz on X: Use credits' "Before moving to another account" posts
// first, which sets the account's mode to first; last then takes its
// place, and Use credits alone, turned on again, keeps whichever was set.
func TestCodexCreditsFirstPosted(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
srv := Handler(nil, nil)
post := func(body string) {
t.Helper()
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings/codex-credits", strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", body, rec.Code, rec.Body)
}
}
const me = "Me@example.com"
for _, c := range []struct{ body, want string }{
{`{"user":"Me@example.com","on":true,"first":true}`, provider.CreditsFirst},
{`{"user":"Me@example.com","on":true}`, provider.CreditsFirst},
{`{"user":"Me@example.com","on":true,"last":true}`, provider.CreditsLast},
{`{"user":"Me@example.com","on":true,"first":true}`, provider.CreditsFirst},
{`{"user":"Me@example.com","on":true,"first":false}`, provider.CreditsOn},
{`{"user":"Me@example.com","on":true,"first":true}`, provider.CreditsFirst},
{`{"user":"Me@example.com","on":false}`, provider.CreditsOff},
{`{"user":"Me@example.com","on":true}`, provider.CreditsOn},
} {
post(c.body)
if got := provider.CodexCreditsMode(me); got != c.want {
t.Fatalf("after %s: %q, want %q", c.body, got, c.want)
}
}
}
+1
View File
@@ -174,6 +174,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
CodexResetLead: 180,
CodexNoCredits: []string{"me@example.com"},
CodexCreditsLast: []string{"two@example.com"},
CodexCreditsFirst: []string{"three@example.com"},
CodexWarmAtOf: map[string]string{"me@example.com": "09:00"},
TextSize: 125,
UpdateSkip: "0.1.500",
@@ -0,0 +1,234 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// jojonas_xyz on X: a Codex account's allowance ran out and magpie moved to
// another account by itself, with no setting to be found to keep spending
// the first one's credits. Under Use credits, while it is on, a line says
// "Before moving to another account" with its switch: off until turned on,
// it posts settings/codex-credits with first for that account, says so,
// and turns; it and "Only after every other account, key and fallback"
// are never on together. The same row is under the account's ⋯ on
// Providers, where its other settings are, and the account magpie moved
// off says, on its tag, where the setting is. The panel's folded line says
// it. At narrow widths nothing is cut off or wider than its card, a click
// moves nothing, no native select, 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" },
];
// magpie moved Codex off Me@example.com (returns) to work@example.com
const logins = [
{ user: "work@example.com", plan: "PLUS", active: true, on: true },
{ user: "Me@example.com", plan: "PLUS", on: true, returns: true },
];
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart",
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
account: { agent: "codex", agentName: "Codex", agentIcon: "codex-color", user: "work@example.com", plan: "PLUS", logins },
};
function serve(lang, posts) {
let off = [], first = [], last = [];
const settings = () => ({ theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", trayUsages: ["codex"], trayUsageEvery: 3,
codexNoCredits: off, codexCreditsFirst: first, 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: one of first and last at most; off clears both,
// on alone keeps either
const body = req.postDataJSON();
posts.push(body);
const who = body.user.toLowerCase();
const was = first.includes(who) ? "first" : last.includes(who) ? "last" : "";
off = off.filter((u) => u !== who);
first = first.filter((u) => u !== who);
last = last.filter((u) => u !== who);
if (!body.on) off.push(who);
else if (body.last) last.push(who);
else if (body.first) first.push(who);
else if (body.last === undefined && body.first === undefined && was) (was === "first" ? first : 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/providers") return json({ providers: [codex], presets: [], excluded: [], 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: "Before moving to another account", on: (who) => `${who} spends its credits before moving to another account`, brief: "Use credits: On, before another account" },
zh: { line: "先用完积分再换账号", on: (who) => `${who} 将先用完积分再换账号`, brief: "使用积分: 开,先于其他账号" },
"zh-TW": { line: "先用完積分再換帳號", on: (who) => `${who} 將先用完積分再換帳號`, brief: null },
ja: { line: "別のアカウントに移る前に使う", on: (who) => `${who} は別のアカウントに移る前にクレジットを使います`, brief: null },
de: { line: "Bevor ein anderes Konto drankommt", on: (who) => `${who} verbraucht Credits, bevor ein anderes Konto drankommt`, brief: null },
};
const keys = [
"Before moving to another account",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.",
"Off: past its windows, it answers on its credits when Routing comes to it.",
"{who} spends its credits before moving to another account",
"On, before another account",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.",
];
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 before moving to another account`, 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");
};
// both lines fit their card, their switches whole and at their
// line's end, 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();
if (b.right > c.right + 0.5) return "row";
for (const [line, sw] of [[".ar-credits-first", ".credits-first"], [".ar-credits-last", ".credits-last"]]) {
const l = r.querySelector(line), s = l.querySelector(sw).getBoundingClientRect(), words = l.querySelector(".ar-case-say");
if (s.right > c.right + 0.5 || s.width < 27 || s.height < 15) return sw;
if (words.scrollWidth > words.clientWidth + 1) return line + " cut off";
}
return "";
}, [row, card]);
const noStripe = (page, sel) => page.evaluate((sel) => [...document.querySelectorAll(sel + ", " + sel + " *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1), sel);
// the Usage page's 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-first").waitFor();
assert.equal(await text(page.locator(row + " .ar-credits-first")), w.line);
const sw = page.locator(row + " .credits-first");
assert.equal(await sw.getAttribute("role"), "switch");
assert.equal(await sw.getAttribute("aria-checked"), "false", "off until set");
assert(await sw.getAttribute("title"));
assert.equal(await fits(page, row, ".subscription-card"), "", `the lines fit the card at ${width}px`);
await flip(page, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row + " .ar-credits-first.on").count(), 1);
assert.equal(await fits(page, row, ".subscription-card"), "", `the lines, on, fit the card at ${width}px`);
// last takes its place: one of the two at most
await page.locator(row + " .credits-last").click();
await wait(posts, 2);
assert.deepEqual(posts.at(-1), { user: "Me@example.com", on: true, last: true });
await page.locator(row + ' .credits-last[aria-checked="true"]').waitFor();
assert.equal(await page.locator(row + " .credits-first").getAttribute("aria-checked"), "false");
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-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row + " .credits-last").getAttribute("aria-checked"), "false");
await flip(page, row, posts, ".credits-first", false, { user: "Me@example.com", on: true, first: false }, back);
// Use credits off: no lines, as nothing is spent at all
await page.locator(row + " .use-credits").click();
await wait(posts, 5);
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-first").count(), 0);
assert.deepEqual(await noStripe(page, ".quota-credits"), [], "no left-border accent");
await page.context().close();
}
// Providers: the account's ⋯, where its other settings are, and the
// account magpie moved off says where it is
for (const width of [900, 440]) {
const posts = [];
const page = await open("http://magpie.test/?view=providers", { width, height: 760 }, posts);
await page.locator(".row.provider", { hasText: "Codex" }).first().click();
const acc = page.locator(".editor .acc", { hasText: "Me@example.com" });
await acc.waitFor();
const tag = acc.locator(".acc-line .using").first();
assert(String(await tag.getAttribute("title")).includes(w.line), "the moved-off account's tag names the setting");
await acc.hover();
await acc.locator(".acc-more").click();
const row = '.editor .acc .acc-credits[data-user="Me@example.com"]';
await page.locator(row + " .ar-credits-first").waitFor();
assert.equal(await text(page.locator(row + " .ar-credits-first")), w.line);
assert.equal(await fits(page, row, ".acc"), "", `the lines fit the account at ${width}px`);
await flip(page, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row).count(), 1, "the ⋯ stays open");
assert.equal(await fits(page, row, ".acc"), "", `the lines, on, fit the account at ${width}px`);
// the account Codex is signed in to has its own
assert.equal(await page.locator('.editor .acc .acc-credits[data-user="work@example.com"]').count(), 1);
assert.equal(await page.locator("select").count(), 0, "no native select");
assert.deepEqual(await noStripe(page, ".acc-credits"), [], "no left-border accent");
await page.context().close();
}
// the menu bar panel's folded line says it
{
const posts = [];
const panel = await open("http://magpie.test/?mode=panel", { width: 360, 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-first").waitFor();
await panel.waitForFunction(() => !quotasLoading);
assert.equal(await fits(panel, row, ".pq-card"), "", "the lines fit the panel's card at 360px");
await flip(panel, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
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, before another account")));
assert(said.endsWith(want), said);
if (lang !== "en") {
const missing = await panel.evaluate(([keys, lang]) => keys.filter((k) => !I18N[lang][k]), [keys, lang]);
assert.deepEqual(missing, [], `every string has its ${lang}`);
}
await panel.context().close();
}
assert.deepEqual(errors, []);
});
}
}
@@ -96,7 +96,7 @@ const words = {
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.",
"Off: past its windows, it answers on its credits when Routing comes to it.",
"{who} spends its credits when its windows run out",
"{who} spends its credits only after everything else",
"On, after everything else",
@@ -38,7 +38,10 @@ function fixtures(now) {
}
function serve(lang, data) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
// Codex's credits off: its card has no credits lines, so how many there
// are doesn't decide whether the balance's card (held down to the
// column beside it) has room to grow
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", codexNoCredits: ["a@x.com"] };
return async (route) => {
const url = new URL(route.request().url());
const json = (body) => route.fulfill({ json: body });
+31 -11
View File
@@ -14,9 +14,10 @@ package provider
// no credits is refused by the vendor at 100% either way; the switch only
// spares it the request.
//
// It doesn't change which account Codex is signed in to: NextLogin moves
// off an account at its routing's spent share (100% at most) and onto none
// past it, credits or not. Unlike the cap, it holds at the vendor's own
// Unless the account spends them first (CodexCreditsFirst), it doesn't
// change which account Codex is signed in to: NextLogin moves off an
// account at its routing's spent share (100% at most) and onto none past
// it, credits or not. Unlike the cap, it holds at the vendor's own
// 100%, so an account that spends its resets by itself spends one there
// (the gateway's autoReset) where a cap never does.
@@ -44,15 +45,29 @@ func CodexCreditsLast(user string) bool {
return user != "" && slices.Contains(s.CodexCreditsLast, user) && !slices.Contains(s.CodexNoCredits, user)
}
// CodexCreditsFirst says whether the Codex account user, which spends its
// credits, spends them before routing moves on: a window used up sends
// neither requests nor Codex's sign-in to another account while it goes
// on on its credits (gateway's creditsFirst, NextLogin), where by default
// an account all but used up waits behind every one with room (Smart)
// and Codex is signed in to another (jojonas_xyz on X). Off unless the
// user set it.
func CodexCreditsFirst(user string) bool {
user = accountKey(user)
s := settings.Load()
return user != "" && slices.Contains(s.CodexCreditsFirst, user) && !slices.Contains(s.CodexNoCredits, user) && !slices.Contains(s.CodexCreditsLast, 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
CreditsOn = "on" // in its place, the default
CreditsFirst = "first" // before moving to another account
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.
// it clears "first" and "last" too.
func SetCodexCredits(user string, on bool) error {
if on {
return SetCodexCreditsMode(user, CreditsOn)
@@ -61,32 +76,37 @@ func SetCodexCredits(user string, on bool) error {
}
// CodexCreditsMode is how user spends its credits: CreditsOn,
// CreditsLast or CreditsOff.
// CreditsFirst, CreditsLast or CreditsOff.
func CodexCreditsMode(user string) string {
switch {
case !CodexCredits(user):
return CreditsOff
case CodexCreditsLast(user):
return CreditsLast
case CodexCreditsFirst(user):
return CreditsFirst
}
return CreditsOn
}
// SetCodexCreditsMode sets how user spends its credits: CreditsOn,
// CreditsLast or CreditsOff.
// CreditsFirst, CreditsLast or CreditsOff. One account has one of them.
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)
if mode != CreditsOn && mode != CreditsFirst && mode != CreditsLast && mode != CreditsOff {
return fmt.Errorf("credits: %q is not on, first, 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)
s.CodexCreditsFirst = slices.DeleteFunc(s.CodexCreditsFirst, not)
if user != "" {
switch mode {
case CreditsOff:
s.CodexNoCredits = append(s.CodexNoCredits, user)
case CreditsFirst:
s.CodexCreditsFirst = append(s.CodexCreditsFirst, user)
case CreditsLast:
s.CodexCreditsLast = append(s.CodexCreditsLast, user)
}
@@ -0,0 +1,106 @@
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// Spending credits first is a fourth way, one of the four an account has:
// setting it clears last, setting last or off clears it, and on clears
// both.
func TestCodexCreditsFirstMode(t *testing.T) {
signIn(t)
if CodexCreditsMode("me@example.com") != CreditsOn || CodexCreditsFirst("me@example.com") {
t.Fatal("first before it was set")
}
if err := SetCodexCreditsMode("me@example.com", CreditsLast); err != nil {
t.Fatal(err)
}
if err := SetCodexCreditsMode(" Me@Example.com ", CreditsFirst); err != nil {
t.Fatal(err)
}
s := settings.Load()
if !slices.Equal(s.CodexCreditsFirst, []string{"me@example.com"}) || len(s.CodexCreditsLast)+len(s.CodexNoCredits) != 0 {
t.Fatalf("kept first %v, last %v, off %v", s.CodexCreditsFirst, s.CodexCreditsLast, s.CodexNoCredits)
}
if !CodexCreditsFirst("ME@example.com") || CodexCreditsLast("me@example.com") || CodexCreditsMode("me@example.com") != CreditsFirst || CodexCreditsFirst("other@example.com") {
t.Fatal("read back wrong")
}
for _, mode := range []string{CreditsLast, CreditsOff, CreditsOn} {
if err := SetCodexCreditsMode("me@example.com", CreditsFirst); err != nil {
t.Fatal(err)
}
if err := SetCodexCreditsMode("me@example.com", mode); err != nil {
t.Fatal(err)
}
if CodexCreditsFirst("me@example.com") || CodexCreditsMode("me@example.com") != mode {
t.Fatalf("%s kept first: %v", mode, settings.Load().CodexCreditsFirst)
}
}
}
// Codex signed in to an account whose week is used up but that holds
// credits is signed in to the next account with room, as by default
// (TestCodexSwitchedWhenUsedUp), unless the account is set to spend its
// credits first (jojonas_xyz on X): then it stays on it while it holds
// them, and moves on once they are gone.
func TestCodexStaysOnAnAccountSpendingCreditsFirst(t *testing.T) {
home := signIn(t) // me@example.com, acct-1
rememberLogins(true)
codexSignIn(t, home, "spare@example.com", "r-spare")
rememberLogins(true)
codexSignIn(t, home, "main@example.com", "r-main") // the one Codex is on
rememberLogins(true)
if err := SetLoginOn("codex", "spare@example.com", true); err != nil {
t.Fatal(err)
}
used := map[string]float64{"acct-main@example.com": 100, "acct-1": 100, "acct-spare@example.com": 20}
credits := true
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body := map[string]any{"plan_type": "plus", "rate_limit": map[string]any{
"primary_window": map[string]any{"used_percent": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 604800}}}
if r.Header.Get("chatgpt-account-id") == "acct-main@example.com" && credits {
body["credits"] = map[string]any{"has_credits": true, "unlimited": false, "balance": "120"}
}
json.NewEncoder(w).Encode(body)
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
t.Cleanup(func() {
codexApp.Lock()
codexApp.switched, codexApp.spent = false, false
codexApp.Unlock()
})
next := func() (string, bool) {
t.Helper()
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
_, to, _, ok := NextLogin(context.Background(), "codex")
return to, ok
}
// by default, credits or not, it moves
if to, ok := next(); !ok || to != "spare@example.com" {
t.Fatalf("default: to %q, %v", to, ok)
}
// set to spend them first, it stays
if err := SetCodexCreditsMode("main@example.com", CreditsFirst); err != nil {
t.Fatal(err)
}
if to, ok := next(); ok {
t.Fatalf("first: moved to %q", to)
}
// its credits gone, it moves on
credits = false
if to, ok := next(); !ok || to != "spare@example.com" {
t.Fatalf("first, no credits left: to %q, %v", to, ok)
}
}
+12
View File
@@ -304,6 +304,11 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
if keep || !known || q.Error != "" || !q.Held && !usedPast(q, share, now) && !capped(from, q) {
return "", "", false, false
}
if agent == "codex" && !q.Held && !capped(from, q) && spendsFirst(from, q) {
// set to spend its credits before another account, and holding
// some: Codex stays on it (jojonas_xyz on X)
return "", "", false, false
}
users := make([]string, 0, len(spares))
for _, l := range spares {
users = append(users, l.User)
@@ -342,6 +347,13 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
return "", "", false, false
}
// spendsFirst says whether the Codex account user, read as q, is set to
// spend its credits before another account (CodexCreditsFirst) and holds
// some, as its windows say (QuotaWindow.Credits).
func spendsFirst(user string, q SubscriptionQuota) bool {
return CodexCreditsFirst(user) && slices.ContainsFunc(q.Windows, func(w QuotaWindow) bool { return w.Credits })
}
// roomMargin is how much more room (roomLeft) an account past its line
// needs than the one the agent is on, past its line too, to be moved to.
const roomMargin = 1
+1 -1
View File
@@ -63,7 +63,7 @@ var Fastest = Strategy{BySpeed: true, Order: func(pool string, seats []Seat) []i
switch {
case s.Resting:
resting = append(resting, i)
case tier(s.Used) == 2:
case seatTier(s) == 2:
spent = append(spent, i)
case s.TTFT > 0:
fast = append(fast, i)
+5
View File
@@ -58,6 +58,11 @@ type Seat struct {
// credits, and is let spend them. All but used up, it goes before
// those used up with nothing to go on with.
Credits bool
// First: such an account the user set to spend its credits before
// another account (provider.CodexCreditsFirst): its windows running
// out never put it behind the others (seatTier), so it keeps the
// place an account with room has.
First bool
// TTFT is how long it took lately to the first of its reply, in ms,
// for the model this seat would be asked for: a decayed average of its
// recent streamed answers, 0 when it hasn't answered one lately.
+16 -4
View File
@@ -29,6 +29,16 @@ func tier(share float64) int {
return 0
}
// seatTier is tier of the seat's share used, but 0 for one set to spend
// its credits before another account (Seat.First): a window it uses up
// doesn't send its requests elsewhere (jojonas_xyz on X).
func seatTier(s Seat) int {
if s.First {
return 0
}
return tier(s.Used)
}
// byLeft is how a pool's wallets go by what they have left (Seat.Left),
// as a comparison of two seats by their index: of seats whose balance is
// in one provider's one unit (Seat.LeftIn), the one with more left first;
@@ -121,7 +131,7 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
left := byLeft(seats, nil)
var fine, low, spent []int
for i, s := range seats {
switch tier(s.Used) {
switch seatTier(s) {
case 2:
spent = append(spent, i)
case 1:
@@ -224,7 +234,9 @@ func Drained(key string) {
// it on the first not used up, in the listed order. Asking again with
// nothing changed gives the same order, so a preview moves nothing.
var Drain = Strategy{Exact: true, Order: func(pool string, seats []Seat) []int {
spent := func(s Seat) bool { return s.Spent || s.Known && s.Used >= provider.SpentShareOf(provider.Drain) }
spent := func(s Seat) bool {
return s.Spent || !s.First && s.Known && s.Used >= provider.SpentShareOf(provider.Drain)
}
drains.Lock()
defer drains.Unlock()
on := drains.m[pool]
@@ -311,7 +323,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
// band's top and part two alike behind it
var byPace []int
for i, s := range seats {
if tier(s.Used) == 0 && !s.Learns {
if seatTier(s) == 0 && !s.Learns {
byPace = append(byPace, i)
}
}
@@ -332,7 +344,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
idx := identity(len(seats))
sort.SliceStable(idx, func(a, b int) bool {
sa, sb := seats[idx[a]], seats[idx[b]]
if ta, tb := tier(sa.Used), tier(sb.Used); ta != tb {
if ta, tb := seatTier(sa), seatTier(sb); ta != tb {
return ta < tb
} else if ta == 2 && sa.Credits != sb.Credits {
return sa.Credits
+10
View File
@@ -314,6 +314,12 @@ type Settings struct {
// 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"`
// CodexCreditsFirst are the ChatGPT accounts (lower-case) that spend
// their credits before routing moves to another account: a window used
// up doesn't send requests or Codex's sign-in elsewhere while the
// account goes on on its credits (jojonas_xyz on X). Not one of
// CodexNoCredits nor CodexCreditsLast.
CodexCreditsFirst []string `json:"codexCreditsFirst,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.
@@ -2151,6 +2157,10 @@ func saveOwn(s Settings, recording, reads bool) error {
s.CodexCreditsLast[i] = strings.ToLower(u)
}
s.CodexCreditsLast = ids(s.CodexCreditsLast)
for i, u := range s.CodexCreditsFirst {
s.CodexCreditsFirst[i] = strings.ToLower(u)
}
s.CodexCreditsFirst = ids(s.CodexCreditsFirst)
s.TrayUsage = ""
if len(s.TrayUsages) > 0 {
s.TrayUsage = s.TrayUsages[0]
+2 -1
View File
@@ -314,7 +314,8 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
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
in.CodexCreditsLast = cur.CodexCreditsLast // and which only after everything else
in.CodexCreditsFirst = cur.CodexCreditsFirst // and which before another account
// and each Codex account's own daily warm-up (codex-warm-at)
in.CodexWarmAtOf = cur.CodexWarmAtOf
// and the text size, which the keyboard changes too (text-size)