Download web/src/settings/UsagePane.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/settings/UsagePane.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/settings/UsagePane.tsx
-
curl -L -o UsagePane.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/settings/UsagePane.tsx
29.3 kB
| import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react"; | |
| import type { CSSProperties } from "react"; | |
| import { Funnel, X } from "@phosphor-icons/react"; | |
| import { createPortal } from "react-dom"; | |
| import { AiUsageCard } from "../account/UsagePage"; | |
| import { loadUsage } from "../account/accountApi"; | |
| import type { Usage } from "../account/accountApi"; | |
| import { UNAUTHORIZED_EVENT } from "../apiContract"; | |
| import { useOverlayLayer } from "../customer-grid/OverlaySurface"; | |
| import { Popover } from "../filter-kit"; | |
| import { isAdmin } from "../shell/session"; | |
| import type { SessionUser } from "../shell/session"; | |
| import { getUsageActivity, getUsageMcpActivity, listUsers, USAGE_KIND_LABELS } from "./settingsApi"; | |
| import type { UsageActivity, UsageActivityFilters, UsageKind, UsageMcpActivity, UsageMcpEvent, UsageSource } from "./settingsApi"; | |
| import "../styles/sdlc85/settings-usage.css"; | |
| const count = (value: number | null | undefined) => value == null ? "Unavailable" : value.toLocaleString(); | |
| const plain = (value: string) => value.replace(/[\u2013\u2014]/g, " "); | |
| const words = (value: string) => value.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").toLowerCase(); | |
| const sourceNames: Record<string, string> = { | |
| security_events: "Security events", activity_events: "Activity events", value_history: "Cell history", | |
| view_audit: "View history", turn_audit: "AI turns", | |
| }; | |
| function usageDates(now = new Date()) { | |
| const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); | |
| const first = new Date(today); | |
| first.setUTCDate(first.getUTCDate() - 29); | |
| const earliest = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - 13, 1)); | |
| const lastDay = new Date(Date.UTC(earliest.getUTCFullYear(), earliest.getUTCMonth() + 1, 0)).getUTCDate(); | |
| earliest.setUTCDate(Math.min(today.getUTCDate(), lastDay)); | |
| return { from: first.toISOString().slice(0, 10), to: today.toISOString().slice(0, 10), min: earliest.toISOString().slice(0, 10) }; | |
| } | |
| function Skeleton({ label = "Loading usage" }: { label?: string }) { | |
| return <div className="set-skeleton" role="status" aria-label={label} aria-busy="true"> | |
| {[0, 1, 2].map(row => <span key={row} className="set-skeleton-line" aria-hidden="true" />)} | |
| </div>; | |
| } | |
| function ReadError({ onRetry, reload = false }: { onRetry: () => void; reload?: boolean }) { | |
| return <div className="set-error" role="alert"> | |
| <span>{reload ? "Reload MCP activity to continue." : "Usage could not be loaded."}</span> | |
| <button type="button" className="set-secondary" onClick={onRetry}>{reload ? "Reload" : "Retry"}</button> | |
| </div>; | |
| } | |
| function Sources({ sources, onRetry }: { sources: UsageSource[]; onRetry: () => void }) { | |
| const limitLabels = new Map([ | |
| ["retention", "Retention limit"], ["legacy_ring", "Legacy event limit"], | |
| ["view_ring", "Stored view limit"], ["turn_week_cap", "Weekly AI limit"], | |
| ]); | |
| return <section className="set-usage-section" aria-label="Activity sources"> | |
| <h4 className="set-h4">Sources</h4> | |
| <div className="set-usage-table-wrap"> | |
| <table className="set-table set-usage-sources"> | |
| <thead><tr><th scope="col">Source</th><th scope="col">Held from</th><th scope="col">Retention</th><th scope="col">Limits</th></tr></thead> | |
| <tbody>{sources.map(source => <tr key={source.source}> | |
| <th scope="row">{sourceNames[source.source] || plain(words(source.source))} | |
| <span className="set-usage-meta">{source.kinds.map(kind => USAGE_KIND_LABELS[kind]).join(", ")}</span> | |
| <span className="set-usage-meta">{source.status === "error" ? "Unreadable" : source.status === "partial" ? "Partial" : "Available"}</span> | |
| <span className="set-usage-meta">{count(source.total)} events</span> | |
| </th> | |
| <td><time dateTime={source.heldFrom}>{plain(source.heldFrom.replace("T", " ").replace(/\.\d+/, ""))}</time></td> | |
| <td>{source.retention ? Object.entries(source.retention).map(([key, value]) => | |
| <div key={key}>{words(key)}: {value === null ? "Not time limited" : count(value)}</div>) : "Unavailable"}</td> | |
| <td>{source.error ? <div className="set-usage-source-error" role="alert"> | |
| <span title={plain(source.error.message)}>Source unavailable</span> | |
| <span className="set-usage-meta">{plain(words(source.error.code))}</span> | |
| <button type="button" className="set-secondary" onClick={onRetry}>Retry</button> | |
| </div> : null} | |
| {source.limitations.length ? source.limitations.map((limit, index) => <div className="set-usage-limit" key={`${limit.code}:${index}`}> | |
| <span title={plain(limit.cause)}>{limitLabels.get(limit.code) || "Source limit"}</span> | |
| {limit.week ? <span className="set-usage-meta">Week {limit.week}</span> : null} | |
| {limit.heldFrom ? <span className="set-usage-meta">Held from {plain(limit.heldFrom)}</span> : null} | |
| {limit.lost != null ? <span className="set-usage-meta">Lost: {count(limit.lost)}</span> : null} | |
| {limit.limit != null ? <span className="set-usage-meta">Limit: {count(limit.limit)}</span> : null} | |
| </div>) : source.error ? null : "None"}</td> | |
| </tr>)}</tbody> | |
| </table> | |
| </div> | |
| </section>; | |
| } | |
| function EventDetail({ event, onClose }: { event: UsageMcpEvent; onClose: () => void }) { | |
| const panelRef = useRef<HTMLDivElement>(null); | |
| const titleId = useId(); | |
| useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, trapFocus: true }); | |
| const fields: Array<[string, string]> = [ | |
| ["Tool", event.tool], ["Action", event.action], ["Outcome", event.outcome], ["Code", event.code], | |
| ["Time", event.time], ["User", event.user], ["Database", event.database], | |
| ["Key ID", event.keyId], ["Key label", event.keyLabel], | |
| ]; | |
| return createPortal(<div className="set-usage-detail-backdrop"> | |
| <div ref={panelRef} className="set-usage-detail" role="dialog" aria-modal="true" aria-labelledby={titleId}> | |
| <div className="set-usage-detail-head"><h4 id={titleId} className="set-h4">MCP event</h4> | |
| <button type="button" className="set-secondary" aria-label="Close event detail" onClick={onClose}><X size={16} aria-hidden="true" /></button></div> | |
| <dl className="set-usage-detail-fields">{fields.map(([label, value]) => <div key={label}> | |
| <dt>{label}</dt><dd>{plain(value) || "Unknown"}</dd> | |
| </div>)}</dl> | |
| </div> | |
| </div>, document.body); | |
| } | |
| function McpReport({ filters, tenant }: { filters: UsageActivityFilters; tenant: string }) { | |
| const [report, setReport] = useState<UsageMcpActivity | null>(null); | |
| const [events, setEvents] = useState<UsageMcpEvent[]>([]); | |
| const [selectedId, setSelectedId] = useState<string | null>(null); | |
| const [loading, setLoading] = useState(true); | |
| const [failed, setFailed] = useState(false); | |
| const [needsReload, setNeedsReload] = useState(false); | |
| const [revision, setRevision] = useState(0); | |
| const request = useRef<AbortController | null>(null); | |
| const read = useCallback(async (cursor?: string) => { | |
| request.current?.abort(); | |
| const controller = new AbortController(); | |
| request.current = controller; | |
| setLoading(true); setFailed(false); | |
| const result = await getUsageMcpActivity(filters, controller.signal, cursor); | |
| if (controller.signal.aborted) return; | |
| setLoading(false); | |
| if (!result.ok) { | |
| const invalidCursor = (result.status === 400 && result.code === "usage_mcp_cursor_invalid") | |
| || (result.status === 409 && result.code === "usage_mcp_cursor_stale"); | |
| setNeedsReload(invalidCursor); setFailed(true); setSelectedId(null); | |
| if (invalidCursor || result.status === 401 || result.status === 403) { setReport(null); setEvents([]); } | |
| return; | |
| } | |
| if (result.data.tenant !== tenant) { setFailed(true); setReport(null); setEvents([]); return; } | |
| setNeedsReload(false); setReport(result.data); | |
| setEvents(old => cursor ? [...old, ...result.data.events] : result.data.events); | |
| }, [filters, tenant]); | |
| useEffect(() => { | |
| setReport(null); setEvents([]); setSelectedId(null); setNeedsReload(false); | |
| void read(); | |
| return () => request.current?.abort(); | |
| }, [read, revision]); | |
| const reload = () => { setSelectedId(null); setRevision(value => value + 1); }; | |
| const selected = events.find(event => event.id === selectedId); | |
| return <section className="set-usage-section" aria-label="MCP activity"> | |
| <h4 className="set-h4">MCP activity</h4> | |
| {failed ? <ReadError reload={needsReload} onRetry={needsReload ? reload : () => { void read(report?.nextCursor || undefined); }} /> : null} | |
| {loading && !report ? <Skeleton label="Loading MCP activity" /> : null} | |
| {report ? <> | |
| <p className="set-help">{count(report.total)} calls{report.complete ? "" : " retained"}</p> | |
| <div className="set-usage-table-wrap"><table className="set-table" aria-label="MCP tool totals"> | |
| <thead><tr><th scope="col">Tool</th><th scope="col" className="is-numeric">Calls</th><th scope="col">Outcomes</th></tr></thead> | |
| <tbody>{report.byTool.map(row => <tr key={row.tool}> | |
| <th scope="row">{plain(row.tool)}</th><td className="is-numeric">{count(row.total)}</td> | |
| <td>{Object.entries(row.byOutcome).map(([outcome, total]) => <span key={outcome} className="set-usage-outcome">{plain(outcome)}: {count(total)}</span>)}</td> | |
| </tr>)}</tbody> | |
| </table></div> | |
| {report.total === 0 ? <p className="set-help" role="status">No MCP activity in this range</p> : null} | |
| {events.length ? <div className="set-usage-table-wrap"><table className="set-table set-usage-events" aria-label="MCP events"> | |
| <thead><tr><th scope="col">Tool</th><th scope="col">Outcome</th><th scope="col">User</th><th scope="col">Time</th></tr></thead> | |
| <tbody>{events.map(event => <tr key={event.id} onClick={() => setSelectedId(event.id)}> | |
| <td><button type="button" className="set-usage-event" onClick={() => setSelectedId(event.id)} aria-label={`Open ${plain(event.tool)} event`}> | |
| {plain(event.tool)}</button></td><td>{plain(event.outcome)}</td><td>{plain(event.user) || "Unknown"}</td> | |
| <td><time dateTime={event.time}>{new Date(event.time).toLocaleString()}</time></td> | |
| </tr>)}</tbody> | |
| </table></div> : null} | |
| <div className="set-usage-pages"><span className="set-help" role="status">{count(events.length)} of {count(report.total)} calls shown</span> | |
| {report.nextCursor && !failed ? <button type="button" className="set-secondary" disabled={loading} | |
| onClick={() => { void read(report.nextCursor || undefined); }}>{loading ? "Loading" : "Load more"}</button> : null} | |
| </div> | |
| {loading && report ? <Skeleton label="Loading more MCP activity" /> : null} | |
| <Sources sources={[report.source]} onRetry={reload} /> | |
| </> : null} | |
| {selected ? <EventDetail event={selected} onClose={() => setSelectedId(null)} /> : null} | |
| </section>; | |
| } | |
| const activityColors: Record<UsageKind, string> = { | |
| mcp: "var(--lp-freeze-navy)", api: "var(--lp-freeze-gold)", | |
| sign_in: "var(--lp-green-deep)", record_edit: "var(--lp-purple-deep)", | |
| field_edit: "var(--lp-teal-deep)", cell_edit: "var(--lp-orange-deep)", | |
| view_edit: "var(--lp-pink-deep)", ai_turn: "var(--lp-red-deep)", | |
| }; | |
| /** The narrowest readable day column, in px, before the Daily activity chart scrolls. */ | |
| const MIN_DAY_WIDTH = 12; | |
| function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: UsageKind[] }) { | |
| const [hiddenKinds, setHiddenKinds] = useState<UsageKind[]>([]); | |
| const [focusedDay, setFocusedDay] = useState(0); | |
| const [hoveredDay, setHoveredDay] = useState<number | null>(null); | |
| const chartRef = useRef<SVGSVGElement>(null); | |
| const scrollRef = useRef<HTMLDivElement>(null); | |
| const [boxWidth, setBoxWidth] = useState(0); | |
| const titleId = useId(); | |
| const descriptionId = useId(); | |
| const known = (value: number | null | undefined) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; | |
| // A kind with no range total cannot be read, so its rail row is disabled and it never joins the chart. | |
| const readable = kinds.filter(kind => known(report.byKind[kind]) !== null); | |
| const enabled = readable.filter(kind => !hiddenKinds.includes(kind)); | |
| const days = report.byDay.map(row => { | |
| const values = enabled.map(kind => ({ kind, value: known(row.byKind[kind]) })); | |
| return { day: row.day, values, knownTotal: values.reduce((total, item) => item.value === null ? total : total + item.value, 0), | |
| anyKnown: values.some(item => item.value !== null) }; | |
| }); | |
| const retained = !report.complete; | |
| const valueLabel = (value: number | null) => value === null ? "Unavailable" : `${count(value)}${retained ? " retained" : ""}`; | |
| const dayLabel = (day: string, short = false) => new Date(`${day}T00:00:00Z`).toLocaleDateString(undefined, | |
| short ? { month: "short", day: "numeric", timeZone: "UTC" } : { year: "numeric", month: "short", day: "numeric", timeZone: "UTC" }); | |
| const describeDay = (row: typeof days[number]) => `${dayLabel(row.day)}. ${row.values | |
| .map(item => `${USAGE_KIND_LABELS[item.kind]}: ${valueLabel(item.value)}`).join(". ")}`; | |
| const maximum = days.reduce((max, row) => Math.max(max, row.knownTotal), 0); | |
| const step = Math.max(1, Math.ceil(maximum / 4)); | |
| const ceiling = step * 4; | |
| const left = Math.max(48, count(ceiling).length * 8 + 12); | |
| const plotted = enabled.length > 0 && days.length > 0; | |
| // The plot fills its scroll box. It scrolls only when a day would fall under the readable minimum. | |
| useLayoutEffect(() => { | |
| const box = scrollRef.current; | |
| if (!box) return; | |
| const measure = () => setBoxWidth(Math.floor(box.getBoundingClientRect().width)); | |
| measure(); | |
| if (typeof ResizeObserver === "undefined") return; | |
| const observer = new ResizeObserver(measure); | |
| observer.observe(box); | |
| return () => observer.disconnect(); | |
| }, [plotted]); | |
| const width = Math.max(left + days.length * MIN_DAY_WIDTH + 16, boxWidth || 600); | |
| const top = 32; | |
| const plotHeight = 176; | |
| const bottom = top + plotHeight; | |
| const slot = (width - left - 16) / Math.max(days.length, 1); | |
| const labelEvery = Math.max(7, Math.ceil(days.length / 12)); | |
| const inspected = days[hoveredDay ?? focusedDay]; | |
| const unavailable = kinds.filter(kind => !readable.includes(kind) | |
| || (enabled.includes(kind) && report.byDay.some(row => known(row.byKind[kind]) === null))); | |
| const unavailableNames = unavailable.map(kind => USAGE_KIND_LABELS[kind]); | |
| const unavailableNote = unavailableNames.length | |
| ? `${unavailableNames.length > 1 ? `${unavailableNames.slice(0, -1).join(", ")} and ${unavailableNames[unavailableNames.length - 1]}` : unavailableNames[0]} unavailable` | |
| : ""; | |
| const toggle = (kind: UsageKind) => setHiddenKinds(old => old.includes(kind) ? old.filter(item => item !== kind) : [...old, kind]); | |
| return <section className="set-usage-section set-usage-chart" aria-labelledby={titleId}> | |
| <h4 id={titleId} className="set-h4">Daily activity</h4> | |
| <div className="set-usage-chart-layout"> | |
| <div className="set-usage-chart-rail" role="group" aria-label="Chart metrics"> | |
| <span className="set-usage-chart-label">Metrics</span> | |
| {kinds.map(kind => { | |
| const total = known(report.byKind[kind]); | |
| const on = total !== null && !hiddenKinds.includes(kind); | |
| return <button key={kind} type="button" role="switch" aria-checked={on} disabled={total === null} | |
| className={"set-usage-chart-metric" + (on ? " is-on" : "")} onClick={() => toggle(kind)} | |
| style={{ "--set-usage-swatch": activityColors[kind] } as CSSProperties}> | |
| <span className="set-usage-chart-swatch" aria-hidden="true" /> | |
| <span className="set-usage-chart-metric-name">{USAGE_KIND_LABELS[kind]}</span> | |
| <span className="set-usage-chart-metric-count">{count(total)}</span> | |
| </button>; | |
| })} | |
| </div> | |
| <div className="set-usage-chart-main"> | |
| <p className="set-help">{report.from} to {report.to} ({report.timezone}){retained ? " · Retained counts" : ""}</p> | |
| {!enabled.length ? <p className="set-help" role="status">{readable.length ? "Select a metric" : "Daily counts unavailable"}</p> | |
| : !days.length ? <p className="set-help" role="status">Daily counts unavailable</p> : <> | |
| <div ref={scrollRef} className="set-usage-chart-scroll" role="region" aria-label="Daily columns" tabIndex={0}> | |
| <svg ref={chartRef} className="set-usage-chart-plot" width={width} height={248} viewBox={`0 0 ${width} 248`} | |
| role="group" aria-labelledby={titleId} aria-describedby={descriptionId}> | |
| <desc id={descriptionId}>Stacked daily event counts for the enabled metrics. Use the arrow keys to browse days, or open Daily values. | |
| {retained ? " Counts cover retained activity only." : ""} | |
| {unavailableNote ? ` ${unavailableNote}. Unavailable counts have no segment.` : ""}</desc> | |
| <g className="set-usage-chart-axis" aria-hidden="true"> | |
| <text x={0} y={14}>Events</text> | |
| {[0, 1, 2, 3, 4].map(tick => { | |
| const y = bottom - tick * plotHeight / 4; | |
| return <g key={tick}> | |
| <line x1={left} x2={width - 16} y1={y} y2={y} /> | |
| <text x={left - 8} y={y} dy="0.35em" textAnchor="end">{count(tick * step)}</text> | |
| </g>; | |
| })} | |
| </g> | |
| {days.map((row, index) => { | |
| const x = left + index * slot; | |
| let stacked = 0; | |
| return <g key={row.day} data-day-index={index} className="set-usage-chart-day" role="img" | |
| tabIndex={index === focusedDay ? 0 : -1} aria-label={describeDay(row)} | |
| onPointerEnter={() => setHoveredDay(index)} onPointerLeave={() => setHoveredDay(null)} | |
| onFocus={() => { setHoveredDay(null); setFocusedDay(index); }} onKeyDown={event => { | |
| const next = event.key === "ArrowRight" ? Math.min(days.length - 1, index + 1) | |
| : event.key === "ArrowLeft" ? Math.max(0, index - 1) | |
| : event.key === "Home" ? 0 : event.key === "End" ? days.length - 1 : null; | |
| if (next === null) return; | |
| event.preventDefault(); | |
| const target = chartRef.current?.querySelector<SVGGElement>(`[data-day-index="${next}"]`); | |
| target?.focus(); | |
| target?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" }); | |
| }}> | |
| <title>{describeDay(row)}</title> | |
| <rect className="set-usage-chart-hit" x={x + 1} y={16} width={slot - 2} height={bottom - 14} aria-hidden="true" /> | |
| {row.values.map(({ kind, value }) => { | |
| if (value === null || value === 0) return null; | |
| stacked += value; | |
| return <rect key={kind} x={x + slot * 0.16} y={bottom - stacked / ceiling * plotHeight} | |
| width={slot * 0.68} height={value / ceiling * plotHeight} fill={activityColors[kind]} aria-hidden="true" />; | |
| })} | |
| {row.anyKnown && row.knownTotal === 0 | |
| ? <circle className="set-usage-chart-zero" cx={x + slot / 2} cy={bottom} r={2} aria-hidden="true" /> : null} | |
| {(index === 0 || index === days.length - 1 || (index % labelEvery === 0 && index < days.length - 3)) | |
| ? <text className="set-usage-chart-date" x={x + slot / 2} y={bottom + 24} | |
| textAnchor={index === 0 ? "start" : index === days.length - 1 ? "end" : "middle"} aria-hidden="true">{dayLabel(row.day, true)}</text> : null} | |
| </g>; | |
| })} | |
| </svg> | |
| </div> | |
| {unavailableNote ? <p className="set-usage-chart-note">{unavailableNote}</p> : null} | |
| {inspected ? <div className="set-usage-chart-readout"> | |
| <time dateTime={inspected.day}>{dayLabel(inspected.day)}</time> | |
| <dl>{inspected.values.map(({ kind, value }) => <div key={kind}> | |
| <dt><span className="set-usage-chart-swatch" style={{ background: activityColors[kind] }} aria-hidden="true" />{USAGE_KIND_LABELS[kind]}</dt> | |
| <dd>{valueLabel(value)}</dd> | |
| </div>)}</dl> | |
| </div> : null} | |
| <details className="set-usage-chart-values"> | |
| <summary>Daily values</summary> | |
| <div className="set-usage-table-wrap"><table className="set-table" aria-label="Daily activity values"> | |
| <thead><tr><th scope="col">Date</th>{enabled.map(kind => <th key={kind} scope="col" className="is-numeric">{USAGE_KIND_LABELS[kind]}</th>)}</tr></thead> | |
| <tbody>{days.map(row => <tr key={row.day}> | |
| <th scope="row"><time dateTime={row.day}>{dayLabel(row.day)}</time></th> | |
| {row.values.map(({ kind, value }) => <td key={kind} className="is-numeric">{valueLabel(value)}</td>)} | |
| </tr>)}</tbody> | |
| </table></div> | |
| </details> | |
| </>} | |
| </div> | |
| </div> | |
| </section>; | |
| } | |
| function ActivityReport({ filters, tenant, onUsers }: { | |
| filters: UsageActivityFilters; tenant: string; onUsers: (users: string[]) => void; | |
| }) { | |
| const [report, setReport] = useState<UsageActivity | null>(null); | |
| const [failed, setFailed] = useState(false); | |
| const [revision, setRevision] = useState(0); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setReport(null); setFailed(false); | |
| void getUsageActivity(filters, controller.signal).then(result => { | |
| if (controller.signal.aborted) return; | |
| if (!result.ok || result.data.tenant !== tenant) { setFailed(true); return; } | |
| setReport(result.data); onUsers(result.data.byUser.map(row => row.user)); | |
| }); | |
| return () => controller.abort(); | |
| }, [filters, tenant, onUsers, revision]); | |
| const retry = () => setRevision(value => value + 1); | |
| if (failed) return <ReadError onRetry={retry} />; | |
| if (!report) return <Skeleton />; | |
| const kinds = Object.keys(report.byKind) as UsageKind[]; | |
| const rangeFoot = report.complete ? "Selected range" : "Retained range"; | |
| // A null total means one source failed. The sum of the kinds that were read still shows, labelled as partial. | |
| const partialTotal = report.total == null && typeof report.availableTotal === "number"; | |
| const metrics: Array<[string, number | null | undefined, string]> = [ | |
| ["Total", partialTotal ? report.availableTotal : report.total, partialTotal ? "Excludes unavailable metrics" : rangeFoot], | |
| ...kinds.map(kind => [USAGE_KIND_LABELS[kind], report.byKind[kind], rangeFoot] as [string, number | null | undefined, string]), | |
| ]; | |
| const period = `${report.from} to ${report.to}`; | |
| return <> | |
| <dl className="set-usage-kpis" aria-label="Activity totals"> | |
| {metrics.map(([label, value, foot]) => | |
| <div className="set-usage-kpi" key={label}><dt>{label}</dt> | |
| <dd>{count(value)}</dd><dd className="set-usage-meta">{foot}</dd> | |
| </div>)} | |
| </dl> | |
| <DailyActivityChart report={report} kinds={kinds} /> | |
| <section className="set-usage-section" aria-label="Usage by user"> | |
| <h4 className="set-h4">By user</h4> | |
| <div className="set-usage-table-wrap"><table className="set-table" aria-label="Activity by user"> | |
| <thead><tr><th scope="col">User</th>{kinds.map(kind => <th key={kind} scope="col" className="is-numeric">{USAGE_KIND_LABELS[kind]}</th>)}</tr></thead> | |
| <tbody>{report.byUser.map(row => <tr key={row.user}><th scope="row">{plain(row.user) || "Unknown"}</th> | |
| {kinds.map(kind => <td key={kind} className="is-numeric">{count(row.byKind[kind])}</td>)} | |
| </tr>)}</tbody> | |
| </table></div> | |
| {!report.byUser.length ? <p className="set-help" role="status">{report.complete ? "No activity in this range" : "No retained activity in this range"}</p> : null} | |
| <p className="set-help">{period} ({report.timezone})</p> | |
| </section> | |
| {filters.kind === "mcp" ? <McpReport filters={filters} tenant={tenant} /> : null} | |
| <Sources sources={report.sources} onRetry={retry} /> | |
| </>; | |
| } | |
| function AiAllowance() { | |
| const [usage, setUsage] = useState<Usage | null>(null); | |
| const [failed, setFailed] = useState(false); | |
| const [revision, setRevision] = useState(0); | |
| useEffect(() => { | |
| let live = true; | |
| setUsage(null); setFailed(false); | |
| void loadUsage("tenant").then(result => { | |
| if (!live) return; | |
| if (result.ok) setUsage(result.value); | |
| else setFailed(true); | |
| }); | |
| return () => { live = false; }; | |
| }, [revision]); | |
| return <section className="set-usage-section set-usage-ai" aria-label="AI allowance"> | |
| <h4 className="set-h4">AI usage</h4> | |
| {failed ? <ReadError onRetry={() => setRevision(value => value + 1)} /> | |
| : usage ? <AiUsageCard usage={usage} /> : <Skeleton label="Loading AI usage" />} | |
| </section>; | |
| } | |
| function AdminUsagePane({ user }: { user: SessionUser }) { | |
| const [dates] = useState(() => usageDates()); | |
| const [filters, setFilters] = useState<UsageActivityFilters>({ from: dates.from, to: dates.to, user: "", kind: "" }); | |
| const [users, setUsers] = useState<string[]>([]); | |
| const [expired, setExpired] = useState(false); | |
| const [revision, setRevision] = useState(0); | |
| const addUsers = useCallback((names: string[]) => setUsers(old => [...new Set([...old, ...names])].sort()), []); | |
| useEffect(() => { | |
| let live = true; | |
| void listUsers().then(result => { if (live && result.ok) addUsers(result.data.users.map(row => row.username)); }); | |
| const expire = () => setExpired(true); | |
| window.addEventListener(UNAUTHORIZED_EVENT, expire); | |
| return () => { live = false; window.removeEventListener(UNAUTHORIZED_EVENT, expire); }; | |
| }, [addUsers]); | |
| const filterCount = Number(Boolean(filters.user)) + Number(Boolean(filters.kind)); | |
| const validRange = filters.from >= dates.min && filters.to <= dates.to && filters.from <= filters.to; | |
| const update = (patch: Partial<UsageActivityFilters>) => setFilters(old => ({ ...old, ...patch })); | |
| const key = JSON.stringify([filters, revision]); | |
| return <div className="set-pane set-usage"> | |
| <h3 className="set-h">Usage</h3> | |
| {expired ? <p className="set-notice" role="status">Reopen Settings to view usage.</p> : <> | |
| <div className="set-usage-toolbar" role="group" aria-label="Usage filters"> | |
| <label className="set-usage-date">From<input type="date" value={filters.from} min={dates.min} max={filters.to || dates.to} | |
| onChange={event => update({ from: event.target.value })} /></label> | |
| <label className="set-usage-date">To<input type="date" value={filters.to} min={filters.from || dates.min} max={dates.to} | |
| onChange={event => update({ to: event.target.value })} /></label> | |
| <Popover label={filterCount ? `Filter (${filterCount})` : "Filter"} icon={<Funnel size={16} aria-hidden="true" />} active={filterCount > 0} tone="filter"> | |
| {() => <div className="set-usage-filter-fields"> | |
| <label className="set-usage-filter">User<select value={filters.user} onChange={event => update({ user: event.target.value })}> | |
| <option value="">All users</option>{users.filter(Boolean).map(name => <option key={name} value={name}>{plain(name)}</option>)} | |
| </select></label> | |
| <label className="set-usage-filter">Kind<select value={filters.kind} onChange={event => update({ kind: event.target.value as UsageKind | "" })}> | |
| <option value="">All kinds</option>{Object.entries(USAGE_KIND_LABELS).map(([kind, label]) => <option key={kind} value={kind}>{label}</option>)} | |
| </select></label> | |
| <button type="button" className="set-secondary" disabled={!filterCount} onClick={() => update({ user: "", kind: "" })}>Clear</button> | |
| </div>} | |
| </Popover> | |
| <button type="button" className="set-secondary" onClick={() => update({ from: dates.from, to: dates.to })}>Last 30 days</button> | |
| <button type="button" className="set-secondary" onClick={() => update({ from: dates.min, to: dates.to })}>13 months</button> | |
| <button type="button" className="set-secondary" onClick={() => setRevision(value => value + 1)}>Refresh</button> | |
| </div> | |
| {filterCount ? <p className="set-help">{[filters.user ? `User: ${plain(filters.user)}` : "", filters.kind ? `Kind: ${USAGE_KIND_LABELS[filters.kind]}` : ""].filter(Boolean).join(" · ")}</p> : null} | |
| {!validRange ? <p className="set-error" role="alert">Choose dates within the last 13 months.</p> | |
| : <ActivityReport key={key} filters={filters} tenant={user.tenant} onUsers={addUsers} />} | |
| <AiAllowance key={revision} /> | |
| </>} | |
| </div>; | |
| } | |
| export default function UsagePane({ user }: { user: SessionUser }) { | |
| return isAdmin(user) ? <AdminUsagePane key={`${user.tenant}:${user.username}:${user.role}`} user={user} /> : null; | |
| } | |