gateway keys: a limit can follow a subscription account's own window (ljayic on X)

A key's limit gains the period "account": it names one subscription
account ("<provider>/<user>") and one of its windows (5h, Weekly, Monthly,
...), and starts and resets when that account's window does, at the reset
time in the account's last good reading (quotas.json), never asked of the
vendor on the request's path (provider.AccountWindow).

When the window can't be read (no reading yet, no such window, or its reset
has passed with no reading since), the limit is "reset unknown": it is
neither reset nor lifted. It counts from the latest time the window can't
have begun before (the reset that passed, else when the limit was set), so
it counts at least the window's calls; a refused call gets Retry-After 300
and a 429 saying the window can't be read now, and the accounts are read
again in the background at most once a minute.

GUI: Gateway keys -> a key's limit -> Window -> "An account's window", then
an app-menu picker of the accounts' windows as read (GET
/api/caller-keys/account-windows); the row reads "$x / $y · 5h of
codex/...", and an unknown reset reads "resets with the account's window".
CLI: magpie gateway-key limit <id> account --account codex/me@example.com
--window 5h --tokens 2m. i18n zh, zh-TW, ja, de. reference.md and
gateway-routing.md say it, with the fallback.

Run (at this tree, base ec8125e68, rebased onto 1ac137e10 which touches
none of these files):
- gofmt -l clean; go vet darwin, linux (-tags nogui), windows clean (mica).
- go test -count=1: internal/access, internal/budget, internal/provider,
  internal/cli, internal/gui ok (mica). TestEveryRouteHasACommandOrIsNamed
  was red until the new route was named (magpie quota).
- New: TestAccountWindowLimit (budget), TestAccountWindowFromLastReading and
  TestReadAccountWindowsOnceAMinute (provider), TestParseAccountWindowLimit
  (cli), TestCallerKeyAccountWindowsRoute (gui). Broken by hand: the unknown
  branch made to guess a 5h window from now -> TestAccountWindowLimit red
  ("let through on a window not read").
- GUI: gateway-key-account-window.test.cjs, chromium + webkit, en zh zh-TW
  ja de, 500px, no native select: 10 of 10 (red without the keys.js and
  i18n change). Every GUI file that loads the caller-keys fixture or the
  Gateway keys page, plus i18n*: 1064 tests, 1046 pass, 18 red, the same
  18 red on origin/main ec8125e68 alone: api-key-theme (6, #6444),
  gateway-key-arrange 420px (10, #6268), text-size webkit (a subtest and its test, #6561).
Not tried: a real Codex/Claude account's window through a live gateway;
the full GUI suite (mote and mica each had a full suite running).
This commit is contained in:
yetone
2026-11-15 03:50:46 +08:00
parent 1ac137e100
commit 6256d9956a
19 changed files with 940 additions and 66 deletions
+12 -2
View File
@@ -683,6 +683,7 @@ magpie gateway-key limit <id> week --tokens 2m --cost 5 # its own limit
magpie gateway-key limit <id> list # each limit, used, left and reset
magpie gateway-key limit <id> 10d --tokens 5m # every 10 days, from now
magpie gateway-key limit <id> total --cost 300 # $300 in total, until reset
magpie gateway-key limit <id> account --account codex/me@example.com --window 5h --tokens 2m # with that account's 5 hours
magpie gateway-key limit <id> 5h --tokens 200k # every 5 hours, from now
magpie gateway-key limit <id> add week --cost 20 # one more limit; all must pass
magpie gateway-key limit <id> add month --cost 20 --model openai/* # a limit of only OpenAI's models
@@ -710,7 +711,16 @@ N from 1 to 3650) or every N hours (#2102; N from 1 to 8760, such as 5 for
a subscription's 5-hour pace), or **in total** (`total`, @Cyrus_4433 on X):
a limit that never resets by the clock, counted from when it is set and
started again only by **Reset usage** (`magpie gateway-key limit <id> total
--cost 300`); its 429 says it stays refused until it is reset or raised. An N-day or N-hour cycle starts when the
--cost 300`); its 429 says it stays refused until it is reset or raised. Or it follows **an account's window** (`account`, ljayic on X): one
subscription account's own 5 hours, week or month, starting and resetting
when that account's last reading says its window does (Gateway keys → the
key's limit → Window → An account's window, then the account's window; CLI
`--account <provider>/<account> --window <name>`). When that window can't
be read (no reading yet, or its reset has passed with none since), the
limit isn't reset or lifted: it counts from the reset that passed (or from
when the limit was set), its row says it resets with the account's window,
and a refused call is told to retry in 5 minutes while magpie reads the
accounts again. An N-day or N-hour cycle starts when the
limit is set and runs N×24 or N hours, then the next one starts where it
ended, so a restart, a time-zone change or a daylight-saving shift doesn't
move it. Changing only
@@ -1142,7 +1152,7 @@ can't drift:
| `POST provider/{action}` | `save`, `delete`, `on`, `off`, `name`, `efforts`, `images`, `arrange`, `route`, `affinity`, `sink`, `usefirst`, `test`, `models`, `list`, and each key's or account's setting (`accountcap`, `accountname`, `windowcap`, `accountweight`, `keyspendcap`, `keyexpiring`, …) |
| `POST keys/{action}`, `POST login/{action}`, `GET login/usage` | a provider's keys, and its signed-in accounts |
| `POST signin` `{"agent": …}`, `GET signin/{id}`, `POST signin/{id}/cancel`, `POST signin/{id}/callback` | OAuth sign-in: the answer holds the vendor's page and the code to type there. Nothing is opened on this computer and no password is taken |
| `GET gateway-keys[/models\|/mcp]`, `POST gateway-keys/{action}` | gateway keys: `add-key`, `rename-key`, `rotate-key`, `limit-key`, `models-key`, `accounts-key`, `mcp-key`, `access-key`, `on-key`, `off-key`, `remove-key`, … |
| `GET gateway-keys[/models\|/mcp\|/account-windows]`, `POST gateway-keys/{action}` | gateway keys: `add-key`, `rename-key`, `rotate-key`, `limit-key`, `models-key`, `accounts-key`, `mcp-key`, `access-key`, `on-key`, `off-key`, `remove-key`, … |
| `GET account-groups`, `POST account-groups/{action}` | named account groups |
| `GET routing-groups`, `GET routing-groups/{id}` | the Routing page's groups and combos, as the app shows them; one by its id or `group/<id>` |
| `POST routing-groups/create`, `POST routing-groups/update` | a group or combo made, or changed: `create` takes the editor's body (`name`, `members`, …) and is 409 for an id in use; `update` takes `id` and only the fields to change, the rest kept (`from` and a new `id` rename it, and the combos naming it follow) |
+1 -1
View File
@@ -853,7 +853,7 @@ limits at once, each in its own window, and a request needs every one
the spent limit that resets last). The saved key keeps the first limit in
`limit`, which older magpie reads, and the rest in `moreLimits`. The answer's
`limit` is the one holding the key most (`budget.Binding`), what older
clients read, and `limits` is each of them (`budget.All`). A limit's period `total` (@Cyrus_4433 on X) never resets by the clock: `access.Limit.Window` counts it from its `Since` (when it was set, or last reset; the epoch if hand-written without one) to a reset a hundred years off, so only the key's Reset moves it; its 429 says it stays refused until reset or raised. `TestTotalLimit*` in [`internal/budget`](../../internal/budget). Holding a
clients read, and `limits` is each of them (`budget.All`). A limit's period `total` (@Cyrus_4433 on X) never resets by the clock: `access.Limit.Window` counts it from its `Since` (when it was set, or last reset; the epoch if hand-written without one) to a reset a hundred years off, so only the key's Reset moves it; its 429 says it stays refused until reset or raised. `TestTotalLimit*` in [`internal/budget`](../../internal/budget). A limit's period `account` (ljayic on X) follows one subscription account's window (`Account` "<provider>/<user>", `AccountWindow` its name): `access.Limit.Window` asks `provider.AccountWindow`, which reads the account's last good reading (quotas.json, never the vendor on the request's path) for that window's start and reset. When it isn't known (no reading, no such window, or the reset passed with no reading since) the reset is zero and the start is the latest time the window can't have begun before (the reset that passed, else `Since`), so the limit counts at least the window's calls and is never lifted on a guess; `budget` then says `resetUnknown`, its 429 retries after 5 minutes, and the accounts are read again in the background at most once a minute. `TestAccountWindowLimit` in [`internal/budget`](../../internal/budget), `TestAccountWindowFromLastReading` in [`internal/provider`](../../internal/provider). Holding a
key to its limits is the Key limits plugin's, on the gateway's budget
point ([Plugin runtime](plugin-runtime.md#gateway-extension-points-p3-budget)):
with it off, a key held to a limit gets 503 and nothing is sent. A limit can count
+71 -9
View File
@@ -2,6 +2,7 @@ package access
import (
"github.com/yetone/magpie/internal/dayzone"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"errors"
@@ -45,6 +46,13 @@ type Limit struct {
// members outside it. None, the whole key, as every limit from
// before this.
Models []string `json:"models,omitempty"`
// Account and AccountWindow are an "account" limit's window
// (ljayic on X): the window of that name ("5h", "Weekly") of one
// subscription account ("codex/me@example.com", as a key's accounts
// are written), so the key's budget starts again when the account's
// does. Empty for the others.
Account string `json:"account,omitempty"`
AccountWindow string `json:"accountWindow,omitempty"`
}
// Scoped: l counts only some models' calls (Limit.Models).
@@ -117,7 +125,8 @@ func (k *Key) setLimits(ls []Limit) {
// sameWindow: l and o count in the same window, so two limits of one key
// that do are one limit with two caps.
func (l *Limit) sameWindow(o *Limit) bool {
return l.Period == o.Period && l.Days == o.Days && l.Hours == o.Hours
return l.Period == o.Period && l.Days == o.Days && l.Hours == o.Hours &&
strings.EqualFold(l.Account, o.Account) && provider.WindowCapID(l.AccountWindow) == provider.WindowCapID(o.AccountWindow)
}
// sameLimit: l and o count the same calls in the same window, so a key
@@ -129,9 +138,12 @@ func (l *Limit) sameLimit(o *Limit) bool {
// Periods are the windows a limit can be set for.
//
// "total" never resets by the calendar: it counts from when it was set,
// or last reset, and only a reset starts it again.
var Periods = []string{"day", "week", "month", "days", "hours", "total"}
// "account" follows one subscription account's window (Account,
// AccountWindow): it starts and resets when that window does, as the
// account's last reading tells. "total" never resets by the calendar: it
// counts from when it was set, or last reset, and only a reset starts it
// again.
var Periods = []string{"day", "week", "month", "days", "hours", "account", "total"}
// MaxDays is the longest "days" cycle, ten years.
const MaxDays = 3650
@@ -173,6 +185,12 @@ func (l *Limit) Valid() (*Limit, error) {
switch v.Period {
case "day", "week", "month", "total":
v.Days, v.Hours = 0, 0
case "account":
v.Days, v.Hours = 0, 0
v.Account, v.AccountWindow = strings.TrimSpace(v.Account), strings.TrimSpace(v.AccountWindow)
if pid, user, ok := strings.Cut(v.Account, "/"); !ok || pid == "" || user == "" || v.AccountWindow == "" {
return nil, errors.New("A limit that follows an account's window names the account, like codex/me@example.com, and the window, like 5h")
}
case "days":
v.Hours = 0
if v.Days < 1 || v.Days > MaxDays {
@@ -184,7 +202,10 @@ func (l *Limit) Valid() (*Limit, error) {
return nil, fmt.Errorf("A limit's cycle is a whole number of hours from 1 to %d", MaxHours)
}
default:
return nil, errors.New("A limit's period is day, week, month, total, every N days or every N hours")
return nil, errors.New("A limit's period is day, week, month, total, every N days, every N hours or an account's window")
}
if v.Period != "account" {
v.Account, v.AccountWindow = "", ""
}
v.Cost = math.Round(v.Cost*1e4) / 1e4
ms, err := CleanModels(v.Models)
@@ -204,9 +225,12 @@ func (l *Limit) Valid() (*Limit, error) {
}
// Per is the window as a sentence ends it: "day", "week", "month",
// "total", "10-day cycle" or "5-hour cycle".
// "total", "10-day cycle", "5-hour cycle" or "codex/me@example.com 5h
// window".
func (l *Limit) Per() string {
switch l.Period {
case "account":
return l.Account + " " + l.AccountWindow + " window"
case "days":
return fmt.Sprintf("%d-day cycle", l.Days)
case "hours":
@@ -224,10 +248,12 @@ func (l *Limit) Counts(model string) bool {
// sinceOf is the Since a limit set as next keeps, with prev the key's
// limit before: its own while the period and cycle stay the same (a new
// cap doesn't restart the window), else a new cycle from now for "days"
// and "hours" and for "total", and none for a calendar period.
// and "hours" and for "total" and "account" (an account's window counts
// from when the limit was set, the calls before it in that window
// aside), and none for a calendar period.
func sinceOf(prev, next *Limit, now time.Time) time.Time {
cyclic := next.cycle() > 0 || next.Period == "total"
if prev != nil && prev.Period == next.Period && prev.Days == next.Days && prev.Hours == next.Hours && (!cyclic || !prev.Since.IsZero()) {
cyclic := next.cycle() > 0 || next.Period == "total" || next.Period == "account"
if prev != nil && prev.sameWindow(next) && (!cyclic || !prev.Since.IsZero()) {
return prev.Since
}
if cyclic {
@@ -247,6 +273,9 @@ var epoch = time.Unix(0, 0)
// in it.
func (l *Limit) Window(now time.Time) (start, reset time.Time) {
loc := now.Location()
if l.Period == "account" {
return l.accountWindow(now)
}
if l.Period == "total" {
// counted from when it was set or reset (a hand-written one with
// no Since, from the epoch), and never ends: the reset a refusal
@@ -296,3 +325,36 @@ func Window(period string, now time.Time) (start, reset time.Time) {
return time.Date(y, m, d, 0, 0, 0, 0, loc), time.Date(y, m, d+1, 0, 0, 0, 0, loc)
}
}
// accountWindow is an "account" limit's window at now: the account's own,
// from its last reading (provider.AccountWindow), begun no earlier than
// the limit was set or reset.
//
// When that window isn't known (no reading, the read failing, its reset
// passed with no reading since), reset is zero, "unknown", and the
// window is taken to have begun at the latest time known to be no later
// than its real start: the reset that passed, else when the limit was
// set or reset. That counts every call of the real window and maybe a
// few before it, never fewer: the key is held a little early rather
// than let through on a guess, and it is never reset on one. It starts
// again once a reading tells the new window.
func (l *Limit) accountWindow(now time.Time) (start, reset time.Time) {
loc := now.Location()
s, end, known := provider.AccountWindow(l.Account, l.AccountWindow, now)
since := l.Since
if since.Before(epoch) {
since = epoch
}
if !known {
start = since
if s.After(start) && !s.After(now) {
start = s
}
return start.In(loc), time.Time{}
}
start = s
if since.After(start) && since.Before(end) {
start = since
}
return start.In(loc), end.In(loc)
}
+149
View File
@@ -0,0 +1,149 @@
package budget
import (
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// A limit that follows a subscription account's window (ljayic on X)
// counts the key's calls from when that account's 5 hours began and
// starts again when the account's does, at the reset its reading tells.
// While the window can't be read it is unknown: the key is held to what
// it spent since the earliest the window can have begun, never reset or
// let through on a guess, and told to ask again in five minutes.
func TestAccountWindowLimit(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Cleanup(Forget)
now := time.Now().Round(0)
set := now.AddDate(0, 0, -10) // the limit is set ten days ago
access.Now = func() time.Time { return set }
t.Cleanup(func() { access.Now = time.Now })
// the account's 5 hours: begun two hours ago, ends in three
type win struct {
start, reset time.Time
known bool
}
w := win{now.Add(-2 * time.Hour), now.Add(3 * time.Hour), true}
var asked []string
t.Cleanup(provider.AccountWindowVia(func(account, name string, at time.Time) (time.Time, time.Time, bool) {
asked = append(asked, account+" "+name)
if account != "codex/me@example.com" || name != "5h" {
return time.Time{}, time.Time{}, false
}
return w.start, w.reset, w.known
}))
if _, err := access.Update("add-key", access.Change{Name: "Shared"}); err != nil {
t.Fatal(err)
}
ks, _ := access.List()
k := ks[0]
// an account limit names its account and window
if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &access.Limit{Period: "account", Account: "codex/me@example.com", Tokens: 1000}}); err == nil {
t.Fatal("an account limit with no window was taken")
}
if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &access.Limit{Period: "account", Account: "codex/me@example.com", AccountWindow: "5h", Tokens: 1000}}); err != nil {
t.Fatal(err)
}
// the same account's week, and another account's 5 hours, are limits of their own
for _, l := range []access.Limit{
{Period: "account", Account: "codex/me@example.com", AccountWindow: "Weekly", Tokens: 100000},
{Period: "account", Account: "claude/me@example.com", AccountWindow: "5h", Tokens: 100000},
} {
n := 1
if l.Account == "claude/me@example.com" {
n = 2
}
if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &l, Index: &n}); err != nil {
t.Fatalf("%s %s: %v", l.Account, l.AccountWindow, err)
}
}
n := 3
if _, err := access.Update("limit-key", access.Change{Key: k.ID, Index: &n, Limit: &access.Limit{Period: "account", Account: "Codex/ME@example.com", AccountWindow: "5H", Tokens: 5}}); err == nil {
t.Fatal("one account's window was taken twice")
}
ks, _ = access.List()
k = ks[0]
if len(k.Limits()) != 3 || !k.Limit.Since.Equal(set) {
t.Fatalf("limits: %+v", k.Limits())
}
who := access.Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More}
refused := func(at time.Time) *Refusal {
t.Helper()
Forget() // counted afresh from the ledger, as after a restart
_, r := Reserve(who, -1, "", at)
return r
}
// before the window: not counted
Append(usage.Record{Time: now.Add(-3 * time.Hour), Provider: "p", Model: "m", Input: 900, Status: 200, CallerKeyID: k.ID})
Append(usage.Record{Time: now.Add(-time.Hour), Provider: "p", Model: "m", Input: 400, Status: 200, CallerKeyID: k.ID})
if r := refused(now); r != nil {
t.Fatalf("a call before the account's window counted: %v", r)
}
st := All(k, now)[0]
if st.Tokens != 400 || !st.Start.Equal(w.start) || !st.Reset.Equal(w.reset) || st.ResetUnknown || st.Account != "codex/me@example.com" || st.AccountWindow != "5h" {
t.Fatalf("status: %+v", st)
}
Append(usage.Record{Time: now.Add(-30 * time.Minute), Provider: "p", Model: "m", Input: 700, Status: 200, CallerKeyID: k.ID})
r := refused(now)
if r == nil {
t.Fatal("not refused with 1100 of 1000 used in the account's window")
}
if !strings.Contains(r.Error(), "5h window of codex/me@example.com") || !strings.Contains(r.Error(), "resets at") || !r.ResetAt().Equal(w.reset) {
t.Errorf("refusal: %s", r.Error())
}
if got := r.RetryAfter(now); got < 3*3600-1 || got > 3*3600+1 {
t.Errorf("retry after %ds", got)
}
// the reset passed, the next window not read yet: still held, from
// the reset that passed, which is when the next can begin earliest
after := w.reset.Add(time.Minute)
Append(usage.Record{Time: w.reset.Add(30 * time.Second), Provider: "p", Model: "m", Input: 1000, Status: 200, CallerKeyID: k.ID})
w = win{w.reset, time.Time{}, false}
r = refused(after)
if r == nil {
t.Fatal("let through on a window not read")
}
if !r.ResetUnknown || !strings.Contains(r.Error(), "can't read") || r.RetryAfter(after) != 300 {
t.Errorf("unknown: %+v %s retry %d", r.Status, r.Error(), r.RetryAfter(after))
}
if st := All(k, after)[0]; !st.ResetUnknown || !st.Start.Equal(w.start) || st.Tokens != 1000 {
t.Errorf("unknown status: %+v", st)
}
// nothing read at all: counted from when the limit was set, every
// call of ten days, and still held
w = win{}
if r := refused(after); r == nil || !r.ResetUnknown {
t.Fatalf("nothing read: %v", r)
}
if st := All(k, after)[0]; !st.Start.Equal(set) || st.Tokens != 3000 {
t.Errorf("nothing read: %+v", st)
}
// the new window is read: begun at the reset, so the last call counts,
// the ones before don't; a new one, read a little later, begun after it
w = win{after.Add(-time.Minute), after.Add(5*time.Hour - time.Minute), true}
if st := All(k, after)[0]; st.ResetUnknown || st.Tokens != 1000 || !st.Reset.Equal(w.reset) {
t.Errorf("read again: %+v", st)
}
w = win{after.Add(-10 * time.Second), after.Add(5 * time.Hour), true}
if r := refused(after); r != nil {
t.Fatalf("held in a new window: %v", r)
}
if !slices.Contains(asked, "codex/me@example.com Weekly") || !slices.Contains(asked, "claude/me@example.com 5h") {
t.Errorf("windows asked: %v", asked)
}
}
+84 -25
View File
@@ -21,6 +21,16 @@
// size in tokens (4 bytes a token) plus the key's mean output per
// call this window. A request is let in while used + reserved is
// under the cap, so parallel requests overshoot by about one call.
// - A limit can follow one subscription account's window ("account",
// ljayic on X): it starts and resets when the account's 5 hours or
// week does, as the account's last reading says (provider
// .AccountWindow). While that isn't known (no reading, the read
// failing, the window over with no reading since), the reset is
// unknown and the window counts from the latest time known to be no
// later than its start (the reset that passed, else when the limit
// was set or reset): never fewer calls than the real window, so the
// key is never let through or reset on a guess. A key refused then
// is told to try again in five minutes (unknownRetry).
// - A key can have several limits, each in its own window (#2227: 5
// hours and a week, as a subscription's): a request is let in only
// while every one has something left, and its reservation is held
@@ -270,11 +280,42 @@ type Status struct {
CostLeft float64 `json:"costLeft"`
// Spent: the key is refused until Reset
Spent bool `json:"spent"`
// Account and AccountWindow are an "account" limit's window
// (access.Limit); ResetUnknown says its reset isn't known now, and
// Reset is zero.
Account string `json:"account,omitempty"`
AccountWindow string `json:"accountWindow,omitempty"`
ResetUnknown bool `json:"resetUnknown,omitempty"`
}
// unknownRetry is how long a client refused by a limit whose reset isn't
// known is told to wait: the accounts are read again meanwhile.
const unknownRetry = 5 * time.Minute
// resetsLater: a reset of a resets after b's; an unknown one (zero)
// after every known one.
func resetsLater(a, b time.Time) bool {
if a.IsZero() || b.IsZero() {
return a.IsZero() && !b.IsZero()
}
return a.After(b)
}
// windowsAt is each of ls's window at now. An account's window reads the
// account's last reading, so it is asked before state is held.
func windowsAt(ls []*access.Limit, now time.Time) (starts, resets []time.Time) {
starts = make([]time.Time, len(ls))
resets = make([]time.Time, len(ls))
for i, l := range ls {
starts[i], resets[i] = l.Window(now)
}
return starts, resets
}
func status(keyID string, l *access.Limit, s *sums, h *held, reset time.Time) Status {
st := Status{Period: l.Period, Days: l.Days, Hours: l.Hours, Start: s.start, Reset: reset, Calls: s.calls, Tokens: s.tokens(l), Cost: s.cost, Unpriced: s.unpriced,
TokenLimit: l.Tokens, CostLimit: l.Cost, CacheReads: l.CacheReads, Models: l.Models}
TokenLimit: l.Tokens, CostLimit: l.Cost, CacheReads: l.CacheReads, Models: l.Models,
Account: l.Account, AccountWindow: l.AccountWindow, ResetUnknown: reset.IsZero()}
if h != nil {
st.InFlight, st.Reserved, st.ReservedCost = h.n, h.tokens, h.cost
}
@@ -324,12 +365,14 @@ func AllOf(keys []access.Key, now time.Time) [][]Status {
}
out := make([][]Status, len(keys))
wants := make([][]*want, len(keys))
resets := make([][]time.Time, len(keys))
byKey := map[string][]*want{} // by the key a call is recorded under, or issued under
var all []*want
for i, k := range keys {
seen := map[window]*want{}
for _, l := range k.Limits() {
start, _ := l.Window(now)
start, reset := l.Window(now)
resets[i] = append(resets[i], reset)
w := window{slot(k.ID), start.Unix(), l.Scope()}
x := seen[w]
if x == nil {
@@ -438,8 +481,7 @@ func AllOf(keys []access.Key, now time.Time) [][]Status {
for i, k := range keys {
for j, l := range k.Limits() {
x := wants[i][j]
_, reset := l.Window(now)
out[i] = append(out[i], status(k.ID, l, x.total, state.held[x.w], reset))
out[i] = append(out[i], status(k.ID, l, x.total, state.held[x.w], resets[i][j]))
}
}
return out
@@ -476,7 +518,7 @@ func Binding(all []Status) *Status {
b = st
}
case st.Spent:
if st.Reset.After(b.Reset) {
if resetsLater(st.Reset, b.Reset) {
b = st
}
case st.share() > b.share():
@@ -527,17 +569,35 @@ func (r *Refusal) Error() string {
if r.Period == "total" {
return fmt.Sprintf("magpie gateway key %q has used %s%s of its total limit; it stays refused until the limit is reset or raised", r.Key, what, on)
}
if r.Period == "account" && r.Reset.IsZero() {
return fmt.Sprintf("magpie gateway key %q has used %s%s for this %s window of %s; it resets when that window does, which magpie can't read now",
r.Key, what, on, r.AccountWindow, r.Account)
}
if r.Period == "account" {
return fmt.Sprintf("magpie gateway key %q has used %s%s for this %s window of %s; it resets at %s",
r.Key, what, on, r.AccountWindow, r.Account, r.Reset.Format("2006-01-02 15:04 MST"))
}
return fmt.Sprintf("magpie gateway key %q has used %s%s for this %s; it resets at %s",
r.Key, what, on, (&access.Limit{Period: r.Period, Days: r.Days, Hours: r.Hours}).Per(), r.Reset.Format("2006-01-02 15:04 MST"))
}
// RetryAfter is how long until the window resets, in whole seconds.
// RetryAfter is how long until the window resets, in whole seconds;
// five minutes when that isn't known (unknownRetry).
func (r *Refusal) RetryAfter(now time.Time) int {
if r.Reset.IsZero() {
return int(unknownRetry / time.Second)
}
return max(int(r.Reset.Sub(now).Seconds()+0.999), 1)
}
// ResetAt is when the window resets.
func (r *Refusal) ResetAt() time.Time { return r.Reset }
// ResetAt is when the window resets; when that isn't known, when to ask
// again (unknownRetry from now).
func (r *Refusal) ResetAt() time.Time {
if r.Reset.IsZero() {
return time.Now().Add(unknownRetry)
}
return r.Reset
}
// Limiter is Reserve as the gateway's budget point asks it
// (gwbudget.Limiter); plugins/budget serves it.
@@ -583,9 +643,11 @@ func reserve(who access.Identity, body int64, model string, now time.Time) (rele
if who.KeyID == "" || len(who.Limits()) == 0 {
return func() {}, nil
}
all := who.Limits()
allStarts, allResets := windowsAt(all, now)
state.Lock()
defer state.Unlock()
ls, starts, resets, ss := windowsOf(who, now, func(l *access.Limit) bool { return !l.Scoped() || scopeHas(l, served) })
ls, starts, resets, ss := windowsOf(who.KeyID, all, allStarts, allResets, func(l *access.Limit) bool { return !l.Scoped() || scopeHas(l, served) })
if len(ls) == 0 {
return func() {}, nil
}
@@ -600,7 +662,7 @@ func reserve(who access.Identity, body int64, model string, now time.Time) (rele
ht, hc = h.tokens, h.cost
}
if (l.Tokens > 0 && s.tokens(l)+ht >= l.Tokens) || (l.Cost > 0 && s.cost+hc >= l.Cost) {
if refused == nil || resets[i].After(refused.Reset) {
if refused == nil || resetsLater(resets[i], refused.Reset) {
refused = &Refusal{Status: status(who.KeyID, l, s, h, resets[i]), Key: who.KeyName}
}
}
@@ -720,9 +782,11 @@ func spentOf(who access.Identity, now time.Time) []access.SpentScope {
if who.KeyID == "" || !slices.ContainsFunc(who.Limits(), (*access.Limit).Scoped) {
return nil
}
all := who.Limits()
allStarts, allResets := windowsAt(all, now)
state.Lock()
defer state.Unlock()
ls, starts, resets, ss := windowsOf(who, now, (*access.Limit).Scoped)
ls, starts, resets, ss := windowsOf(who.KeyID, all, allStarts, allResets, (*access.Limit).Scoped)
var out []access.SpentScope
for i, l := range ls {
s, h := ss[i], state.held[window{slot(who.KeyID), starts[i].Unix(), l.Scope()}]
@@ -733,25 +797,20 @@ func spentOf(who access.Identity, now time.Time) []access.SpentScope {
}
if (l.Tokens > 0 && s.tokens(l)+ht >= l.Tokens) || (l.Cost > 0 && s.cost+hc >= l.Cost) {
r := &Refusal{Status: status(who.KeyID, l, s, h, resets[i]), Key: who.KeyName}
out = append(out, access.SpentScope{Models: s.models, Reset: resets[i], Why: r.Error()})
out = append(out, access.SpentScope{Models: s.models, Reset: r.ResetAt(), Why: r.Error()})
}
}
return out
}
// windowsOf is who's limits that keep holds, each with its window's start
// and reset and its sums. The sums of every limit are asked for, the ones
// left out too: sumsFor lets go of a window no limit asked for counts in,
// and a request of one model would read another's limit's again from the
// ledger on the next. Called with state held.
func windowsOf(who access.Identity, now time.Time, keep func(*access.Limit) bool) (ls []*access.Limit, starts, resets []time.Time, ss []*sums) {
all := who.Limits()
allStarts := make([]time.Time, len(all))
allResets := make([]time.Time, len(all))
for i, l := range all {
allStarts[i], allResets[i] = l.Window(now)
}
allSums := sumsFor(who.KeyID, all, allStarts)
// windowsOf is the limits all of keyID's that keep holds, each with its
// window's start and reset (windowsAt) and its sums. The sums of every
// limit are asked for, the ones left out too: sumsFor lets go of a window
// no limit asked for counts in, and a request of one model would read
// another's limit's again from the ledger on the next. Called with state
// held.
func windowsOf(keyID string, all []*access.Limit, allStarts, allResets []time.Time, keep func(*access.Limit) bool) (ls []*access.Limit, starts, resets []time.Time, ss []*sums) {
allSums := sumsFor(keyID, all, allStarts)
for i, l := range all {
if keep(l) {
ls = append(ls, l)
+28
View File
@@ -0,0 +1,28 @@
package cli
import (
"errors"
"testing"
)
// `gateway-key limit <id> account --account … --window …` is a limit that
// follows that account's window (ljayic on X); one without either, or
// either on another period, is refused.
func TestParseAccountWindowLimit(t *testing.T) {
usage := errors.New("usage")
l, err := parseKeyLimit("account", []string{"--account", "codex/me@example.com", "--window=5h", "--tokens", "2m"}, usage)
if err != nil || l.Period != "account" || l.Account != "codex/me@example.com" || l.AccountWindow != "5h" || l.Tokens != 2000000 {
t.Fatalf("%+v %v", l, err)
}
for _, args := range [][]string{
{"--account", "codex/me@example.com", "--tokens", "2m"},
{"--window", "5h", "--tokens", "2m"},
} {
if l, err := parseKeyLimit("account", args, usage); err == nil {
t.Errorf("%v taken: %+v", args, l)
}
}
if l, err := parseKeyLimit("week", []string{"--window", "5h", "--tokens", "2m"}, usage); err == nil {
t.Errorf("--window on a week taken: %+v", l)
}
}
+45 -10
View File
@@ -119,7 +119,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
args = args[:2]
}
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> [--key <value> | --key -] | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|total|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]] | models <id> [all | <provider>/<model>|<provider>/*|re:<regexp> ...] | aliases <id> [none | <name>=<provider>/<model> ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | concurrency <id> [<n> | off] | tier <id> [follow | standard | fast | ultrafast] | redact <id> [follow | on | off] | mcp <id> [all | none | <server>|<server>/<tool> ...] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> [--key <value> | --key -] | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|total|<N>d|<N>h|account [--account <provider>/<account> --window <name>] [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]] | models <id> [all | <provider>/<model>|<provider>/*|re:<regexp> ...] | aliases <id> [none | <name>=<provider>/<model> ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | concurrency <id> [<n> | off] | tier <id> [follow | standard | fast | ultrafast] | redact <id> [follow | on | off] | mcp <id> [all | none | <server>|<server>/<tool> ...] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
}
switch action {
case "list", "add", "rotate", "remove":
@@ -195,7 +195,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
//
// magpie gateway-key limit <id> [list] what it has used of each limit
// magpie gateway-key limit <id> off no limit
// magpie gateway-key limit <id> day|week|month|total|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]
// magpie gateway-key limit <id> day|week|month|total|<N>d|<N>h|account [--account <provider>/<account> --window <name>] [--tokens N] [--cost USD] [--cache-reads]
// its only limit, or the one of several with that window
// magpie gateway-key limit <id> add <window> [--tokens N] [--cost USD] [--cache-reads] [--model openai/*]
// one more limit; a request passes only while every one has something left
@@ -207,7 +207,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
// one model or provider under one key, the key's other models served once
// it is spent.
func gatewayKeyLimit(out io.Writer, args []string) error {
usage := fmt.Errorf("usage: magpie gateway-key limit <id> [off | reset [<n>] | remove <n> | [add] day|week|month|total|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]]")
usage := fmt.Errorf("usage: magpie gateway-key limit <id> [off | reset [<n>] | remove <n> | [add] day|week|month|total|<N>d|<N>h|account [--account <provider>/<account> --window <name>] [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]]")
if len(args) == 0 {
return usage
}
@@ -293,7 +293,8 @@ func gatewayKeyLimit(out io.Writer, args []string) error {
if len(have) > 1 {
v, _ := lim.Valid()
n := slices.IndexFunc(have, func(l *access.Limit) bool {
return v != nil && l.Period == v.Period && l.Days == v.Days && l.Hours == v.Hours && l.Scope() == v.Scope()
return v != nil && l.Period == v.Period && l.Days == v.Days && l.Hours == v.Hours && l.Scope() == v.Scope() &&
strings.EqualFold(l.Account, v.Account) && strings.EqualFold(l.AccountWindow, v.AccountWindow)
})
if n < 0 {
return fmt.Errorf("%s has %d limits and none %s%s: add one with `magpie gateway-key limit %s add %s ...`, or take one off with `remove <n>`", keys[i].Name, len(have), perPhrase(v), onModels(v), id, args[1])
@@ -324,12 +325,16 @@ func gatewayKeyLimit(out io.Writer, args []string) error {
for n, st := range all {
if len(all) > 1 {
fmt.Fprintf(w, "\t\n")
fmt.Fprintf(w, "Limit %d\t%s, all must have something left\n", n+1, perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}))
fmt.Fprintf(w, "Limit %d\t%s, all must have something left\n", n+1, perPhrase(statusLimit(st)))
}
if len(st.Models) > 0 {
fmt.Fprintf(w, "Models\t%s: only their calls count, and only requests for them are refused once it is spent\n", strings.Join(st.Models, ", "))
}
fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", (&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}).Per(), st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04"))
ends := st.Reset.Format("2006-01-02 15:04")
if st.ResetUnknown {
ends = "when the account's window resets (not readable now; counted from the earliest it can have begun)"
}
fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", statusLimit(st).Per(), st.Start.Format("2006-01-02 15:04"), ends)
if st.TokenLimit > 0 {
counted := "input, output and cache writes"
if st.CacheReads {
@@ -353,6 +358,8 @@ func gatewayKeyLimit(out io.Writer, args []string) error {
until := st.Reset.Format("2006-01-02 15:04")
if st.Period == "total" {
until = "the limit is reset or raised"
} else if st.ResetUnknown {
until = "the account's window resets"
}
state = "spent: requests are refused until " + until
if len(st.Models) > 0 {
@@ -379,9 +386,17 @@ func perPhrase(l *access.Limit) string {
if l.Period == "total" {
return "in total"
}
if l.Period == "account" {
return "per " + l.Per()
}
return "per " + l.Period
}
// statusLimit is the window of the limit st is the status of.
func statusLimit(st budget.Status) *access.Limit {
return &access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours, Account: st.Account, AccountWindow: st.AccountWindow}
}
// onModels is " on <models>" for a limit of some models, "" for one of the
// whole key.
func onModels(l *access.Limit) string {
@@ -395,7 +410,7 @@ func onModels(l *access.Limit) string {
// --cost and --cache-reads.
func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, error) {
lim := &access.Limit{Period: window}
if window == "day" || window == "week" || window == "month" || window == "total" {
if window == "day" || window == "week" || window == "month" || window == "total" || window == "account" {
// a period by its name: month ends in an h, and is no count of hours
} else if n, ok := strings.CutSuffix(window, "d"); ok {
days, err := strconv.Atoi(n)
@@ -411,7 +426,7 @@ func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, er
}
lim = &access.Limit{Period: "hours", Hours: hours}
} else if !slices.Contains(access.Periods, lim.Period) || lim.Period == "days" || lim.Period == "hours" {
return nil, fmt.Errorf("a limit's period is day, week, month, total, <N>d (every N days) or <N>h (every N hours), not %q", lim.Period)
return nil, fmt.Errorf("a limit's period is day, week, month, total, <N>d (every N days), <N>h (every N hours) or account (an account's window), not %q", lim.Period)
}
for i := 0; i < len(rest); i++ {
flag, val, has := strings.Cut(rest[i], "=")
@@ -446,6 +461,19 @@ func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, er
}
case "--cache-reads":
lim.CacheReads = true
case "--account", "--window":
v, err := next()
if err != nil {
return nil, err
}
if lim.Period != "account" {
return nil, fmt.Errorf("%s is for an account limit: limit <id> account --account <provider>/<account> --window <name>", flag)
}
if flag == "--account" {
lim.Account = v
} else {
lim.AccountWindow = v
}
case "--model", "--models":
v, err := next()
if err != nil {
@@ -463,6 +491,9 @@ func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, er
if !lim.Limited() {
return nil, fmt.Errorf("say --tokens, --cost or both, or off for no limit")
}
if lim.Period == "account" && (lim.Account == "" || lim.AccountWindow == "") {
return nil, fmt.Errorf("an account limit names the account and its window: --account codex/me@example.com --window 5h")
}
return lim, nil
}
@@ -615,9 +646,13 @@ func limitWords(k access.Key, now time.Time) string {
if st.CostLimit > 0 {
parts = append(parts, fmt.Sprintf("$%.2f/$%.2f", st.Cost, st.CostLimit))
}
s := strings.Join(parts, " ") + " " + perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}) + onModels(&access.Limit{Models: st.Models})
s := strings.Join(parts, " ") + " " + perPhrase(statusLimit(st)) + onModels(&access.Limit{Models: st.Models})
if st.Spent {
s += " (spent until " + st.Reset.Format("01-02 15:04") + ")"
if st.ResetUnknown {
s += " (spent until the account's window resets)"
} else {
s += " (spent until " + st.Reset.Format("01-02 15:04") + ")"
}
}
each = append(each, s)
}
+1
View File
@@ -197,6 +197,7 @@ var cliForRoute = map[string]string{
"POST /api/davsync/{action}": "magpie webdav",
"GET /api/caller-keys": "magpie gateway-key list",
"POST /api/caller-keys/{action}": "magpie gateway-key",
"GET /api/caller-keys/account-windows": "magpie quota", // the windows `gateway-key limit <id> account` takes
"GET /api/account-groups": "magpie gateway-key groups",
"POST /api/account-groups/{action}": "magpie gateway-key groups",
"GET /api/groups": "magpie groups",
+1
View File
@@ -47,6 +47,7 @@ var adminRoutes = []adminRoute{
{pattern: "POST /signin/{id}/callback"},
{pattern: "GET /gateway-keys", to: "/caller-keys"},
{pattern: "GET /gateway-keys/models", to: "/caller-keys/models"},
{pattern: "GET /gateway-keys/account-windows", to: "/caller-keys/account-windows"},
{pattern: "GET /gateway-keys/mcp", to: "/caller-keys/mcp"},
{pattern: "POST /gateway-keys/{action}", to: "/caller-keys/{action}", actions: adminKeyActions},
{pattern: "GET /account-groups"},
+2
View File
@@ -3255,6 +3255,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
#gatewayKeys .klf .klf-period, #gatewayKeys .klf .klf-pick { width: 100%; max-width: none; height: 28px; justify-content: space-between; color: var(--fg); }
#gatewayKeys .klf.with-days { grid-template-columns: minmax(0, 1fr) minmax(0, 0.6fr) minmax(0, 1fr) minmax(0, 1fr); }
#gatewayKeys .klf-days[hidden] { display: none; }
#gatewayKeys .klf-acct { grid-column: span 2; }
#gatewayKeys .klf-acct[hidden] { display: none; }
#gatewayKeys .klf-models { grid-column: 1 / -1; }
#gatewayKeys .klf .klf-pick > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.editor .headers.aliases .pair .alias-pick { flex: 6; max-width: none; min-width: 0; height: 27px; justify-content: space-between; }
+44
View File
@@ -582,6 +582,17 @@ const I18N = {
"per week": "每周",
"per month": "每月",
"in total": "总额",
"An account's window": "账号的周期",
"{window} of {account}": "{account} 的 {window}",
"refused until the account's window resets": "账号周期重置前拒绝请求",
"resets with the account's window": "随账号周期重置",
"Counted from {start}; the account's window can't be read now, so when it resets isn't known": "自 {start} 起计;现在读不到账号的周期,不知道何时重置",
"Account window": "账号周期",
"Pick a window": "选择周期",
"Pick an account's window": "请选择一个账号的周期",
"Not read now": "现在读不到",
"No account's window can be read now": "现在读不到任何账号的周期",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.": "{name} 已用的 Token 和费用一起清零,本周期内此前的调用不再计入;周期仍随账号的周期重置。",
"refused until reset": "重置前一直拒绝",
"Counted from {start}": "自 {start} 起计",
"The tokens and cost {name} has used go back to 0 together, and counting starts again from now.": "{name} 已用的 Token 和费用一起归零,并从现在起重新计数。",
@@ -5895,6 +5906,17 @@ const I18N = {
"per week": "每週",
"per month": "每月",
"in total": "總額",
"An account's window": "帳號的週期",
"{window} of {account}": "{account} 的 {window}",
"refused until the account's window resets": "帳號週期重置前拒絕請求",
"resets with the account's window": "隨帳號週期重置",
"Counted from {start}; the account's window can't be read now, so when it resets isn't known": "自 {start} 起計;現在讀不到帳號的週期,不知道何時重置",
"Account window": "帳號週期",
"Pick a window": "選擇週期",
"Pick an account's window": "請選擇一個帳號的週期",
"Not read now": "現在讀不到",
"No account's window can be read now": "現在讀不到任何帳號的週期",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.": "{name} 已用的 Token 和費用一起歸零,本週期內此前的呼叫不再計入;週期仍隨帳號的週期重置。",
"refused until reset": "重置前一直拒絕",
"Counted from {start}": "自 {start} 起計",
"The tokens and cost {name} has used go back to 0 together, and counting starts again from now.": "{name} 已用的 Token 和費用一起歸零,並從現在起重新計數。",
@@ -11168,6 +11190,17 @@ const I18N = {
"per week": "1週間あたり",
"per month": "1か月あたり",
"in total": "合計",
"An account's window": "アカウントの期間",
"{window} of {account}": "{account} の {window}",
"refused until the account's window resets": "アカウントの期間がリセットされるまで拒否",
"resets with the account's window": "アカウントの期間とともにリセット",
"Counted from {start}; the account's window can't be read now, so when it resets isn't known": "{start} から集計。アカウントの期間を今は読み取れないため、リセット時刻は不明です",
"Account window": "アカウントの期間",
"Pick a window": "期間を選択",
"Pick an account's window": "アカウントの期間を選んでください",
"Not read now": "今は読み取れません",
"No account's window can be read now": "今読み取れるアカウントの期間はありません",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.": "{name} が使ったトークンと費用をまとめて 0 に戻します。この期間のこれまでの呼び出しは数えなくなり、リセットは引き続きアカウントの期間に合わせます。",
"refused until reset": "リセットまで拒否",
"Counted from {start}": "{start} から集計",
"The tokens and cost {name} has used go back to 0 together, and counting starts again from now.": "{name} の使用済みトークンと費用がまとめて 0 に戻り、今から数え直します。",
@@ -16459,6 +16492,17 @@ const I18N = {
"per week": "pro Woche",
"per month": "pro Monat",
"in total": "insgesamt",
"An account's window": "Zeitraum eines Kontos",
"{window} of {account}": "{window} von {account}",
"refused until the account's window resets": "abgelehnt, bis der Zeitraum des Kontos zurückgesetzt wird",
"resets with the account's window": "wird mit dem Zeitraum des Kontos zurückgesetzt",
"Counted from {start}; the account's window can't be read now, so when it resets isn't known": "Gezählt ab {start}; der Zeitraum des Kontos kann gerade nicht gelesen werden, daher ist unbekannt, wann er zurückgesetzt wird",
"Account window": "Zeitraum des Kontos",
"Pick a window": "Zeitraum wählen",
"Pick an account's window": "Wähle den Zeitraum eines Kontos",
"Not read now": "Gerade nicht gelesen",
"No account's window can be read now": "Gerade lässt sich kein Zeitraum eines Kontos lesen",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.": "Die Tokens und Kosten von {name} gehen zusammen auf 0 zurück. Bisherige Aufrufe in diesem Zeitraum zählen nicht mehr; zurückgesetzt wird weiterhin mit dem Zeitraum des Kontos.",
"refused until reset": "bis zum Reset abgelehnt",
"Counted from {start}": "Gezählt ab {start}",
"The tokens and cost {name} has used go back to 0 together, and counting starts again from now.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0 zurück, und die Zählung beginnt jetzt neu.",
+65 -15
View File
@@ -1064,16 +1064,22 @@ function gatewayRedactBadge(k) {
// "days" is every N days from when the limit is set or reset (#1509),
// "hours" every N hours (#2102), a subscription's 5-hour window's pace,
// "total" never resets by itself, only by Reset (@Cyrus_4433 on X)
const limitPeriods = ["day", "week", "month", "days", "hours", "total"];
const limitPer = { day: "per day", week: "per week", month: "per month", days: "Every N days", hours: "Every N hours", total: "in total" };
// "account" follows one subscription account's window, its 5 hours or its
// week, and resets when that does (ljayic on X); "total" never resets by
// itself, only by Reset (@Cyrus_4433 on X)
const limitPeriods = ["day", "week", "month", "days", "hours", "account", "total"];
const limitPer = { day: "per day", week: "per week", month: "per month", days: "Every N days", hours: "Every N hours", account: "An account's window", total: "in total" };
const cyclic = (period) => period === "days" || period === "hours";
// perWords is a limit's window as the badge says it: "per week", "every
// 10 days", "every 5 hours"
const perWords = (period, days, hours) => period === "days"
// 10 days", "every 5 hours", "5h of codex/Work"
const perWords = (period, days, hours, l) => period === "days"
? (days === 1 ? t("every 1 day") : t("every {n} days", { n: days }))
: period === "hours" ? (hours === 1 ? t("every 1 hour") : t("every {n} hours", { n: hours }))
: t(limitPer[period] || period);
: period === "account" ? acctWindowWords(l?.account, l?.accountWindow)
: t(limitPer[period] || period);
// acctWindowWords names an account's window: "5h of codex/Work"
const acctWindowWords = (account, window) => account && window
? t("{window} of {account}", { window, account: accountShown(account) }) : t(limitPer.account);
// limitDays reads a cycle's days: a whole number from 1 to 3650, else NaN
function limitDays(v) {
const s = String(v ?? "").trim();
@@ -1117,13 +1123,15 @@ function limitDraft(k, n) {
const taken = keyLimits(k).map((x) => x.period);
// a new one in a window the key has no limit in yet: a week beside 5 hours
const period = l.period || (n ? ["week", "hours", "day", "month"].find((p) => !taken.includes(p)) || "days" : "day");
return { id: k.id, n, period, days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : (n && period === "hours" ? "5" : ""), tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads, models: [...(l.models || [])] };
return { id: k.id, n, period, days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : (n && period === "hours" ? "5" : ""), tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads, models: [...(l.models || [])], account: l.account || "", accountWindow: l.accountWindow || "" };
}
// bindingUsed is the limit holding a key most: of those spent, the one
// that resets last, as it is refused until then; else the first
// that resets last, as it is refused until then (one whose reset isn't
// known now after every other); else the first
function bindingUsed(k) {
const all = keyUsed(k), spent = all.filter((u) => u.spent);
return spent.length ? spent.reduce((a, b) => (new Date(b.reset) > new Date(a.reset) ? b : a)) : all[0];
const later = (a, b) => a.resetUnknown || b.resetUnknown ? !!b.resetUnknown && !a.resetUnknown : new Date(b.reset) > new Date(a.reset);
return spent.length ? spent.reduce((a, b) => (later(a, b) ? b : a)) : all[0];
}
// gatewayLimitBadge opens a key's limit editor: "Limit" on hover when it
@@ -1138,7 +1146,7 @@ function gatewayLimitBadge(k) {
const parts = [];
if (u.tokenLimit) parts.push(fmtN(u.tokens) + " / " + fmtN(u.tokenLimit));
if (u.costLimit) parts.push(usd(u.cost) + " / " + usd(u.costLimit));
b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days, u.hours)
b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days, u.hours, u)
+ (u.models?.length ? " · " + limitModels(u.models) : "")
+ (more > 0 ? " · " + t(more === 1 ? "+1 limit" : "+{n} limits", { n: more }) : "");
}
@@ -1160,17 +1168,22 @@ function gatewayLimitBadge(k) {
function gatewayLimitLine(k, u) {
const line = el("div", "key-limit" + (u.spent ? " spent" : ""));
const parts = [];
if (keyUsed(k).length > 1) parts.push(perWords(u.period, u.days, u.hours));
if (keyUsed(k).length > 1) parts.push(perWords(u.period, u.days, u.hours, u));
if (u.models?.length) parts.push(limitModels(u.models));
if (u.tokenLimit) parts.push(t("{used} of {limit} tokens · {left} left", { used: fmtN(u.tokens), limit: fmtN(u.tokenLimit), left: fmtN(u.tokensLeft) }));
if (u.costLimit) parts.push(t("{used} of {limit} estimated · {left} left", { used: usd(u.cost), limit: usd(u.costLimit), left: usd(u.costLeft) }));
const at = new Date(u.reset);
if (u.period !== "total") parts.push(t(u.spent ? "refused until {when}" : "resets {when}", { when: resetClock(at) }));
// an account's window whose reset can't be read now: the key is held
// to what it spent since the earliest the window can have begun
if (u.resetUnknown) parts.push(t(u.spent ? "refused until the account's window resets" : "resets with the account's window"));
else if (u.period !== "total") parts.push(t(u.spent ? "refused until {when}" : "resets {when}", { when: resetClock(at) }));
else if (u.spent) parts.push(t("refused until reset"));
if (u.inFlight) parts.push(t(u.inFlight === 1 ? "1 in flight" : "{n} in flight", { n: u.inFlight }));
line.textContent = parts.join(" · ");
line.title = (u.models?.length ? u.models.join(", ") + "\n" : "")
+ (u.period === "total"
+ (u.resetUnknown
? t("Counted from {start}; the account's window can't be read now, so when it resets isn't known", { start: new Date(u.start).toLocaleString(intlLang()) })
: u.period === "total"
? t("Counted from {start}", { start: new Date(u.start).toLocaleString(intlLang()) })
: t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(intlLang()), when: at.toLocaleString(intlLang()) }))
+ (u.unpriced ? "\n" + t("{n} calls without a known price aren't in the cost", { n: u.unpriced }) : "");
@@ -1188,6 +1201,7 @@ function gatewayLimitEditor(k) {
|| limitCost(d.cost) !== (kept.cost || 0) || d.cacheReads !== !!kept.cacheReads
|| (d.period === "days" && limitDays(d.days) !== kept.days)
|| (d.period === "hours" && limitHours(d.hours) !== kept.hours)
|| (d.period === "account" && (d.account !== (kept.account || "") || d.accountWindow !== (kept.accountWindow || "")))
|| !sameModels(d.models, kept.models);
const fields = el("div", "klf");
// the app's own menu, not a native select
@@ -1202,6 +1216,7 @@ function gatewayLimitEditor(k) {
fields.classList.toggle("with-days", cyclic(d.period));
dl.hidden = d.period !== "days";
hl.hidden = d.period !== "hours";
al.hidden = d.period !== "account";
};
// the days of a cycle, shown for "every N days"
const days = input(d.days, "10");
@@ -1215,6 +1230,19 @@ function gatewayLimitEditor(k) {
hours.inputMode = "numeric";
const hl = el("label", "klf-field klf-days klf-hours");
hl.append(el("span", "klf-name", t("Hours")), hours);
// the account's window an "account" limit follows (ljayic on X)
const acct = el("button", "sess-pick klf-pick klf-acct-pick");
acct.type = "button";
acct.setAttribute("aria-label", t("Account window"));
acct.setAttribute("aria-haspopup", "menu");
acct.setAttribute("aria-expanded", "false");
const paintAcct = () => {
acct.title = d.account ? d.account + " · " + d.accountWindow : "";
acct.replaceChildren(el("span", "", d.account ? acctWindowWords(d.account, d.accountWindow) : t("Pick a window")), svg(CHEV, 11, 1.6));
};
paintAcct();
const al = el("label", "klf-field klf-acct");
al.append(el("span", "klf-name", t("Account window")), acct);
paintPeriod();
const tokens = input(d.tokens, t("No token cap"));
tokens.setAttribute("aria-label", t("Token limit"));
@@ -1242,7 +1270,7 @@ function gatewayLimitEditor(k) {
paintModels();
const ml = el("label", "klf-field klf-models");
ml.append(el("span", "klf-name", t("Models")), models);
fields.append(pl, dl, hl, tl, cl, ml);
fields.append(pl, dl, hl, al, tl, cl, ml);
// a key's limits (#2227), each a tab, when it has more than one or one
// is being added: the editor is of one at a time
let which = null;
@@ -1250,7 +1278,7 @@ function gatewayLimitEditor(k) {
which = el("div", "klf-which");
which.setAttribute("role", "tablist");
which.setAttribute("aria-label", t("This key's limits"));
const tabs = limits.map((l, i) => ({ i, name: perWords(l.period, l.days, l.hours) + (l.models?.length ? " · " + limitModels(l.models) : "") }));
const tabs = limits.map((l, i) => ({ i, name: perWords(l.period, l.days, l.hours, l) + (l.models?.length ? " · " + limitModels(l.models) : "") }));
if (n >= limits.length) tabs.push({ i: n, name: t("New limit") });
for (const x of tabs) {
const tab = el("button", "klf-tab" + (x.i === n ? " on" : ""), x.name);
@@ -1279,6 +1307,7 @@ function gatewayLimitEditor(k) {
const update = () => {
const bad = d.period === "days" && Number.isNaN(limitDays(d.days)) ? t("Days is a whole number from 1 to 3650")
: d.period === "hours" && Number.isNaN(limitHours(d.hours)) ? t("Hours is a whole number from 1 to 8760")
: d.period === "account" && !d.account ? t("Pick an account's window")
: Number.isNaN(limitTokens(d.tokens)) ? t("Tokens is a count, like 2000000 or 2M")
: Number.isNaN(limitCost(d.cost)) ? t("The cost is US dollars, like 5 or 2.50") : "";
err.textContent = bad;
@@ -1299,6 +1328,25 @@ function gatewayLimitEditor(k) {
if (v === "hours") hours.focus({ preventScroll: true });
}, "Limit window", "sess-menu");
};
acct.onclick = async (e) => {
e.preventDefault();
e.stopPropagation();
if (acct.classList.contains("open")) return closeProtoMenu();
let list = [];
try { ({ windows: list } = await api("caller-keys/account-windows")); } catch (err) { status(t(err.message), "err"); return; }
if (!acct.isConnected || gatewayLimit !== d) return;
const key = (a, w) => a + "\n" + w;
const opts = (list || []).map((w) => ({ v: key(w.account, w.window), name: acctWindowWords(w.account, w.window), note: t("resets {when}", { when: resetClock(new Date(w.reset)) }), literalName: true }));
if (d.account && !opts.some((o) => o.v === key(d.account, d.accountWindow))) {
opts.push({ v: key(d.account, d.accountWindow), name: acctWindowWords(d.account, d.accountWindow), note: "Not read now", literalName: true });
}
if (!opts.length) { status(t("No account's window can be read now"), "err"); return; }
openProtoMenu(acct, opts, d.account ? key(d.account, d.accountWindow) : "", (v) => {
[d.account, d.accountWindow] = v.split("\n");
paintAcct();
update();
}, "Account window", "sess-menu");
};
models.onclick = async (e) => {
e.preventDefault();
e.stopPropagation();
@@ -1346,6 +1394,7 @@ function gatewayLimitEditor(k) {
if (limit && d.models.length) limit.models = d.models;
if (limit && d.period === "days") limit.days = limitDays(d.days);
if (limit && d.period === "hours") limit.hours = limitHours(d.hours);
if (limit && d.period === "account") Object.assign(limit, { account: d.account, accountWindow: d.accountWindow });
// which one only when there are several: one is the key's only limit
const out = await gatewayKeyAction("limit-key", which ? { key: k.id, limit, index: n } : { key: k.id, limit });
if (!out) { update(); return; }
@@ -1416,6 +1465,7 @@ function askResetLimit(k, n) {
? t("The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.", { name: k.name, n: u.days })
: u.period === "hours" ? t("The tokens and cost {name} has used go back to 0 together, and a new {n}-hour cycle starts now.", { name: k.name, n: u.hours })
: u.period === "total" ? t("The tokens and cost {name} has used go back to 0 together, and counting starts again from now.", { name: k.name })
: u.resetUnknown ? t("The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.", { name: k.name })
: t("The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.", { name: k.name, when: resetClock(new Date(u.reset)) })));
const bar = el("div", "bar");
const cancel = el("button", "text", t("Cancel"));
@@ -0,0 +1,22 @@
package gui
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// The limit editor's list of the accounts' windows a key can follow
// (ljayic on X) is a list even with no account read: the page reads
// "windows" and says none can be read now, never fails on null.
func TestCallerKeyAccountWindowsRoute(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
callerKeyRoutes(mux)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/caller-keys/account-windows", nil))
if w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"windows":[]}` {
t.Fatalf("%d %s", w.Code, w.Body)
}
}
+15
View File
@@ -2,6 +2,7 @@ package gui
import (
"cmp"
"context"
"encoding/json"
"net/http"
"slices"
@@ -76,6 +77,20 @@ func callerKeyRoutes(mux *http.ServeMux) {
}
writeJSON(w, map[string]any{"keys": withLimits(keys), "accountNames": provider.AccountNames(), "accountGroups": accountGroupsJSON()})
})
// the subscription accounts' windows a key's limit can follow
// (ljayic on X): each one's 5 hours, week or month, from the cards as
// last read; an account not read yet is read meanwhile, waited for a
// few seconds at most
mux.HandleFunc("GET /api/caller-keys/account-windows", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
defer cancel()
out := provider.KeyWindows(ctx, time.Now())
if out == nil {
out = []provider.KeyWindow{}
}
writeJSON(w, map[string]any{"windows": out})
})
// the models a key may be held to (#882), and the accounts and keys
// (#905): the routing groups, then each provider's models, then its
// accounts and keys; a group the key names is its with every member
+7 -1
View File
@@ -159,6 +159,9 @@ function fixture(lang, theme, events, options = {}) {
{ name: "magpie-browser", title: "Magpie Browser", tools: ["browser"], own: true },
{ name: "github", tools: ["create_issue", "search_code"] },
] });
// the subscription accounts' windows a key's limit can follow (ljayic
// on X): options.accountWindows is the test's own list
if (url.pathname === "/api/caller-keys/account-windows") return json({ windows: options.accountWindows || [] });
if (url.pathname.startsWith("/api/caller-keys/")) {
const action = url.pathname.split("/").at(-1), body = req.postDataJSON();
events.push({ action, body });
@@ -189,7 +192,10 @@ function fixture(lang, theme, events, options = {}) {
// what a key has used is the fixture's; a new limit starts unused
const usedOf = (l) => {
const span = l.period === "hours" ? l.hours * 36e5 : (l.days || 1) * 864e5;
return { period: l.period, days: l.days, hours: l.hours, start: new Date().toISOString(), reset: new Date(Date.now() + span).toISOString(),
// an account's window resets when the window listed for it does
const w = l.period === "account" && (options.accountWindows || []).find((w) => w.account === l.account && w.window === l.accountWindow);
return { period: l.period, days: l.days, hours: l.hours, start: w ? w.start : new Date().toISOString(), reset: w ? w.reset : new Date(Date.now() + span).toISOString(),
...(l.period === "account" ? { account: l.account, accountWindow: l.accountWindow } : {}),
calls: 0, tokens: 0, cost: 0, tokenLimit: l.tokens, costLimit: l.cost, tokensLeft: l.tokens, costLeft: l.cost, spent: false,
...(l.models ? { models: l.models } : {}) };
};
@@ -0,0 +1,128 @@
// A gateway key's limit that follows a subscription account's own window
// (ljayic on X): the window menu offers "An account's window", a second
// picker lists the accounts' windows as last read, Save sends the account
// and window, and a limit whose window can't be read now says it resets
// with the account's, never a made-up time. In every language, both
// engines, and at a narrow width, with no native select.
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const src = fs.readFileSync(path.resolve(__dirname, "../assets/i18n.js"), "utf8");
const I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
const hour = 36e5;
const accountWindows = () => [
{ account: "codex/me@example.com", window: "5h", provider: "Codex", user: "me@example.com",
start: new Date(Date.now() - 2 * hour).toISOString(), reset: new Date(Date.now() + 3 * hour).toISOString() },
{ account: "codex/me@example.com", window: "Weekly", provider: "Codex", user: "me@example.com",
start: new Date(Date.now() - 48 * hour).toISOString(), reset: new Date(Date.now() + 120 * hour).toISOString() },
];
// Laptop's limit follows Claude's 5 hours, which can't be read now: spent,
// and held until that window resets
const limits = () => ({
laptop: {
limit: { period: "account", account: "claude/me@example.com", accountWindow: "5h", tokens: 1000 },
used: { period: "account", account: "claude/me@example.com", accountWindow: "5h", resetUnknown: true,
start: new Date(Date.now() - 4 * hour).toISOString(), reset: "0001-01-01T00:00:00Z", calls: 9,
tokens: 1200, cost: 0, tokenLimit: 1000, tokensLeft: 0, spent: true },
},
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a key's limit follows an account's window`, async (t) => {
const tr = (k, vars = {}) => {
const s = lang === "en" ? k : I18N[lang][k];
assert.equal(typeof s, "string", `${lang} has ${k}`);
return s.replace(/\{(\w+)\}/g, (_, v) => String(vars[v]));
};
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 1000, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true, limits: limits(), accountWindows: accountWindows() }));
await page.goto("http://magpie.test/?view=gateway");
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
const sent = (action) => events.filter((e) => e.action === action);
const per = tr("An account's window");
if (lang === "zh") assert.equal(per, "账号的周期");
// the row: the account's window, and refused until it resets, no time
const claude5h = tr("{window} of {account}", { window: "5h", account: "claude/me@example.com" });
assert.match((await row("laptop").locator(".amodels.limit").textContent()).trim(), new RegExp(`· ${claude5h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`));
const line = row("laptop").locator(".key-limit").first();
assert((await line.textContent()).includes(tr("refused until the account's window resets")), await line.textContent());
assert.doesNotMatch(await line.textContent(), /0001|1970/);
const tail = tr("Counted from {start}; the account's window can't be read now, so when it resets isn't known", { start: "\u0000" }).split("\u0000")[1];
assert((await line.getAttribute("title")).endsWith(tail), await line.getAttribute("title"));
// a new limit: the menu offers the account's window before "in total"
await row("work").getByRole("button", { name: tr("Set a limit for this key"), exact: true }).click();
const wed = row("work").locator(".key-limit-ed");
await wed.waitFor();
await wed.getByRole("textbox", { name: tr("Estimated cost limit, US$"), exact: true }).fill("5");
const acct = wed.getByRole("button", { name: tr("Account window"), exact: true });
assert.equal(await acct.isVisible(), false, "the account picker shows for another window");
await wed.getByRole("button", { name: tr("Limit window"), exact: true }).click();
const items = page.locator(".proto-menu .pm-item");
const names = (await items.allTextContents()).map((s) => s.trim());
assert.deepEqual(names.slice(-2), [per, tr("in total")]);
await items.nth(names.length - 2).click();
assert.equal(await wed.getByRole("button", { name: tr("Limit window"), exact: true }).getAttribute("data-value"), "account");
await acct.waitFor();
// none picked yet: said, and nothing to save
const save = wed.getByRole("button", { name: tr("Save"), exact: true });
assert.equal(await save.isDisabled(), true);
assert((await wed.textContent()).includes(tr("Pick an account's window")));
// the accounts' windows as read, with when each resets
await acct.click();
const picks = page.locator(".proto-menu .pm-item");
await picks.first().waitFor();
assert.equal(await picks.count(), 2);
const weekly = tr("{window} of {account}", { window: "Weekly", account: "codex/me@example.com" });
assert.equal((await picks.nth(1).locator(".pm-name").textContent()).trim(), weekly);
await picks.nth(1).click();
assert.equal((await acct.textContent()).trim(), weekly);
assert.equal(await wed.locator("select").count(), 0, "no native select");
// narrow: the editor fits
await page.setViewportSize({ width: 500, height: 740 });
await page.waitForTimeout(100);
assert.equal(await wed.evaluate((e) => e.scrollWidth > e.clientWidth || e.getBoundingClientRect().right > window.innerWidth), false, "the editor overflows at 500px");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, "the page overflows at 500px");
await page.setViewportSize({ width: 1000, height: 700 });
await save.click();
await wed.waitFor({ state: "detached" });
assert.deepEqual(sent("limit-key").map((e) => e.body), [{ key: "work", limit: { period: "account", tokens: 0, cost: 5, cacheReads: false, account: "codex/me@example.com", accountWindow: "Weekly" } }]);
assert.match(await row("work").locator(".amodels.limit").textContent(), new RegExp(`\\$5\\.00 · ${weekly.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
// the window kept on Laptop isn't read now: it stays, said so
await row("laptop").getByRole("button", { name: tr("Change this key's limit"), exact: true }).click();
const ed = row("laptop").locator(".key-limit-ed");
await ed.waitFor();
const lacct = ed.getByRole("button", { name: tr("Account window"), exact: true });
assert.equal((await lacct.textContent()).trim(), claude5h);
await lacct.click();
await page.locator(".proto-menu .pm-item").first().waitFor();
assert.equal(await page.locator(".proto-menu .pm-item").count(), 3);
assert.equal((await page.locator(".proto-menu .pm-item").last().locator(".pm-note").textContent()).trim(), tr("Not read now"));
await page.keyboard.press("Escape");
// Reset usage says it still resets when the account's window does
await ed.getByRole("button", { name: tr("Reset usage"), exact: true }).click();
const modal = page.locator("#modal");
await modal.getByText(tr("Reset {name}'s usage?", { name: "Laptop" })).waitFor();
assert((await modal.textContent()).includes(tr("The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets when the account's window does.", { name: "Laptop" })));
await modal.getByRole("button", { name: tr("Reset usage"), exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(sent("reset-limit-key").map((e) => e.body), [{ key: "laptop" }]);
assert.deepEqual(errors, []);
});
}
}
+170
View File
@@ -0,0 +1,170 @@
package provider
// A gateway key's limit can follow one subscription account's own window
// (ljayic on X): its 5 hours, its week or its month, starting and ending
// when the vendor says that account's does. Here is where such a window
// is found: in the account's last good reading (quotas.json, keepLast),
// never by asking the vendor on the request's path.
import (
"context"
"strings"
"sync/atomic"
"time"
)
// AccountWindow is the window named name of account ("<provider>/<user>",
// as a key's accounts are written) as the account's last good reading
// tells it: when it began and when it resets. known is false when there
// is no such reading, it has no such window, the window has no reset
// clock or no length, or its reset has passed with no reading since.
//
// When it isn't known, start is the latest time known to be no later than
// the window's start: the reset that passed (a window never begins before
// the last one ended), or zero when nothing is. A limit counting from it
// counts every call of the window it follows, and maybe more, never less.
//
// It asks no vendor itself: it is on every keyed request's path. When the
// window isn't known, the accounts are read again in the background, at
// most once a minute, as the Usage page would (and only when allowances
// are read without being asked, settings.QuotaReads).
func AccountWindow(account, name string, now time.Time) (start, reset time.Time, known bool) {
return accountWindowVia(account, name, now)
}
var accountWindowVia = accountWindow
// AccountWindowVia has AccountWindow answer with f until restore is
// called: a test's accounts and windows, with no reading and no vendor.
func AccountWindowVia(f func(account, name string, now time.Time) (start, reset time.Time, known bool)) (restore func()) {
was := accountWindowVia
accountWindowVia = f
return func() { accountWindowVia = was }
}
func accountWindow(account, name string, now time.Time) (start, reset time.Time, known bool) {
pid, user, ok := strings.Cut(account, "/")
if !ok || pid == "" || user == "" || strings.TrimSpace(name) == "" {
return time.Time{}, time.Time{}, false
}
defer func() {
if !known {
readAccountWindows(now)
}
}()
c := &lastQuotas
c.Lock()
c.load()
e, had := c.m[strings.ToLower(pid)+"/"+strings.ToLower(user)]
c.Unlock()
if !had {
return time.Time{}, time.Time{}, false
}
for i, w := range e.Q.Windows {
if !sameWindowName(w, name) {
continue
}
if i < len(e.Spans) {
w.Span = e.Spans[i].Span
}
s, end, ok := w.Bounds(e.At)
if !ok {
if end := resetOf(w, e.At); !end.IsZero() && !end.After(now) {
return end, time.Time{}, false
}
return time.Time{}, time.Time{}, false
}
if !end.After(now) {
// over, and the next one not read yet
return end, time.Time{}, false
}
return s, end, true
}
return time.Time{}, time.Time{}, false
}
// resetOf is when w, read at readAt, resets; zero when not told.
func resetOf(w QuotaWindow, readAt time.Time) time.Time {
switch {
case w.ResetsAt != nil:
return *w.ResetsAt
case w.ResetSecs > 0:
return readAt.Add(time.Duration(w.ResetSecs) * time.Second)
}
return time.Time{}
}
// sameWindowName is whether w is the window a limit names: by its own
// name or, for a pool's, the name its line is kept under, in any case.
func sameWindowName(w QuotaWindow, name string) bool {
id := WindowCapID(name)
return WindowCapID(w.Name) == id || WindowCapID(w.LineName()) == id
}
// KeyWindow is a subscription account's window a gateway key's limit can
// follow, as the limit editor lists it.
type KeyWindow struct {
Account string `json:"account"` // "<provider>/<user>"
Window string `json:"window"` // the window's name, as the account's card says it
Provider string `json:"provider"` // the card's name: "Codex", "Claude"
User string `json:"user"`
Alias string `json:"alias,omitempty"`
Start time.Time `json:"start"`
Reset time.Time `json:"reset"`
}
// KeyWindows are the windows of every subscription account a key's limit
// can follow: each that runs out and starts again on a clock the vendor
// tells, from the accounts' cards as last read. One with no reset clock
// can't place a window, nor can money set aside, a text row or another
// magpie's card.
func KeyWindows(ctx context.Context, now time.Time) []KeyWindow {
var out []KeyWindow
names := AccountNames()
for _, q := range SubscriptionUsage(ctx) {
if q.User == "" || q.From != "" || q.GatewayKey != nil {
continue
}
account := q.Provider + "/" + q.User
for _, w := range q.Windows {
if w.Text || w.Unlimited || w.Lane != "" || w.Aside || w.Balance != nil {
continue
}
name := w.LineName()
s, end, ok := accountWindow(account, name, now)
if !ok {
continue
}
kw := KeyWindow{Account: account, Window: name, Provider: q.Name, User: q.User, Start: s, Reset: end}
if n := names[strings.ToLower(account)]; n != "" {
kw.Alias = n
}
out = append(out, kw)
}
}
return out
}
// accountWindowsAsked is when readAccountWindows last began a read,
// UnixNano.
var accountWindowsAsked atomic.Int64
// readAccountWindows reads the accounts' allowances again in the
// background, at most once a minute, without waiting for it.
var readAccountWindows = func(now time.Time) {
last := accountWindowsAsked.Load()
if now.UnixNano()-last < int64(time.Minute) && now.UnixNano() >= last {
return
}
if accountWindowsAsked.CompareAndSwap(last, now.UnixNano()) {
go readAccounts() // never under the caller's locks
}
}
// readAccounts begins a read of every account's allowances and waits
// for nothing.
var readAccounts = func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
SubscriptionUsage(ctx)
}
+88
View File
@@ -0,0 +1,88 @@
package provider
import (
"sync/atomic"
"testing"
"time"
)
// A key's limit that follows an account's window (ljayic on X) finds it
// in the account's last good reading, read again from disk after a
// restart: when it began and when it resets. Past its reset, or with no
// reading, it is unknown, never a window guessed, and the accounts are
// asked to be read again without waiting.
func TestAccountWindowFromLastReading(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
restart := func() {
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
}
restart()
defer restart()
asked := 0
was := readAccountWindows
readAccountWindows = func(time.Time) { asked++ }
defer func() { readAccountWindows = was }()
now := time.Now().Round(time.Second)
reset := now.Add(2 * time.Hour)
week := now.Add(3 * 24 * time.Hour)
keepLast(SubscriptionQuota{Provider: "codex", Name: "Codex", User: "Me@example.com", Windows: []QuotaWindow{
{Name: "5h", Used: 40, ResetsAt: &reset, Span: 5 * time.Hour},
{Name: "Weekly", Used: 10, ResetSecs: int64(week.Sub(now) / time.Second)},
{Name: "Credits", Display: "12", Text: true},
}}, "")
restart() // from disk, as after a restart: the span isn't in the window's json
start, end, known := AccountWindow("codex/me@example.com", "5H", now)
if !known || !end.Equal(reset) || !start.Equal(reset.Add(-5*time.Hour)) {
t.Fatalf("5h: %v – %v known %v", start, end, known)
}
start, end, known = AccountWindow("codex/me@example.com", "weekly", now)
if !known || end.Sub(week).Abs() > 2*time.Second || end.Sub(start) != 7*24*time.Hour {
t.Fatalf("weekly: %v – %v known %v", start, end, known)
}
if asked != 0 {
t.Fatalf("read again with every window known: %d", asked)
}
// past the reset with no reading since: unknown, from the reset that
// passed, which no later window begins before
start, end, known = AccountWindow("codex/me@example.com", "5h", reset.Add(time.Minute))
if known || !end.IsZero() || !start.Equal(reset) {
t.Fatalf("over: %v – %v known %v", start, end, known)
}
// a window with no clock, an account with no reading, a window it hasn't
for _, c := range [][2]string{{"codex/me@example.com", "Credits"}, {"codex/other@example.com", "5h"}, {"codex/me@example.com", "Monthly"}, {"codex", "5h"}} {
if start, end, known := AccountWindow(c[0], c[1], now); known || !start.IsZero() || !end.IsZero() {
t.Fatalf("%v: %v – %v known %v", c, start, end, known)
}
}
if asked == 0 {
t.Fatal("an unknown window wasn't read again")
}
}
// readAccountWindows reads the accounts again at most once a minute,
// however many requests find a window unknown.
func TestReadAccountWindowsOnceAMinute(t *testing.T) {
var reads atomic.Int32
was := readAccounts
readAccounts = func() { reads.Add(1) }
defer func() { readAccounts = was }()
accountWindowsAsked.Store(0)
now := time.Now()
for range 5 {
readAccountWindows(now)
}
readAccountWindows(now.Add(30 * time.Second))
readAccountWindows(now.Add(61 * time.Second))
deadline := time.Now().Add(10 * time.Second)
for reads.Load() < 2 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if n := reads.Load(); n != 2 {
t.Fatalf("%d reads, want 2", n)
}
}
+7 -3
View File
@@ -41,7 +41,9 @@ type GatewayKeyLimit struct {
// Limited is false for a key the remote holds to no limit.
Limited bool `json:"limited"`
// Period is "day", "week", "month", "days" (a cycle of Days days) or
// "hours" (of Hours hours) or "total" (until reset by hand).
// "hours" (of Hours hours), "total" (until reset by hand) or "account"
// (one subscription account's window there; Reset zero while the
// remote can't read it).
Period string `json:"period,omitempty"`
Days int `json:"days,omitempty"`
Hours int `json:"hours,omitempty"`
@@ -202,8 +204,10 @@ func keyLimitCard(a *remoteKeyAnswer) (*GatewayKeyLimit, []QuotaWindow) {
continue
}
resets := &x.Reset
if x.Period == "total" {
resets = nil // it never ends by itself
if x.Period == "total" || x.Reset.IsZero() {
// it never ends by itself, or follows an account's window
// whose reset the remote can't read now
resets = nil
}
if x.TokenLimit > 0 {
ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", x.Period), Used: share(float64(x.Tokens), float64(x.TokenLimit)), ResetsAt: resets,