Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Account usage: bars, Check now and badge line (frontend) (#599)

Oleksandr Ivanchenko2f140f49678a
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d497aa78..05c1cd50 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -83,7 +83,7 @@ import { playSfx } from './audio/chiptune';
import { haptic, messageHaptic } from './haptics';
import { Toasts, Toast } from './components/Toasts';
import { clearAllTurns, forgetLastRuns, resetTurns, turnEnded, turnRunsOn, turnStarted } from './kwantActivity';
-import { setBadgeBots, setBadgeEngines } from './modelBadgeData';
+import { setBadgeBots, setBadgeEngines, setBadgeProfiles } from './modelBadgeData';
import { setKnownBots } from './botLooks';
import { clearMoods, moodOutput, moodTurnEnded, moodTurnStarted, restingUntil, setMoodNeedsYou, setMoodResting } from './kwantMood';
import { browserTabDoc, createTabSignal, needsYouCount } from './tabSignal';
@@ -3771,6 +3771,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
forgetLastRuns();
}, [kwants]);
useEffect(() => setBadgeEngines(engines.engines), [engines.engines]);
+ useEffect(() => setBadgeProfiles(profiles), [profiles]);
// What the empty chat shows: a bot's home, #general's, or nothing special for a team or other channel.
const chatHome: ChatHome = currentKwant
diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsx
index 4620578e..a4d5a54e 100644
--- a/frontend/src/components/EngineAccounts.tsx
+++ b/frontend/src/components/EngineAccounts.tsx
@@ -11,8 +11,15 @@ import {
NewAccountSpec,
PROTOCOLS,
Profile,
+ AccountUsage,
+ UsageRow,
accountState,
+ hasUsageLimits,
isLoginDone,
+ usageCheckedText,
+ usageCoolingDown,
+ usageRows,
+ usageStale,
isThirdPartyLabel,
newAccountFor,
profilesApi,
@@ -87,6 +94,148 @@ export function accountStatus(p: Profile, engine: EngineInfo, now = Date.now()):
}
}
+/** Re-renders every 30 s so "checked … ago", stale and the Check now wait stay true while Settings is open. */
+function useClock(): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const t = window.setInterval(() => setNow(Date.now()), 30_000);
+ return () => window.clearInterval(t);
+ }, []);
+ return now;
+}
+
+const newerUsage = (a: AccountUsage | null | undefined, b: AccountUsage | null | undefined): AccountUsage | null =>
+ !a ? b ?? null : !b ? a : Date.parse(b.checked_at) > Date.parse(a.checked_at) ? b : a;
+
+/** One limit: its label and value, and a thin bar that fills with what is left (design §2). */
+const UsageMeter: React.FC<{ row: UsageRow }> = ({ row: r }) => {
+ const valueText = r.leftText ? `${r.leftText}${r.reset ? `, ${r.reset}` : ''}` : r.reset ?? '';
+ return (
+ <div data-usage-row={r.kind} data-usage-tone={r.tone}>
+ <div className="flex flex-wrap items-baseline justify-between gap-x-2 text-[11px]">
+ <span className="text-zinc-400">{r.label}</span>
+ <span className="ml-auto whitespace-nowrap text-zinc-500">
+ {r.leftText && <span className={`font-medium ${r.tone === 'ok' ? 'text-zinc-100' : 'text-amber-200'}`}>{r.leftText}</span>}
+ {r.leftText && r.reset && ' · '}
+ {r.reset}
+ </span>
+ </div>
+ <div
+ role="meter"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={r.left ?? undefined}
+ aria-label={`${r.label} usage left`}
+ aria-valuetext={valueText}
+ className={`mt-1 h-1 rounded-full overflow-hidden ${r.tone === 'out' ? 'bg-amber-500/20' : 'bg-zinc-800'}`}
+ >
+ {r.left !== null && r.left > 0 && (
+ <div
+ className={`h-full ${r.tone === 'low' ? 'bg-amber-400' : 'bg-zinc-400'} origin-left transition-transform duration-150 ease-out motion-reduce:transition-none`}
+ style={{ transform: `scaleX(${r.left / 100})` }}
+ />
+ )}
+ </div>
+ </div>
+ );
+};
+
+/** What a failed Check now says: the server's own reason (PR #604 sends plain words, e.g. "Codex is signed out"),
+ * or '' for the generic "couldn't check" line when there is none, or on a 429 (pressed again within the minute). */
+export function usageCheckError(e: unknown): string {
+ const err = e as { message?: unknown; status?: unknown } | null;
+ // Only an HTTP answer carries a reason meant for people; a dropped connection's TypeError does not.
+ if (!err || typeof err.status !== 'number' || err.status === 429) return '';
+ const msg = typeof err.message === 'string' ? err.message.trim() : '';
+ if (!msg || msg.startsWith('Request failed')) return '';
+ return msg.replace(/[.\s]+$/, '');
+}
+
+/**
+ * A Claude or Codex sign-in's 5-hour and weekly limits (autonomy/account-usage/design.md): when they were read, a
+ * thin bar each, and Check now (POST /api/profiles/:id/usage, only when pressed). Claude's check is one tiny model
+ * call; Codex's reads `codex app-server` and is the only way Codex numbers arrive (its turns report none, PR #604), so
+ * a Codex sign-in with no numbers still gets the block and its button. Nothing for API keys or Custom API.
+ */
+export const AccountUsageBars: React.FC<{ profile: Profile; canCheck: boolean; dim?: boolean; onChanged: () => Promise<void> }> = ({ profile: p, canCheck, dim, onChanged }) => {
+ const clock = useClock();
+ const [fresh, setFresh] = useState<AccountUsage | null>(null);
+ const [checking, setChecking] = useState(false);
+ // A failed check: the server's reason (plain words, PR #604's 502), or '' for the generic line.
+ const [failed, setFailed] = useState<string | null>(null);
+ if (!hasUsageLimits(p)) return null;
+ const usage = newerUsage(p.usage, fresh);
+ if (!usage && !canCheck) return null;
+ const codex = p.engine === 'codex';
+ const now = Math.max(clock, Date.now());
+ const rows = usageRows({ ...p, usage }, now);
+ const stale = usageStale(usage, now);
+ const wait = !checking && usageCoolingDown(usage, now);
+ const check = async () => {
+ if (checking || wait) return;
+ playSfx('click');
+ setChecking(true);
+ setFailed(null);
+ try {
+ setFresh(await profilesApi.usage(p.id));
+ await onChanged();
+ } catch (e) {
+ setFailed(usageCheckError(e));
+ } finally {
+ setChecking(false);
+ }
+ };
+ const note = checking
+ ? '· checking…'
+ : failed !== null
+ ? `· ${failed || 'couldn’t check, try again in a minute'}`
+ : usage
+ ? `· ${usageCheckedText(usage, now)}`
+ : codex
+ ? '· press Check now'
+ : '· shows after its next reply';
+ const btnProps = {
+ type: 'button' as const,
+ onClick: check,
+ disabled: checking || wait,
+ 'aria-busy': checking || undefined,
+ 'aria-label': 'Check usage now',
+ title: wait ? 'You can check again in a minute' : codex ? 'Check now' : 'Check now. This uses a tiny bit of this account.',
+ 'data-usage-check': true,
+ };
+ const spin = checking ? 'animate-spin motion-reduce:animate-none' : '';
+ return (
+ <div data-usage data-usage-stale={stale || undefined} className={`space-y-1.5 ${dim ? 'opacity-70' : ''}`}>
+ <div className="flex items-center gap-1 min-h-6 text-[11px]">
+ <span className="font-medium text-zinc-300">Usage</span>
+ <span role="status" data-usage-note className={failed !== null && !checking ? 'text-rose-300' : 'text-zinc-500'}>
+ {note}
+ </span>
+ {canCheck &&
+ (stale ? (
+ <button {...btnProps} className={`${quietBtn} ml-auto max-sm:py-2`}>
+ <RefreshCw size={11} aria-hidden="true" className={spin} /> {checking ? 'Checking…' : 'Check now'}
+ </button>
+ ) : (
+ <button
+ {...btnProps}
+ className="ml-auto inline-flex items-center justify-center w-6 h-6 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 max-sm:hover:bg-transparent disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400 max-sm:w-11 max-sm:h-11 max-sm:-my-2.5 max-sm:-mr-2.5"
+ >
+ <RefreshCw size={12} aria-hidden="true" className={spin} />
+ </button>
+ ))}
+ </div>
+ {rows.length > 0 && (
+ <div className={`space-y-1.5 ${stale ? 'opacity-60' : ''}`}>
+ {rows.map((r) => (
+ <UsageMeter key={r.kind} row={r} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
/** A small on/off switch with its name for screen readers. */
const Switch: React.FC<{ on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }> = ({ on, label, disabled, onChange }) => (
<button
@@ -668,6 +817,8 @@ const AccountRow: React.FC<{
/>
</div>
+ <AccountUsageBars profile={p} dim={off} canCheck={p.enabled && !off && (isSystem ? status.tone !== 'muted' && status.label !== 'Needs sign-in' : p.signed_in === true)} onChanged={onChanged} />
+
{hostAction && <div>{hostAction}</div>}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">
diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsx
index 48b4d3bd..a2ba2cbe 100644
--- a/frontend/src/components/ModernAvatar.tsx
+++ b/frontend/src/components/ModernAvatar.tsx
@@ -1,8 +1,8 @@
import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { HardHat, useDevModeOn } from './DevModeSwitch';
import { isKwantWorking, lastRunOf, liveRunOf, subscribeKwant } from '../kwantActivity';
-import { modelBadgeFor, modelBadgeSize, type ModelBadge } from '../engines';
-import { badgeBotOf, badgeEngines, subscribeBadgeData } from '../modelBadgeData';
+import { badgeUsageFor, modelBadgeFor, modelBadgeSize, type ModelBadge } from '../engines';
+import { badgeBotOf, badgeEngines, badgeProfiles, subscribeBadgeData } from '../modelBadgeData';
import { EngineMark } from './EngineMark';
import { AvatarMood, useKwantMood, useKwantNotices } from './AvatarMood';
import { moodLabel, restingUntilOf } from '../kwantMood';
@@ -61,6 +61,14 @@ export const useModelBadge = (kwantId: string | undefined): ModelBadge | null =>
);
};
+/** The hover's usage line for the account the bot's next turn would use, re-read when accounts or engines change. */
+const useBadgeUsage = (badge: ModelBadge | null) => {
+ const engines = useSyncExternalStore(subscribeBadgeData, badgeEngines, () => null);
+ const profiles = useSyncExternalStore(subscribeBadgeData, badgeProfiles, () => null);
+ const mark = badge && !badge.cantRun ? badge.mark : null;
+ return useMemo(() => badgeUsageFor(mark, engines, profiles), [mark, engines, profiles]);
+};
+
const prefersReducedMotion = () => typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
const BadgeFace: React.FC<{ badge: ModelBadge; glyph: number; className?: string }> = ({ badge, glyph, className = '' }) => (
@@ -75,6 +83,7 @@ const BadgeFace: React.FC<{ badge: ModelBadge; glyph: number; className?: string
/** Bottom-left, the mirror of the status dot. A changed mark cross-fades in 150 ms (instant under reduced motion). */
export const AvatarModelBadge: React.FC<{ kwantId: string; size: number }> = ({ kwantId, size }) => {
const badge = useModelBadge(kwantId);
+ const usage = useBadgeUsage(badge);
const d = modelBadgeSize(size);
const [leaving, setLeaving] = useState<ModelBadge | null>(null);
const shownRef = useRef<ModelBadge | null>(badge);
@@ -94,19 +103,28 @@ export const AvatarModelBadge: React.FC<{ kwantId: string; size: number }> = ({
}, [key]);
if (!badge || !d) return null;
const glyph = Math.round(d * (badge.mark === 'custom' ? 0.7 : 0.64));
+ const tip = usage ? `${badge.label}\n${usage.text}` : badge.label;
return (
<span
className={`kw-model-badge ring-2 ring-zinc-950 ${badge.cantRun ? 'bg-zinc-950' : 'bg-zinc-900'}`}
style={{ width: d, height: d }}
role="img"
- aria-label={badge.label}
- title={badge.label}
+ aria-label={tip.replace('\n', '. ')}
+ title={tip}
data-model-badge={badge.mark}
data-badge-resting={badge.resting || undefined}
data-badge-cant-run={badge.cantRun ?? undefined}
>
{leaving && <BadgeFace key={`out:${leaving.key}`} badge={leaving} glyph={glyph} className="kw-mb-out" />}
<BadgeFace key={badge.key} badge={badge} glyph={glyph} className={leaving ? 'kw-mb-in' : ''} />
+ {usage?.low && (
+ <span
+ className="absolute -top-px -right-px rounded-full bg-amber-400 ring-1 ring-zinc-950"
+ style={{ width: Math.max(4, Math.round(d * 0.36)), height: Math.max(4, Math.round(d * 0.36)) }}
+ aria-hidden="true"
+ data-badge-low
+ />
+ )}
{badge.resting && badge.auto && (
<span className="kw-mb-spark text-violet-300" style={{ fontSize: Math.max(8, Math.round(d * 0.55)) }} aria-hidden="true" data-badge-spark>
✦
diff --git a/frontend/src/engines.ts b/frontend/src/engines.ts
index 3b255ee1..b3673337 100644
--- a/frontend/src/engines.ts
+++ b/frontend/src/engines.ts
@@ -1,5 +1,6 @@
// Engines: whether each way of running a model (a CLI, an API key, Ollama) can run right now, from
// GET /api/engines, and the shared Engine → Model choice stored in a kwant's preferred_model.
+import { hasUsageLimits, usageSummary, type Profile } from './profiles';
export type EngineId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama' | 'custom_api';
export type EngineKind = 'cli' | 'api' | 'local';
@@ -515,6 +516,27 @@ export function pinnedCantRun(
return badge && !badge.auto && badge.cantRun ? badge.label : null;
}
+/**
+ * The badge hover's usage line (account-usage design §5) for the account a bot's next turn would use: the first
+ * engine of its family that can run, and the account it runs on now (`uses`). The account's name goes first when
+ * 2+ accounts of that engine are signed in and on. `low` (a window under 20% left) draws the amber dot. null for
+ * Laya's ✦, an API key or Custom API account, or when nothing was read yet.
+ */
+export function badgeUsageFor(
+ mark: BadgeMark | null | undefined,
+ engines: EngineInfo[] | null | undefined,
+ profiles: Profile[] | null | undefined,
+ now = Date.now(),
+): { text: string; low: boolean } | null {
+ if (!mark || mark === 'laya' || !engines?.length || !profiles?.length) return null;
+ const engine = engines.find((e) => FAMILY_OF[e.id] === mark && isUsable(e) && e.uses?.profile_id);
+ const account = engine ? profiles.find((p) => p.id === engine.uses!.profile_id) : null;
+ if (!account || !hasUsageLimits(account)) return null;
+ const signedIn = profiles.filter((p) => p.engine === account.engine && hasUsageLimits(p) && p.enabled && p.signed_in === true);
+ const name = signedIn.length > 1 ? (account.kind === 'system' ? account.account_label || 'This computer' : account.name) : null;
+ return usageSummary(account, now, name);
+}
+
/** The badge's diameter for an avatar of `size` px: none under 24, 14 at 28–34, larger on big avatars. */
export function modelBadgeSize(size: number): number | null {
if (size < 24) return null;
diff --git a/frontend/src/modelBadgeData.ts b/frontend/src/modelBadgeData.ts
index 87eff011..5787f128 100644
--- a/frontend/src/modelBadgeData.ts
+++ b/frontend/src/modelBadgeData.ts
@@ -1,6 +1,7 @@
// What the avatar's model badge needs besides the live turn: each bot's pick and last reply's engine
// (from the app's bot list), and which engines can run (GET /api/engines). The app fills it, like botLooks.
import type { EngineInfo, RunsOn } from './engines';
+import type { Profile } from './profiles';
export interface BadgeBot {
id: string;
@@ -11,6 +12,7 @@ export interface BadgeBot {
let bots = new Map<string, BadgeBot>();
let engines: EngineInfo[] | null = null;
+let profiles: Profile[] | null = null;
let rev = 0;
const listeners = new Set<() => void>();
const bump = () => {
@@ -30,8 +32,16 @@ export function setBadgeEngines(list: EngineInfo[] | null): void {
bump();
}
+/** The space's accounts, for the hover's "5-hour 93% left · Weekly 44% left" (account-usage). */
+export function setBadgeProfiles(list: Profile[] | null): void {
+ if (list === profiles) return;
+ profiles = list;
+ bump();
+}
+
export const badgeBotOf = (id: string | undefined): BadgeBot | undefined => (id ? bots.get(id) : undefined);
export const badgeEngines = (): EngineInfo[] | null => engines;
+export const badgeProfiles = (): Profile[] | null => profiles;
export const badgeDataRev = (): number => rev;
export function subscribeBadgeData(fn: () => void): () => void {
listeners.add(fn);
diff --git a/frontend/src/profiles.ts b/frontend/src/profiles.ts
index 7fe149be..dde78d1d 100644
--- a/frontend/src/profiles.ts
+++ b/frontend/src/profiles.ts
@@ -40,6 +40,28 @@ export interface Profile {
last_error: 'quota' | 'auth' | null;
/** Custom API accounts only. */
custom?: CustomServer | null;
+ /** How much of its 5-hour and weekly limit a Claude or Codex sign-in has left, as last read. null or
+ * missing: never read (or a server before account-usage). */
+ usage?: AccountUsage | null;
+}
+
+/** A subscription's limit: the rolling 5-hour one or the weekly one. */
+export type UsageKind = 'five_hour' | 'weekly';
+
+export interface UsageWindow {
+ kind: UsageKind;
+ /** 0–100, rounded. The UI shows 100 − this as "% left". */
+ used_pct: number;
+ resets_at: string | null;
+}
+
+/** GET /api/profiles `usage`, and what POST /api/profiles/:id/usage returns. */
+export interface AccountUsage {
+ checked_at: string;
+ /** "turn": read off a bot's reply; "check": the person pressed Check now. */
+ source: 'turn' | 'check';
+ status: 'ok' | 'warning' | 'out' | null;
+ windows: UsageWindow[];
}
export type LoginStatus = 'starting' | 'waiting' | 'succeeded' | 'failed' | 'expired' | 'cancelled';
@@ -150,6 +172,115 @@ export function formatUntil(at: Date, now = Date.now()): string {
return at.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}
+/** Below this much left, a limit's bar and the avatar badge turn amber (account-usage design §2.2). */
+export const USAGE_LOW_LEFT = 20;
+/** Numbers older than this are dimmed and say so (design §2.4). */
+export const USAGE_STALE_MS = 60 * 60_000;
+/** The server answers Check now from its copy for this long after a read, so the button waits too. */
+export const USAGE_CHECK_COOLDOWN_MS = 60_000;
+
+const USAGE_LABEL: Record<UsageKind, '5-hour' | 'Weekly'> = { five_hour: '5-hour', weekly: 'Weekly' };
+
+/** One limit on an account row: "5-hour · 93% left · resets 22:29". */
+export interface UsageRow {
+ kind: UsageKind;
+ label: '5-hour' | 'Weekly';
+ /** 0–100; null once its reset has passed (the old number is wrong and the new one isn't known yet). */
+ left: number | null;
+ /** "93% left"; null once reset. */
+ leftText: string | null;
+ /** "resets 22:29", "resets Wed 00:59", "resets Nov 20"; "reset at 14:29" once passed; null when not known. */
+ reset: string | null;
+ /** low: under 20% left (amber); out: nothing left (empty amber track); reset: its reset has passed. */
+ tone: 'ok' | 'low' | 'out' | 'reset';
+}
+
+/** Only sign-ins to Claude or Codex have these limits; API keys and Custom API accounts never show them. */
+export const hasUsageLimits = (p: Pick<Profile, 'engine' | 'kind'>) => (p.engine === 'claude' || p.engine === 'codex') && (p.kind === 'system' || p.kind === 'cli_home');
+
+/** A time on the person's own clock: "22:29" or "10:29 PM". */
+const clockOf = (at: Date) => at.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
+const sameDay = (a: Date, b: Date) => a.toDateString() === b.toDateString();
+const weekday = (at: Date) => at.toLocaleDateString(undefined, { weekday: 'short' });
+
+/** When a limit resets: the time today, "Wed 00:59" within 6 days, else "Nov 20". */
+export function usageResetTime(at: Date, now = Date.now()): string {
+ if (sameDay(at, new Date(now))) return clockOf(at);
+ if (at.getTime() - now < 6 * 86400_000) return `${weekday(at)} ${clockOf(at)}`;
+ return at.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+/** An account's limits, 5-hour first; [] when it has none or they were never read. */
+export function usageRows(p: Pick<Profile, 'engine' | 'kind' | 'usage'>, now = Date.now()): UsageRow[] {
+ if (!hasUsageLimits(p) || !p.usage?.windows?.length) return [];
+ const rows: UsageRow[] = [];
+ for (const kind of ['five_hour', 'weekly'] as const) {
+ const w = p.usage.windows.find((x) => x.kind === kind);
+ if (!w || typeof w.used_pct !== 'number' || !Number.isFinite(w.used_pct)) continue;
+ const parsed = w.resets_at ? new Date(w.resets_at) : null;
+ const at = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null;
+ const label = USAGE_LABEL[kind];
+ if (at && at.getTime() <= now) {
+ const when = sameDay(at, new Date(now)) ? clockOf(at) : `${weekday(at)} ${clockOf(at)}`;
+ rows.push({ kind, label, left: null, leftText: null, reset: `reset at ${when}`, tone: 'reset' });
+ continue;
+ }
+ const left = Math.max(0, Math.min(100, Math.round(100 - w.used_pct)));
+ rows.push({
+ kind,
+ label,
+ left,
+ leftText: `${left}% left`,
+ reset: at ? `resets ${usageResetTime(at, now)}` : null,
+ tone: left <= 0 ? 'out' : left < USAGE_LOW_LEFT ? 'low' : 'ok',
+ });
+ }
+ return rows;
+}
+
+/** "checked just now", "… 4 min ago", "… 6 h ago", "… yesterday", then "checked Nov 11"; null when never read. */
+export function usageCheckedText(usage: Pick<AccountUsage, 'checked_at'> | null | undefined, now = Date.now()): string | null {
+ const t = usage?.checked_at ? Date.parse(usage.checked_at) : NaN;
+ if (Number.isNaN(t)) return null;
+ const s = Math.max(0, Math.round((now - t) / 1000));
+ if (s < 60) return 'checked just now';
+ const m = Math.floor(s / 60);
+ if (m < 60) return `checked ${m} min ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `checked ${h} h ago`;
+ const at = new Date(t);
+ const yesterday = new Date(now);
+ yesterday.setDate(yesterday.getDate() - 1);
+ return sameDay(at, yesterday) ? 'checked yesterday' : `checked ${at.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`;
+}
+
+/** Read more than an hour ago: dimmed, with a labelled Check now. */
+export const usageStale = (usage: Pick<AccountUsage, 'checked_at'> | null | undefined, now = Date.now()) => {
+ const t = usage?.checked_at ? Date.parse(usage.checked_at) : NaN;
+ return !Number.isNaN(t) && now - t > USAGE_STALE_MS;
+};
+
+/** Read under a minute ago: Check now would only get the server's copy back, so it waits. */
+export const usageCoolingDown = (usage: Pick<AccountUsage, 'checked_at'> | null | undefined, now = Date.now()) => {
+ const t = usage?.checked_at ? Date.parse(usage.checked_at) : NaN;
+ return !Number.isNaN(t) && now - t >= 0 && now - t < USAGE_CHECK_COOLDOWN_MS;
+};
+
+/**
+ * The model-badge hover's line (design §5): "5-hour 93% left · Weekly 44% left". A low window adds its reset
+ * ("5-hour 12% left, resets 22:29"), a reset one is left out, stale numbers add " · checked 6 h ago", and `name`
+ * (given when 2+ accounts of that engine could run) goes first. `low` draws the badge's amber dot. null when there's
+ * nothing to say.
+ */
+export function usageSummary(p: Pick<Profile, 'engine' | 'kind' | 'usage'>, now = Date.now(), name?: string | null): { text: string; low: boolean } | null {
+ const rows = usageRows(p, now).filter((r) => r.tone !== 'reset');
+ if (!rows.length) return null;
+ const parts = rows.map((r) => `${r.label} ${r.leftText}${r.tone !== 'ok' && r.reset ? `, ${r.reset}` : ''}`);
+ if (name) parts.unshift(name);
+ if (usageStale(p.usage, now)) parts.push(usageCheckedText(p.usage, now)!);
+ return { text: parts.join(' · '), low: rows.some((r) => r.tone !== 'ok') };
+}
+
/** What the server's account label says when Claude Code is set up for another provider, not a Claude login. */
const THIRD_PARTY_LABELS = new Set(['Amazon Bedrock', 'Google Vertex AI', 'Microsoft Foundry', 'a third-party provider', 'third_party']);
export const isThirdPartyLabel = (label: string | null | undefined) => !!label && THIRD_PARTY_LABELS.has(label);
@@ -239,7 +370,7 @@ async function request<T>(method: string, url: string, body?: unknown): Promise<
// no JSON body
}
if (res.status === 409 && message.startsWith('Request failed')) message = 'A profile with that name or folder already exists.';
- throw new Error(message);
+ throw Object.assign(new Error(message), { status: res.status });
}
if (res.status === 204) return undefined as T;
return res.json();
@@ -269,6 +400,8 @@ export const profilesApi = {
) => request<Profile>('PATCH', `/api/profiles/${enc(id)}`, body),
/** Checks a Custom API account's server again now. */
check: (id: string) => request<Profile>('POST', `/api/profiles/${enc(id)}/check`),
+ /** Reads fresh 5-hour and weekly numbers (one tiny model call; the server answers from its copy within 60 s). */
+ usage: (id: string) => request<AccountUsage>('POST', `/api/profiles/${enc(id)}/usage`),
remove: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}`),
setKey: (id: string, apiKey: string) => request<void>('PUT', `/api/profiles/${enc(id)}/key`, { api_key: apiKey }),
removeKey: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}/key`),
diff --git a/frontend/tests/accountUsage.test.mjs b/frontend/tests/accountUsage.test.mjs
new file mode 100644
index 00000000..8466f945
--- /dev/null
+++ b/frontend/tests/accountUsage.test.mjs
@@ -0,0 +1,178 @@
+// account-usage (autonomy/account-usage/design.md): the 5-hour and weekly bars on a Claude/Codex sign-in's row,
+// "checked … ago", and Check now (POST /api/profiles/:id/usage, only when pressed).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia = (q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {} });
+g.IS_REACT_ACT_ENVIRONMENT = false;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { AccountList } from './src/components/EngineAccounts';
+`);
+const h = m.React.createElement;
+const settle = (ms = 0) => new Promise((r) => setTimeout(r, ms));
+
+const calls = [];
+let reply = null;
+g.fetch = g.window.fetch = async (url, init = {}) => {
+ calls.push(`${init.method ?? 'GET'} ${url}`);
+ if (url.endsWith('/usage') && reply) return reply();
+ return new Response('{}', { status: 404 });
+};
+
+const ago = (min) => new Date(Date.now() - min * 60_000).toISOString();
+const inMin = (min) => new Date(Date.now() + min * 60_000).toISOString();
+const usage = (five, week, checkedMinAgo = 2) => ({
+ checked_at: ago(checkedMinAgo), source: 'turn', status: 'ok',
+ windows: [{ kind: 'five_hour', used_pct: five, resets_at: inMin(90) }, { kind: 'weekly', used_pct: week, resets_at: inMin(3 * 1440) }],
+});
+const acct = (over) => ({
+ id: 'prf_w', engine: 'claude', name: 'Work', kind: 'cli_home', enabled: true, is_default: false, priority: 100, home_dir: null,
+ has_key: false, signed_in: true, account_label: '[email protected]', limited_until: null, last_error: null, ...over,
+});
+const engine = { id: 'claude', name: 'Claude Code CLI', kind: 'cli', status: 'ready', detail: null, version: null, models: [], checked_at: null, enabled: true, ready: true, uses: { profile_id: 'prf_w', label: 'Work' } };
+
+async function mount(accounts, eng = engine) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ m.flushSync(() => root.render(h(m.AccountList, { engine: eng, accounts, onChanged: async () => {} })));
+ await settle();
+ return { host, done: () => { root.unmount(); host.remove(); } };
+}
+const rowOf = (host, id) => [...host.querySelectorAll('li')].find((li) => li.querySelector(`#account-${id}-name`));
+
+test('bars fill with what is left, amber below 20%, nothing for an API key', async () => {
+ const { host, done } = await mount([
+ acct({ usage: usage(7, 56) }),
+ acct({ id: 'prf_low', name: 'Low', usage: usage(88, 10) }),
+ acct({ id: 'prf_key', name: 'Key', kind: 'api_key', has_key: true, usage: usage(7, 56) }),
+ ]);
+ const work = rowOf(host, 'prf_w');
+ const meters = work.querySelectorAll('[role="meter"]');
+ assert.equal(meters.length, 2);
+ assert.equal(meters[0].getAttribute('aria-label'), '5-hour usage left');
+ assert.equal(meters[0].getAttribute('aria-valuenow'), '93');
+ assert.match(meters[0].getAttribute('aria-valuetext'), /^93% left, resets /);
+ assert.equal(meters[0].firstElementChild.style.transform, 'scaleX(0.93)');
+ assert.match(work.querySelector('[data-usage]').textContent, /^Usage· checked 2 min ago5-hour93% left · resets .+Weekly44% left · resets \S+ /);
+ const low = rowOf(host, 'prf_low').querySelector('[data-usage-row="five_hour"]');
+ assert.equal(low.dataset.usageTone, 'low');
+ assert.match(low.innerHTML, /bg-amber-400/);
+ assert.equal(rowOf(host, 'prf_key').querySelector('[data-usage]'), null);
+ assert.doesNotMatch(host.textContent, /unknown|rate limit|utilization|window/i);
+ assert.equal(calls.length, 0, 'never reads usage on load');
+ done();
+});
+
+test('out: an empty amber-tinted track; reset passed: "reset at", no %; stale: dimmed with a text Check now', async () => {
+ const stale = { ...usage(100, 49, 6 * 60), windows: [{ kind: 'five_hour', used_pct: 100, resets_at: ago(30) }, { kind: 'weekly', used_pct: 49, resets_at: inMin(2000) }] };
+ const { host, done } = await mount([acct({ usage: usage(100, 69), limited_until: inMin(120) }), acct({ id: 'prf_s', name: 'Old', usage: stale })]);
+ const out = rowOf(host, 'prf_w').querySelector('[data-usage-row="five_hour"]');
+ assert.equal(out.dataset.usageTone, 'out');
+ assert.match(out.querySelector('[role="meter"]').className, /bg-amber-500\/20/);
+ assert.equal(out.querySelector('[role="meter"]').children.length, 0);
+ assert.match(rowOf(host, 'prf_w').textContent, /Out of usage/);
+ const s = rowOf(host, 'prf_s');
+ assert.ok(s.querySelector('[data-usage-stale]'));
+ assert.match(s.querySelector('[data-usage-note]').textContent, /checked 6 h ago/);
+ assert.match(s.querySelector('[data-usage-row="five_hour"]').textContent, /^5-hourreset at /);
+ assert.equal(s.querySelector('[data-usage-check]').textContent.trim(), 'Check now');
+ done();
+});
+
+test('no numbers yet: Claude says when they come; a Codex sign-in gets the block and Check now', async () => {
+ const { host, done } = await mount([acct({ usage: null }), acct({ id: 'prf_c', engine: 'codex', name: 'Codex', usage: null }), acct({ id: 'prf_out', name: 'Signed out', signed_in: false })]);
+ assert.equal(rowOf(host, 'prf_w').querySelector('[data-usage]').textContent, 'Usage· shows after its next reply');
+ assert.equal(rowOf(host, 'prf_w').querySelectorAll('[role="meter"]').length, 0);
+ assert.equal(rowOf(host, 'prf_w').querySelector('[data-usage-check]').title, 'Check now. This uses a tiny bit of this account.');
+ // Codex numbers come only from Check now (PR #604: its turns report none), so the button must be there.
+ const codex = rowOf(host, 'prf_c');
+ assert.equal(codex.querySelector('[data-usage-note]').textContent, '· press Check now');
+ assert.equal(codex.querySelectorAll('[role="meter"]').length, 0);
+ const btn = codex.querySelector('[data-usage-check]');
+ assert.ok(btn, 'Codex sign-in with no numbers has a Check now button');
+ assert.equal(btn.disabled, false);
+ assert.equal(btn.title, 'Check now', 'no "uses a tiny bit" for Codex: its read makes no model call');
+ assert.equal(rowOf(host, 'prf_out').querySelector('[data-usage]'), null);
+ done();
+ // A Codex row that can't check (turned off) still shows nothing.
+ const off = await mount([acct({ id: 'prf_c', engine: 'codex', name: 'Codex', usage: null, enabled: false })]);
+ assert.equal(rowOf(off.host, 'prf_c').querySelector('[data-usage]'), null);
+ off.done();
+});
+
+test('a failed check shows the server reason; a 429 or no reason keeps the generic line', async () => {
+ calls.length = 0;
+ reply = async () => new Response('{"error":"Codex is signed out"}', { status: 502, headers: { 'Content-Type': 'application/json' } });
+ const a = await mount([acct({ id: 'prf_c', engine: 'codex', name: 'Codex', usage: null })]);
+ a.host.querySelector('[data-usage-check]').click();
+ await settle(10);
+ assert.deepEqual(calls, ['POST /api/profiles/prf_c/usage']);
+ const note = a.host.querySelector('[data-usage-note]');
+ assert.equal(note.textContent, '· Codex is signed out');
+ assert.match(note.className, /text-rose-300/);
+ a.done();
+
+ reply = async () => new Response('{"error":"Wait a minute before checking again."}', { status: 429, headers: { 'Retry-After': '60', 'Content-Type': 'application/json' } });
+ const b = await mount([acct({ usage: null })]);
+ b.host.querySelector('[data-usage-check]').click();
+ await settle(10);
+ assert.equal(b.host.querySelector('[data-usage-note]').textContent, '· couldn’t check, try again in a minute');
+ b.done();
+
+ reply = async () => new Response('', { status: 502 });
+ const c = await mount([acct({ usage: null })]);
+ c.host.querySelector('[data-usage-check]').click();
+ await settle(10);
+ assert.equal(c.host.querySelector('[data-usage-note]').textContent, '· couldn’t check, try again in a minute');
+ c.done();
+ reply = null;
+});
+
+test('Check now posts once, shows checking…, then the new numbers; a failure keeps the old bars', async () => {
+ calls.length = 0;
+ let release;
+ reply = () => new Promise((r) => { release = () => r(new Response(JSON.stringify({ ...usage(40, 60, 0), source: 'check' }), { status: 200, headers: { 'Content-Type': 'application/json' } })); });
+ const { host, done } = await mount([acct({ usage: usage(7, 56, 5) })]);
+ const btn = host.querySelector('[data-usage-check]');
+ assert.equal(btn.getAttribute('aria-label'), 'Check usage now');
+ assert.equal(btn.disabled, false);
+ btn.click();
+ await settle();
+ assert.deepEqual(calls, ['POST /api/profiles/prf_w/usage']);
+ assert.equal(host.querySelector('[data-usage-note]').textContent, '· checking…');
+ assert.equal(btn.disabled, true);
+ assert.match(btn.querySelector('svg').getAttribute('class'), /animate-spin/);
+ assert.equal(host.querySelector('[role="meter"]').getAttribute('aria-valuenow'), '93', 'old bars stay while checking');
+ release();
+ await settle(10);
+ assert.equal(host.querySelector('[role="meter"]').getAttribute('aria-valuenow'), '60');
+ assert.equal(host.querySelector('[data-usage-note]').textContent, '· checked just now');
+ // Read under a minute ago: it waits, so a second press can't spend more.
+ assert.equal(host.querySelector('[data-usage-check]').disabled, true);
+ assert.equal(host.querySelector('[data-usage-check]').title, 'You can check again in a minute');
+ done();
+
+ reply = async () => new Response('', { status: 502 });
+ const second = await mount([acct({ usage: usage(7, 56, 5) })]);
+ second.host.querySelector('[data-usage-check]').click();
+ await settle(10);
+ const note = second.host.querySelector('[data-usage-note]');
+ assert.equal(note.textContent, '· couldn’t check, try again in a minute');
+ assert.match(note.className, /text-rose-300/);
+ assert.equal(second.host.querySelector('[role="meter"]').getAttribute('aria-valuenow'), '93');
+ second.done();
+ reply = null;
+});
diff --git a/frontend/tests/modelBadge.test.mjs b/frontend/tests/modelBadge.test.mjs
index f79d42ee..b07eb28c 100644
--- a/frontend/tests/modelBadge.test.mjs
+++ b/frontend/tests/modelBadge.test.mjs
@@ -310,3 +310,53 @@ test('0.9.8 #7: a bot pinned to a signed-out engine with failover off gets no gr
assert.match(side, /const pinnedTip = pinnedCantRun\(k, engines\.engines\);\n\s+const status = asked \? 'needs_you' : statusOf\(k\.id, botStatus, pinnedTip \? false : canRun\);/);
assert.match(side, /title=\{status === 'cant_run' \? pinnedTip \?\? "Can't run yet: no account works here"/);
});
+
+// ---- account-usage: the hover's usage line for the account the next turn would use ----
+
+test('badgeUsageFor: the account its engine uses now; nothing for Laya, API keys or unread', () => {
+ const u = (five, week) => ({ checked_at: new Date().toISOString(), source: 'turn', status: 'ok', windows: [
+ { kind: 'five_hour', used_pct: five, resets_at: new Date(Date.now() + 3600e3).toISOString() },
+ { kind: 'weekly', used_pct: week, resets_at: new Date(Date.now() + 86400e3).toISOString() },
+ ] });
+ const acct = (id, over) => ({ id, engine: 'claude', name: id, kind: 'cli_home', enabled: true, is_default: false, priority: 1, home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null, ...over });
+ const engines = [ready('claude', { uses: { profile_id: 'work', label: 'Work' } }), ready('anthropic_api', { kind: 'api', uses: { profile_id: 'key', label: 'Key' } })];
+ const profs = [acct('work', { usage: u(7, 56) }), acct('key', { kind: 'api_key', has_key: true })];
+ assert.deepEqual(m.badgeUsageFor('claude', engines, profs), { text: '5-hour 93% left · Weekly 44% left', low: false });
+ assert.equal(m.badgeUsageFor('claude', engines, [acct('work', { usage: u(90, 10) })]).low, true);
+ assert.equal(m.badgeUsageFor('laya', engines, profs), null);
+ assert.equal(m.badgeUsageFor('claude', [{ ...engines[0], ready: false, status: 'error' }, engines[1]], profs), null); // API key next: no limits
+ assert.equal(m.badgeUsageFor('claude', engines, [acct('work', {})]), null);
+ assert.equal(m.badgeUsageFor('codex', engines, profs), null);
+ // Two signed-in Claude accounts: the one in use is named.
+ assert.equal(m.badgeUsageFor('claude', engines, [...profs, acct('play', { usage: u(1, 1) })]).text, 'work · 5-hour 93% left · Weekly 44% left');
+ assert.equal(m.badgeUsageFor('claude', engines, [...profs, acct('play', { signed_in: false })]).text, '5-hour 93% left · Weekly 44% left');
+});
+
+test('the badge tip adds the usage line and an amber dot only when low', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const u = (five) => ({ checked_at: new Date().toISOString(), source: 'turn', status: 'ok', windows: [{ kind: 'five_hour', used_pct: five, resets_at: null }, { kind: 'weekly', used_pct: 56, resets_at: null }] });
+ const acct = { id: 'work', engine: 'claude', name: 'Work', kind: 'cli_home', enabled: true, is_default: true, priority: 1, home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null, usage: u(7) };
+ m.setBadgeEngines([ready('claude', { uses: { profile_id: 'work', label: 'Work' }, models: [{ id: 'sonnet', label: 'Sonnet', default: true }] })]);
+ m.setBadgeBots([{ id: 'ku', preferred_model: 'claude/sonnet' }]);
+ m.setBadgeProfiles([acct]);
+ flushSync(() => root.render(h(m.ModernAvatar, { kwantId: 'ku', size: 40, modelBadge: true })));
+ await settle();
+ let b = host.querySelector('[data-model-badge]');
+ assert.equal(b.getAttribute('title'), 'Runs on Claude · Sonnet\n5-hour 93% left · Weekly 44% left');
+ assert.equal(b.getAttribute('aria-label'), 'Runs on Claude · Sonnet. 5-hour 93% left · Weekly 44% left');
+ assert.equal(host.querySelector('[data-badge-low]'), null);
+ flushSync(() => m.setBadgeProfiles([{ ...acct, usage: u(85) }]));
+ await settle();
+ b = host.querySelector('[data-model-badge]');
+ assert.equal(b.getAttribute('title'), 'Runs on Claude · Sonnet\n5-hour 15% left · Weekly 44% left');
+ const dot = host.querySelector('[data-badge-low]');
+ assert.ok(dot);
+ assert.equal(dot.style.width, '5px'); // 40 px avatar → 14 px badge → 5 px dot (design §5)
+ flushSync(() => m.setBadgeProfiles(null));
+ await settle();
+ assert.equal(host.querySelector('[data-model-badge]').getAttribute('title'), 'Runs on Claude · Sonnet');
+ root.unmount();
+ host.remove();
+});
diff --git a/frontend/tests/profiles.test.mjs b/frontend/tests/profiles.test.mjs
index aaebfcb6..e09279ac 100644
--- a/frontend/tests/profiles.test.mjs
+++ b/frontend/tests/profiles.test.mjs
@@ -124,3 +124,94 @@ test('a kwant works until every turn it started has ended, whatever the outcome'
activity.turnEnded('k1', 'y');
assert.deepEqual(seen, [true, false, true, false, true, false]);
});
+
+// ---- account-usage: 5-hour and weekly limits on Claude/Codex sign-ins (design.md §3) ----
+
+const at = (d, h, m = 0) => new Date(2026, 10, d, h, m); // local time, Nov 2026 (13th is a Friday)
+const clock = (d) => d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
+const wd = (d) => d.toLocaleDateString(undefined, { weekday: 'short' });
+const usage = (fiveUsed, weekUsed, over = {}) => ({
+ checked_at: at(13, 20, 31).toISOString(),
+ source: 'turn',
+ status: 'ok',
+ windows: [
+ { kind: 'weekly', used_pct: weekUsed, resets_at: at(18, 0, 59).toISOString() },
+ { kind: 'five_hour', used_pct: fiveUsed, resets_at: at(13, 22, 29).toISOString() },
+ ],
+ ...over,
+});
+const NOW = at(13, 20, 32).getTime();
+
+test('usageRows: % left, 5-hour first, reset today vs. within the week vs. later', () => {
+ const rows = profiles.usageRows(profile({ usage: usage(7, 56) }), NOW);
+ assert.deepEqual(rows.map((r) => [r.label, r.left, r.leftText, r.tone]), [
+ ['5-hour', 93, '93% left', 'ok'],
+ ['Weekly', 44, '44% left', 'ok'],
+ ]);
+ assert.equal(rows[0].reset, `resets ${clock(at(13, 22, 29))}`);
+ assert.equal(rows[1].reset, `resets ${wd(at(18, 0, 59))} ${clock(at(18, 0, 59))}`); // "resets Wed 00:59"
+ const later = profiles.usageRows(profile({ usage: usage(7, 56, { windows: [{ kind: 'weekly', used_pct: 1, resets_at: at(20, 9).toISOString() }] }) }), NOW);
+ assert.equal(later[0].reset, `resets ${at(20, 9).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`);
+ assert.equal(profiles.usageRows(profile({ usage: usage(7, 56, { windows: [{ kind: 'five_hour', used_pct: 7, resets_at: null }] }) }), NOW)[0].reset, null);
+});
+
+test('usageRows: amber below 20% left, out at 0, clamped', () => {
+ const tones = (u5, uw) => profiles.usageRows(profile({ usage: usage(u5, uw) }), NOW).map((r) => r.tone);
+ assert.deepEqual(tones(80, 81), ['ok', 'low']); // 20% left is not low; 19% is
+ assert.deepEqual(tones(100, 130), ['out', 'out']);
+ assert.equal(profiles.usageRows(profile({ usage: usage(-5, 0) }), NOW)[0].left, 100);
+ assert.equal(profiles.usageRows(profile({ usage: usage(12.4, 0) }), NOW)[0].leftText, '88% left');
+});
+
+test('usageRows: a reset that has passed shows "reset at …" with no %', () => {
+ const [five, week] = profiles.usageRows(profile({ usage: usage(97, 10) }), at(13, 23, 0).getTime());
+ assert.deepEqual([five.left, five.leftText, five.tone], [null, null, 'reset']);
+ assert.equal(five.reset, `reset at ${clock(at(13, 22, 29))}`);
+ assert.equal(week.tone, 'ok');
+ const [next] = profiles.usageRows(profile({ usage: usage(97, 10) }), at(14, 9, 0).getTime());
+ assert.equal(next.reset, `reset at ${wd(at(13, 22, 29))} ${clock(at(13, 22, 29))}`);
+});
+
+test('usageRows: nothing for API keys, Custom API, Grok, or never read', () => {
+ assert.deepEqual(profiles.usageRows(profile({ kind: 'api_key', usage: usage(7, 56) }), NOW), []);
+ assert.deepEqual(profiles.usageRows(profile({ engine: 'custom', kind: 'custom_api', usage: usage(7, 56) }), NOW), []);
+ assert.deepEqual(profiles.usageRows(profile({ engine: 'grok', usage: usage(7, 56) }), NOW), []);
+ assert.deepEqual(profiles.usageRows(profile({ usage: null }), NOW), []);
+ assert.deepEqual(profiles.usageRows(profile({}), NOW), []);
+ assert.equal(profiles.usageRows(profile({ engine: 'codex', kind: 'system', usage: usage(7, 56) }), NOW).length, 2);
+});
+
+test('usageCheckedText: the "checked … ago" wording', () => {
+ const t = (s) => profiles.usageCheckedText({ checked_at: new Date(NOW - s * 1000).toISOString() }, NOW);
+ assert.equal(t(10), 'checked just now');
+ assert.equal(t(60), 'checked 1 min ago');
+ assert.equal(t(4 * 60 + 30), 'checked 4 min ago');
+ assert.equal(t(59 * 60), 'checked 59 min ago');
+ assert.equal(t(6 * 3600 + 1200), 'checked 6 h ago');
+ assert.equal(profiles.usageCheckedText({ checked_at: at(12, 9).toISOString() }, NOW), 'checked yesterday');
+ assert.equal(profiles.usageCheckedText({ checked_at: at(11, 9).toISOString() }, NOW), `checked ${at(11, 9).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`);
+ assert.equal(profiles.usageCheckedText(null, NOW), null);
+ assert.equal(profiles.usageCheckedText({ checked_at: 'nope' }, NOW), null);
+});
+
+test('usageStale over 60 min, and Check now waits 60 s after a read', () => {
+ const ago = (s) => ({ checked_at: new Date(NOW - s * 1000).toISOString() });
+ assert.equal(profiles.usageStale(ago(3600), NOW), false);
+ assert.equal(profiles.usageStale(ago(3601), NOW), true);
+ assert.equal(profiles.usageStale(null, NOW), false);
+ assert.equal(profiles.usageCoolingDown(ago(30), NOW), true);
+ assert.equal(profiles.usageCoolingDown(ago(60), NOW), false);
+ assert.equal(profiles.usageCoolingDown(null, NOW), false);
+});
+
+test('usageSummary: the badge hover line (design §5)', () => {
+ const sum = (u, now = NOW, name) => profiles.usageSummary(profile({ usage: u }), now, name);
+ assert.deepEqual(sum(usage(7, 56)), { text: '5-hour 93% left · Weekly 44% left', low: false });
+ assert.deepEqual(sum(usage(88, 56)), { text: `5-hour 12% left, resets ${clock(at(13, 22, 29))} · Weekly 44% left`, low: true });
+ assert.equal(sum(usage(100, 69)).text, `5-hour 0% left, resets ${clock(at(13, 22, 29))} · Weekly 31% left`);
+ assert.equal(sum(usage(7, 56), NOW, 'Work').text, 'Work · 5-hour 93% left · Weekly 44% left');
+ // Stale: the reset window drops out and the age is added; both reset: no line.
+ assert.equal(sum(usage(7, 56), at(14, 3, 0).getTime()).text, 'Weekly 44% left · checked 6 h ago');
+ assert.equal(sum(usage(7, 56), at(19, 3, 0).getTime()), null);
+ assert.equal(profiles.usageSummary(profile({ kind: 'api_key', usage: usage(7, 56) }), NOW), null);
+});