55c8b461be
* 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>
92 lines
2.8 KiB
Go
92 lines
2.8 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/kandev/kandev/internal/agent/agents"
|
|
agentusage "github.com/kandev/kandev/internal/agent/usage"
|
|
)
|
|
|
|
type fakeHostUsageLister struct {
|
|
entries []agentusage.HostAgentUsage
|
|
lastFresh bool
|
|
calls int
|
|
}
|
|
|
|
func (f *fakeHostUsageLister) List(_ context.Context, fresh bool) []agentusage.HostAgentUsage {
|
|
f.calls++
|
|
f.lastFresh = fresh
|
|
return f.entries
|
|
}
|
|
|
|
func TestControllerSubscriptionUsage_NoLister(t *testing.T) {
|
|
ctrl := newTestController(map[string]agents.Agent{})
|
|
|
|
resp := ctrl.SubscriptionUsage(context.Background(), false)
|
|
|
|
if resp == nil || resp.Agents == nil {
|
|
t.Fatalf("expected non-nil response with empty agents, got %+v", resp)
|
|
}
|
|
if len(resp.Agents) != 0 {
|
|
t.Fatalf("expected empty listing without a lister, got %+v", resp.Agents)
|
|
}
|
|
}
|
|
|
|
func TestControllerSubscriptionUsage_MapsEntries(t *testing.T) {
|
|
ctrl := newTestController(map[string]agents.Agent{
|
|
"claude-acp": &testAgent{id: "claude-acp", name: "claude-acp", displayName: "Claude", enabled: true},
|
|
})
|
|
now := time.Now()
|
|
usage := &agentusage.ProviderUsage{
|
|
Provider: "anthropic",
|
|
Plan: "max",
|
|
Windows: []agentusage.UtilizationWindow{{Label: "5-hour", UtilizationPct: 42, ResetAt: now}},
|
|
FetchedAt: now,
|
|
}
|
|
lister := &fakeHostUsageLister{entries: []agentusage.HostAgentUsage{
|
|
{AgentID: "claude-acp", Usage: usage},
|
|
{AgentID: "unknown-acp", Error: "failed to fetch usage from provider"},
|
|
}}
|
|
ctrl.SetHostUsageLister(lister)
|
|
|
|
resp := ctrl.SubscriptionUsage(context.Background(), false)
|
|
|
|
if len(resp.Agents) != 2 {
|
|
t.Fatalf("agents = %+v, want 2 entries", resp.Agents)
|
|
}
|
|
// Registry display-name lookup for known agents.
|
|
if resp.Agents[0].AgentID != "claude-acp" || resp.Agents[0].DisplayName != "Claude" {
|
|
t.Errorf("entry[0] = %+v", resp.Agents[0])
|
|
}
|
|
if resp.Agents[0].Usage != usage || resp.Agents[0].Error != "" {
|
|
t.Errorf("entry[0] usage/error = %+v", resp.Agents[0])
|
|
}
|
|
// Unknown agents fall back to the agent ID and forward the error.
|
|
if resp.Agents[1].DisplayName != "unknown-acp" || resp.Agents[1].Error == "" {
|
|
t.Errorf("entry[1] = %+v", resp.Agents[1])
|
|
}
|
|
if resp.Agents[1].Usage != nil {
|
|
t.Errorf("entry[1] usage = %+v, want nil", resp.Agents[1].Usage)
|
|
}
|
|
}
|
|
|
|
func TestControllerSubscriptionUsage_PropagatesFresh(t *testing.T) {
|
|
ctrl := newTestController(map[string]agents.Agent{})
|
|
lister := &fakeHostUsageLister{}
|
|
ctrl.SetHostUsageLister(lister)
|
|
|
|
_ = ctrl.SubscriptionUsage(context.Background(), true)
|
|
if !lister.lastFresh {
|
|
t.Error("fresh=true was not propagated to the lister")
|
|
}
|
|
_ = ctrl.SubscriptionUsage(context.Background(), false)
|
|
if lister.lastFresh {
|
|
t.Error("fresh=false was not propagated to the lister")
|
|
}
|
|
if lister.calls != 2 {
|
|
t.Errorf("lister calls = %d, want 2", lister.calls)
|
|
}
|
|
}
|