diff --git a/docs/reference.md b/docs/reference.md index 674b7dca9..8b44a5faf 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -669,6 +669,7 @@ magpie gateway-key remove # revokes remote access magpie gateway-key limit week --tokens 2m --cost 5 # its own limit magpie gateway-key limit list # each limit, used, left and reset magpie gateway-key limit 10d --tokens 5m # every 10 days, from now +magpie gateway-key limit total --cost 300 # $300 in total, until reset magpie gateway-key limit 5h --tokens 200k # every 5 hours, from now magpie gateway-key limit add week --cost 20 # one more limit; all must pass magpie gateway-key limit add month --cost 20 --model openai/* # a limit of only OpenAI's models @@ -692,7 +693,10 @@ Each gateway key can have its own **limit**: a token total, an estimated cost in US$, or both, per day, week or month (calendar windows in local time: from midnight, from Monday, from the 1st), every N days (#1509; 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). An N-day or N-hour cycle starts when the +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 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 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 diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3cd98dc9e..77c0248a9 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -808,7 +808,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`). 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). 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 diff --git a/internal/access/limit.go b/internal/access/limit.go index ce6cef56c..292554b76 100644 --- a/internal/access/limit.go +++ b/internal/access/limit.go @@ -125,7 +125,10 @@ func (l *Limit) sameLimit(o *Limit) bool { } // Periods are the windows a limit can be set for. -var Periods = []string{"day", "week", "month", "days", "hours"} +// +// "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"} // MaxDays is the longest "days" cycle, ten years. const MaxDays = 3650 @@ -165,7 +168,7 @@ func (l *Limit) Valid() (*Limit, error) { v.Period = "day" } switch v.Period { - case "day", "week", "month": + case "day", "week", "month", "total": v.Days, v.Hours = 0, 0 case "days": v.Hours = 0 @@ -178,7 +181,7 @@ 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, every N days or every N hours") + return nil, errors.New("A limit's period is day, week, month, total, every N days or every N hours") } v.Cost = math.Round(v.Cost*1e4) / 1e4 ms, err := CleanModels(v.Models) @@ -198,7 +201,7 @@ func (l *Limit) Valid() (*Limit, error) { } // Per is the window as a sentence ends it: "day", "week", "month", -// "10-day cycle" or "5-hour cycle". +// "total", "10-day cycle" or "5-hour cycle". func (l *Limit) Per() string { switch l.Period { case "days": @@ -218,9 +221,9 @@ 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 none for a calendar period. +// and "hours" and for "total", and none for a calendar period. func sinceOf(prev, next *Limit, now time.Time) time.Time { - cyclic := next.cycle() > 0 + 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()) { return prev.Since } @@ -241,6 +244,16 @@ 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 == "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 + // names is a hundred years off + start = l.Since + if start.Before(epoch) { + start = epoch + } + return start.In(loc), start.AddDate(100, 0, 0).In(loc) + } if n := l.cycle(); n > 0 { anchor := l.Since if anchor.Before(epoch) { diff --git a/internal/access/limit_test.go b/internal/access/limit_test.go index 7987997fe..f33eda81f 100644 --- a/internal/access/limit_test.go +++ b/internal/access/limit_test.go @@ -460,3 +460,42 @@ func TestSeveralLimits(t *testing.T) { t.Fatalf("authenticated without its second limit: %+v", who.More) } } + +// A "total" limit (@Cyrus_4433 on X) is a kept period: it starts when set +// or reset, ends a century off, and an old file without it reads the same. +func TestLimitTotal(t *testing.T) { + since := time.Date(2026, 3, 4, 5, 6, 0, 0, time.UTC) + l := &Limit{Period: "total", Cost: 300, Since: since} + for _, now := range []time.Time{since, since.AddDate(0, 7, 0), since.AddDate(40, 0, 0)} { + start, reset := l.Window(now) + if !start.Equal(since) || !reset.After(now.AddDate(50, 0, 0)) { + t.Errorf("at %s: %s – %s", now, start, reset) + } + } + if start, _ := (&Limit{Period: "total", Cost: 1}).Window(since); !start.Equal(epoch) { + t.Errorf("no Since starts at %s", start) + } + v, err := (&Limit{Period: "total", Days: 3, Hours: 4, Cost: 300}).Valid() + if err != nil || v.Period != "total" || v.Days != 0 || v.Hours != 0 || v.Per() != "total" { + t.Fatalf("%+v %v", v, err) + } + if v, _ := (&Limit{Period: "month", Cost: 5}).Valid(); v.Period != "month" { + t.Errorf("month: %+v", v) + } + // setting it starts it, a new cap keeps it, a period change starts anew + now := time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC) + if got := sinceOf(nil, v0("total"), now); !got.Equal(now) { + t.Errorf("new total since %s", got) + } + if got := sinceOf(&Limit{Period: "total", Since: since}, v0("total"), now); !got.Equal(since) { + t.Errorf("a new cap restarted it: %s", got) + } + if got := sinceOf(&Limit{Period: "month"}, v0("total"), now); !got.Equal(now) { + t.Errorf("month to total since %s", got) + } + if got := sinceOf(&Limit{Period: "total", Since: since}, v0("month"), now); !got.IsZero() { + t.Errorf("total to month since %s", got) + } +} + +func v0(period string) *Limit { return &Limit{Period: period, Cost: 1} } diff --git a/internal/budget/budget.go b/internal/budget/budget.go index fc7e02efa..237a484a1 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -524,6 +524,9 @@ func (r *Refusal) Error() string { if len(r.Models) > 0 { on = " on " + strings.Join(r.Models, ", ") } + 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) + } 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")) } diff --git a/internal/budget/total_test.go b/internal/budget/total_test.go new file mode 100644 index 000000000..6a8af0b47 --- /dev/null +++ b/internal/budget/total_test.go @@ -0,0 +1,89 @@ +package budget + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/usage" +) + +// A "total" limit (@Cyrus_4433 on X) never resets by the clock: what a +// key spent 100 days ago still counts against it, where a month limit has +// forgotten it, and only the key's Reset usage starts it again. +func TestTotalLimitNeverResetsByThePeriod(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")) + now := time.Now().Round(0) + long := now.AddDate(0, 0, -100) + // the limits are set 120 days ago, so a total one counts from then + access.Now = func() time.Time { return now.AddDate(0, 0, -120) } + t.Cleanup(func() { access.Now = time.Now }) + newKey := func(name, period string) access.Key { + t.Helper() + if _, err := access.Update("add-key", access.Change{Name: name}); err != nil { + t.Fatal(err) + } + ks, _ := access.List() + for _, k := range ks { + if k.Name == name { + if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &access.Limit{Period: period, Tokens: 1000}}); err != nil { + t.Fatal(err) + } + } + } + ks, _ = access.List() + for _, k := range ks { + if k.Name == name { + return k + } + } + t.Fatal("no key") + return access.Key{} + } + refused := func(k access.Key) *Refusal { + t.Helper() + who := access.Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More} + _, r := Reserve(who, -1, "", now) + return r + } + for _, name := range []string{"Total", "Month"} { + period := strings.ToLower(name) + k := newKey(name, period) + Append(usage.Record{Time: long, Provider: "p", Model: "m", Input: 1000, Status: 200, CallerKeyID: k.ID}) + r := refused(k) + if period == "month" && r != nil { + t.Fatalf("a month limit still counts a call of 100 days ago: %v", r) + } + if period == "total" { + if r == nil { + t.Fatal("a total limit forgot a call of 100 days ago") + } + if !strings.Contains(r.Error(), "total limit") || strings.Contains(r.Error(), "resets at") { + t.Errorf("refusal: %s", r.Error()) + } + if r.RetryAfter(now) < 365*24*3600 { + t.Errorf("retry after %ds", r.RetryAfter(now)) + } + // Reset usage counts it again from now + access.Now = func() time.Time { return now.Add(-time.Minute) } + if _, err := access.Update("reset-limit-key", access.Change{Key: k.ID}); err != nil { + t.Fatal(err) + } + ks, _ := access.List() + for _, x := range ks { + if x.ID == k.ID { + k = x + } + } + if r := refused(k); r != nil { + t.Fatalf("still refused after Reset usage: %v", r) + } + } + } +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index abf528b65..8023a71fc 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -111,7 +111,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 [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|total|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -187,7 +187,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { // // magpie gateway-key limit [list] what it has used of each limit // magpie gateway-key limit off no limit -// magpie gateway-key limit day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] +// magpie gateway-key limit day|week|month|total|d|h [--tokens N] [--cost USD] [--cache-reads] // its only limit, or the one of several with that window // magpie gateway-key limit add [--tokens N] [--cost USD] [--cache-reads] [--model openai/*] // one more limit; a request passes only while every one has something left @@ -199,7 +199,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 [off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]]") + usage := fmt.Errorf("usage: magpie gateway-key limit [off | reset [] | remove | [add] day|week|month|total|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]]") if len(args) == 0 { return usage } @@ -342,9 +342,13 @@ func gatewayKeyLimit(out io.Writer, args []string) error { } state := "open" if st.Spent { - state = "spent: requests are refused until " + st.Reset.Format("2006-01-02 15:04") + until := st.Reset.Format("2006-01-02 15:04") + if st.Period == "total" { + until = "the limit is reset or raised" + } + state = "spent: requests are refused until " + until if len(st.Models) > 0 { - state = "spent: requests for these models are refused until " + st.Reset.Format("2006-01-02 15:04") + state = "spent: requests for these models are refused until " + until } } fmt.Fprintf(w, "State\t%s\n", state) @@ -364,6 +368,9 @@ func perPhrase(l *access.Limit) string { case "hours": return fmt.Sprintf("every %d hours", l.Hours) } + if l.Period == "total" { + return "in total" + } return "per " + l.Period } @@ -380,7 +387,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" { + if window == "day" || window == "week" || window == "month" || window == "total" { // 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) @@ -396,7 +403,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, d (every N days) or h (every N hours), not %q", lim.Period) + return nil, fmt.Errorf("a limit's period is day, week, month, total, d (every N days) or h (every N hours), not %q", lim.Period) } for i := 0; i < len(rest); i++ { flag, val, has := strings.Cut(rest[i], "=") diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c86bda2b8..4b7f1c2a8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -559,6 +559,12 @@ const I18N = { "per day": "每日", "per week": "每周", "per month": "每月", + "in total": "总额", + "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 和费用一起归零,并从现在起重新计数。", + "Tokens in total": "总额 Token", + "Spend in total": "总额花费", "Change this key's limit": "修改此密钥的限额", "Set a limit for this key": "为此密钥设置限额", "Models this key may use": "此密钥可用的模型", @@ -5642,6 +5648,12 @@ const I18N = { "per day": "每日", "per week": "每週", "per month": "每月", + "in total": "總額", + "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 和費用一起歸零,並從現在起重新計數。", + "Tokens in total": "總額 Token", + "Spend in total": "總額花費", "Change this key's limit": "修改此金鑰的限額", "Set a limit for this key": "為此金鑰設定限額", "Models this key may use": "此金鑰可用的模型", @@ -10686,6 +10698,12 @@ const I18N = { "per day": "1日あたり", "per week": "1週間あたり", "per month": "1か月あたり", + "in total": "合計", + "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 に戻り、今から数え直します。", + "Tokens in total": "合計トークン", + "Spend in total": "合計費用", "Change this key's limit": "このキーの上限を変更", "Set a limit for this key": "このキーに上限を設定", "Models this key may use": "このキーで使えるモデル", @@ -15748,6 +15766,12 @@ const I18N = { "per day": "pro Tag", "per week": "pro Woche", "per month": "pro Monat", + "in total": "insgesamt", + "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.", + "Tokens in total": "Token insgesamt", + "Spend in total": "Ausgaben insgesamt", "Change this key's limit": "Limit dieses Schlüssels ändern", "Set a limit for this key": "Limit für diesen Schlüssel festlegen", "Models this key may use": "Modelle, die dieser Schlüssel nutzen darf", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 5911ca19d..9fcf9a0cd 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -1002,9 +1002,10 @@ function gatewayTierBadge(k) { // ---- a gateway key's own limit (#585) ---- // "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 -const limitPeriods = ["day", "week", "month", "days", "hours"]; -const limitPer = { day: "per day", week: "per week", month: "per month", days: "Every N days", hours: "Every N hours" }; +// "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" }; 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" @@ -1103,11 +1104,14 @@ function gatewayLimitLine(k, u) { 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); - parts.push(t(u.spent ? "refused until {when}" : "resets {when}", { when: resetClock(at) })); + 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" : "") - + t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(intlLang()), when: at.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 }) : ""); return line; } @@ -1350,6 +1354,7 @@ function askResetLimit(k, n) { ed.append(head, el("p", "lib-confirm", u.period === "days" ? 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 }) : 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")); diff --git a/internal/gui/tests/gateway-key-total.test.cjs b/internal/gui/tests/gateway-key-total.test.cjs new file mode 100644 index 000000000..97cba8c6c --- /dev/null +++ b/internal/gui/tests/gateway-key-total.test.cjs @@ -0,0 +1,93 @@ +// A gateway key's limit "in total" (@Cyrus_4433 on X): the window menu +// offers it, the row says "$0.00 / $300 · " with no reset time, and +// Reset usage says counting starts again from now. In every language, both +// engines, and at a narrow width. +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 day = 864e5; +const limits = () => ({ + laptop: { + limit: { period: "total", cost: 300, since: new Date(Date.now() - 40 * day).toISOString() }, + used: { period: "total", start: new Date(Date.now() - 40 * day).toISOString(), reset: new Date(Date.now() + 36500 * day).toISOString(), calls: 90, + tokens: 4000000, cost: 0, costLimit: 300, tokensLeft: 0, costLeft: 300, spent: false }, + }, +}); + +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 in total`, 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() })); + 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 inTotal = tr("in total"); + if (lang === "zh") assert.equal(inTotal, "总额"); + + // the row: used / limit · total, and no reset time + const badge = row("laptop").locator(".amodels.limit"); + assert.equal((await badge.textContent()).trim(), `$0.00 / $300 · ${inTotal}`); + assert.equal(await row("laptop").locator(".key-limit").first().textContent().then((s) => /\b(resets|重置|リセット|Reset)\b/i.test(s) && s.includes("2126")), false, "a total limit names a reset date"); + + // the menu offers it last, and a new limit in total is sent as one + 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(); + assert.equal(await wed.locator("select").count(), 0, "no native select"); + await wed.getByRole("textbox", { name: tr("Estimated cost limit, US$"), exact: true }).fill("300"); + await wed.getByRole("button", { name: tr("Limit window"), exact: true }).click(); + const items = page.locator(".proto-menu .pm-item"); + assert.equal((await items.last().textContent()).trim(), inTotal); + await items.last().click(); + const win = wed.getByRole("button", { name: tr("Limit window"), exact: true }); + assert.equal(await win.getAttribute("data-value"), "total"); + assert.equal((await win.textContent()).trim(), inTotal); + assert.equal(await wed.getByRole("textbox", { name: tr("Days in a cycle"), exact: true }).isVisible(), false); + assert.equal(await wed.getByRole("textbox", { name: tr("Hours in a cycle"), exact: true }).isVisible(), false); + // 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 wed.getByRole("button", { name: tr("Save"), exact: true }).click(); + await wed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").map((e) => e.body), [{ key: "work", limit: { period: "total", tokens: 0, cost: 300, cacheReads: false } }]); + assert.match(await row("work").locator(".amodels.limit").textContent(), new RegExp(`\\$300 · ${inTotal}`)); + + // Reset usage says counting starts again, not a window's end + 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(); + assert.equal((await ed.getByRole("button", { name: tr("Limit window"), exact: true }).textContent()).trim(), inTotal); + 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, and counting starts again from now.", { 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, []); + }); + } +} diff --git a/internal/provider/remote_key_limits.go b/internal/provider/remote_key_limits.go index a4a3dc093..dc7cfff57 100644 --- a/internal/provider/remote_key_limits.go +++ b/internal/provider/remote_key_limits.go @@ -41,7 +41,7 @@ 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). + // "hours" (of Hours hours) or "total" (until reset by hand). Period string `json:"period,omitempty"` Days int `json:"days,omitempty"` Hours int `json:"hours,omitempty"` @@ -201,13 +201,16 @@ func keyLimitCard(a *remoteKeyAnswer) (*GatewayKeyLimit, []QuotaWindow) { // key's continue } - reset := x.Reset + resets := &x.Reset + if x.Period == "total" { + resets = nil // it never ends by itself + } if x.TokenLimit > 0 { - ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", x.Period), Used: share(float64(x.Tokens), float64(x.TokenLimit)), ResetsAt: &reset, + ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", x.Period), Used: share(float64(x.Tokens), float64(x.TokenLimit)), ResetsAt: resets, Amount: float64(x.Tokens), Limit: float64(x.TokenLimit), Unit: "tokens"}) } if x.CostLimit > 0 { - ws = append(ws, QuotaWindow{Name: keyWindowName("Spend", x.Period), Used: share(x.Cost, x.CostLimit), ResetsAt: &reset, + ws = append(ws, QuotaWindow{Name: keyWindowName("Spend", x.Period), Used: share(x.Cost, x.CostLimit), ResetsAt: resets, Amount: math.Round(x.Cost*100) / 100, Limit: x.CostLimit, Unit: "USD"}) } } @@ -235,6 +238,8 @@ func keyWindowName(what, period string) string { return what + " this week" case "month": return what + " this month" + case "total": + return what + " in total" } return what + " this cycle" }