later 0.0.49

Distributed Background jobs manager and runner for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Later Dashboard</title>
  <style>
    :root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; color: #172033; background: #f4f6fa; }
    * { box-sizing: border-box; }
    body { margin: 0; }
    header { padding: 1rem 1.5rem 0; color: white; background: #3157d5; box-shadow: 0 2px 8px #16295b33; }
    header strong { font-size: 1.2rem; }
    .header-title { padding-bottom: 1rem; }
    main { display: grid; grid-template-columns: minmax(10rem, 14rem) minmax(0, 1fr); gap: 1.5rem; max-width: 90rem; margin: 1.5rem auto; padding: 0 1.5rem; }
    #performance { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .75rem; }
    .metric { min-height: 6rem; padding: 1rem; border: 1px solid #dce1ec; border-radius: .65rem; background: white; box-shadow: 0 2px 10px #1720330d; }
    .metric-label { display: block; color: #59657a; font-size: .76rem; text-transform: uppercase; letter-spacing: .04em; }
    .metric-value { display: block; margin-top: .35rem; font-size: 1.65rem; font-weight: 650; }
    .metric-note { display: block; margin-top: .2rem; color: #6f7a8e; font-size: .75rem; }
    nav, section { background: white; border: 1px solid #dce1ec; border-radius: .65rem; box-shadow: 0 2px 10px #1720330d; }
    nav { padding: .5rem; align-self: start; }
    button { font: inherit; cursor: pointer; }
    #tabs { display: flex; gap: .25rem; align-items: center; }
    #tabs[hidden] { display: none; }
    .tab { padding: .6rem 1.1rem; border: 0; border-bottom: 3px solid transparent; border-radius: .4rem .4rem 0 0; color: #c8d3f0; background: transparent; }
    .tab:hover { color: white; }
    .tab[aria-current="true"] { color: white; border-bottom-color: white; }
    #topics-menu { position: relative; }
    #topics-menu summary { list-style: none; }
    #topics-menu summary::-webkit-details-marker { display: none; }
    #topics-menu summary::after { content: "▾"; margin-left: .35rem; font-size: .75rem; }
    #topic-list { position: absolute; z-index: 1; top: calc(100% + .25rem); left: 0; display: grid; min-width: 12rem; max-height: 16rem; overflow-y: auto; padding: .35rem; border: 1px solid #dce1ec; border-radius: .4rem; background: white; box-shadow: 0 6px 18px #17203333; }
    .topic-option { display: flex; align-items: center; justify-content: space-between; gap: .6rem; padding: .55rem .7rem; border: 0; border-radius: .3rem; color: #30394c; background: transparent; text-align: left; }
    .topic-option:hover, .topic-option[aria-current="true"] { color: #2145bd; background: #edf1ff; }
    .lag-badge { min-width: 1.6rem; padding: .05rem .45rem; border-radius: 1rem; font-size: .74rem; color: white; background: #68748d; text-align: center; }
    .lag-badge[data-zero="true"] { background: #8b95a8; opacity: .55; }
    .lag-badge[hidden] { display: none; }
    #partition-picker { display: flex; flex-direction: column; gap: .35rem; padding: .5rem .8rem .9rem; border-bottom: 1px solid #e5e8ef; margin-bottom: .5rem; }
    #partition-picker[hidden] { display: none; }
    #partition-picker label { color: #59657a; font-size: .76rem; text-transform: uppercase; letter-spacing: .04em; }
    #partition-picker select { padding: .45rem; border: 1px solid #bdc5d6; border-radius: .35rem; font: inherit; }
    .stage { display: flex; width: 100%; justify-content: space-between; padding: .7rem .8rem; border: 0; border-radius: .4rem; color: #30394c; background: transparent; text-align: left; }
    .stage:hover, .stage[aria-current="true"] { color: #2145bd; background: #edf1ff; }
    .count { min-width: 2rem; padding: .1rem .5rem; border-radius: 1rem; color: white; background: #68748d; text-align: center; }
    section { min-height: 16rem; overflow: hidden; }
    #notice { margin: 1rem; padding: .8rem 1rem; border-radius: .4rem; background: #edf1ff; }
    #notice.error { color: #851f2a; background: #ffeaed; }
    .table-scroll { overflow-x: auto; overscroll-behavior-x: contain; -webkit-overflow-scrolling: touch; }
    table { width: 100%; min-width: 42rem; border-collapse: collapse; }
    th, td { padding: .75rem 1rem; border-bottom: 1px solid #e5e8ef; text-align: left; vertical-align: top; }
    th { color: #59657a; background: #fafbfc; font-size: .8rem; text-transform: uppercase; letter-spacing: .04em; }
    code { overflow-wrap: anywhere; }
    .job-link { padding: 0; border: 0; color: #2145bd; background: none; text-align: left; }
    footer { display: flex; justify-content: space-between; align-items: center; padding: 1rem; }
    footer button, dialog button { padding: .45rem .8rem; border: 1px solid #bdc5d6; border-radius: .35rem; background: white; }
    footer button:disabled { cursor: default; opacity: .45; }
    dialog { width: min(46rem, calc(100% - 2rem)); border: 0; border-radius: .7rem; box-shadow: 0 18px 60px #17203355; }
    dialog::backdrop { background: #17203388; }
    .dialog-head { display: flex; align-items: start; justify-content: space-between; gap: 1rem; }
    .detail-navigation { display: flex; align-items: center; gap: .6rem; margin: 1rem 0; }
    .detail-navigation span { color: #59657a; font-size: .85rem; }
    .history { padding-left: 1.25rem; }
    .relations { display: grid; gap: .5rem; }
    .relations p { margin: 0; }
    .payload { background: #f4f6fa; border: 1px solid #e5e8ef; border-radius: .35rem; padding: .6rem .8rem; font-size: .8rem; overflow-x: auto; white-space: pre-wrap; word-break: break-word; }
    .payload-note { color: #59657a; font-size: .76rem; margin: .3rem 0 0; }
    .relation-links { display: flex; flex-wrap: wrap; gap: .4rem; }
    #monitoring { grid-column: 1 / -1; overflow: visible; }
    #monitoring[hidden] { display: none; }
    .monitoring-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr)); gap: 1rem; padding: 1.1rem; }
    .chart-card h3 { margin: 0 0 .1rem; font-size: .85rem; color: #30394c; }
    .chart-note { margin: 0 0 .6rem; color: #8b95a8; font-size: .74rem; }
    .chart-card canvas { display: block; width: 100%; height: 9.5rem; }
    .chart-legend { display: flex; flex-wrap: wrap; gap: .4rem .9rem; margin-top: .5rem; font-size: .76rem; color: #59657a; }
    .chart-legend .swatch { display: inline-block; width: .6rem; height: .6rem; margin-right: .35rem; border-radius: 50%; vertical-align: middle; }
    @media (max-width: 700px) { main { grid-template-columns: 1fr; padding: 0 .75rem; } }
  </style>
</head>
<body>
  <header>
    <div class="header-title"><strong>later</strong> job dashboard</div>
    <div id="tabs" aria-label="Job views" hidden>
      <button id="all-jobs" class="tab" type="button">All</button>
      <details id="topics-menu">
        <summary class="tab">Topics</summary>
        <div id="topic-list" role="menu" aria-label="Topics"></div>
      </details>
      <button id="monitoring-tab" class="tab" type="button" hidden>Monitoring</button>
    </div>
  </header>
  <main>
    <div id="performance" aria-label="Performance over the last 60 seconds">
      <div class="metric"><span class="metric-label">Completed / sec</span><span class="metric-value" id="jobs-per-second">0.00</span><span class="metric-note">60 second average</span></div>
      <div class="metric"><span class="metric-label">Active workers</span><span class="metric-value" id="active-workers">0</span><span class="metric-note">heartbeat in last 15s</span></div>
      <div class="metric"><span class="metric-label">Busy workers</span><span class="metric-value" id="busy-workers">0</span><span class="metric-note">jobs currently running</span></div>
      <div class="metric"><span class="metric-label">Started</span><span class="metric-value" id="started">0</span><span class="metric-note">last 60 seconds</span></div>
      <div class="metric"><span class="metric-label">Succeeded</span><span class="metric-value" id="succeeded">0</span><span class="metric-note">last 60 seconds</span></div>
      <div class="metric"><span class="metric-label">Retried</span><span class="metric-value" id="retried">0</span><span class="metric-note">last 60 seconds</span></div>
      <div class="metric"><span class="metric-label">Failed</span><span class="metric-value" id="failed">0</span><span class="metric-note">last 60 seconds</span></div>
      <div class="metric"><span class="metric-label">Regular queue wait</span><span class="metric-value" id="wait-regular">-</span><span class="metric-note" id="wait-regular-note">avg, last 60s</span></div>
      <div class="metric"><span class="metric-label">Sequential queue wait</span><span class="metric-value" id="wait-sequential">-</span><span class="metric-note" id="wait-sequential-note">avg, last 60s</span></div>
      <div class="metric"><span class="metric-label">Database size</span><span class="metric-value" id="db-size">-</span><span class="metric-note">entire database, not just Later's tables</span></div>
    </div>
    <nav id="stages" aria-label="Job stages">
      <div id="partition-picker" hidden>
        <label for="partition-select">Partition</label>
        <select id="partition-select"></select>
      </div>
      <div id="stage-buttons"></div>
    </nav>
    <section id="jobs-section" aria-live="polite">
      <div id="notice">Loading jobs...</div>
      <div id="job-table" class="table-scroll" tabindex="0" aria-label="Jobs table. Scroll horizontally to see all columns." hidden>
        <table id="jobs">
          <thead><tr><th>ID</th><th class="type">Type</th><th class="seq">Seq</th><th class="date">Date</th><th>Duration</th><th>Stage</th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
      <footer id="paging" hidden>
        <button id="previous" type="button">Previous</button>
        <span id="page-label"></span>
        <button id="next" type="button">Next</button>
      </footer>
    </section>
    <section id="monitoring" aria-label="Monitoring" hidden>
      <div id="monitoring-grid" class="monitoring-grid"></div>
    </section>
  </main>
  <dialog id="details">
    <div class="dialog-head"><h2>Job details</h2><button id="close" type="button">Close</button></div>
    <div class="detail-navigation" aria-label="Jobs in the current view">
      <button id="detail-previous" type="button">Previous job</button>
      <span id="detail-position"></span>
      <button id="detail-next" type="button">Next job</button>
    </div>
    <p><strong>ID:</strong> <code id="detail-id"></code></p>
    <p><strong>Type:</strong> <code id="detail-type"></code></p>
    <p><strong>Current stage:</strong> <code id="detail-stage"></code></p>
    <p><strong>Total duration:</strong> <code id="detail-total-duration"></code></p>
    <p><strong>Processing:</strong> <code id="detail-processing-duration"></code></p>
    <p><strong>Waiting:</strong> <code id="detail-waiting-duration"></code></p>
    <p id="detail-partition-row" hidden><strong>Partition:</strong> <code id="detail-partition"></code></p>
    <h3>Related jobs</h3>
    <div id="relations" class="relations"></div>
    <h3>Payload</h3>
    <pre id="detail-payload" class="payload"></pre>
    <p id="detail-payload-note" class="payload-note" hidden>
      Shown as a positional array: fields are in declaration order, not
      named, because payloads are stored without field name metadata.
    </p>
    <h3>Previous stages</h3>
    <ol id="history" class="history"></ol>
  </dialog>
  <script>
    const BASE_APP = __LATER_DASHBOARD_BASE__;
    const TOPICS = __LATER_DASHBOARD_TOPICS__;
    // Retained-log topics configured for consumer-lag reporting
    // (Config::retained_log_lag) - independent of TOPICS (job-queue
    // partition ordering); a topic can be in one, both, or neither list.
    const LAG_TOPICS = __LATER_DASHBOARD_LAG_TOPICS__;
    // Whether the job server was built with Later's `prometheus` feature -
    // only then does the dashboard's own "metrics" command return anything,
    // so the Monitoring tab stays hidden entirely otherwise.
    const METRICS_ENABLED = __LATER_DASHBOARD_METRICS_ENABLED__;
    // Union of every topic name shown in the menu, job-queue topics first.
    const MENU_TOPICS = TOPICS.map(t => t.name)
      .concat(LAG_TOPICS.filter(name => !TOPICS.some(t => t.name === name)));
    const STAGE_ORDER = ["delayed", "waiting", "enqueued", "running", "requeued", "success", "failed"];
    const state = {
      mode: "stages", counts: {}, stage: "", topic: null, partition: 0,
      cursor: null, nextCursor: null, history: [], visibleJobs: [],
      selectedJobIndex: null, loading: false,
      // Topic name -> total retained-log consumer lag summed across every
      // group and partition, refreshed alongside everything else in
      // refresh(). Empty unless Config::retained_log_lag is configured.
      consumerLag: {},
      // Topic name -> total not-yet-completed jobs summed across every
      // partition. Always available for every topic in TOPICS.
      queueDepthTotals: {},
      // Topic name -> { partitionNumber: depth }, for the partition picker.
      queueDepthByPartition: {}
    };
    const elements = {
      tabs: document.querySelector("#tabs"), allJobs: document.querySelector("#all-jobs"),
      topicsMenu: document.querySelector("#topics-menu"), topicList: document.querySelector("#topic-list"),
      stages: document.querySelector("#stage-buttons"),
      partitionPicker: document.querySelector("#partition-picker"),
      partitionSelect: document.querySelector("#partition-select"),
      notice: document.querySelector("#notice"),
      jobTable: document.querySelector("#job-table"), body: document.querySelector("#jobs tbody"),
      paging: document.querySelector("#paging"), previous: document.querySelector("#previous"),
      next: document.querySelector("#next"), pageLabel: document.querySelector("#page-label"),
      details: document.querySelector("#details"),
      detailPrevious: document.querySelector("#detail-previous"),
      detailNext: document.querySelector("#detail-next"), detailPosition: document.querySelector("#detail-position"),
      performance: document.querySelector("#performance"), jobsSection: document.querySelector("#jobs-section"),
      monitoringTab: document.querySelector("#monitoring-tab"), monitoring: document.querySelector("#monitoring"),
      monitoringGrid: document.querySelector("#monitoring-grid")
    };

    // Process-local Prometheus metrics, polled (not scraped) directly from
    // the same dashboard endpoint - see DashboardCmd::Metrics. No history is
    // kept server-side, so every chart starts empty on page load and only
    // ever shows what this browser tab has itself observed since.
    const CHART_COLORS = ["#2145bd", "#dc6803", "#12b76a", "#7839ee", "#e11d48", "#0891b2", "#65a30d", "#c026d3"];
    const MAX_METRIC_POINTS = 150; // ~5 minutes at the 2.5 second poll interval below
    // The x-axis is a fixed, wall-clock window rather than "however much
    // data currently spans" - the latter rescales visibly (and jarringly)
    // every time a new point arrives, especially early on when only a few
    // points exist. A fixed window instead lets requestAnimationFrame
    // scroll it continuously in real time (see drawChart), independent of
    // when the next poll happens to land.
    const CHART_WINDOW_MS = 2 * 60 * 1000;
    let monitoringAnimationFrame = null;
    const CHART_DEFS = [
      // Fed from stored per-minute readings rather than the browser's own
      // polling, so the line shows a backlog draining over hours and survives
      // a reload. `windowMs` is changed by the selector on the card.
      { key: "queueLength", title: "Queue length", unit: "", note: "Jobs waiting for a worker (sampled each minute, kept on the server).", fixedLabels: ["queued", "partitioned"], server: true, windowMs: 6 * 60 * 60 * 1000 },
      { key: "throughput", title: "Job throughput", unit: "/s", note: "Completed stage transitions per second.", fixedLabels: ["success", "failed", "requeued"] },
      { key: "workers", title: "Workers", unit: "", note: "Worker tasks in this process, by state.", fixedLabels: ["active", "busy"] },
      { key: "queueDepth", title: "Durable queue depth", unit: "", note: "Not-yet-completed jobs, by state." },
      { key: "handlerLatency", title: "Handler latency", unit: "ms", note: "Average time spent in job handlers.", fixedLabels: ["success", "error"] },
      { key: "partitionBacklog", title: "Partition backlog", unit: "", note: "Ready, unleased partition heads, by topic." },
      { key: "commands", title: "Worker commands", unit: "/s", note: "Delivery commands handled per second, by outcome.", fixedLabels: ["success", "error"] }
    ];
    const metricsState = {
      series: {},        // chartKey -> { label: [{ t, v }, ...] }
      prevCounter: {},   // "chartKey:label" -> { t, value } - for rate calculation
      prevHistogram: {}  // "chartKey:label" -> { t, count, sum } - for average calculation
    };

    function uri(command) {
      return `${BASE_APP}?${new URLSearchParams({ query: JSON.stringify(command) })}`;
    }

    // A request that never answers (a database locked by a write storm, a
    // dropped connection) must not wedge the polling loops below forever.
    const REQUEST_TIMEOUT_MS = 20000;

    async function request(command) {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
      let response;
      try {
        response = await fetch(uri(command), { signal: controller.signal });
      } catch (error) {
        if (error.name === "AbortError") throw new Error("Dashboard request timed out");
        throw error;
      } finally {
        clearTimeout(timer);
      }
      if (!response.ok) {
        let message = `Dashboard request failed (${response.status})`;
        try { message = (await response.json()).error || message; } catch (_) {}
        throw new Error(message);
      }
      return response.json();
    }

    function showNotice(message, error = false) {
      elements.notice.textContent = message;
      elements.notice.classList.toggle("error", error);
      elements.notice.hidden = false;
      elements.jobTable.hidden = true;
      elements.paging.hidden = true;
    }

    function renderStages() {
      const existing = elements.stages.children.length === STAGE_ORDER.length;
      STAGE_ORDER.forEach((name, index) => {
        const isCurrent = String(name === state.stage);
        const displayCount = state.counts[name] ?? 0;
        if (existing) {
          // Update in place so the sidebar doesn't flicker on every refresh.
          const button = elements.stages.children[index];
          button.setAttribute("aria-current", isCurrent);
          button.querySelector(".count").textContent = displayCount;
          return;
        }
        const button = document.createElement("button");
        button.type = "button";
        button.className = "stage";
        button.dataset.stage = name;
        button.setAttribute("aria-current", isCurrent);
        const label = document.createElement("span");
        label.textContent = name;
        const count = document.createElement("span");
        count.className = "count";
        count.textContent = displayCount;
        button.append(label, count);
        button.addEventListener("click", () => loadStage(name, null, true));
        elements.stages.append(button);
      });
    }

    function lagBadge(name) {
      const badge = document.createElement("span");
      badge.className = "lag-badge";
      badge.title = "Backlog: unread retained-log records plus not-yet-completed queued jobs";
      // Stays hidden until the first refresh() populates a real reading -
      // every job-queue topic in TOPICS always ends up with one, so this
      // only matters for the brief window before that first fetch resolves.
      badge.hidden = true;
      return badge;
    }

    function renderTabs() {
      elements.tabs.hidden = false;
      const viewingAll = state.mode === "stages";
      elements.allJobs.setAttribute("aria-current", String(viewingAll));
      elements.topicsMenu.hidden = MENU_TOPICS.length === 0;
      elements.topicsMenu.querySelector("summary").setAttribute("aria-current", String(state.mode === "partition"));
      elements.monitoringTab.hidden = !METRICS_ENABLED;
      elements.monitoringTab.setAttribute("aria-current", String(state.mode === "monitoring"));
      const existing = elements.topicList.children.length === MENU_TOPICS.length;
      MENU_TOPICS.forEach((name, index) => {
        const isJobQueueTopic = TOPICS.some(t => t.name === name);
        const isCurrent = String(isJobQueueTopic && name === state.topic);
        if (existing) {
          const row = elements.topicList.children[index];
          if (isJobQueueTopic) row.setAttribute("aria-current", isCurrent);
          return;
        }
        const label = document.createElement("span");
        label.textContent = name;
        if (isJobQueueTopic) {
          const button = document.createElement("button");
          button.type = "button";
          button.className = "topic-option";
          button.setAttribute("role", "menuitem");
          button.setAttribute("aria-current", isCurrent);
          button.append(label, lagBadge(name));
          button.addEventListener("click", () => {
            elements.topicsMenu.open = false;
            switchToTopic(name);
          });
          elements.topicList.append(button);
        } else {
          // A retained-log-only topic (Config::retained_log_lag but not
          // Config::topics) has no job-queue partition view to switch to -
          // shown for its lag reading only, not clickable.
          const row = document.createElement("div");
          row.className = "topic-option";
          row.append(label, lagBadge(name));
          elements.topicList.append(row);
        }
      });
    }

    // Combines retained-log consumer lag and job-queue depth into one badge
    // per topic - most topics only ever have one of the two, but a topic
    // configured as both shows their sum, still a meaningful "how far
    // behind is this topic" signal either way.
    function renderTopicBadges() {
      MENU_TOPICS.forEach((name, index) => {
        const row = elements.topicList.children[index];
        if (!row) return;
        const badge = row.querySelector(".lag-badge");
        const lag = state.consumerLag[name];
        const depth = state.queueDepthTotals[name];
        if (lag === undefined && depth === undefined) return;
        const total = (lag || 0) + (depth || 0);
        badge.hidden = false;
        badge.dataset.zero = String(total === 0);
        badge.textContent = total;
      });
    }

    function switchToStages() {
      if (state.mode === "stages") return;
      stopMonitoringAnimation();
      state.mode = "stages";
      state.topic = null;
      elements.performance.hidden = false;
      elements.jobsSection.hidden = false;
      elements.monitoring.hidden = true;
      elements.stages.hidden = false;
      elements.partitionPicker.hidden = true;
      elements.topicsMenu.open = false;
      renderTabs();
      loadStage(state.stage || "enqueued", null, true);
    }

    function switchToTopic(name) {
      stopMonitoringAnimation();
      state.mode = "partition";
      state.topic = name;
      state.partition = 0;
      elements.performance.hidden = false;
      elements.jobsSection.hidden = false;
      elements.monitoring.hidden = true;
      elements.stages.hidden = true;
      renderTabs();
      renderPartitionPicker();
      loadPartition(name, 0, null, true);
    }

    function switchToMonitoring() {
      if (!METRICS_ENABLED || state.mode === "monitoring") return;
      state.mode = "monitoring";
      elements.topicsMenu.open = false;
      elements.performance.hidden = true;
      elements.jobsSection.hidden = true;
      elements.stages.hidden = true;
      elements.partitionPicker.hidden = true;
      elements.monitoring.hidden = false;
      renderTabs();
      CHART_DEFS.forEach(renderChart);
      startMonitoringAnimation();
    }

    // Redraws every chart's canvas on every animation frame while Monitoring
    // is the active tab, independent of the (much slower) poll interval -
    // this is what makes the x-axis scroll continuously in real time rather
    // than snapping forward once per poll. Legend text (the latest value per
    // series) only needs to change when new data actually arrives, so that
    // stays in renderChart/updateLegend, called from pollMetrics instead.
    function startMonitoringAnimation() {
      if (monitoringAnimationFrame !== null) return;
      const tick = () => {
        if (state.mode !== "monitoring") {
          monitoringAnimationFrame = null;
          return;
        }
        CHART_DEFS.forEach(def => drawChartCanvas(def));
        monitoringAnimationFrame = requestAnimationFrame(tick);
      };
      monitoringAnimationFrame = requestAnimationFrame(tick);
    }

    function stopMonitoringAnimation() {
      if (monitoringAnimationFrame !== null) {
        cancelAnimationFrame(monitoringAnimationFrame);
        monitoringAnimationFrame = null;
      }
    }

    function renderMonitoringCards() {
      elements.monitoringGrid.replaceChildren(...CHART_DEFS.map(def => {
        const card = document.createElement("div");
        card.className = "chart-card";
        const heading = document.createElement("h3");
        heading.textContent = def.title;
        const note = document.createElement("p");
        note.className = "chart-note";
        note.textContent = def.note;
        const canvas = document.createElement("canvas");
        canvas.id = `chart-${def.key}`;
        canvas.setAttribute("role", "img");
        canvas.setAttribute("aria-label", `${def.title} chart`);
        const legend = document.createElement("div");
        legend.className = "chart-legend";
        legend.id = `legend-${def.key}`;
        if (def.server) {
          const picker = document.createElement("select");
          picker.setAttribute("aria-label", `${def.title} time range`);
          [["1 hour", 60], ["6 hours", 360], ["24 hours", 1440], ["7 days", 10080]].forEach(([label, minutes]) => {
            const option = document.createElement("option");
            option.value = String(minutes);
            option.textContent = `Last ${label}`;
            picker.append(option);
          });
          picker.value = String(Math.round(def.windowMs / 60000));
          picker.addEventListener("change", () => {
            def.windowMs = Number(picker.value) * 60000;
            refreshQueueLength();
          });
          card.append(heading, note, picker, canvas, legend);
          return card;
        }
        card.append(heading, note, canvas, legend);
        return card;
      }));
    }

    // Assigns each label a stable color by hashing its name, rather than by
    // position - a dynamic label set (topics, queue states) can gain or
    // lose entries between polls without every other line's color shifting.
    function colorForLabel(label) {
      let hash = 0;
      for (let i = 0; i < label.length; i += 1) hash = (hash * 31 + label.charCodeAt(i)) >>> 0;
      return CHART_COLORS[hash % CHART_COLORS.length];
    }

    function formatMetricValue(value, unit) {
      if (!Number.isFinite(value)) return "-";
      const rounded = value >= 100 ? Math.round(value) : Math.round(value * 100) / 100;
      const text = value >= 1000 ? rounded.toLocaleString() : String(rounded);
      return unit ? `${text}${unit}` : text;
    }

    function familyIndex(families) {
      const byName = {};
      (families || []).forEach(family => { byName[family.name] = family; });
      return byName;
    }

    function sumByLabel(byName, metricName, groupLabel) {
      const family = byName[metricName];
      const totals = {};
      if (!family) return totals;
      family.metrics.forEach(metric => {
        const key = groupLabel ? (metric.labels[groupLabel] ?? "unknown") : "total";
        totals[key] = (totals[key] || 0) + (metric.value || 0);
      });
      return totals;
    }

    function sumHistogramByLabel(byName, metricName, groupLabel) {
      const family = byName[metricName];
      const totals = {};
      if (!family) return totals;
      family.metrics.forEach(metric => {
        if (!metric.histogram) return;
        const key = groupLabel ? (metric.labels[groupLabel] ?? "unknown") : "total";
        const bucket = totals[key] || { count: 0, sum: 0 };
        bucket.count += metric.histogram.sample_count || 0;
        bucket.sum += metric.histogram.sample_sum || 0;
        totals[key] = bucket;
      });
      return totals;
    }

    function pushMetricPoint(chartKey, label, t, v) {
      const series = (metricsState.series[chartKey] ??= {});
      const points = (series[label] ??= []);
      points.push({ t, v });
      if (points.length > MAX_METRIC_POINTS) points.shift();
    }

    function recordGauge(chartKey, totals, now) {
      Object.entries(totals).forEach(([label, value]) => pushMetricPoint(chartKey, label, now, value));
    }

    // Prometheus counters only ever go up, so a usable rate needs two polls -
    // the first sighting of any label just seeds `prevCounter` with no point
    // plotted yet.
    function recordCounterRate(chartKey, totals, now) {
      Object.entries(totals).forEach(([label, value]) => {
        const key = `${chartKey}:${label}`;
        const previous = metricsState.prevCounter[key];
        metricsState.prevCounter[key] = { t: now, value };
        if (!previous) return;
        const deltaSeconds = (now - previous.t) / 1000;
        if (deltaSeconds <= 0) return;
        // max(0, ...) guards against a process restart resetting the counter
        // below its last-seen value, which would otherwise plot as negative.
        pushMetricPoint(chartKey, label, now, Math.max(0, (value - previous.value) / deltaSeconds));
      });
    }

    function recordHistogramRate(chartKey, totals, now) {
      Object.entries(totals).forEach(([label, { count, sum }]) => {
        const key = `${chartKey}:${label}`;
        const previous = metricsState.prevHistogram[key];
        metricsState.prevHistogram[key] = { t: now, count, sum };
        if (!previous) return;
        const deltaCount = count - previous.count;
        if (deltaCount <= 0) return;
        pushMetricPoint(chartKey, label, now, Math.max(0, ((sum - previous.sum) / deltaCount) * 1000));
      });
    }

    // Reads the stored queue-length readings for the graph's selected range.
    // A missed refresh just leaves the previous line in place.
    async function refreshQueueLength() {
      const def = CHART_DEFS.find(candidate => candidate.key === "queueLength");
      if (!def) return;
      let history;
      try { history = await request({ cmd: "queue_history", minutes: Math.round(def.windowMs / 60000) }); }
      catch (_) { return; }
      metricsState.series.queueLength = {
        queued: history.points.map(point => ({ t: point.t, v: point.queued })),
        partitioned: history.points.map(point => ({ t: point.t, v: point.partitioned }))
      };
      if (state.mode === "monitoring") renderChart(def);
    }

    async function pollMetrics() {
      if (!METRICS_ENABLED) return;
      let families;
      try { families = await request({ cmd: "metrics" }); }
      catch (_) { return; } // a missed sample just leaves a gap, not a page-wide error
      const byName = familyIndex(families);
      const now = Date.now();
      recordCounterRate("throughput", sumByLabel(byName, "later_job_transitions_total", "stage"), now);
      recordGauge("workers", sumByLabel(byName, "later_workers", "state"), now);
      recordGauge("queueDepth", sumByLabel(byName, "later_queue_jobs", "state"), now);
      recordHistogramRate("handlerLatency", sumHistogramByLabel(byName, "later_job_handler_duration_seconds", "outcome"), now);
      recordGauge("partitionBacklog", sumByLabel(byName, "later_partition_backlog", "topic"), now);
      recordCounterRate("commands", sumByLabel(byName, "later_worker_commands_total", "outcome"), now);
      if (state.mode === "monitoring") CHART_DEFS.forEach(renderChart);
    }

    function chartLabels(def) {
      const series = metricsState.series[def.key] || {};
      return def.fixedLabels
        ? def.fixedLabels.filter(label => series[label] && series[label].length > 0)
        : Object.keys(series).filter(label => series[label].length > 0);
    }

    // Legend text (the latest value per series) only needs to update when
    // new data actually arrives - called from pollMetrics, on its own poll
    // cadence. The canvas itself redraws separately and far more often (see
    // startMonitoringAnimation) so the line can keep scrolling smoothly
    // between polls too.
    function renderChart(def) {
      updateLegend(def);
      drawChartCanvas(def);
    }

    function updateLegend(def) {
      const legend = document.querySelector(`#legend-${def.key}`);
      if (!legend) return;
      const series = metricsState.series[def.key] || {};
      const labels = chartLabels(def);
      if (labels.length === 0) {
        legend.replaceChildren(document.createTextNode("Collecting data..."));
        return;
      }
      legend.replaceChildren(...labels.map(label => {
        const points = series[label];
        const latest = points[points.length - 1].v;
        const item = document.createElement("span");
        const swatch = document.createElement("i");
        swatch.className = "swatch";
        swatch.style.background = colorForLabel(label);
        item.append(swatch, document.createTextNode(`${label}: ${formatMetricValue(latest, def.unit)}`));
        return item;
      }));
    }

    function drawChartCanvas(def) {
      const canvas = document.querySelector(`#chart-${def.key}`);
      if (!canvas) return;
      const series = metricsState.series[def.key] || {};
      const labels = chartLabels(def);
      drawChart(canvas, labels.map(label => ({ color: colorForLabel(label), points: series[label] })), def.windowMs || CHART_WINDOW_MS);
    }

    // A dependency-free line chart - Later's dashboard is a single embedded
    // HTML file with no build step, so pulling in a charting library isn't
    // worth it for a handful of simple time series. The x-axis is a fixed
    // window ending "now" (CHART_WINDOW_MS), not however far the data
    // happens to span - combined with being redrawn on every animation
    // frame (not just every poll), that's what makes the line scroll
    // smoothly in real time instead of snapping forward in visible jumps
    // once every poll interval. Curves are drawn through quadratic
    // midpoints rather than straight segments between raw points, which
    // reads as noticeably less jagged for noisy series like per-second
    // rates without hiding real spikes.
    function drawChart(canvas, series, windowMs = CHART_WINDOW_MS) {
      const ctx = canvas.getContext("2d");
      const dpr = window.devicePixelRatio || 1;
      const rect = canvas.getBoundingClientRect();
      const width = Math.max(rect.width, 1);
      const height = Math.max(rect.height, 1);
      const pixelWidth = Math.round(width * dpr);
      const pixelHeight = Math.round(height * dpr);
      if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
        canvas.width = pixelWidth;
        canvas.height = pixelHeight;
      }
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, width, height);

      const now = Date.now();
      const windowStart = now - windowMs;
      const visibleSeries = series
        .map(({ color, points }) => ({ color, points: points.filter(point => point.t >= windowStart) }))
        .filter(entry => entry.points.length >= 2);
      if (visibleSeries.length === 0) {
        ctx.fillStyle = "#9aa4b8";
        ctx.font = "12px ui-sans-serif, system-ui, sans-serif";
        ctx.fillText("Collecting data...", 10, height / 2);
        return;
      }

      const padding = 8;
      const plotWidth = width - padding * 2;
      const plotHeight = height - padding * 2;
      const maxV = Math.max(1, ...visibleSeries.flatMap(entry => entry.points.map(point => point.v)));
      const x = t => padding + ((t - windowStart) / windowMs) * plotWidth;
      const y = v => padding + plotHeight - (v / maxV) * plotHeight;

      ctx.strokeStyle = "#e5e8ef";
      ctx.lineWidth = 1;
      for (let i = 0; i <= 2; i += 1) {
        const gy = padding + (plotHeight / 2) * i;
        ctx.beginPath();
        ctx.moveTo(padding, gy);
        ctx.lineTo(width - padding, gy);
        ctx.stroke();
      }

      ctx.fillStyle = "#9aa4b8";
      ctx.font = "11px ui-sans-serif, system-ui, sans-serif";
      ctx.textBaseline = "top";
      // Top right: a draining line starts at the top left and would sit on it.
      ctx.textAlign = "right";
      ctx.fillText(Math.round(maxV).toLocaleString(), width - padding - 2, padding + 2);
      ctx.textAlign = "left";

      visibleSeries.forEach(({ color, points }) => {
        ctx.strokeStyle = color;
        ctx.lineWidth = 1.75;
        ctx.lineJoin = "round";
        ctx.lineCap = "round";
        ctx.beginPath();
        ctx.moveTo(x(points[0].t), y(points[0].v));
        for (let i = 1; i < points.length - 1; i += 1) {
          const px = x(points[i].t);
          const py = y(points[i].v);
          const midX = (px + x(points[i + 1].t)) / 2;
          const midY = (py + y(points[i + 1].v)) / 2;
          ctx.quadraticCurveTo(px, py, midX, midY);
        }
        const last = points[points.length - 1];
        ctx.lineTo(x(last.t), y(last.v));
        ctx.stroke();
      });
    }

    function renderPartitionPicker() {
      const topic = TOPICS.find(candidate => candidate.name === state.topic);
      if (!topic) { elements.partitionPicker.hidden = true; return; }
      elements.partitionPicker.hidden = false;
      const depths = state.queueDepthByPartition[topic.name] || {};
      const options = [];
      for (let partition = 0; partition < topic.partition_count; partition += 1) options.push(partition);
      elements.partitionSelect.replaceChildren(...options.map(partition => {
        const option = document.createElement("option");
        option.value = String(partition);
        const depth = depths[partition];
        option.textContent = depth === undefined
          ? `Partition ${partition}`
          : `Partition ${partition} (${depth} queued)`;
        return option;
      }));
      elements.partitionSelect.value = String(state.partition);
    }

    function renderPerformance(performance, dbSizeBytes) {
      document.querySelector("#jobs-per-second").textContent = Number(performance.jobs_per_second || 0).toFixed(2);
      for (const name of ["active_workers", "busy_workers", "started", "succeeded", "retried", "failed"]) {
        document.querySelector(`#${name.replaceAll("_", "-")}`).textContent = performance[name] ?? 0;
      }
      for (const mode of ["regular", "sequential"]) {
        const wait = (performance.wait_time || {})[mode] || { count: 0, avg_ms: 0, max_ms: 0 };
        document.querySelector(`#wait-${mode}`).textContent = wait.count > 0 ? formatDuration(wait.avg_ms) : "-";
        document.querySelector(`#wait-${mode}-note`).textContent = wait.count > 0
          ? `avg of ${wait.count}, max ${formatDuration(wait.max_ms)}`
          : "no recent dispatches";
      }
      // `null` when the storage backend has no meaningful single-database
      // size to report (Redis, in-memory) - only SQLite/PostgreSQL do.
      document.querySelector("#db-size").textContent = dbSizeBytes == null ? "-" : formatBytes(dbSizeBytes);
    }

    function formatBytes(bytes) {
      const value = Number(bytes);
      if (!Number.isFinite(value) || value < 0) return "-";
      if (value < 1024) return `${value} B`;
      if (value < 1024 ** 2) return `${(value / 1024).toFixed(1)} KB`;
      if (value < 1024 ** 3) return `${(value / 1024 ** 2).toFixed(1)} MB`;
      return `${(value / 1024 ** 3).toFixed(2)} GB`;
    }

    function stageDate(stage) {
      if (!stage || !stage.date) return "";
      const date = new Date(stage.date);
      if (Number.isNaN(date.valueOf())) return stage.date;
      // `Date` only carries millisecond precision; read the fractional
      // seconds straight from the source timestamp so up to microsecond
      // precision survives when the server sent it.
      const match = /\.(\d+)/.exec(stage.date);
      const fraction = match
        ? match[1].slice(0, 6).padEnd(3, "0")
        : String(date.getMilliseconds()).padStart(3, "0");
      return `${date.toLocaleString()}.${fraction}`;
    }

    function formatDuration(milliseconds) {
      const value = Number(milliseconds);
      if (!Number.isFinite(value) || value < 0) return "-";
      if (value < 1) return "<1 ms";
      if (value < 1000) return `${Math.round(value)} ms`;
      if (value < 60000) return `${(value / 1000).toFixed(2)} s`;
      if (value < 3600000) return `${(value / 60000).toFixed(2)} min`;
      return `${(value / 3600000).toFixed(2)} h`;
    }

    function renderJobs(response) {
      const rows = response.result.map(job => {
        const row = document.createElement("tr");
        const idCell = document.createElement("td");
        const link = document.createElement("button");
        link.type = "button";
        link.className = "job-link";
        link.textContent = job.id.slice(-6);
        link.title = job.id;
        link.addEventListener("click", () => loadJob(job.id));
        idCell.append(link);
        const type = document.createElement("td");
        type.className = "type";
        type.textContent = job.info.payload_type;
        const seq = document.createElement("td");
        seq.className = "seq";
        seq.textContent = job.info.sequence ?? "-";
        const date = document.createElement("td");
        date.className = "date";
        date.textContent = stageDate(job.info.stage);
        const duration = document.createElement("td");
        duration.textContent = formatDuration(job.timing.total_ms);
        const stage = document.createElement("td");
        stage.textContent = job.info.stage.type;
        row.append(idCell, type, seq, date, duration, stage);
        return row;
      });
      elements.body.replaceChildren(...rows);
      elements.notice.hidden = response.result.length > 0;
      elements.notice.classList.remove("error");
      elements.notice.textContent = "Nothing to show here";
      const selectedId = state.selectedJobIndex === null
        ? null
        : state.visibleJobs[state.selectedJobIndex]?.id;
      state.visibleJobs = response.result;
      state.selectedJobIndex = selectedId === null
        ? null
        : state.visibleJobs.findIndex(job => job.id === selectedId);
      if (state.selectedJobIndex === -1) state.selectedJobIndex = null;
      updateDetailNavigation();
      elements.jobTable.hidden = response.result.length === 0;
      state.nextCursor = response.paging.next_cursor;
      elements.pageLabel.textContent = `Page ${state.history.length + 1}`;
      elements.previous.disabled = state.history.length === 0;
      elements.next.disabled = state.nextCursor === null;
      elements.paging.hidden = state.history.length === 0 && state.nextCursor === null;
    }

    async function loadStage(stage, cursor, reset = false, silent = false) {
      if (state.loading) return;
      state.loading = true;
      if (reset || state.stage !== stage) state.history = [];
      state.stage = stage;
      state.cursor = cursor;
      renderStages();
      // A silent (background) refresh keeps the current table visible while
      // it fetches, instead of flashing "Loading jobs..." over it every tick.
      if (!silent) showNotice("Loading jobs...");
      try { renderJobs(await request({ cmd: "jobs_in_stage", stage, cursor })); }
      catch (error) { showNotice(error.message, true); }
      finally { state.loading = false; }
    }

    async function loadPartition(topic, partition, cursor, reset = false, silent = false) {
      if (state.loading) return;
      state.loading = true;
      if (reset || state.topic !== topic || state.partition !== partition) state.history = [];
      state.mode = "partition";
      state.topic = topic;
      state.partition = partition;
      state.cursor = cursor;
      if (!silent) showNotice("Loading jobs...");
      try { renderJobs(await request({ cmd: "partition_jobs", topic, partition, cursor })); }
      catch (error) { showNotice(error.message, true); }
      finally { state.loading = false; }
    }

    function showJob(job) {
      const info = job.info;
      location.hash = encodeURIComponent(info.id);
      const index = state.visibleJobs.findIndex(candidate => candidate.id === info.id);
      state.selectedJobIndex = index === -1 ? null : index;
      updateDetailNavigation();
      document.querySelector("#detail-id").textContent = info.id;
      document.querySelector("#detail-type").textContent = info.payload_type;
      document.querySelector("#detail-stage").textContent = info.stage.type;
      document.querySelector("#detail-total-duration").textContent = formatDuration(job.timing.total_ms);
      document.querySelector("#detail-processing-duration").textContent = formatDuration(job.timing.processing_ms);
      document.querySelector("#detail-waiting-duration").textContent = formatDuration(job.timing.waiting_ms);
      const relations = job.relations || {};
      const partition = relations.partition;
      const partitionRow = document.querySelector("#detail-partition-row");
      if (partition) {
        document.querySelector("#detail-partition").textContent =
          `${partition.topic} / partition ${partition.partition} / sequence ${partition.sequence}`;
        partitionRow.hidden = false;
      } else {
        partitionRow.hidden = true;
      }
      const relationRows = [];
      if (relations.parent_job_id) {
        relationRows.push(relationRow("Parent", [relations.parent_job_id]));
      }
      if ((relations.continuation_job_ids || []).length > 0) {
        relationRows.push(relationRow("Continues with", relations.continuation_job_ids));
      }
      if (relations.continuations_truncated) {
        const note = document.createElement("p");
        note.textContent = "Only the first 25 continuation jobs are shown.";
        relationRows.push(note);
      }
      if (partition && partition.previous_job_id) {
        relationRows.push(relationRow("Previous in partition", [partition.previous_job_id]));
      }
      if (partition && partition.next_job_id) {
        relationRows.push(relationRow("Next in partition", [partition.next_job_id]));
      }
      if (relationRows.length === 0) {
        const empty = document.createElement("p");
        empty.textContent = "No related jobs";
        relationRows.push(empty);
      }
      document.querySelector("#relations").replaceChildren(...relationRows);
      const payload = job.payload;
      const payloadNote = document.querySelector("#detail-payload-note");
      const payloadEl = document.querySelector("#detail-payload");
      if (payload && payload.format === "msgpack") {
        payloadEl.textContent = JSON.stringify(payload.value, null, 2);
        payloadNote.hidden = !Array.isArray(payload.value);
      } else if (payload && payload.format === "raw") {
        payloadEl.textContent = payload.value;
        payloadNote.hidden = true;
      } else {
        payloadEl.textContent = "(unavailable)";
        payloadNote.hidden = true;
      }
      document.querySelector("#history").replaceChildren(...info.previous_stages.slice().reverse().map(stage => {
        const item = document.createElement("li");
        item.textContent = `${stage.type} - ${stageDate(stage)}`;
        return item;
      }));
      if (!elements.details.open) elements.details.showModal();
    }

    function updateDetailNavigation() {
      const index = state.selectedJobIndex;
      const jobCount = state.visibleJobs.length;
      const isInView = Number.isInteger(index) && index >= 0 && index < jobCount;
      elements.detailPrevious.disabled = !isInView || index === 0;
      elements.detailNext.disabled = !isInView || index === jobCount - 1;
      elements.detailPosition.textContent = isInView
        ? `Job ${index + 1} of ${jobCount}`
        : "Not in the current view";
    }

    function relationRow(label, jobIds) {
      const row = document.createElement("p");
      const title = document.createElement("strong");
      title.textContent = `${label}: `;
      const links = document.createElement("span");
      links.className = "relation-links";
      links.replaceChildren(...jobIds.map(id => {
        const link = document.createElement("button");
        link.type = "button";
        link.className = "job-link";
        link.textContent = id;
        link.addEventListener("click", () => loadJob(id));
        return link;
      }));
      row.append(title, links);
      return row;
    }

    async function loadJob(id) {
      try { showJob(await request({ cmd: "job", id })); }
      catch (error) { showNotice(error.message, true); }
    }

    function loadAdjacentJob(offset) {
      if (state.selectedJobIndex === null) return;
      const job = state.visibleJobs[state.selectedJobIndex + offset];
      if (job) loadJob(job.id);
    }

    function reload(cursor) {
      if (state.mode === "partition") loadPartition(state.topic, state.partition, cursor);
      else loadStage(state.stage, cursor);
    }

    async function refreshConsumerLag() {
      if (LAG_TOPICS.length === 0) return;
      try {
        const readings = await request({ cmd: "consumer_lag" });
        const totals = {};
        readings.forEach(reading => {
          totals[reading.topic] = (totals[reading.topic] || 0) + reading.lag;
        });
        state.consumerLag = totals;
      } catch (_) {
        // Silently skipped - a missed lag reading isn't worth a page-wide
        // error banner the way a failed job-list refresh is.
      }
    }

    async function refreshQueueDepth() {
      if (TOPICS.length === 0) return;
      try {
        const readings = await request({ cmd: "partition_queue_depth" });
        // The server only reports partitions with at least one queued job,
        // so every configured topic is seeded at 0 first - otherwise a
        // fully caught-up topic would never get an entry here at all, and
        // its badge would stay hidden forever instead of showing "0".
        const totals = {};
        TOPICS.forEach(topic => { totals[topic.name] = 0; });
        const byPartition = {};
        readings.forEach(reading => {
          totals[reading.topic] = (totals[reading.topic] || 0) + reading.depth;
          (byPartition[reading.topic] ??= {})[reading.partition] = reading.depth;
        });
        state.queueDepthTotals = totals;
        state.queueDepthByPartition = byPartition;
      } catch (_) {
        // Silently skipped, same reasoning as refreshConsumerLag.
      }
    }

    async function refresh() {
      try {
        const response = await request({ cmd: "count" });
        const previousCount = state.counts[state.stage];
        state.counts = response.stages;
        renderPerformance(response.performance, response.db_size_bytes);
        if (state.mode === "stages") {
          renderStages();
          if (!state.stage) await loadStage("enqueued", null, true);
          else if (previousCount !== state.counts[state.stage]) await loadStage(state.stage, state.cursor, false, true);
        } else if (state.mode === "partition") {
          await loadPartition(state.topic, state.partition, state.cursor, false, true);
        }
        // state.mode === "monitoring": nothing job-list-related to refresh
        // here - pollMetrics() (its own interval) handles that view. Calling
        // loadPartition() unconditionally in this branch used to also match
        // "monitoring", and loadPartition() unconditionally sets
        // state.mode = "partition" - silently kicking the dashboard out of
        // Monitoring one refresh cycle (≤2.5s) after switching to it, which
        // froze every chart in place since pollMetrics() only redraws them
        // while state.mode is still "monitoring".
      } catch (error) { showNotice(error.message, true); }
      await Promise.all([refreshConsumerLag(), refreshQueueDepth()]);
      renderTopicBadges();
      if (state.mode === "partition") renderPartitionPicker();
    }

    elements.previous.addEventListener("click", () => {
      if (state.history.length === 0) return;
      reload(state.history.pop());
    });
    elements.next.addEventListener("click", () => {
      if (state.nextCursor === null) return;
      state.history.push(state.cursor);
      reload(state.nextCursor);
    });
    elements.partitionSelect.addEventListener("change", () => {
      loadPartition(state.topic, Number(elements.partitionSelect.value), null, true);
    });
    elements.allJobs.addEventListener("click", switchToStages);
    elements.monitoringTab.addEventListener("click", switchToMonitoring);
    elements.detailPrevious.addEventListener("click", () => loadAdjacentJob(-1));
    elements.detailNext.addEventListener("click", () => loadAdjacentJob(1));
    document.querySelector("#close").addEventListener("click", () => { elements.details.close(); location.hash = ""; });
    window.addEventListener("hashchange", () => {
      const id = decodeURIComponent(location.hash.slice(1));
      if (id) loadJob(id);
    });

    renderMonitoringCards();
    renderTabs();
    if (location.hash.length > 1) loadJob(decodeURIComponent(location.hash.slice(1)));
    // Each poll waits for the previous one to finish before the next delay
    // starts. A fixed setInterval kept firing while a slow response (large
    // backlog, busy database) was still in flight, so requests piled up
    // unbounded, each holding a database connection - making the slowness
    // worse until the page showed nothing at all.
    function pollEvery(task, delayMs) {
      const tick = async () => {
        try { await task(); } finally { setTimeout(tick, delayMs); }
      };
      tick();
    }
    pollEvery(refresh, 2500);
    if (METRICS_ENABLED) {
      pollEvery(pollMetrics, 2500);
      pollEvery(refreshQueueLength, 15000);
    }
  </script>
</body>
</html>