From 8903b7b8fbe2e5787861e88453dfb5fb82a3903d Mon Sep 17 00:00:00 2001 From: Silkage Date: Sat, 31 Oct 2026 07:19:58 +0800 Subject: [PATCH] feat: show account credit balances --- README.md | 7 ++-- docs/compatibility.md | 2 ++ internal/app/app.go | 72 ++++++++++++++++++++++++++++++++++---- internal/app/usage_test.go | 38 +++++++++++++++++--- 4 files changed, 106 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 1b263e3..a594754 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,11 @@ shows an error summary in the `ERROR` column, and prints the complete redacted error below the table. The last failure is retained in the local usage cache so `--cached` remains diagnostic after the failing process exits. -The compact list shows the next automatic reset for each quota window. Its +The compact list shows the next automatic reset for each quota window and a +`CREDITS` column with the remaining credit balance when Codex provides it. Its `RESETS` column is separate: it reports earned manual rate-limit resets and the -nearest known expiration, when Codex provides them. `account usage ` -shows exact local reset times plus each returned earned-reset grant and expiry. +nearest known expiration. `account usage ` shows the exact credit balance, +local reset times, and each returned earned-reset grant and expiry. The authoritative earned-reset count can be present even when the service omits or caps its detail rows. diff --git a/docs/compatibility.md b/docs/compatibility.md index 0091f51..6b24f94 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -78,6 +78,8 @@ ignored, the command explicitly overrides `cli_auth_credentials_store` to `file` so the selected profile is read from the isolated temporary home. When returned by `account/rateLimits/read`, the client also preserves +the remaining `credits.balance`, credit availability flags, optional individual +spend-control limits, and `rateLimitResetCredits.availableCount` and its optional grant/expiration detail rows. Older services that omit this optional object remain supported. diff --git a/internal/app/app.go b/internal/app/app.go index 855ed93..195dea0 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -311,7 +311,7 @@ func newAccountListCommand(options *Options) *cobra.Command { return nil } writer := tabwriter.NewWriter(options.Output, 0, 4, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "\tALIAS\tIDENTITY\tPLAN\tLIMITS\tRESETS\tTOKENS\tUPDATED\tERROR") + _, _ = fmt.Fprintln(writer, "\tALIAS\tIDENTITY\tPLAN\tLIMITS\tCREDITS\tRESETS\tTOKENS\tUPDATED\tERROR") for _, view := range views { marker := " " if view.Active { @@ -321,8 +321,8 @@ func newAccountListCommand(options *Options) *cobra.Command { if identity == "" { identity = view.AccountID } - plan, limits, resets, tokens, updated := summarizeUsage(view.Usage, time.Now()) - _, _ = fmt.Fprintf(writer, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", marker, view.Alias, identity, plan, limits, resets, tokens, updated, compactUsageError(view.Usage)) + plan, limits, credits, resets, tokens, updated := summarizeUsage(view.Usage, time.Now()) + _, _ = fmt.Fprintf(writer, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", marker, view.Alias, identity, plan, limits, credits, resets, tokens, updated, compactUsageError(view.Usage)) } if err := writer.Flush(); err != nil { return err @@ -1230,9 +1230,9 @@ func compactUsageError(usage *usageView) string { return value } -func summarizeUsage(usage *usageView, now time.Time) (string, string, string, string, string) { +func summarizeUsage(usage *usageView, now time.Time) (string, string, string, string, string, string) { if usage == nil || usage.Status == "unavailable" { - return "-", "unavailable", "-", "-", "-" + return "-", "unavailable", "-", "-", "-", "-" } plan := usage.PlanType if plan == "" { @@ -1251,6 +1251,7 @@ func summarizeUsage(usage *usageView, now time.Time) (string, string, string, st limits = strings.Join(parts, " · ") } } + credits := compactCredits(mainRateLimit(usage.RateLimits)) resets := compactResetCredits(usage.RateLimits, now) tokens := "-" if usage.TokenUsage != nil && usage.TokenUsage.Summary.LifetimeTokens != nil { @@ -1263,7 +1264,7 @@ func summarizeUsage(usage *usageView, now time.Time) (string, string, string, st if usage.Error != "" { updated += " (error)" } - return plan, limits, resets, tokens, updated + return plan, limits, credits, resets, tokens, updated } func formatUsage(view accountView, now time.Time) string { @@ -1317,6 +1318,7 @@ func formatUsage(view accountView, now time.Time) string { } fmt.Fprintf(&output, "\n %s: %s", label, value) } + formatCredits(&output, mainRateLimit(usage.RateLimits)) formatResetCredits(&output, usage.RateLimits.RateLimitResetCredits, now) } if usage.TokenUsage != nil { @@ -1360,6 +1362,64 @@ func formatUsage(view accountView, now time.Time) string { return output.String() } +func compactCredits(limit *codexusage.RateLimitSnapshot) string { + if limit == nil || limit.Credits == nil { + return "-" + } + credits := limit.Credits + if credits.Unlimited { + return "unlimited" + } + if credits.Balance != nil && strings.TrimSpace(*credits.Balance) != "" { + return formatCreditAmount(*credits.Balance) + } + if credits.HasCredits { + return "available" + } + return "0" +} + +func formatCredits(output *strings.Builder, limit *codexusage.RateLimitSnapshot) { + if limit == nil || limit.Credits == nil { + return + } + credits := limit.Credits + switch { + case credits.Unlimited: + output.WriteString("\nCredits: unlimited") + case credits.Balance != nil && strings.TrimSpace(*credits.Balance) != "": + fmt.Fprintf(output, "\nCredits: %s available", formatCreditAmount(*credits.Balance)) + case credits.HasCredits: + output.WriteString("\nCredits: available; balance not provided") + default: + output.WriteString("\nCredits: none") + } +} + +func formatCreditAmount(value string) string { + value = strings.TrimSpace(value) + parsed, err := strconv.ParseFloat(value, 64) + if err != nil { + return value + } + formatted := strconv.FormatFloat(parsed, 'f', 2, 64) + parts := strings.SplitN(formatted, ".", 2) + integer := parts[0] + sign := "" + if strings.HasPrefix(integer, "-") { + sign = "-" + integer = strings.TrimPrefix(integer, "-") + } + for index := len(integer) - 3; index > 0; index -= 3 { + integer = integer[:index] + "," + integer[index:] + } + fraction := strings.TrimRight(parts[1], "0") + if fraction == "" { + return sign + integer + } + return sign + integer + "." + fraction +} + func mainRateLimit(limits *codexusage.RateLimits) *codexusage.RateLimitSnapshot { if limits == nil { return nil diff --git a/internal/app/usage_test.go b/internal/app/usage_test.go index 7741317..308932f 100644 --- a/internal/app/usage_test.go +++ b/internal/app/usage_test.go @@ -18,6 +18,7 @@ func TestSummarizeUsage(t *testing.T) { secondaryReset := now.Add(3*24*time.Hour + 4*time.Hour).Unix() creditExpiry := now.Add(26 * time.Hour).Unix() lifetime := int64(1_234_567) + balance := "61287.1250" view := &usageView{ Status: "fresh", FetchedAt: now.Add(-10 * time.Second), @@ -26,6 +27,7 @@ func TestSummarizeUsage(t *testing.T) { "codex": { Primary: &codexusage.RateLimitWindow{UsedPercent: 21, WindowDurationMins: &primaryDuration, ResetsAt: &primaryReset}, Secondary: &codexusage.RateLimitWindow{UsedPercent: 81, WindowDurationMins: &secondaryDuration, ResetsAt: &secondaryReset}, + Credits: &codexusage.CreditsSnapshot{HasCredits: true, Balance: &balance}, }, }, RateLimitResetCredits: &codexusage.RateLimitResetCreditsSummary{ AvailableCount: 2, @@ -33,9 +35,9 @@ func TestSummarizeUsage(t *testing.T) { }}, TokenUsage: &codexusage.TokenUsage{Summary: codexusage.TokenUsageSummary{LifetimeTokens: &lifetime}}, } - plan, limits, resets, tokens, updated := summarizeUsage(view, now) - if plan != "pro" || limits != "5h 21% ↻2h 15m · 7d 81% ↻3d 4h" || resets != "2 exp 1d 2h" || tokens != "1.2M" || updated != "just now" { - t.Fatalf("unexpected summary: %q %q %q %q %q", plan, limits, resets, tokens, updated) + plan, limits, credits, resets, tokens, updated := summarizeUsage(view, now) + if plan != "pro" || limits != "5h 21% ↻2h 15m · 7d 81% ↻3d 4h" || credits != "61,287.12" || resets != "2 exp 1d 2h" || tokens != "1.2M" || updated != "just now" { + t.Fatalf("unexpected summary: %q %q %q %q %q %q", plan, limits, credits, resets, tokens, updated) } } @@ -86,6 +88,7 @@ func TestFormatUsageShowsDetailedWindows(t *testing.T) { expires := now.Add(72 * time.Hour).Unix() name := "Codex" title := "Rate-limit reset" + balance := "61287.1250" view := accountView{ Alias: "work", Email: "person@example.com", @@ -96,7 +99,11 @@ func TestFormatUsageShowsDetailedWindows(t *testing.T) { PlanType: "plus", RateLimits: &codexusage.RateLimits{ RateLimitsByLimitID: map[string]codexusage.RateLimitSnapshot{ - "codex": {LimitName: &name, Primary: &codexusage.RateLimitWindow{UsedPercent: 33, WindowDurationMins: &duration, ResetsAt: &reset}}, + "codex": { + LimitName: &name, + Primary: &codexusage.RateLimitWindow{UsedPercent: 33, WindowDurationMins: &duration, ResetsAt: &reset}, + Credits: &codexusage.CreditsSnapshot{HasCredits: true, Balance: &balance}, + }, }, RateLimitResetCredits: &codexusage.RateLimitResetCreditsSummary{ AvailableCount: 2, @@ -116,6 +123,7 @@ func TestFormatUsageShowsDetailedWindows(t *testing.T) { "work (person@example.com) [active]", "Plan: plus", "Codex: 5h 33% used, resets in 2h 15m at " + formatLocalTime(time.Unix(reset, 0)), + "Credits: 61,287.12 available", "Earned resets: 2 available", "Rate-limit reset: available; expires in 3d 0h at " + formatLocalTime(time.Unix(expires, 0)), "granted " + formatLocalTime(time.Unix(granted, 0)), @@ -127,6 +135,28 @@ func TestFormatUsageShowsDetailedWindows(t *testing.T) { } } +func TestCompactCreditsDistinguishesStates(t *testing.T) { + balance := "46476.3720375000" + tests := []struct { + name string + limit *codexusage.RateLimitSnapshot + want string + }{ + {name: "unavailable", want: "-"}, + {name: "none", limit: &codexusage.RateLimitSnapshot{Credits: &codexusage.CreditsSnapshot{}}, want: "0"}, + {name: "available without balance", limit: &codexusage.RateLimitSnapshot{Credits: &codexusage.CreditsSnapshot{HasCredits: true}}, want: "available"}, + {name: "balance", limit: &codexusage.RateLimitSnapshot{Credits: &codexusage.CreditsSnapshot{HasCredits: true, Balance: &balance}}, want: "46,476.37"}, + {name: "unlimited", limit: &codexusage.RateLimitSnapshot{Credits: &codexusage.CreditsSnapshot{Unlimited: true}}, want: "unlimited"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := compactCredits(test.limit); got != test.want { + t.Fatalf("compactCredits() = %q, want %q", got, test.want) + } + }) + } +} + func TestFormatUsageDistinguishesUnavailableResetDetails(t *testing.T) { now := time.Date(2026, 8, 21, 12, 0, 0, 0, time.UTC) view := accountView{Alias: "work", Usage: &usageView{