usage: a ChatGPT card has an image row: used up until the refusal's reset, else unknown (#6160, hqqqqqqqh on X)

ChatGPT's image generation has a quota apart from the 5-hour and weekly
windows. Neither /wham/usage (additional_rate_limits is null) nor the reply
headers (x-codex-primary-*, x-codex-secondary-*) tell it, so no remaining
count exists to show. Each Codex account's card (Usage page, magpie quota
--json, /v1/magpie/quotas, /v1/magpie/quotas/cards) now has an "Image
generation" row (provider.WithImageLane, Lane "images", Text and Aside so
routing, holds, history, tray and statusline never see it): "Used up" with
the reset time while the image model rests on that account after a refusal
(the #2244 drawing-lane rest, whose time is the refusal's resets_at), and
"Unknown" otherwise. Never a share or a count. Shown in en, zh, zh-TW, ja, de.

app.js: a Text row's display now goes through t(), a same-length change, as
the core script budget has 1 byte of room.

Run (on mote): go test -count=1 -run 'TestWithImageLane|TestCodexImageRow'
./internal/provider ./internal/gateway ok; codex-image-row.test.cjs in
chromium and webkit at 900 and 390px in all five languages ok;
TestCoreScriptBudget ok; go vet darwin, windows, linux nogui on provider and
gateway ok; gofmt clean; 158 GUI files matching i18n/quota/usage/balance
names in both engines (result in the follow-up).
Broken by hand: the GUI test is red with app.js's display line put back to
the old form; the Go row tests are red with imageRestOf returning false.
Not tried: a real ChatGPT account hitting its image quota (the row is
driven by a faked refusal's rest); the generated-image count the issue also
asks for is not built.
This commit is contained in:
yetone
2026-11-11 21:59:36 +08:00
parent da169135a0
commit 0706d7a35a
11 changed files with 278 additions and 5 deletions
File diff suppressed because one or more lines are too long
+32
View File
@@ -0,0 +1,32 @@
package gateway
import (
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
func init() { provider.ImageRest = imageRestOf }
// imageRestOf is when the ChatGPT account user draws again, as the refusal
// that rested its image model said (restDrawer; usage_limit_reached's
// resets_at), while that rest holds. It is the only thing magpie learns of
// the account's image allowance, which the backend shows no share of
// (provider.ImageLane, #6160), and it is only that: not when the allowance
// began, nor what it counted. The latest of several resting image models
// (a rest per model) is the one that says when drawing is back.
func imageRestOf(agent, user string, now time.Time) (time.Time, bool) {
restingUntil.Lock()
defer restingUntil.Unlock()
var last time.Time
for k, r := range restingUntil.note {
if r.agent != agent || !strings.EqualFold(r.user, user) || !strings.HasPrefix(r.Model, codexDrawerFamily) {
continue
}
if until := restingUntil.m[k]; until.After(now) && until.After(last) {
last = until
}
}
return last, !last.IsZero()
}
+58
View File
@@ -0,0 +1,58 @@
package gateway
import (
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// #6160: a ChatGPT account's image allowance shows on its card as the time
// the refusal that rested it said, and as unknown before any refusal; the
// chat windows around it are as they were.
func TestCodexImageRowIsTheRefusalsResetTime(t *testing.T) {
user := "Image.Lane@example.com"
c := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: user}}, model: codexDrawer}
t.Cleanup(func() { clearRest(c.restID()) })
card := func() provider.SubscriptionQuota {
in := []provider.SubscriptionQuota{{Provider: "codex", User: user, Windows: []provider.QuotaWindow{{Name: "5 hours", Used: 40}, {Name: "7 days", Used: 10}}}}
out := provider.WithImageLane(in, time.Now())
if len(in[0].Windows) != 2 {
t.Fatalf("the cached card was written to: %d windows", len(in[0].Windows))
}
return out[0]
}
row := func(q provider.SubscriptionQuota) provider.QuotaWindow {
if len(q.Windows) != 3 || q.Windows[0].Name != "5 hours" || q.Windows[1].Name != "7 days" {
t.Fatalf("windows = %+v", q.Windows)
}
return q.Windows[2]
}
w := row(card())
if w.Lane != provider.ImageLane || !w.Text || !w.Aside || w.ResetsAt != nil || w.Used != 0 || w.Display != "Unknown" {
t.Fatalf("before any refusal the row = %+v, want unknown with no time", w)
}
at := time.Now().Add(3 * time.Hour).Truncate(time.Second)
body := []byte(`{"error":{"type":"usage_limit_reached","resets_at":` + itoa(int(at.Unix())) + `}}`)
restDrawer(c, http.StatusTooManyRequests, string(body))
w = row(card())
if w.ResetsAt == nil || w.ResetsAt.Sub(at).Abs() > 2*time.Second || w.Display != "Used up" || w.Used != 0 || !w.Text {
t.Fatalf("after the refusal the row = %+v, want used up until %v and no share", w, at)
}
// another account's refusal is not this one's
other := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "other@example.com"}}, model: codexDrawer}
t.Cleanup(func() { clearRest(other.restID()) })
restDrawer(other, http.StatusTooManyRequests, string(body))
clearRest(c.restID())
if w = row(card()); w.ResetsAt != nil {
t.Fatalf("a rest lifted still shows a time: %+v", w)
}
// a chat model's rest on the account is not the image allowance
chat := candidate{p: c.p, model: "gpt-5"}
t.Cleanup(func() { clearRest(chat.restID()) })
restDrawer(chat, http.StatusTooManyRequests, string(body))
if w = row(card()); w.ResetsAt != nil {
t.Fatalf("a chat model's rest shows as the image row: %+v", w)
}
}
+2 -1
View File
@@ -14441,7 +14441,8 @@ function quotaText(w) {
if (w.balance != null) return t("{n} left", { n: (countFormat.format(w.balance) + " " + t(w.unit || "")).trim() });
// a text row used 100 is Claude's overages (claudeOveragesWindow): "In use", said in the reader's language
if (w.text && w.used >= 100) return t("In use");
if (quotaNoShare(w)) return w.display || t("No allowance reported");
// a Text row's display is said in the reader's language (the image row's "Used up" and "Unknown", #6160)
if (quotaNoShare(w)) return t(w.display || "No allowance reported");
const used = to100(w.used);
const n = quotaLeft ? 100 - used : used;
const pct = t(quotaLeft ? "{n} left" : "{n} used", { n: (Number.isInteger(n) ? n : n.toFixed(1)) + "%" });
+4
View File
@@ -2346,6 +2346,7 @@ const I18N = {
"Droid Core · 7 days": "Droid Core · 7 天",
"Droid Core · 30 days": "Droid Core · 30 天",
"Extra usage": "额外用量",
"Used up": "已用完",
"Usage credits": "额外用量额度",
"Gift plans to claim in the ZCode app": "待在 ZCode 客户端领取的赠送额度",
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 赠送额度(-Trial 模型)需要 ZCode 登录",
@@ -7426,6 +7427,7 @@ const I18N = {
"Droid Core · 7 days": "Droid Core · 7 天",
"Droid Core · 30 days": "Droid Core · 30 天",
"Extra usage": "額外用量",
"Used up": "已用完",
"Usage credits": "額外用量額度",
"Gift plans to claim in the ZCode app": "待在 ZCode 用戶端領取的贈送額度",
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 贈送額度(-Trial 模型)需要 ZCode 登入",
@@ -12482,6 +12484,7 @@ const I18N = {
"Droid Core · 7 days": "Droid Core · 7日",
"Droid Core · 30 days": "Droid Core · 30日",
"Extra usage": "追加使用量",
"Used up": "使い切り",
"Usage credits": "追加使用量のクレジット",
"Gift plans to claim in the ZCode app": "ZCode アプリで受け取れるギフト枠",
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode のギフト枠(-Trial モデル)には ZCode でのサインインが必要",
@@ -17569,6 +17572,7 @@ const I18N = {
"Droid Core · 7 days": "Droid Core · 7 Tage",
"Droid Core · 30 days": "Droid Core · 30 Tage",
"Extra usage": "Zusätzliche Nutzung",
"Used up": "Aufgebraucht",
"Usage credits": "Nutzungsguthaben",
"Gift plans to claim in the ZCode app": "In der ZCode-App abzuholen",
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode-Geschenkpläne (-Trial-Modelle) brauchen die ZCode-Anmeldung",
@@ -0,0 +1,83 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A ChatGPT account's image allowance (#6160) is a row of its own on the
// Usage card, beside the 5-hour and weekly windows: "used up" with the time
// it comes back when a refusal named it, "unknown" when nothing is known,
// and never a share or a meter. In every language, at the window's width
// and a phone's. No backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const soon = new Date(Date.now() + 3 * 3600 * 1000).toISOString();
const img = (extra) => ({ name: "Image generation", lane: "images", text: true, aside: true, used: 0, display: "Unknown", ...extra });
const chat = [{ name: "5 hours", used: 40, resetSecs: 3600 }, { name: "7 days", used: 10, resetSecs: 86400 }];
const quotas = [
{ provider: "codex", name: "Codex", icon: "codex-color", user: "spent@example.com", windows: [...chat, img({ display: "Used up", resetsAt: soon, resetSecs: 10800 })] },
{ provider: "codex", name: "Codex", icon: "codex-color", user: "fresh@example.com", windows: [...chat, img({})] },
];
const words = {
en: { name: "Image generation", used: "Used up", unknown: "Unknown" },
zh: { name: "生图模型", used: "已用完", unknown: "未知" },
"zh-TW": { name: "生圖模型", used: "已用完", unknown: "未知" },
ja: { name: "画像生成", used: "使い切り", unknown: "不明" },
de: { name: "Bilderzeugung", used: "Aufgebraucht", unknown: "Unbekannt" },
};
function serve(lang) {
const settings = { theme: "light", lang, currency: "usd" };
return async (route) => {
const url = new URL(route.request().url());
const json = (body) => route.fulfill({ json: body });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/usage/quotas/history") return json([]);
if (url.pathname === "/api/usage") return json({ days: [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a ChatGPT account's image row says used up until a time, or unknown, in every language`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [900, 390]) for (const lang of Object.keys(words)) {
const at = `${lang} ${width}`;
const errors = [];
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=usage&tab=usage");
await page.locator("#subscriptionUsage .quota").first().waitFor();
await page.locator(".quota-more").click();
const w = words[lang];
for (const [user, text, resets] of [["spent@example.com", w.used, true], ["fresh@example.com", w.unknown, false]]) {
const mine = page.locator(`[data-card="codex|${user}"] + .quota-windows`);
const row = mine.locator(".quota", { hasText: w.name });
await row.waitFor();
assert.equal((await row.locator(".quota-n").textContent()).trim(), text, at + " " + user);
assert.equal(await row.locator(".quota-track").count(), 0, at + " an image row has no meter, nothing told a share");
assert.equal(await row.locator(".quota-reset").count(), resets ? 1 : 0, at + " " + user + " reset line");
assert.doesNotMatch(await row.textContent(), /%/, at + " no percent is made up");
}
assert.equal(await page.locator('[data-card="codex|spent@example.com"] + .quota-windows .quota-track').count(), 2, at + " the chat windows keep their meters");
assert.deepEqual(errors, [], at);
await page.context().close();
}
});
}
+50
View File
@@ -0,0 +1,50 @@
package provider
import (
"strings"
"time"
)
// ImageLane is the name of a ChatGPT account's image window (QuotaWindow.Lane).
// Drawing with gpt-image-2 counts against an allowance of its own, apart from
// Codex's 5-hour and weekly windows (#6160), and the backend tells no share of
// it: /wham/usage has no image window (additional_rate_limits is null) and a
// reply carries no x-codex-* header for one. What magpie knows is the refusal
// it got, usage_limit_reached with the time it comes back, which the gateway
// keeps as the image model's rest (ImageRest). So the row says that time, or
// "unknown": never a share, which nothing told.
const ImageLane = "images"
// ImageRest is, set by the gateway, when the image model of the ChatGPT
// account user (as its usage is read, Account.UsageAgent) is back, while the
// vendor's refusal keeps it resting; false when it is not.
var ImageRest func(agent, user string, now time.Time) (time.Time, bool)
// WithImageLane is qs with a row for the image allowance added to each
// ChatGPT account's card that was read: Text and Aside, so no share is told
// and routing never reads it, with ResetsAt when a refusal named the time it
// comes back and no time otherwise. A card of another magpie is as it came;
// qs and its windows, which the caches share, are left as they were.
func WithImageLane(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota {
out := make([]SubscriptionQuota, len(qs))
for i, q := range qs {
out[i] = q
if q.Provider != "codex" || q.From != "" || q.Error != "" || q.User == "" {
continue
}
ws := make([]QuotaWindow, 0, len(q.Windows)+1)
for _, w := range q.Windows {
if w.Lane != ImageLane {
ws = append(ws, w)
}
}
w := QuotaWindow{Name: "Image generation", Lane: ImageLane, Text: true, Aside: true, Display: "Unknown"}
if ImageRest != nil {
if until, ok := ImageRest("codex", strings.ToLower(q.User), now); ok {
w.Display, w.ResetsAt, w.ResetSecs = "Used up", &until, int64(until.Sub(now)/time.Second)
}
}
out[i].Windows = append(ws, w)
}
return out
}
+38
View File
@@ -0,0 +1,38 @@
package provider
import (
"testing"
"time"
)
// WithImageLane adds the image row to a read ChatGPT account's card only,
// once, and says unknown, never a share, when nothing was heard.
func TestWithImageLaneOnlyReadCodexCards(t *testing.T) {
was := ImageRest
t.Cleanup(func() { ImageRest = was })
ImageRest = nil
now := time.Now()
win := []QuotaWindow{{Name: "5 hours", Used: 100}}
in := []SubscriptionQuota{
{Provider: "codex", User: "a@x.com", Windows: win},
{Provider: "codex", User: "b@x.com", Error: "not signed in"},
{Provider: "codex", User: "c@x.com", From: "elsewhere", Windows: win},
{Provider: "claude", User: "d@x.com", Windows: win},
}
out := WithImageLane(WithImageLane(in, now), now)
if len(out[0].Windows) != 2 || out[0].Windows[1].Lane != ImageLane || out[0].Windows[1].Used != 0 || out[0].Windows[1].Display != "Unknown" || out[0].Windows[1].ResetsAt != nil {
t.Fatalf("read card = %+v", out[0].Windows)
}
for _, i := range []int{1, 2, 3} {
if len(out[i].Windows) != len(in[i].Windows) {
t.Errorf("card %d got a row: %+v", i, out[i].Windows)
}
}
until := now.Add(time.Hour)
ImageRest = func(agent, user string, _ time.Time) (time.Time, bool) {
return until, agent == "codex" && user == "a@x.com"
}
if w := WithImageLane(in, now)[0].Windows[1]; w.ResetsAt == nil || !w.ResetsAt.Equal(until) || w.ResetSecs != 3600 {
t.Fatalf("row = %+v", w)
}
}
+4 -2
View File
@@ -56,7 +56,7 @@ func quotas(ctx context.Context) (subs, plans, balances []SubscriptionQuota) {
go func() { p <- PlanQuotas(ctx) }()
go func() { r <- RemoteCards(ctx) }()
plans, subs = seatCards(<-p, SubscriptionUsage(ctx))
subs, balances = withAccountNames(subs), <-b
subs, balances = WithImageLane(withAccountNames(subs), time.Now()), <-b
// a remote magpie's cards, each after this computer's of its kind
for _, q := range <-r {
switch q.Kind {
@@ -132,6 +132,8 @@ type QuotaSpan struct {
// Text: the window is its Display alone, Used and Remaining no
// reading (QuotaWindow.Text)
Text bool `json:"text,omitempty"`
// Lane names an allowance apart from the account's own (QuotaWindow.Lane)
Lane string `json:"lane,omitempty"`
// Amount of Limit in Unit: the window's count, used, when the vendor
// counts it so ("credits")
Amount float64 `json:"amount,omitempty"`
@@ -206,7 +208,7 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo
// a pool's own windows stand in for the models' drawing on it,
// as the usage page shows them
for _, w := range PooledWindows(q.Windows) {
s := QuotaSpan{Unlimited: w.Unlimited, Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text,
s := QuotaSpan{Unlimited: w.Unlimited, Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text, Lane: w.Lane,
Amount: w.Amount, Limit: w.Limit, Unit: w.Unit, Pool: w.Pool, RunsOutAt: w.RunsOutAt, RunsOut: w.RunsOut, Balance: w.Balance,
Spent: w.Spent, SpentSince: w.SpentSince, Holds: w.Holds, HoldsWhy: w.HoldsWhy}
if s.ResetsAt == nil && w.ResetSecs > 0 {
+1 -1
View File
@@ -140,7 +140,7 @@ func CachedCards(now time.Time) []SubscriptionQuota {
}
plans, balances = withKeyReadings(plans, ps, "plan"), withKeyReadings(balances, ps, "balance")
plans, subs = seatCards(plans, subs)
subs = withAccountNames(subs)
subs = WithImageLane(withAccountNames(subs), now)
out := []SubscriptionQuota{}
for _, g := range []struct {
kind string
+5
View File
@@ -41,6 +41,11 @@ type QuotaWindow struct {
// "100% left". Claude's "Extra usage" row (claudeOveragesWindow) is
// the one Text window with Used 100: the account counts as spent.
Text bool `json:"text,omitempty"`
// Lane names a window of an allowance apart from the account's own
// ("images", ImageLane): its row is Text, and says only when it comes
// back, if known. Added as cards are handed out (WithImageLane), never
// cached.
Lane string `json:"lane,omitempty"`
// Amount of Limit is the window's own count in Unit, when the vendor
// counts it so (WorkBuddy's credits): Used is Amount as a share of
// Limit. The GUI says it as used or left, as it says the share (#659).