loopable / web /src /account /UsagePage.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame Contribute Delete
11.6 kB
// ---------------------------------------------------------------------------
// account/UsagePage.tsx β€” WAVE 35 Β· W35-T19 (owner item 13, ruling R9, C6/C7).
//
// R9: ONE meter for every AI surface. It REPORTS weekly usage against an
// allowance and does not cut anyone off this wave; over the allowance the
// product still works and the bar is red.
//
// β›”β›” THIS PAGE MAY NOT INVENT A FIGURE, AND THAT IS THE WHOLE TICKET.
// Every number here comes off `GET /usage` β€” the week, the reset date, the
// allowance, each surface's tokens and calls. Nothing is derived from a clock,
// nothing is estimated, and a surface with no ledger lines shows **0**, not a
// blank and not an omission (E-9 guarantees all four surfaces are always
// present, so there is no missing-row branch to get wrong).
// [[no-unverifiable-aggregates]]
//
// β›” AND `unmeasured` IS RENDERED, NOT SWALLOWED. Those are real calls whose
// provider declined to report a token count, so the total beside them is a
// FLOOR. A page that hides them presents the floor as a complete figure, which
// is the cost-surprise failure one step removed β€” the same reason
// `usage_ledger` books an unmeasured call as unknown rather than as zero.
//
// ⚠ SURFACE/READ SPLIT, as on Home and Starred: `renderToStaticMarkup` runs no
// effect, so a shot of the fetching component photographs only its spinner.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useRef, useState } from "react";
import { fmt } from "../ui/fmt";
import { loadUsage } from "./accountApi";
import type { Usage, UsageSurface } from "./accountApi";
import TurnAuditTable from "./TurnAuditTable";
import "./account.css";
/**
* The four surfaces C7 names, in the order R9 lists them.
*
* ⚠ AN UNKNOWN KEY IS HUMANISED, NEVER DROPPED. Dropping it would hide real usage from a meter
* whose whole job is to account for it, and printing the raw key would put an internal identifier
* on screen. The day a fifth LLM entry point lands (this product added two in one wave) it shows
* up here as a readable name with the right number beside it, and somebody can then decide what
* to call it.
*/
const SURFACE_LABEL: Record<string, string> = {
assistant: "Assistant",
field_agent: "Field agents",
ai_review: "Reviews",
automation_draft: "Drafting",
};
const ORDER = ["assistant", "field_agent", "ai_review", "automation_draft"];
export function surfaceLabel(key: string): string {
const known = SURFACE_LABEL[key];
if (known) return known;
const words = key.replace(/[_-]+/g, " ").trim();
return words ? words.charAt(0).toUpperCase() + words.slice(1) : key;
}
/** C7's order first, then anything the server added, alphabetically. */
export function orderSurfaces(surfaces: UsageSurface[]): UsageSurface[] {
const rank = (s: UsageSurface) => {
const i = ORDER.indexOf(s.surface);
return i === -1 ? ORDER.length : i;
};
return [...surfaces].sort(
(a, b) => rank(a) - rank(b) || surfaceLabel(a.surface).localeCompare(surfaceLabel(b.surface))
);
}
/**
* The bar's fill, as a percentage, CLAMPED to 100.
*
* ⚠ The clamp is what keeps "over the allowance" a COLOUR rather than a bar that overflows its
* own track and paints across the page. The number above the bar is unclamped and is where the
* overage is actually read.
* ⚠ An allowance of 0 (unset) yields 0 rather than a division by zero: no allowance means the
* meter has nothing to measure against, and a full red bar would be an assertion nobody made.
*/
export function barPct(value: number, of: number): number {
if (!(of > 0)) return 0;
return Math.max(0, Math.min(100, (value / of) * 100));
}
export type UsageLoad =
| { phase: "loading" }
| { phase: "ready"; usage: Usage }
| { phase: "failed"; message: string };
function Bar({ pct, over }: { pct: number; over: boolean }) {
return (
<span className="acct-bar" aria-hidden="true">
<span className={"acct-bar-fill" + (over ? " is-over" : "")} style={{ width: `${pct}%` }} />
</span>
);
}
export function UsageSurfaceRows({ usage }: { usage: Usage }) {
// ⚠ SCALED TO THE LARGEST SURFACE, NOT TO THE WEEK'S TOTAL, and the difference is legibility
// rather than accuracy. `total` is the week's whole figure and can legitimately exceed the sum
// of these four (unattributed calls are counted there and belong to nobody), so scaling to it
// shrinks every bar by an amount the reader cannot see the cause of. Scaled to the biggest row,
// the bars answer the question a row of bars is actually asked: which surface is spending most.
// The absolute number sits beside each one, so nothing here is only readable as a shape.
const biggest = usage.surfaces.reduce((m, s) => Math.max(m, s.tokens), 0);
return (
<div className="acct-rows">
{orderSurfaces(usage.surfaces).map((s) => (
<div key={s.surface} className="acct-row">
<span className="acct-row-name">{surfaceLabel(s.surface)}</span>
<Bar pct={barPct(s.tokens, biggest)} over={false} />
<span className="acct-row-num">{fmt.int(s.tokens)}</span>
<span className="acct-row-sub">
{fmt.int(s.calls)} {s.calls === 1 ? "call" : "calls"}
{/* β›” NOT HOVER-ONLY. A surface whose provider declined to report tokens has a
token number that is a floor, and D-253 is a booked defect whose entire content
is "the explanation was satisfied only on hover". */}
{s.unmeasured > 0 ? `, ${fmt.int(s.unmeasured)} not measured` : ""}
</span>
</div>
))}
</div>
);
}
/** Both account and Settings render the server's allowance and over flag here. */
export function AiUsageCard({ usage }: { usage: Usage }) {
return <>
<div className="acct-meter">
<div className="acct-meter-head">
<span className="acct-meter-who">{usage.scope === "tenant" ? "This workspace" : "You"}, this week</span>
</div>
<div className="acct-meter-head">
<span className={"acct-meter-value" + (usage.over ? " is-over" : "")}>{fmt.int(usage.total)}</span>
<span className="acct-meter-of">of {fmt.int(usage.allowance)} tokens</span>
</div>
<Bar pct={barPct(usage.total, usage.allowance)} over={usage.over} />
<div className="acct-meter-foot">
<span>Week {usage.week}. Resets {fmt.date(usage.resets)}.</span>
<span className="acct-meter-calls">{fmt.int(usage.calls)} {usage.calls === 1 ? "call" : "calls"}</span>
</div>
</div>
{usage.over ? <p className="acct-error" role="status">
Over allowance. AI remains available.
</p> : null}
{usage.note ? <p className="acct-note acct-note--inline">{usage.note}</p> : null}
</>;
}
export function UsageView({
load,
scope,
canSeeTenant,
onScope,
onRetry,
}: {
load: UsageLoad;
scope: "me" | "tenant";
/**
* Whether the workspace view is reachable AT ALL for this account.
*
* β›” THE TOGGLE IS NOT DRAWN WHEN IT IS NOT, and that is R8's fake-affordance rule applied to a
* permission: `?scope=tenant` is admin-only and 403s for everybody else, so an always-visible
* control would be a button most accounts can only be refused by.
*/
canSeeTenant: boolean;
onScope: (scope: "me" | "tenant") => void;
onRetry: () => void;
}) {
return (
<div className="acct-page">
<h1 className="acct-title">Usage</h1>
<div className="acct-col acct-col--usage">
{canSeeTenant ? (
<div className="acct-scope" role="group" aria-label="Whose usage">
{(["me", "tenant"] as const).map((key) => (
<button
key={key}
type="button"
className={"acct-scope-btn" + (scope === key ? " is-on" : "")}
aria-pressed={scope === key}
onClick={() => onScope(key)}
>
{key === "me" ? "You" : "Workspace"}
</button>
))}
</div>
) : null}
{load.phase === "loading" ? (
<div className="acct-loading">
<span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
</div>
) : load.phase === "failed" ? (
// β›” NOT A ZERO METER. A failed read and a quiet week look identical on screen unless
// this branch exists, and a meter reading zero is the most reassuring possible lie.
<div className="acct-failed">
<p className="acct-note">{load.message}</p>
<button type="button" className="acct-retry" onClick={onRetry}>
Try again
</button>
</div>
) : (
<>
<AiUsageCard usage={load.usage} />
<h2 className="acct-section">By surface</h2>
<UsageSurfaceRows usage={load.usage} />
{load.usage.scope === scope ? <TurnAuditTable key={scope} scope={scope} /> : null}
{load.usage.unattributed > 0 ? (
// ⚠ LABELLED A WIRING GAP, NOT USAGE (E-9). These are AI calls this container could
// not attribute to an account. Folding them into somebody's total would be an
// invented attribution, and leaving them out entirely would understate the week.
<p className="acct-note acct-note--inline">
{fmt.int(load.usage.unattributed)} tokens this week could not be attributed to an
account. That is a wiring gap in the meter, not somebody's usage.
</p>
) : null}
</>
)}
</div>
</div>
);
}
export default function UsagePage() {
const [load, setLoad] = useState<UsageLoad>({ phase: "loading" });
const [scope, setScope] = useState<"me" | "tenant">("me");
/**
* Whether the workspace view exists for this account, ANSWERED BY ASKING ONCE.
*
* β›” WHY A PROBE RATHER THAN A ROLE CHECK. The frame knows the role, but these pages take no
* props by contract (C6's trap: a page that decides its own visibility is a second opinion that
* will one day disagree with the route). The route itself is the authority, so the page asks it
* once: a 200 means the door is open and the toggle is real; a 403 means it is not and no
* control is drawn. ⚠ That 403 is an ANSWER, not an error β€” it is never shown to the reader.
* ⭐ AND IT IS WHAT GIVES `?scope=tenant` A DOOR. E built it admin-only; without this it would
* be a finished capability with no caller, which is this repo's most-repeated failure
* [[reachable-is-not-the-same-as-built]].
*/
const [canSeeTenant, setCanSeeTenant] = useState(false);
const gen = useRef(0);
const read = useCallback((which: "me" | "tenant") => {
const mine = gen.current + 1;
gen.current = mine;
setLoad({ phase: "loading" });
void loadUsage(which === "tenant" ? "tenant" : undefined).then((r) => {
if (gen.current !== mine) return;
setLoad(r.ok ? { phase: "ready", usage: r.value } : { phase: "failed", message: r.message });
});
}, []);
useEffect(() => {
read(scope);
return () => {
gen.current += 1;
};
}, [read, scope]);
useEffect(() => {
let live = true;
void loadUsage("tenant").then((r) => {
if (live) setCanSeeTenant(r.ok);
});
return () => {
live = false;
};
}, []);
return (
<UsageView
load={load}
scope={scope}
canSeeTenant={canSeeTenant}
onScope={setScope}
onRetry={() => read(scope)}
/>
);
}