File size: 29,299 Bytes
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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;
}