Files
kandev/apps/backend/internal/agent/usage/host.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

107 lines
3.1 KiB
Go

package usage
import (
"context"
"os"
"path/filepath"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/logger"
)
// freshMaxAge clamps fresh (hover-triggered) fetches: a provider is queried
// again at most every 15 s even when callers keep requesting fresh data.
const freshMaxAge = 15 * time.Second
// hostUsageFetchError is the sanitized per-agent error surfaced through the
// API. Raw provider errors can contain credential paths and response bodies,
// so those are only logged server-side.
const hostUsageFetchError = "failed to fetch usage from provider"
// HostAgentUsage is one host-installed subscription agent's usage entry.
type HostAgentUsage struct {
AgentID string `json:"agent_id"`
Usage *ProviderUsage `json:"usage,omitempty"`
Error string `json:"error,omitempty"`
}
// hostUsageClient is a ProviderUsageClient that can also report whether
// subscription credentials are present on disk.
type hostUsageClient interface {
ProviderUsageClient
HasSubscriptionCredentials() bool
}
type hostEntry struct {
agentID string
cacheKey string
client hostUsageClient
}
// HostService lists subscription utilization for agent CLIs installed on the
// kandev host (Claude Code, Codex). Agents without subscription credentials
// are omitted from List results.
type HostService struct {
cache *UsageCache
entries []hostEntry
logger *logger.Logger
}
// NewHostService builds a HostService reading credentials from the current
// user's home directory. The service is empty when the home dir is unavailable.
func NewHostService(log *logger.Logger) *HostService {
s := &HostService{cache: NewUsageCache(), logger: log}
home, err := os.UserHomeDir()
if err != nil {
return s
}
claudePath := filepath.Join(home, ".claude", ".credentials.json")
codexPath := filepath.Join(home, ".codex", "auth.json")
s.entries = []hostEntry{
{
agentID: "claude-acp",
cacheKey: CacheKey("anthropic", claudePath),
client: NewClaudeUsageClientWithPath(claudePath),
},
{
agentID: "codex-acp",
cacheKey: CacheKey("openai", codexPath),
client: NewCodexUsageClientWithPath(codexPath),
},
}
return s
}
// List returns usage for every host agent that has subscription credentials.
// With fresh=false cached results up to 5 minutes old are served; fresh=true
// re-queries the providers, bounded by freshMaxAge. Fetch failures are
// reported per-agent via the Error field rather than failing the whole listing.
func (s *HostService) List(ctx context.Context, fresh bool) []HostAgentUsage {
maxAge := cacheTTL
if fresh {
maxAge = freshMaxAge
}
out := make([]HostAgentUsage, 0, len(s.entries))
for _, e := range s.entries {
if !e.client.HasSubscriptionCredentials() {
continue
}
entry := HostAgentUsage{AgentID: e.agentID}
u, err := s.cache.GetOrFetchWithin(ctx, e.cacheKey, maxAge, e.client.FetchUsage)
switch {
case err != nil:
if s.logger != nil {
s.logger.Warn("subscription usage fetch failed",
zap.String("agent", e.agentID), zap.Error(err))
}
entry.Error = hostUsageFetchError
default:
entry.Usage = u
}
out = append(out, entry)
}
return out
}