@slack/radar-mcp 1.3.0 → 1.5.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.
@@ -1,729 +1,1082 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <title>Slack Radar</title>
6
- <style>
7
- * { box-sizing: border-box; }
8
- html, body {
9
- margin: 0;
10
- padding: 0;
11
- height: 100%;
12
- overflow: hidden;
13
- }
14
- body {
15
- font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", sans-serif;
16
- font-size: 13px;
17
- background: #ffffff;
18
- color: #1d1c1d;
19
- display: flex;
20
- flex-direction: column;
21
- }
22
- header {
23
- display: flex;
24
- align-items: center;
25
- gap: 12px;
26
- padding: 10px 16px;
27
- background: #f8f8f8;
28
- border-bottom: 1px solid #e0e0e0;
29
- }
30
- header h1 {
31
- margin: 0;
32
- font-size: 15px;
33
- font-weight: 600;
34
- color: #1d1c1d;
35
- }
36
- .badge {
37
- display: inline-flex;
38
- align-items: center;
39
- gap: 6px;
40
- font-size: 11px;
41
- color: #616061;
42
- padding: 3px 10px;
43
- background: #eeeeee;
44
- border-radius: 10px;
45
- }
46
- .status-dot {
47
- width: 8px;
48
- height: 8px;
49
- border-radius: 50%;
50
- background: #e01e5a;
51
- }
52
- .status-dot.connected { background: #2bac76; }
53
- .status-dot.paused { background: #de9f19; }
54
- .tabs {
55
- display: flex;
56
- background: #f8f8f8;
57
- border-bottom: 1px solid #e0e0e0;
58
- }
59
- .tab {
60
- padding: 10px 16px;
61
- cursor: pointer;
62
- color: #616061;
63
- border-bottom: 2px solid transparent;
64
- user-select: none;
65
- font-weight: 500;
66
- }
67
- .tab:hover { color: #1d1c1d; }
68
- .tab.active {
69
- color: #1d1c1d;
70
- border-bottom-color: #1264a3;
71
- }
72
- .tab .count {
73
- margin-left: 6px;
74
- font-size: 11px;
75
- color: #868686;
76
- }
77
- .toolbar {
78
- display: flex;
79
- gap: 8px;
80
- padding: 8px 16px;
81
- background: #ffffff;
82
- border-bottom: 1px solid #e0e0e0;
83
- align-items: center;
84
- }
85
- .toolbar input, .toolbar button, .toolbar select {
86
- padding: 6px 10px;
87
- border: 1px solid #d0d0d0;
88
- border-radius: 4px;
89
- background: #ffffff;
90
- color: #1d1c1d;
91
- font-size: 12px;
92
- font-family: inherit;
93
- }
94
- .toolbar input { flex: 1; }
95
- .toolbar input:focus { outline: none; border-color: #1264a3; }
96
- .toolbar button {
97
- cursor: pointer;
98
- user-select: none;
99
- }
100
- .toolbar button:hover { background: #f0f0f0; }
101
- .toolbar button.active { background: #1264a3; border-color: #1264a3; color: #fff; }
102
- .main {
103
- flex: 1;
104
- min-height: 0;
105
- display: flex;
106
- overflow: hidden;
107
- }
108
- .list {
109
- flex: 1;
110
- min-height: 0;
111
- overflow-y: auto;
112
- background: #ffffff;
113
- }
114
- .row {
115
- display: grid;
116
- grid-template-columns: 90px 60px 1fr 120px;
117
- gap: 12px;
118
- padding: 6px 16px;
119
- border-bottom: 1px solid #f0f0f0;
120
- cursor: pointer;
121
- font-family: "SF Mono", Menlo, monospace;
122
- font-size: 12px;
123
- align-items: center;
124
- }
125
- .row:hover { background: #f7f7f7; }
126
- .row.selected { background: #e3f1fa; }
127
- .row .time { color: #868686; }
128
- .row .status { text-align: right; color: #868686; }
129
- .row .status.ok { color: #2bac76; }
130
- .row .status.err { color: #e01e5a; }
131
- .row .status.warn { color: #de9f19; }
132
- .row .main-col { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
133
- .row .method, .row .direction {
134
- font-weight: 600;
135
- color: #616061;
136
- }
137
- .row .method.POST { color: #1264a3; }
138
- .row .method.GET { color: #2bac76; }
139
- .row .method.PUT { color: #de9f19; }
140
- .row .method.DELETE { color: #e01e5a; }
141
- .row .direction.IN { color: #2bac76; }
142
- .row .direction.OUT { color: #1264a3; }
143
- .detail {
144
- flex: 1;
145
- min-height: 0;
146
- overflow-y: auto;
147
- background: #fafafa;
148
- border-left: 1px solid #e0e0e0;
149
- padding: 16px;
150
- font-family: "SF Mono", Menlo, monospace;
151
- font-size: 12px;
152
- white-space: pre-wrap;
153
- word-break: break-word;
154
- color: #1d1c1d;
155
- }
156
- .detail .placeholder {
157
- color: #868686;
158
- font-family: inherit;
159
- font-style: italic;
160
- }
161
- .detail h3 {
162
- margin: 12px 0 6px 0;
163
- font-family: inherit;
164
- font-size: 12px;
165
- font-weight: 600;
166
- color: #616061;
167
- text-transform: uppercase;
168
- letter-spacing: 0.5px;
169
- }
170
- .detail h3:first-child { margin-top: 0; }
171
- .detail-actions {
172
- position: sticky;
173
- top: 0;
174
- background: #fafafa;
175
- padding: 4px 0 8px;
176
- z-index: 1;
177
- display: flex;
178
- gap: 6px;
179
- }
180
- .detail-actions button {
181
- font-size: 11px;
182
- padding: 3px 10px;
183
- cursor: pointer;
184
- background: #e8e8e8;
185
- border: 1px solid #ccc;
186
- border-radius: 4px;
187
- color: #333;
188
- }
189
- .detail-actions button:hover { background: #ddd; }
190
- .detail-actions button.copied { background: #2bac76; color: #fff; border-color: #2bac76; }
191
- .empty {
192
- padding: 40px 16px;
193
- text-align: center;
194
- color: #868686;
195
- }
196
- .marker {
197
- padding: 6px 16px;
198
- color: #868686;
199
- font-style: italic;
200
- font-size: 11px;
201
- text-align: center;
202
- border-top: 1px dashed #d0d0d0;
203
- border-bottom: 1px dashed #d0d0d0;
204
- background: #fafafa;
205
- }
206
- .tab-panel { display: none; flex: 1; flex-direction: column; overflow: hidden; }
207
- .tab-panel.active { display: flex; }
208
- </style>
209
- </head>
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"/>
3
+ <title>Slack Radar Dashboard</title>
4
+ <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; }
9
+ .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; }
28
+ .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") */
112
+ .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; }
116
+ .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; }
119
+ .dbmain { flex:1; min-width:0; display:flex; flex-direction:column; }
120
+ .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; }
133
+ .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; }
146
+ #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>
210
161
  <body>
211
- <header>
212
- <h1>Slack Radar</h1>
213
- <span class="badge"><span id="status-dot" class="status-dot"></span> <span id="status-text">connecting</span></span>
214
- <span class="badge" id="uptime-badge"></span>
215
- <button id="extend-btn" style="display: none; font-size: 11px; padding: 2px 8px; margin-left: 4px; cursor: pointer; background: #2bac76; color: #fff; border: none; border-radius: 10px;">Extend 5m</button>
216
- </header>
217
-
218
- <div class="tabs">
219
- <div class="tab active" data-tab="network">Network <span class="count" id="network-count">0</span></div>
220
- <div class="tab" data-tab="rtm">RTM <span class="count" id="rtm-count">0</span></div>
221
- <div class="tab" data-tab="clog">Clogs <span class="count" id="clog-count">0</span></div>
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>
222
175
  </div>
223
-
224
- <div class="toolbar">
225
- <input type="text" id="filter" placeholder="Filter by URL, channel, event name, payload..." />
226
- <span id="profile-label" style="display: none; font-size: 12px; color: #616061; margin-right: 4px;"></span>
227
- <button id="enable-btn" style="display: none;">Enable Radar</button>
228
- <button id="disconnect-btn" style="display: none;">Disconnect</button>
229
- <button id="pause-btn">Pause</button>
230
- <button id="clear-btn">Clear</button>
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>
231
197
  </div>
232
-
233
- <div class="main">
234
- <div class="list" id="list"></div>
235
- <div class="detail" id="detail">
236
- <div class="placeholder">Select a row to see the full payload.</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>
237
205
  </div>
238
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;
239
216
 
240
- <script>
241
- const state = {
242
- tab: "network",
243
- filter: "",
244
- paused: false,
245
- connected: false,
246
- hadConnection: false, // true once we've ever connected successfully
247
- selected: null, // { type, id }
248
- buffers: {
249
- network: [],
250
- rtm: [],
251
- clog: [],
252
- },
253
- MAX_BUFFER: 1000,
254
- };
255
-
256
- const listEl = document.getElementById("list");
257
- const detailEl = document.getElementById("detail");
258
- const filterEl = document.getElementById("filter");
259
- const enableBtn = document.getElementById("enable-btn");
260
- const profileLabel = document.getElementById("profile-label");
261
- const disconnectBtn = document.getElementById("disconnect-btn");
262
- const pauseBtn = document.getElementById("pause-btn");
263
- const clearBtn = document.getElementById("clear-btn");
264
- const statusDot = document.getElementById("status-dot");
265
- const statusText = document.getElementById("status-text");
266
- const uptimeBadge = document.getElementById("uptime-badge");
267
-
268
- // --- Tabs ---
269
- document.querySelectorAll(".tab").forEach((el) => {
270
- el.addEventListener("click", () => {
271
- state.tab = el.dataset.tab;
272
- document.querySelectorAll(".tab").forEach((t) => t.classList.toggle("active", t === el));
273
- state.selected = null;
274
- renderList();
275
- renderDetail();
276
- });
277
- });
278
-
279
- // --- Toolbar ---
280
- filterEl.addEventListener("input", () => {
281
- state.filter = filterEl.value.toLowerCase();
282
- renderList();
283
- });
284
-
285
- pauseBtn.addEventListener("click", () => {
286
- state.paused = !state.paused;
287
- pauseBtn.textContent = state.paused ? "Resume" : "Pause";
288
- pauseBtn.classList.toggle("active", state.paused);
289
- statusDot.classList.toggle("paused", state.paused);
290
- statusText.textContent = state.paused ? "paused" : (state.connected ? "connected" : "disconnected");
291
- });
292
-
293
- clearBtn.addEventListener("click", async () => {
294
- state.buffers.network = [];
295
- state.buffers.rtm = [];
296
- state.buffers.clog = [];
297
- state.selected = null;
298
- try {
299
- await fetch("/api/clear");
300
- } catch (e) {
301
- // Ignore — device may have shut down
302
- }
303
- updateCounts();
304
- renderList();
305
- renderDetail();
306
- });
307
-
308
- enableBtn.addEventListener("click", async () => {
309
- enableBtn.disabled = true;
310
- enableBtn.textContent = "Enabling…";
311
- try {
312
- const res = await fetch("/_control/activate", { method: "POST" });
313
- const data = await res.json();
314
- if (!data.ok) {
315
- statusText.textContent = "enable failed";
316
- alert(data.error || "Failed to enable radar");
317
- } else {
318
- statusText.textContent = "connecting";
319
- // Device-side server needs a moment to start after the broadcast.
320
- // Without this delay, the SSE connect races the server startup and
321
- // gets connection-refused, snapping back to disconnected instantly.
322
- await new Promise((r) => setTimeout(r, 1500));
323
- connectStream();
324
- return; // skip the finally reset — stay in "connecting" state
325
- }
326
- } catch (e) {
327
- alert("Failed to reach server: " + e.message);
328
- }
329
- enableBtn.disabled = false;
330
- enableBtn.textContent = "Enable Radar";
331
- });
332
-
333
- async function fetchProfiles() {
334
- try {
335
- const res = await fetch("/_control/profiles");
336
- const data = await res.json();
337
- const profiles = data.profiles || [];
338
- const activeId = data.active_user_id;
339
-
340
- if (activeId && profiles.length >= 1) {
341
- const active = profiles.find((p) => p.userId === activeId) ?? profiles[0];
342
- profileLabel.textContent = active.label;
343
- profileLabel.style.display = "";
344
- } else if (profiles.length >= 1) {
345
- profileLabel.textContent = profiles[0].label;
346
- profileLabel.style.display = "";
347
- } else {
348
- profileLabel.style.display = "none";
349
- }
350
- } catch {
351
- profileLabel.style.display = "none";
352
- }
353
- }
354
-
355
- function setDisconnectedUi(disconnected) {
356
- enableBtn.style.display = disconnected ? "" : "none";
357
- disconnectBtn.style.display = disconnected ? "none" : "";
358
- if (disconnected) {
359
- uptimeBadge.textContent = "";
360
- extendBtn.style.display = "none";
361
- }
362
- fetchProfiles();
363
- }
364
-
365
- disconnectBtn.addEventListener("click", () => {
366
- if (activeStream) {
367
- activeStream.close();
368
- activeStream = null;
369
- }
370
- state.connected = false;
371
- statusDot.classList.remove("connected");
372
- statusText.textContent = "disconnected";
373
- enableBtn.disabled = false;
374
- enableBtn.textContent = "Enable Radar";
375
- setDisconnectedUi(true);
376
- renderList();
377
- });
378
-
379
- // --- SSE ---
380
- function insertReconnectMarker() {
381
- const marker = {
382
- __marker: true,
383
- timestamp: Date.now(),
384
- label: `reconnected @ ${new Date().toLocaleTimeString("en-US", { hour12: false })}`,
385
- };
386
- const buffers = state.buffers;
387
- for (const type of ["network", "rtm", "clog"]) {
388
- const buf = buffers[type];
389
- if (buf.length > 0) buf.push({ ...marker }); // avoid empty-list markers
390
- }
391
- }
392
-
393
- let activeStream = null;
394
-
395
- function connectStream() {
396
- const es = new EventSource("/api/stream");
397
- activeStream = es;
398
- es.onopen = () => {
399
- const wasDisconnected = !state.connected && state.hadConnection;
400
- state.connected = true;
401
- state.hadConnection = true;
402
- if (wasDisconnected) insertReconnectMarker();
403
- statusDot.classList.add("connected");
404
- statusText.textContent = state.paused ? "paused" : "connected";
405
- setDisconnectedUi(false);
406
- renderList();
407
- };
408
- es.onmessage = (ev) => {
409
- if (state.paused) return;
410
- try {
411
- const parsed = JSON.parse(ev.data);
412
- ingest(parsed.type, parsed.event);
413
- } catch (e) {
414
- // Skip malformed
415
- }
416
- };
417
- es.onerror = () => {
418
- state.connected = false;
419
- statusDot.classList.remove("connected");
420
- statusText.textContent = "disconnected";
421
- enableBtn.disabled = false;
422
- enableBtn.textContent = "Enable Radar";
423
- setDisconnectedUi(true);
424
- renderList();
425
- es.close();
426
- };
427
- }
428
-
429
- function ingest(type, event) {
430
- // Attribute incoming events to whichever profile is currently active.
431
- // There is a small misattribution window right at a switch boundary
432
- // (a few events in flight may land in the wrong bucket), which is an
433
- // acceptable cost relative to server-side event tagging.
434
- const buffers = state.buffers;
435
- const buf = buffers[type];
436
- if (!buf) return;
437
- buf.push(event);
438
- if (buf.length > state.MAX_BUFFER) buf.shift();
439
- updateCounts();
440
- if (state.tab === type) renderList();
441
- }
442
-
443
- function updateCounts() {
444
- const buffers = state.buffers;
445
- document.getElementById("network-count").textContent = buffers.network.length;
446
- document.getElementById("rtm-count").textContent = buffers.rtm.length;
447
- document.getElementById("clog-count").textContent = buffers.clog.length;
448
- }
449
-
450
- // --- Rendering ---
451
- function filterRows(rows) {
452
- if (!state.filter) return rows;
453
- return rows.filter((r) => {
454
- if (r.__marker) return true; // always keep markers so history stays anchored
455
- return JSON.stringify(r).toLowerCase().includes(state.filter);
456
- });
457
- }
458
-
459
- function renderList() {
460
- const rows = filterRows(state.buffers[state.tab]);
461
- // Count real (non-marker) rows when deciding empty-state
462
- const nonMarkerCount = rows.filter((r) => !r.__marker).length;
463
- if (nonMarkerCount === 0) {
464
- let msg;
465
- if (state.filter) {
466
- msg = "No matches. Clear the filter or try a different query.";
467
- } else if (!state.connected) {
468
- msg = "Radar is not connected. Click Enable Radar in the toolbar to activate.";
469
- } else {
470
- msg = `No ${state.tab} events yet. Interact with the app to capture events.`;
471
- }
472
- listEl.innerHTML = `<div class="empty">${msg}</div>`;
473
- return;
474
- }
475
- // Newest first
476
- const html = rows.slice().reverse().map((row) => {
477
- if (row.__marker) return `<div class="marker">─── ${row.label} ───</div>`;
478
- return renderRow(state.tab, row);
479
- }).join("");
480
- listEl.innerHTML = html;
481
- listEl.querySelectorAll(".row").forEach((el) => {
482
- el.addEventListener("click", () => {
483
- const id = Number(el.dataset.id);
484
- state.selected = { type: state.tab, id };
485
- listEl.querySelectorAll(".row").forEach((r) => r.classList.toggle("selected", r === el));
486
- renderDetail();
487
- });
488
- });
489
- }
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;
490
221
 
491
- function renderRow(type, row) {
492
- const time = new Date(row.timestamp).toLocaleTimeString("en-US", { hour12: false });
493
- const selected = state.selected && state.selected.type === type && state.selected.id === row.id ? "selected" : "";
494
- if (type === "network") {
495
- const statusClass = row.status_code >= 500 ? "err" : row.status_code >= 400 ? "warn" : "ok";
496
- return `
497
- <div class="row ${selected}" data-id="${row.id}">
498
- <span class="time">${time}</span>
499
- <span class="method ${row.method}">${row.method}</span>
500
- <span class="main-col">${escapeHtml(row.url)}</span>
501
- <span class="status ${statusClass}">${row.status_code} · ${row.duration_ms}ms</span>
502
- </div>`;
503
- }
504
- if (type === "rtm") {
505
- return `
506
- <div class="row ${selected}" data-id="${row.id}">
507
- <span class="time">${time}</span>
508
- <span class="direction ${row.direction === "INCOMING" ? "IN" : "OUT"}">${row.direction === "INCOMING" ? "←" : "→"}</span>
509
- <span class="main-col">${escapeHtml(row.event_type ?? "(no type)")}${row.channel ? " · " + escapeHtml(row.channel) : ""}</span>
510
- <span class="status"></span>
511
- </div>`;
512
- }
513
- // clog
514
- return `
515
- <div class="row ${selected}" data-id="${row.id}">
516
- <span class="time">${time}</span>
517
- <span></span>
518
- <span class="main-col">${escapeHtml(row.event_name ?? "(unknown)")}</span>
519
- <span class="status"></span>
520
- </div>`;
521
- }
522
-
523
- let lastDetailData = null;
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();
524
267
 
525
- async function renderDetail() {
526
- if (!state.selected) {
527
- lastDetailData = null;
528
- detailEl.innerHTML = '<div class="placeholder">Select a row to see the full payload.</div>';
529
- return;
530
- }
531
- const { type, id } = state.selected;
532
- detailEl.innerHTML = '<div class="placeholder">Loading…</div>';
533
- try {
534
- const endpoint = type === "network" ? "/api/network/" : type === "rtm" ? "/api/rtm/" : "/api/clogs/";
535
- const res = await fetch(endpoint + id);
536
- const data = await res.json();
537
- lastDetailData = data;
538
- detailEl.innerHTML = detailActions() + formatDetail(type, data);
539
- wireDetailActions();
540
- } catch (e) {
541
- lastDetailData = null;
542
- detailEl.innerHTML = '<div class="placeholder">Failed to load detail: ' + escapeHtml(e.message) + '</div>';
543
- }
544
- }
545
-
546
- function detailActions() {
547
- const isNetwork = state.selected && state.selected.type === "network";
548
- return `<div class="detail-actions">
549
- <button id="copy-json-btn">Copy JSON</button>
550
- <button id="copy-body-btn">Copy Body</button>
551
- ${isNetwork ? '<button id="copy-curl-btn">Copy cURL</button>' : ''}
552
- </div>`;
553
- }
554
-
555
- function wireDetailActions() {
556
- const copyJsonBtn = document.getElementById("copy-json-btn");
557
- const copyBodyBtn = document.getElementById("copy-body-btn");
558
- if (copyJsonBtn) {
559
- copyJsonBtn.addEventListener("click", () => {
560
- if (!lastDetailData) return;
561
- navigator.clipboard.writeText(JSON.stringify(lastDetailData, null, 2));
562
- copyJsonBtn.textContent = "Copied!";
563
- copyJsonBtn.classList.add("copied");
564
- setTimeout(() => { copyJsonBtn.textContent = "Copy JSON"; copyJsonBtn.classList.remove("copied"); }, 1500);
565
- });
566
- }
567
- if (copyBodyBtn) {
568
- copyBodyBtn.addEventListener("click", () => {
569
- if (!lastDetailData) return;
570
- const body = lastDetailData.response_body ?? lastDetailData.data ?? lastDetailData.request_body ?? "";
571
- const text = tryPretty(body);
572
- navigator.clipboard.writeText(text);
573
- copyBodyBtn.textContent = "Copied!";
574
- copyBodyBtn.classList.add("copied");
575
- setTimeout(() => { copyBodyBtn.textContent = "Copy Body"; copyBodyBtn.classList.remove("copied"); }, 1500);
576
- });
577
- }
578
- const copyCurlBtn = document.getElementById("copy-curl-btn");
579
- if (copyCurlBtn) {
580
- copyCurlBtn.addEventListener("click", () => {
581
- if (!lastDetailData) return;
582
- navigator.clipboard.writeText(buildCurl(lastDetailData));
583
- copyCurlBtn.textContent = "Copied!";
584
- copyCurlBtn.classList.add("copied");
585
- setTimeout(() => { copyCurlBtn.textContent = "Copy cURL"; copyCurlBtn.classList.remove("copied"); }, 1500);
586
- });
587
- }
588
- }
589
-
590
- function shellEscape(s) {
591
- if (!s) return "''";
592
- return "'" + s.replace(/'/g, "'\\''") + "'";
593
- }
594
-
595
- function buildCurl(d) {
596
- const parts = [`curl -X ${d.method} ${shellEscape(d.url)}`];
597
- const headers = d.request_headers ?? {};
598
- let hasAuth = false;
599
- for (const [k, v] of Object.entries(headers)) {
600
- const lower = k.toLowerCase();
601
- if (lower === "accept-encoding" || lower === "host" || lower === "content-length") continue;
602
- if (lower === "authorization" || lower === "cookie") hasAuth = true;
603
- parts.push(` -H ${shellEscape(k + ": " + v)}`);
604
- }
605
- if (d.request_body) {
606
- parts.push(` --data-raw ${shellEscape(d.request_body)}`);
607
- }
608
- let cmd = parts.join(" \\\n");
609
- if (!hasAuth) {
610
- cmd += "\n# Note: auth cookies are injected by OkHttp after the app interceptor and are not captured. Add -b 'cookie=...' manually to replay.";
611
- }
612
- return cmd;
613
- }
614
-
615
- function formatDetail(type, data) {
616
- if (type === "network") {
617
- return `
618
- <h3>Request</h3>
619
- ${escapeHtml(data.method)} ${escapeHtml(data.url)}
620
-
621
- <h3>Request Headers</h3>
622
- ${escapeHtml(JSON.stringify(data.request_headers ?? {}, null, 2))}
623
-
624
- <h3>Request Body</h3>
625
- ${escapeHtml(data.request_body ?? "(none)")}
626
-
627
- <h3>Response · ${data.status_code} · ${data.duration_ms}ms</h3>
628
-
629
- <h3>Response Headers</h3>
630
- ${escapeHtml(JSON.stringify(data.response_headers ?? {}, null, 2))}
631
-
632
- <h3>Response Body</h3>
633
- ${escapeHtml(tryPretty(data.response_body))}
634
- `;
635
- }
636
- if (type === "rtm") {
637
- return `
638
- <h3>${escapeHtml(data.direction)} · ${escapeHtml(data.event_type ?? "(no type)")}</h3>
639
- Channel: ${escapeHtml(data.channel ?? "(none)")}
640
- Timestamp: ${new Date(data.timestamp).toISOString()}
641
- Base64: ${data.is_base64}
642
-
643
- <h3>Payload</h3>
644
- ${escapeHtml(tryPretty(data.data))}
645
- `;
646
- }
647
- // clog
648
- return `
649
- <h3>${escapeHtml(data.event_name)}</h3>
650
- Timestamp: ${new Date(data.timestamp).toISOString()}
651
-
652
- <h3>Payload</h3>
653
- ${escapeHtml(tryPretty(data.data))}
654
- `;
655
- }
656
-
657
- function tryPretty(s) {
658
- if (!s) return "(empty)";
659
- try {
660
- return JSON.stringify(JSON.parse(s), null, 2);
661
- } catch {
662
- return s;
663
- }
664
- }
665
-
666
- function escapeHtml(s) {
667
- return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
668
- }
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
+ });
669
315
 
670
- // --- Uptime ping ---
671
- const extendBtn = document.getElementById("extend-btn");
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);
672
357
 
673
- function formatUptime(ms) {
674
- const totalSec = Math.floor(ms / 1000);
675
- const h = Math.floor(totalSec / 3600);
676
- const m = Math.floor((totalSec % 3600) / 60);
677
- const s = totalSec % 60;
678
- if (h > 0) return `up ${h}h ${m}m`;
679
- if (m > 0) return `up ${m}m ${s}s`;
680
- return `up ${s}s`;
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'); }
681
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
+ }); }
682
453
 
683
- async function extendSession() {
684
- try {
685
- await fetch("/api/ping?timeout_minutes=5");
686
- } catch {}
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);
687
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; }
688
763
 
689
- extendBtn.addEventListener("click", async () => {
690
- extendBtn.disabled = true;
691
- extendBtn.textContent = "Extending…";
692
- await extendSession();
693
- await pollPing();
694
- extendBtn.disabled = false;
695
- extendBtn.textContent = "Extend 5m";
696
- });
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>'; }
697
927
 
698
- async function pollPing() {
699
- if (!state.connected) return;
700
- try {
701
- const res = await fetch("/api/ping");
702
- const data = await res.json();
703
- if (data.uptime_ms != null) {
704
- const remaining = data.remaining_minutes ?? 0;
705
- const timerLabel = remaining >= 4 ? "active" : `${remaining}m left`;
706
- uptimeBadge.textContent = `${formatUptime(data.uptime_ms)} · ${timerLabel}`;
707
- extendBtn.style.display = state.connected ? "" : "none";
708
- extendBtn.style.background = remaining < 4 ? "#de9f19" : "#2bac76";
709
- if (remaining <= 1 && state.connected) {
710
- await extendSession();
711
- }
712
- }
713
- } catch {
714
- uptimeBadge.textContent = "";
715
- extendBtn.style.display = "none";
716
- }
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>';
717
960
  }
718
- // pollPing runs on interval; skips when not connected.
719
- setInterval(pollPing, 5000);
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
+ };
720
1080
 
721
- // --- Go ---
722
- // Start in disconnected state. User picks a profile and clicks Enable.
723
- // connectStream() is called after Enable succeeds.
724
- setDisconnectedUi(true);
725
- updateCounts();
726
- renderList();
727
- </script>
728
- </body>
729
- </html>
1081
+ pollSpec(); // initial build
1082
+ </script></body></html>