dial9-viewer 0.3.13

CLI trace viewer and S3 browser for dial9-tokio-telemetry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>dial9 Trace Browser</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace;
            background: #1a1a2e; color: #e0e0e0;
            display: flex; flex-direction: column; height: 100vh;
        }
        header {
            padding: 12px 20px; background: #16213e;
            border-bottom: 1px solid #333; flex-shrink: 0;
            display: flex; align-items: center; gap: 12px;
        }
        header h1 { font-size: 1.1em; color: #6c63ff; }
        header span { font-size: 0.8em; color: #666; }
        header .spacer { flex: 1; }
        .controls {
            padding: 12px 20px; background: #16213e;
            border-bottom: 1px solid #333; flex-shrink: 0;
            display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
        }
        .controls label { font-size: 0.8em; color: #888; }
        .controls input[type="text"], .controls input[type="datetime-local"] {
            background: #2a2a4a; border: 1px solid #444; color: #e0e0e0;
            padding: 6px 10px; border-radius: 4px; font-size: 0.85em;
            font-family: inherit;
        }
        button {
            background: #2a2a4a; border: 1px solid #444; color: #ccc;
            padding: 6px 14px; border-radius: 4px; cursor: pointer;
            font-size: 0.85em; font-family: inherit;
        }
        button:hover { background: #3a3a5a; }
        button:disabled { opacity: 0.4; cursor: not-allowed; }
        button.primary { background: #6c63ff; border-color: #6c63ff; color: #fff; }
        button.primary:hover { background: #5a52e0; }
        button.primary:disabled { background: #4a4a6a; border-color: #4a4a6a; }
        button.active { background: #6c63ff; border-color: #6c63ff; color: #fff; }
        .quick-btns { display: flex; gap: 4px; }
        .quick-btns button.selected { background: #6c63ff; border-color: #6c63ff; color: #fff; }
        .main-area { flex: 1; overflow-y: auto; padding: 0; display: flex; flex-direction: column; }
        .status { padding: 40px; text-align: center; color: #666; font-size: 0.9em; }
        .status.error { color: #ff6b6b; }

        /* Tab bar */
        .tab-bar {
            display: flex; gap: 0; border-bottom: 1px solid #333;
            padding: 0 20px; background: #16213e; flex-shrink: 0;
        }
        .tab-bar button {
            border: none; border-bottom: 2px solid transparent;
            border-radius: 0; padding: 8px 16px; font-size: 0.85em;
            background: transparent; color: #888;
        }
        .tab-bar button:hover { color: #ccc; background: transparent; }
        .tab-bar button.active { color: #6c63ff; border-bottom-color: #6c63ff; background: transparent; }

        /* Host picker */
        .host-grid {
            display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 12px; padding: 20px;
        }
        .host-card {
            background: #222244; border: 1px solid #333; border-radius: 6px;
            padding: 14px; cursor: pointer; transition: border-color 0.15s;
        }
        .host-card:hover { border-color: #6c63ff; }
        .host-card.selected { border-color: #6c63ff; background: #2a2a5a; }
        .host-card .svc { color: #7ec8e3; font-size: 0.85em; margin-bottom: 2px; }
        .host-card .hostname { font-size: 1em; font-weight: 600; }
        .host-card .meta { font-size: 0.8em; color: #888; margin-top: 6px; }

        /* Segment list */
        .segment-panel { padding: 12px 20px; flex: 1; overflow-y: auto; }
        .segment-panel .back-link {
            font-size: 0.85em; color: #6c63ff; cursor: pointer;
            margin-bottom: 10px; display: inline-block;
        }
        .segment-panel .back-link:hover { text-decoration: underline; }
        .segment-panel h3 { font-size: 0.95em; margin-bottom: 8px; }
        table { width: 100%; border-collapse: collapse; font-size: 0.85em; }
        thead th {
            position: sticky; top: 0; background: #1a1a2e;
            text-align: left; padding: 8px 6px; color: #888;
            border-bottom: 1px solid #333; font-weight: 600;
            cursor: pointer; user-select: none;
        }
        thead th:hover { color: #bbb; }
        thead th .sort-arrow { font-size: 0.7em; margin-left: 3px; }
        tbody tr { border-bottom: 1px solid #222; }
        tbody tr:hover { background: #222244; }
        tbody td { padding: 6px; white-space: nowrap; }
        td.size, td.date { color: #aaa; }
        td.service { color: #7ec8e3; }
        td.host { color: #aaa; font-size: 0.8em; }
        td input[type="checkbox"] { accent-color: #6c63ff; }

        .actions {
            padding: 8px 20px; background: #16213e;
            border-top: 1px solid #333; flex-shrink: 0;
            display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
        }
        .actions .count { font-size: 0.8em; color: #888; margin-left: auto; }
        footer {
            padding: 6px 20px; font-size: 0.75em; color: #444;
            border-top: 1px solid #222; flex-shrink: 0;
        }
        footer a { color: #6c63ff; text-decoration: none; }
    </style>
</head>
<body>
    <header>
        <h1>dial9 Trace Browser</h1>
        <span>search &amp; view traces from S3</span>
        <span class="spacer"></span>
        <button id="tz-btn" title="Toggle between UTC and local timezone">TZ: UTC</button>
    </header>

    <div class="controls">
        <label>Bucket:</label>
        <input type="text" id="bucket-input" placeholder="my-trace-bucket" style="width:180px" />
        <label>Prefix:</label>
        <input type="text" id="prefix-input" placeholder="detecting…" style="width:120px" />
        <span id="prefix-suggestions" style="display:inline-flex;gap:4px"></span>
        <span style="color:#444">|</span>
        <div class="quick-btns">
            <button onclick="setQuickRange(1)">Last 1hr</button>
            <button onclick="setQuickRange(3)">Last 3hr</button>
            <button onclick="setQuickRange(24)">Last 24hr</button>
        </div>
        <label>From:</label>
        <input type="datetime-local" id="range-from" step="60" />
        <label>To:</label>
        <input type="datetime-local" id="range-to" step="60" />
        <button class="primary" id="search-btn" onclick="doTimeRangeSearch()" disabled>Search</button>
    </div>

    <div class="tab-bar">
        <button class="active" onclick="switchTab('browse')" id="tab-browse">Browse</button>
        <button onclick="switchTab('raw')" id="tab-raw">Raw Search</button>
    </div>

    <div class="main-area" id="main-area">
        <!-- Browse mode: status / host grid / segment list -->
        <div id="browse-view">
            <div class="status" id="browse-status">
                Select a time range and click Search to find traces.
            </div>
            <div class="host-grid" id="host-grid" style="display:none"></div>
            <div class="segment-panel" id="segment-panel" style="display:none"></div>
        </div>

        <!-- Raw search mode (hidden by default) -->
        <div id="raw-view" style="display:none">
            <div style="padding:12px 20px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                <label style="font-size:0.8em;color:#888">Prefix:</label>
                <input type="text" id="raw-search-input"
                       placeholder="e.g. 2026-04-09/1910/checkout-api"
                       style="flex:1;min-width:200px;background:#2a2a4a;border:1px solid #444;color:#e0e0e0;padding:6px 10px;border-radius:4px;font-size:0.85em;font-family:inherit" />
                <button onclick="doRawSearch()">Search</button>
            </div>
            <div class="status" id="raw-status">Enter a prefix and search.</div>
            <div style="padding:0 20px;flex:1;overflow-y:auto">
                <table id="raw-table" style="display:none">
                    <thead>
                        <tr>
                            <th style="width:30px"><input type="checkbox" id="raw-select-all" /></th>
                            <th data-sort="service">Service</th>
                            <th data-sort="host">Host</th>
                            <th data-sort="bootId">Boot</th>
                            <th data-sort="traceStart">Trace Start</th>
                            <th data-sort="segIndex">Seg #</th>
                            <th data-sort="size">Size</th>
                            <th data-sort="last_modified">Uploaded</th>
                        </tr>
                    </thead>
                    <tbody id="raw-body"></tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="actions" id="actions-bar">
        <button onclick="rawSelectAll(true)">Select All</button>
        <button onclick="rawSelectAll(false)">Deselect All</button>
        <button class="primary" id="view-btn" onclick="viewSelected()" disabled>
            View Selected in Trace Viewer
        </button>
        <span class="count" id="selection-count"></span>
    </div>

    <footer id="footer-drop"
        style="padding:10px 20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;border:2px dashed transparent;transition:border-color 0.2s">
        <a href="viewer.html">Open Trace Viewer</a>
        <span style="color:#333">|</span>
        <button class="primary" id="load-demo-btn" style="padding:4px 12px;font-size:0.8em">Load demo trace</button>
        <span style="color:#555;font-size:0.8em;margin-left:auto">drop a .bin file to open viewer</span>
    </footer>

    <script>
    // ── ?trace= passthrough: redirect to viewer ──
    (function() {
        const t = new URLSearchParams(window.location.search).get('trace');
        if (t) { window.location.replace('viewer.html?trace=' + encodeURIComponent(t)); return; }
    })();

    // ── Demo trace button ──
    document.getElementById('load-demo-btn').addEventListener('click', () => {
        window.open('viewer.html?trace=demo-trace.bin', '_blank');
    });
    // ── Global drag-and-drop → open viewer ──
    const footerDrop = document.getElementById('footer-drop');
    document.body.addEventListener('dragover', (e) => { e.preventDefault(); footerDrop.style.borderColor = '#6c63ff'; });
    document.body.addEventListener('dragleave', (e) => {
        if (!e.relatedTarget || !document.body.contains(e.relatedTarget)) footerDrop.style.borderColor = 'transparent';
    });
    document.body.addEventListener('drop', (e) => {
        e.preventDefault(); footerDrop.style.borderColor = 'transparent';
        const file = e.dataTransfer.files[0];
        if (file) {
            const url = URL.createObjectURL(file);
            window.open('viewer.html?trace=' + encodeURIComponent(url), '_blank');
        }
    });
    // ── State ──
    let useLocalTz = false;
    let allObjects = [];       // all objects from time-range search
    let hostGroups = {};       // { "service/host": [objects] }
    let selectedHost = null;   // currently selected host key
    let rawObjects = [];       // raw search results
    let currentTab = 'browse';

    const bucketInput = document.getElementById('bucket-input');
    const browseStatus = document.getElementById('browse-status');
    const hostGrid = document.getElementById('host-grid');
    const segmentPanel = document.getElementById('segment-panel');

    // ── Init: load config ──
    const params = new URLSearchParams(window.location.search);
    if (params.get('bucket')) bucketInput.value = params.get('bucket');

    const prefixInput = document.getElementById('prefix-input');
    let serverHasPrefix = false;

    function updateSearchReady() {
        const waitingForPrefix = serverHasPrefix && prefixInput.value.trim() === '';
        document.getElementById('search-btn').disabled = waitingForPrefix;
    }
    prefixInput.addEventListener('input', updateSearchReady);

    fetch('/api/config').then(async r => {
        if (!r.ok) {
            const body = await r.text().catch(() => '');
            throw new Error(`HTTP ${r.status}${body ? ': ' + body : ''}`);
        }
        return r.json();
    }).then(config => {
        if (!bucketInput.value && config.default_bucket) bucketInput.value = config.default_bucket;
        if (config.default_prefix) {
            prefixInput.value = config.default_prefix;
            serverHasPrefix = true;
            updateSearchReady();
        }
        discoverPrefixes();
    }).catch(() => { discoverPrefixes(); });

    // Default to last 1 hour
    setQuickRange(1);

    // ── Auto-discover prefixes ──
    async function discoverPrefixes() {
        const bucket = bucketInput.value.trim();
        if (!bucket) { prefixInput.placeholder = 'e.g. traces'; updateSearchReady(); return; }
        try {
            const resp = await fetch(`/api/prefixes?bucket=${encodeURIComponent(bucket)}`);
            if (!resp.ok) {
                const body = await resp.text().catch(() => '');
                console.warn(`prefix discovery failed: HTTP ${resp.status}${body ? ': ' + body : ''}`);
                prefixInput.placeholder = 'discovery failed — enter manually';
                updateSearchReady();
                return;
            }
            const prefixes = await resp.json();
            const suggestions = document.getElementById('prefix-suggestions');
            suggestions.innerHTML = '';
            if (prefixes.length === 0) {
                prefixInput.placeholder = '(none found)';
                updateSearchReady();
                return;
            }
            // If there's exactly one prefix and the input is empty, auto-select it
            if (prefixes.length === 1 && !prefixInput.value) {
                prefixInput.value = prefixes[0].replace(/\/$/, '');
            }
            prefixInput.placeholder = 'e.g. traces';
            for (const p of prefixes) {
                const label = p.replace(/\/$/, '');
                const btn = document.createElement('button');
                btn.textContent = label;
                btn.style.cssText = 'font-size:0.75em;padding:2px 8px';
                btn.addEventListener('click', () => {
                    prefixInput.value = label;
                    suggestions.querySelectorAll('button').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    updateSearchReady();
                });
                if (prefixInput.value === label) btn.classList.add('active');
                suggestions.appendChild(btn);
            }
            updateSearchReady();
        } catch {
            prefixInput.placeholder = 'discovery failed — enter manually';
            updateSearchReady();
        }
    }

    // Re-discover when bucket changes
    bucketInput.addEventListener('change', discoverPrefixes);

    // ── Timezone toggle ──
    document.getElementById('tz-btn').addEventListener('click', () => {
        // Read current picker values in the OLD tz mode before toggling
        const fromDate = pickerToDate(document.getElementById('range-from').value);
        const toDate = pickerToDate(document.getElementById('range-to').value);

        useLocalTz = !useLocalTz;
        document.getElementById('tz-btn').textContent = useLocalTz ? 'TZ: Local' : 'TZ: UTC';

        // Re-write picker values in the NEW tz mode
        if (fromDate) document.getElementById('range-from').value = dateToPickerStr(fromDate);
        if (toDate) document.getElementById('range-to').value = dateToPickerStr(toDate);

        // Re-render current view
        if (currentTab === 'browse') {
            if (selectedHost) showSegments(selectedHost);
            else if (Object.keys(hostGroups).length) renderHostGrid();
        } else {
            renderRawTable(rawObjects);
        }
    });

    // ── Helpers ──
    function esc(s) {
        const d = document.createElement('div');
        d.textContent = s;
        return d.innerHTML.replace(/"/g, '&quot;');
    }

    function formatSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }

    function formatDate(dateStr) {
        if (!dateStr) return '';
        try {
            const d = new Date(dateStr);
            if (useLocalTz) {
                const pad = n => String(n).padStart(2, '0');
                return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) +
                    ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
            }
            return d.toISOString().replace('T', ' ').slice(0, 19);
        } catch { return dateStr; }
    }

    function formatEpoch(epoch) {
        if (!epoch) return '';
        return formatDate(new Date(epoch * 1000).toISOString());
    }

    function parseKey(key) {
        // Default layout (as of issue #225):
        //   {prefix}/{YYYY-MM-DD}/{HHMM}/{service}/{instance}/{boot_id}/{epoch}-{index}.bin[.gz]
        // Legacy layout (pre-#225):
        //   {prefix}/{YYYY-MM-DD}/{HHMM}/{service}/{instance}/{epoch}-{index}.bin[.gz]
        // We find the date-shaped segment and count components between it
        // and the filename to distinguish. Custom instance paths containing
        // slashes will fall back to best-effort positional parsing.
        const parts = key.split('/');
        const dateRe = /^\d{4}-\d{2}-\d{2}$/;
        let dateIdx = -1;
        for (let i = parts.length - 1; i >= 0; i--) {
            if (dateRe.test(parts[i])) { dateIdx = i; break; }
        }
        const file = parts[parts.length - 1];
        const match = file.match(/^(\d+)-(\d+)\.bin/);
        let epoch = 0, segIndex = '';
        if (match) {
            epoch = parseInt(match[1], 10);
            segIndex = match[2];
        }
        if (dateIdx >= 0) {
            const below = parts.length - 1 - dateIdx; // count after date, not including date itself
            if (below === 5) {
                return {
                    service: parts[dateIdx + 2],
                    host: parts[dateIdx + 3],
                    bootId: parts[dateIdx + 4],
                    epoch, segIndex,
                    get traceStart() { return formatEpoch(epoch); },
                };
            }
            if (below === 4) {
                return {
                    service: parts[dateIdx + 2],
                    host: parts[dateIdx + 3],
                    bootId: '',
                    epoch, segIndex,
                    get traceStart() { return formatEpoch(epoch); },
                };
            }
        }
        // Fallback — positional, best-effort.
        if (parts.length >= 5) {
            return {
                service: parts[parts.length - 3],
                host: parts[parts.length - 2],
                bootId: '',
                epoch, segIndex,
                get traceStart() { return formatEpoch(epoch); },
            };
        }
        return { service: '', host: key, bootId: '', epoch: 0, segIndex: '', get traceStart() { return ''; } };
    }

    function toLocalDatetime(d) {
        const pad = n => String(n).padStart(2, '0');
        return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) +
            'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
    }

    function toUTCDatetime(d) {
        const pad = n => String(n).padStart(2, '0');
        return d.getUTCFullYear() + '-' + pad(d.getUTCMonth()+1) + '-' + pad(d.getUTCDate()) +
            'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes());
    }

    /** Format a Date for the datetime-local picker in the current TZ mode */
    function dateToPickerStr(d) {
        return useLocalTz ? toLocalDatetime(d) : toUTCDatetime(d);
    }

    /** Parse a datetime-local picker value into a Date using the current TZ mode */
    function pickerToDate(str) {
        if (!str) return null;
        if (useLocalTz) return new Date(str);
        // Treat the picker value as UTC
        return new Date(str + 'Z');
    }

    // ── Quick range buttons ──
    function setQuickRange(hours) {
        const now = new Date();
        const from = new Date(now.getTime() - hours * 3600 * 1000);
        document.getElementById('range-from').value = dateToPickerStr(from);
        document.getElementById('range-to').value = dateToPickerStr(now);
        // Highlight the selected quick button
        document.querySelectorAll('.quick-btns button').forEach(b => b.classList.remove('selected'));
        const labels = {'1': 'Last 1hr', '3': 'Last 3hr', '24': 'Last 24hr'};
        document.querySelectorAll('.quick-btns button').forEach(b => {
            if (b.textContent === labels[hours]) b.classList.add('selected');
        });
    }

    // Clear quick-button highlight when user manually edits the range
    document.getElementById('range-from').addEventListener('input', () => {
        document.querySelectorAll('.quick-btns button').forEach(b => b.classList.remove('selected'));
    });
    document.getElementById('range-to').addEventListener('input', () => {
        document.querySelectorAll('.quick-btns button').forEach(b => b.classList.remove('selected'));
    });

    // ── Tab switching ──
    function switchTab(tab) {
        currentTab = tab;
        document.getElementById('tab-browse').classList.toggle('active', tab === 'browse');
        document.getElementById('tab-raw').classList.toggle('active', tab === 'raw');
        document.getElementById('browse-view').style.display = tab === 'browse' ? '' : 'none';
        document.getElementById('raw-view').style.display = tab === 'raw' ? '' : 'none';
        updateSelectionCount();
    }

    // ── Generate hour-level prefixes for a time range ──
    function hourPrefixes(from, to) {
        const prefixes = [];
        // Start at the beginning of `from`'s hour (UTC — S3 keys use UTC)
        const cur = new Date(from);
        cur.setUTCMinutes(0, 0, 0);
        while (cur <= to) {
            const pad = n => String(n).padStart(2, '0');
            const dateStr = cur.getUTCFullYear() + '-' + pad(cur.getUTCMonth()+1) + '-' + pad(cur.getUTCDate());
            const hourStr = pad(cur.getUTCHours());
            prefixes.push(dateStr + '/' + hourStr);
            cur.setTime(cur.getTime() + 3600 * 1000);
        }
        return prefixes;
    }

    // ── Time-range search (Browse mode) ──
    async function doTimeRangeSearch() {
        const bucket = bucketInput.value.trim();
        if (!bucket) { alert('Bucket is required'); return; }

        const fromStr = document.getElementById('range-from').value;
        const toStr = document.getElementById('range-to').value;
        if (!fromStr || !toStr) { alert('Select a time range'); return; }

        const from = pickerToDate(fromStr);
        const to = pickerToDate(toStr);
        const keyPrefix = !serverHasPrefix ? prefixInput.value.trim() : '';
        const prefixes = hourPrefixes(from, to).map(
            p => keyPrefix ? keyPrefix + '/' + p : p
        );

        browseStatus.textContent = `Searching ${prefixes.length} hour(s)`;
        browseStatus.className = 'status';
        browseStatus.style.display = '';
        hostGrid.style.display = 'none';
        segmentPanel.style.display = 'none';
        selectedHost = null;

        try {
            // Fire parallel queries for each hour prefix
            const fetches = prefixes.map(p => {
                const url = `/api/search?bucket=${encodeURIComponent(bucket)}&q=${encodeURIComponent(p)}`;
                return fetch(url).then(async r => {
                    if (!r.ok) {
                        const body = await r.text().catch(() => '');
                        throw new Error(`HTTP ${r.status}${body ? ': ' + body : ''}`);
                    }
                    return r.json();
                });
            });
            const results = await Promise.all(fetches);
            allObjects = results.flat();

            // Filter to objects whose epoch falls within the actual range
            const fromEpoch = from.getTime() / 1000;
            const toEpoch = to.getTime() / 1000;
            allObjects = allObjects.filter(obj => {
                const p = parseKey(obj.key);
                if (!p.epoch) return true; // keep if we can't parse
                // Include if segment overlaps the range (use last_modified as end proxy)
                const end = obj.last_modified ? new Date(obj.last_modified).getTime() / 1000 : p.epoch;
                return p.epoch <= toEpoch && end >= fromEpoch;
            });

            if (allObjects.length === 0) {
                browseStatus.className = 'status';
                hostGroups = {};
                // Show sample keys to help the user understand the bucket layout
                try {
                    const sampleResp = await fetch(`/api/search?bucket=${encodeURIComponent(bucket)}&q=`);
                    const samples = sampleResp.ok ? await sampleResp.json() : [];
                    if (samples.length > 0) {
                        browseStatus.innerHTML = 'No traces found in this time range. Sample keys in this bucket:<br>' +
                            samples.slice(0, 5).map(o => `<code style="color:#7ec8e3;font-size:0.85em">${esc(o.key)}</code>`).join('<br>');
                    } else {
                        browseStatus.textContent = 'No traces found in this time range. Bucket appears empty.';
                    }
                } catch {
                    browseStatus.textContent = 'No traces found in this time range.';
                }
                return;
            }

            // Group by service/host[/boot]. A new boot_id indicates a
            // separate process run — keeping runs distinct prevents
            // segment-index duplicates when a service restarts.
            hostGroups = {};
            for (const obj of allObjects) {
                const p = parseKey(obj.key);
                const groupKey = p.bootId
                    ? p.service + '/' + p.host + '/' + p.bootId
                    : p.service + '/' + p.host;
                if (!hostGroups[groupKey]) hostGroups[groupKey] = { service: p.service, host: p.host, bootId: p.bootId, objects: [] };
                hostGroups[groupKey].objects.push(obj);
            }

            browseStatus.style.display = 'none';
            renderHostGrid();
        } catch (err) {
            browseStatus.textContent = 'Error: ' + err.message;
            browseStatus.className = 'status error';
        }
    }

    // ── Host grid ──
    function renderHostGrid() {
        hostGrid.innerHTML = '';
        hostGrid.style.display = '';
        segmentPanel.style.display = 'none';
        selectedHost = null;

        const groups = Object.values(hostGroups).sort((a, b) =>
            ((a.service + a.host + (a.bootId || '')).localeCompare(b.service + b.host + (b.bootId || ''))));

        for (const g of groups) {
            const epochs = g.objects.map(o => parseKey(o.key).epoch).filter(e => e > 0);
            const minEpoch = epochs.length ? Math.min(...epochs) : 0;
            const endTimes = g.objects.map(o => o.last_modified ? new Date(o.last_modified).getTime() / 1000 : 0).filter(e => e > 0);
            const maxEnd = endTimes.length ? Math.max(...endTimes) : 0;
            const totalSize = g.objects.reduce((s, o) => s + o.size, 0);

            const bootLine = g.bootId ? `<div class="meta" style="font-size:0.75em;color:#7a7ab0">boot ${esc(g.bootId)}</div>` : '';
            const card = document.createElement('div');
            card.className = 'host-card';
            card.innerHTML = `
                <div class="svc">${esc(g.service)}</div>
                <div class="hostname">${esc(g.host)}</div>
                ${bootLine}
                <div class="meta">
                    ${g.objects.length} segment${g.objects.length !== 1 ? 's' : ''} · ${formatSize(totalSize)}<br>
                    ${formatEpoch(minEpoch)}${maxEnd ? '' + formatEpoch(maxEnd) : ''}
                </div>
            `;
            const gk = g.bootId ? g.service + '/' + g.host + '/' + g.bootId : g.service + '/' + g.host;
            card.addEventListener('click', () => showSegments(gk));
            hostGrid.appendChild(card);
        }
    }

    // ── Segment list for a selected host ──
    function showSegments(groupKey) {
        selectedHost = groupKey;
        hostGrid.style.display = 'none';
        segmentPanel.style.display = '';

        const g = hostGroups[groupKey];
        if (!g) return;

        // Sort segments by epoch
        const sorted = [...g.objects].sort((a, b) => parseKey(a.key).epoch - parseKey(b.key).epoch);

        segmentPanel.innerHTML = `
            <span class="back-link" onclick="renderHostGrid()"> Back to hosts</span>
            <h3>${esc(g.service)} / ${esc(g.host)}${g.bootId ? ' <span style="color:#7a7ab0;font-weight:400;font-size:0.85em">(boot ' + esc(g.bootId) + ')</span>' : ''}</h3>
            <div style="margin-bottom:8px;display:flex;gap:8px;align-items:center">
                <button onclick="segSelectAll(true)">Select All</button>
                <button onclick="segSelectAll(false)">Deselect All</button>
                <button class="primary" onclick="viewSelected()" id="seg-view-btn">
                    View Selected in Trace Viewer
                </button>
                <span class="count" id="seg-count"></span>
            </div>
            <table>
                <thead>
                    <tr>
                        <th style="width:30px"><input type="checkbox" id="seg-select-all" checked /></th>
                        <th>Trace Start</th>
                        <th>Seg #</th>
                        <th>Size</th>
                        <th>Uploaded</th>
                    </tr>
                </thead>
                <tbody id="seg-body"></tbody>
            </table>
        `;

        const tbody = document.getElementById('seg-body');
        for (const obj of sorted) {
            const p = parseKey(obj.key);
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input type="checkbox" class="seg-cb" data-key="${esc(obj.key)}" checked /></td>
                <td>${esc(p.traceStart)}</td>
                <td>${esc(p.segIndex)}</td>
                <td class="size">${formatSize(obj.size)}</td>
                <td class="date">${formatDate(obj.last_modified)}</td>
            `;
            tr.querySelector('.seg-cb').addEventListener('change', updateSegCount);
            tbody.appendChild(tr);
        }

        document.getElementById('seg-select-all').addEventListener('change', (e) => {
            segSelectAll(e.target.checked);
        });
        updateSegCount();
    }

    function segSelectAll(checked) {
        document.querySelectorAll('.seg-cb').forEach(cb => { cb.checked = checked; });
        const sa = document.getElementById('seg-select-all');
        if (sa) sa.checked = checked;
        updateSegCount();
    }

    function updateSegCount() {
        const keys = getSegSelectedKeys();
        const el = document.getElementById('seg-count');
        if (el) el.textContent = keys.length ? `${keys.length} selected` : '';
    }

    function getSegSelectedKeys() {
        return Array.from(document.querySelectorAll('.seg-cb:checked')).map(cb => cb.dataset.key);
    }

    // ── Raw search mode ──
    async function doRawSearch() {
        const bucket = bucketInput.value.trim();
        if (!bucket) { alert('Bucket is required'); return; }

        const q = document.getElementById('raw-search-input').value.trim();
        const url = `/api/search?bucket=${encodeURIComponent(bucket)}&q=${encodeURIComponent(q)}`;

        const rawStatus = document.getElementById('raw-status');
        rawStatus.textContent = 'Searching…';
        rawStatus.className = 'status';
        rawStatus.style.display = '';
        document.getElementById('raw-table').style.display = 'none';

        try {
            const resp = await fetch(url);
            if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
            rawObjects = await resp.json();
            renderRawTable(rawObjects);
        } catch (err) {
            rawStatus.textContent = 'Error: ' + err.message;
            rawStatus.className = 'status error';
        }
    }

    document.getElementById('raw-search-input').addEventListener('keydown', (e) => {
        if (e.key === 'Enter') doRawSearch();
    });

    async function renderRawTable(objects) {
        const rawStatus = document.getElementById('raw-status');
        const rawTable = document.getElementById('raw-table');
        const rawBody = document.getElementById('raw-body');
        rawBody.innerHTML = '';

        if (objects.length === 0) {
            rawStatus.style.display = '';
            rawTable.style.display = 'none';
            try {
                const bucket = bucketInput.value.trim();
                const sampleResp = await fetch(`/api/search?bucket=${encodeURIComponent(bucket)}&q=`);
                const samples = sampleResp.ok ? await sampleResp.json() : [];
                if (samples.length > 0) {
                    rawStatus.innerHTML = 'No results found. Sample keys in this bucket:<br>' +
                        samples.slice(0, 5).map(o => `<code style="color:#7ec8e3;font-size:0.85em">${esc(o.key)}</code>`).join('<br>');
                } else {
                    rawStatus.textContent = 'No results found. Bucket appears empty.';
                }
            } catch {
                rawStatus.textContent = 'No results found.';
            }
            return;
        }

        rawStatus.style.display = 'none';
        rawTable.style.display = '';

        const rows = objects.map(obj => ({ ...obj, parsed: parseKey(obj.key) }));
        rows.sort((a, b) => a.parsed.epoch - b.parsed.epoch);

        for (const row of rows) {
            const p = row.parsed;
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input type="checkbox" class="raw-cb" data-key="${esc(row.key)}" /></td>
                <td class="service">${esc(p.service)}</td>
                <td class="host">${esc(p.host)}</td>
                <td class="host">${esc(p.bootId || '')}</td>
                <td>${esc(p.traceStart)}</td>
                <td>${esc(p.segIndex)}</td>
                <td class="size">${formatSize(row.size)}</td>
                <td class="date">${formatDate(row.last_modified)}</td>
            `;
            tr.querySelector('.raw-cb').addEventListener('change', updateSelectionCount);
            rawBody.appendChild(tr);
        }
        updateSelectionCount();
    }

    document.getElementById('raw-select-all').addEventListener('change', (e) => {
        rawSelectAll(e.target.checked);
    });

    function rawSelectAll(checked) {
        document.querySelectorAll('.raw-cb').forEach(cb => { cb.checked = checked; });
        document.getElementById('raw-select-all').checked = checked;
        updateSelectionCount();
    }

    // ── Selection & view ──
    function getSelectedKeys() {
        // In browse mode with segments showing, use seg checkboxes
        if (currentTab === 'browse' && selectedHost) {
            return getSegSelectedKeys();
        }
        // In raw mode, use raw checkboxes
        return Array.from(document.querySelectorAll('.raw-cb:checked')).map(cb => cb.dataset.key);
    }

    function updateSelectionCount() {
        const keys = getSelectedKeys();
        const el = document.getElementById('selection-count');
        el.textContent = keys.length ? `${keys.length} selected` : '';
        document.getElementById('view-btn').disabled = keys.length === 0;
    }

    function viewSelected() {
        const keys = getSelectedKeys();
        if (keys.length === 0) return;

        const bucket = bucketInput.value.trim();
        const keysParams = keys.map(k => `keys=${encodeURIComponent(k)}`).join('&');
        const traceUrl = `/api/trace?bucket=${encodeURIComponent(bucket)}&${keysParams}`;

        // Pass structured metadata for the viewer title
        const parsed = keys.map(k => parseKey(k));
        const services = [...new Set(parsed.map(p => p.service).filter(Boolean))];
        const hosts = [...new Set(parsed.map(p => p.host).filter(Boolean))];
        const epochs = parsed.map(p => p.epoch).filter(e => e > 0).sort((a, b) => a - b);
        const titleParams = new URLSearchParams();
        titleParams.set('trace', traceUrl);
        if (services.length) titleParams.set('svc', services.join(', '));
        if (hosts.length === 1) titleParams.set('host', hosts[0]);
        if (epochs.length >= 2) {
            titleParams.set('from', formatEpoch(epochs[0]));
            titleParams.set('to', formatEpoch(epochs[epochs.length - 1]));
        } else if (epochs.length === 1) {
            titleParams.set('from', formatEpoch(epochs[0]));
        }
        titleParams.set('segs', String(keys.length));

        window.open(`viewer.html?${titleParams.toString()}`, '_blank');
    }
    </script>
</body>
</html>