-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.tsx
More file actions
1007 lines (954 loc) · 39.8 KB
/
Copy pathapp.tsx
File metadata and controls
1007 lines (954 loc) · 39.8 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
definePluginApp,
useComposer,
useRealtime,
useRealtimeConnectionState,
useRpc,
} from "@get-bb/plugin-sdk/app";
import type { PluginRealtimeConnectionState } from "@get-bb/plugin-sdk/app";
import type { AnalyticsBundle, AnalyticsVisualization } from "./bundle-contract.ts";
import {
getBrowserAnalyticsEngine,
type BrowserDashboardResult,
type BrowserQueryResult,
} from "./browser-engine.ts";
import type { AnalyticsBundleResponse, AnalyticsCatalogResponse, rpcContract } from "./rpc-contract.ts";
import { ChartPaintingAnimation } from "./chart-painting-animation.tsx";
import { EChartsFigure } from "./echarts-figure.tsx";
import { compileEChartsFigure, type AnalyticsCompiledFigure } from "./echarts-options.ts";
import { useAnalyticsChartEnvironment } from "./chart-environment.ts";
import { downloadDataUrl, downloadText, rowsToCsv } from "./analytics-export.ts";
import { formatAnalyticsValue } from "./formatting.ts";
import { describeIndexStatus } from "./analytics-status.ts";
import type { ChartIntent, FigureRuntimeController, InteractiveDatumMeta } from "./analytics-model.ts";
import "./app.css";
type AnalyticsDashboard = AnalyticsBundleResponse & BrowserDashboardResult;
type QueryResult = BrowserQueryResult;
type QueryRow = QueryResult["rows"][number];
const RANGE_OPTIONS = [
{ value: 1, label: "24 hours" },
{ value: 7, label: "7 days" },
{ value: 14, label: "14 days" },
{ value: 30, label: "30 days" },
{ value: 90, label: "90 days" },
] as const;
function AnalyticsPanel() {
const rpc = useRpc<typeof rpcContract>();
const connection = useRealtimeConnectionState();
const [catalog, setCatalog] = useState<AnalyticsCatalogResponse | null>(null);
const [dashboard, setDashboard] = useState<AnalyticsDashboard | null>(null);
const [bundleId, setBundleId] = useState("tool-reliability");
const [rangeDays, setRangeDays] = useState(14);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const requestSequence = useRef(0);
const requestController = useRef<AbortController | null>(null);
const loadCatalog = useCallback(async () => {
const next = await rpc.call("catalog");
setCatalog(next);
setBundleId((current) => next.bundles.some((bundle) => bundle.id === current)
? current
: next.bundles[0]?.id ?? "tool-reliability");
return next;
}, [rpc]);
const loadDashboard = useCallback(async (
selectedBundleId = bundleId,
selectedRangeDays = rangeDays,
selectedIndex = catalog?.index,
) => {
const sequence = ++requestSequence.current;
requestController.current?.abort();
const controller = new AbortController();
requestController.current = controller;
setLoading(true);
setError(null);
try {
const selected = await rpc.call("getBundle", { bundleId: selectedBundleId });
const engine = await getBrowserAnalyticsEngine();
const result = await engine.loadAndRun(selected.bundle, selectedRangeDays, {
generationId: selectedIndex?.generationId ?? null,
asOf: indexAsOf(selectedIndex),
signal: controller.signal,
});
if (sequence === requestSequence.current) setDashboard({ ...selected, ...result });
} catch (cause) {
if (sequence === requestSequence.current && !isAbortError(cause)) {
setError(cause instanceof Error ? cause.message : "Analytics could not run this dashboard.");
}
} finally {
if (sequence === requestSequence.current) setLoading(false);
if (requestController.current === controller) requestController.current = null;
}
}, [bundleId, catalog, rangeDays, rpc]);
useEffect(() => {
// Analytics was explicitly opened, so overlap lazy worker startup with
// catalog loading while every other BB surface remains idle.
void getBrowserAnalyticsEngine().catch(() => {
// loadDashboard owns the user-visible retry/error state.
});
void loadCatalog()
.then((next) => loadDashboard(next.bundles[0]?.id ?? bundleId, rangeDays, next.index))
.catch((cause) => {
setError(cause instanceof Error ? cause.message : "Analytics could not load.");
setLoading(false);
});
}, [loadCatalog]);
useRealtime("analytics-index-changed", useCallback(() => {
void loadCatalog().then((next) => {
setRefreshing(next.index.status === "indexing");
if (next.index.status === "ready") void loadDashboard(bundleId, rangeDays, next.index);
}).catch((cause) => {
setRefreshing(false);
setError(cause instanceof Error ? cause.message : "Analytics could not refresh its catalog.");
});
}, [loadCatalog, loadDashboard]));
useRealtime("analytics-bundles-changed", useCallback(() => {
void loadCatalog().then((next) => {
const nextBundleId = next.bundles.some((bundle) => bundle.id === bundleId)
? bundleId
: next.bundles[0]?.id ?? "tool-reliability";
if (nextBundleId !== bundleId) setBundleId(nextBundleId);
void loadDashboard(nextBundleId, rangeDays, next.index);
}).catch((cause) => {
setError(cause instanceof Error ? cause.message : "Analytics could not reload its dashboards.");
});
}, [bundleId, loadCatalog, loadDashboard, rangeDays]));
useEffect(() => {
if (connection === "connected") return;
setRefreshing(false);
}, [connection]);
useEffect(() => () => requestController.current?.abort(), []);
const selectBundle = (nextId: string) => {
setBundleId(nextId);
void loadDashboard(nextId, rangeDays, catalog?.index);
};
const selectRange = (nextRange: number) => {
setRangeDays(nextRange);
void loadDashboard(bundleId, nextRange, catalog?.index);
};
const refreshIndex = async () => {
if (refreshing || index?.status === "indexing") return;
setRefreshing(true);
try {
const index = await rpc.call("requestRefresh");
setCatalog((current) => current == null ? current : { ...current, index });
} catch (cause) {
setRefreshing(false);
setError(cause instanceof Error ? cause.message : "Could not request a refresh.");
}
};
const shownDashboard = dashboard?.bundle.id === bundleId ? dashboard : null;
const index = catalog?.index ?? null;
const indexRefreshing = refreshing || index?.status === "indexing";
const coldState = index != null
&& index.generationId === 0
&& index.snapshotUpdatedAt == null
&& (index.status === "empty" || index.status === "indexing");
return (
<main className="analytics-shell">
<div className="analytics-toolbar">
<label className="analytics-field">
<span>Dashboard</span>
<select value={bundleId} onChange={(event) => selectBundle(event.target.value)}>
{(catalog?.bundles ?? []).map((bundle) => (
<option key={bundle.id} value={bundle.id}>{bundle.title}{bundle.builtin ? "" : " · authored"}</option>
))}
</select>
</label>
<label className="analytics-field">
<span>Range</span>
<select value={rangeDays} onChange={(event) => selectRange(Number(event.target.value))}>
{RANGE_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
</label>
<button
type="button"
className="analytics-refresh"
disabled={indexRefreshing}
aria-busy={indexRefreshing}
onClick={() => void refreshIndex()}
>
<RefreshIcon spinning={indexRefreshing} />
<span>Refresh</span>
</button>
</div>
<IndexStatus index={index} connection={connection} refreshing={indexRefreshing} />
{error != null && shownDashboard == null ? (
<EmptyState title="Analytics could not load" detail={error} action={() => void loadDashboard(bundleId, rangeDays, index ?? undefined)} />
) : coldState ? (
index?.status === "indexing" ? (
<LoadingState
title="Painting your first dashboard…"
detail="Building the bounded capability snapshot."
/>
) : (
<EmptyState
title="No capability snapshot yet"
detail="Analytics is waiting for its first bounded snapshot."
action={() => void refreshIndex()}
/>
)
) : shownDashboard == null ? (
<LoadingState title="Painting your dashboard…" detail="Opening the bounded capability snapshot." />
) : (
<>
{error != null && (
<div className="analytics-dashboard-error" role="alert">
<span>{error}</span>
<button type="button" onClick={() => void loadDashboard(bundleId, rangeDays, index ?? undefined)}>Try again</button>
</div>
)}
<Dashboard dashboard={shownDashboard} loading={loading} refreshing={indexRefreshing} />
</>
)}
</main>
);
}
const Dashboard = memo(function Dashboard({ dashboard, loading, refreshing }: { dashboard: AnalyticsDashboard; loading: boolean; refreshing: boolean }) {
const rpc = useRpc<typeof rpcContract>();
const composer = useComposer();
const chartEnvironment = useAnalyticsChartEnvironment();
const [figureMenu, setFigureMenu] = useState<FigureMenuState | null>(null);
const resultsById = useMemo(
() => new Map(dashboard.results.map((result) => [result.id, result])),
[dashboard.results],
);
const visualizationsById = useMemo(
() => new Map(dashboard.bundle.visualizations.map((visualization) => [visualization.id, visualization])),
[dashboard.bundle.visualizations],
);
const queriesById = useMemo(
() => new Map(dashboard.bundle.queries.map((query) => [query.id, query])),
[dashboard.bundle.queries],
);
const createReference = useCallback(async (state: FigureMenuState) => rpc.call("createReference", {
bundleId: dashboard.bundle.id,
queryId: state.visualization.queryId,
visualizationId: state.visualization.id,
resultGeneration: state.result.generation,
snapshotGenerationId: dashboard.generationId,
snapshotUpdatedAt: dashboard.asOf,
rangeDays: dashboard.rangeDays,
coverage: state.result.extent,
selection: state.datum == null ? null : {
datumKey: state.datum.datumKey,
label: state.datum.label,
row: {
[state.visualization.x]: state.datum.row[state.visualization.x] ?? null,
[state.visualization.y]: state.datum.row[state.visualization.y] ?? null,
},
predicate: state.datum.predicate,
},
}), [dashboard, rpc]);
return (
<div className="analytics-dashboard" aria-busy={loading}>
<span ref={chartEnvironment.probeRef} className="analytics-echart-theme-probe" aria-hidden="true" />
<header className="analytics-dashboard-heading">
<div>
<div className="analytics-title-line">
<h1>{dashboard.bundle.title}</h1>
{!dashboard.builtin && <span>Authored bundle</span>}
</div>
<p>{dashboard.bundle.description}</p>
</div>
<div className="analytics-dashboard-meta">
<span>{loading || refreshing ? `Refreshing dashboard · ${formatAsOf(dashboard.asOf)}` : formatAsOf(dashboard.asOf)}</span>
<span className="analytics-query-health" title="Total worker time across this bundle's bounded DuckDB queries">
{dashboard.queryMs.toLocaleString()} ms query time
</span>
</div>
</header>
<div className="analytics-grid">
{dashboard.bundle.layout.map((item) => {
const visualization = visualizationsById.get(item.visualizationId);
if (visualization == null) return null;
return (
<VisualizationCard
key={visualization.id}
visualization={visualization}
result={resultsById.get(visualization.queryId) ?? null}
query={queriesById.get(visualization.queryId) ?? null}
width={item.width}
chartTheme={chartEnvironment.theme}
reducedMotion={chartEnvironment.reducedMotion}
onOpenMenu={setFigureMenu}
/>
);
})}
</div>
<details className="analytics-diagnostics">
<summary>Bundle and query diagnostics</summary>
<div>
<span>Loader: {dashboard.bundle.loader.label}</span>
<span>{dashboard.bundle.queries.length} queries</span>
<span>{dashboard.bundle.visualizations.length} visualizations</span>
<span>DuckDB startup: {dashboard.startupMs.toLocaleString()} ms</span>
<span>Fact load: {dashboard.loadMs.toLocaleString()} ms · {formatBytes(dashboard.factBytes)}{dashboard.materializationCached ? " · reused" : ""}</span>
{dashboard.results.map((result) => (
<span key={result.id}>{result.id}: {result.cached ? "reused" : `${result.elapsedMs.toLocaleString()} ms`}{result.truncated ? " · capped" : ""}</span>
))}
</div>
</details>
{figureMenu != null && (
<FigureContextMenu
state={figureMenu}
lineage={{
bundleId: dashboard.bundle.id,
snapshotGenerationId: dashboard.generationId,
snapshotUpdatedAt: dashboard.asOf,
rangeDays: dashboard.rangeDays,
}}
onClose={() => setFigureMenu(null)}
onCopyReference={async () => {
const reference = await createReference(figureMenu);
await navigator.clipboard.writeText(reference.token);
return `Copied ${reference.token}`;
}}
onAddToChat={async () => {
const reference = await createReference(figureMenu);
composer.insertMention({
provider: "analytics-reference",
id: reference.id,
label: `Analytics: ${reference.label}`,
});
composer.focus();
setFigureMenu(null);
}}
/>
)}
</div>
);
});
const VisualizationCard = memo(function VisualizationCard({
visualization,
result,
query,
width,
chartTheme,
reducedMotion,
onOpenMenu,
}: {
visualization: AnalyticsVisualization;
result: QueryResult | null;
query: AnalyticsBundle["queries"][number] | null;
width: "third" | "half" | "full";
chartTheme: ReturnType<typeof useAnalyticsChartEnvironment>["theme"];
reducedMotion: boolean;
onOpenMenu: (menu: FigureMenuState) => void;
}) {
const rows = result?.rows ?? [];
const chartVisualization = visualization.kind === "bar" || visualization.kind === "line" ? visualization : null;
const compilation = useMemo(() => {
if (chartVisualization == null || result == null) return { figure: null, error: null };
try {
return { figure: compileEChartsFigure(chartVisualization, result, chartTheme, reducedMotion), error: null };
} catch (cause) {
return { figure: null, error: cause instanceof Error ? cause.message : "This result cannot be plotted." };
}
},
[chartTheme, chartVisualization, reducedMotion, result]);
const figure = compilation.figure;
const controller = useRef<FigureRuntimeController | null>(null);
const openMenu = useCallback((intent: ChartIntent, restoreTo?: HTMLElement | null) => {
if (figure == null || result == null || query == null) return;
onOpenMenu({
figure,
result,
visualization: figure.visualization,
query,
datum: intent.target.kind === "datum" ? intent.target.datum : null,
clientX: intent.clientX,
clientY: intent.clientY,
controller: controller.current,
restoreTo: restoreTo ?? null,
});
}, [figure, onOpenMenu, query, result]);
return (
<section className="analytics-card" data-width={width}>
{visualization.kind === "metric" ? (
<Metric visualization={visualization} row={rows[0] ?? null} />
) : (
<>
<header>
<h2>{visualization.title}</h2>
<div className="analytics-card-heading-actions">
{figure != null && result != null && query != null && (
<button
type="button"
aria-label={`Actions for ${visualization.title}`}
onClick={(event) => {
const bounds = event.currentTarget.getBoundingClientRect();
openMenu({
kind: "open-context-menu",
figureId: visualization.id,
clientX: bounds.right,
clientY: bounds.bottom,
target: { kind: "figure" },
source: "keyboard",
}, event.currentTarget);
}}
>•••</button>
)}
{result != null && <span>{result.cached ? "reused" : `${result.elapsedMs.toLocaleString()} ms`}</span>}
</div>
</header>
{compilation.error != null ? (
<p className="analytics-card-empty">{compilation.error}</p>
) : rows.length === 0 ? (
<p className="analytics-card-empty">No matching activity in this range.</p>
) : visualization.kind === "table" ? (
result != null && <ResultTable visualization={visualization} result={result} />
) : (
figure != null && (
<>
<EChartsFigure figure={figure} onIntent={openMenu} onController={(next) => { controller.current = next; }} />
<ChartDataDisclosure figure={figure} onOpenMenu={openMenu} />
</>
)
)}
</>
)}
</section>
);
});
function Metric({ visualization, row }: {
visualization: Extract<AnalyticsVisualization, { kind: "metric" }>;
row: QueryRow | null;
}) {
return (
<div className="analytics-metric">
<span>{visualization.title}</span>
<strong>{formatAnalyticsValue(row?.[visualization.value] ?? null, visualization.format)}</strong>
{visualization.detail != null && <small>{String(row?.[visualization.detail] ?? "")}</small>}
</div>
);
}
function ResultTable({
visualization,
result,
}: {
visualization: Extract<AnalyticsVisualization, { kind: "table" }>;
result: QueryResult;
}) {
if (visualization.id === "native-command-outcomes-table") {
return <CommandOutcomesTable result={result} />;
}
return (
<div className="analytics-table-scroll">
<table>
<thead>
<tr>{visualization.columns.map((column) => <th key={column.field} scope="col">{column.label}</th>)}</tr>
</thead>
<tbody>
{result.rows.map((row, index) => (
<tr key={result.datumKeys[index]}>
{visualization.columns.map((column) => (
<td key={column.field}>{formatAnalyticsValue(row[column.field] ?? null, column.format)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
type CommandInvestigationLevel = "binary" | "argument-1" | "signature";
type CommandInvestigationSlice = "all" | "eligible" | "help" | "observed-not-attributed" | "shell-wrapped" | "composite";
type CommandInvestigationSort = "calls" | "eligible" | "attributed" | "rate" | "help" | "observed" | "notAttributed";
type CommandInvestigationRow = Readonly<{
key: string;
label: string;
calls: number;
eligible: number;
attributed: number;
help: number;
observed: number;
notAttributed: number;
shellWrapped: number;
composite: number;
}>;
const COMMAND_LEVEL_LABELS: Readonly<Record<CommandInvestigationLevel, string>> = {
binary: "Binary",
"argument-1": "Binary + argument 1",
signature: "Full safe signature",
};
const COMMAND_SLICE_LABELS: Readonly<Record<CommandInvestigationSlice, string>> = {
all: "All executions",
eligible: "Eligible direct",
help: "Contains --help",
"observed-not-attributed": "Observed, not attributed",
"shell-wrapped": "Shell wrapped",
composite: "Composite or unparsed",
};
const COMMAND_SORT_LABELS: Readonly<Record<CommandInvestigationSort, string>> = {
calls: "Calls",
eligible: "Eligible direct",
attributed: "Attributed failures",
rate: "Attributed rate",
help: "Help",
observed: "Observed failed/nonzero",
notAttributed: "Observed, not attributed",
};
function CommandOutcomesTable({ result }: { result: QueryResult }) {
const [level, setLevel] = useState<CommandInvestigationLevel>("signature");
const [slice, setSlice] = useState<CommandInvestigationSlice>("all");
const [search, setSearch] = useState("");
const [sort, setSort] = useState<CommandInvestigationSort>("calls");
const [direction, setDirection] = useState<"ascending" | "descending">("descending");
const rows = useMemo(() => commandInvestigationRows(result.rows, level), [level, result.rows]);
const displayedRows = useMemo(() => {
const normalizedSearch = search.trim().toLocaleLowerCase();
return rows
.filter((row) => {
if (normalizedSearch !== "" && !row.label.toLocaleLowerCase().includes(normalizedSearch)) return false;
if (slice === "eligible") return row.eligible > 0;
if (slice === "help") return row.help > 0;
if (slice === "observed-not-attributed") return row.notAttributed > 0;
if (slice === "shell-wrapped") return row.shellWrapped > 0;
if (slice === "composite") return row.composite > 0;
return true;
})
.toSorted((left, right) => {
const order = direction === "descending" ? -1 : 1;
const delta = commandSortValue(left, sort) - commandSortValue(right, sort);
return delta === 0 ? left.label.localeCompare(right.label) : order * delta;
});
}, [direction, rows, search, slice, sort]);
const setSortColumn = useCallback((next: CommandInvestigationSort) => {
if (next === sort) setDirection((current) => current === "descending" ? "ascending" : "descending");
else {
setSort(next);
setDirection("descending");
}
}, [sort]);
const reset = useCallback(() => {
setLevel("signature");
setSlice("all");
setSearch("");
setSort("calls");
setDirection("descending");
}, []);
const resultScope = result.extent.kind === "exact"
? `${result.extent.rows.toLocaleString()} signature rows`
: `the first ${result.rows.length.toLocaleString()} of at least ${result.extent.rows.toLocaleString()} signature rows`;
return (
<div className="analytics-command-investigation">
<p className="analytics-command-investigation__description">
Frequency-first investigation index. Attributed rates use only eligible, direct executions; composite, wrapped, help, and unparsed failures are observed but not attributed to the displayed first segment.
</p>
<div className="analytics-command-investigation__controls">
<label>
<span>Group by</span>
<select value={level} onChange={(event) => setLevel(event.target.value as CommandInvestigationLevel)}>
{Object.entries(COMMAND_LEVEL_LABELS).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select>
</label>
<label>
<span>Slice</span>
<select value={slice} onChange={(event) => setSlice(event.target.value as CommandInvestigationSlice)}>
{Object.entries(COMMAND_SLICE_LABELS).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select>
</label>
<label className="analytics-command-investigation__search">
<span>Find binary or safe argument</span>
<input value={search} onChange={(event) => setSearch(event.target.value)} type="search" placeholder="e.g. rg or --help" />
</label>
<button type="button" onClick={reset}>Reset</button>
</div>
<div className="analytics-table-scroll">
<table>
<caption>Showing {displayedRows.length.toLocaleString()} grouped rows from {resultScope}; source ranking is Calls descending.</caption>
<thead>
<tr>
<th scope="col">{COMMAND_LEVEL_LABELS[level]}</th>
<CommandSortHeader column="calls" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="eligible" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="attributed" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="rate" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="help" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="observed" active={sort} direction={direction} onSort={setSortColumn} />
<CommandSortHeader column="notAttributed" active={sort} direction={direction} onSort={setSortColumn} />
<th scope="col">Context</th>
</tr>
</thead>
<tbody>
{displayedRows.map((row) => (
<tr key={row.key}>
<th scope="row">{row.label}</th>
<td>{formatAnalyticsValue(row.calls, "integer")}</td>
<td>{formatAnalyticsValue(row.eligible, "integer")}</td>
<td>{row.eligible === 0 ? "—" : `${formatAnalyticsValue(row.attributed, "integer")} / ${formatAnalyticsValue(row.eligible, "integer")}`}</td>
<td>{row.eligible === 0 ? "—" : formatAnalyticsValue(100 * row.attributed / row.eligible, "percent")}</td>
<td>{formatAnalyticsValue(row.help, "integer")}</td>
<td>{formatAnalyticsValue(row.observed, "integer")}</td>
<td>{formatAnalyticsValue(row.notAttributed, "integer")}</td>
<td>{commandContext(row)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
function CommandSortHeader({
column,
active,
direction,
onSort,
}: {
column: CommandInvestigationSort;
active: CommandInvestigationSort;
direction: "ascending" | "descending";
onSort: (column: CommandInvestigationSort) => void;
}) {
const isActive = column === active;
return (
<th scope="col" aria-sort={isActive ? direction : "none"}>
<button type="button" onClick={() => onSort(column)}>
{COMMAND_SORT_LABELS[column]}{isActive ? direction === "descending" ? " ↓" : " ↑" : ""}
</button>
</th>
);
}
function commandInvestigationRows(source: readonly QueryRow[], level: CommandInvestigationLevel): CommandInvestigationRow[] {
const groups = new Map<string, CommandInvestigationRow>();
for (const row of source) {
const binary = commandText(row.command_binary);
const argument1 = commandText(row.command_argument_1);
const argument2 = commandText(row.command_argument_2);
const label = level === "binary"
? binary
: level === "argument-1"
? `${binary} ${argument1}`
: `${binary} ${argument1}${argument2 === "—" ? "" : ` ${argument2}`}`;
const existing = groups.get(label);
const next: CommandInvestigationRow = existing ?? {
key: label,
label,
calls: 0,
eligible: 0,
attributed: 0,
help: 0,
observed: 0,
notAttributed: 0,
shellWrapped: 0,
composite: 0,
};
const merged = {
...next,
calls: next.calls + commandNumber(row.calls),
eligible: next.eligible + commandNumber(row.eligible_executions),
attributed: next.attributed + commandNumber(row.attributed_actual_failures),
help: next.help + commandNumber(row.contains_help_calls),
observed: next.observed + commandNumber(row.observed_failed_or_nonzero_executions),
notAttributed: next.notAttributed + commandNumber(row.observed_not_attributed_executions),
shellWrapped: next.shellWrapped + commandNumber(row.shell_wrapped_executions),
composite: next.composite + commandNumber(row.composite_or_unparsed_executions),
};
groups.set(label, merged);
}
return [...groups.values()];
}
function commandSortValue(row: CommandInvestigationRow, sort: CommandInvestigationSort): number {
if (sort === "calls") return row.calls;
if (sort === "eligible") return row.eligible;
if (sort === "attributed") return row.attributed;
if (sort === "rate") return row.eligible === 0 ? -1 : row.attributed / row.eligible;
if (sort === "help") return row.help;
if (sort === "observed") return row.observed;
return row.notAttributed;
}
function commandContext(row: CommandInvestigationRow): string {
const context = [
row.eligible === row.calls ? "direct eligible" : null,
row.help > 0 ? `${row.help} help` : null,
row.shellWrapped > 0 ? `${row.shellWrapped} shell wrapped` : null,
row.composite > 0 ? `${row.composite} composite/unparsed` : null,
].filter((value): value is string => value != null);
return context.length === 0 ? "—" : context.join(" · ");
}
function commandText(value: QueryRow[string]): string {
return typeof value === "string" && value !== "" ? value : "—";
}
function commandNumber(value: QueryRow[string]): number {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
type FigureMenuState = {
figure: AnalyticsCompiledFigure;
result: QueryResult;
visualization: Extract<AnalyticsVisualization, { kind: "bar" | "line" }>;
query: AnalyticsBundle["queries"][number];
datum: InteractiveDatumMeta | null;
clientX: number;
clientY: number;
controller: FigureRuntimeController | null;
restoreTo: HTMLElement | null;
};
function ChartDataDisclosure({
figure,
onOpenMenu,
}: {
figure: AnalyticsCompiledFigure;
onOpenMenu: (intent: ChartIntent, restoreTo?: HTMLElement | null) => void;
}) {
const [open, setOpen] = useState(false);
const total = figure.total.kind === "exact"
? `${figure.total.rows.toLocaleString()}`
: `at least ${figure.total.rows.toLocaleString()}`;
return (
<details className="analytics-chart-data" onToggle={(event) => setOpen(event.currentTarget.open)}>
<summary>Exact plotted data · showing {figure.plottedCount.toLocaleString()} of {total}</summary>
{open && <div className="analytics-table-scroll">
<table>
<thead>
<tr>
<th scope="col">{figure.visualization.x}</th>
<th scope="col">{figure.visualization.y}</th>
<th scope="col"><span className="analytics-visually-hidden">Actions</span></th>
</tr>
</thead>
<tbody>
{figure.plottedRows.map((row, index) => {
const datum = figure.dataIndex.get(index);
return (
<tr key={figure.plottedDatumKeys[index]}>
<td>{String(row[figure.visualization.x] ?? "—")}</td>
<td>{formatAnalyticsValue(row[figure.visualization.y], figure.format)}</td>
<td>
{datum != null && (
<button
type="button"
onClick={(event) => {
const bounds = event.currentTarget.getBoundingClientRect();
onOpenMenu({
kind: "open-context-menu",
figureId: figure.visualization.id,
clientX: bounds.right,
clientY: bounds.bottom,
target: { kind: "datum", datum },
source: "keyboard",
}, event.currentTarget);
}}
>Actions</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>}
</details>
);
}
function FigureContextMenu({
state,
lineage,
onClose,
onCopyReference,
onAddToChat,
}: {
state: FigureMenuState;
lineage: {
bundleId: string;
snapshotGenerationId: number | null;
snapshotUpdatedAt: number | null;
rangeDays: number;
};
onClose: () => void;
onCopyReference: () => Promise<string>;
onAddToChat: () => Promise<void>;
}) {
const menu = useRef<HTMLDivElement | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [pending, setPending] = useState(false);
useEffect(() => {
const target = menu.current;
const first = target?.querySelector<HTMLButtonElement>("button:not(:disabled)");
first?.focus();
const dismiss = (event: PointerEvent) => {
if (target != null && !target.contains(event.target as Node)) onClose();
};
document.addEventListener("pointerdown", dismiss);
return () => {
document.removeEventListener("pointerdown", dismiss);
if (state.restoreTo?.isConnected) state.restoreTo.focus();
};
}, [onClose, state.restoreTo]);
const run = async (action: () => Promise<string | void>) => {
setPending(true);
setMessage(null);
try {
const next = await action();
if (typeof next === "string") setMessage(next);
} catch (cause) {
setMessage(cause instanceof Error ? cause.message : "That action could not be completed.");
} finally {
setPending(false);
}
};
const filename = safeFilename(`${state.visualization.id}-${state.datum?.label ?? "figure"}`);
const left = Math.max(8, Math.min(state.clientX, window.innerWidth - 248));
const top = Math.max(8, Math.min(state.clientY, window.innerHeight - 300));
return (
<div
ref={menu}
className="analytics-context-menu"
role="menu"
aria-label={`Actions for ${state.datum?.label ?? state.visualization.title}`}
style={{ left, top }}
onContextMenu={(event) => event.preventDefault()}
onKeyDown={(event) => {
if (event.key === "Escape") { event.preventDefault(); onClose(); return; }
if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
event.preventDefault();
const items = [...(menu.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? [])];
const current = items.indexOf(document.activeElement as HTMLButtonElement);
const direction = event.key === "ArrowDown" ? 1 : -1;
items[(current + direction + items.length) % items.length]?.focus();
}}
>
<strong>{state.datum?.label ?? state.visualization.title}</strong>
{state.datum != null && <span>{formatAnalyticsValue(state.datum.value, state.visualization.format)}</span>}
<button role="menuitem" type="button" disabled={pending} onClick={() => void run(onAddToChat)}>Add reference to chat</button>
<button role="menuitem" type="button" disabled={pending} onClick={() => void run(onCopyReference)}>Copy reference token</button>
<button role="menuitem" type="button" onClick={() => {
downloadText(`${filename}-plotted.csv`, rowsToCsv(state.figure.accessibleData), "text/csv;charset=utf-8");
onClose();
}}>Export plotted CSV</button>
<button role="menuitem" type="button" onClick={() => {
downloadText(`${filename}-result.csv`, rowsToCsv(state.figure.exportData), "text/csv;charset=utf-8");
onClose();
}}>Export complete bounded result CSV</button>
<button role="menuitem" type="button" disabled={state.controller == null || pending} onClick={() => void run(async () => {
const svg = await state.controller?.exportSvg();
if (svg == null) throw new Error("The chart renderer is not ready to export.");
downloadDataUrl(`${filename}.svg`, svg);
downloadText(`${filename}-lineage.json`, JSON.stringify({
version: 1,
exportedAt: new Date().toISOString(),
...lineage,
queryId: state.query.id,
querySql: state.query.sql,
visualizationId: state.visualization.id,
resultGeneration: state.result.generation,
coverage: state.result.extent,
plottedRows: state.figure.plottedCount,
}, null, 2), "application/json;charset=utf-8");
onClose();
})}>Export SVG + lineage</button>
{message != null && <p role="status">{message}</p>}
</div>
);
}
function safeFilename(value: string): string {
const normalized = value.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
return normalized.slice(0, 80) || "analytics";
}
function RefreshIcon({ spinning }: { spinning: boolean }) {
return (
<svg
viewBox="0 0 16 16"
width="14"
height="14"
aria-hidden="true"
className={spinning ? "analytics-refresh-icon is-spinning" : "analytics-refresh-icon"}
>
<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.89" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
<path d="M13.5 2.3v3.9h-3.9" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
}
function IndexStatus({
index,
connection,
refreshing,
}: {
index: AnalyticsCatalogResponse["index"] | null;
connection: PluginRealtimeConnectionState;
refreshing: boolean;
}) {
const [detailsOpen, setDetailsOpen] = useState(false);
if (index == null) return null;
const view = describeIndexStatus({
status: index.status,
refreshing,
degraded: index.degraded,
lastError: index.lastError,
connection,
freshnessLabel: formatAsOf(indexAsOf(index)),
});
const hasDetails = index.factCount > 0 || index.loadedThreads > 0 || index.lastFullReconciliationAt != null;
return (
<div className="analytics-index-status" data-tone={view.tone} role={view.errorText != null ? "alert" : undefined}>
<span className="analytics-index-status-dot" data-tone={view.tone} aria-hidden="true" />
<strong>{view.headline}</strong>
{view.note != null && <span className="analytics-index-status-note">{view.note}</span>}
{view.errorText != null && <span className="analytics-index-status-error">{view.errorText}</span>}
{hasDetails && (
<button
type="button"
className="analytics-index-status-toggle"
aria-expanded={detailsOpen}
aria-controls="analytics-index-status-detail"
onClick={() => setDetailsOpen((open) => !open)}
>
{detailsOpen ? "Hide details" : "Details"}
</button>
)}
{hasDetails && detailsOpen && (
<div id="analytics-index-status-detail" className="analytics-index-status-detail">
<span>{index.factCount.toLocaleString()} facts · {index.loadedThreads.toLocaleString()} threads</span>
{index.truncatedThreads > 0 && <span>{index.truncatedThreads.toLocaleString()} threads capped at 500 events</span>}
{index.lastFullReconciliationAt != null && <span>Last full reconciliation {formatAsOf(index.lastFullReconciliationAt)}</span>}
</div>
)}
</div>
);
}
function EmptyState({ title, detail, action }: { title: string; detail: string; action?: () => void }) {
return (
<div className="analytics-empty">
<strong>{title}</strong>
<p>{detail}</p>
{action != null && <button type="button" onClick={action}>Try again</button>}
</div>
);
}
function LoadingState({ title, detail }: { title: string; detail: string }) {
return (
<section className="analytics-loading" aria-busy="true">
<ChartPaintingAnimation />
<strong>{title}</strong>
<p>{detail}</p>
</section>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1_024) return `${bytes.toLocaleString()} B`;
if (bytes < 1_048_576) return `${(bytes / 1_024).toFixed(1)} KiB`;
return `${(bytes / 1_048_576).toFixed(1)} MiB`;
}
function indexAsOf(index: AnalyticsCatalogResponse["index"] | null | undefined): number | null {
return index?.snapshotUpdatedAt ?? index?.completedAt ?? null;
}
function formatAsOf(timestamp: number | null): string {
return timestamp == null
? "As of unavailable"
: `As of ${new Date(timestamp).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "medium" })}`;
}
function isAbortError(cause: unknown): boolean {
return cause instanceof DOMException && cause.name === "AbortError";
}
export default definePluginApp((app) => {
app.slots.navPanel({