diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 00277e05f..5f38a0cf0 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -825,6 +825,7 @@ body.window .field.solo { grid-column: auto; } /* a window's whole (WindowHolds): a line of its own under the reset */ .quota-reset .quota-holds { flex-basis: 100%; display: flex; flex-wrap: wrap; column-gap: 4px; min-width: 0; } .quota-reset .quota-holds > span { white-space: nowrap; } +.quota-reset .quota-holds-why { flex-basis: 100%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: .75; cursor: help; } .quota-track { height: 4px; border-radius: 2px; background: var(--pill); overflow: hidden; } .quota-track i { display: block; height: 100%; border-radius: inherit; background: var(--accent); } .subscription-error { font-size: 11px; color: var(--faint); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 17cf5965e..0b04936fe 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16911,6 +16911,24 @@ function holdsLine(h) { return line; } +// holdsWhy: why a window's whole isn't told (provider.Holds*), for +// holdsUnknownLine's tooltip; a reason not listed here says nothing. +const holdsWhy = { + low: () => t("Under {n}% of it is used: a rounded share that small is too coarse to scale up", { n: 5 }), + clock: () => t("Its reset time isn't known, so neither is when it began"), + log: () => t("It began before magpie's request log, so some of its calls weren't seen"), + none: () => t("magpie hasn't routed a call through this account in it yet"), + credits: () => t("A call in it may have been paid from credits or extra usage, not from the window"), +}; +// holdsUnknownLine: a window whose whole the server couldn't reckon +// (#2045): "not enough data", muted, and why in its tooltip, where it said +// nothing before and a reader couldn't tell a gap from a fault. +function holdsUnknownLine(why) { + const line = el("span", "quota-holds-why", t("Whole: not enough data")); + line.title = t("The whole window can't be estimated from magpie's calls yet") + "\n" + holdsWhy[why](); + return line; +} + // isKeyCard: the card of a remote magpie's gateway keys (#1547, // remote_key_limits.go), "/~keys", one account per key; quotaName // says so by its name, which is the remote's. @@ -17005,6 +17023,10 @@ function quotaWindows(sub) { if (w.holds) { if (!r) quota.append(r = el("div", "quota-reset")); r.append(holdsLine(w.holds)); + } else if (w.holdsWhy && holdsWhy[w.holdsWhy] && !sub.history) { + // and where it can't be told, so, and why in its tooltip (#2045) + if (!r) quota.append(r = el("div", "quota-reset")); + r.append(holdsUnknownLine(w.holdsWhy)); } // a model family's figure: its models, level by level, in its tooltip if (w.tiers) quota.title = t("{family}: the most used of its models", { family: w.name }) + "\n" + tiersText(w); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 228a313c9..46f023b2b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2440,6 +2440,13 @@ const I18N = { "All": "全部", "effective prices": "生效价格", "Whole ≈ {n} tokens": "整窗 ≈ {n} tokens", + "Whole: not enough data": "整窗:数据不足", + "The whole window can't be estimated from magpie's calls yet": "还无法按 magpie 经手的调用估算整个窗口", + "Under {n}% of it is used: a rounded share that small is too coarse to scale up": "已用不到 {n}%:这么小的取整比例太粗,没法按比例推算", + "Its reset time isn't known, so neither is when it began": "不知道它的重置时间,也就不知道它从何时开始", + "It began before magpie's request log, so some of its calls weren't seen": "它开始于 magpie 的请求记录之前,有些调用 magpie 没看到", + "magpie hasn't routed a call through this account in it yet": "magpie 在这个窗口里还没经手过这个账号的调用", + "A call in it may have been paid from credits or extra usage, not from the window": "其中有调用可能是用积分或额外用量付的,不是这个窗口的额度", "The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices": "整个窗口 ≈ {tokens} tokens(输入加输出),按 API 标价 ≈ {cost}", "The whole window ≈ {tokens} tokens of input and output; some of its models have no API price": "整个窗口 ≈ {tokens} tokens(输入加输出);其中有模型没有 API 标价", "Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used": "按 magpie 在这个窗口里经手这个账号的用量推算:{calls} 次调用 {tokens} tokens,缓存读取 {cache},除以服务商给出的已用 {used}", @@ -6565,6 +6572,13 @@ const I18N = { "All": "全部", "effective prices": "生效價格", "Whole ≈ {n} tokens": "整窗 ≈ {n} tokens", + "Whole: not enough data": "整窗:資料不足", + "The whole window can't be estimated from magpie's calls yet": "還無法按 magpie 經手的呼叫估算整個視窗", + "Under {n}% of it is used: a rounded share that small is too coarse to scale up": "已用不到 {n}%:這麼小的取整比例太粗,沒法按比例推算", + "Its reset time isn't known, so neither is when it began": "不知道它的重置時間,也就不知道它從何時開始", + "It began before magpie's request log, so some of its calls weren't seen": "它開始於 magpie 的請求記錄之前,有些呼叫 magpie 沒看到", + "magpie hasn't routed a call through this account in it yet": "magpie 在這個視窗裡還沒經手過這個帳號的呼叫", + "A call in it may have been paid from credits or extra usage, not from the window": "其中有呼叫可能是用積分或額外用量付的,不是這個視窗的額度", "The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices": "整個視窗 ≈ {tokens} tokens(輸入加輸出),按 API 標價 ≈ {cost}", "The whole window ≈ {tokens} tokens of input and output; some of its models have no API price": "整個視窗 ≈ {tokens} tokens(輸入加輸出);其中有模型沒有 API 標價", "Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used": "按 magpie 在這個視窗裡經手這個帳號的用量推算:{calls} 次呼叫 {tokens} tokens,快取讀取 {cache},除以服務商給出的已用 {used}", @@ -10694,6 +10708,13 @@ const I18N = { "All": "すべて", "effective prices": "適用価格", "Whole ≈ {n} tokens": "枠全体 ≈ {n} トークン", + "Whole: not enough data": "枠全体:データ不足", + "The whole window can't be estimated from magpie's calls yet": "magpie の呼び出しから枠全体をまだ見積もれません", + "Under {n}% of it is used: a rounded share that small is too coarse to scale up": "使用率が {n}% 未満です。丸められたこれほど小さな割合からは推算できません", + "Its reset time isn't known, so neither is when it began": "リセット時刻が不明なため、枠の開始時刻もわかりません", + "It began before magpie's request log, so some of its calls weren't seen": "magpie のリクエスト記録より前に始まった枠なので、見えていない呼び出しがあります", + "magpie hasn't routed a call through this account in it yet": "この枠では、magpie はまだこのアカウント経由で呼び出しを送っていません", + "A call in it may have been paid from credits or extra usage, not from the window": "この枠の呼び出しの一部は、枠ではなくクレジットや追加使用量で支払われた可能性があります", "The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices": "枠全体 ≈ {tokens} トークン(入力と出力)、API 定価で ≈ {cost}", "The whole window ≈ {tokens} tokens of input and output; some of its models have no API price": "枠全体 ≈ {tokens} トークン(入力と出力)。API 価格のないモデルが含まれます", "Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used": "この枠で magpie がこのアカウント経由で送った分から推算:{calls} 回の呼び出しで {tokens} トークン、キャッシュ読み取り {cache}、それをベンダーの示す使用率 {used} で割った値", @@ -14820,6 +14841,13 @@ const I18N = { "All": "Alle", "effective prices": "effektive Preise", "Whole ≈ {n} tokens": "Gesamt ≈ {n} Tokens", + "Whole: not enough data": "Gesamt: zu wenig Daten", + "The whole window can't be estimated from magpie's calls yet": "Das ganze Fenster lässt sich aus magpies Aufrufen noch nicht schätzen", + "Under {n}% of it is used: a rounded share that small is too coarse to scale up": "Weniger als {n} % verbraucht: ein so kleiner, gerundeter Anteil ist zu grob zum Hochrechnen", + "Its reset time isn't known, so neither is when it began": "Seine Rücksetzzeit ist unbekannt, also auch sein Beginn", + "It began before magpie's request log, so some of its calls weren't seen": "Es begann vor magpies Anfrageprotokoll, einige seiner Aufrufe wurden also nicht gesehen", + "magpie hasn't routed a call through this account in it yet": "magpie hat in diesem Fenster noch keinen Aufruf über dieses Konto geleitet", + "A call in it may have been paid from credits or extra usage, not from the window": "Ein Aufruf darin wurde vielleicht aus Guthaben oder zusätzlicher Nutzung bezahlt, nicht aus dem Fenster", "The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices": "Das ganze Fenster ≈ {tokens} Tokens Ein- und Ausgabe, ≈ {cost} zu API-Listenpreisen", "The whole window ≈ {tokens} tokens of input and output; some of its models have no API price": "Das ganze Fenster ≈ {tokens} Tokens Ein- und Ausgabe; einige seiner Modelle haben keinen API-Preis", "Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used": "Hochgerechnet aus dem, was magpie in diesem Fenster über dieses Konto geleitet hat: {tokens} Tokens in {calls} Aufrufen, {cache} Cache-Lesezugriffe, geteilt durch die {used}, die der Anbieter als verbraucht meldet", diff --git a/internal/gui/tests/quota-holds.test.cjs b/internal/gui/tests/quota-holds.test.cjs index d273d756a..4c5731a15 100644 --- a/internal/gui/tests/quota-holds.test.cjs +++ b/internal/gui/tests/quota-holds.test.cjs @@ -4,7 +4,9 @@ // the share used — "≈ N tokens · ≈ $X" under its reset, in every language, // at a phone's width too, and in its tooltip how it was reckoned and that // it reads low if the account is used elsewhere. A window the server didn't -// reckon says nothing, and one with no API price says no cost. +// reckon says "not enough data", muted, with why in its tooltip (#2045), +// one it gives no reason for says nothing, and one with no API price says +// no cost. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -18,10 +20,13 @@ const quotas = [ { provider: "claude", name: "Claude Code", icon: "claude-color", plan: "max", user: "dee@example.com", windows: [ { name: "5 hours", used: 20, resetsAt: soon(2), holds: holds(12345678, 85.4321, 20) }, { name: "7 days", used: 40, resetsAt: soon(70), holds: holds(234567890, 1234.5, 40) }, - { name: "7 days · Fable", used: 3, resetsAt: soon(70) }, + { name: "7 days · Fable", used: 3, resetsAt: soon(70), holdsWhy: "low" }, + { name: "7 days · Sonnet", used: 30, resetsAt: soon(70), holdsWhy: "credits" }, + { name: "7 days · Haiku", used: 30, resetsAt: soon(70), holdsWhy: "some reason this GUI doesn't know" }, ] }, { provider: "kiro", name: "Kiro", icon: "kiro-color", plan: "Pro", user: "kay@example.com", windows: [ { name: "Weekly", used: 25, holds: holds(40000, 0, 25, false) }, + { name: "Credits", used: 30, holdsWhy: "clock" }, ] }, ]; function serve(lang) { @@ -48,19 +53,19 @@ function serve(lang) { } const want = { - en: { line: "Whole ≈ 12M tokens", low: "reads low" }, - zh: { line: "整窗 ≈ 1234.6 万 tokens", low: "偏低" }, - "zh-TW": { line: "整窗 ≈ 1234.6 萬 tokens", low: "偏低" }, - ja: { line: "枠全体 ≈ 12M トークン", low: "低め" }, - de: { line: "Gesamt ≈ 12M Tokens", low: "zu niedrig" }, + en: { line: "Whole ≈ 12M tokens", low: "reads low", none: "Whole: not enough data", under: "Under 5%", credits: "credits", clock: "reset time" }, + zh: { line: "整窗 ≈ 1234.6 万 tokens", low: "偏低", none: "整窗:数据不足", under: "不到 5%", credits: "积分", clock: "重置时间" }, + "zh-TW": { line: "整窗 ≈ 1234.6 萬 tokens", low: "偏低", none: "整窗:資料不足", under: "不到 5%", credits: "積分", clock: "重置時間" }, + ja: { line: "枠全体 ≈ 12M トークン", low: "低め", none: "枠全体:データ不足", under: "5% 未満", credits: "クレジット", clock: "リセット時刻" }, + de: { line: "Gesamt ≈ 12M Tokens", low: "zu niedrig", none: "Gesamt: zu wenig Daten", under: "Weniger als 5 %", credits: "Guthaben", clock: "Rücksetzzeit" }, }; for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) { - test(`${name}: a window's whole, under its reset, whole at 360 and 440px in every language`, async () => { + test(`${name}: a window's whole, or not enough data and why, under its reset, whole at 360 to 1100px in every language`, async () => { const browser = await engine.launch(); try { for (const lang of Object.keys(want)) { - for (const width of [360, 440, 1000]) { + for (const width of [360, 420, 440, 1000, 1100]) { const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); await page.route("**/*", serve(lang)); @@ -80,12 +85,31 @@ for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) { inCard: b.left >= card.left - 1 && b.right <= card.right + 1, }; }), + unknown: [...document.querySelectorAll(".quota-holds-why")].map((l) => { + const card = l.closest(".subscription-card").getBoundingClientRect(), b = l.getBoundingClientRect(), cs = getComputedStyle(l); + return { + text: l.textContent, title: l.title, window: l.closest(".quota").querySelector(".quota-labels > span").textContent, + inReset: !!l.closest(".quota-reset"), cut: l.scrollWidth > l.clientWidth + 1, inCard: b.left >= card.left - 1 && b.right <= card.right + 1, + muted: Number(cs.opacity) < 1 && cs.color === getComputedStyle(l.closest(".quota-reset")).color, + }; + }), pageScroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1, }; }); const at = `${lang} ${width}px`; - assert.equal(got.count, 4, at); - assert.equal(got.lines.length, 3, `${at}: the Fable week, too little used, says nothing: ${JSON.stringify(got.lines)}`); + assert.equal(got.count, 7, at); + assert.equal(got.lines.length, 3, `${at}: only the windows reckoned tell a whole: ${JSON.stringify(got.lines)}`); + // the ones not reckoned say so, and why; one with a reason this + // GUI doesn't know says nothing + assert.deepEqual(got.unknown.map((l) => l.text), [want[lang].none, want[lang].none, want[lang].none], `${at}: ${JSON.stringify(got.unknown)}`); + const [fable, sonnet, credits] = got.unknown; + assert.ok(fable.title.includes(want[lang].under), `${at}: ${fable.title}`); + assert.ok(sonnet.title.includes(want[lang].credits), `${at}: ${sonnet.title}`); + assert.ok(credits.title.includes(want[lang].clock), `${at}: ${credits.title}`); + for (const l of got.unknown) { + assert.ok(l.inReset && !l.cut && l.inCard && l.muted, `${at}: ${JSON.stringify(l)}`); + assert.equal(l.title.split("\n").length, 2, at); + } const [five, week, kiro] = got.lines; assert.equal(five.text, want[lang].line + " · ≈ $85.43", at); assert.match(week.text, /≈ \$1235$/, at); diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 732d4e3df..ebc758332 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -80,6 +80,12 @@ type QuotaWindow struct { // calls through the account (usage.WithWindowHolds), for the GUI only; // nil where that can't be told honestly. Holds *WindowHolds `json:"holds,omitempty"` + // HoldsWhy is, where Holds is nil on a window of an account's own card + // that runs out and starts again, why its whole isn't told (#2045): + // HoldsLow, HoldsNoClock, HoldsBeforeLog, HoldsNoneRouted or + // HoldsCredits. Empty where no whole is ever told (a pool, a family, + // money aside, another magpie's card). + HoldsWhy string `json:"holdsWhy,omitempty"` // matches further scopes pools whose membership isn't one model word. matches func(string) bool // partial is set on the windows of a reading that may leave some out: diff --git a/internal/provider/window_holds.go b/internal/provider/window_holds.go index 8c2afcb9a..ff5309338 100644 --- a/internal/provider/window_holds.go +++ b/internal/provider/window_holds.go @@ -38,6 +38,16 @@ type WindowHolds struct { // below it a percent the vendor rounds is too coarse to scale up. const HoldsFloor = 5.0 +// Why a window's whole isn't told (QuotaWindow.HoldsWhy), for the GUI to +// say "not enough data" and why rather than leave it out (#2045). +const ( + HoldsLow = "low" // under HoldsFloor used + HoldsNoClock = "clock" // no reset clock, so no known start + HoldsBeforeLog = "log" // began before magpie's log does + HoldsNoneRouted = "none" // magpie routed nothing it counts in it + HoldsCredits = "credits" // a call in it may have been paid from credits +) + // Bounds is when w, read at readAt, began and ends: its reset, and that // less how long it runs; a month's window began on the same day a month // before. ok is false when either isn't known. diff --git a/internal/usage/window_holds.go b/internal/usage/window_holds.go index 173435546..7fa8ff293 100644 --- a/internal/usage/window_holds.go +++ b/internal/usage/window_holds.go @@ -22,8 +22,8 @@ import ( // it stood at now. qs itself, which the caller may share, is left as it is. func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota { since, ok := holdsSince(qs, now) - if !ok { - return qs + if !ok { // none can be reckoned: each one only says why + return windowHolds(qs, now, time.Time{}, nil, nil, nil, func(func(Record)) {}) } s := readLogSnapshot() dry := dryRuns(qs, provider.QuotaHistories(since, "", ""), now) @@ -37,7 +37,7 @@ func holdsSince(qs []provider.SubscriptionQuota, now time.Time) (time.Time, bool for _, q := range qs { at := readAtOf(q, now) for _, w := range q.Windows { - if start, _, ok := holdsBounds(q, w, at); ok && (!found || start.Before(since)) { + if start, _, why := holdsBounds(q, w, at); why == "" && (!found || start.Before(since)) { since, found = start, true } } @@ -52,22 +52,30 @@ func readAtOf(q provider.SubscriptionQuota, now time.Time) time.Time { return now } -// holdsBounds is the window of q's account to reckon w's whole over, ok -// only where w can be: an account's own card, a window that runs out and -// starts again on a known clock, counts a whole account's or some named -// models' calls, and is used enough, and a reading not past its reset. -func holdsBounds(q provider.SubscriptionQuota, w provider.QuotaWindow, at time.Time) (time.Time, time.Time, bool) { +// holdsBounds is the window of q's account to reckon w's whole over, where +// w can be: an account's own card, a window that runs out and starts again +// on a known clock, counts a whole account's or some named models' calls, +// and is used enough, and a reading not past its reset. why is empty where +// it can be, else the provider.Holds* reason it can't, or "-" for a window +// whose whole is never told (no reason worth a line on the card). +func holdsBounds(q provider.SubscriptionQuota, w provider.QuotaWindow, at time.Time) (start, end time.Time, why string) { if q.Error != "" || q.From != "" || q.User == "" || q.Balance != "" { - return time.Time{}, time.Time{}, false + return time.Time{}, time.Time{}, "-" } - if w.Unlimited || w.Aside || w.Family != "" || w.Pool != "" || math.IsNaN(w.Used) || w.Used < provider.HoldsFloor { - return time.Time{}, time.Time{}, false + if w.Unlimited || w.Aside || w.Family != "" || w.Pool != "" || math.IsNaN(w.Used) { + return time.Time{}, time.Time{}, "-" + } + if w.Used < provider.HoldsFloor { + return time.Time{}, time.Time{}, provider.HoldsLow } start, end, ok := w.Bounds(at) - if !ok || !end.After(at) || !start.Before(at) { - return time.Time{}, time.Time{}, false + if !ok { + return time.Time{}, time.Time{}, provider.HoldsNoClock } - return start, end, true + if !end.After(at) || !start.Before(at) { + return time.Time{}, time.Time{}, "-" + } + return start, end, "" } // dryRun is a stretch in which one of an account's windows had nothing @@ -144,12 +152,20 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf type slot struct{ q, w int } type span struct{ start, end time.Time } want := map[slot]span{} + why := map[slot]string{} // a window not reckoned, and why byAccount := map[string][]slot{} for i, q := range qs { at := readAtOf(q, now) for j, w := range q.Windows { - start, _, ok := holdsBounds(q, w, at) - if !ok || first.IsZero() || first.After(start) { + start, _, no := holdsBounds(q, w, at) + switch { + case no == "-": + continue + case no != "": + why[slot{i, j}] = no + continue + case first.IsZero() || first.After(start): + why[slot{i, j}] = provider.HoldsBeforeLog continue } k := q.Provider + "\x00" + strings.ToLower(q.User) @@ -157,7 +173,7 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf want[slot{i, j}] = span{start, at} } } - if len(want) == 0 { + if len(want) == 0 && len(why) == 0 { return qs } sums := map[slot]*provider.WindowHolds{} @@ -209,21 +225,33 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf } } }) - if len(sums) == 0 { - return qs - } out := make([]provider.SubscriptionQuota, len(qs)) copy(out, qs) cloned := map[int]bool{} - for s, h := range sums { - if h.Routed.Tokens <= 0 || slices.ContainsFunc(inRun[s], func(k runKey) bool { return paidOtherwise[k] }) { - continue - } + window := func(s slot) *provider.QuotaWindow { q := &out[s.q] if !cloned[s.q] { // the caller's windows are left as they are q.Windows, cloned[s.q] = append([]provider.QuotaWindow(nil), q.Windows...), true } - w := &q.Windows[s.w] + return &q.Windows[s.w] + } + for s := range want { + h := sums[s] + switch { + case h == nil || h.Routed.Tokens <= 0: + why[s] = provider.HoldsNoneRouted + case slices.ContainsFunc(inRun[s], func(k runKey) bool { return paidOtherwise[k] }): + why[s] = provider.HoldsCredits + } + } + for s, no := range why { + window(s).HoldsWhy = no + } + for s, h := range sums { + if why[s] != "" { + continue + } + w := window(s) h.Used = w.Used scale := 100 / w.Used h.Tokens = int64(math.Round(float64(h.Routed.Tokens) * scale)) diff --git a/internal/usage/window_holds_test.go b/internal/usage/window_holds_test.go index 84d507ffc..a9278ca0c 100644 --- a/internal/usage/window_holds_test.go +++ b/internal/usage/window_holds_test.go @@ -111,15 +111,32 @@ func TestWindowHoldsReckonsWhatMagpieRouted(t *testing.T) { t.Errorf("%s %s: cost %v (priced %v), want %v", got[x.q].Provider, w.Name, h.Cost, h.Priced, x.cost) } } - for _, x := range [][2]int{{0, 3}, {1, 1}, {2, 1}, {3, 0}} { - if h := got[x[0]].Windows[x[1]].Holds; h != nil { - t.Errorf("%s %s: reckoned %+v, want none", got[x[0]].Provider, got[x[0]].Windows[x[1]].Name, h) + // and where it isn't, why, for the card's "not enough data" (#2045): + // money aside and a card with an error say nothing + for _, x := range []struct { + q, w int + why string + }{{0, 3, ""}, {1, 1, provider.HoldsLow}, {2, 1, provider.HoldsNoClock}, {3, 0, ""}} { + w := got[x.q].Windows[x.w] + if w.Holds != nil || w.HoldsWhy != x.why { + t.Errorf("%s %s: reckoned %+v, why %q; want none, why %q", got[x.q].Provider, w.Name, w.Holds, w.HoldsWhy, x.why) } } + for _, x := range want { + if why := got[x.q].Windows[x.w].HoldsWhy; why != "" { + t.Errorf("%s %s: reckoned, and why not %q", got[x.q].Provider, got[x.q].Windows[x.w].Name, why) + } + } + // with no window that can be reckoned, each still says why + low := []provider.SubscriptionQuota{{Provider: "codex", User: "sam@example.com", Windows: []provider.QuotaWindow{ + {Name: "7 days", Used: 4, ResetsAt: at(4 * 24 * time.Hour), Span: 7 * 24 * time.Hour}}}} + if w := WithWindowHolds(low, now)[0].Windows[0]; w.Holds != nil || w.HoldsWhy != provider.HoldsLow || low[0].Windows[0].HoldsWhy != "" { + t.Errorf("4%% used, none reckonable: %+v why %q (the caller's %q), want why %q", w.Holds, w.HoldsWhy, low[0].Windows[0].HoldsWhy, provider.HoldsLow) + } // the cards the caller passed, which a cache may share, are as they were for _, q := range qs { for _, w := range q.Windows { - if w.Holds != nil { + if w.Holds != nil || w.HoldsWhy != "" { t.Fatalf("the caller's %s %s was written to", q.Provider, w.Name) } } @@ -140,15 +157,15 @@ func TestWindowHoldsNeedsTheWholeWindowLogged(t *testing.T) { } } priceOf := func(Record) *catalog.Price { return nil } - if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, nil, nil, read); got[0].Windows[0].Holds != nil { - t.Fatalf("the log began 2 days into the week, and the week was reckoned: %+v", got[0].Windows[0].Holds) + if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, nil, nil, read); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsBeforeLog { + t.Fatalf("the log began 2 days into the week, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy) } got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, nil, nil, read) if h := got[0].Windows[0].Holds; h == nil || h.Tokens != 500 || h.Priced { t.Fatalf("logged since before the week: %+v, want 500 tokens, unpriced", h) } - if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, nil, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil { - t.Fatalf("nothing routed, and the week was reckoned: %+v", got[0].Windows[0].Holds) + if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, nil, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsNoneRouted { + t.Fatalf("nothing routed, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy) } // a provider since renamed: its calls under the old id are the account's recs[0].Provider = "claude-old" @@ -203,8 +220,10 @@ func TestWindowHoldsLeavesOutCallsPaidOtherwise(t *testing.T) { pt := func(ago time.Duration, left float64) provider.QuotaPoint { return provider.QuotaPoint{At: now.Add(-ago), Left: left} } + var whys [2]string holds := func(qs []provider.SubscriptionQuota, h []provider.QuotaHistory, recs ...Record) (five, week *provider.WindowHolds) { got := windowHolds(qs, now, first, priceOf, nil, dryRuns(qs, h, now), reads(recs...)) + whys = [2]string{got[0].Windows[0].HoldsWhy, got[0].Windows[1].HoldsWhy} return got[0].Windows[0].Holds, got[0].Windows[1].Holds } @@ -212,6 +231,9 @@ func TestWindowHoldsLeavesOutCallsPaidOtherwise(t *testing.T) { if five, week := holds(card(100, time.Hour), nil, subscription, credits); five != nil || week != nil { t.Fatalf("a window ran dry at an unknown time and was reckoned: 5 hours %+v, week %+v", five, week) } + if whys != [2]string{provider.HoldsCredits, provider.HoldsCredits} { + t.Fatalf("why not reckoned: %q, want credits for both (#2045)", whys) + } // read dry 90 minutes ago, some left 3 hours ago: the call an hour ago was credits dry := hist(pt(3*time.Hour, 40), pt(90*time.Minute, 0)) if five, week := holds(card(100, time.Hour), dry, subscription, credits); five != nil || week != nil {