Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1591 lines (1486 loc) · 65.3 KB
/
Copy pathindex.ts
File metadata and controls
1591 lines (1486 loc) · 65.3 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
// @genclass/runtime/devtools: the in-page overlay that shows exactly what GenClass observed and changed.
//
// import { mountDevtools } from "@genclass/runtime/devtools";
// const devtools = mountDevtools(GenClass.runtime!, { position: "bottom-right" });
//
// Vanilla DOM in an open shadow root (no framework, no global styles). It only reads the public Runtime API
// (status, mode, interventions, decisions, history, explain, situation, inflight, on) and calls setMode and
// ActionRecord.undo when the developer clicks them. The host element carries `data-genclass-ignore` so the
// runtime's DOM observer does not record clicks inside the overlay as app user actions.
import type {
ActionRecord,
Answer,
CheckFinding,
Clock,
Decision,
EffectiveGates,
Explanation,
Learned,
LearnedFlow,
Mode,
ModelStatus,
Op,
Report,
RtEvent,
Runtime,
RuntimeEvents,
Situation,
StoreInfo,
TriggerKind,
} from "../types.js";
import { CSS } from "./css.js";
import {
actTitle,
ago,
answerRows,
clockT,
dataLines,
diagP,
diagTitle,
diagTone,
dur,
eventText,
groupOf,
h,
icon,
kindLabel,
linesOf,
mark,
mb,
opDuration,
opStatus,
pct,
repeatKey,
safeJson,
setDoc,
splitReport,
topFact,
type Group,
type IconName,
type Kid,
} from "./ui.js";
export type DevtoolsPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
export type DevtoolsTab = "interventions" | "detections" | "checks" | "activity" | "now" | "expectations";
export interface DevtoolsOptions {
/** Corner of the viewport. Default "bottom-right". */
position?: DevtoolsPosition;
/** Start as the small pill (default true); false opens the panel immediately. */
collapsed?: boolean;
/**
* Default "dark": genclass.dev's black design, whatever the page's or the OS's theme. "light" is the same design on
* white; "auto" follows prefers-color-scheme (light or dark) live.
*/
theme?: "auto" | "light" | "dark";
/** Initially selected view. Default "interventions". */
tab?: DevtoolsTab;
/** Alt+Shift+G toggles the panel. Default true. */
hotkey?: boolean;
/** Where to attach the overlay host. Default document.body. */
container?: HTMLElement;
}
export interface DevtoolsHandle {
open(): void;
close(): void;
toggle(): void;
unmount(): void;
/** The overlay's host element (its shadow root holds the UI), or null when there is no DOM. */
readonly element: HTMLElement | null;
}
/** Mount the GenClass devtools overlay for a runtime. Returns a no-op handle when there is no DOM (SSR). */
export function mountDevtools(runtime: Runtime, options: DevtoolsOptions = {}): DevtoolsHandle {
const doc = options.container?.ownerDocument ?? (globalThis as { document?: Document }).document;
if (!doc || !runtime) return { open() {}, close() {}, toggle() {}, unmount() {}, element: null };
return new Devtools(runtime, doc, options).handle;
}
// -------------------------------------------------------------------------------------------- internals
type G = typeof globalThis & {
requestAnimationFrame?: (fn: () => void) => number;
setTimeout: (fn: () => void, ms: number) => unknown;
};
const g = globalThis as G;
// Captured at module load so the overlay's own scheduling never goes through instrumented timers.
const rawRaf = g.requestAnimationFrame?.bind(g);
const rawSetTimeout = g.setTimeout?.bind(g);
const TABS: [DevtoolsTab, string][] = [
["interventions", "Interventions"],
["detections", "Detections"],
["checks", "Checks"],
["activity", "Activity"],
["expectations", "Expectations"],
["now", "Now"],
];
const MODES: [Mode, string, string][] = [
["observe", "Observe", "Observe (default): never changes execution; reports what GenClass would have done"],
["guard", "Guard", "Guard (opt-in): prevents only extremely-high-confidence failures with minimal actions (drop, defer, coalesce, delay)"],
["heal", "Heal", "Heal (experimental): broader autonomous recovery (retry, cached responses, rollback, resync)"],
];
const FILTERS: [Group, string][] = [
["user", "User"],
["op", "Ops"],
["state", "State"],
["error", "Errors"],
["gc", "GenClass"],
["other", "Other"],
];
const QLABEL: Record<string, string> = { diagnosis: "Diagnosis", action: "Action" };
// a measured check's kind in words, on its card and in the pill's label (the kind itself stays on the card)
const CHECK_TITLE: Record<string, string> = {
"text-invisible": "Invisible text",
"text-low-contrast": "Hard-to-read text",
"scroll-lock-stuck": "Page cannot scroll",
"pointer-events-leak": "Page stopped taking clicks",
"click-blocked": "Clicks blocked by an invisible layer",
"dialog-covered": "Dialog covered",
"focus-obscured": "Focused control hidden",
"ad-heavy": "Ads covering content",
"page-blank": "Blank page",
};
const qrank = (q: string): number => (q === "diagnosis" ? 0 : q === "action" ? 1 : 2);
const MAX_CARDS = 200;
const MAX_ROWS = 400;
const STATUS = 1;
const MODE = 2;
const LISTS = 4;
const EVENTS = 8;
const ALL = 15;
interface Entry {
kind: "act" | "det";
/** Action id (act) or decision id (det). */
id: string;
at: number;
action?: ActionRecord;
decision?: Decision;
open: boolean;
dirty: boolean;
fresh: boolean;
/** Repeated identical detections folded into this card. */
count: number;
key?: string;
undone?: boolean;
undoErr?: string;
/** Cached explain() result (null: not available). */
ex?: Explanation | null;
el?: HTMLElement;
}
interface OpRow {
el: HTMLElement;
x: HTMLElement;
start: number;
}
/** Keep a Map (insertion-ordered) to its newest `max` entries; `drop` sees evicted values. */
function bound<K, V>(m: Map<K, V>, max: number, drop?: (v: V) => void): void {
for (const [k, v] of m) {
if (m.size <= max) break;
m.delete(k);
drop?.(v);
}
}
function safe<T>(fn: () => T, fallback: T): T {
try {
const v = fn();
return v ?? fallback;
} catch {
return fallback;
}
}
const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));
let instances = 0;
class Devtools {
readonly handle: DevtoolsHandle;
private readonly host: HTMLElement;
private readonly sr: ShadowRoot;
private readonly pill: HTMLElement;
private readonly panel: HTMLElement;
private readonly st: HTMLElement;
private readonly stB: HTMLElement;
private readonly stM: HTMLElement;
private readonly sbi: HTMLElement;
private readonly pb: HTMLElement;
private readonly pbi: HTMLElement;
private readonly pm: HTMLElement;
private readonly pcA: HTMLElement;
private readonly pcD: HTMLElement;
private readonly pcC: HTMLElement;
private readonly nA: HTMLElement;
private readonly nD: HTMLElement;
private readonly pauseBtn: HTMLElement;
private readonly pz: HTMLElement;
private readonly pzT: HTMLElement;
private readonly modeBtns: HTMLElement[];
private readonly tabBtns: HTMLElement[];
private readonly panes: Record<DevtoolsTab, HTMLElement>;
private readonly listA: HTMLElement;
private readonly listD: HTMLElement;
private readonly emptyA: HTMLElement;
private readonly emptyD: HTMLElement;
private readonly emptyE: HTMLElement;
private readonly listC: HTMLElement;
private readonly emptyC: HTMLElement;
private readonly nC: HTMLElement;
/** Measured visual checks (rt.checks(), the "check" event), newest last. */
private chks = new Map<string, { f: CheckFinding; el?: HTMLElement; dirty: boolean }>();
private hlBox: HTMLElement | null = null;
private readonly evs: HTMLElement;
private readonly nowEl: HTMLElement;
private readonly expEl: HTMLElement;
private isOpen = false;
private tab: DevtoolsTab;
private paused = false;
private dead = false;
private acts = new Map<string, Entry>();
private dets = new Map<string, Entry>();
/** decision id -> detection card id (repeats share a card) */
private detOf = new Map<string, string>();
private decs = new Map<string, Decision>();
/** decision id -> action id */
private actOf = new Map<string, string>();
/** action or decision id -> the runtime's report sentence */
private msgs = new Map<string, string>();
private evq: RtEvent[] = [];
private rows: HTMLElement[] = [];
private rowEvents = new WeakMap<HTMLElement, RtEvent[]>();
/** event seq -> row (the runtime re-emits a typing burst's event as it grows) */
private rowBySeq = new Map<number, HTMLElement>();
private opRows = new Map<number, OpRow>();
/** op id -> short description, to name causes in expanded activity rows */
private opNames = new Map<number, string>();
private hide = new Set<Group>();
private query = "";
private unseen = 0;
private offs: (() => void)[] = [];
private clock: Clock | null = null;
private lastT = 0;
private bits = 0;
private scheduled = false;
private ticking = false;
private ticks = 0;
private scrolledActivity = false;
constructor(
private readonly rt: Runtime,
private readonly doc: Document,
private readonly o: DevtoolsOptions,
) {
setDoc(doc);
this.tab = o.tab ?? "interventions";
const pos = o.position ?? "bottom-right";
const [vert, horiz] = pos.split("-");
const host = (this.host = doc.createElement("genclass-devtools"));
host.setAttribute("data-genclass-devtools", "");
host.setAttribute("data-genclass-ignore", "");
host.style.cssText = `all:initial;display:block;position:fixed;z-index:2147483646;${vert}:16px;${horiz}:16px;`;
const sr = (this.sr = host.attachShadow({ mode: "open" }));
this.adoptStyles();
// pill
this.pill = h(
"button",
{ class: "pill", type: "button", "aria-expanded": "false", "aria-haspopup": "dialog", "data-part": "pill", onclick: () => this.open(true) },
mark(),
h("span", { class: "pn", text: "GenClass" }),
(this.pm = h("span", { class: "pm" })),
h("span", { class: "vs" }),
(this.pcA = h("span", { class: "pc a", title: "Interventions" }, icon("shield"), h("b", { text: "0" }))),
(this.pcD = h("span", { class: "pc d", title: "Detections" }, icon("eye"), h("b", { text: "0" }))),
(this.pcC = h("span", { class: "pc c", title: "Measured checks" }, icon("scan"), h("b", { text: "0" }))),
h("span", { class: "pd" }),
(this.pb = h("span", { class: "pb", hidden: true }, (this.pbi = h("i")))),
);
this.pill.addEventListener("animationend", (e) => {
if ((e as AnimationEvent).animationName === "ring") this.pill.classList.remove("pa", "pdd", "pck");
});
// header
this.modeBtns = MODES.map(([m, label, tip]) =>
h(
"button",
{ type: "button", role: "radio", class: `m-${m}`, "data-mode": m, title: tip, "aria-checked": "false", tabindex: "-1", onclick: () => this.setMode(m, true) },
h("span", { class: "md" }),
label,
),
);
const header = h(
"div",
{ class: "hd" },
h("div", { class: "brand" }, mark(), h("span", { class: "bn", text: "GenClass" }), h("span", { class: "bt", text: "runtime" })),
h("div", { class: "modes", role: "radiogroup", "aria-label": "Mode", onkeydown: (e: KeyboardEvent) => this.modeKey(e) }, this.modeBtns),
this.aggrSelect(),
h("button", { class: "ib", type: "button", "aria-label": "Minimize", title: "Minimize (Alt+Shift+G)", "data-part": "minimize", onclick: () => this.close(true) }, icon("min")),
);
this.st = h("div", { class: "st", role: "status", "data-part": "status" }, h("span", { class: "dot" }), (this.stB = h("b")), (this.stM = h("span", { class: "sm" })), h("div", { class: "sb" }, (this.sbi = h("i"))));
// tabs
this.tabBtns = TABS.map(([id, label]) =>
h(
"button",
{
type: "button",
role: "tab",
class: `tab${id === "interventions" ? " ta" : id === "detections" ? " td" : id === "checks" ? " tc" : ""}`,
id: `gc-t-${id}`,
"data-tab": id,
"aria-controls": `gc-p-${id}`,
"aria-selected": "false",
tabindex: "-1",
onclick: () => this.setTab(id, true),
},
label,
id === "interventions" || id === "detections" || id === "checks" ? h("span", { class: "n", text: "0" }) : null,
),
);
this.nA = this.tabBtns[0].querySelector(".n") as HTMLElement;
this.nD = this.tabBtns[1].querySelector(".n") as HTMLElement;
this.nC = this.tabBtns[2].querySelector(".n") as HTMLElement;
const tabs = h(
"div",
{ class: "tabs" },
h("div", { class: "tabs-in", role: "tablist", "aria-label": "GenClass views", onkeydown: (e: KeyboardEvent) => this.tabKey(e) }, this.tabBtns),
h("span", { class: "sp" }),
(this.pauseBtn = h("button", { class: "ib", type: "button", "aria-pressed": "false", "aria-label": "Pause feed", title: "Pause feed", "data-part": "pause", onclick: () => this.setPaused(!this.paused) }, icon("pause"))),
h("button", { class: "ib", type: "button", "aria-label": "Clear feeds", title: "Clear feeds", "data-part": "clear", onclick: () => this.clear() }, icon("clear")),
);
this.pz = h("div", { class: "pz", hidden: true }, icon("pause"), (this.pzT = h("span")), h("button", { type: "button", text: "Resume", onclick: () => this.setPaused(false) }));
// panes
const pane = (id: DevtoolsTab, ...kids: Kid[]): HTMLElement =>
h("div", { class: "pane", role: "tabpanel", id: `gc-p-${id}`, "aria-labelledby": `gc-t-${id}`, "data-pane": id, hidden: true }, ...kids);
this.listA = h("div", { class: "list", role: "feed", "aria-label": "Interventions" });
this.listD = h("div", { class: "list", role: "feed", "aria-label": "Detections" });
this.emptyA = h("div", { class: "empty" });
this.emptyD = empty("eye", "Nothing flagged", "Findings the model reports but GenClass did not act on appear here, with the evidence and what it would have done.");
this.emptyE = empty("pulse", "Waiting for activity", "User actions, requests, state writes and errors appear here as they happen.");
this.listC = h("div", { class: "list", role: "feed", "aria-label": "Measured visual checks" });
this.emptyC = empty(
"scan",
"No visual problems measured",
"Measured checks with fixed thresholds (unreadable text, broken images, sideways scrolling, covered controls, and more) appear here with the CSS change to make. They are measurements, not model findings.",
);
this.evs = h("div", { class: "evs", role: "log", "aria-label": "Runtime activity" });
this.nowEl = h("div", { class: "now" });
this.expEl = h("div", { class: "now", "data-part": "expectations" });
this.panes = {
interventions: pane("interventions", this.listA, this.emptyA),
detections: pane("detections", this.listD, this.emptyD),
checks: pane("checks", this.listC, this.emptyC),
activity: pane("activity", this.filterBar(), this.evs, this.emptyE),
now: pane("now", this.nowEl),
expectations: pane("expectations", this.expEl),
};
this.panel = h(
"section",
{ class: "panel", role: "dialog", "aria-label": "GenClass devtools", hidden: true, "data-part": "panel", onkeydown: (e: KeyboardEvent) => this.panelKey(e) },
header,
this.st,
tabs,
this.pz,
h("div", { class: "body" }, Object.values(this.panes)),
);
const root = h("div", { class: "root", "data-pos": pos }, this.pill, this.panel);
// "auto" follows the OS setting live; "light"/"dark" are fixed. Black by default, like genclass.dev.
const theme = o.theme ?? "dark";
const mql = theme === "auto" ? safe(() => (globalThis as { matchMedia?: (q: string) => MediaQueryList }).matchMedia?.("(prefers-color-scheme: dark)") ?? null, null) : null;
const applyTheme = (): void => root.setAttribute("data-theme", theme === "auto" ? (mql?.matches ? "dark" : "light") : theme);
applyTheme();
if (mql?.addEventListener) {
mql.addEventListener("change", applyTheme);
this.offs.push(() => mql.removeEventListener("change", applyTheme));
}
sr.appendChild(root);
(o.container ?? doc.body ?? doc.documentElement).appendChild(host);
this.subscribe();
this.backfill();
if (o.hotkey !== false) {
const onKey = (ev: KeyboardEvent): void => {
if (ev.altKey && ev.shiftKey && !ev.ctrlKey && !ev.metaKey && (ev.code === "KeyG" || ev.key === "G" || ev.key === "g")) {
ev.preventDefault();
this.toggle(true);
}
};
doc.addEventListener("keydown", onKey, true);
this.offs.push(() => doc.removeEventListener("keydown", onKey, true));
}
this.bits = ALL;
this.flush();
if (o.collapsed === false) this.open(false);
const self = this;
this.handle = {
open: () => this.open(false),
close: () => this.close(false),
toggle: () => this.toggle(false),
unmount: () => this.unmount(),
get element() {
return self.dead ? null : self.host;
},
};
}
// ------------------------------------------------------------------------------------------- setup
private adoptStyles(): void {
const Sheet = (globalThis as { CSSStyleSheet?: { new (): CSSStyleSheet; prototype: CSSStyleSheet } }).CSSStyleSheet;
try {
if (Sheet && "adoptedStyleSheets" in this.sr && typeof Sheet.prototype.replaceSync === "function") {
const sheet = new Sheet();
sheet.replaceSync(CSS);
this.sr.adoptedStyleSheets = [sheet];
return;
}
} catch {
/* fall back to a <style> element inside the shadow root */
}
this.sr.appendChild(h("style", { text: CSS }));
}
private subscribe(): void {
const on = <K extends keyof RuntimeEvents>(type: K, fn: (v: RuntimeEvents[K]) => void): void => {
try {
const off = this.rt.on(type, (v) => {
if (!this.dead) fn(v);
});
if (typeof off === "function") this.offs.push(off);
} catch {
/* runtime without this event */
}
};
// detections from their decisions: the "detect" event carries possible ones only when the app asked for them
on("decide", (d) => {
this.addDecision(d);
if (d.detection) this.addDet(d, true);
});
on("act", (a) => this.addAct(a, true));
on("report", (r) => this.addReport(r));
on("event", (e) => this.addEvent(e));
on("status", () => this.mark(STATUS | MODE)); // setMode() is announced as a status change too
on("check", (f) => this.addCheck(f, true));
on("report", (r) => {
// a fix line (applied, undone, dropped) changes that finding's card
const c = r.kind === "check" && r.check ? this.chks.get(r.check.id) : undefined;
if (c) {
c.dirty = true;
this.mark(LISTS);
}
});
// The runtime's clock (virtual in tests/sim), for "4s ago" labels and the overlay's own timers.
try {
const off = this.rt.use({
name: `genclass-devtools-${++instances}`,
setup: (api) => {
this.clock = api.clock;
},
});
if (typeof off === "function") this.offs.push(off);
} catch {
/* no plugin support: fall back to event times */
}
}
private backfill(): void {
const decs = safe(() => this.rt.decisions(200), [] as Decision[]).slice().sort((a, b) => a.at - b.at);
for (const d of decs) {
this.decs.set(d.id, d);
this.seen(d.at);
}
for (const a of safe(() => this.rt.interventions(MAX_CARDS), [] as ActionRecord[]).slice().sort((x, y) => x.at - y.at)) this.addAct(a, false);
// the tier the runtime recorded with the gates it decided with: the same detections the console and telemetry reported
for (const d of decs) {
if (d.detection) this.addDet(d, false);
}
for (const e of safe(() => this.rt.history(MAX_ROWS), [] as RtEvent[])) this.addEvent(e);
const checks = (this.rt as { checks?: (n?: number) => CheckFinding[] }).checks;
if (typeof checks === "function") for (const f of safe(() => checks.call(this.rt, MAX_CARDS), [] as CheckFinding[])) this.addCheck(f);
// mounting the overlay means someone is looking: start the measured visual checks when the option is "local"
safe(() => (this.rt as { vis?: { start(): void } | null }).vis?.start(), undefined);
}
private addCheck(f: CheckFinding, live = false): void {
if (!f || this.chks.has(f.id)) return;
this.chks.set(f.id, { f, dirty: false });
bound(this.chks, MAX_CARDS, (c) => c.el?.remove());
this.mark(LISTS);
if (live) this.notify("c");
}
// -------------------------------------------------------------------------------------- data intake
private seen(t: number): void {
if (Number.isFinite(t) && t > this.lastT) this.lastT = t;
}
private now(): number {
const c = this.clock;
return c ? safe(() => c.now(), this.lastT) : this.lastT;
}
private addDecision(d: Decision): void {
this.decs.set(d.id, d);
bound(this.decs, 500);
this.seen(d.at);
const e = this.dets.get(this.detOf.get(d.id) ?? "") ?? this.acts.get(this.actOf.get(d.id) ?? "");
if (e) {
e.decision = d;
e.dirty = true;
this.mark(LISTS);
}
}
private addAct(a: ActionRecord, live: boolean): void {
this.seen(a.at);
const known = this.acts.get(a.id);
if (known) {
known.action = a;
known.dirty = true;
return this.mark(LISTS);
}
this.acts.set(a.id, { kind: "act", id: a.id, at: a.at, action: a, decision: this.decs.get(a.decisionId), open: false, dirty: false, fresh: live, count: 1 });
this.actOf.set(a.decisionId, a.id);
bound(this.acts, MAX_CARDS, (e) => e.el?.remove());
bound(this.actOf, 1000);
// A decision that ended up acting moves from Detections to Interventions.
const detId = this.detOf.get(a.decisionId);
const det = detId ? this.dets.get(detId) : undefined;
this.detOf.delete(a.decisionId);
if (det && det.count > 1) {
det.count--;
det.dirty = true;
} else if (det) {
det.el?.remove();
this.dets.delete(det.id);
}
if (live) this.notify("a");
this.mark(LISTS);
}
private addDet(d: Decision, live: boolean): void {
this.decs.set(d.id, d);
this.seen(d.at);
// Executed non-passive decisions are interventions (their ActionRecord follows).
if (this.actOf.has(d.id) || this.detOf.has(d.id) || (d.executed && d.tier !== "passive")) return;
// Repeats of the same finding within a minute fold into one card (×N), like the console's rate limiting.
const key = repeatKey(d);
let same: Entry | undefined;
for (const x of this.dets.values()) if (x.key === key && d.at - x.at <= 60_000) same = x;
if (same) {
same.count++;
same.decision = d;
same.at = d.at;
same.ex = undefined;
same.fresh = live;
same.el?.remove();
same.el = undefined;
this.dets.delete(same.id);
this.dets.set(same.id, same); // newest last: rendered on top
this.detOf.set(d.id, same.id);
} else {
this.dets.set(d.id, { kind: "det", id: d.id, at: d.at, decision: d, open: false, dirty: false, fresh: live, count: 1, key });
this.detOf.set(d.id, d.id);
}
bound(this.dets, MAX_CARDS, (e) => e.el?.remove());
bound(this.detOf, 1000);
// a possible detection is a secondary card: no pulse, not counted as unseen
if (live && d.detection !== "possible") this.notify("d");
this.mark(LISTS);
}
private addReport(r: Report): void {
if (r.kind === "expectation") {
if (this.isOpen && this.tab === "expectations" && !this.paused) this.renderExpectations();
return;
}
if (r.kind === "status" || !r.message) return;
const id = r.kind === "intervene" ? r.action?.id ?? (r.decision ? this.actOf.get(r.decision.id) ?? r.decision.id : undefined) : r.decision?.id;
if (!id) return;
this.msgs.set(id, r.message);
bound(this.msgs, 500);
const e = this.acts.get(id) ?? this.dets.get(this.detOf.get(id) ?? "");
if (e) {
e.dirty = true;
this.mark(LISTS);
}
}
private addEvent(e: RtEvent): void {
this.seen(e.t);
// An intervention undone elsewhere (console, app code) shows as undone here too.
if (e.kind === "action" && e.name === "undo" && typeof e.data?.id === "string") {
const ent = this.acts.get(e.data.id);
if (ent && !ent.undone) {
ent.undone = true;
ent.dirty = true;
this.mark(LISTS);
}
}
if (e.op != null && (e.kind === "user" || e.kind === "op.start")) {
this.opNames.set(e.op, eventText(e));
bound(this.opNames, 2000);
}
this.evq.push(e);
if (this.evq.length > MAX_ROWS) this.evq.splice(0, this.evq.length - MAX_ROWS);
this.mark(EVENTS);
}
private notify(kind: "a" | "d" | "c"): void {
if (this.paused) this.unseen++;
const p = this.pill;
p.classList.remove("pa", "pdd", "pck");
void p.offsetWidth; // restart the animation
p.classList.add(kind === "a" ? "pa" : kind === "d" ? "pdd" : "pck");
}
// ------------------------------------------------------------------------------------------ render
private mark(bits: number): void {
this.bits |= bits;
if (this.scheduled || this.dead) return;
this.scheduled = true;
const run = (): void => {
this.scheduled = false;
this.flush();
};
if (rawRaf) rawRaf(run);
else this.after(16, run);
}
private flush(): void {
if (this.dead) return;
let b = this.bits;
this.bits = 0;
if (b & STATUS) this.renderStatus();
if (b & MODE) this.renderMode();
// Lists and activity render only while visible and not paused; their bits stay set until then.
if (this.isOpen && !this.paused) {
if (b & LISTS) this.renderList(this.acts, this.listA, this.emptyA);
if (b & LISTS) this.renderList(this.dets, this.listD, this.emptyD);
if (b & LISTS) this.renderChecks();
if (b & EVENTS) this.renderEvents();
b &= ~(LISTS | EVENTS);
}
this.bits |= b & (LISTS | EVENTS);
this.renderCounts();
}
private renderCounts(): void {
const na = this.acts.size;
// possible detections (observe's lower tier) are listed as secondary cards, not counted in the badges
let nd = 0;
let np = 0;
for (const e of this.dets.values()) {
if (e.decision?.detection === "possible") np += e.count;
else nd += e.count;
}
(this.pcA.lastElementChild as HTMLElement).textContent = String(na);
(this.pcD.lastElementChild as HTMLElement).textContent = String(nd);
this.pcA.classList.toggle("on", na > 0);
this.pcD.classList.toggle("on", nd > 0);
this.nA.textContent = String(na);
this.nD.textContent = String(nd);
this.nA.classList.toggle("on", na > 0);
this.nD.classList.toggle("on", nd > 0);
this.nD.title = np ? `${nd} likely, ${np} possible` : "";
// measured checks count in the pill too: a page GenClass fixed on screen must not read "0 · 0"
const nc = this.chks.size;
let nf = 0;
for (const c of this.chks.values()) if (c.f.fix?.applied) nf++;
(this.pcC.lastElementChild as HTMLElement).textContent = String(nc);
this.pcC.classList.toggle("on", nc > 0);
this.pcC.title = nc ? `${nc} measured ${nc === 1 ? "check" : "checks"}, ${nf} fixed on screen` : "Measured checks";
this.nC.textContent = String(nc);
this.nC.classList.toggle("on", nc > 0);
const s = safe(() => this.rt.status.state, "off");
this.pill.setAttribute("aria-label", `Open GenClass devtools: ${na} interventions, ${nd} detections, ${nc} checks (${nf} fixed), model ${s}`);
this.pz.hidden = !this.paused;
this.pzT.textContent = this.unseen ? `Feed paused · ${this.unseen} new` : "Feed paused";
}
private renderStatus(): void {
const s: ModelStatus = safe(() => this.rt.status, { state: "off" } as ModelStatus);
let title: string;
let meta: string;
let prog = -1;
switch (s.state) {
case "ready":
title = "Model ready";
meta = [s.device === "webgpu" ? "WebGPU" : s.device === "wasm" ? "WASM" : "", s.variant, s.progress?.total ? `${mb(s.progress.total)} MB` : "", s.loadMs != null ? `loaded in ${dur(s.loadMs)}` : ""]
.filter(Boolean)
.join(" · ");
break;
case "loading": {
title = "Loading model";
const p = s.progress;
prog = p && p.total > 0 ? Math.min(1, p.loaded / p.total) : 0;
meta = p && p.total > 0 ? `${mb(p.loaded)} / ${mb(p.total)} MB · ${pct(prog)}` : "starting…";
break;
}
case "error":
title = "Model unavailable";
meta = `observing only${s.error ? ` · ${s.error}` : ""}`;
break;
default:
title = "No model";
meta = "observing only · no decisions";
}
this.st.className = `st s-${s.state}`;
this.pill.classList.remove("s-off", "s-loading", "s-ready", "s-error");
this.pill.classList.add(`s-${s.state}`);
this.stB.textContent = title;
this.stM.textContent = meta;
this.stM.title = [meta, s.model].filter(Boolean).join(" · ");
this.pb.hidden = prog < 0;
for (const bar of [this.pbi, this.sbi]) bar.style.width = prog < 0 ? "0" : `${(prog * 100).toFixed(1)}%`;
this.renderEmpty();
}
private mode(): Mode {
return safe(() => this.rt.mode, "observe" as Mode);
}
private renderMode(): void {
const m = this.mode();
for (const b of this.modeBtns) {
const on = b.dataset.mode === m;
b.setAttribute("aria-checked", String(on));
b.tabIndex = on ? 0 : -1;
}
this.pm.textContent = m;
this.renderEmpty();
}
/** Empty Interventions view: explains why nothing happened yet (mode, model state). */
private renderEmpty(): void {
const m = this.mode();
const st = safe(() => this.rt.status.state, "off");
const [title, text] =
st === "loading"
? ["Model loading", "Until the model is ready GenClass only observes: nothing is held, changed or retried."]
: st === "off" || st === "error"
? ["Observing only", "No model is available, so GenClass records activity but never decides or acts."]
: m === "observe"
? ["No interventions in observe mode", "Observe mode never changes execution. What GenClass would have done appears under Detections."]
: m === "heal"
? ["No interventions yet", "Heal mode may also retry, serve cached responses, roll back or resync, only when the model is confident."]
: ["No interventions yet", "Guard mode acts only at very high calibrated confidence, with minimal, reversible actions."];
this.emptyA.replaceChildren(...empty("shield", title, text).childNodes);
}
private renderList(m: Map<string, Entry>, list: HTMLElement, emptyEl: HTMLElement): void {
for (const e of m.values()) {
if (!e.el) {
e.el = this.card(e);
list.prepend(e.el);
} else if (e.dirty) {
const old = e.el;
const focused = this.sr.activeElement;
const part = focused && old.contains(focused) ? focused.getAttribute("data-act") : null;
e.el = this.card(e);
old.replaceWith(e.el);
if (part) (e.el.querySelector(`[data-act="${part}"]`) as HTMLElement | null)?.focus();
}
e.dirty = false;
}
emptyEl.hidden = m.size > 0;
}
// ------------------------------------------------------------------------------------- measured checks
private renderChecks(): void {
for (const c of this.chks.values()) {
if (!c.el) {
c.el = this.checkCard(c.f);
this.listC.prepend(c.el);
} else if (c.dirty) {
const old = c.el;
c.el = this.checkCard(c.f);
old.replaceWith(c.el);
}
c.dirty = false;
}
this.emptyC.hidden = this.chks.size > 0;
}
/** One finding: kind, target, what was measured against which threshold, the CSS to make, Show and Undo. */
private checkCard(f: CheckFinding): HTMLElement {
const line = f.message.replace(/^\[GenClass\] Check \(measured\): /, "");
const cut = line.indexOf(" Suggested CSS: ");
const body = cut >= 0 ? line.slice(0, cut) : line;
const css = f.suggestion ? `${f.suggestion.selector} { ${f.suggestion.css} }` : "";
const fix = f.fix;
return h(
"article",
{ class: `card chk sev-${f.severity}`, "data-id": f.id, "data-kind": f.kind, "aria-label": `${f.kind} on ${f.target}` },
h("div", { class: "ci" }, icon("scan")),
h(
"div",
{ class: "cb" },
h(
"div",
{ class: "ch" },
h("span", { class: "cl", text: CHECK_TITLE[f.kind] ?? f.kind }),
h("span", { class: "ct", text: f.kind }),
h("span", { class: "badge", text: "measured", title: "A deterministic measurement against a fixed threshold, not a model finding" }),
h("time", { class: "ago", "data-at": String(f.at), text: ago(this.now() - f.at), title: `runtime clock ${clockT(f.at)}` }),
),
h("p", { class: "cx", text: body }),
h(
"div",
{ class: "chips" },
h("span", { class: `chip t-${f.severity === "high" ? "bad" : f.severity === "medium" ? "warn" : "ok"}` }, h("span", { class: "cd" }), h("b", { text: f.severity })),
h("span", { class: "chip", title: f.threshold.source }, `threshold ${f.threshold.value} ${f.threshold.unit}`),
f.count && f.count > 1 ? h("span", { class: "chip", text: `${f.count}×` }) : null,
f.context.state && f.context.state !== "rest" ? h("span", { class: "chip", text: f.context.state }) : null,
),
css ? sec("Suggested CSS", copyBtn(css), h("pre", { class: "code", "data-part": "css", text: css }), f.suggestion?.note ? h("p", { class: "none", text: f.suggestion.note }) : null) : null,
fix?.applied
? h("div", { class: "note chg" }, icon("check"), h("span", { text: `Runtime fix applied: ${fix.css ?? ""}` }))
: fix?.reason
? h("div", { class: "note" }, icon("info"), h("span", { text: `Runtime fix: ${fix.reason}` }))
: null,
h(
"div",
{ class: "cf" },
h("button", { class: "btn", type: "button", "data-act": "show", title: "Scroll to the element and outline it", onclick: () => this.show(f) }, icon("eye"), "Show"),
fix?.applied
? h("button", { class: "btn u", type: "button", "data-act": "undo", title: "Remove the runtime fix", onclick: () => this.undoFix(f) }, icon("undo"), "Undo")
: null,
),
),
);
}
/** Scroll to the finding's element and outline it inside the overlay's own shadow root (nothing is written to the app's DOM). */
private show(f: CheckFinding): void {
const el = safe(() => f.element(), null);
if (!el) return;
safe(() => el.scrollIntoView({ block: "center" }), undefined);
this.after(250, () => {
const r = el.getBoundingClientRect();
const box = this.hlBox ?? h("div", { class: "hl", "data-part": "highlight" });
this.hlBox = box;
Object.assign(box.style, { left: `${r.left - 3}px`, top: `${r.top - 3}px`, width: `${r.width + 6}px`, height: `${r.height + 6}px`, opacity: "1" });
(this.sr.querySelector(".root") as HTMLElement | null)?.appendChild(box);
this.after(1800, () => {
box.style.opacity = "0";
});
});
}
private undoFix(f: CheckFinding): void {
safe(() => f.fix?.undo(), false);
const c = this.chks.get(f.id);
if (c) c.dirty = true;
this.bits |= LISTS;
this.flush();
}
// --------------------------------------------------------------------------------------------- cards
private card(e: Entry): HTMLElement {
const a = e.action;
const d = e.decision ?? (a ? this.decs.get(a.decisionId) : undefined);
if (d) e.decision = d;
const isAct = e.kind === "act";
const trigger = a?.trigger ?? d?.trigger;
const msg = isAct ? this.msgs.get(e.id) ?? (a ? this.msgs.get(a.decisionId) : undefined) : d ? this.msgs.get(d.id) : undefined;
let { title, body } = splitReport(msg, a?.changed);
if (!isAct) title = diagTitle(d?.diagnosis, trigger);
else if (!title) title = actTitle(a?.action ?? "", d?.diagnosis, trigger, !!a?.late);
if (!body) body = topFact(d?.facts) || a?.subject || d?.subject || "";
const evId = `gc-ev-${e.kind}-${e.id}`;
const dp = d ? diagP(d) : NaN;
const possible = !isAct && d?.detection === "possible";
const el = h(
"article",
{ class: `card ${e.kind}${possible ? " possible" : ""}${e.undone ? " undone" : ""}${e.fresh ? " new" : ""}${e.open ? " open" : ""}`, "data-id": e.id, "aria-label": possible ? `Possible: ${title}` : title },
h("div", { class: "ci" }, icon(isAct ? "shield" : "eye")),
h(
"div",
{ class: "cb" },
h(
"div",
{ class: "ch" },
h("span", { class: "ct", text: title }),
e.count > 1 ? h("span", { class: "rep", text: `×${e.count}`, title: `${e.count} times within a minute; showing the latest` }) : null,
h("time", { class: "ago", "data-at": String(e.at), text: ago(this.now() - e.at), title: `runtime clock ${clockT(e.at)}` }),
),
body ? h("p", { class: "cx", text: body }) : null,
h(
"div",
{ class: "chips" },
d?.diagnosis
? h("span", { class: `chip t-${diagTone(d.diagnosis)}`, title: `Diagnosis, calibrated probability ${dp.toFixed(2)}` }, h("span", { class: "cd" }), h("b", { text: d.diagnosis }), h("span", { class: "p", text: pct(dp) }))
: null,
possible ? h("span", { class: "chip poss", title: "Possible: below the report gate, at or above observe's possible gate (rt.gates().possible)" }, "possible") : null,
a ? h("span", { class: "chip", title: `Action, ${a.tier} tier` }, h("code", { text: a.action }), h("span", { class: "tier", text: a.tier })) : null,
),
isAct ? this.changedNote(e) : this.wouldNote(d),
h(
"div",
{ class: "cf" },
isAct ? this.undoCtl(e) : null,
h(
"button",
{ class: "btn", type: "button", "data-act": "evidence", "aria-expanded": String(e.open), "aria-controls": evId, onclick: () => this.toggleEvidence(e) },
icon("chev", "i chev"),
"Evidence",
),
),
e.open ? this.evidence(e, evId) : null,
),
);
e.fresh = false;
return el;
}
private changedNote(e: Entry): Kid {
const a = e.action;
if (!a) return null;
if (!a.ok) return h("div", { class: "note fail" }, icon("alert"), h("span", {}, h("b", { text: "Action failed: " }), a.error ?? "it threw"));
if (e.undone) return h("div", { class: "note" }, icon("undo"), h("span", {}, h("b", { text: "Reversed: " }), a.changed || a.action));
return a.changed ? h("div", { class: "note chg" }, icon("check"), h("span", { text: a.changed })) : null;
}
private wouldNote(d: Decision | undefined): Kid {
if (!d || !d.action) return null;
if (d.tier === "passive")
return h("div", { class: "note" }, icon("info"), h("span", {}, "The model chose ", h("code", { text: d.action }), ": nothing was changed."));
// Held back by the mode ("observe mode never changes execution", "guard mode does not allow heal-tier
// actions") or by policy (threshold, deny, rate limit, hold budget): say which.
const m = this.mode();
const byMode = d.reason ? /\bmode\b/.test(d.reason) : !(m === "heal" || (m === "guard" && d.tier === "guard"));
return h(
"div",
{ class: "note" },
icon("info"),
byMode
? h("span", {}, "Would have run ", h("code", { text: d.action }), ` in ${d.tier} mode.`)
: h("span", {}, `Not acted on: ${d.reason ?? "held back by policy"}. The model chose `, h("code", { text: d.action }), ` (${d.tier}).`),
);
}
private undoCtl(e: Entry): Kid {
const a = e.action;
if (e.undone) return h("span", { class: "done", "data-act": "undone" }, icon("check"), "Undone");
if (!a || typeof a.undo !== "function") return null;
return [
h("button", { class: "btn u", type: "button", "data-act": "undo", title: "Reverse what GenClass changed", onclick: () => this.undo(e) }, icon("undo"), "Undo"),
e.undoErr ? h("span", { class: "err", text: e.undoErr }) : null,
];
}
private undo(e: Entry): void {
try {
e.action?.undo?.();
e.undone = true;
e.undoErr = undefined;
} catch (err) {
e.undoErr = `Undo failed: ${errText(err)}`;
}
e.dirty = true;
this.bits |= LISTS;