Files
pipelines/internal/claude/quota.go
T
alan 293474ac3c Chat usage limit: Claude Code-style banner with auto-continue; drop the approaching-limit banner
- The usage-limit banner now reads 'Out of usage credits' (or the refusal's
  own 'You've hit your 5-hour limit'), 'Auto-resuming at <time>', an
  'Auto-continue when limits reset' checkbox and Try again, keeping the
  account switcher's 'Switch to <account>'.
- Auto-continue (a shared, persisted preference, on by default) hands the
  server a durable scheduled prompt (send_at = reset + 1 min) with an
  idempotent auto-continue-<refusal id> operation id: the refused operator
  message again, or 'continue' when the refused turn had already worked.
  Unchecking unqueues it; Try again unqueues it and sends now.
- Remove the approaching-limit banner, its SnackBar announcements and their
  marks; the send-button usage ring replaces them.
- Claude Code's rate_limit_event overage fields (overageStatus,
  isUsingOverage/overageInUse, overageDisabledReason, overageResetsAt) reach
  clients as usage.account.extra_usage; the ring tooltip and the banner say
  'Extra usage available' or 'Using extra usage'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:13:33 +00:00

255 lines
7.9 KiB
Go

package claude
import (
"encoding/json"
"math"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Account quota comes only from what Claude Code already sends: the
// `rate_limit_event` stream-json line (SDKRateLimitEvent, verified against the
// installed CLI 2.1.316's message schema) and the `account` object of the
// initialize control response. Nothing here starts a request or a model call.
//
// rate_limit_info carries the currently limiting window at the top level
// (rateLimitType, utilization 0-1, resetsAt epoch seconds) and, for
// subscription logins, unifiedWindows with every tracked window
// (five_hour, seven_day, seven_day_overage_included). The CLI emits a new
// event whenever a window's rounded percentage, reset, status or threshold
// moves. API-key, Bedrock and Vertex sessions never receive one.
const quotaHarness = "Claude Code"
const quotaSource = "rate_limit_event"
// accountIdentity is the signed-in account a process reported at initialize.
// key is never sent to clients; it only shares quota between sessions.
type accountIdentity struct {
key string
plan string
}
func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
var account struct {
Email string `json:"email"`
Organization string `json:"organization"`
SubscriptionType string `json:"subscriptionType"`
APIProvider string `json:"apiProvider"`
}
if len(raw) == 0 || json.Unmarshal(raw, &account) != nil {
return accountIdentity{}
}
key := strings.TrimSpace(account.Email) + "\x00" + strings.TrimSpace(account.Organization) + "\x00" + account.APIProvider
if strings.Trim(key, "\x00") == "" {
key = ""
}
return accountIdentity{key: key, plan: strings.TrimSpace(account.SubscriptionType)}
}
type rateLimitWindowInfo struct {
Utilization *float64 `json:"utilization"`
ResetsAt *float64 `json:"resetsAt"`
}
type rateLimitInfo struct {
Status string `json:"status"`
ResetsAt *float64 `json:"resetsAt"`
RateLimitType string `json:"rateLimitType"`
Utilization *float64 `json:"utilization"`
UnifiedWindows map[string]*rateLimitWindowInfo `json:"unifiedWindows"`
// Extra usage ("overage"): paid usage credits past the subscription
// limits. Claude Code reports whether they would be accepted, whether
// they are in use and why they are off; nothing here applies them.
OverageStatus string `json:"overageStatus"`
OverageResetsAt *float64 `json:"overageResetsAt"`
OverageDisabledReason string `json:"overageDisabledReason"`
IsUsingOverage *bool `json:"isUsingOverage"`
OverageInUse *bool `json:"overageInUse"`
}
// extraUsage is the event's overage state, or nil when it names none.
func (info rateLimitInfo) extraUsage() *protocol.ChatExtraUsage {
if info.OverageStatus == "" && info.OverageDisabledReason == "" {
return nil
}
inUse := (info.IsUsingOverage != nil && *info.IsUsingOverage) ||
(info.OverageInUse != nil && *info.OverageInUse)
extra := &protocol.ChatExtraUsage{
Status: info.OverageStatus,
InUse: inUse,
DisabledReason: info.OverageDisabledReason,
}
if at := info.OverageResetsAt; at != nil && *at > 0 && !math.IsInf(*at, 0) {
extra.ResetsAt = int64(*at * 1000)
}
return extra
}
// quotaWindowOrder lists the windows Claude Code names, in display order.
var quotaWindowOrder = []struct{ id, label string }{
{"five_hour", "5-hour"},
{"seven_day", "Weekly"},
{"seven_day_opus", "Weekly (Opus)"},
{"seven_day_sonnet", "Weekly (Sonnet)"},
{"seven_day_overage_included", "Weekly (included)"},
}
func quotaWindowLabel(id string) (string, bool) {
for _, w := range quotaWindowOrder {
if w.id == id {
return w.label, true
}
}
return "", false
}
func quotaWindow(id string, utilization, resetsAt *float64) (protocol.ChatQuotaWindow, bool) {
label, ok := quotaWindowLabel(id)
if !ok || utilization == nil || math.IsNaN(*utilization) || math.IsInf(*utilization, 0) || *utilization < 0 {
return protocol.ChatQuotaWindow{}, false
}
w := protocol.ChatQuotaWindow{ID: id, Label: label, UsedPercent: math.Round(*utilization*1000) / 10}
if resetsAt != nil && *resetsAt > 0 && !math.IsInf(*resetsAt, 0) {
w.ResetsAt = int64(*resetsAt * 1000)
}
return w, true
}
// mergeRateLimit folds one rate_limit_info into previous (which may be nil)
// and reports the new snapshot, or nil when the event names no usable window.
// Windows the event does not mention keep their last reported value.
func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, plan string, now time.Time) *protocol.ChatAccountUsage {
var info rateLimitInfo
if len(raw) == 0 || json.Unmarshal(raw, &info) != nil {
return nil
}
windows := map[string]protocol.ChatQuotaWindow{}
if previous != nil {
for _, w := range previous.Windows {
windows[w.ID] = w
}
}
changed := false
if w, ok := quotaWindow(info.RateLimitType, info.Utilization, info.ResetsAt); ok {
windows[w.ID] = w
changed = true
}
for id, window := range info.UnifiedWindows {
if window == nil {
continue
}
if w, ok := quotaWindow(id, window.Utilization, window.ResetsAt); ok {
windows[w.ID] = w
changed = true
}
}
// Overage news alone updates a report that already has windows.
extra := info.extraUsage()
if extra != nil && previous != nil {
changed = true
}
if !changed {
return nil
}
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
if previous != nil {
if next.Plan == "" {
next.Plan = previous.Plan
}
// A switch stays recorded: the refusal it cleared is still in the
// transcript.
next.SwitchedAt = previous.SwitchedAt
if extra == nil && previous.ExtraUsage != nil {
kept := *previous.ExtraUsage
extra = &kept
}
}
next.ExtraUsage = extra
for _, entry := range quotaWindowOrder {
if w, ok := windows[entry.id]; ok {
next.Windows = append(next.Windows, w)
}
}
return next
}
// accountUsage returns a copy of the latest quota for an account key.
func (c *Chat) accountUsage(key string) *protocol.ChatAccountUsage {
if key == "" {
return nil
}
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
return c.quotas[key].Clone()
}
// handleRateLimit records a rate_limit_event for the session's account and
// republishes the latest usage snapshot, with the new quota, to every session
// of that account.
func (s *session) handleRateLimit(raw json.RawMessage) {
s.mu.Lock()
account := s.account
s.mu.Unlock()
key := account.key
if key == "" {
// An account the CLI did not identify still belongs to this session.
key = "session:" + s.id
s.mu.Lock()
s.account.key = key
s.mu.Unlock()
}
c := s.chat
c.quotaMu.Lock()
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
if next == nil {
c.quotaMu.Unlock()
return
}
if c.quotas == nil {
c.quotas = map[string]*protocol.ChatAccountUsage{}
}
c.quotas[key] = next
c.quotaMu.Unlock()
c.mu.Lock()
targets := make([]*session, 0, len(c.sessions))
for _, other := range c.sessions {
targets = append(targets, other)
}
c.mu.Unlock()
if !containsSession(targets, s) {
targets = append(targets, s)
}
for _, target := range targets {
target.mu.Lock()
same := target.account.key == key
target.mu.Unlock()
if same {
target.republishUsage()
}
}
}
func containsSession(list []*session, s *session) bool {
for _, other := range list {
if other == s {
return true
}
}
return false
}
// republishUsage emits the retained token snapshot (or an empty one) so the
// account quota attached by emit reaches watchers without inventing tokens.
func (s *session) republishUsage() {
s.mu.Lock()
usage := &protocol.ChatUsage{}
if s.usage != nil && s.usage.Usage != nil {
copy := *s.usage.Usage
usage = &copy
}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: usage})
}