usage: a plan says when its paid time ends — a ChatGPT account the date its sign-in names (only while it is ahead: a token not refreshed since says nothing of now), a GLM Coding plan (ZCode, or a Zhipu or Z.ai key) its renewal or end from the account's subscriptions as ZCode reads them — beside the plan on the Usage page, under the account in the panel, and in the TUI and magpie quota

This commit is contained in:
yetone
2026-09-27 23:23:56 +08:00
parent fb21a7fbc5
commit d8200dfe54
12 changed files with 217 additions and 8 deletions
+4
View File
@@ -512,6 +512,10 @@ body.window .field.solo { grid-column: auto; }
.pq-row { display: flex; align-items: center; gap: 8px; min-height: 24px; font-size: 12px; }
.pq-row .ic { flex: none; }
.pq-who { flex: 1 1 0; min-width: 96px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg-2); }
.pq-who.two { display: flex; flex-direction: column; line-height: 1.25; padding: 2px 0; }
.pq-who.two > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pq-term { font-size: 10px; color: var(--faint); }
.pq-term.ends { color: var(--muted); }
.pq-ws { flex: 0 1 auto; min-width: 0; display: flex; align-items: center; gap: 14px; font-size: 10.5px; color: var(--muted); }
.pq-w { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; min-width: 0; }
.pq-n { max-width: 84px; overflow: hidden; text-overflow: ellipsis; }
+22 -4
View File
@@ -3793,7 +3793,7 @@ function renderQuotas() {
const card = el("div", "subscription-card" + (first.user ? " several" : ""));
const head = el("div", "subscription-head");
head.append(icon(first.icon), el("b", "", first.name));
if (!first.user && first.plan) head.append(el("span", "plan", first.plan));
if (!first.user && (first.plan || first.until)) head.append(planSpan(first));
card.append(head);
for (const sub of subs) {
if (sub.user) {
@@ -3801,7 +3801,7 @@ function renderQuotas() {
const u = el("span", "user", sub.user);
u.title = sub.user;
who.append(u);
if (sub.plan) who.append(el("span", "plan", sub.plan));
if (sub.plan || sub.until) who.append(planSpan(sub));
card.append(who);
}
card.append(quotaWindows(sub));
@@ -3810,6 +3810,19 @@ function renderQuotas() {
}
}
// planTerm says when a plan's paid time ends: renewed then, over, or
// either (the vendor doesn't say which), as short as a panel row needs.
function planTerm(q) {
if (!q.until) return "";
const date = new Date(q.until).toLocaleDateString(locale === "zh" ? "zh-CN" : undefined, { month: "short", day: "numeric" });
return t(q.renew === "auto" ? "Renews {date}" : q.renew === "off" ? "Expires {date}" : "Until {date}", { date });
}
function planSpan(q) {
const s = el("span", "plan", [q.plan, planTerm(q)].filter(Boolean).join(" · "));
if (q.until) s.title = t(q.renew === "auto" ? "Renews {date}" : q.renew === "off" ? "Expires {date}" : "Until {date}", { date: new Date(q.until).toLocaleString() });
return s;
}
// The tray panel keeps every subscription's allowance in sight, a line per
// account under the agents: its two rolling windows, or its balance, the
// rest on the Usage page. Its heading folds it away, remembered.
@@ -3850,8 +3863,13 @@ function renderPanelQuota() {
function panelQuotaRow(q) {
const row = el("div", "pq-row");
const who = el("span", "pq-who", q.user || q.name);
row.title = [q.name, q.user, q.plan].filter(Boolean).join(" · ");
let who = el("span", "pq-who", q.user || q.name);
row.title = [q.name, q.user, q.plan, planTerm(q)].filter(Boolean).join(" · ");
if (q.until) {
// when the plan's paid time ends, under the account, the meters kept their width
who = el("span", "pq-who two");
who.append(el("span", "", q.user || q.name), el("span", "pq-term" + (q.renew === "off" ? " ends" : ""), planTerm(q)));
}
row.append(icon(q.icon), who);
const ws = el("span", "pq-ws");
if (q.balance) {
+3
View File
@@ -593,6 +593,9 @@ const I18N = {
"A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "API key 只能查到它自己的剩余额度。要在用量页显示整个账户的余额,请在 {p} 的设置中生成系统访问令牌并粘贴到这里;它不作他用。",
"Antigravity hasn't set this account up — hover for why": "Antigravity 还没为这个账号开通,悬停查看原因",
"Resets {when}": "重置于 {when}",
"Renews {date}": "{date}续费",
"Expires {date}": "{date}到期",
"Until {date}": "有效期至{date}",
"Allowance": "用量额度",
"Chat requests": "聊天请求",
"Completions": "代码补全",
+19
View File
@@ -6,6 +6,7 @@ package provider
import (
"context"
"os"
"strings"
"sync"
"time"
@@ -117,6 +118,7 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
if plan, q.Windows, err = codexWindows(ctx, tok, accountID); plan != "" {
q.Plan = plan
}
q.Until = codexUntil(codexLoginAuth(l), time.Now())
}
}
if err != nil {
@@ -138,3 +140,20 @@ func CodexUsedUp(ctx context.Context) bool {
}
return false
}
// codexLoginAuth is the auth.json of a ChatGPT account magpie knows: the
// file Codex is signed in with, or the one kept for it.
func codexLoginAuth(l Login) []byte {
if l.Active {
b, _ := os.ReadFile(codexAuthPath())
return b
}
loginsMu.Lock()
defer loginsMu.Unlock()
for _, x := range readLogins() {
if x.Agent == "codex" && strings.EqualFold(x.User, l.User) {
return x.Auth
}
}
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package provider
import (
"encoding/base64"
"encoding/json"
"testing"
"time"
)
func TestZhipuTermOf(t *testing.T) {
var subs []zhipuSubscription
json.Unmarshal([]byte(`[
{"status":"EXPIRED","nextRenewTime":"2026-08-01 00:00:00","autoRenew":1},
{"status":"VALID","valid":"2026-09-18 10:00:00-2026-10-18 10:00:00","autoRenew":1,"nextRenewTime":"2026-10-18 10:00:00"}]`), &subs)
until, renew := zhipuTermOf(subs)
if until == nil || renew != "auto" || !until.Equal(time.Date(2026, 10, 18, 2, 0, 0, 0, time.UTC)) {
t.Fatalf("auto: %v %q", until, renew)
}
subs = nil
json.Unmarshal([]byte(`[{"status":"VALID","valid":"2026-09-18 10:00:00-2026-12-18 10:00:00","autoRenew":false}]`), &subs)
if until, renew = zhipuTermOf(subs); until == nil || renew != "off" || until.Month() != 12 {
t.Fatalf("off, from valid: %v %q", until, renew)
}
subs = nil
json.Unmarshal([]byte(`[{"status":"VALID","autoRenew":true}]`), &subs)
if until, renew = zhipuTermOf(subs); until != nil || renew != "" {
t.Fatalf("nothing said: %v %q", until, renew)
}
}
func TestCodexUntil(t *testing.T) {
now := time.Date(2026, 9, 27, 0, 0, 0, 0, time.UTC)
auth := func(until string) []byte {
claims, _ := json.Marshal(map[string]any{"https://api.openai.com/auth": map[string]any{"chatgpt_subscription_active_until": until}})
b, _ := json.Marshal(map[string]any{"tokens": map[string]any{"id_token": "e30." + base64.RawURLEncoding.EncodeToString(claims) + ".sig"}})
return b
}
if u := codexUntil(auth("2026-10-18T09:00:00+00:00"), now); u == nil || u.Day() != 18 {
t.Fatalf("future: %v", u)
}
if u := codexUntil(auth("2026-09-18T09:00:00+00:00"), now); u != nil {
t.Fatalf("a stale token's date is shown: %v", u)
}
if u := codexUntil([]byte(`{}`), now); u != nil {
t.Fatalf("none: %v", u)
}
}
+3
View File
@@ -343,6 +343,9 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
q.Error = err.Error()
default:
q.Plan, q.Windows = plan, ws
if strings.HasSuffix(j.src.url, "/api/monitor/usage/quota/limit") { // Zhipu, Z.ai
q.Until, q.Renew = zhipuTerm(ctx, zcodeRoot(j.src.url), j.key)
}
}
got[i] = &q
}()
+7 -2
View File
@@ -137,6 +137,10 @@ func TestPlanQuotas(t *testing.T) {
w.Write([]byte(`{"success":true,"data":{"level":"lite","limits":[{"type":"TOKENS_LIMIT","unit":3,"number":5,"percentage":90}]}}`))
case "open.bigmodel.cn/api/monitor/usage/quota/limit glm-payg":
w.Write([]byte(`{"success":true,"data":{"limits":[]}}`))
case "open.bigmodel.cn/api/biz/subscription/list glm-a":
w.Write([]byte(`{"code":200,"success":true,"data":[{"productName":"GLM Coding Pro","status":"VALID","autoRenew":1,"nextRenewTime":"2026-10-18 10:00:00"}]}`))
case "open.bigmodel.cn/api/biz/subscription/list glm-b":
w.WriteHeader(http.StatusInternalServerError)
case "opencode.ai/zen/go/v1/usage Bearer go-k":
w.Write([]byte(`{"usage":{"rolling":{"percent":5,"resetsAt":"2026-09-25T20:00:00Z"}}}`))
default:
@@ -167,10 +171,11 @@ func TestPlanQuotas(t *testing.T) {
if len(got) != 3 {
t.Fatalf("cards: %+v", got)
}
if q := got["glm/work"]; q.Plan != "pro" || len(q.Windows) != 1 || q.Windows[0].Used != 20 {
if q := got["glm/work"]; q.Plan != "pro" || len(q.Windows) != 1 || q.Windows[0].Used != 20 ||
q.Until == nil || q.Until.UTC().Hour() != 2 || q.Renew != "auto" {
t.Errorf("first key: %+v", q)
}
if q := got["glm/home"]; q.Plan != "lite" || q.Windows[0].Used != 90 {
if q := got["glm/home"]; q.Plan != "lite" || q.Windows[0].Used != 90 || q.Until != nil || q.Error != "" {
t.Errorf("second key: %+v", q)
}
if q := got["go/"]; q.Name != "OpenCode Go" || len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" {
+22 -1
View File
@@ -71,6 +71,10 @@ type Quota struct {
Windows []QuotaSpan `json:"windows"`
Balance string `json:"balance,omitempty"`
Error string `json:"error,omitempty"`
// Until is when the plan's paid time ends, renewed then when Renew is
// "auto", over when "off", either when "".
Until *time.Time `json:"until,omitempty"`
Renew string `json:"renew,omitempty"`
}
// QuotaSpan is one window of an allowance: how much of it is used and
@@ -93,7 +97,7 @@ func QuotaReport(ctx context.Context, now time.Time) []Quota {
}{{"subscription", subs}, {"plan", plans}, {"balance", balances}} {
for _, q := range g.qs {
r := Quota{Provider: q.Provider, Name: q.Name, Kind: g.kind, Plan: q.Plan, User: q.User,
Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error}
Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error, Until: q.Until, Renew: q.Renew}
for _, w := range q.Windows {
s := QuotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display}
if s.ResetsAt == nil && w.ResetSecs > 0 {
@@ -107,3 +111,20 @@ func QuotaReport(ctx context.Context, now time.Time) []Quota {
}
return out
}
// PlanTerm says when a plan's paid time ends, "renews Oct 18", "expires
// Oct 18" or "until Oct 18" when the vendor doesn't say which; "" when
// it isn't known.
func PlanTerm(until *time.Time, renew string) string {
if until == nil {
return ""
}
d := until.Local().Format("Jan 2")
switch renew {
case "auto":
return "renews " + d
case "off":
return "expires " + d
}
return "until " + d
}
+25 -1
View File
@@ -44,7 +44,12 @@ type SubscriptionQuota struct {
User string `json:"user,omitempty"` // the account, so two of one vendor tell apart
Windows []QuotaWindow `json:"windows"`
Balance string `json:"balance,omitempty"` // what is left on an API key, instead of windows
Error string `json:"error,omitempty"`
// Until is when the plan's paid time ends: it renews then when Renew
// is "auto", is over when "off", and either when "" (the vendor
// doesn't say which).
Until *time.Time `json:"until,omitempty"`
Renew string `json:"renew,omitempty"`
Error string `json:"error,omitempty"`
}
var subscriptionUsageCache struct {
@@ -430,12 +435,31 @@ func codexSubscriptionUsage(ctx context.Context, path string) SubscriptionQuota
return q
}
q.Plan, q.Windows, err = codexWindows(ctx, token, accountID)
if b, rerr := os.ReadFile(path); rerr == nil {
q.Until = codexUntil(b, time.Now())
}
if err != nil {
q.Error = err.Error()
}
return q
}
// codexUntil is when the ChatGPT plan of a Codex sign-in (auth.json) is
// paid until, as its id token says: nil when it doesn't, or names a time
// gone by — a token not refreshed since, which says nothing of now.
func codexUntil(auth []byte, now time.Time) *time.Time {
var a codexAuth
if json.Unmarshal(auth, &a) != nil {
return nil
}
s := claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_subscription_active_until")
t, err := time.Parse(time.RFC3339, s)
if err != nil || !t.After(now) {
return nil
}
return &t
}
// codexWindows is the plan and allowance of the ChatGPT account token
// signs in to.
func codexWindows(ctx context.Context, token, accountID string) (plan string, out []QuotaWindow, err error) {
+58
View File
@@ -33,6 +33,7 @@ import (
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
@@ -310,9 +311,66 @@ func zcodeQuota(ctx context.Context, l Login, k zcodeKey) SubscriptionQuota {
}
q.Windows = append(q.Windows, w)
}
q.Until, q.Renew = zhipuTerm(ctx, zcodeRoot(k.Base), k.Key)
return q
}
// zhipuTerm is how long a GLM Coding plan is paid for, from the
// account's subscriptions as ZCode reads them: the valid one's next
// renewal, a charge when it renews itself, else the end of its time — or
// the last date its "valid" span names.
func zhipuTerm(ctx context.Context, root, key string) (*time.Time, string) {
var subs []zhipuSubscription
if zcodeGet(ctx, root+"/api/biz/subscription/list", key, &subs) != nil {
return nil, ""
}
return zhipuTermOf(subs)
}
type zhipuSubscription struct {
Status string `json:"status"`
Valid string `json:"valid"`
AutoRenew any `json:"autoRenew"` // true or 1
NextRenew string `json:"nextRenewTime"`
}
// zhipuDate finds the dates in a span like "2026-09-18 12:00:00-2026-10-18 12:00:00".
var zhipuDate = regexp.MustCompile(`\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?`)
// zhipuTime reads the plan's times, "2026-10-18 12:00:00" in Beijing.
func zhipuTime(s string) *time.Time {
s = strings.Replace(strings.TrimSpace(s), " ", "T", 1)
cst := time.FixedZone("CST", 8*3600)
for _, f := range []string{"2006-01-02T15:04:05", "2006-01-02"} {
if t, err := time.ParseInLocation(f, s, cst); err == nil {
return &t
}
}
return nil
}
func zhipuTermOf(subs []zhipuSubscription) (*time.Time, string) {
for _, s := range subs {
if !strings.EqualFold(s.Status, "VALID") {
continue
}
auto := s.AutoRenew == true || s.AutoRenew == float64(1)
if t := zhipuTime(s.NextRenew); t != nil {
if auto {
return t, "auto"
}
return t, "off"
}
if ds := zhipuDate.FindAllString(s.Valid, -1); len(ds) > 0 && !auto {
if t := zhipuTime(ds[len(ds)-1]); t != nil {
return t, "off"
}
}
return nil, ""
}
return nil, ""
}
// zcodeSpan reads a limit's window: unit 3 counts hours, 6 weeks (and
// 4, 5 days and months by the same count).
func zcodeSpan(unit, n int) time.Duration {
+4
View File
@@ -585,6 +585,10 @@ func quotaLines(qs []provider.SubscriptionQuota, asked, left bool, width int, no
plain += " · " + q.Plan
styled += sMuted.Render(" · " + q.Plan)
}
if t := provider.PlanTerm(q.Until, q.Renew); t != "" {
plain += " · " + t
styled += sFaint.Render(" · " + t)
}
if q.User != "" {
plain += " · " + q.User
styled += sFaint.Render(" · " + q.User)
+3
View File
@@ -78,6 +78,9 @@ func quotaTitle(q provider.Quota) string {
if q.Plan != "" {
t += " · " + q.Plan
}
if s := provider.PlanTerm(q.Until, q.Renew); s != "" {
t += " · " + s
}
if q.User != "" {
t += " · " + q.User
}