@slack/radar-mcp 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +5 -4
  2. package/dist/mcp/api-paths.d.ts +1 -0
  3. package/dist/mcp/api-paths.js +108 -0
  4. package/dist/mcp/db-tools.d.ts +46 -0
  5. package/dist/mcp/db-tools.js +160 -0
  6. package/dist/mcp/index.js +84 -80
  7. package/dist/mcp/logs-result.d.ts +9 -0
  8. package/dist/mcp/logs-result.js +15 -0
  9. package/dist/mcp/tools.js +70 -7
  10. package/dist/shared/android.d.ts +2 -2
  11. package/dist/shared/android.js +30 -13
  12. package/dist/shared/constants.d.ts +15 -0
  13. package/dist/shared/constants.js +24 -0
  14. package/dist/shared/db.d.ts +31 -14
  15. package/dist/shared/db.js +44 -32
  16. package/dist/shared/debug-log.d.ts +50 -0
  17. package/dist/shared/debug-log.js +108 -0
  18. package/dist/shared/screen.d.ts +35 -2
  19. package/dist/shared/screen.js +75 -6
  20. package/dist/shared/stream.d.ts +1 -1
  21. package/dist/shared/transport.d.ts +22 -4
  22. package/dist/web/bin.d.ts +16 -1
  23. package/dist/web/bin.js +133 -19
  24. package/dist/web/public/index.html +244 -1069
  25. package/dist/web/public/next/app.js +210 -0
  26. package/dist/web/public/next/db.js +286 -0
  27. package/dist/web/public/next/esc.js +13 -0
  28. package/dist/web/public/next/feed.js +608 -0
  29. package/dist/web/public/next/filters.js +120 -0
  30. package/dist/web/public/next/hooks.js +57 -0
  31. package/dist/web/public/next/html.js +10 -0
  32. package/dist/web/public/next/inspector.js +258 -0
  33. package/dist/web/public/next/registry.js +65 -0
  34. package/dist/web/public/next/screen.js +180 -0
  35. package/dist/web/public/next/spec-types.js +1 -0
  36. package/dist/web/public/next/store.js +714 -0
  37. package/dist/web/public/next/widgets.js +194 -0
  38. package/dist/web/public/vendor/README.md +25 -0
  39. package/dist/web/public/vendor/hooks.module.js +2 -0
  40. package/dist/web/public/vendor/htm.LICENSE +202 -0
  41. package/dist/web/public/vendor/htm.module.js +1 -0
  42. package/dist/web/public/vendor/preact.LICENSE +21 -0
  43. package/dist/web/public/vendor/preact.module.js +2 -0
  44. package/dist/web/server.d.ts +17 -0
  45. package/dist/web/server.js +194 -16
  46. package/package.json +6 -2
@@ -1,1082 +1,257 @@
1
1
  <!doctype html>
2
2
  <html lang="en"><head><meta charset="utf-8"/>
3
3
  <title>Slack Radar Dashboard</title>
4
+ <!-- Apply the theme BEFORE first paint so there is no flash on load. A saved choice
5
+ (radar-theme) always wins; with NO saved choice the default follows the OS via
6
+ prefers-color-scheme. MUST stay an inline synchronous <head> script: a module/deferred
7
+ load would paint the dark default first and flash. try/catch covers private-mode storage. -->
8
+ <script>try{var t=localStorage.getItem('radar-theme');var light=t?t==='light':(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches);if(light)document.documentElement.classList.add('light');}catch(e){}</script>
4
9
  <style>
5
- :root { color-scheme: dark; } * { box-sizing: border-box; }
6
- body { margin:0; font:15px/1.4 ui-monospace,Menlo,Consolas,monospace; background:#0b0f14; color:#dfe7ef; padding:28px; }
7
- h1 { font-size:15px; font-weight:600; color:#8aa0b4; margin:0 0 14px; letter-spacing:.04em; }
8
- .live { color:#39d98a; }
10
+ /* ---- THEME TOKENS. Dark is the default (:root); :root.light overrides. Every color in
11
+ the UI references a token, so the theme switch is one class on <html>. The full token
12
+ set ships in Foundation so the stacked container PRs are pure logic diffs and never
13
+ serially conflict on this one stylesheet; component rules are inert until their
14
+ component lands. ---- */
15
+ :root {
16
+ color-scheme: dark; --row-h:24px;
17
+ --bg:#0b0f14; --surface:#121925; --surface-2:#0e151e; --surface-3:#141d2b; --inset:#0c1117;
18
+ --text:#e8f0f8; --text-2:#cfd8e3; --muted:#5f7186; --muted-2:#8aa0b4;
19
+ --border:#1e2a3a; --border-2:#243244; --border-3:#2c3e52; --rowline:#11161d;
20
+ --accent:#39d98a; --accent-bg:#1c3a2a; --accent-text:#39d98a;
21
+ --blue:#6cb6ff; --blue-2:#7d9bd6; --purple:#c39bff;
22
+ --warn:#ffb454; --warn-2:#ffd479; --error:#ff6b60; --error-2:#ff5b50;
23
+ --hover:#11202e; --sel:#1d3a52; --hover-soft:#172230; --sel-soft:#1d2c3e;
24
+ --shadow:rgba(0,0,0,.5); --overlay:rgba(0,0,0,.45);
25
+ --chip-net-bg:#13314a; --chip-rtm-bg:#2c1f47; --chip-clog-bg:#10332a; --chip-log-bg:#2a2a2a; --chip-log-fg:#b0b0b0;
26
+ --lvl-err-bg:#3a1513; --lvl-warn-bg:#3a2f10; --lvl-info-bg:#10283a; --lvl-dbg-bg:#222;
27
+ --copybtn-bg:#172a1f; --copybtn-border:#2c5a3e; --copybtn-fg:#7fd6a3;
28
+ --j-key:#7fb0ff; --j-str:#9fe8bd; --j-num:#ffd479; --j-bool:#c39bff; --j-null:#7e8a99;
29
+ }
30
+ :root.light {
31
+ color-scheme: light;
32
+ --bg:#f4f6f9; --surface:#ffffff; --surface-2:#f0f3f7; --surface-3:#eef2f7; --inset:#ffffff;
33
+ --text:#1a2330; --text-2:#33404f; --muted:#6b7787; --muted-2:#4a5666;
34
+ --border:#d4dde7; --border-2:#c3cedb; --border-3:#aebccb; --rowline:#e7edf3;
35
+ --accent:#0e9f6e; --accent-bg:#d6f3e6; --accent-text:#0a7d56;
36
+ --blue:#1d6fd0; --blue-2:#2f6bbf; --purple:#7a3fd0;
37
+ --warn:#b06c00; --warn-2:#8a5a00; --error:#d83a30; --error-2:#e0473d;
38
+ --hover:#eaf1f8; --sel:#d4e6f7; --hover-soft:#eaf1f8; --sel-soft:#dbe9f7;
39
+ --shadow:rgba(20,40,70,.18); --overlay:rgba(20,30,45,.28);
40
+ --chip-net-bg:#dbeafe; --chip-rtm-bg:#ecddfb; --chip-clog-bg:#d6f3e6; --chip-log-bg:#e7ebf0; --chip-log-fg:#4a5666;
41
+ --lvl-err-bg:#fbdcd9; --lvl-warn-bg:#faedcf; --lvl-info-bg:#dbeafe; --lvl-dbg-bg:#e7ebf0;
42
+ --copybtn-bg:#dcf3e7; --copybtn-border:#9cd6b8; --copybtn-fg:#0a7d56;
43
+ --j-key:#1d6fd0; --j-str:#0a7d56; --j-num:#9a6700; --j-bool:#7a3fd0; --j-null:#8a96a3;
44
+ }
45
+ * { box-sizing: border-box; }
46
+ html, body { height:100%; }
47
+ /* App-style fixed-height layout: the PAGE never scrolls; only the feed scrolls internally.
48
+ The min-height:0 chain (#app -> stage -> feedwrap -> vp) is LOAD-BEARING for the feed
49
+ virtualization, which measures the flex-filled viewport height via ResizeObserver. */
50
+ body { margin:0; font:14px/1.35 ui-monospace,Menlo,Consolas,monospace; background:var(--bg); color:var(--text); padding:12px 16px; overflow:hidden; }
51
+ body.screenopen { padding-right:356px; }
52
+ #app { height:100%; display:flex; flex-direction:column; min-height:0; }
53
+ h1 { font-size:13px; font-weight:600; color:var(--muted-2); margin:0 0 6px; letter-spacing:.04em; display:flex; align-items:center; gap:8px; flex-wrap:wrap; flex:0 0 auto; }
9
54
  .conn { font-size:13px; font-weight:600; }
10
- .conn.connected { color:#39d98a; }
11
- .conn.waiting { color:#ffb454; }
12
- .reconnect { background:#3a2a10; border:1px solid #ffb454; color:#ffb454; border-radius:8px; padding:4px 12px; font:inherit; font-size:12px; font-weight:600; cursor:pointer; margin-left:8px; }
13
- .reconnect:hover { background:#4a360f; } .reconnect:disabled { opacity:.6; cursor:default; }
14
- .modebar { display:flex; gap:6px; margin:10px 0 6px; flex-wrap:wrap; }
15
- .modebtn { background:#121925; border:1px solid #243244; color:#8aa0b4; border-radius:8px; padding:6px 14px; font:inherit; font-size:12.5px; cursor:pointer; }
16
- .modebtn:hover { border-color:#39d98a; color:#dfe7ef; }
17
- .modebtn.active { background:#1c3a2a; border-color:#39d98a; color:#39d98a; font-weight:600; }
18
- .modebtn.custom { margin-left:10px; border-style:dashed; color:#b39ddb; } .modebtn.custom:hover { border-color:#b39ddb; color:#d6c8f0; }
19
- .modebtn.custom.active { background:#241c3a; border-color:#b39ddb; color:#d6c8f0; }
20
- .status { font-size:12px; color:#5f7186; margin-bottom:18px; min-height:16px; }
21
- .status.err { color:#ff7b72; } .status.think { color:#ffd479; } .status.ready { color:#39d98a; }
22
- .sub { margin-bottom:22px; }
23
- .sub .summary { display:block; color:#dfe7ef; font-size:15px; font-weight:600; margin-bottom:4px; }
24
- .sub .tech { display:block; color:#5f7186; font-size:11.5px; }
25
- .filters { max-width:1100px; margin-bottom:18px; background:#0e151e; border:1px solid #1e2a3a; border-radius:10px; padding:6px 14px; }
26
- .filters summary { cursor:pointer; color:#8aa0b4; font-size:12px; font-weight:600; padding:6px 0; }
27
- .filters .fsec { color:#5f7186; font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; margin:12px 0 6px; }
55
+ .conn.connected { color:var(--accent); } .conn.waiting { color:var(--warn); }
56
+ .reconnect { background:var(--surface); border:1px solid var(--warn); color:var(--warn); border-radius:8px; padding:4px 12px; font:inherit; font-size:12px; font-weight:600; cursor:pointer; }
57
+ .reconnect:hover { border-color:var(--warn-2); } .reconnect:disabled { opacity:.6; cursor:default; }
58
+ .profilewrap { font-size:12px; color:var(--blue-2); } .profilewrap b { color:var(--text); }
59
+ .themebtn, .screenbtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:5px 12px; font:inherit; font-size:12.5px; cursor:pointer; }
60
+ .themebtn:hover, .screenbtn:hover { border-color:var(--accent); color:var(--text); } .screenbtn.on { background:var(--accent-bg); border-color:var(--accent); color:var(--accent-text); }
61
+ .modebar { display:flex; gap:6px; margin:0 0 6px; flex-wrap:wrap; flex:0 0 auto; }
62
+ .modebtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:6px 14px; font:inherit; font-size:12.5px; cursor:pointer; }
63
+ .modebtn:hover { border-color:var(--accent); color:var(--text); }
64
+ .modebtn.active { background:var(--accent-bg); border-color:var(--accent); color:var(--accent-text); font-weight:600; }
65
+ .modebtn.custom { margin-left:10px; border-style:dashed; color:var(--purple); } .modebtn.custom.active { background:var(--accent-bg); border-color:var(--purple); color:var(--purple); }
66
+ .sub { margin:0 0 6px; flex:0 0 auto; } .sub .summary { display:block; color:var(--text-2); font-size:12px; font-weight:600; } .sub .tech { display:none; }
67
+ /* filters slim when collapsed */
68
+ .filters { max-width:1100px; margin-bottom:6px; flex:0 0 auto; }
69
+ .filters[open] { background:var(--surface-2); border:1px solid var(--border); border-radius:10px; padding:4px 12px; }
70
+ .filters summary { cursor:pointer; color:var(--muted); font-size:11px; font-weight:600; padding:2px 0; list-style:none; }
71
+ .filters summary::before { content:"\25B8 "; } .filters[open] summary::before { content:"\25BE "; }
72
+ .filters .fsec { color:var(--muted); font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; margin:12px 0 6px; }
28
73
  .filters .frow { display:flex; gap:8px; align-items:center; margin:6px 0; }
29
- .filters .frow label { color:#5f7186; font-size:12px; min-width:96px; }
30
- .filters input, .filters select { background:#121925; border:1px solid #243244; border-radius:7px; color:#e8f0f8; padding:6px 9px; font:inherit; font-size:12px; }
31
- .filters input { flex:1; min-width:0; } .filters input:focus, .filters select:focus { outline:none; border-color:#39d98a; }
32
- .filters .matchrow .f_mk { flex:0 0 130px; } .filters .matchrow .f_mvwrap { flex:1; display:flex; } .filters .matchrow .f_mv { flex:1; width:100%; }
33
- .combo { position:relative; flex:1; display:flex; }
34
- .combo .f_mv { flex:1; padding-right:24px; }
35
- .combocaret { position:absolute; right:8px; top:50%; transform:translateY(-50%); color:#5f7186; font-size:10px; cursor:pointer; }
36
- .combolist { display:none; position:absolute; top:100%; left:0; right:0; z-index:30; margin-top:2px; max-height:200px; overflow:auto; background:#121925; border:1px solid #2c3e52; border-radius:7px; box-shadow:0 6px 18px rgba(0,0,0,.5); }
37
- .combolist.open { display:block; }
38
- .comboitem { padding:6px 10px; font-size:12px; color:#dfe7ef; cursor:pointer; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
39
- .comboitem:hover { background:#1d2c3e; color:#39d98a; }
40
- .meta { color:#5f7186; font-size:11.5px; margin-bottom:8px; }
41
- .filters .fdel { background:none; border:none; color:#ff6b60; cursor:pointer; font-size:13px; padding:0 4px; }
42
- .filters .fadd { background:none; border:1px dashed #2c3e52; color:#8aa0b4; border-radius:7px; padding:5px 10px; font:inherit; font-size:11.5px; cursor:pointer; margin-top:4px; }
43
- .filters .fapply { background:#1c3a2a; border:1px solid #39d98a; color:#39d98a; border-radius:8px; padding:7px 16px; font:inherit; font-size:12.5px; font-weight:600; cursor:pointer; }
44
- .filters .fmsg { color:#5f7186; font-size:12px; } .filters .fhint { color:#5f7186; font-size:11.5px; font-style:italic; }
45
- .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,190px)); gap:14px; max-width:none; align-items:start; }
46
- .card { background:#121925; border:1px solid #1e2a3a; border-radius:12px; padding:12px 16px; }
47
- .label { font-size:11px; text-transform:uppercase; letter-spacing:.08em; color:#5f7186; margin-bottom:8px; }
48
- .big { font-size:36px; font-weight:700; color:#e8f0f8; font-variant-numeric:tabular-nums; line-height:1; }
49
- .unit { font-size:12px; color:#5f7186; margin-left:5px; }
50
- .graphcard { grid-column:1/-1; background:#121925; border:1px solid #1e2a3a; border-radius:12px; padding:14px 18px; }
51
- .graphcard svg { width:100%; height:180px; display:block; background:#0e151e; border-radius:8px; margin-top:8px; }
52
- .graphcard .legend { margin-top:8px; font-size:12px; }
53
- .graphcard .legend span { margin-right:14px; }
54
- .spark { display:flex; align-items:flex-end; gap:3px; height:60px; }
55
- .bar { width:8px; background:#39d98a; border-radius:2px 2px 0 0; min-height:2px; transition:height .2s; }
56
- .stage { display:flex; gap:18px; max-width:none; margin-top:18px; align-items:flex-start; }
57
- .stage.split { flex-wrap:wrap; }
58
- .stage.haswidth #feedwrap { flex:2 1 380px; }
59
- .stage.haswidth .inspector { flex:1 1 300px; max-width:520px; }
60
- .feed { background:#121925; border:1px solid #1e2a3a; border-radius:12px; padding:14px 18px; max-height:calc(100vh - 230px); overflow-y:auto; }
61
- .feedbar { display:flex; gap:8px; align-items:center; margin-bottom:8px; }
62
- .feedbar input { flex:1; background:#0e151e; border:1px solid #243244; border-radius:8px; color:#e8f0f8; padding:7px 10px; font:inherit; font-size:12.5px; }
63
- .feedbar input:focus { outline:none; border-color:#39d98a; }
64
- .ffilterwrap { position:relative; flex:1; display:flex; }
65
- .ffilterwrap input { flex:1; padding-right:26px; }
66
- .ffilterclear { position:absolute; right:8px; top:50%; transform:translateY(-50%); cursor:pointer; color:#7e8ea0; background:#1c2737; border-radius:50%; width:16px; height:16px; line-height:14px; text-align:center; font-size:10px; }
67
- .ffilterclear:hover { color:#fff; background:#ff5b50; }
68
- .feedbar button { background:#1c2a3a; border:1px solid #2c3e52; border-radius:8px; color:#dfe7ef; padding:6px 10px; font:inherit; font-size:12px; cursor:pointer; white-space:nowrap; }
69
- .feedbar button:hover { border-color:#39d98a; }
70
- .feedbar button.paused { color:#ffb454; border-color:#ffb454; }
71
- .fcount { color:#5f7186; font-size:11.5px; white-space:nowrap; }
72
- .fsortlbl { color:#5f7186; font-size:12px; display:flex; align-items:center; gap:5px; white-space:nowrap; }
73
- .feedbar select { background:#1c2a3a; border:1px solid #2c3e52; border-radius:8px; color:#dfe7ef; padding:6px 8px; font:inherit; font-size:12px; cursor:pointer; max-width:200px; }
74
- .feedbar select:focus { outline:none; border-color:#39d98a; }
75
- #fpkg { color:#7d9bd6; }
76
- .chips { display:flex; flex-wrap:wrap; gap:7px; margin-bottom:10px; }
77
- .chip { display:inline-flex; align-items:center; gap:7px; background:#141d2b; border:1px solid #2c3e52; color:#cfe0f0; border-radius:999px; padding:4px 6px 4px 11px; font-size:12px; }
78
- .chip b { color:#7d9bd6; font-weight:600; } .chip .v { color:#e8f0f8; }
79
- .chip .x { cursor:pointer; color:#7e8ea0; background:#1c2737; border-radius:50%; width:16px; height:16px; line-height:14px; text-align:center; font-size:11px; }
80
- .chip .x:hover { color:#fff; background:#ff5b50; }
81
- .row.hidden { display:none; }
82
- .row { display:flex; gap:14px; padding:5px 0; border-bottom:1px solid #16202c; font-size:12.5px; }
83
- .row:last-child{border-bottom:none}
84
- .row.clickable{ cursor:pointer; border-radius:6px; padding-left:8px; margin-left:-8px; }
85
- .row.clickable:hover{ background:#172230; }
86
- .row.sel{ background:#1d2c3e; }
87
- .row.breach{ background:rgba(255,59,48,.14); box-shadow:inset 3px 0 #ff3b30; }
88
- .row.breach span:nth-child(3){ color:#ff6b60; font-weight:600; }
89
- .breachbadge{ margin-left:auto; background:#3a1513; color:#ff8077; font-weight:700; font-size:11.5px; padding:2px 9px; border-radius:999px; white-space:nowrap; }
90
- .tchip{ font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.04em; padding:1px 6px; border-radius:4px; }
91
- .t-network{ background:#13314a; color:#6cb6ff; } .t-rtm{ background:#2c1f47; color:#c39bff; } .t-clog{ background:#10332a; color:#39d98a; } .t-log{ background:#2a2a2a; color:#b0b0b0; }
92
- .lvl{ font-size:10px; font-weight:700; padding:1px 5px; border-radius:4px; }
93
- .lvl-ERROR,.lvl-FATAL{ background:#3a1513; color:#ff6b60; } .lvl-WARN{ background:#3a2f10; color:#ffd479; } .lvl-INFO{ background:#10283a; color:#6cb6ff; } .lvl-DEBUG,.lvl-VERBOSE{ background:#222; color:#8aa0b4; }
94
- .logpkg{ color:#7d9bd6; background:#141d2b; font-size:10.5px; padding:1px 6px; border-radius:4px; white-space:nowrap; max-width:130px; overflow:hidden; text-overflow:ellipsis; }
95
- .logtag{ color:#8aa0b4; font-weight:600; } .logmsg{ color:#cfd8e3; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
96
- .t { color:#5f7186; } .dir-OUTGOING{color:#6cb6ff} .dir-INCOMING{color:#c39bff}
97
- .chan { color:#8aa0b4; } .pulse{animation:p .4s} @keyframes p{from{color:#39d98a}to{}}
98
- .extract { color:#ffd479; font-weight:600; margin-left:auto; max-width:46%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
99
- #flash { position:fixed; inset:0; background:#ff3b30; opacity:0; pointer-events:none; z-index:50; transition:opacity .08s; }
100
- #flash.on { opacity:.38; }
101
- #alertbanner { position:fixed; top:0; left:0; right:0; z-index:60; display:none; text-align:center; background:#ff3b30; color:#fff; font-weight:700; padding:10px; letter-spacing:.04em; box-shadow:0 2px 12px rgba(0,0,0,.4); }
102
- #alertbanner.on { display:block; animation:slidein .15s; }
103
- @keyframes slidein { from{transform:translateY(-100%)} to{transform:translateY(0)} }
104
- .inspector { flex:1 1 340px; min-width:280px; background:#0e151e; border:1px solid #1e2a3a; border-radius:12px; padding:14px 18px; max-height:calc(100vh - 32px); overflow:auto; position:sticky; top:16px; align-self:flex-start; }
105
- .inspector .label{ margin-bottom:10px; }
106
- .inspector pre { margin:0; white-space:pre-wrap; word-break:break-word; font-size:12px; color:#cfe3d6; }
107
- .inspector .empty{ color:#5f7186; font-size:12.5px; }
108
- .copybar { display:flex; gap:6px; margin-bottom:8px; flex-wrap:wrap; }
109
- .copybtn { background:#172a1f; border:1px solid #2c5a3e; color:#7fd6a3; border-radius:6px; padding:3px 9px; font:inherit; font-size:11.5px; cursor:pointer; }
110
- .copybtn:hover { border-color:#39d98a; color:#39d98a; }
111
- /* DB browser (source:"db") */
74
+ .filters .frow label { color:var(--muted); font-size:12px; min-width:96px; }
75
+ .filters input, .filters select { background:var(--surface); border:1px solid var(--border-2); border-radius:7px; color:var(--text); padding:6px 9px; font:inherit; font-size:12px; }
76
+ .filters input:focus, .filters select:focus { outline:none; border-color:var(--accent); }
77
+ .matchrow .f_mk { flex:0 0 130px; } .combo { position:relative; flex:1; display:flex; } .combo .f_mv { flex:1; padding-right:24px; }
78
+ .combocaret { position:absolute; right:8px; top:50%; transform:translateY(-50%); color:var(--muted); font-size:10px; cursor:pointer; }
79
+ .combolist { position:absolute; top:100%; left:0; right:0; z-index:30; margin-top:2px; max-height:200px; overflow:auto; background:var(--surface); border:1px solid var(--border-3); border-radius:7px; box-shadow:0 6px 18px var(--shadow); }
80
+ .comboitem { padding:6px 10px; font-size:12px; color:var(--text); cursor:pointer; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
81
+ .comboitem:hover { background:var(--sel-soft); color:var(--accent); }
82
+ .filters .fdel { background:none; border:none; color:var(--error); cursor:pointer; font-size:13px; padding:0 4px; }
83
+ .filters .fadd { background:none; border:1px dashed var(--border-3); color:var(--muted-2); border-radius:7px; padding:5px 10px; font:inherit; font-size:11.5px; cursor:pointer; margin-top:4px; }
84
+ .filters .fapply { background:var(--accent-bg); border:1px solid var(--accent); color:var(--accent-text); border-radius:8px; padding:7px 16px; font:inherit; font-size:12.5px; font-weight:600; cursor:pointer; }
85
+ .filters .fmsg { color:var(--muted); font-size:12px; } .filters .fhint { color:var(--muted); font-size:11.5px; font-style:italic; }
86
+ .chips { display:flex; flex-wrap:wrap; gap:7px; margin-bottom:6px; flex:0 0 auto; }
87
+ .chip { display:inline-flex; align-items:center; gap:7px; background:var(--surface-3); border:1px solid var(--border-3); color:var(--text-2); border-radius:999px; padding:4px 6px 4px 11px; font-size:12px; }
88
+ .chip b { color:var(--blue-2); font-weight:600; } .chip .v { color:var(--text); }
89
+ .chip .x { cursor:pointer; color:var(--muted-2); background:var(--surface); border-radius:50%; width:16px; height:16px; line-height:14px; text-align:center; font-size:11px; }
90
+ .chip .x:hover { color:#fff; background:var(--error-2); }
91
+ /* stats strip */
92
+ .statstrip { display:flex; align-items:center; gap:18px; margin-bottom:6px; flex:0 0 auto; min-height:0; }
93
+ .label { font-size:11px; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); }
94
+ .stat { display:inline-flex; align-items:baseline; gap:6px; white-space:nowrap; }
95
+ .statlabel { font-size:10px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); }
96
+ .statval { font-size:22px; font-weight:700; color:var(--text); font-variant-numeric:tabular-nums; line-height:1; }
97
+ .statunit { font-size:11px; color:var(--muted); }
98
+ .ministat { display:inline-flex; align-items:center; gap:8px; white-space:nowrap; }
99
+ .minispark { display:inline-flex; align-items:flex-end; gap:2px; height:24px; }
100
+ .minibar { width:4px; background:var(--accent); border-radius:1px 1px 0 0; min-height:2px; }
101
+ /* collapsible graph */
102
+ .cgraph { display:inline-flex; align-items:center; }
103
+ .cgraph-mini { display:inline-flex; align-items:center; gap:8px; cursor:pointer; padding:3px 8px; border:1px solid var(--border); border-radius:8px; background:var(--surface-2); }
104
+ .cgraph-mini:hover { border-color:var(--accent); }
105
+ .minigraph { width:120px; height:28px; display:block; }
106
+ .cgraph-vals { display:inline-flex; gap:10px; }
107
+ .cgraph-val { font-size:12px; font-weight:700; font-variant-numeric:tabular-nums; }
108
+ .cgraph-exp { color:var(--muted); font-size:12px; }
109
+ .cgraph-overlay { position:fixed; inset:0; z-index:55; background:var(--overlay); display:flex; align-items:center; justify-content:center; }
110
+ .cgraph-panel { background:var(--surface); border:1px solid var(--border-3); border-radius:12px; padding:14px 18px; width:min(720px,86vw); box-shadow:0 12px 40px var(--shadow); }
111
+ .cgraph-head { display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; }
112
+ .cgraph-head .label { font-size:12px; }
113
+ .cgraph-collapse { cursor:pointer; color:var(--muted-2); border:1px solid var(--border-3); border-radius:6px; padding:1px 8px; }
114
+ .cgraph-collapse:hover { color:var(--error); border-color:var(--error); }
115
+ .graphcard { display:block; }
116
+ .graphcard > .label { display:none; }
117
+ .graphcard svg { width:100%; height:260px; display:block; background:var(--inset); border-radius:8px; }
118
+ .graphcard .legend { margin-top:8px; font-size:12px; } .graphcard .legend span { margin-right:12px; display:inline-block; }
119
+ /* stage: feed + inspector */
120
+ .stage { display:flex; gap:18px; margin-top:0; align-items:stretch; flex:1; min-height:0; }
121
+ .stage.split .feedwrap-next { flex:2 1 380px; min-width:0; } .stage.split .inspector { flex:1 1 300px; }
122
+ .feedwrap-next { flex:1; min-width:0; display:flex; flex-direction:column; min-height:0; }
123
+ .feedbar { display:flex; gap:8px; align-items:center; margin-bottom:8px; flex-wrap:wrap; flex:0 0 auto; }
124
+ .ffilterwrap { position:relative; flex:1; display:flex; min-width:140px; } .ffilterwrap .ffilter { flex:1; padding-right:26px; }
125
+ .feedbar input { background:var(--surface-2); border:1px solid var(--border-2); border-radius:8px; color:var(--text); padding:7px 10px; font:inherit; font-size:12.5px; }
126
+ .feedbar input:focus { outline:none; border-color:var(--accent); }
127
+ .ffilterclear { position:absolute; right:8px; top:50%; transform:translateY(-50%); cursor:pointer; color:var(--muted-2); background:var(--surface); border-radius:50%; width:16px; height:16px; line-height:14px; text-align:center; font-size:10px; }
128
+ .ffilterclear:hover { color:#fff; background:var(--error-2); }
129
+ .fbtn { background:var(--surface); border:1px solid var(--border-3); border-radius:8px; color:var(--text); padding:6px 10px; font:inherit; font-size:12px; cursor:pointer; white-space:nowrap; }
130
+ .fbtn:hover { border-color:var(--accent); } .fbtn:disabled { opacity:.4; cursor:default; } .fbtn.paused { color:var(--warn); border-color:var(--warn); }
131
+ .fcount { color:var(--muted); font-size:11.5px; white-space:nowrap; }
132
+ .fstatus { font-size:11.5px; font-weight:600; white-space:nowrap; }
133
+ .fstatus.st-live { color:var(--accent); } .fstatus.st-locked { color:var(--warn); } .fstatus.st-paused { color:var(--warn); }
134
+ .fsortlbl { color:var(--muted); font-size:12px; display:flex; align-items:center; gap:5px; white-space:nowrap; }
135
+ .feedbar select { background:var(--surface); border:1px solid var(--border-3); border-radius:8px; color:var(--text); padding:6px 8px; font:inherit; font-size:12px; cursor:pointer; max-width:200px; }
136
+ /* the virtualized viewport */
137
+ .vpbox { position:relative; flex:1; min-height:0; display:flex; }
138
+ .vp { position:relative; flex:1; min-height:0; overflow-y:auto; border:1px solid var(--border); border-radius:12px; background:var(--inset); user-select:none; -webkit-user-select:none; }
139
+ .spacer { position:relative; width:100%; }
140
+ .row { position:absolute; left:0; right:0; height:var(--row-h); line-height:var(--row-h); display:flex; gap:12px; align-items:center; padding:0 14px; white-space:nowrap; overflow:hidden; border-bottom:1px solid var(--rowline); cursor:default; font-size:12.5px; }
141
+ /* row state order matters: breach/failed give the red LEFT-BAR + a faint tint; the
142
+ selection/inspect backgrounds are declared AFTER so equal-specificity selection WINS the
143
+ background (fixes "a red >800ms or failed row showed no grey when selected"). */
144
+ .row.breach, .row.failed { background:rgba(255,59,48,.12); box-shadow:inset 3px 0 var(--error); }
145
+ .row:hover { background:var(--hover); }
146
+ .row.sel { background:var(--sel); } /* selection background beats breach/failed tint */
147
+ .row.inspecting { box-shadow:inset 3px 0 var(--accent); } /* inspected row marker (overrides the red bar) */
148
+ .row .t { color:var(--muted); } .dir-OUTGOING{color:var(--blue)} .dir-INCOMING{color:var(--purple)} .chan { color:var(--muted-2); }
149
+ .tchip { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.04em; padding:1px 6px; border-radius:4px; }
150
+ /* network status code chip in the row */
151
+ .stchip { font-size:10px; font-weight:700; padding:1px 6px; border-radius:4px; font-variant-numeric:tabular-nums; }
152
+ .stchip.st2 { background:var(--chip-clog-bg); color:var(--accent); } .stchip.st3 { background:var(--lvl-info-bg); color:var(--blue); }
153
+ .stchip.st4 { background:var(--lvl-warn-bg); color:var(--warn-2); } .stchip.st5 { background:var(--lvl-err-bg); color:var(--error); }
154
+ .t-network{ background:var(--chip-net-bg); color:var(--blue); } .t-rtm{ background:var(--chip-rtm-bg); color:var(--purple); } .t-clog{ background:var(--chip-clog-bg); color:var(--accent); } .t-log{ background:var(--chip-log-bg); color:var(--chip-log-fg); }
155
+ .lvl { font-size:10px; font-weight:700; padding:1px 5px; border-radius:4px; }
156
+ .lvl-ERROR,.lvl-FATAL{ background:var(--lvl-err-bg); color:var(--error); } .lvl-WARN{ background:var(--lvl-warn-bg); color:var(--warn-2); } .lvl-INFO{ background:var(--lvl-info-bg); color:var(--blue); } .lvl-DEBUG,.lvl-VERBOSE{ background:var(--lvl-dbg-bg); color:var(--muted-2); }
157
+ .logpkg { color:var(--blue-2); background:var(--surface-3); font-size:10.5px; padding:1px 6px; border-radius:4px; white-space:nowrap; max-width:130px; overflow:hidden; text-overflow:ellipsis; }
158
+ .logtag { color:var(--muted-2); font-weight:600; } .logmsg { color:var(--text-2); overflow:hidden; text-overflow:ellipsis; }
159
+ .breachbadge { margin-left:auto; background:var(--lvl-err-bg); color:var(--error); font-weight:700; font-size:11.5px; padding:2px 9px; border-radius:999px; white-space:nowrap; }
160
+ .pill { position:absolute; left:50%; transform:translateX(-50%); top:10px; background:var(--sel); color:var(--text); border:1px solid var(--accent); border-radius:18px; padding:5px 14px; cursor:pointer; box-shadow:0 2px 10px var(--shadow); font-size:12px; z-index:6; }
161
+ .pill-bottom { top:auto; bottom:14px; background:var(--surface); border-color:var(--border-3); color:var(--muted-2); }
162
+ .pillkey { margin-left:6px; font-size:10.5px; opacity:.8; border:1px solid currentColor; border-radius:4px; padding:0 5px; font-variant-numeric:tabular-nums; }
163
+ /* inspector */
164
+ .inspector { flex:1 1 340px; min-width:280px; min-height:0; background:var(--surface-2); border:1px solid var(--border); border-radius:12px; padding:14px 18px; overflow:auto; }
165
+ .inspector-hd { display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:8px; }
166
+ .inspector-hd .ttl { color:var(--text); font-size:13px; font-weight:600; word-break:break-word; }
167
+ .inspector-hd .x { cursor:pointer; color:var(--muted-2); border:1px solid var(--border-3); border-radius:6px; padding:1px 8px; flex:0 0 auto; }
168
+ .inspector-hd .x:hover { color:var(--error); border-color:var(--error); }
169
+ .inspector .empty { color:var(--muted); font-size:12.5px; }
170
+ /* header badges: the at-a-glance facts */
171
+ .ibadges { display:flex; flex-wrap:wrap; gap:6px; margin-bottom:8px; }
172
+ .ibadge { font-size:11px; font-weight:600; padding:2px 8px; border-radius:999px; background:var(--surface-3); color:var(--text-2); white-space:nowrap; }
173
+ .ibadge.meth { background:var(--chip-net-bg); color:var(--blue); }
174
+ .ibadge.st2 { background:var(--chip-clog-bg); color:var(--accent); } .ibadge.st3 { background:var(--lvl-info-bg); color:var(--blue); }
175
+ .ibadge.st4 { background:var(--lvl-warn-bg); color:var(--warn-2); } .ibadge.st5 { background:var(--lvl-err-bg); color:var(--error); }
176
+ .ibadge.slow { background:var(--lvl-err-bg); color:var(--error); }
177
+ .ibadge.dir-OUTGOING { background:var(--chip-net-bg); color:var(--blue); } .ibadge.dir-INCOMING { background:var(--chip-rtm-bg); color:var(--purple); }
178
+ .ibadge.lvl-ERROR,.ibadge.lvl-FATAL { background:var(--lvl-err-bg); color:var(--error); } .ibadge.lvl-WARN { background:var(--lvl-warn-bg); color:var(--warn-2); } .ibadge.lvl-INFO { background:var(--lvl-info-bg); color:var(--blue); }
179
+ .iurl { font-size:11.5px; color:var(--text-2); background:var(--inset); border:1px solid var(--border); border-radius:6px; padding:5px 8px; margin-bottom:8px; word-break:break-all; }
180
+ .copybar { display:flex; gap:6px; margin-bottom:10px; flex-wrap:wrap; }
181
+ .copybtn { background:var(--copybtn-bg); border:1px solid var(--copybtn-border); color:var(--copybtn-fg); border-radius:6px; padding:3px 9px; font:inherit; font-size:11.5px; cursor:pointer; }
182
+ .copybtn:hover { border-color:var(--accent); color:var(--accent); }
183
+ .copynote { align-self:center; font-size:10.5px; color:var(--text-2); opacity:.85; cursor:help; }
184
+ .copynote::before { content:"⚠ "; }
185
+ /* collapsible sections */
186
+ .insec { border:1px solid var(--border); border-radius:8px; margin-bottom:8px; overflow:hidden; }
187
+ .insec-hd { display:flex; align-items:center; gap:7px; padding:6px 10px; cursor:pointer; background:var(--surface-2); }
188
+ .insec-hd:hover { background:var(--hover); }
189
+ .insec-caret { color:var(--muted); font-size:10px; width:10px; }
190
+ .insec-title { font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted-2); font-weight:600; }
191
+ .insec-sub { color:var(--muted); font-size:11px; margin-left:auto; }
192
+ .insec-body { padding:8px 10px; border-top:1px solid var(--border); }
193
+ .inspector pre.json, .inspector pre.logmsg-full { margin:0; white-space:pre-wrap; word-break:break-word; font-size:12px; line-height:1.45; color:var(--text-2); }
194
+ .inspector pre.logmsg-full { color:var(--text); }
195
+ /* JSON syntax tokens. The .inspector pre.json .j-* rules MUST out-specify the base
196
+ pre.json color or the tokens render monochrome. */
197
+ .j-key { color:var(--j-key); } .j-str { color:var(--j-str); } .j-num { color:var(--j-num); } .j-bool { color:var(--j-bool); } .j-null { color:var(--j-null); font-style:italic; }
198
+ .inspector pre.json .j-key { color:var(--j-key); } .inspector pre.json .j-str { color:var(--j-str); } .inspector pre.json .j-num { color:var(--j-num); } .inspector pre.json .j-bool { color:var(--j-bool); } .inspector pre.json .j-null { color:var(--j-null); }
199
+ /* key/value grid for headers */
200
+ .trunc { background:var(--lvl-warn-bg); border:1px solid var(--warn); color:var(--warn-2); border-radius:6px; padding:7px 9px; font-size:11.5px; line-height:1.5; margin-bottom:8px; }
201
+ .inspector pre.rawbody { color:var(--text-2); }
202
+ .kv { display:grid; grid-template-columns:auto 1fr; gap:2px 12px; font-size:11.5px; }
203
+ .kv-k { color:var(--muted-2); white-space:nowrap; } .kv-v { color:var(--text-2); word-break:break-all; }
204
+ /* alert */
205
+ #flash { position:fixed; inset:0; background:#ff3b30; opacity:0; pointer-events:none; z-index:50; transition:opacity .08s; } #flash.on { opacity:.38; }
206
+ #alertbanner { position:fixed; top:0; left:0; right:0; z-index:60; text-align:center; background:#ff3b30; color:#fff; font-weight:700; padding:10px; letter-spacing:.04em; box-shadow:0 2px 12px var(--shadow); display:flex; justify-content:center; gap:20px; }
207
+ #alertbanner .x { cursor:pointer; }
208
+ /* DB browser */
112
209
  .dbview { display:flex; gap:16px; max-width:1180px; margin-top:8px; height:72vh; }
113
- .dbside { flex:0 0 260px; overflow:auto; border:1px solid #1e2a3a; border-radius:10px; padding:12px; }
114
- .dbsec { color:#5f7186; font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; margin:6px 0 6px; }
115
- .dbsec:not(:first-child){ margin-top:14px; }
210
+ .dbside { flex:0 0 260px; overflow:auto; border:1px solid var(--border); border-radius:10px; padding:12px; }
211
+ .dbsec { color:var(--muted); font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; margin:6px 0 6px; } .dbsec:not(:first-child){ margin-top:14px; }
116
212
  .dbitem { padding:6px 9px; border-radius:7px; cursor:pointer; font-size:12.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
117
- .dbitem:hover { background:#172230; } .dbitem.sel { background:#1d2c3e; color:#39d98a; }
118
- .dbitem .rows { float:right; color:#5f7186; font-size:11px; }
213
+ .dbitem:hover { background:var(--hover-soft); } .dbitem.sel { background:var(--sel-soft); color:var(--accent); } .dbitem .rows { float:right; color:var(--muted); font-size:11px; }
214
+ .dbitem.kbd { outline:2px solid var(--accent); outline-offset:-2px; } /* keyboard-focused row */
119
215
  .dbmain { flex:1; min-width:0; display:flex; flex-direction:column; }
120
216
  .dbqbar { display:flex; gap:8px; margin-bottom:8px; }
121
- .dbqbar input { flex:1; background:#121925; border:1px solid #243244; border-radius:8px; color:#e8f0f8; padding:8px 11px; font:inherit; font-size:12.5px; }
122
- .dbqbar input:focus { outline:none; border-color:#39d98a; }
123
- .dbqbar button { background:#1c3a2a; border:1px solid #39d98a; color:#39d98a; border-radius:8px; padding:0 16px; font:inherit; font-size:12.5px; font-weight:600; cursor:pointer; }
124
- .dbmeta { color:#5f7186; font-size:11.5px; margin-bottom:8px; }
125
- .dbprivacy { background:#2a2112; border:1px solid #6b5320; color:#e8c879; border-radius:8px; padding:8px 11px; font-size:11.5px; line-height:1.5; margin-bottom:10px; }
126
- .dbprofile { color:#7d9bd6; font-size:11.5px; margin-bottom:8px; }
127
- .dbprofile b { color:#cfe0f0; }
128
- .dbprofcap { color:#5f7186; text-transform:uppercase; letter-spacing:.06em; font-size:10px; }
129
- .dbprofile select { background:#121925; border:1px solid #243244; border-radius:6px; color:#e8f0f8; padding:3px 6px; font:inherit; font-size:11px; margin-left:4px; }
130
- .dbrefresh { background:#1c2a3a; border:1px solid #2c3e52; border-radius:6px; color:#8aa0b4; padding:2px 8px; font:inherit; font-size:11px; cursor:pointer; margin-left:8px; }
131
- .dbrefresh:hover { border-color:#39d98a; color:#39d98a; }
132
- .dbout { flex:1; overflow:auto; border:1px solid #1e2a3a; border-radius:10px; }
217
+ .dbqbar input { flex:1; background:var(--surface); border:1px solid var(--border-2); border-radius:8px; color:var(--text); padding:8px 11px; font:inherit; font-size:12.5px; } .dbqbar input:focus { outline:none; border-color:var(--accent); }
218
+ .dbqbar button { background:var(--accent-bg); border:1px solid var(--accent); color:var(--accent-text); border-radius:8px; padding:0 16px; font:inherit; font-size:12.5px; font-weight:600; cursor:pointer; }
219
+ .dbmeta { color:var(--muted); font-size:11.5px; margin-bottom:8px; }
220
+ .dbprivacy { background:var(--lvl-warn-bg); border:1px solid var(--warn); color:var(--warn-2); border-radius:8px; padding:8px 11px; font-size:11.5px; line-height:1.5; margin-bottom:10px; }
221
+ .dbprofile { color:var(--blue-2); font-size:11.5px; margin-bottom:8px; } .dbprofile b { color:var(--text); }
222
+ .dbprofcap { color:var(--muted); text-transform:uppercase; letter-spacing:.06em; font-size:10px; }
223
+ .dbprofile select { background:var(--surface); border:1px solid var(--border-2); border-radius:6px; color:var(--text); padding:3px 6px; font:inherit; font-size:11px; margin-left:4px; }
224
+ .dbrefresh { background:var(--surface); border:1px solid var(--border-3); border-radius:6px; color:var(--muted-2); padding:2px 8px; font:inherit; font-size:11px; cursor:pointer; margin-left:8px; } .dbrefresh:hover { border-color:var(--accent); color:var(--accent); }
225
+ .dbout { flex:1; overflow:auto; border:1px solid var(--border); border-radius:10px; }
133
226
  .dbout table { border-collapse:collapse; width:100%; font-size:12px; }
134
- .dbout th { position:sticky; top:0; background:#121925; color:#8aa0b4; text-align:left; padding:7px 10px; border-bottom:1px solid #1e2a3a; white-space:nowrap; }
135
- .dbout td { padding:6px 10px; border-bottom:1px solid #16202c; max-width:380px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
136
- .dbout tr:hover td { background:#10161f; }
137
- .msg { color:#5f7186; font-size:12px; padding:10px; }
138
- .msg.err { color:#ff6b60; }
139
- /* Screen overlay: a global panel docked to the right, available over any tab. */
140
- .screenbtn { background:#121925; border:1px solid #243244; color:#8aa0b4; border-radius:8px; padding:5px 12px; font:inherit; font-size:12.5px; cursor:pointer; margin-left:8px; }
141
- .screenbtn:hover { border-color:#39d98a; color:#dfe7ef; }
142
- .screenbtn.on { background:#1c3a2a; border-color:#39d98a; color:#39d98a; }
143
- #screenpanel { position:fixed; top:0; right:0; bottom:0; width:340px; background:#0b1016; border-left:1px solid #1e2a3a; z-index:40; display:none; flex-direction:column; padding:12px; box-shadow:-4px 0 16px rgba(0,0,0,.4); overflow:auto; }
144
- #screenpanel.on { display:flex; }
145
- body.screenopen { padding-right:356px; }
227
+ .dbout th { position:sticky; top:0; background:var(--surface); color:var(--muted-2); text-align:left; padding:7px 10px; border-bottom:1px solid var(--border); white-space:nowrap; }
228
+ .dbout td { padding:6px 10px; border-bottom:1px solid var(--rowline); max-width:380px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
229
+ .dbout tr:hover td { background:var(--hover); }
230
+ .msg { color:var(--muted); font-size:12px; padding:10px; } .msg.err { color:var(--error); }
231
+ /* screen overlay */
232
+ #screenpanel { position:fixed; top:0; right:0; bottom:0; width:340px; background:var(--surface-2); border-left:1px solid var(--border); z-index:40; display:flex; flex-direction:column; padding:12px; box-shadow:-4px 0 16px var(--shadow); overflow:auto; }
146
233
  #screenpanel .schead { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
147
- #screenpanel .schead .sctitle { font-size:12.5px; color:#dfe7ef; font-weight:600; flex:1; }
148
- #screenpanel .scbtn { background:#121925; border:1px solid #243244; color:#8aa0b4; border-radius:6px; padding:3px 9px; font:inherit; font-size:11.5px; cursor:pointer; }
149
- #screenpanel .scbtn:hover { border-color:#39d98a; color:#dfe7ef; }
150
- #screenpanel .scbtn.rec { color:#ff6b60; border-color:#5a2c2c; }
151
- #screenimg { width:100%; border:1px solid #1e2a3a; border-radius:8px; background:#000; min-height:120px; }
152
- #schint { font-size:11.5px; color:#5f7186; margin-top:8px; line-height:1.5; }
153
- .scconsent { background:#161b22; border:1px solid #2c3a4a; border-radius:8px; padding:12px; font-size:12px; color:#cfd8e3; line-height:1.55; }
154
- .scconsent b { color:#ffd479; }
155
- .scconsent .scaccept { background:#1c3a2a; border:1px solid #39d98a; color:#39d98a; border-radius:6px; padding:6px 14px; font:inherit; font-size:12px; cursor:pointer; margin-top:10px; }
156
- .scconsent .scaccept:hover { background:#24492f; }
157
- .scinstall { background:#0e151e; border:1px solid #1e2a3a; border-radius:6px; padding:8px 10px; margin-top:8px; font-size:11.5px; color:#cfe3d6; }
158
- .scinstall code { color:#7fd6a3; }
159
- .scinstall .sccopy { background:#172a1f; border:1px solid #2c5a3e; color:#7fd6a3; border-radius:5px; padding:2px 8px; font:inherit; font-size:11px; cursor:pointer; margin-left:6px; }
160
- </style></head>
234
+ #screenpanel .sctitle { font-size:12.5px; color:var(--text); font-weight:600; flex:1; }
235
+ #screenpanel .scbtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:6px; padding:3px 9px; font:inherit; font-size:11.5px; cursor:pointer; } #screenpanel .scbtn:hover { border-color:var(--accent); color:var(--text); } #screenpanel .scbtn.rec { color:var(--error); border-color:var(--error); }
236
+ #screenimg { width:100%; border:1px solid var(--border); border-radius:8px; background:#000; min-height:120px; }
237
+ #schint { font-size:11.5px; color:var(--muted); margin-top:8px; line-height:1.5; }
238
+ .scconsent { background:var(--surface); border:1px solid var(--border-3); border-radius:8px; padding:12px; font-size:12px; color:var(--text-2); line-height:1.55; } .scconsent b { color:var(--warn-2); }
239
+ .scconsent .scaccept { background:var(--accent-bg); border:1px solid var(--accent); color:var(--accent-text); border-radius:6px; padding:6px 14px; font:inherit; font-size:12px; cursor:pointer; margin-top:10px; display:block; } .scconsent .scaccept:hover { filter:brightness(1.1); }
240
+ .scinstall { background:var(--surface-2); border:1px solid var(--border); border-radius:6px; padding:8px 10px; margin-top:8px; font-size:11.5px; color:var(--text-2); } .scinstall code { color:var(--copybtn-fg); }
241
+ .scinstall .sccopy { background:var(--copybtn-bg); border:1px solid var(--copybtn-border); color:var(--copybtn-fg); border-radius:5px; padding:2px 8px; font:inherit; font-size:11px; cursor:pointer; margin-left:6px; }
242
+ </style>
243
+ <!-- No-build Preact: the import map resolves the bare `preact` + `preact/hooks` + `htm`
244
+ specifiers to the vendored ES modules (served by serveStatic from vendor/). No bundler,
245
+ no build step for consumers -- the `npx @slack/radar-mcp@latest` model is unchanged. -->
246
+ <script type="importmap">
247
+ { "imports": {
248
+ "preact": "./vendor/preact.module.js",
249
+ "preact/hooks": "./vendor/hooks.module.js",
250
+ "htm": "./vendor/htm.module.js"
251
+ } }
252
+ </script>
253
+ </head>
161
254
  <body>
162
- <div id="flash"></div>
163
- <div id="alertbanner"></div>
164
- <h1>SLACK RADAR DASHBOARD <span class="conn waiting" id="conn">&#9679; connecting…</span> <button id="reconnect" class="reconnect" style="display:none">⟳ Reconnect Radar</button> <button id="screenbtn" class="screenbtn" title="Mirror the live device screen">▣ Screen</button></h1>
165
- <div id="screenpanel">
166
- <div class="schead">
167
- <span class="sctitle">Device screen</span>
168
- <button class="scbtn" id="screenshot" title="Full-resolution screenshot">📷</button>
169
- <button class="scbtn" id="screenrec" title="Record to mp4">● rec</button>
170
- <button class="scbtn" id="screenredetect" title="Re-detect the active display">⟳</button>
171
- <button class="scbtn" id="screenclose" title="Close">✕</button>
172
- </div>
173
- <div id="screenbody"></div>
174
- <div id="schint"></div>
175
- </div>
176
- <div class="modebar" id="modebar"></div>
177
- <div class="status" id="status"></div>
178
- <div class="sub" id="sub"></div>
179
- <details class="filters" id="filterpanel" style="display:none">
180
- <summary>Filters</summary>
181
- <div id="filterbody"></div>
182
- </details>
183
- <div class="grid" id="cards"></div>
184
- <div class="stage" id="stage">
185
- <div class="feedwrap" id="feedwrap" style="flex:1; min-width:0;">
186
- <div class="feedbar" id="feedbar" style="display:none">
187
- <span class="ffilterwrap"><input id="ffilter" placeholder="filter rows…" autocomplete="off"/><span class="ffilterclear" id="ffilterclear" title="clear filter" style="display:none">✕</span></span>
188
- <label class="fsortlbl" id="fpkgwrap" style="display:none">app <select id="fpkg" title="show only one app's log lines"></select></label>
189
- <label class="fsortlbl">sort <select id="fsort"></select></label>
190
- <button id="fpause" title="pause stream">⏸ live</button>
191
- <span id="fcount" class="fcount"></span>
192
- </div>
193
- <div class="chips" id="chips" style="display:none"></div>
194
- <div class="feed" id="feed"></div>
195
- </div>
196
- <div class="inspector" id="inspector" style="display:none"></div>
197
- </div>
198
- <div class="dbview" id="dbview" style="display:none">
199
- <div class="dbside"><div class="dbsec">databases</div><div id="db_dbs" class="msg">loading…</div><div class="dbsec">tables</div><div id="db_tbls" class="msg">pick a database</div></div>
200
- <div class="dbmain">
201
- <div class="dbprivacy">Privacy: opening a database copies the on-device Slack store (message text, request/response bodies, user, channel, and team IDs) in plaintext to a temp file on this machine. The copy is read-only and auto-deleted when this dashboard stops. Review before sharing anything from here.</div>
202
- <div class="dbqbar"><input id="db_sql" placeholder="SELECT * FROM table LIMIT 100 (read-only)" autocomplete="off"/><button id="db_run">Run</button></div>
203
- <div class="dbmeta" id="db_meta"></div>
204
- <div class="dbout" id="db_out"><div class="msg">pick a database, then a table</div></div>
205
- </div>
206
- </div>
207
- <script>
208
- // The web page is just pre-built dashboard TABS over the device Radar stream. No in-page
209
- // Claude. Customization happens in a terminal Claude Code session (via the
210
- // open_radar_dashboard MCP tool -> /setspec); when a pushed spec does not match any
211
- // pre-built tab, a "Custom" tab appears and selects. The page polls /spec and renders
212
- // whichever preset (or custom spec) is active.
213
- const statusEl=document.getElementById('status');
214
- function setStatus(state,msg){ statusEl.className='status '+(state==='error'?'err':state==='ready'?'ready':''); statusEl.textContent = msg||''; }
215
- document.getElementById('reconnect').onclick=doReconnect;
216
-
217
- // The live dashboard spec. Hoisted above the first renderModes() call so markActiveMode()
218
- // can read it before build() first assigns it, without a TDZ ReferenceError. Reassigned by
219
- // build(spec); the engine section below treats this as its single source of truth.
220
- let SPEC=null;
221
-
222
- // ---- pre-built dashboards: the product. one tab each. ----
223
- // Presets use only generic placeholders. The dashboard learns the real endpoints,
224
- // channels, and event names LIVE from the device stream; nothing internal is baked in.
225
- const MODES=[
226
- {key:'all', label:'Live', spec:{title:'Live',summary:'Live: network, RTM, analytics clogs, and Slack-app logcat in one timeline. (Logs filtered to the Slack app; clear the package chip for all apps.)',source:'all',viz:['counter','rate','sparkline','feed','inspector'],match:{package:'com.Slack.internal.debug'}}},
227
- {key:'network',label:'Network',spec:{title:'Network',summary:'Network calls per second vs average response time, every call listed, slow ones flagged.',source:'network',viz:['counter','rate','graph','feed','inspector'],series:[{metric:'ratePerSec',label:'calls/s',unit:'/s'},{metric:'avg',field:'duration_ms',label:'avg ms',unit:'ms'}],highlight:{field:'duration_ms',op:'>',value:800,label:'slow (>800ms)'},rateWindowSec:10}},
228
- {key:'rtm', label:'RTM', spec:{title:'RTM',summary:'Real-time websocket events as they happen.',source:'rtm',viz:['counter','rate','feed','inspector']}},
229
- {key:'clog', label:'Clogs', spec:{title:'Clogs',summary:'Analytics clog events, click any to see its full payload.',source:'clog',viz:['counter','rate','feed','inspector']}},
230
- {key:'log', label:'Logs', spec:{title:'Device Logs',summary:'Live Slack app logcat, color-coded by level. Clear the package chip for all apps, or switch app with the dropdown.',source:'log',viz:['counter','feed','inspector'],match:{package:'com.Slack.internal.debug'}}},
231
- {key:'db', label:'Database', spec:{title:'Device DB',summary:'Browse the on-device SQLite databases (read-only snapshot).',source:'db'}},
232
- ];
233
- // A spec is "custom" when it did NOT come from a MODES preset — i.e. a terminal Claude
234
- // session pushed it via the open_radar_dashboard MCP tool. We detect that by comparing
235
- // the live spec to the presets; a non-match shows the Custom tab.
236
- let CUSTOM_ACTIVE=false; // is the live spec the custom (Claude-pushed) one RIGHT NOW?
237
- let lastCustomSpec=null; // the most-recent custom spec; keeps the Custom tab present
238
- // until a page refresh, so you can flip back to it.
239
- // A spec pushed by THIS browser (a Filters-panel Apply, or a tab click) is a local edit, not
240
- // a Claude-pushed custom dashboard — so it must NOT spawn a "Custom" tab. localPushKey holds
241
- // the JSON of the next spec we expect back from /spec because we just pushed it; pollSpec sees
242
- // it match and treats it as a local edit (stays on the current tab). Only a non-preset spec we
243
- // did NOT push (an MCP open_radar_dashboard) becomes the Custom tab.
244
- let localPushKey=null;
245
- function markLocalPush(spec){ localPushKey=JSON.stringify(spec); }
246
- function specMatchesMode(spec){ if(!spec||spec.blank) return null;
247
- return MODES.find(m=>JSON.stringify(m.spec)===JSON.stringify(spec))?.key || null; }
248
- function renderModes(){ const bar=document.getElementById('modebar'); if(!bar) return;
249
- let html=MODES.map(m=>'<button class="modebtn" data-k="'+m.key+'">'+m.label+'</button>').join('');
250
- // Custom tab persists once a custom spec has been pushed this page-load (lastCustomSpec),
251
- // not just while it is the live spec — so switching to a pre-built tab does not lose it.
252
- if(lastCustomSpec) html+='<button class="modebtn custom" data-k="__custom__" title="'+esc(lastCustomSpec.title||'custom')+' — pushed from a terminal Claude Code session; persists until refresh">✎ '+esc(lastCustomSpec.title||'Custom')+'</button>';
253
- bar.innerHTML=html;
254
- bar.querySelectorAll('.modebtn').forEach(b=>b.onclick=async()=>{
255
- const k=b.dataset.k;
256
- const spec = k==='__custom__' ? lastCustomSpec : MODES.find(x=>x.key===k)?.spec;
257
- if(!spec) return;
258
- setStatus('', k==='__custom__' ? 'showing: '+(lastCustomSpec.title||'Custom') : 'showing: '+MODES.find(x=>x.key===k).label);
259
- try{ const r=await (await fetch('/setspec',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(spec)})).json();
260
- if(!r.ok) setStatus('error','⚠ '+(r.error||'failed')); }catch{ setStatus('error','switch failed'); } });
261
- markActiveMode();
262
- }
263
- function markActiveMode(){ const bar=document.getElementById('modebar'); if(!bar) return;
264
- const activeKey = CUSTOM_ACTIVE ? '__custom__' : specMatchesMode(SPEC);
265
- bar.querySelectorAll('.modebtn').forEach(b=>b.classList.toggle('active', b.dataset.k===activeKey)); }
266
- renderModes();
267
-
268
- // ---- keyboard navigation ----
269
- // Up/Down (or vim j/k) move the selected feed row; Home/End jump to first/last.
270
- // Left/Right (or vim h/l) switch tabs. All clamp at the ends — no wrap.
271
- // Reuses inspect() for selection and the existing .modebtn click for tab switches,
272
- // and reads the live DOM each press so it survives stream-driven re-renders.
273
- function visibleRows(){
274
- // feed is null on tabs without a feed viz; guard.
275
- return feed ? [...feed.children].filter(r=>r.classList.contains('row') && !r.classList.contains('hidden')) : [];
276
- }
277
- function pickRow(r){
278
- if(!r) return;
279
- // inspect() toggles selection OFF when called on the already-selected row, so skip it.
280
- if(!r.classList.contains('sel')) inspect(r,r._ev);
281
- r.scrollIntoView({block:'nearest'});
282
- }
283
- function moveRow(dir){ // dir: -1 up, +1 down, 'first', 'last'
284
- const rows=visibleRows();
285
- if(rows.length===0) return;
286
- if(dir==='first') return pickRow(rows[0]);
287
- if(dir==='last') return pickRow(rows[rows.length-1]);
288
- const cur=rows.findIndex(r=>r.classList.contains('sel'));
289
- if(cur===-1) return pickRow(dir>0?rows[0]:rows[rows.length-1]);
290
- const next=Math.max(0,Math.min(rows.length-1,cur+dir)); // clamp
291
- pickRow(rows[next]);
292
- }
293
- function moveTab(dir){ // dir: -1 left, +1 right; clamp
294
- const btns=[...document.querySelectorAll('#modebar .modebtn')];
295
- if(btns.length===0) return;
296
- let cur=btns.findIndex(b=>b.classList.contains('active'));
297
- if(cur===-1) cur=0;
298
- const next=Math.max(0,Math.min(btns.length-1,cur+dir));
299
- if(next!==cur) btns[next].click(); // fires existing onclick → /setspec → rebuild
300
- }
301
- document.addEventListener('keydown',(e)=>{
302
- const t=e.target;
303
- if(t && (t.tagName==='INPUT' || t.tagName==='TEXTAREA' || t.isContentEditable)) return;
304
- switch(e.key){
305
- case 'ArrowDown': case 'j': moveRow(+1); break;
306
- case 'ArrowUp': case 'k': moveRow(-1); break;
307
- case 'ArrowRight': case 'l': moveTab(+1); break;
308
- case 'ArrowLeft': case 'h': moveTab(-1); break;
309
- case 'Home': moveRow('first'); break;
310
- case 'End': moveRow('last'); break;
311
- default: return;
312
- }
313
- e.preventDefault(); // stop the list/page from also scrolling
314
- });
315
-
316
- // ---- poll /spec; rebuild when it changes, and show/hide the Custom tab accordingly ----
317
- let specKey='';
318
- async function pollSpec(){ try{ const spec=await (await fetch('/spec')).json(); const key=JSON.stringify(spec); if(key===specKey) return; specKey=key;
319
- // A non-blank spec that matches no preset is a Claude-pushed custom dashboard — UNLESS this
320
- // browser just pushed it (a Filters-panel Apply or a tab click), which is a local edit and
321
- // must stay on the current tab, not spawn a Custom tab.
322
- const isLocalEdit = key===localPushKey; if(isLocalEdit) localPushKey=null;
323
- CUSTOM_ACTIVE = !isLocalEdit && !!spec && !spec.blank && specMatchesMode(spec)===null;
324
- let needRerender=false;
325
- if(CUSTOM_ACTIVE){ // remember it so the tab persists; re-render if it's new/changed
326
- if(!lastCustomSpec || JSON.stringify(lastCustomSpec)!==JSON.stringify(spec)){ lastCustomSpec=spec; needRerender=true; }
327
- }
328
- if(needRerender) renderModes(); // add or update the Custom tab (label = its title)
329
- build(spec);
330
- if(CUSTOM_ACTIVE) setStatus('ready','Custom dashboard (pushed from a Claude Code session): '+(spec.title||''));
331
- else { const k=specMatchesMode(spec); const m=MODES.find(x=>x.key===k); if(m) setStatus('','showing: '+m.label); }
332
- markActiveMode();
333
- }catch{} }
334
- setInterval(pollSpec,700);
335
- // Default to the Live dashboard on load (instead of a blank canvas).
336
- async function bootDefault(){ try{ const cur=await (await fetch('/spec')).json();
337
- if(!cur||cur.blank){ const live=MODES[0]; await fetch('/setspec',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(live.spec)}).catch(()=>{}); }
338
- }catch{} }
339
- bootDefault();
340
- // Connection dot driven by an always-on device health check, independent of whether
341
- // a dashboard is built (a blank dashboard has no stream, so the dot was otherwise dead).
342
- let lastEventTs=0, healthMisses=0;
343
- // Clear a stale red "device unreachable / backfill failed" status once health is back. These
344
- // errors are set once (e.g. at build/backfill time) and were otherwise sticky until a tab
345
- // switch — so a transient blip left the red banner up long after the device recovered.
346
- function clearStaleError(){ if(statusEl.classList.contains('err')) setStatus('',''); }
347
- async function pollHealth(){
348
- // Recent stream activity proves liveness without a /health round-trip.
349
- if(Date.now()-lastEventTs<6000){ healthMisses=0; setConn('connected',''); clearStaleError(); return; }
350
- try{ const h=await (await fetch('/health')).json();
351
- if(h.device){ healthMisses=0; setConn('connected',''); clearStaleError(); }
352
- // Require TWO consecutive misses before flipping the dot — a single slow/missed poll
353
- // (while the stream is otherwise fine) should not flash "connecting".
354
- else if(++healthMisses>=2){ setConn('waiting','device offline, retrying…'); }
355
- }catch{ if(++healthMisses>=2) setConn('waiting','reconnecting…'); } }
356
- pollHealth(); setInterval(pollHealth,2000);
357
-
358
- // ---- the dashboard engine: build(spec) tears down and rebuilds widgets live ----
359
- let es=null, tickTimer=null;
360
- let total=0, times=[], perSec=[], counterEl=null, rateEl=null, sparkEl=null, feed=null, cards=null, GRAPH=null;
361
- // liveMatches counts ONLY genuine live arrivals (not backfilled/replayed history), so the
362
- // alert {at:N} "fire once at the Nth match" threshold is measured from when the dashboard
363
- // opened — independent of how many matching events the device buffer already held. `total`
364
- // stays history-inclusive because the counter widget should show every event seen.
365
- let liveMatches=0;
366
- function has(v){ return SPEC.viz.includes(v); }
367
- function showInspector(){ return has('feed') || has('inspector'); }
368
- function build(spec){
369
- SPEC=spec; total=0; liveMatches=0; times=[]; perSec=new Array(30).fill(0);
370
- markActiveMode();
371
- cards=document.getElementById('cards'); cards.innerHTML=''; feed=document.getElementById('feed'); feed.innerHTML='';
372
- counterEl=rateEl=sparkEl=null;
373
- const insp=document.getElementById('inspector'), stage=document.getElementById('stage');
374
- if(es){ es.close(); es=null; } if(tickTimer){ clearInterval(tickTimer); tickTimer=null; }
375
- const dbv=document.getElementById('dbview');
376
- const fp=document.getElementById('filterpanel');
377
- if(SPEC.blank){ document.getElementById('sub').textContent='Pick a dashboard above (Live, Network, RTM, Clogs, Logs, Database). For a custom view, ask a Claude Code session in your terminal to build one — it appears here as a Custom tab.'; insp.style.display='none'; stage.classList.remove('split'); if(fp) fp.style.display='none'; stage.style.display='flex'; if(dbv) dbv.style.display='none'; return; }
378
- if(SPEC.source==='db'){
379
- // The DB browser is a distinct, point-in-time view (no stream/widgets/filters). Hide the
380
- // streaming UI + the Filters panel, show the db list -> tables -> query grid.
381
- stage.style.display='none'; cards.style.display='none'; insp.style.display='none';
382
- if(fp) fp.style.display='none';
383
- const subEl=document.getElementById('sub');
384
- subEl.innerHTML='<span class="summary">'+esc(SPEC.summary||'Device database browser')+'</span><span class="tech">source=db (on-device SQLite snapshot, read-only)</span>';
385
- if(dbv) dbv.style.display='flex';
386
- buildDbView(SPEC);
387
- return;
388
- }
389
- if(dbv) dbv.style.display='none';
390
- document.getElementById('stage').style.display='flex'; cards.style.display='grid';
391
- if(showInspector()){ insp.style.display='block'; insp.innerHTML='<div class="label">inspector</div><div class="empty">click a row to see its full detail</div>'; }
392
- else { insp.style.display='none'; }
393
- const split = showInspector();
394
- stage.classList.toggle('split', split); stage.classList.toggle('haswidth', split);
395
- setupFeedControls();
396
- const subEl=document.getElementById('sub');
397
- const tech=describeConstraints(SPEC);
398
- subEl.innerHTML = SPEC.summary
399
- ? '<span class="summary">'+esc(SPEC.summary)+'</span><span class="tech">'+esc(tech)+'</span>'
400
- : esc(SPEC.title+' — '+tech);
401
- renderFilters();
402
- if(has('counter')){ const c=card('total matched', big('0','counterEl')); c.querySelector('.label').id='counterLabel'; cards.appendChild(c); }
403
- if(has('rate')){ cards.appendChild(card('rate ('+(SPEC.rateWindowSec||10)+'s)', big('0','rateEl','/'+(SPEC.rateWindowSec||10)+'s'))); }
404
- if(has('sparkline')){ const c=card('per second',''); const s=document.createElement('div'); s.className='spark'; s.id='spark'; c.appendChild(s); cards.appendChild(c); }
405
- counterEl=document.getElementById('counterEl'); rateEl=document.getElementById('rateEl'); sparkEl=document.getElementById('spark');
406
- GRAPH=null;
407
- if(has('graph') && Array.isArray(SPEC.series)){
408
- const N=60;
409
- GRAPH={ series: SPEC.series.map(s=>({def:s, buckets:new Array(N).fill(0), counts:new Array(N).fill(0)})), N };
410
- const wrap=document.createElement('div'); wrap.className='graphcard';
411
- wrap.innerHTML='<div class="label">'+esc(SPEC.series.map(s=>s.label||s.metric).join(' vs '))+'</div><svg id="graph" viewBox="0 0 640 200"></svg><div class="legend" id="legend"></div>';
412
- cards.appendChild(wrap);
413
- }
414
- if(es) es.close();
415
- es=new EventSource('/stream'); es.onmessage=onEvent;
416
- es.onerror=()=>{ setConn('waiting','reconnecting…'); };
417
- if(tickTimer) clearInterval(tickTimer); tickTimer=setInterval(tick,1000);
418
- replayCache(); // instant: everything seen this session for this source (incl logs)
419
- backfill(); // device ring-buffer history from before this session; dedup avoids double-count
420
- }
421
- // Pre-populate a freshly-built tab from the device ring-buffer (the source of truth), so
422
- // switching tabs shows recent data immediately instead of resetting to nothing. Logcat is
423
- // host-side (no device buffer) so "log"-only tabs have nothing to backfill — they still
424
- // stream live. Each replayed frame goes through onEvent with live=false, so it populates
425
- // widgets but does not fire alerts (those are reserved for genuine /stream arrivals).
426
- let backfillToken=0;
427
- async function backfill(){
428
- const myToken=++backfillToken; const src=SPEC.source;
429
- if(!src) return;
430
- if(src==='log'){ setStatus('','live device logs — history is not buffered on-device, so this tab fills as new lines arrive'); return; }
431
- try{ const r=await (await fetch('/backfill?source='+encodeURIComponent(src)+'&limit=200')).json();
432
- if(myToken!==backfillToken) return;
433
- const frames=(r&&r.frames)||[];
434
- // live=false: backfilled frames are device HISTORY (events from before this tab opened),
435
- // so they count toward widgets but must NOT fire alerts — only genuine /stream arrivals do.
436
- for(const f of frames) onEvent({data:JSON.stringify(f)}, false);
437
- if(frames.length===0){
438
- try{ const h=await (await fetch('/health')).json();
439
- if(!h.device) setStatus('error','no history loaded — device unreachable. Wake/replug the phone, then ⟳ Reconnect Radar');
440
- else setStatus('','no recent '+src+' activity buffered on the device yet — interact with Slack and it will stream in');
441
- }catch{ setStatus('error','no history loaded — device unreachable. ⟳ Reconnect Radar'); }
442
- }
443
- }catch{ setStatus('error','backfill failed — device unreachable?'); }
444
- }
445
- function matches(ev){ if(!SPEC.match) return true;
446
- return Object.entries(SPEC.match).every(([k,v])=>{
447
- // the package field only exists on LOG events. In the unified "all" timeline, applying
448
- // it to network/rtm/clog (which have no package) would wrongly drop them — they already
449
- // come from the Slack app. So a package filter constrains log rows only; others pass.
450
- if(k==='package' && ev._type && ev._type!=='log') return true;
451
- return String(ev[k]??'').toLowerCase().includes(String(v).toLowerCase());
452
- }); }
453
-
454
- // ---- hand-editable Filters panel: renders the current spec's filters as form controls,
455
- // edits POST back to /setspec, engine rebuilds live ----
456
- const MATCH_FIELDS={ network:['url','method','status_code'], rtm:['event_type','direction','channel'], clog:['event_name'],
457
- log:['tag','level','message','pid','package'], all:['url','method','status_code','event_type','direction','channel','event_name','tag','level','message','pid','package'] };
458
- const FIELD_VALUES={ direction:['OUTGOING','INCOMING'], level:['VERBOSE','DEBUG','INFO','WARN','ERROR','FATAL'], method:['GET','POST','PUT','DELETE','PATCH'] };
459
- function candidatesFor(field){
460
- if(FIELD_VALUES[field]) return FIELD_VALUES[field].slice();
461
- const seen=SEEN[field]; return seen ? [...seen].sort() : [];
462
- }
463
- function valueControlHTML(field,val){
464
- const n=candidatesFor(field).length;
465
- const ph = FIELD_VALUES[field] ? 'pick or type…' : (n? 'type or pick ('+n+' seen)' : 'contains…');
466
- return '<span class="combo"><input class="f_mv" autocomplete="off" data-field="'+esc(field)+'" value="'+esc(String(val).trim())+'" placeholder="'+ph+'"/><span class="combocaret">▾</span><div class="combolist"></div></span>';
467
- }
468
- function renderFilters(){
469
- const panel=document.getElementById('filterpanel'), bodyEl=document.getElementById('filterbody');
470
- if(!panel||SPEC.blank){ if(panel) panel.style.display='none'; return; }
471
- if(!panel._wired){ panel._wired=true; panel.addEventListener('toggle',()=>{ if(panel.open) renderFilters(); }); }
472
- panel.style.display='block';
473
- const fields=MATCH_FIELDS[SPEC.source]||[];
474
- const m=SPEC.match&&typeof SPEC.match==='object'?SPEC.match:{};
475
- let h='';
476
- h+='<div class="frow"><label>source</label><select id="f_source">'+
477
- ['rtm','network','clog','log','all'].map(s=>'<option'+(s===SPEC.source?' selected':'')+'>'+s+'</option>').join('')+'</select></div>';
478
- h+='<div class="fsec">match (all must hold)</div><div id="f_matchrows">';
479
- const entries=Object.entries(m); if(!entries.length) h+='<div class="fhint">no match filter — showing everything</div>';
480
- for(const [k,v] of entries){ h+=matchRow(k,v,fields); }
481
- h+='</div><button class="fadd" id="f_addmatch">+ add match field</button>';
482
- if(SPEC.source==='network'||SPEC.source==='all')
483
- h+='<div class="frow"><label>body contains</label><input id="f_body" value="'+esc(SPEC.bodyContains||'')+'" placeholder="substring in request/response body"/></div>';
484
- const hl=SPEC.highlight||{};
485
- h+='<div class="fsec">highlight (flag rows)</div><div class="frow">'+
486
- '<input id="f_hlfield" value="'+esc(hl.field||'')+'" placeholder="field e.g. duration_ms" style="flex:2"/>'+
487
- '<select id="f_hlop">'+['>','>=','<','<=','=='].map(o=>'<option'+(o===(hl.op||'>')?' selected':'')+'>'+o+'</option>').join('')+'</select>'+
488
- '<input id="f_hlval" value="'+(hl.value!=null?hl.value:'')+'" placeholder="value" style="flex:1"/></div>';
489
- h+='<div class="frow"><label>rate window (s)</label><input id="f_rate" type="number" value="'+(SPEC.rateWindowSec||10)+'" style="flex:1"/></div>';
490
- h+='<div class="frow"><button class="fapply" id="f_apply">Apply changes</button><span id="f_msg" class="fmsg"></span></div>';
491
- bodyEl.innerHTML=h;
492
- bodyEl.querySelectorAll('.matchrow').forEach(wireMatchRow);
493
- document.getElementById('f_addmatch').onclick=()=>{ const d=document.createElement('div'); d.innerHTML=matchRow(fields[0]||'','',fields); const row=d.firstChild; document.getElementById('f_matchrows').appendChild(row); wireMatchRow(row); };
494
- document.getElementById('f_apply').onclick=applyFilters;
495
- }
496
- function matchRow(k,v,fields){
497
- const opts=fields.map(f=>'<option'+(f===k?' selected':'')+'>'+f+'</option>').join('');
498
- return '<div class="frow matchrow"><select class="f_mk">'+opts+(fields.includes(k)?'':'<option selected>'+esc(k)+'</option>')+
499
- '</select><span class="f_mvwrap">'+valueControlHTML(k,v)+'</span><button class="fdel">✕</button></div>';
500
- }
501
- function wireMatchRow(row){
502
- const mk=row.querySelector('.f_mk'), wrap=row.querySelector('.f_mvwrap');
503
- mk.onchange=()=>{ wrap.innerHTML=valueControlHTML(mk.value,''); wireCombo(wrap.querySelector('.combo')); };
504
- row.querySelector('.fdel').onclick=()=>row.remove();
505
- wireCombo(wrap.querySelector('.combo'));
506
- }
507
- function wireCombo(combo){
508
- if(!combo) return;
509
- const input=combo.querySelector('.f_mv'), caret=combo.querySelector('.combocaret'), list=combo.querySelector('.combolist');
510
- const field=input.getAttribute('data-field');
511
- const openList=()=>{ const q=input.value.trim().toLowerCase();
512
- const cands=candidatesFor(field).filter(v=>!q||String(v).toLowerCase().includes(q)).slice(0,50);
513
- if(!cands.length){ list.classList.remove('open'); return; }
514
- list.innerHTML=cands.map(v=>'<div class="comboitem">'+esc(v)+'</div>').join('');
515
- list.classList.add('open');
516
- list.querySelectorAll('.comboitem').forEach(it=>it.onmousedown=(e)=>{ e.preventDefault(); input.value=it.textContent; list.classList.remove('open'); });
517
- };
518
- input.onfocus=openList; input.oninput=openList;
519
- caret.onmousedown=(e)=>{ e.preventDefault(); if(list.classList.contains('open')) list.classList.remove('open'); else { input.focus(); openList(); } };
520
- input.onblur=()=>setTimeout(()=>list.classList.remove('open'),120);
521
- }
522
- async function applyFilters(){
523
- const g=id=>document.getElementById(id);
524
- const spec=JSON.parse(JSON.stringify(SPEC));
525
- spec.source=g('f_source').value;
526
- const match={}; document.querySelectorAll('#f_matchrows .matchrow').forEach(r=>{ const k=r.querySelector('.f_mk').value.trim(); const v=r.querySelector('.f_mv').value.trim(); if(k&&v) match[k]=v; });
527
- spec.match=match;
528
- const body=g('f_body'); if(body){ const bv=body.value.trim(); if(bv) spec.bodyContains=bv; else delete spec.bodyContains; }
529
- const hf=g('f_hlfield').value.trim(), hv=g('f_hlval').value.trim();
530
- if(hf&&hv!==''&&!isNaN(Number(hv))) spec.highlight={field:hf,op:g('f_hlop').value,value:Number(hv),label:(SPEC.highlight&&SPEC.highlight.label)||hf}; else delete spec.highlight;
531
- const rw=Number(g('f_rate').value); if(rw>0) spec.rateWindowSec=rw;
532
- const msg=g('f_msg'); msg.textContent='applying…';
533
- markLocalPush(spec); // a hand-edit of the current view, not a Claude-pushed Custom dashboard
534
- try{ const r=await (await fetch('/setspec',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(spec)})).json();
535
- msg.textContent = r.ok?'applied ✓':('⚠ '+(r.error||'rejected')); }
536
- catch{ msg.textContent='⚠ failed'; }
537
- }
538
- function pluck(o,p){ return p.split('.').reduce((x,k)=>(x==null?undefined:x[k]),o); }
539
- async function enrich(ev){ if(!SPEC.extract||ev.id==null) return null; try{ const kind=SPEC.extract.kind||SPEC.source; const d=await (await fetch('/detail?kind='+kind+'&id='+ev.id)).json(); let src=d[SPEC.extract.parse||'response_body']; if(typeof src==='string'){ try{src=JSON.parse(src);}catch{} } return pluck(src,SPEC.extract.field); }catch{ return null; } }
540
- function setConn(state,msg){ const d=document.getElementById('conn'); if(!d) return; d.className='conn '+state; d.textContent=(state==='connected'?'● live':'● '+(msg||'reconnecting…'));
541
- const rc=document.getElementById('reconnect'); if(rc && !rc._busy) rc.style.display = state==='connected' ? 'none' : 'inline-block'; }
542
- async function doReconnect(){ const rc=document.getElementById('reconnect'); if(!rc) return; rc._busy=true; rc.disabled=true; rc.textContent='⟳ enabling…';
543
- try{ await fetch('/enable',{method:'POST'}); }catch{}
544
- rc._busy=false; rc.disabled=false; rc.textContent='⟳ Reconnect Radar'; pollHealth(); pollSpec(); }
545
- // live defaults true so the SSE handler (es.onmessage=onEvent) keeps firing alerts on
546
- // genuine arrivals; backfill() passes live=false so replayed device HISTORY counts toward
547
- // widgets without triggering alerts for events that already happened.
548
- function onEvent(m, live){ if(live===undefined) live=true; let f; try{f=JSON.parse(m.data);}catch{return;}
549
- if(f.type==='_status'){ setConn(f.event.state, f.event.msg); return; }
550
- if(f.type==='_error'){ setConn('waiting', f.event.msg); return; }
551
- // Server-replayed log history is tagged replay:true. Treat it as history (live=false)
552
- // so it never fires alerts or pulses, even on a fresh browser whose own cache is empty
553
- // (the server log ring outlives/outsizes the client cache, so reconnect replay can carry
554
- // frames the client never saw). Live frames are unaffected.
555
- if(f.replay) live=false;
556
- if(!['network','rtm','clog','log'].includes(f.type)) return;
557
- lastEventTs=Date.now(); setConn('connected','');
558
- const ev=f.event||{}; ev._type=f.type;
559
- // Cache EVERY frame (all types, before the current-tab filter) so a tab switch can
560
- // replay history — including logs, which the device cannot backfill. Dedup: a frame
561
- // already cached (re-delivered by a stream reconnect or present in backfill) is not
562
- // re-counted. cacheFrame() also learns dropdown values via observe().
563
- const isNew=cacheFrame(f.type,ev);
564
- if(SPEC.source!=='all' && f.type!==SPEC.source) return; // not for the current tab's widgets
565
- if(!isNew) return; // already rendered/counted this frame
566
- if(!matches(ev)) return;
567
- if(SPEC.bodyContains){ bodyMatches(ev).then(ok=>{ if(ok) acceptEvent(ev,live); }); return; }
568
- acceptEvent(ev,live);
569
- }
570
- async function bodyMatches(ev){ if(ev.id==null || ev._type==='clog') return false; const needle=String(SPEC.bodyContains).toLowerCase();
571
- try{ const d=await (await fetch('/detail?kind='+(ev._type||SPEC.source)+'&id='+ev.id)).json();
572
- return ((d.request_body||'')+(d.response_body||'')).toLowerCase().includes(needle); }catch{ return false; } }
573
- const SEEN={};
574
- const SUGGEST_FIELDS=['event_type','event_name','tag','status_code','channel','url','package'];
575
- function observe(ev){ for(const f of SUGGEST_FIELDS){ let v=ev[f]; if(v==null||v==='') continue;
576
- if(f==='url'){ try{ v=new URL(v).pathname.replace('/api/',''); }catch{} }
577
- v=String(v); if(v.length>80) continue;
578
- (SEEN[f]||(SEEN[f]=new Set())).add(v);
579
- const cap = f==='package' ? Infinity : 500;
580
- while(SEEN[f].size>cap){ const it=SEEN[f].values().next().value; SEEN[f].delete(it); } } }
581
- // Session cache: every frame seen this browser session, across ALL tabs, keyed for
582
- // dedup. Switching tabs replays from here so events (and logs, which the device cannot
583
- // backfill) persist instead of the stream restarting from zero.
584
- // EVICTION (two bounds, whichever hits first, so memory is bounded on a long-lived tab):
585
- // 1. COUNT — at most CACHE_CAP frames (FIFO drop oldest).
586
- // 2. AGE — frames older than CACHE_TTL_MS are dropped on each insert + on a timer.
587
- // The dedup Set is kept in lockstep with the array (evicted keys are deleted) so it can
588
- // never grow unbounded. evictCache() also runs on a 30s timer to age out an idle tab.
589
- const CACHE=[]; const CACHE_KEYS=new Set(); const CACHE_CAP=8000; const CACHE_TTL_MS=15*60*1000;
590
- function frameKey(type,ev){ return type+':'+(ev.id!=null?ev.id:(ev.log_ts||'')+'|'+(ev.pid||'')+'|'+(ev.message||ev.event_type||ev.event_name||'')); }
591
- function dropFront(){ const old=CACHE.shift(); if(old) CACHE_KEYS.delete(frameKey(old.type,old.ev)); }
592
- function evictCache(){ const cutoff=Date.now()-CACHE_TTL_MS;
593
- while(CACHE.length && CACHE[0].ts<cutoff) dropFront(); // age bound
594
- while(CACHE.length>CACHE_CAP) dropFront(); // count bound
595
- }
596
- setInterval(evictCache,30000); // age out an idle tab even with no new frames arriving
597
- // Add a frame to the cache. Returns true if NEW (not a dup re-delivery). Learns
598
- // dropdown values here so suggestions reflect everything seen, not just rendered.
599
- function cacheFrame(type,ev){ const k=frameKey(type,ev); if(CACHE_KEYS.has(k)) return false;
600
- CACHE_KEYS.add(k); CACHE.push({type,ev,ts:ev.timestamp||Date.now()}); observe(ev);
601
- evictCache();
602
- return true; }
603
- // Replay the cache into the freshly-built tab, filtered to the current source, in
604
- // chronological order. Counters/rate/sparkline/graph all reflect it because acceptEvent
605
- // buckets by each event's REAL timestamp. Like backfill, this is HISTORY: it passes
606
- // live=false so alerts do not fire — only genuine /stream arrivals (onEvent default) do.
607
- // Replay applies matches() but NOT bodyContains: the body filter is live-only by design.
608
- // Honoring it here would mean one /detail fetch per cached row on every tab switch (a
609
- // fetch storm up to the full cache). Replay shows what you already saw; the body filter
610
- // stays a live-only refinement.
611
- function replayCache(){
612
- const rows=CACHE.filter(c=> (SPEC.source==='all'||c.type===SPEC.source));
613
- for(const c of rows){ const ev=c.ev; ev._type=c.type; if(matches(ev)) acceptEvent(ev,false); }
614
- }
615
- // Rebuild the FEED rows from the session cache for the current FEED.filter, WITHOUT
616
- // touching counters/graph (those already counted every event). Needed because addRow now
617
- // drops non-matching rows from the DOM entirely (not insert-then-hide), so changing or
618
- // clearing the feed filter cannot just un-hide rows that are no longer there — it must
619
- // re-add the matching ones from the cache.
620
- function rebuildFeedFromCache(){
621
- if(!feed) return;
622
- feed.innerHTML='';
623
- const rows=CACHE.filter(c=> (SPEC.source==='all'||c.type===SPEC.source));
624
- for(const c of rows){ const ev=c.ev; ev._type=c.type;
625
- if(!matches(ev)) continue;
626
- const r=addRow(ev, ev.timestamp||Date.now());
627
- if(r && SPEC.extract) enrich(ev).then(val=>{ if(val!=null&&r) appendExtract(r,val); });
628
- }
629
- if(FEED.sort!=='newest') applyFeedControls(); else updateFeedCount();
630
- }
631
- // accept an event into the widgets. live=true for stream arrivals (fires alerts, enrich,
632
- // pulse); live=false for cache replay (silent, time-accurate). Buckets by the event's own
633
- // timestamp so replayed history lands in the right second of the rate/sparkline/graph.
634
- function acceptEvent(ev, live){ if(live===undefined) live=true; const now=Date.now(); const ets=ev.timestamp||now;
635
- const ageSec=Math.max(0,Math.floor((now-ets)/1000));
636
- total++; times.push(ets);
637
- const si=perSec.length-1-ageSec; if(si>=0&&si<perSec.length) perSec[si]++;
638
- if(GRAPH){ const gi=GRAPH.N-1-ageSec; if(gi>=0&&gi<GRAPH.N){ for(const s of GRAPH.series){ const d=s.def;
639
- if(d.metric==='ratePerSec') s.buckets[gi]++;
640
- else if(d.metric==='count') s.buckets[gi]++;
641
- else if(d.metric==='avg'){ const v=Number(ev[d.field]); if(!isNaN(v)){ s.buckets[gi]+=v; s.counts[gi]++; } }
642
- else if(d.metric==='errorRate'){ s.counts[gi]++; if(Number(ev.status_code)>=400) s.buckets[gi]++; }
643
- } } }
644
- if(counterEl){ syncCounter(); if(live){ counterEl.classList.remove('pulse'); void counterEl.offsetWidth; counterEl.classList.add('pulse'); } }
645
- const row=FEED.paused?null:addRow(ev,ets); if(row && live && SPEC.extract) enrich(ev).then(val=>{ if(val!=null&&row) appendExtract(row,val); });
646
- if(live){ liveMatches++;
647
- if(SPEC.alert){ const at=Number(SPEC.alert.at)||0;
648
- // at:N fires once on the Nth LIVE match (liveMatches), not the Nth event overall —
649
- // device history replayed at build time must not consume the threshold.
650
- if(at>0){ if(liveMatches===at) fireAlert(ev, 'reached '+at); }
651
- else fireAlert(ev);
652
- }
653
- }
654
- }
655
- let audioCtx=null;
656
- function beep(){ try{ audioCtx=audioCtx||new (window.AudioContext||window.webkitAudioContext)(); const o=audioCtx.createOscillator(), g=audioCtx.createGain(); o.type='sine'; o.frequency.value=880; o.connect(g); g.connect(audioCtx.destination); g.gain.setValueAtTime(0.0001,audioCtx.currentTime); g.gain.exponentialRampToValueAtTime(0.25,audioCtx.currentTime+0.01); g.gain.exponentialRampToValueAtTime(0.0001,audioCtx.currentTime+0.25); o.start(); o.stop(audioCtx.currentTime+0.26); }catch{} }
657
- let alertTimer=null;
658
- function dismissAlert(){ const b=document.getElementById('alertbanner'); b.classList.remove('on'); if(alertTimer){ clearTimeout(alertTimer); alertTimer=null; } }
659
- function fireAlert(ev, note){ const a=SPEC.alert||{};
660
- if(a.flash!==false){ const f=document.getElementById('flash'); f.classList.add('on'); setTimeout(()=>f.classList.remove('on'),140); }
661
- if(a.sound!==false) beep();
662
- const tail = note ? note : esc(ev.event_type||ev.event_name||shortUrl(ev.url)||'');
663
- const b=document.getElementById('alertbanner'); b.innerHTML='<span>'+esc(a.say||'ALERT')+' — '+tail+'</span><span class="x">dismiss ✕</span>'; b.classList.add('on');
664
- if(!alertTimer) alertTimer=setTimeout(dismissAlert,2500);
665
- }
666
- function tick(){ const now=Date.now(), w=(SPEC.rateWindowSec||10)*1000; while(times.length&&times[0]<now-w) times.shift(); if(rateEl) rateEl.textContent=times.length; perSec.push(0); if(perSec.length>30) perSec.shift(); if(sparkEl){ const mx=Math.max(1,...perSec); sparkEl.innerHTML=perSec.map(n=>'<div class="bar" style="height:'+(2+n/mx*56)+'px"></div>').join(''); }
667
- if(GRAPH){ drawGraph(); for(const s of GRAPH.series){ s.buckets.push(0); s.buckets.shift(); s.counts.push(0); s.counts.shift(); } }
668
- if((SPEC.source==='log'||SPEC.source==='all') && document.activeElement!==document.getElementById('fpkg')) refreshPkgOptions();
669
- }
670
- const GCOLORS=['#39d98a','#ffd479'];
671
- function unitFor(def){
672
- if(def.unit) return def.unit;
673
- if(def.metric==='ratePerSec') return '/s';
674
- if(def.metric==='avg') return (def.field&&/ms|duration/i.test(def.field))?'ms':'';
675
- if(def.metric==='errorRate') return '%';
676
- if(def.metric==='count') return '';
677
- return '';
678
- }
679
- function fmtNum(v){ if(v==null) return '—'; const a=Math.abs(v); return a>=100?Math.round(v):a>=10?Math.round(v*10)/10:Math.round(v*100)/100; }
680
- function seriesValues(s){
681
- if(s.def.metric==='count'){ let run=0; return s.buckets.map(b=>run+=b); }
682
- if(s.def.metric==='avg') return s.buckets.map((b,i)=> s.counts[i]? b/s.counts[i] : null);
683
- if(s.def.metric==='errorRate') return s.buckets.map((b,i)=> s.counts[i]? b/s.counts[i] : null);
684
- return s.buckets.slice();
685
- }
686
- function drawGraph(){ const svg=document.getElementById('graph'); if(!svg) return;
687
- const VB_W=640, VB_H=200, N=GRAPH.N;
688
- const L=46, R=GRAPH.series.length>1?52:14, T=10, B=26;
689
- const x0=L, x1=VB_W-R, y0=T, y1=VB_H-B, pw=x1-x0, ph=y1-y0;
690
- let out='', legend='';
691
- out+='<rect x="'+x0+'" y="'+y0+'" width="'+pw+'" height="'+ph+'" fill="none" stroke="#1e2a3a"/>';
692
- for(let k=0;k<=4;k++){ const fx=x0+(k/4)*pw; const secsAgo=Math.round((1-k/4)*N); const lbl=secsAgo===0?'now':'-'+secsAgo+'s';
693
- out+='<line x1="'+fx.toFixed(1)+'" y1="'+y1+'" x2="'+fx.toFixed(1)+'" y2="'+(y1+4)+'" stroke="#33455c"/>';
694
- out+='<text x="'+fx.toFixed(1)+'" y="'+(y1+16)+'" fill="#5f7186" font-size="10" text-anchor="middle">'+lbl+'</text>'; }
695
- GRAPH.series.forEach((s,si)=>{ const raw=seriesValues(s);
696
- const scale = s.def.metric==='errorRate'?100:1;
697
- let last=null; const vals=raw.map(v=>{ v=(v==null?null:v*scale); if(v!=null){ last=v; return v; } return last; });
698
- const real=vals.filter(v=>v!=null); const mx=Math.max(1,...real);
699
- const col=GCOLORS[si], unit=unitFor(s.def);
700
- const axX = si===0 ? x0 : x1; const anchor = si===0?'end':'start'; const tx = si===0 ? x0-6 : x1+6;
701
- for(let k=0;k<=2;k++){ const val=mx*k/2; const fy=y1-(k/2)*ph;
702
- out+='<text x="'+tx+'" y="'+(fy+3).toFixed(1)+'" fill="'+col+'" font-size="10" text-anchor="'+anchor+'">'+fmtNum(val)+'</text>'; }
703
- out+='<text x="'+axX+'" y="'+(y0-1)+'" fill="'+col+'" font-size="9" text-anchor="'+(si===0?'start':'end')+'">'+esc(unit||s.def.metric)+'</text>';
704
- const pts=vals.map((v,i)=>{ if(v==null) return null; const px=x0+(i/(N-1))*pw; const py=y1-(v/mx)*ph; return px.toFixed(1)+','+py.toFixed(1); }).filter(Boolean).join(' ');
705
- if(pts) out+='<polyline fill="none" stroke="'+col+'" stroke-width="2" points="'+pts+'"/>';
706
- const h=SPEC.highlight;
707
- if(h && s.def.field && h.field===s.def.field && h.value<=mx){ const ty=y1-(h.value/mx)*ph;
708
- out+='<line x1="'+x0+'" y1="'+ty.toFixed(1)+'" x2="'+x1+'" y2="'+ty.toFixed(1)+'" stroke="#ff3b30" stroke-width="1" stroke-dasharray="4 3"/>';
709
- out+='<text x="'+(x0+4)+'" y="'+(ty-3).toFixed(1)+'" fill="#ff6b60" font-size="9">'+esc(h.label||('>'+h.value))+' '+esc(unit||'')+'</text>'; }
710
- const shown=fmtNum(last)+(unit?(' '+unit):'');
711
- legend+='<span style="color:'+col+'">■ '+esc(s.def.label||s.def.metric)+': '+shown+'</span> ';
712
- });
713
- svg.innerHTML=out; const lg=document.getElementById('legend'); if(lg) lg.innerHTML=legend+' <span style="color:#5f7186">x: time (last '+N+'s, right=now)</span>';
714
- }
715
- function shortUrl(u){ try{ return new URL(u).pathname.replace('/api/',''); }catch{ return u||''; } }
716
- function shortPkg(p){ if(!p) return ''; const parts=String(p).split('.'); return parts.length<=2?p:parts.slice(-2).join('.'); }
717
- function addRow(ev,now){ if(!has('feed')) return null; const r=document.createElement('div'); r.className='row'; const ts=new Date(ev.timestamp||now).toLocaleTimeString();
718
- const typeChip = (SPEC.source==='all' && ev._type) ? '<span class="tchip t-'+ev._type+'">'+ev._type+'</span>' : '';
719
- if((ev._type||SPEC.source)==='log'){
720
- const lv=(ev.level||'').toUpperCase();
721
- const pkg = ev.package ? '<span class="logpkg" title="'+esc(ev.package)+'">'+esc(shortPkg(ev.package))+'</span>' : '';
722
- r.innerHTML='<span class="t">'+ts+'</span>'+typeChip+'<span class="lvl lvl-'+lv+'">'+esc(lv||'LOG')+'</span>'+pkg+'<span class="logtag">'+esc(ev.tag||'')+'</span><span class="logmsg">'+esc(ev.message||'')+'</span>';
723
- } else {
724
- r.innerHTML='<span class="t">'+ts+'</span>'+typeChip+'<span class="dir-'+(ev.direction||'')+'">'+(ev.direction||ev.method||'')+'</span><span>'+esc(ev.event_type||ev.event_name||shortUrl(ev.url))+'</span>'+(ev.channel?'<span class="chan">'+esc(ev.channel)+'</span>':'');
725
- }
726
- if(showInspector()){ r.classList.add('clickable'); r._ev=ev; r.onclick=()=>inspect(r,ev); }
727
- if(breaches(ev)){ r.classList.add('breach'); const h=SPEC.highlight; const v=Number(ev[h.field]);
728
- const unit = /ms|duration/i.test(h.field)?'ms' : (h.field==='status_code'?'':'');
729
- const b=document.createElement('span'); b.className='breachbadge'; b.textContent=fmtNum(v)+unit+' '+(h.op||'>')+' '+h.value+unit;
730
- r.appendChild(b); }
731
- r._search=(r.textContent||'').toLowerCase(); r._ev=ev; r._ts=ev.timestamp||now;
732
- // When the feed text filter is active, DROP non-matching rows entirely instead of
733
- // inserting-then-hiding them. The 200-row DOM cap below counts every child, so hidden
734
- // non-matching rows would otherwise flood the cap and evict the matching rows the user
735
- // is watching for (filtered rows flash in, then vanish as unmatched rows push them out).
736
- if(FEED.filter && !r._search.includes(FEED.filter)) return null;
737
- const atTop = feed.scrollTop <= 4;
738
- feed.insertBefore(r,feed.firstChild); while(feed.children.length>200) feed.removeChild(feed.lastChild);
739
- if(!atTop){ feed.scrollTop += r.offsetHeight; }
740
- if(FEED.sort!=='newest') applyFeedControls(); else updateFeedCount();
741
- return r; }
742
- const LOG_LEVEL_RANK={ FATAL:5, ERROR:4, WARN:3, INFO:2, DEBUG:1, VERBOSE:0 };
743
- const TYPE_RANK={ network:0, rtm:1, clog:2, log:3 };
744
- function sortOptionsFor(spec){
745
- const src=spec.source, opts=[{key:'newest',label:'newest first',get:r=>r._ts,dir:'desc'},{key:'oldest',label:'oldest first',get:r=>r._ts,dir:'asc'}];
746
- if(src==='all'){
747
- opts.push({key:'type',label:'group by type',get:r=>TYPE_RANK[r._ev._type]??9,dir:'asc'});
748
- return opts;
749
- }
750
- if(src==='network'){
751
- opts.push({key:'slow',label:'slowest (response time)',get:r=>Number(r._ev.duration_ms),dir:'desc'});
752
- opts.push({key:'status',label:'status code (high→low)',get:r=>Number(r._ev.status_code),dir:'desc'});
753
- }
754
- if(src==='log') opts.push({key:'severity',label:'severity (errors first)',get:r=>LOG_LEVEL_RANK[(r._ev.level||'').toUpperCase()]??-1,dir:'desc'});
755
- if(src==='rtm') opts.push({key:'evtype',label:'event type (A→Z)',get:r=>r._ev.event_type||'',dir:'asc'});
756
- if(src==='clog') opts.push({key:'name',label:'clog name (A→Z)',get:r=>r._ev.event_name||'',dir:'asc'});
757
- if(spec.highlight && spec.highlight.field && !opts.some(o=>o.key===spec.highlight.field))
758
- opts.push({key:spec.highlight.field,label:spec.highlight.field+' (high→low)',get:r=>Number(r._ev[spec.highlight.field]),dir:'desc'});
759
- return opts;
760
- }
761
- function breaches(ev){ const h=SPEC.highlight; if(!h) return false; const v=Number(ev[h.field]); if(isNaN(v)) return false;
762
- const op=h.op||'>'; return op==='>'?v>h.value:op==='>='?v>=h.value:op==='<'?v<h.value:op==='<='?v<=h.value:v===h.value; }
763
-
764
- // ---- feed controls: instant filter, pause, dynamic sort (operate on rendered rows) ----
765
- let FEED={ filter:'', sort:'newest', paused:false, opts:[] };
766
- function setupFeedControls(){
767
- const opts=sortOptionsFor(SPEC);
768
- const stickySort = opts.some(o=>o.key===FEED.sort) ? FEED.sort : 'newest';
769
- FEED={ filter:FEED.filter||'', sort:stickySort, paused:false, opts };
770
- const bar=document.getElementById('feedbar'); if(!bar) return;
771
- bar.style.display = has('feed') ? 'flex' : 'none';
772
- const fi=document.getElementById('ffilter'), fs=document.getElementById('fsort'), fp=document.getElementById('fpause');
773
- fi.value=FEED.filter; fp.textContent='⏸ live'; fp.classList.remove('paused');
774
- fs.innerHTML=FEED.opts.map(o=>'<option value="'+o.key+'">'+o.label+'</option>').join('');
775
- fs.value=FEED.sort;
776
- const fx=document.getElementById('ffilterclear');
777
- const syncClear=()=>{ if(fx) fx.style.display = fi.value ? 'block' : 'none'; };
778
- const clearFilterBox=()=>{ fi.value=''; FEED.filter=''; syncClear(); rebuildFeedFromCache(); fi.focus(); };
779
- syncClear();
780
- // Rebuild from cache (not just hide/show) because addRow drops non-matching rows from
781
- // the DOM, so a filter change must re-add matching rows that are no longer present.
782
- // Debounced: oninput fires per keystroke, and rebuild re-runs enrich() per matching row
783
- // on extract dashboards, so an undebounced rebuild-per-keystroke can fan out /detail
784
- // fetches. Settle ~180ms after the last keystroke before rebuilding.
785
- let filterTimer=null;
786
- fi.oninput=()=>{ FEED.filter=fi.value.trim().toLowerCase(); syncClear();
787
- if(filterTimer) clearTimeout(filterTimer); filterTimer=setTimeout(rebuildFeedFromCache,180); };
788
- fi.onkeydown=(e)=>{ if(e.key==='Escape') clearFilterBox(); };
789
- if(fx) fx.onclick=clearFilterBox;
790
- fs.onchange=()=>{ FEED.sort=fs.value; applyFeedControls(); };
791
- fp.onclick=()=>{ FEED.paused=!FEED.paused; fp.textContent=FEED.paused?'▶ paused':'⏸ live'; fp.classList.toggle('paused',FEED.paused); };
792
- setupPkgControl();
793
- renderChips();
794
- }
795
- function renderChips(){
796
- const wrap=document.getElementById('chips'); if(!wrap) return;
797
- if(!SPEC||SPEC.blank||!has('feed')){ wrap.style.display='none'; return; }
798
- const m=(SPEC.match&&typeof SPEC.match==='object')?SPEC.match:{};
799
- const items=Object.entries(m).map(([k,v])=>({k,v,kind:'match'}));
800
- if(SPEC.bodyContains) items.push({k:'body contains',v:SPEC.bodyContains,kind:'body'});
801
- if(!items.length){ wrap.style.display='none'; return; }
802
- wrap.style.display='flex';
803
- wrap.innerHTML=items.map((it,i)=>'<span class="chip"><b>'+esc(it.k)+':</b><span class="v">'+esc(String(it.v))+'</span><span class="x" data-i="'+i+'">✕</span></span>').join('');
804
- wrap.querySelectorAll('.x').forEach(x=>x.onclick=()=>{ const it=items[Number(x.dataset.i)]; clearFilter(it); });
805
- }
806
- async function clearFilter(it){
807
- const spec=JSON.parse(JSON.stringify(SPEC));
808
- if(it.kind==='body') delete spec.bodyContains;
809
- else { if(spec.match) delete spec.match[it.k]; if(spec.match&&!Object.keys(spec.match).length) delete spec.match; }
810
- await fetch('/setspec',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(spec)}).catch(()=>{});
811
- }
812
- function setupPkgControl(){
813
- const wrap=document.getElementById('fpkgwrap'), sel=document.getElementById('fpkg');
814
- if(!wrap||!sel) return;
815
- const isLogish = SPEC.source==='log'||SPEC.source==='all';
816
- wrap.style.display = isLogish ? 'flex' : 'none';
817
- if(!isLogish) return;
818
- refreshPkgOptions();
819
- sel.onchange=async()=>{ const v=sel.value;
820
- const spec=JSON.parse(JSON.stringify(SPEC)); spec.match=spec.match||{};
821
- if(v==='__all__') delete spec.match.package; else spec.match.package=v;
822
- if(!Object.keys(spec.match).length) delete spec.match;
823
- await fetch('/setspec',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(spec)}).catch(()=>{});
824
- };
825
- }
826
- // Package options are learned live from the stream (observed in SEEN.package). No internal
827
- // package list is baked in; the running debug build surfaces as soon as it emits a line.
828
- function refreshPkgOptions(){
829
- const sel=document.getElementById('fpkg'); if(!sel) return;
830
- const cur=(SPEC.match&&SPEC.match.package)||'__all__';
831
- const observed=[...(SEEN.package||new Set())].sort();
832
- let pkgs=observed.slice();
833
- if(cur!=='__all__'&&!pkgs.includes(cur)) pkgs.unshift(cur);
834
- const opts=['<option value="__all__">all apps</option>'].concat(pkgs.map(p=>'<option value="'+esc(p)+'"'+(p===cur?' selected':'')+'>'+esc(shortPkg(p))+'</option>'));
835
- sel.innerHTML=opts.join(''); sel.value=cur;
836
- }
837
- function applyFeedControls(){ if(!feed) return; const rows=[...feed.children];
838
- let shown=0; for(const r of rows){ const hide = FEED.filter && !(r._search||'').includes(FEED.filter); r.classList.toggle('hidden',hide); if(!hide) shown++; }
839
- const opt=FEED.opts.find(o=>o.key===FEED.sort)||FEED.opts[0];
840
- const val=(r)=>{ const v=opt.get(r); return (v==null||(typeof v==='number'&&isNaN(v)))?null:v; };
841
- rows.sort((a,b)=>{ const va=val(a), vb=val(b); if(va==null&&vb==null) return 0; if(va==null) return 1; if(vb==null) return -1;
842
- if(va<vb) return opt.dir==='asc'?-1:1; if(va>vb) return opt.dir==='asc'?1:-1; return 0; });
843
- for(const r of rows) feed.appendChild(r);
844
- updateFeedCount(shown);
845
- }
846
- function updateFeedCount(shown){ const c=document.getElementById('fcount'); if(!c||!feed) return;
847
- const total=feed.children.length; if(shown==null) shown=[...feed.children].filter(r=>!r.classList.contains('hidden')).length;
848
- c.textContent = FEED.filter ? (shown+' / '+total+' shown') : (total+' rows');
849
- syncCounter(shown); }
850
- function syncCounter(shown){
851
- if(!counterEl) return;
852
- const label=document.getElementById('counterLabel');
853
- if(FEED && FEED.filter){
854
- if(shown==null) shown=[...feed.children].filter(r=>!r.classList.contains('hidden')).length;
855
- counterEl.textContent=shown;
856
- if(label) label.textContent = total>feed.children.length ? 'matching "'+FEED.filter+'" (recent)' : 'matching "'+FEED.filter+'"';
857
- } else {
858
- counterEl.textContent=total;
859
- if(label) label.textContent='total matched';
860
- }
861
- }
862
- let inspectToken=0;
863
- async function inspect(row,ev){
864
- const insp=document.getElementById('inspector');
865
- if(row.classList.contains('sel')){ row.classList.remove('sel'); insp.innerHTML='<div class="label">inspector</div><div class="empty">click a row to see its full detail</div>'; inspectToken++; return; }
866
- document.querySelectorAll('.row.sel').forEach(x=>x.classList.remove('sel')); row.classList.add('sel');
867
- const myToken=++inspectToken;
868
- insp.innerHTML='<div class="label">inspector</div><div class="empty">loading…</div>';
869
- let detail=ev;
870
- const kind=ev._type||SPEC.source;
871
- if(ev.id!=null && kind!=='clog' && kind!=='log'){ try{ detail=await (await fetch('/detail?kind='+kind+'&id='+ev.id)).json(); }catch{} }
872
- if(myToken!==inspectToken) return;
873
- const shown=JSON.parse(JSON.stringify(detail));
874
- for(const k of ['response_body','request_body','data']){ if(typeof shown[k]==='string'){ try{ shown[k]=JSON.parse(shown[k]); }catch{} } }
875
- INSPECTED=detail; // raw detail for the copy actions
876
- // Copy actions: JSON always; Body + cURL when this is a network call (has url/method).
877
- const isNet=(kind==='network')||detail.url!=null||detail.method!=null;
878
- let btns='<button class="copybtn" data-c="json">Copy JSON</button>';
879
- if(isNet) btns+='<button class="copybtn" data-c="body">Copy body</button><button class="copybtn" data-c="curl">Copy cURL</button>';
880
- insp.innerHTML='<div class="label">inspector — '+esc(ev.event_name||ev.event_type||shortUrl(ev.url)||'detail')+'</div><div class="copybar">'+btns+'</div><pre>'+esc(JSON.stringify(shown,null,2))+'</pre>';
881
- insp.querySelectorAll('.copybtn').forEach(b=>b.onclick=()=>copyInspected(b.dataset.c,b));
882
- }
883
- let INSPECTED=null;
884
- function copyInspected(kind,btn){ const d=INSPECTED||{}; let text='';
885
- if(kind==='json') text=JSON.stringify(d,null,2);
886
- else if(kind==='body') text=String(d.response_body??d.request_body??'');
887
- else if(kind==='curl') text=toCurl(d);
888
- navigator.clipboard?.writeText(text).then(()=>{ const o=btn.textContent; btn.textContent='copied ✓'; setTimeout(()=>btn.textContent=o,1200); }).catch(()=>{});
889
- }
890
- // Build a runnable curl from a captured network call. Headers + method + body if present.
891
- function toCurl(d){ if(!d.url) return ''; const parts=["curl -i"];
892
- if(d.method && d.method!=='GET') parts.push("-X "+d.method);
893
- const h=d.request_headers||d.requestHeaders||{};
894
- for(const k of Object.keys(h)) parts.push("-H "+shq(k+": "+h[k]));
895
- const body=d.request_body||d.requestBody; if(body) parts.push("--data "+shq(typeof body==='string'?body:JSON.stringify(body)));
896
- parts.push(shq(d.url));
897
- return parts.join(" \\\n ");
898
- }
899
- function shq(s){ return "'"+String(s).replace(/'/g,"'\\''")+"'"; }
900
- function appendExtract(row,val){ const s=document.createElement('span'); s.className='extract'; s.textContent=(SPEC.extract.label?SPEC.extract.label+': ':'')+val; row.appendChild(s); }
901
- // Escapes the five HTML-significant chars. Quotes are included because esc() output is
902
- // interpolated into double-quoted ATTRIBUTES (title="...", value="..."), not just text
903
- // content — a spec-authored title/value containing a quote would otherwise break out of the
904
- // attribute and inject an event handler (DOM-XSS with no < or > needed). All esc() call
905
- // sites in this file feed HTML, so escaping quotes is safe everywhere.
906
- function esc(s){ return String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
907
- // Human-readable one-line summary of a spec's actual filters + constraints, so every tab
908
- // (the Custom one especially) explains what it is showing rather than just "source=X".
909
- // Covers the fields the old "source=X match={}" line dropped: highlight, bodyContains,
910
- // alert, graph series, rate window. Returns a "·"-joined clause string.
911
- function describeConstraints(spec){
912
- const parts=['source '+spec.source];
913
- if(spec.match && Object.keys(spec.match).length)
914
- parts.push('where '+Object.entries(spec.match).map(([k,v])=>k+'='+v).join(', '));
915
- if(spec.bodyContains) parts.push('body contains "'+spec.bodyContains+'"');
916
- if(spec.highlight && spec.highlight.field)
917
- parts.push('flag '+spec.highlight.field+' '+(spec.highlight.op||'>')+' '+spec.highlight.value+(spec.highlight.label?' ('+spec.highlight.label+')':''));
918
- if(Array.isArray(spec.series) && spec.series.length)
919
- parts.push('graph '+spec.series.map(s=>s.label||s.metric+(s.field?' of '+s.field:'')).join(' vs '));
920
- if(spec.extract && spec.extract.field) parts.push('extract '+spec.extract.field);
921
- if(spec.alert){ const a=spec.alert; parts.push('alert'+(a.at?' at '+a.at:'')+(a.say?' "'+a.say+'"':'')); }
922
- if(spec.rateWindowSec) parts.push('rate window '+spec.rateWindowSec+'s');
923
- return parts.join(' · ');
924
- }
925
- function card(label,inner){ const d=document.createElement('div'); d.className='card'; d.innerHTML='<div class="label">'+label+'</div>'+inner; return d; }
926
- function big(v,id,unit){ return '<div class="big"><span id="'+id+'">'+v+'</span>'+(unit?'<span class="unit">'+unit+'</span>':'')+'</div>'; }
927
-
928
- // ---- DB browser view (source:"db"): db list -> tables -> read-only query grid ----
929
- let DBV={ db:null, user:null };
930
- // Build the ?user= suffix so every db call targets the profile the operator picked
931
- // (or the dashboard's bound profile). Keeps list / pull / query on the same store.
932
- function dbUserQS(){ return DBV.user!=null ? '&user='+encodeURIComponent(DBV.user) : ''; }
933
- async function buildDbView(spec){
934
- const dbsEl=document.getElementById('db_dbs'), tblsEl=document.getElementById('db_tbls');
935
- document.getElementById('db_run').onclick=dbRun;
936
- document.getElementById('db_sql').onkeydown=e=>{ if(e.key==='Enter') dbRun(); };
937
- tblsEl.innerHTML='<div class="msg">pick a database</div>';
938
- document.getElementById('db_out').innerHTML='<div class="msg">pick a database, then a table</div>';
939
- document.getElementById('db_meta').textContent='';
940
- dbsEl.innerHTML='<div class="msg">loading…</div>';
941
- await loadDbList(spec);
942
- }
943
- function profileLabel(u){ return u===''||u==null ? 'device' : (u==='0' ? 'personal (user 0)' : 'secondary (user '+esc(u)+')'); }
944
- async function loadDbList(spec){
945
- const dbsEl=document.getElementById('db_dbs');
946
- try{ const r=await (await fetch('/dbs?'+dbUserQS().slice(1))).json();
947
- if(r.error){ dbsEl.innerHTML='<div class="msg err">'+esc(r.error)+'</div>'; return; }
948
- if(!r.names||!r.names.length){ dbsEl.innerHTML='<div class="msg">no databases (device unreachable, or debug build not installed)</div>'; return; }
949
- DBV.user = r.user;
950
- // Which profile's store this is. With more than one profile, show ONLY a switcher
951
- // (the dropdown's selected option already names the profile — no redundant text line).
952
- // With a single profile, show it as plain text.
953
- const avail=r.availableUsers||[];
954
- let head;
955
- if(avail.length>1){
956
- head='<div class="dbprofile"><span class="dbprofcap">profile</span> <select id="db_userpick" title="which profile\'s on-device store to browse">'+
957
- avail.map(u=>'<option value="'+esc(u)+'"'+(u===r.user?' selected':'')+'>'+profileLabel(u)+'</option>').join('')+'</select></div>';
958
- } else {
959
- head='<div class="dbprofile">profile: <b>'+profileLabel(r.user)+'</b></div>';
960
- }
961
- dbsEl.innerHTML=head+r.names.map(n=>'<div class="dbitem" data-n="'+esc(n)+'">'+esc(n)+'</div>').join('');
962
- dbsEl.querySelectorAll('.dbitem').forEach(d=>d.onclick=()=>dbSelectDb(d.dataset.n,d));
963
- const pick=document.getElementById('db_userpick');
964
- if(pick) pick.onchange=()=>{ DBV.user=pick.value; DBV.db=null;
965
- document.getElementById('db_tbls').innerHTML='<div class="msg">pick a database</div>';
966
- document.getElementById('db_out').innerHTML='<div class="msg">pick a database, then a table</div>';
967
- document.getElementById('db_meta').textContent=''; loadDbList(spec); };
968
- if(spec&&spec.db){ const el=[...dbsEl.querySelectorAll('.dbitem')].find(x=>x.dataset.n===spec.db); if(el) dbSelectDb(spec.db,el,spec.table,spec.sql); }
969
- }catch(e){ dbsEl.innerHTML='<div class="msg err">'+esc(String(e))+'</div>'; }
970
- }
971
- async function dbSelectDb(name,el,wantTable,wantSql,refresh){ DBV.db=name;
972
- document.querySelectorAll('#db_dbs .dbitem').forEach(x=>x.classList.remove('sel')); if(el) el.classList.add('sel');
973
- // clear stale SQL/results so a leftover table query can't run against the newly-picked db
974
- document.getElementById('db_sql').value=''; document.getElementById('db_out').innerHTML='<div class="msg">pick a table or write a query</div>';
975
- const tblsEl=document.getElementById('db_tbls'); tblsEl.innerHTML='<div class="msg">'+(refresh?'re-pulling':'pulling')+' + reading…</div>';
976
- try{ const r=await (await fetch('/dbtables?db='+encodeURIComponent(name)+dbUserQS()+(refresh?'&refresh=1':''))).json();
977
- if(r.error){ tblsEl.innerHTML='<div class="msg err">'+esc(r.error)+'</div>'; return; }
978
- tblsEl.innerHTML=r.tables.map(t=>'<div class="dbitem" data-t="'+esc(t.name)+'">'+esc(t.name)+'<span class="rows">'+esc(String(t.rows))+'</span></div>').join('');
979
- tblsEl.querySelectorAll('.dbitem').forEach(d=>d.onclick=()=>dbSelectTbl(d.dataset.t,d));
980
- document.getElementById('db_meta').innerHTML=esc(name)+' — '+((r.sizeBytes/1024)|0)+' KB snapshot, '+r.tables.length+' tables · '+esc(profileLabel(DBV.user))+' <button class="dbrefresh" id="db_refresh" title="re-pull the latest from the device">↻ refresh</button>';
981
- const rb=document.getElementById('db_refresh'); if(rb) rb.onclick=()=>dbSelectDb(name,el,null,null,true);
982
- if(wantSql){ document.getElementById('db_sql').value=wantSql; dbRun(); }
983
- else if(wantTable){ const te=[...tblsEl.querySelectorAll('.dbitem')].find(x=>x.dataset.t===wantTable); if(te) dbSelectTbl(wantTable,te); }
984
- }catch(e){ tblsEl.innerHTML='<div class="msg err">'+esc(String(e))+'</div>'; }
985
- }
986
- function dbSelectTbl(t,el){ document.querySelectorAll('#db_tbls .dbitem').forEach(x=>x.classList.remove('sel')); if(el) el.classList.add('sel');
987
- document.getElementById('db_sql').value='SELECT * FROM "'+t+'" LIMIT 100'; dbRun(); }
988
- async function dbRun(){ if(!DBV.db) return; const sql=document.getElementById('db_sql').value;
989
- const out=document.getElementById('db_out'); out.innerHTML='<div class="msg">running…</div>';
990
- try{ const r=await (await fetch('/dbquery?db='+encodeURIComponent(DBV.db)+'&sql='+encodeURIComponent(sql)+dbUserQS())).json();
991
- if(r.error){ out.innerHTML='<div class="msg err">'+esc(r.error)+'</div>'; return; }
992
- if(!r.rows||!r.rows.length){ out.innerHTML='<div class="msg">0 rows</div>'; document.getElementById('db_meta').textContent=DBV.db+' — 0 rows'; return; }
993
- const cols=Object.keys(r.rows[0]);
994
- let h='<table><thead><tr>'+cols.map(c=>'<th>'+esc(c)+'</th>').join('')+'</tr></thead><tbody>';
995
- for(const row of r.rows){ h+='<tr>'+cols.map(c=>'<td title="'+esc(String(row[c]??''))+'">'+esc(String(row[c]??''))+'</td>').join('')+'</tr>'; }
996
- h+='</tbody></table>'; out.innerHTML=h;
997
- document.getElementById('db_meta').textContent=DBV.db+' — '+r.rows.length+' rows';
998
- }catch(e){ out.innerHTML='<div class="msg err">'+esc(String(e))+'</div>'; }
999
- }
1000
- // ---- Screen overlay: a global panel that mirrors the live device screen. -----
1001
- // OFF by default. The live screen shows real DMs and message content, so the panel
1002
- // opens to a consent gate first; only after the user accepts does it request frames.
1003
- // Consent is granted server-side (per process) and the stream/record routes enforce it.
1004
- const SCREEN={ on:false, consent:false, recording:false, caps:null };
1005
- function scCopy(text,btn){ navigator.clipboard?.writeText(text).then(()=>{ if(btn){ const t=btn.textContent; btn.textContent='copied'; setTimeout(()=>btn.textContent=t,1200); } }).catch(()=>{}); }
1006
- async function scLoadCaps(){ try{ SCREEN.caps=await (await fetch('/screen/caps')).json(); SCREEN.consent=!!SCREEN.caps.consent; }catch{ SCREEN.caps=null; } }
1007
- function scRenderConsent(){
1008
- const body=document.getElementById('screenbody'); const hint=document.getElementById('schint');
1009
- hint.textContent='';
1010
- body.innerHTML='<div class="scconsent">This mirrors the <b>live device screen</b>. It shows whatever is on the phone right now, including open DMs, message content, and notifications. Review what is on screen before sharing it. Frames are not requested until you accept, and the mirror stays on until you restart the dashboard. If you <b>record</b>, the clip is saved to a file on this computer (owner-only, removed when the dashboard restarts).<button class="scaccept" id="scaccept">Show the screen</button></div>';
1011
- document.getElementById('scaccept').onclick=async()=>{ try{ await fetch('/screen/consent',{method:'POST'}); SCREEN.consent=true; scRenderLive(); }catch{ hint.textContent='consent failed'; } };
1012
- }
1013
- function scRenderLive(){
1014
- const body=document.getElementById('screenbody'); const hint=document.getElementById('schint');
1015
- const caps=SCREEN.caps||{};
1016
- if(caps.liveCast){
1017
- body.innerHTML='<img id="screenimg" alt="device screen"/>';
1018
- document.getElementById('screenimg').src='/screen/stream?fps=20&t='+Date.now();
1019
- hint.textContent='capturing first frame (~3s on a foldable)…';
1020
- setTimeout(()=>{ if(SCREEN.on) hint.textContent='live. ▣ Screen again to close.'; },3500);
1021
- } else {
1022
- // No ffmpeg: live cast is unavailable. Screenshot still works (pure screencap).
1023
- // Show the platform install command (copy only — never auto-installed) + scrcpy hint.
1024
- const cmd=esc(caps.installHint||'install ffmpeg');
1025
- let html='<div class="scinstall">Live mirroring needs <b>ffmpeg</b>, which is not installed. Install it, then reopen this panel:<br><br><code>'+cmd+'</code><button class="sccopy" id="scffcopy">copy</button></div>';
1026
- html+='<div class="scinstall">📷 Screenshot works without ffmpeg — use the button above.</div>';
1027
- if(caps.scrcpy) html+='<div class="scinstall">scrcpy is installed; for a native mirror window run <code>scrcpy</code> in a terminal.</div>';
1028
- body.innerHTML=html;
1029
- const c=document.getElementById('scffcopy'); if(c) c.onclick=()=>scCopy(caps.installHint||'',c);
1030
- hint.textContent='live mirroring unavailable (no ffmpeg); screenshot still works.';
1031
- }
1032
- }
1033
- async function scOpen(){
1034
- SCREEN.on=true; document.getElementById('screenpanel').classList.add('on');
1035
- document.body.classList.add('screenopen'); document.getElementById('screenbtn').classList.add('on');
1036
- await scLoadCaps();
1037
- if(SCREEN.consent) scRenderLive(); else scRenderConsent();
1038
- }
1039
- function scClose(){
1040
- SCREEN.on=false; document.getElementById('screenpanel').classList.remove('on');
1041
- document.body.classList.remove('screenopen'); document.getElementById('screenbtn').classList.remove('on');
1042
- const img=document.getElementById('screenimg'); if(img) img.src=''; // drop the stream viewer
1043
- if(SCREEN.recording){ fetch('/screen/record/stop',{method:'POST'}).catch(()=>{}); SCREEN.recording=false; document.getElementById('screenrec').textContent='● rec'; }
1044
- }
1045
- document.getElementById('screenbtn').onclick=()=>{ SCREEN.on?scClose():scOpen(); };
1046
- document.getElementById('screenclose').onclick=scClose;
1047
- document.getElementById('screenshot').onclick=async()=>{
1048
- if(!SCREEN.consent){ document.getElementById('schint').textContent='accept the notice first'; return; }
1049
- // Blob download (not a bare <a href> navigation), so taking a screenshot cannot cancel
1050
- // the in-flight /screen/stream connection and drop the live <img>.
1051
- try{ const blob=await (await fetch('/screen/shot?t='+Date.now())).blob(); const u=URL.createObjectURL(blob);
1052
- const a=document.createElement('a'); a.href=u; a.download='radar-screen-'+Date.now()+'.png'; document.body.appendChild(a); a.click(); a.remove();
1053
- setTimeout(()=>URL.revokeObjectURL(u),10000);
1054
- }catch{ document.getElementById('schint').textContent='screenshot failed'; }
1055
- };
1056
- document.getElementById('screenrec').onclick=async()=>{
1057
- if(!SCREEN.consent || !(SCREEN.caps&&SCREEN.caps.liveCast)){ document.getElementById('schint').textContent='recording needs ffmpeg + consent'; return; }
1058
- const rec=document.getElementById('screenrec');
1059
- if(!SCREEN.recording){ SCREEN.recording=true; rec.textContent='■ stop'; rec.classList.add('rec'); await fetch('/screen/record/start',{method:'POST'}).catch(()=>{}); }
1060
- else { rec.textContent='saving…'; const r=await (await fetch('/screen/record/stop',{method:'POST'})).json().catch(()=>({})); SCREEN.recording=false; rec.classList.remove('rec'); rec.textContent='● rec';
1061
- if(r.download){
1062
- // Fetch the mp4 as a blob and download via an object URL. A bare <a href=/screen/download>
1063
- // click is a same-origin navigation that the browser can use to cancel the in-flight
1064
- // /screen/stream connection, which silently kills the live <img> (server keeps casting).
1065
- // A blob download touches no navigation and leaves the stream connection alone.
1066
- try{ const blob=await (await fetch(r.download)).blob(); const u=URL.createObjectURL(blob);
1067
- const a=document.createElement('a'); a.href=u; a.download=(r.file||'radar-screen.mp4'); document.body.appendChild(a); a.click(); a.remove();
1068
- setTimeout(()=>URL.revokeObjectURL(u),10000);
1069
- }catch{ document.getElementById('schint').textContent='recording saved on host: '+(r.file||''); }
1070
- // Belt-and-suspenders: re-arm the live <img> in case the browser still dropped it.
1071
- const img=document.getElementById('screenimg'); if(img) img.src='/screen/stream?fps=20&t='+Date.now();
1072
- } }
1073
- };
1074
- document.getElementById('screenredetect').onclick=async()=>{
1075
- document.getElementById('schint').textContent='re-detecting active panel…';
1076
- const r=await (await fetch('/screen/redetect')).json().catch(()=>({}));
1077
- if(SCREEN.on && SCREEN.consent && SCREEN.caps&&SCREEN.caps.liveCast){ const img=document.getElementById('screenimg'); if(img) img.src='/screen/stream?fps=20&t='+Date.now(); }
1078
- document.getElementById('schint').textContent='display: '+(r.display||'default');
1079
- };
1080
-
1081
- pollSpec(); // initial build
1082
- </script></body></html>
255
+ <div id="app"></div>
256
+ <script type="module" src="./next/app.js"></script>
257
+ </body></html>