Files
kandev/apps/backend/internal/agent/usage/host_internal_test.go
T
João Salavisa 55c8b461be feat: surface agent subscription usage in settings and chat tooltip (#1697)
* feat: surface agent subscription usage in settings and chat tooltip

Adds live subscription rate-limit visibility for Claude Code and Codex:

- GET /api/v1/agents/usage lists per-agent utilization windows (plan, percent,
  reset time) for host agents with subscription credentials; ?fresh=true
  bypasses the 5-minute cache with a 15s per-provider clamp.
- Fixes both existing usage clients: Claude parsed float utilization as int
  (decode failure) and now reads the richer limits[] array incl. per-model
  weekly windows; Codex read a nonexistent auth.json field and response
  headers - now reads tokens.access_token, parses the body windows, and
  refreshes OAuth tokens on 401. Token refresh persists without dropping
  unknown credential fields.
- Settings > Agents gains a Subscription Usage section; the chat context
  doughnut tooltip shows the session agent's windows, fetched fresh on hover.
- Shared UsageWindowRows component (bars, Good/High/Critical status,
  reset countdowns) keeps settings, tooltip, and office surfaces consistent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: recompute agent billing type on every read

Subscription billing detection for Claude and Codex was cached with
sync.OnceValue for the process lifetime, so logging in with OAuth after
the backend started never flipped billing badges or office usage checks
until restart. Detection now re-reads the credential files on each call
and reuses the usage clients' HasSubscriptionCredentials checks. Also
adds a regression assertion that fractional-second resets_at timestamps
parse under the RFC3339 layout.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: address subscription usage review feedback

- serialize empty utilization windows as arrays, not null
- sanitize per-agent usage errors in the API (raw provider errors are
  logged server-side; they can carry credential paths/response bodies)
- persist refreshed CLI credentials via atomic temp-file rename
- keep previous settings usage on transient refresh failure; drop stale
  tooltip usage (and its memo) when a fresh fetch fails
- add controller tests for SubscriptionUsage mapping and fresh propagation

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: coalesce concurrent usage fetches and guard codex token refresh

- serialize usage-cache fetches per key with a double-checked lock so
  concurrent fresh requests make one provider call instead of a burst
- reject codex refresh responses with an empty access_token instead of
  persisting them and wiping working credentials
- pin the usage-rows reset fixture 30s under the day boundary so the
  formatted value is deterministic on fast runners

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: coalesce failed usage fetches with short negative caching

Concurrent lookups after a fetch error each retried the provider once
the per-key lock rotated. Failures are now cached for 15 seconds (never
longer than the caller's staleness bound), so bursts share one error
result and the provider gets a breather before the next retry.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: keep stale usage through failed refreshes and skip caching cancellations

Track the last success and last failure independently in the usage
cache: a failed fresh refresh no longer evicts a still-valid success
(non-fresh callers keep the stale value while fresh callers share the
recent error), and a caller-cancelled context no longer records a
negative entry that would penalize other callers.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: synchronize concurrent usage-cache tests with a channel barrier

Replaces the sleep-widened race window in the coalescing tests with a
started/release barrier per the backend testing guidelines, and dedupes
the two concurrent-caller tests into one helper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-15 08:50:21 +01:00

241 lines
7.3 KiB
Go

package usage
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
)
type fakeHostClient struct {
hasCreds bool
usage *ProviderUsage
err error
calls int
}
func (f *fakeHostClient) FetchUsage(_ context.Context) (*ProviderUsage, error) {
f.calls++
return f.usage, f.err
}
func (f *fakeHostClient) HasSubscriptionCredentials() bool { return f.hasCreds }
func TestHostServiceList(t *testing.T) {
now := time.Now()
okUsage := &ProviderUsage{
Provider: "anthropic",
Plan: "max",
Windows: []UtilizationWindow{{Label: "5-hour", UtilizationPct: 42, ResetAt: now}},
FetchedAt: now,
}
noCreds := &fakeHostClient{hasCreds: false}
ok := &fakeHostClient{hasCreds: true, usage: okUsage}
failing := &fakeHostClient{hasCreds: true, err: errors.New("boom")}
svc := &HostService{
cache: NewUsageCache(),
entries: []hostEntry{
{agentID: "claude-acp", cacheKey: "k1", client: noCreds},
{agentID: "codex-acp", cacheKey: "k2", client: ok},
{agentID: "other-acp", cacheKey: "k3", client: failing},
},
}
got := svc.List(context.Background(), false)
if len(got) != 2 {
t.Fatalf("List = %+v, want 2 entries", got)
}
if got[0].AgentID != "codex-acp" || got[0].Usage != okUsage || got[0].Error != "" {
t.Errorf("entry[0] = %+v", got[0])
}
if got[1].AgentID != "other-acp" || got[1].Usage != nil || got[1].Error != hostUsageFetchError {
t.Errorf("entry[1] = %+v", got[1])
}
if noCreds.calls != 0 {
t.Errorf("client without creds was fetched %d times", noCreds.calls)
}
// Second List hits the cache for the successful entry.
_ = svc.List(context.Background(), false)
if ok.calls != 1 {
t.Errorf("expected cached fetch, got %d calls", ok.calls)
}
}
func TestHostServiceList_FreshBypassesStaleCache(t *testing.T) {
now := time.Now()
okUsage := &ProviderUsage{Provider: "anthropic", FetchedAt: now}
ok := &fakeHostClient{hasCreds: true, usage: okUsage}
svc := &HostService{
cache: NewUsageCache(),
entries: []hostEntry{{agentID: "claude-acp", cacheKey: "k1", client: ok}},
}
_ = svc.List(context.Background(), false)
if ok.calls != 1 {
t.Fatalf("initial fetch calls = %d", ok.calls)
}
// Entry is younger than freshMaxAge: fresh serves the cached value.
_ = svc.List(context.Background(), true)
if ok.calls != 1 {
t.Errorf("fresh within clamp should hit cache, calls = %d", ok.calls)
}
// Age the entry past freshMaxAge but below the 5-minute TTL: a normal List
// still serves the cache, a fresh List re-queries the provider.
svc.cache.mu.Lock()
svc.cache.entries["k1"].successAt = now.Add(-freshMaxAge - time.Second)
svc.cache.mu.Unlock()
_ = svc.List(context.Background(), false)
if ok.calls != 1 {
t.Errorf("stale-but-within-TTL cached List should not refetch, calls = %d", ok.calls)
}
_ = svc.List(context.Background(), true)
if ok.calls != 2 {
t.Errorf("fresh List should refetch, calls = %d", ok.calls)
}
}
func TestNewHostServiceRegistersHostAgents(t *testing.T) {
svc := NewHostService(nil)
if len(svc.entries) != 2 {
t.Fatalf("entries = %d, want 2", len(svc.entries))
}
if svc.entries[0].agentID != "claude-acp" || svc.entries[1].agentID != "codex-acp" {
t.Errorf("agent IDs = %q, %q", svc.entries[0].agentID, svc.entries[1].agentID)
}
}
// runCoalescedFetch launches n concurrent GetOrFetchWithin callers whose first
// fetch blocks until every goroutine has been started, maximizing contention
// without sleep-based synchronization. It returns the per-caller results.
func runCoalescedFetch(
t *testing.T,
cache *UsageCache,
n int,
result *ProviderUsage,
fetchErr error,
calls *atomic.Int32,
) {
t.Helper()
release := make(chan struct{})
fetch := func(_ context.Context) (*ProviderUsage, error) {
calls.Add(1)
<-release
return result, fetchErr
}
var started, wg sync.WaitGroup
for range n {
started.Add(1)
wg.Add(1)
go func() {
defer wg.Done()
started.Done()
_, err := cache.GetOrFetchWithin(context.Background(), "k", freshMaxAge, fetch)
if fetchErr == nil && err != nil {
t.Errorf("GetOrFetchWithin: %v", err)
}
if fetchErr != nil && err == nil {
t.Error("expected error from coalesced failing fetch")
}
}()
}
started.Wait()
close(release)
wg.Wait()
}
func TestUsageCacheCoalescesConcurrentFetches(t *testing.T) {
cache := NewUsageCache()
var calls atomic.Int32
runCoalescedFetch(t, cache, 8, &ProviderUsage{Provider: "anthropic", FetchedAt: time.Now()}, nil, &calls)
if got := calls.Load(); got != 1 {
t.Errorf("concurrent misses fetched %d times, want 1", got)
}
}
func TestUsageCacheCoalescesFailures(t *testing.T) {
cache := NewUsageCache()
var calls atomic.Int32
runCoalescedFetch(t, cache, 8, nil, errors.New("boom"), &calls)
if got := calls.Load(); got != 1 {
t.Errorf("concurrent failing fetches called provider %d times, want 1", got)
}
fetch := func(_ context.Context) (*ProviderUsage, error) {
calls.Add(1)
return nil, errors.New("boom")
}
// Once the negative entry ages past failureCacheTTL, the provider is retried.
cache.mu.Lock()
cache.entries["k"].errAt = time.Now().Add(-failureCacheTTL - time.Second)
cache.mu.Unlock()
if _, err := cache.GetOrFetchWithin(context.Background(), "k", freshMaxAge, fetch); err == nil {
t.Error("expected error on retry after TTL")
}
if got := calls.Load(); got != 2 {
t.Errorf("expired failure entry should refetch, calls = %d, want 2", got)
}
}
func TestUsageCacheFailureKeepsStaleSuccess(t *testing.T) {
cache := NewUsageCache()
okUsage := &ProviderUsage{Provider: "anthropic", FetchedAt: time.Now()}
okFetch := func(_ context.Context) (*ProviderUsage, error) { return okUsage, nil }
failFetch := func(_ context.Context) (*ProviderUsage, error) { return nil, errors.New("boom") }
if _, err := cache.GetOrFetchWithin(context.Background(), "k", freshMaxAge, okFetch); err != nil {
t.Fatalf("seed fetch: %v", err)
}
// Age the success past the fresh clamp but within the regular TTL.
cache.mu.Lock()
cache.entries["k"].successAt = time.Now().Add(-freshMaxAge - time.Second)
cache.mu.Unlock()
// A failed fresh refresh returns the error to the fresh caller...
if _, err := cache.GetOrFetchWithin(context.Background(), "k", freshMaxAge, failFetch); err == nil {
t.Fatal("expected error from failed fresh fetch")
}
// ...but must not evict the stale-but-valid success for non-fresh callers.
got, err := cache.GetOrFetchWithin(context.Background(), "k", cacheTTL, failFetch)
if err != nil || got != okUsage {
t.Errorf("stale success was evicted: usage=%v err=%v", got, err)
}
}
func TestUsageCacheDoesNotCacheCancellation(t *testing.T) {
cache := NewUsageCache()
var calls atomic.Int32
fetch := func(ctx context.Context) (*ProviderUsage, error) {
calls.Add(1)
return nil, ctx.Err()
}
cancelled, cancel := context.WithCancel(context.Background())
cancel()
if _, err := cache.GetOrFetchWithin(cancelled, "k", freshMaxAge, fetch); err == nil {
t.Fatal("expected cancellation error")
}
// The cancellation must not have been recorded as a provider failure.
okUsage := &ProviderUsage{Provider: "anthropic", FetchedAt: time.Now()}
got, err := cache.GetOrFetchWithin(context.Background(), "k", freshMaxAge,
func(_ context.Context) (*ProviderUsage, error) { return okUsage, nil })
if err != nil || got != okUsage {
t.Errorf("cancelled fetch poisoned the cache: usage=%v err=%v", got, err)
}
if calls.Load() != 1 {
t.Errorf("fetch calls = %d, want 1", calls.Load())
}
}