Chat info: account quota per harness (Claude rate_limit_event, Codex account/rateLimits, OpenCode unsupported)
Usage frames carry optional usage.account {harness, source, plan, as_of,
windows[{id,label,used_percent,resets_at}], unsupported}. Claude Code quota
comes from its rate_limit_event stream lines and the initialize account
(plan), shared across chats on the same account. Codex reads
account/rateLimits/read once per connection (re-read when a chat opens after
5 min) and merges account/rateLimits/updated. OpenCode exposes no quota API
and says so. The app's chat info sheet shows an Account usage section with a
progress bar and reset countdown per window, Material and Cupertino.
This commit is contained in:
+29
-1
@@ -68,6 +68,12 @@ type Chat struct {
|
||||
usage map[string]usageSnapshot
|
||||
usageOrder uint64
|
||||
modes map[string]string
|
||||
|
||||
// Account quota (quota.go): merged native snapshot and the read schedule.
|
||||
quota *quotaState
|
||||
accountReads bool
|
||||
accountReading bool
|
||||
accountReadAt time.Time
|
||||
}
|
||||
|
||||
type pendingForm struct {
|
||||
@@ -139,6 +145,10 @@ func Open(ctx context.Context) (*Chat, error) {
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("initialize Codex app-server: %w", err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.accountReads = true
|
||||
c.mu.Unlock()
|
||||
c.readAccountRateLimits()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -279,6 +289,11 @@ func (c *Chat) respond(id json.RawMessage, result any) {
|
||||
|
||||
func (c *Chat) emit(frame protocol.ChatEventFrame) {
|
||||
c.mu.Lock()
|
||||
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil {
|
||||
usage := *frame.Usage
|
||||
usage.Account = c.accountLocked()
|
||||
frame.Usage = &usage
|
||||
}
|
||||
if frame.Kind == protocol.ChatEventUsage && !c.retainUsageLocked(frame) {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
@@ -343,12 +358,21 @@ func (c *Chat) subscribe(id string) chan protocol.ChatEventFrame {
|
||||
}
|
||||
c.subs[id][ch] = struct{}{}
|
||||
if snapshot, ok := c.usage[id]; ok {
|
||||
ch <- snapshot.frame
|
||||
frame := snapshot.frame
|
||||
if frame.Usage != nil {
|
||||
usage := *frame.Usage
|
||||
usage.Account = c.accountLocked()
|
||||
frame.Usage = &usage
|
||||
}
|
||||
ch <- frame
|
||||
} else if account := c.accountLocked(); account != nil {
|
||||
ch <- protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Account: account}}
|
||||
}
|
||||
if frame, ok := c.compactions[id]; ok {
|
||||
ch <- frame
|
||||
}
|
||||
c.mu.Unlock()
|
||||
c.readAccountRateLimits()
|
||||
return ch
|
||||
}
|
||||
|
||||
@@ -764,6 +788,10 @@ func (c *Chat) handleNotification(msg rpcMessage) {
|
||||
c.receiveUsage(msg.Params)
|
||||
return
|
||||
}
|
||||
if msg.Method == "account/rateLimits/updated" {
|
||||
c.receiveRateLimits(msg.Params)
|
||||
return
|
||||
}
|
||||
if msg.Method == "serverRequest/resolved" {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Account quota, verified against the App Server schema generated by the
|
||||
// installed codex-cli 0.164.0 (`codex app-server generate-ts`):
|
||||
// v2/GetAccountRateLimitsResponse.ts, RateLimitSnapshot.ts, RateLimitWindow.ts,
|
||||
// AccountRateLimitsUpdatedNotification.ts and PlanType.ts.
|
||||
//
|
||||
// `account/rateLimits/read` is an account read, not a model call; it runs once
|
||||
// per connection and again only when a chat is opened after the cached copy is
|
||||
// older than accountReadInterval. `account/rateLimits/updated` is a sparse
|
||||
// rolling update that the App Server pushes itself; it is merged into the
|
||||
// latest read, and a null field never clears a known value.
|
||||
|
||||
const accountReadInterval = 5 * time.Minute
|
||||
const accountReadTimeout = 10 * time.Second
|
||||
|
||||
type rateLimitWindow struct {
|
||||
UsedPercent *float64 `json:"usedPercent"`
|
||||
WindowDurationMins *int64 `json:"windowDurationMins"`
|
||||
ResetsAt *int64 `json:"resetsAt"`
|
||||
}
|
||||
|
||||
type rateLimitSnapshot struct {
|
||||
LimitID *string `json:"limitId"`
|
||||
Primary *rateLimitWindow `json:"primary"`
|
||||
Secondary *rateLimitWindow `json:"secondary"`
|
||||
PlanType *string `json:"planType"`
|
||||
}
|
||||
|
||||
// quotaState is the merged native snapshot behind the published quota.
|
||||
type quotaState struct {
|
||||
limitID string
|
||||
primary *rateLimitWindow
|
||||
secondary *rateLimitWindow
|
||||
plan string
|
||||
asOf time.Time
|
||||
}
|
||||
|
||||
// windowLabel names a window by its native duration: "5-hour", "Weekly".
|
||||
func windowLabel(minutes *int64, fallback string) string {
|
||||
if minutes == nil || *minutes <= 0 {
|
||||
return fallback
|
||||
}
|
||||
m := *minutes
|
||||
switch {
|
||||
case m == 7*24*60:
|
||||
return "Weekly"
|
||||
case m == 24*60:
|
||||
return "Daily"
|
||||
case m%(24*60) == 0:
|
||||
return fmt.Sprintf("%d-day", m/(24*60))
|
||||
case m%60 == 0:
|
||||
return fmt.Sprintf("%d-hour", m/60)
|
||||
default:
|
||||
return fmt.Sprintf("%d-minute", m)
|
||||
}
|
||||
}
|
||||
|
||||
func quotaWindow(id, fallback string, w *rateLimitWindow) (protocol.ChatQuotaWindow, bool) {
|
||||
if w == nil || w.UsedPercent == nil || math.IsNaN(*w.UsedPercent) || math.IsInf(*w.UsedPercent, 0) || *w.UsedPercent < 0 {
|
||||
return protocol.ChatQuotaWindow{}, false
|
||||
}
|
||||
out := protocol.ChatQuotaWindow{ID: id, Label: windowLabel(w.WindowDurationMins, fallback), UsedPercent: *w.UsedPercent}
|
||||
if w.ResetsAt != nil && *w.ResetsAt > 0 {
|
||||
// RateLimitWindow.resetsAt is Unix seconds (codex-rs RateLimitWindow).
|
||||
out.ResetsAt = *w.ResetsAt * 1000
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// merge folds a (possibly sparse) snapshot into the state and reports whether
|
||||
// anything usable changed. A snapshot for another metered limit is ignored.
|
||||
func (q *quotaState) merge(s *rateLimitSnapshot, now time.Time) bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
if s.LimitID != nil && *s.LimitID != "" {
|
||||
if q.limitID != "" && q.limitID != *s.LimitID {
|
||||
return false
|
||||
}
|
||||
q.limitID = *s.LimitID
|
||||
}
|
||||
changed := false
|
||||
if s.Primary != nil && s.Primary.UsedPercent != nil {
|
||||
q.primary, changed = s.Primary, true
|
||||
}
|
||||
if s.Secondary != nil && s.Secondary.UsedPercent != nil {
|
||||
q.secondary, changed = s.Secondary, true
|
||||
}
|
||||
if s.PlanType != nil && *s.PlanType != "" && *s.PlanType != "unknown" {
|
||||
changed = changed || q.plan != *s.PlanType
|
||||
q.plan = *s.PlanType
|
||||
}
|
||||
if changed {
|
||||
q.asOf = now
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func (q *quotaState) account() *protocol.ChatAccountUsage {
|
||||
if q == nil {
|
||||
return nil
|
||||
}
|
||||
out := &protocol.ChatAccountUsage{Harness: "Codex", Source: "account/rateLimits", Plan: q.plan, AsOf: q.asOf.UnixMilli()}
|
||||
if w, ok := quotaWindow("primary", "Primary", q.primary); ok {
|
||||
out.Windows = append(out.Windows, w)
|
||||
}
|
||||
if w, ok := quotaWindow("secondary", "Secondary", q.secondary); ok {
|
||||
out.Windows = append(out.Windows, w)
|
||||
}
|
||||
if len(out.Windows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// accountLocked is the published quota. Called under mu.
|
||||
func (c *Chat) accountLocked() *protocol.ChatAccountUsage {
|
||||
return c.quota.account()
|
||||
}
|
||||
|
||||
// readAccountRateLimits performs the one cheap native read, when due. It never
|
||||
// runs on the reader goroutine (call waits on a response the reader delivers).
|
||||
func (c *Chat) readAccountRateLimits() {
|
||||
c.mu.Lock()
|
||||
due := c.accountReads && !c.closed && !c.accountReading && time.Since(c.accountReadAt) >= accountReadInterval
|
||||
if due {
|
||||
c.accountReading = true
|
||||
c.accountReadAt = time.Now()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !due {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
c.accountReading = false
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(c.ctx, accountReadTimeout)
|
||||
defer cancel()
|
||||
raw, err := c.call(ctx, "account/rateLimits/read", map[string]any{"excludeResetCreditDetails": true})
|
||||
if err != nil {
|
||||
return // API-key logins and older servers have no quota; stay unknown
|
||||
}
|
||||
var reply struct {
|
||||
RateLimits *rateLimitSnapshot `json:"rateLimits"`
|
||||
}
|
||||
if json.Unmarshal(raw, &reply) == nil {
|
||||
c.applyRateLimits(reply.RateLimits)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *Chat) receiveRateLimits(raw json.RawMessage) {
|
||||
var p struct {
|
||||
RateLimits *rateLimitSnapshot `json:"rateLimits"`
|
||||
}
|
||||
if json.Unmarshal(raw, &p) == nil {
|
||||
c.applyRateLimits(p.RateLimits)
|
||||
}
|
||||
}
|
||||
|
||||
// applyRateLimits merges a snapshot and republishes every watched or retained
|
||||
// session's usage with the new quota. Token figures are never invented: a
|
||||
// session without a token snapshot gets an account-only frame.
|
||||
func (c *Chat) applyRateLimits(s *rateLimitSnapshot) {
|
||||
c.mu.Lock()
|
||||
if c.quota == nil {
|
||||
c.quota = "aState{}
|
||||
}
|
||||
if !c.quota.merge(s, time.Now()) {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for id := range c.subs {
|
||||
ids[id] = true
|
||||
}
|
||||
for id := range c.usage {
|
||||
ids[id] = true
|
||||
}
|
||||
frames := make([]protocol.ChatEventFrame, 0, len(ids))
|
||||
for id := range ids {
|
||||
usage := &protocol.ChatUsage{}
|
||||
if snapshot, ok := c.usage[id]; ok && snapshot.frame.Usage != nil {
|
||||
copy := *snapshot.frame.Usage
|
||||
usage = ©
|
||||
}
|
||||
frames = append(frames, protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventUsage, Usage: usage})
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, frame := range frames {
|
||||
c.emit(frame)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func waitAccount(t *testing.T, ch <-chan protocol.ChatEventFrame) protocol.ChatEventFrame {
|
||||
t.Helper()
|
||||
deadline := time.After(5 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case frame := <-ch:
|
||||
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil {
|
||||
return frame
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("no account usage frame")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRateLimitsReadOnceAndMergeSparseUpdates(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
reads := 0
|
||||
chat := modelTestChat(t, func(method string, raw json.RawMessage) any {
|
||||
if method != "account/rateLimits/read" {
|
||||
t.Errorf("unexpected method %s", method)
|
||||
return &rpcError{Code: -32601, Message: "unexpected"}
|
||||
}
|
||||
var params map[string]any
|
||||
if json.Unmarshal(raw, ¶ms) != nil || params["excludeResetCreditDetails"] != true {
|
||||
t.Errorf("read params = %s", raw)
|
||||
}
|
||||
mu.Lock()
|
||||
reads++
|
||||
mu.Unlock()
|
||||
return json.RawMessage(modelFixture(t, "account-rate-limits-read"))
|
||||
})
|
||||
chat.accountReads = true
|
||||
ch := chat.subscribe(fixtureThread)
|
||||
read := waitAccount(t, ch)
|
||||
want := []protocol.ChatQuotaWindow{
|
||||
{ID: "primary", Label: "5-hour", UsedPercent: 37, ResetsAt: 1_900_000_000_000},
|
||||
{ID: "secondary", Label: "Weekly", UsedPercent: 12, ResetsAt: 1_900_500_000_000},
|
||||
}
|
||||
account := read.Usage.Account
|
||||
if account.Harness != "Codex" || account.Plan != "plus" || account.Source != "account/rateLimits" || account.AsOf <= 0 || !reflect.DeepEqual(account.Windows, want) {
|
||||
t.Fatalf("read account = %+v", account)
|
||||
}
|
||||
if read.Usage.Scope != "" || read.Usage.TotalTokens != nil {
|
||||
t.Fatalf("account-only frame invented token usage: %+v", read.Usage)
|
||||
}
|
||||
|
||||
// The sparse update moves the 5-hour window and keeps the weekly one and
|
||||
// the plan, and the token snapshot that follows carries the merged quota.
|
||||
var update rpcMessage
|
||||
if err := json.Unmarshal(modelFixture(t, "account-rate-limits-updated"), &update); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat.handleNotification(update)
|
||||
merged := waitAccount(t, ch).Usage.Account
|
||||
if merged.Plan != "plus" || len(merged.Windows) != 2 || merged.Windows[0].UsedPercent != 41 || merged.Windows[1].UsedPercent != 12 {
|
||||
t.Fatalf("merged account = %+v", merged)
|
||||
}
|
||||
chat.receiveUsage(json.RawMessage(`{"threadId":"` + fixtureThread + `","tokenUsage":{"total":{"totalTokens":5},"last":{}}}`))
|
||||
tokens := waitAccount(t, ch).Usage
|
||||
if tokens.TotalTokens == nil || *tokens.TotalTokens != 5 || tokens.Account.Windows[0].UsedPercent != 41 {
|
||||
t.Fatalf("token usage = %+v", tokens)
|
||||
}
|
||||
|
||||
// Another metered limit's update is not this account's codex quota.
|
||||
chat.handleNotification(rpcMessage{Method: "account/rateLimits/updated", Params: json.RawMessage(`{"rateLimits":{"limitId":"other","primary":{"usedPercent":99,"windowDurationMins":300,"resetsAt":null}}}`)})
|
||||
// A second subscriber within the interval replays the cache, no new read.
|
||||
second := chat.subscribe(fixtureThread)
|
||||
replayed := waitAccount(t, second).Usage
|
||||
if replayed.Account.Windows[0].UsedPercent != 41 || replayed.TotalTokens == nil {
|
||||
t.Fatalf("replay = %+v", replayed)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if reads != 1 {
|
||||
t.Fatalf("account reads = %d, want 1", reads)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRateLimitsUnknownStaysHidden(t *testing.T) {
|
||||
chat := usageTestChat()
|
||||
ch := chat.subscribe("thread")
|
||||
// A failed/absent read leaves no quota, and an update without windows adds none.
|
||||
chat.receiveRateLimits(json.RawMessage(`{"rateLimits":{"limitId":null,"primary":null,"secondary":null,"planType":"unknown"}}`))
|
||||
chat.receiveRateLimits(json.RawMessage(`not json`))
|
||||
if len(ch) != 0 {
|
||||
t.Fatalf("unknown quota published: %+v", <-ch)
|
||||
}
|
||||
if got := windowLabel(nil, "Primary"); got != "Primary" {
|
||||
t.Fatalf("label without duration = %q", got)
|
||||
}
|
||||
for minutes, want := range map[int64]string{300: "5-hour", 10080: "Weekly", 1440: "Daily", 4320: "3-day", 45: "45-minute"} {
|
||||
if got := windowLabel(&minutes, ""); got != want {
|
||||
t.Fatalf("label(%d) = %q, want %q", minutes, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -42,3 +42,14 @@ before `turn/start`. Files retain the existing attachment-store retention rules.
|
||||
History keeps local file/image parts; native image parts use the stored basename
|
||||
while a companion text input retains the original display name.
|
||||
All wire tests use fake JSON-RPC servers, never the production control socket.
|
||||
|
||||
## Account rate limits
|
||||
|
||||
`account-rate-limits-read.json` (an `account/rateLimits/read` result) and
|
||||
`account-rate-limits-updated.json` (an `account/rateLimits/updated`
|
||||
notification) follow the schema generated by the installed codex-cli 0.164.0
|
||||
(`codex app-server generate-ts`: `v2/GetAccountRateLimitsResponse.ts`,
|
||||
`RateLimitSnapshot.ts`, `RateLimitWindow.ts`,
|
||||
`AccountRateLimitsUpdatedNotification.ts`). Numbers are synthetic. `resetsAt`
|
||||
is Unix seconds; `usedPercent` is 0-100. The update is sparse: null fields keep
|
||||
the previously read values.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"ordinaryUsageAllowed": true,
|
||||
"rateLimits": {
|
||||
"limitId": "codex",
|
||||
"limitName": null,
|
||||
"normalModelSlug": null,
|
||||
"primary": {"usedPercent": 37, "windowDurationMins": 300, "resetsAt": 1900000000},
|
||||
"secondary": {"usedPercent": 12, "windowDurationMins": 10080, "resetsAt": 1900500000},
|
||||
"credits": {"hasCredits": false, "unlimited": false, "balance": null},
|
||||
"individualLimit": null,
|
||||
"spendControlReached": null,
|
||||
"planType": "plus",
|
||||
"rateLimitReachedType": null
|
||||
},
|
||||
"rateLimitsByLimitId": null,
|
||||
"rateLimitResetCredits": null,
|
||||
"accountId": null,
|
||||
"rateLimitUpsell": null
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"method": "account/rateLimits/updated",
|
||||
"params": {
|
||||
"rateLimits": {
|
||||
"limitId": "codex",
|
||||
"limitName": null,
|
||||
"normalModelSlug": null,
|
||||
"primary": {"usedPercent": 41, "windowDurationMins": 300, "resetsAt": 1900000000},
|
||||
"secondary": null,
|
||||
"credits": null,
|
||||
"individualLimit": null,
|
||||
"spendControlReached": null,
|
||||
"planType": null,
|
||||
"rateLimitReachedType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user