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>
138 lines
4.7 KiB
TypeScript
138 lines
4.7 KiB
TypeScript
"use client";
|
|
|
|
import { memo } from "react";
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
|
import { cn } from "@/lib/utils";
|
|
import { UsageWindowRows, usageStatus } from "@/components/usage/usage-window-rows";
|
|
import { useSessionContextWindow } from "@/hooks/domains/session/use-session-context-window";
|
|
import { useSessionAgentUsage } from "@/hooks/domains/session/use-session-agent-usage";
|
|
|
|
type TokenUsageDisplayProps = {
|
|
sessionId: string | null;
|
|
className?: string;
|
|
};
|
|
|
|
/**
|
|
* A context-window report is only trustworthy when we have a positive window
|
|
* size and usage that does not exceed it. `used > size` is impossible for a
|
|
* real window, so it means the agent (via the ACP bridge) reported a stale or
|
|
* wrong `size` (e.g. 200K for a model actually running on the 1M beta window).
|
|
* In that case we hide the indicator instead of showing a confusing >100%.
|
|
* `used === size` (exactly full) is valid and still renders.
|
|
*/
|
|
export function isContextWindowReliable(size: number, used: number): boolean {
|
|
return size > 0 && used <= size;
|
|
}
|
|
|
|
function formatNumber(num: number): string {
|
|
if (num >= 1_000_000) {
|
|
return `${(num / 1_000_000).toFixed(1)}M`;
|
|
}
|
|
if (num >= 1_000) {
|
|
return `${(num / 1_000).toFixed(1)}K`;
|
|
}
|
|
return num.toLocaleString();
|
|
}
|
|
|
|
function getCircleColor(efficiency: number): string {
|
|
if (efficiency >= 90) return "text-yellow-500";
|
|
if (efficiency >= 75) return "text-yellow-300";
|
|
if (efficiency >= 50) return "text-blue-500";
|
|
return "text-blue-300";
|
|
}
|
|
|
|
/**
|
|
* Subscription utilization rows for the session's agent, rendered inside the
|
|
* doughnut tooltip. Mounted only while the tooltip is open, so each hover
|
|
* triggers a fresh provider fetch (server-clamped to one per 15 s).
|
|
*/
|
|
function SessionUsageRows({ sessionId }: { sessionId: string | null }) {
|
|
const agentUsage = useSessionAgentUsage(sessionId);
|
|
const usage = agentUsage?.usage;
|
|
if (!usage || usage.windows.length === 0) return null;
|
|
const status = usageStatus(usage);
|
|
|
|
return (
|
|
<div
|
|
className="pt-2 mt-2 border-t border-border/60 space-y-2 min-w-56"
|
|
data-testid="doughnut-subscription-usage"
|
|
>
|
|
<div className="flex items-center justify-between gap-4">
|
|
<span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
|
|
Subscription usage{usage.plan ? ` · ${usage.plan}` : ""}
|
|
</span>
|
|
<span className={cn("text-[10px] font-semibold", status.className)}>{status.label}</span>
|
|
</div>
|
|
<UsageWindowRows usage={usage} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export const TokenUsageDisplay = memo(function TokenUsageDisplay({
|
|
sessionId,
|
|
className,
|
|
}: TokenUsageDisplayProps) {
|
|
const contextWindow = useSessionContextWindow(sessionId);
|
|
|
|
if (!contextWindow) return null;
|
|
|
|
const { size, used } = contextWindow;
|
|
|
|
// Hide when there's no data yet (size 0) or the report is impossible
|
|
// (used > size) — see isContextWindowReliable.
|
|
if (!isContextWindowReliable(size, used)) return null;
|
|
|
|
const usagePercent = (used / size) * 100;
|
|
const progress = usagePercent / 100;
|
|
|
|
// SVG circle parameters
|
|
const radius = 10;
|
|
const strokeWidth = 2.5;
|
|
const circumference = 2 * Math.PI * radius;
|
|
const strokeDashoffset = circumference * (1 - progress);
|
|
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<div className={cn("flex items-center gap-2 cursor-help", className)}>
|
|
<div className="relative flex items-center justify-center">
|
|
<svg viewBox="0 0 24 24" className="w-5 h-5 -rotate-90" aria-hidden="true">
|
|
{/* Background circle */}
|
|
<circle
|
|
cx="12"
|
|
cy="12"
|
|
r={radius}
|
|
fill="none"
|
|
stroke="currentColor"
|
|
strokeWidth={strokeWidth}
|
|
className="text-muted"
|
|
/>
|
|
{/* Progress circle */}
|
|
<circle
|
|
cx="12"
|
|
cy="12"
|
|
r={radius}
|
|
fill="none"
|
|
stroke="currentColor"
|
|
strokeWidth={strokeWidth}
|
|
strokeLinecap="round"
|
|
strokeDasharray={circumference}
|
|
strokeDashoffset={strokeDashoffset}
|
|
className={cn(getCircleColor(usagePercent), "transition-all duration-300 ease-out")}
|
|
/>
|
|
</svg>
|
|
</div>
|
|
</div>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="top">
|
|
<div className="text-xs space-y-1">
|
|
<div className="font-medium">
|
|
{usagePercent.toFixed(0)}% ({formatNumber(used)} / {formatNumber(size)})
|
|
</div>
|
|
<SessionUsageRows sessionId={sessionId} />
|
|
</div>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
);
|
|
});
|