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>
112 lines
3.3 KiB
TypeScript
112 lines
3.3 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
||
import { cleanup, render } from "@testing-library/react";
|
||
import {
|
||
UsageWindowRows,
|
||
formatResetShort,
|
||
shortWindowLabel,
|
||
usageStatus,
|
||
} from "./usage-window-rows";
|
||
import type { ProviderUsage } from "@/lib/types/agent-profile";
|
||
|
||
afterEach(cleanup);
|
||
|
||
describe("shortWindowLabel", () => {
|
||
it("shortens hour and day windows", () => {
|
||
expect(shortWindowLabel("5-hour")).toBe("5h");
|
||
expect(shortWindowLabel("7-day")).toBe("7d");
|
||
expect(shortWindowLabel("30-day")).toBe("30d");
|
||
expect(shortWindowLabel("7-day (Opus)")).toBe("7d (Opus)");
|
||
});
|
||
|
||
it("leaves unknown labels untouched", () => {
|
||
expect(shortWindowLabel("primary")).toBe("primary");
|
||
});
|
||
});
|
||
|
||
describe("formatResetShort", () => {
|
||
const now = Date.UTC(2026, 6, 14, 12, 0, 0);
|
||
|
||
it("formats minutes", () => {
|
||
expect(formatResetShort(new Date(now + 42 * 60_000).toISOString(), now)).toBe("42m");
|
||
});
|
||
|
||
it("formats hours and minutes", () => {
|
||
expect(formatResetShort(new Date(now + 3 * 3_600_000 + 17 * 60_000).toISOString(), now)).toBe(
|
||
"3h 17m",
|
||
);
|
||
});
|
||
|
||
it("formats days and hours", () => {
|
||
expect(formatResetShort(new Date(now + 29 * 3_600_000).toISOString(), now)).toBe("1d 5h");
|
||
});
|
||
|
||
it("handles past reset times", () => {
|
||
expect(formatResetShort(new Date(now - 60_000).toISOString(), now)).toBe("soon");
|
||
});
|
||
|
||
it("handles invalid timestamps", () => {
|
||
expect(formatResetShort("not-a-date", now)).toBe("soon");
|
||
});
|
||
});
|
||
|
||
function makeUsage(pcts: number[]): ProviderUsage {
|
||
return {
|
||
provider: "anthropic",
|
||
plan: "max",
|
||
windows: pcts.map((pct, i) => ({
|
||
label: `${i + 1}-day`,
|
||
utilization_pct: pct,
|
||
reset_at: new Date(Date.now() + 3_600_000).toISOString(),
|
||
})),
|
||
fetched_at: new Date().toISOString(),
|
||
};
|
||
}
|
||
|
||
describe("usageStatus", () => {
|
||
it("is Good below 80%", () => {
|
||
expect(usageStatus(makeUsage([10, 79])).label).toBe("Good");
|
||
});
|
||
|
||
it("is High at 80–89%", () => {
|
||
expect(usageStatus(makeUsage([10, 85])).label).toBe("High");
|
||
});
|
||
|
||
it("is Critical at 90%+", () => {
|
||
expect(usageStatus(makeUsage([10, 94])).label).toBe("Critical");
|
||
});
|
||
});
|
||
|
||
describe("UsageWindowRows", () => {
|
||
it("renders a colored bar, percentage, and reset time per window", () => {
|
||
const usage: ProviderUsage = {
|
||
provider: "anthropic",
|
||
plan: "max",
|
||
windows: [
|
||
{
|
||
label: "5-hour",
|
||
utilization_pct: 94,
|
||
reset_at: new Date(Date.now() + 2 * 3_600_000).toISOString(),
|
||
},
|
||
{
|
||
label: "7-day",
|
||
utilization_pct: 39,
|
||
// 30s under 5 days so the elapsed render time cannot flip the
|
||
// formatted value between "5d 0h" and "4d 23h".
|
||
reset_at: new Date(Date.now() + 5 * 24 * 3_600_000 - 30_000).toISOString(),
|
||
},
|
||
],
|
||
fetched_at: new Date().toISOString(),
|
||
};
|
||
|
||
const { container, getByText } = render(<UsageWindowRows usage={usage} />);
|
||
|
||
expect(getByText("5h")).toBeDefined();
|
||
expect(getByText("94%")).toBeDefined();
|
||
expect(getByText("7d")).toBeDefined();
|
||
expect(getByText("39%")).toBeDefined();
|
||
expect(getByText("4d 23h")).toBeDefined();
|
||
expect(container.querySelector(".bg-red-500")).not.toBeNull();
|
||
expect(container.querySelector(".bg-emerald-500")).not.toBeNull();
|
||
});
|
||
});
|