-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathapp.js
More file actions
2606 lines (2278 loc) · 105 KB
/
Copy pathapp.js
File metadata and controls
2606 lines (2278 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Orchestrator Web Dashboard — Frontend
*
* Connects to SSE endpoint for live state updates.
* Zero dependencies, vanilla JS.
*/
// ─── Helpers ────────────────────────────────────────────────────────────────
function formatDuration(ms) {
if (!ms || ms <= 0) return "—";
const totalSec = Math.floor(ms / 1000);
const h = Math.floor(totalSec / 3600);
const m = Math.floor((totalSec % 3600) / 60);
const s = totalSec % 60;
if (h > 0) return `${h}h ${String(m).padStart(2, "0")}m`;
return `${m}m ${String(s).padStart(2, "0")}s`;
}
function relativeTime(epochOrIso) {
if (!epochOrIso) return "";
const ts = typeof epochOrIso === "string" ? new Date(epochOrIso).getTime() : epochOrIso;
if (isNaN(ts)) return "";
const diff = Date.now() - ts;
if (diff < 60000) return `${Math.floor(diff / 1000)}s ago`;
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
return `${Math.floor(diff / 3600000)}h ago`;
}
function pctClass(pct) {
if (pct >= 100) return "pct-hi";
if (pct >= 50) return "pct-mid";
if (pct > 0) return "pct-low";
return "pct-0";
}
function escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
/** Format token count as human-readable (e.g., 1.2k, 45k, 1.2M). */
function formatTokens(n) {
if (!n || n === 0) return "0";
if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M";
if (n >= 1_000) return (n / 1_000).toFixed(1) + "k";
return String(n);
}
function formatCost(usd) {
if (!usd || usd === 0) return "";
if (usd < 0.01) return `$${usd.toFixed(4)}`;
if (usd < 1) return `$${usd.toFixed(3)}`;
return `$${usd.toFixed(2)}`;
}
/**
* TP-107: Check if a lane has a live agent via the Runtime V2 registry.
* Returns true/false if registry data is available, null if no V2 data.
*/
function isLaneAliveV2(laneNumber) {
if (!currentData || !currentData.runtimeRegistry || !currentData.runtimeRegistry.agents) return null;
const agents = Object.values(currentData.runtimeRegistry.agents);
const laneAgents = agents.filter(a => a.laneNumber === laneNumber);
if (laneAgents.length === 0) return null;
return laneAgents.some(a => a.status === 'running' || a.status === 'spawning');
}
/**
* TP-107: Merge Runtime V2 lane snapshot data onto legacy lane state.
* V2 fields take precedence when present; legacy fields are preserved as fallback.
*/
function mergeV2LaneSnapshot(legacyLs, v2snap) {
const base = legacyLs ? { ...legacyLs } : {};
// Overlay V2 fields from nested worker snapshot onto flat legacy shape.
// RuntimeLaneSnapshot has worker: { status, elapsedMs, toolCalls, contextPct, ... }
const w = v2snap.worker;
if (w) {
// Map V2 agent status to legacy dashboard status strings
if (w.status) {
const statusMap = { running: 'running', spawning: 'running', exited: 'done', crashed: 'error', killed: 'done', timed_out: 'error', wrapping_up: 'running' };
base.workerStatus = statusMap[w.status] || w.status;
}
if (w.elapsedMs != null) base.workerElapsed = w.elapsedMs;
if (w.contextPct != null) base.workerContextPct = w.contextPct;
if (w.toolCalls != null) base.workerToolCount = w.toolCalls;
if (w.lastTool) base.workerLastTool = w.lastTool;
if (w.costUsd != null) base.workerCostUsd = w.costUsd;
if (w.inputTokens != null) base.workerInputTokens = w.inputTokens;
if (w.outputTokens != null) base.workerOutputTokens = w.outputTokens;
if (w.cacheReadTokens != null) base.workerCacheReadTokens = w.cacheReadTokens;
if (w.cacheWriteTokens != null) base.workerCacheWriteTokens = w.cacheWriteTokens;
}
if (v2snap.taskId) base.taskId = v2snap.taskId;
if (v2snap.batchId) base.batchId = v2snap.batchId;
// Enrich progress display from V2 snapshot
if (v2snap.progress) {
base._v2Progress = v2snap.progress;
}
return base;
}
function isReviewerActiveForTask(ls, task) {
if (!ls || !task) return false;
return !!(ls.reviewerStatus === "running" && task.status === "running" && (!ls.taskId || ls.taskId === task.taskId));
}
/** Build a compact token summary string from lane state sidecar data.
* Display: ↑total_input ↓output (cost)
* Anthropic splits input into: uncached `input` + `cacheRead`.
* Both represent tokens the model processed as input.
* We show the combined figure as ↑ for clarity.
*/
function tokenSummaryFromLaneState(ls) {
if (!ls) return "";
const inp = ls.workerInputTokens || 0;
const out = ls.workerOutputTokens || 0;
const cr = ls.workerCacheReadTokens || 0;
const cw = ls.workerCacheWriteTokens || 0;
const cost = ls.workerCostUsd || 0;
const totalIn = inp + cr; // uncached + cached = total input processed
if (totalIn === 0 && out === 0) return "";
let s = `↑${formatTokens(totalIn)} ↓${formatTokens(out)}`;
if (cost > 0) s += ` ${formatCost(cost)}`;
return s;
}
function tokenSummaryFromReviewerLaneState(ls) {
if (!ls) return "";
const inp = ls.reviewerInputTokens || 0;
const out = ls.reviewerOutputTokens || 0;
const cr = ls.reviewerCacheReadTokens || 0;
const cw = ls.reviewerCacheWriteTokens || 0;
const cost = ls.reviewerCostUsd || 0;
const totalIn = inp + cr; // uncached + cached = total input processed
if (totalIn === 0 && out === 0) return "";
let s = `↑${formatTokens(totalIn)} ↓${formatTokens(out)}`;
if (cost > 0) s += ` ${formatCost(cost)}`;
return s;
}
/** Build compact telemetry badge HTML for retry/compaction indicators.
* Only shows badges when telemetry data has meaningful values.
* @param {object|null} tel - Telemetry data for a lane (from currentData.telemetry[prefix])
* @param {boolean} [suppressRetry=false] - When true, hide the retrying badge
* (used when reviewer is active — long tool calls trigger false retry signals)
* @returns {string} HTML string with badges, or "" if nothing to show
*/
function telemetryBadgesHtml(tel, suppressRetry) {
if (!tel) return "";
let badges = "";
if (tel.retryActive && !suppressRetry) {
const err = tel.lastRetryError ? ` — ${tel.lastRetryError}` : "";
badges += `<span class="telem-badge telem-retry-active" title="Retry in progress${escapeHtml(err)}">🔄 retrying</span>`;
} else if (tel.retries > 0 && !suppressRetry) {
badges += `<span class="telem-badge telem-retry" title="${tel.retries} auto-retry event(s)">🔄 ${tel.retries}</span>`;
}
if (tel.compactions > 0) {
badges += `<span class="telem-badge telem-compaction" title="${tel.compactions} context compaction(s)">🗜 ${tel.compactions}</span>`;
}
return badges;
}
// ─── Copy to Clipboard ──────────────────────────────────────────────────────
let toastEl = null;
let toastTimer = null;
function showCopyToast(text) {
if (!toastEl) {
toastEl = document.createElement("div");
toastEl.className = "copy-toast";
document.body.appendChild(toastEl);
}
toastEl.textContent = `Copied: ${text}`;
toastEl.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove("visible"), 2000);
}
function copySessionId(sessionName) {
// Retained for potential future use but no longer rendered in the UI.
navigator.clipboard.writeText(sessionName).then(() => {
showCopyToast(`session ${sessionName}`);
const btn = document.querySelector(`[data-session="${sessionName}"]`);
if (btn) {
btn.classList.add("copied");
setTimeout(() => btn.classList.remove("copied"), 1500);
}
}).catch(() => {
// Fallback: select the text
const btn = document.querySelector(`[data-session="${sessionName}"]`);
if (btn) {
const range = document.createRange();
range.selectNodeContents(btn);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
});
}
// ─── DOM References ─────────────────────────────────────────────────────────
const $ = (id) => document.getElementById(id);
const $batchId = $("batch-id");
const $batchPhase = $("batch-phase");
const $workspaceMode = $("workspace-mode");
const $submoduleStatus = $("submodule-status");
const $connDot = $("conn-dot");
const $lastUpdate = $("last-update");
const $progressBarBg = $("progress-bar-bg");
const $overallPct = $("overall-pct");
const $summaryCounts = $("summary-counts");
const $summaryElapsed = $("summary-elapsed");
const $summaryWaves = $("summary-waves");
const $lanesTasksBody = $("lanes-tasks-body");
const $mergeBody = $("merge-body");
const $errorsPanel = $("errors-panel");
const $errorsBody = $("errors-body");
const $footerInfo = $("footer-info");
const $content = $("content");
const $historySelect = $("history-select");
const $historyPanel = $("history-panel");
const $historyBody = $("history-body");
// ─── Repo Filter State ──────────────────────────────────────────────────────
const $repoFilter = $("repo-filter");
let selectedRepo = ""; // "" means "All repos"
let knownRepos = []; // sorted list of known repo IDs
let repoFilterVisible = false;
// ─── History State ──────────────────────────────────────────────────────────
let historyList = []; // compact batch summaries
let viewingHistoryId = null; // batchId if viewing history, null if live
// ─── Viewer State ───────────────────────────────────────────────────────────
let viewerMode = null; // "conversation" | "status-md" | null
let viewerTarget = null; // session name (conversation) or taskId (status-md)
let lastBatchId = null; // TP-178: track batchId for stale viewer detection (#487)
// ─── Repo Helpers ───────────────────────────────────────────────────────────
/**
* Build a sorted, deduplicated list of repo IDs from the batch payload.
*/
function collectRepoIds(batch) {
if (!batch || batch.mode !== "workspace") return [];
const repos = new Set();
for (const lane of (batch.lanes || [])) {
if (lane.repoId) repos.add(lane.repoId);
}
for (const task of (batch.tasks || [])) {
const rid = task.resolvedRepoId || task.repoId;
if (rid) repos.add(rid);
}
for (const mr of (batch.mergeResults || [])) {
for (const rr of (mr.repoResults || [])) {
if (rr.repoId) repos.add(rr.repoId);
}
}
const sorted = Array.from(repos).sort();
return sorted;
}
/**
* Build the repo set used by the filter dropdown.
* Returns empty array when mode !== "workspace" or when fewer than 2 repos.
*/
function buildRepoSet(batch) {
const sorted = collectRepoIds(batch);
return sorted.length >= 2 ? sorted : [];
}
/**
* Update the repo filter dropdown options and visibility.
* Resets selection to "All repos" if the previously selected repo disappeared.
*/
function updateRepoFilter(repos) {
knownRepos = repos;
const shouldShow = repos.length >= 2;
if (shouldShow !== repoFilterVisible) {
$repoFilter.style.display = shouldShow ? "" : "none";
repoFilterVisible = shouldShow;
}
if (!shouldShow) {
selectedRepo = "";
return;
}
// If selected repo disappeared, reset to "All"
if (selectedRepo && !repos.includes(selectedRepo)) {
selectedRepo = "";
}
// Rebuild options only if repo set changed
const currentOpts = Array.from($repoFilter.options).slice(1).map(o => o.value);
const changed = currentOpts.length !== repos.length || currentOpts.some((v, i) => v !== repos[i]);
if (changed) {
// Preserve selection
const prev = selectedRepo;
$repoFilter.innerHTML = '<option value="">All repos</option>';
for (const r of repos) {
const opt = document.createElement("option");
opt.value = r;
opt.textContent = r;
$repoFilter.appendChild(opt);
}
$repoFilter.value = prev;
}
}
/** Get the effective repo ID for a task (prefer resolvedRepoId, fallback repoId). */
function taskRepoId(task) {
return task.resolvedRepoId || task.repoId || undefined;
}
/** Render a repo badge span. Returns "" if repoId is falsy or repos not active. */
function repoBadgeHtml(repoId, extraClass) {
if (!repoId || knownRepos.length < 2) return "";
return `<span class="repo-badge ${extraClass || ""}" title="Repo: ${escapeHtml(repoId)}">${escapeHtml(repoId)}</span>`;
}
function parseSegmentId(segmentId) {
if (!segmentId || typeof segmentId !== "string") return null;
const sep = segmentId.indexOf("::");
if (sep <= 0 || sep >= segmentId.length - 2) return null;
return {
taskId: segmentId.slice(0, sep),
repoId: segmentId.slice(sep + 2),
};
}
function segmentProgressText(segmentInfo) {
if (!segmentInfo) return "";
const repo = segmentInfo.repoId || "unknown";
if (segmentInfo.index && segmentInfo.total) {
return `Segment ${segmentInfo.index}/${segmentInfo.total}: ${repo}`;
}
return `Segment: ${repo}`;
}
function buildSegmentStatusMap(batch) {
const map = new Map();
for (const seg of (batch?.segments || [])) {
if (seg && typeof seg.segmentId === "string") {
map.set(seg.segmentId, seg.status || "pending");
}
}
return map;
}
function taskSegmentProgress(task, segmentStatusMap, forcedActiveSegmentId) {
const segmentIds = Array.isArray(task?.segmentIds)
? task.segmentIds.filter(id => typeof id === "string")
: [];
// Repo-singleton (or repo-mode) tasks should stay visually clean.
if (segmentIds.length <= 1) return null;
const activeSegmentId = forcedActiveSegmentId || task.activeSegmentId;
let currentSegmentId = activeSegmentId && segmentIds.includes(activeSegmentId)
? activeSegmentId
: null;
if (!currentSegmentId) {
if (task.status === "pending" || task.status === "running") {
currentSegmentId = segmentIds.find((id) => {
const status = segmentStatusMap.get(id);
return !["succeeded", "failed", "stalled", "skipped"].includes(status);
}) || segmentIds[segmentIds.length - 1];
} else {
currentSegmentId = segmentIds[segmentIds.length - 1];
}
}
const idx = Math.max(0, segmentIds.indexOf(currentSegmentId));
const parsed = parseSegmentId(currentSegmentId);
return {
index: idx + 1,
total: segmentIds.length,
repoId: parsed?.repoId || taskRepoId(task) || undefined,
segmentId: currentSegmentId,
};
}
function laneActiveSegmentInfo(v2snap, laneTasks, segmentStatusMap) {
if (!v2snap || !v2snap.segmentId) return null;
const parsed = parseSegmentId(v2snap.segmentId);
if (!parsed) return null;
const ownerTaskId = v2snap.taskId || parsed.taskId;
const ownerTask = (laneTasks || []).find(t => t.taskId === ownerTaskId) || null;
if (ownerTask) {
const byTask = taskSegmentProgress(ownerTask, segmentStatusMap, v2snap.segmentId);
if (byTask) return byTask;
return null;
}
return {
index: null,
total: null,
repoId: parsed.repoId,
segmentId: v2snap.segmentId,
};
}
// Repo filter change handler
$repoFilter.addEventListener("change", (e) => {
selectedRepo = e.target.value;
// Re-render with current data
if (currentData) {
const batch = currentData.batch;
const sessions = currentData.sessions ?? currentData.tmuxSessions ?? [];
if (batch) {
renderLanesTasks(batch, sessions);
renderMergeAgents(batch, sessions);
}
}
});
// ─── Render: Header ─────────────────────────────────────────────────────────
function renderHeader(batch) {
if (!batch) {
$batchId.textContent = "—";
$batchPhase.textContent = "No batch";
$batchPhase.className = "header-badge badge-phase";
$workspaceMode.style.display = "none";
$submoduleStatus.style.display = "none";
return;
}
$batchId.textContent = batch.batchId;
$batchPhase.textContent = batch.phase;
$batchPhase.className = `header-badge badge-phase phase-${batch.phase}`;
if (batch.mode === "workspace") {
const repoIds = collectRepoIds(batch);
const repoCount = repoIds.length;
$workspaceMode.style.display = "";
$workspaceMode.textContent = `${repoCount} repo${repoCount === 1 ? "" : "s"}`;
$workspaceMode.title = repoCount > 0
? `Workspace batch spanning ${repoCount} repo${repoCount === 1 ? "" : "s"}`
: "Workspace batch";
} else {
$workspaceMode.style.display = "none";
}
if (batch.workspaceSyncStatus) {
$submoduleStatus.style.display = "";
$submoduleStatus.textContent = batch.workspaceSyncStatus.label;
$submoduleStatus.title = batch.workspaceSyncStatus.detail || "Workspace repo/submodule sync status";
$submoduleStatus.className = `header-badge badge-sync sync-${batch.workspaceSyncStatus.state}`;
} else {
$submoduleStatus.style.display = "none";
}
}
// ─── Render: Summary ────────────────────────────────────────────────────────
function renderSummary(batch) {
if (!batch) {
$progressBarBg.innerHTML = "";
$overallPct.textContent = "0%";
$summaryCounts.innerHTML = "";
$summaryElapsed.textContent = "—";
$summaryWaves.innerHTML = "";
return;
}
const tasks = batch.tasks || [];
const total = tasks.length;
const succeeded = tasks.filter(t => t.status === "succeeded").length;
const running = tasks.filter(t => t.status === "running").length;
const failed = tasks.filter(t => t.status === "failed").length;
const stalled = tasks.filter(t => t.status === "stalled").length;
const pending = tasks.filter(t => t.status === "pending").length;
// ── Checkbox-based progress by wave ──────────────────────────
const taskMap = new Map(tasks.map(t => [t.taskId, t]));
const wavePlan = batch.wavePlan || [tasks.map(t => t.taskId)]; // fallback: single wave
const currentWaveIdx = batch.currentWaveIndex || 0;
// TP-148: Build wave segment context — for each task appearing in multiple waves,
// determine which segment corresponds to each wave appearance.
const taskWaveAppearance = new Map(); // taskId → count of appearances so far
const waveSegmentLabels = wavePlan.map((taskIds) => {
const labels = new Map(); // taskId → label string
for (const tid of taskIds) {
const task = taskMap.get(tid);
const segmentIds = task?.segmentIds;
if (!segmentIds || segmentIds.length <= 1) continue;
const count = (taskWaveAppearance.get(tid) || 0);
taskWaveAppearance.set(tid, count + 1);
const segId = segmentIds[count];
if (segId) {
const parsed = parseSegmentId(segId);
const repo = parsed ? parsed.repoId : "";
labels.set(tid, `${tid} (segment ${count + 1}/${segmentIds.length}: ${repo})`);
}
}
return labels;
});
// Compute per-wave and overall checkbox totals
let batchChecked = 0, batchTotal = 0;
const waveStats = wavePlan.map((taskIds, waveIdx) => {
let wChecked = 0, wTotal = 0;
let allSucceeded = taskIds.length > 0;
for (const tid of taskIds) {
const t = taskMap.get(tid);
if (!t || t.status !== "succeeded") allSucceeded = false;
if (t && t.status === "succeeded" && t.statusData) {
// Succeeded task with statusData: count as fully done even if
// STATUS.md checkboxes weren't all ticked before .DONE was created
const total = t.statusData.total || 1;
wChecked += total;
wTotal += total;
} else if (t && t.statusData) {
wChecked += t.statusData.checked || 0;
wTotal += t.statusData.total || 0;
} else if (t && t.status === "succeeded") {
// Succeeded tasks may not have statusData if STATUS.md was cleaned up
// Count as fully done — use a small placeholder if no data
wChecked += 1;
wTotal += 1;
}
}
batchChecked += wChecked;
batchTotal += wTotal;
return { waveIdx, taskIds, checked: wChecked, total: wTotal, allSucceeded };
});
const overallPct = batchTotal > 0 ? Math.round((batchChecked / batchTotal) * 100) : 0;
$overallPct.textContent = `${overallPct}%`;
// Build segmented progress bar — each wave gets a proportional segment
let barHtml = "";
for (const ws of waveStats) {
const segWidthPct = batchTotal > 0 ? (ws.total / batchTotal) * 100 : (100 / waveStats.length);
const fillPct = ws.total > 0 ? (ws.checked / ws.total) * 100 : 0;
const checkboxDone = ws.checked === ws.total && ws.total > 0;
const pastWave = ws.waveIdx < currentWaveIdx;
const batchDone = batch.phase === "completed";
// TP-178: During merging, only past waves are truly done. The current wave's
// checkboxDone/allSucceeded can be true (tasks finished) but the wave itself
// isn't done until the merge completes. (#493)
const isMerging = batch.phase === "merging";
const isDone = batchDone || pastWave || (!isMerging && (checkboxDone || ws.allSucceeded));
const isMergingWave = isMerging && ws.waveIdx === currentWaveIdx;
const isCurrent = ws.waveIdx === currentWaveIdx && (batch.phase === "executing" || isMerging);
const isFuture = ws.waveIdx > currentWaveIdx && (batch.phase === "executing" || isMerging);
const fillClass = isDone ? "pct-hi" : fillPct > 50 ? "pct-mid" : fillPct > 0 ? "pct-low" : "pct-0";
const fillWidth = isDone ? 100 : fillPct;
// TP-178: Add merging visual state for the wave currently being merged (#493)
const segClass = isMergingWave ? "wave-seg-current wave-seg-merging" : isCurrent ? "wave-seg-current" : isFuture ? "wave-seg-future" : "";
// TP-148: Use segment-aware labels in tooltip when available
const segLabels = waveSegmentLabels[ws.waveIdx] || new Map();
const tooltipTasks = ws.taskIds.map(tid => segLabels.get(tid) || tid).join(', ');
barHtml += `<div class="wave-seg ${segClass}" style="width:${segWidthPct.toFixed(1)}%" title="W${ws.waveIdx + 1}: ${ws.checked}/${ws.total} checkboxes (${tooltipTasks})">`;
barHtml += ` <div class="wave-seg-fill ${fillClass}" style="width:${fillWidth.toFixed(1)}%"></div>`;
barHtml += ` <span class="wave-seg-label">W${ws.waveIdx + 1}</span>`;
barHtml += `</div>`;
}
$progressBarBg.innerHTML = barHtml;
let countsHtml = "";
if (succeeded > 0) countsHtml += `<span class="count-chip count-succeeded"><span class="count-num">${succeeded}</span><span class="count-icon">✓</span></span>`;
if (running > 0) countsHtml += `<span class="count-chip count-running"><span class="count-num">${running}</span><span class="count-icon">▶</span></span>`;
if (failed > 0) countsHtml += `<span class="count-chip count-failed"><span class="count-num">${failed}</span><span class="count-icon">✗</span></span>`;
if (stalled > 0) countsHtml += `<span class="count-chip count-stalled"><span class="count-num">${stalled}</span><span class="count-icon">⏸</span></span>`;
if (pending > 0) countsHtml += `<span class="count-chip count-pending"><span class="count-num">${pending}</span><span class="count-icon">◌</span></span>`;
countsHtml += `<span class="count-total">/ ${total}</span>`;
$summaryCounts.innerHTML = countsHtml;
const elapsed = batch.startedAt ? Date.now() - batch.startedAt : 0;
let elapsedStr = `elapsed: ${formatDuration(elapsed)}`;
if (batch.updatedAt) elapsedStr += ` · updated: ${relativeTime(batch.updatedAt)}`;
// Aggregate tokens/cost for summary.
// Runtime V2 snapshots are authoritative when present; legacy lane-state sidecars are fallback.
const laneStates = currentData?.laneStates || {};
const runtimeLaneSnapshots = currentData?.runtimeLaneSnapshots || {};
const v2Snaps = Object.values(runtimeLaneSnapshots);
let batchInput = 0, batchOutput = 0, batchCacheRead = 0, batchCacheWrite = 0, batchCostFromSnapshots = 0;
if (v2Snaps.length > 0) {
for (const snap of v2Snaps) {
const w = snap?.worker || {};
batchInput += w.inputTokens || 0;
batchOutput += w.outputTokens || 0;
batchCacheRead += w.cacheReadTokens || 0;
batchCacheWrite += w.cacheWriteTokens || 0;
batchCostFromSnapshots += w.costUsd || 0;
const r = snap?.reviewer || null;
if (r) {
batchInput += r.inputTokens || 0;
batchOutput += r.outputTokens || 0;
batchCacheRead += r.cacheReadTokens || 0;
batchCacheWrite += r.cacheWriteTokens || 0;
batchCostFromSnapshots += r.costUsd || 0;
}
}
} else {
// Legacy fallback
for (const ls of Object.values(laneStates)) {
batchInput += ls.workerInputTokens || 0;
batchOutput += ls.workerOutputTokens || 0;
batchCacheRead += ls.workerCacheReadTokens || 0;
batchCacheWrite += ls.workerCacheWriteTokens || 0;
batchCostFromSnapshots += ls.workerCostUsd || 0;
}
}
// Keep server-computed cost as fallback for uncovered early-start lanes.
const batchCost = batchCostFromSnapshots > 0
? batchCostFromSnapshots
: ((currentData?.batchTotalCost != null && currentData.batchTotalCost > 0)
? currentData.batchTotalCost
: 0);
const batchTotalIn = batchInput + batchCacheRead;
if (batchTotalIn > 0 || batchOutput > 0) {
let tokenStr = ` · tokens: ↑${formatTokens(batchTotalIn)} ↓${formatTokens(batchOutput)}`;
if (batchCost > 0) tokenStr += ` · cost: ${formatCost(batchCost)}`;
elapsedStr += tokenStr;
}
$summaryElapsed.textContent = elapsedStr;
// Waves
if (batch.wavePlan && batch.wavePlan.length > 0) {
const waveIdx = batch.currentWaveIndex || 0;
let wavesHtml = '<span style="color:var(--text-muted); font-weight:600; margin-right:4px;">Waves</span>';
batch.wavePlan.forEach((taskIds, i) => {
// TP-178: During merging, only past waves are done; current wave shows merging state (#493)
const isDone = i < waveIdx || batch.phase === "completed";
const isCurrent = i === waveIdx && (batch.phase === "executing" || batch.phase === "merging");
const isMergingChip = i === waveIdx && batch.phase === "merging";
const cls = isDone ? "done" : isMergingChip ? "current merging" : isCurrent ? "current" : "";
wavesHtml += `<span class="wave-chip ${cls}">W${i + 1} [${taskIds.join(", ")}]</span>`;
});
$summaryWaves.innerHTML = wavesHtml;
} else {
$summaryWaves.innerHTML = "";
}
}
// ─── Render: Lanes + Tasks (integrated) ─────────────────────────────────────
function renderLanesTasks(batch, sessions) {
if (!batch || !batch.lanes || batch.lanes.length === 0) {
$lanesTasksBody.innerHTML = '<div class="empty-state">No lanes</div>';
return;
}
const tasks = batch.tasks || [];
const sessionSet = new Set(sessions || []);
const laneStates = currentData?.laneStates || {};
const telemetry = currentData?.telemetry || {};
// TP-107: V2 lane snapshots take precedence over legacy lane states when present
const v2Snapshots = currentData?.runtimeLaneSnapshots || {};
const showRepos = knownRepos.length >= 2;
const segmentStatusMap = buildSegmentStatusMap(batch);
let html = "";
for (const lane of batch.lanes) {
const laneTasks = (lane.taskIds || []).map(tid => tasks.find(t => t.taskId === tid)).filter(Boolean);
const v2snap = v2Snapshots[lane.laneNumber] || null;
const laneActiveSegment = laneActiveSegmentInfo(v2snap, laneTasks, segmentStatusMap);
// Repo filtering: if a repo is selected, skip lanes that don't match
if (selectedRepo && showRepos) {
const laneMatchesRepo = (lane.repoId === selectedRepo) ||
laneTasks.some(t => (taskRepoId(t) || lane.repoId) === selectedRepo);
if (!laneMatchesRepo) continue;
}
// TP-107: check Runtime V2 registry for liveness first, fall back to session list
const laneSessionId = lane.laneSessionId;
const v2Alive = isLaneAliveV2(lane.laneNumber);
const alive = v2Alive !== null ? v2Alive : sessionSet.has(laneSessionId);
// Lane header
html += `<div class="lane-group">`;
html += `<div class="lane-header">`;
html += ` <span class="lane-num">${lane.laneNumber}</span>`;
html += ` <div class="lane-meta">`;
html += ` <span class="lane-session">${escapeHtml(laneSessionId || "—")}</span>`;
html += ` <span class="lane-branch">${escapeHtml(lane.branch || "—")}</span>`;
if (showRepos && lane.repoId) {
html += ` ${repoBadgeHtml(lane.repoId, "repo-badge-lane")}`;
}
if (laneActiveSegment) {
html += ` <span class="lane-segment" title="${escapeHtml(laneActiveSegment.segmentId || segmentProgressText(laneActiveSegment))}">${escapeHtml(segmentProgressText(laneActiveSegment))}</span>`;
}
html += ` </div>`;
html += ` <div class="lane-right">`;
html += ` <span class="session-dot ${alive ? "alive" : "dead"}" title="${alive ? "session alive" : "session not active"}"></span>`;
// View button: shows conversation stream when available
const isViewingConv = viewerMode === 'conversation' && viewerTarget === laneSessionId;
html += ` <button class="session-view-btn${isViewingConv ? ' active' : ''}" onclick="viewConversation('${escapeHtml(laneSessionId)}')" title="View worker conversation">👁 View</button>`;
html += ` </div>`;
html += `</div>`;
// Task rows for this lane
if (laneTasks.length === 0) {
html += `<div class="task-row"><span class="task-icon"></span><span style="color:var(--text-faint);grid-column:2/-1;">No tasks assigned</span></div>`;
}
// Get lane state and telemetry for worker stats
// TP-107: V2 lane snapshots take precedence when present
const legacyLs = laneStates[laneSessionId] || null;
const ls = v2snap ? mergeV2LaneSnapshot(legacyLs, v2snap) : legacyLs;
const tel = telemetry[laneSessionId] || null;
for (const task of laneTasks) {
// Repo filtering at task level
const tRepo = taskRepoId(task) || lane.repoId;
if (selectedRepo && showRepos && tRepo !== selectedRepo) continue;
const sd = task.statusData;
const dur = task.startedAt
? formatDuration((task.endedAt || Date.now()) - task.startedAt)
: "—";
const segmentInfo = taskSegmentProgress(task, segmentStatusMap, null);
const packetHomeRepo = typeof task.packetRepoId === "string" ? task.packetRepoId : "";
const showPacketHome = !!packetHomeRepo && packetHomeRepo !== (tRepo || lane.repoId || "");
// Progress cell
// TP-174: Prefer V2 snapshot progress (segment-scoped when available)
// over full STATUS.md counts when the task is actively running on this lane.
// TP-176: Succeeded tasks always show 100% regardless of sidecar/statusData (#491).
let progressHtml = "";
const v2p = ls && ls._v2Progress;
const taskMatch = v2p && ls.taskId === task.taskId;
// Split V2 usage: progress needs totals > 0, but step/iter can be used whenever present
const useV2Progress = taskMatch && v2p.total > 0;
const useV2Step = taskMatch && !!v2p.currentStep;
if (task.status === "succeeded") {
// #491 fix: succeeded tasks always show 100%
progressHtml = `
<div class="task-progress">
<div class="task-progress-bar"><div class="task-progress-fill pct-hi" style="width:100%"></div></div>
<span class="task-progress-text">100%</span>
</div>`;
} else if (useV2Progress || (sd && sd.total > 0)) {
const displayChecked = useV2Progress ? v2p.checked : sd.checked;
const displayTotal = useV2Progress ? v2p.total : sd.total;
const displayProgress = displayTotal > 0 ? Math.round((displayChecked / displayTotal) * 100) : 0;
const fillClass = pctClass(displayProgress);
progressHtml = `
<div class="task-progress">
<div class="task-progress-bar">
<div class="task-progress-fill ${fillClass}" style="width:${displayProgress}%"></div>
</div>
<span class="task-progress-text">${displayProgress}% ${displayChecked}/${displayTotal}</span>
</div>`;
} else if (task.status === "running") {
// #494 fix: running tasks without meaningful totals show executing indicator
// This covers non-final segments, early execution before sidecar captures, and stale 0/0 data
progressHtml = `
<div class="task-progress">
<div class="task-progress-bar"><div class="task-progress-fill pct-low task-progress-executing" style="width:100%"></div></div>
<span class="task-progress-text">executing…</span>
</div>`;
} else if (task.status === "pending") {
progressHtml = `
<div class="task-progress">
<div class="task-progress-bar"><div class="task-progress-fill pct-0" style="width:0%"></div></div>
<span class="task-progress-text">0%</span>
</div>`;
} else {
progressHtml = '<span style="color:var(--text-faint)">—</span>';
}
// Step cell
// TP-178: Prefer V2 snapshot currentStep (refreshed every sidecar poll) over
// server-parsed statusData which can lag behind (#488).
let stepHtml = "";
if (task.status === "succeeded") {
// TP-178: Succeeded tasks always show "Complete" regardless of sidecar data (#491)
stepHtml = '<span style="color:var(--green)">Complete</span>';
} else if (sd || useV2Step) {
// #488 fix: prefer V2 step name whenever present (even if totals are 0)
const stepName = useV2Step ? v2p.currentStep : (sd ? sd.currentStep : "Unknown");
const iter = (useV2Step && v2p.iteration != null) ? v2p.iteration : (sd ? sd.iteration : 0);
const revs = (useV2Step && v2p.reviews != null) ? v2p.reviews : (sd ? sd.reviews : 0);
stepHtml = escapeHtml(stepName);
if (iter > 0) stepHtml += `<span class="task-iter">i${iter}</span>`;
if (revs > 0) stepHtml += `<span class="task-iter">r${revs}</span>`;
} else if (task.status === "pending") {
stepHtml = '<span style="color:var(--text-faint)">Waiting</span>';
} else {
stepHtml = `<span style="color:var(--text-faint)">${escapeHtml(task.exitReason || "—")}</span>`;
}
const detailBits = [];
if (segmentInfo) {
detailBits.push(`<span class="task-segment-progress" title="${escapeHtml(segmentInfo.segmentId || segmentProgressText(segmentInfo))}">${escapeHtml(segmentProgressText(segmentInfo))}</span>`);
}
if (showPacketHome) {
detailBits.push(`<span class="task-packet-home" title="Task packet home repo">packet: ${escapeHtml(packetHomeRepo)}</span>`);
}
if (detailBits.length > 0) {
stepHtml = `${detailBits.join('<span class="task-detail-sep"> · </span>')}<span class="task-detail-sep"> · </span><span class="task-step-main">${stepHtml}</span>`;
}
// Worker stats from lane state sidecar + telemetry badges
let workerHtml = "";
// Reviewer sub-row should only appear under the active running task in this lane.
// Runtime V2 snapshots provide taskId; during early startup it can be briefly unset,
// so allow a task-status fallback while still avoiding duplicate rows.
const reviewerActive = isReviewerActiveForTask(ls, task);
const telemBadges = task.status !== "pending" ? telemetryBadgesHtml(tel, reviewerActive) : "";
if (ls && ls.workerStatus === "running" && task.status === "running") {
const elapsed = ls.workerElapsed ? `${Math.round(ls.workerElapsed / 1000)}s` : "";
const tools = ls.workerToolCount || 0;
const ctx = ls.workerContextPct ? `${Math.round(ls.workerContextPct)}%` : "";
const lastTool = reviewerActive ? "[awaiting review]" : (ls.workerLastTool || "");
const tokenStr = tokenSummaryFromLaneState(ls);
workerHtml = `<div class="worker-stats">`;
workerHtml += `<span class="worker-stat" title="Worker elapsed">⏱ ${elapsed}</span>`;
workerHtml += `<span class="worker-stat" title="Tool calls">🔧 ${tools}</span>`;
if (ctx) workerHtml += `<span class="worker-stat" title="Context window used">📊 ${ctx}</span>`;
if (tokenStr) workerHtml += `<span class="worker-stat" title="Tokens: input↑ output↓ cacheRead(R) cacheWrite(W)">🪙 ${tokenStr}</span>`;
if (lastTool) workerHtml += `<span class="worker-stat worker-last-tool" title="${reviewerActive ? 'Waiting for reviewer' : 'Last tool call'}">${reviewerActive ? '<span style="color:var(--yellow)">' + escapeHtml(lastTool) + '</span>' : escapeHtml(lastTool)}</span>`;
workerHtml += telemBadges;
workerHtml += `</div>`;
} else if (!ls && tel && task.status === "running") {
// Running task with telemetry but no lane-state yet (early startup)
const lastTool = tel.lastTool || "";
workerHtml = `<div class="worker-stats">`;
if (lastTool) workerHtml += `<span class="worker-stat worker-last-tool" title="Last tool call">${escapeHtml(lastTool)}</span>`;
workerHtml += telemBadges;
workerHtml += `</div>`;
} else if (ls && ls.workerStatus === "done" && task.status !== "pending") {
workerHtml = `<div class="worker-stats"><span class="worker-stat" style="color:var(--green)">✓ Worker done</span>${telemBadges}</div>`;
} else if (ls && ls.workerStatus === "error" && task.status !== "pending") {
workerHtml = `<div class="worker-stats"><span class="worker-stat" style="color:var(--red)">✗ Worker error</span>${telemBadges}</div>`;
} else if (telemBadges && task.status !== "pending") {
// No lane-state but telemetry exists (done/error lane without sidecar)
workerHtml = `<div class="worker-stats">${telemBadges}</div>`;
}
// Reviewer sub-row: shown when reviewer is actively running
let reviewerRowHtml = "";
if (reviewerActive) {
const rElapsed = ls.reviewerElapsed ? `${Math.round(ls.reviewerElapsed / 1000)}s` : "";
const rTools = ls.reviewerToolCount || 0;
const rCtx = ls.reviewerContextPct ? `${Math.round(ls.reviewerContextPct)}%` : "";
const rLastTool = ls.reviewerLastTool || "";
const rTokenStr = tokenSummaryFromReviewerLaneState(ls);
const rType = ls.reviewerType || "review";
const rStep = ls.reviewerStep || "?";
reviewerRowHtml = `
<div class="task-row reviewer-sub-row">
<span class="task-icon"></span>
<span class="task-actions"></span>
<span class="reviewer-label">📋 Reviewer</span>
<span class="reviewer-type">${escapeHtml(rType)} · Step ${rStep}</span>
<span class="task-duration"></span>
<span></span>
<span class="task-step">
<div class="worker-stats reviewer-stats">
<span class="worker-stat" title="Reviewer elapsed">⏱ ${rElapsed}</span>
<span class="worker-stat" title="Reviewer tool calls">🔧 ${rTools}</span>
${rCtx ? `<span class="worker-stat" title="Reviewer context used">📊 ${rCtx}</span>` : ""}
${rTokenStr ? `<span class="worker-stat" title="Reviewer tokens: input↑ output↓ cacheRead(R) cacheWrite(W)">🪙 ${rTokenStr}</span>` : ""}
${rLastTool ? `<span class="worker-stat worker-last-tool" title="Reviewer last tool">${escapeHtml(rLastTool)}</span>` : ""}
</div>
</span>
</div>`;
}
const isViewingStatus = viewerMode === 'status-md' && viewerTarget === task.taskId;
const eyeHtml = task.status !== 'pending'
? `<button class="viewer-eye-btn${isViewingStatus ? ' active' : ''}" onclick="viewStatusMd('${escapeHtml(task.taskId)}')" title="View STATUS.md">👁</button>`
: '';
html += `
<div class="task-row">
<span class="task-icon"><span class="status-dot ${task.status}"></span></span>
<span class="task-actions">${eyeHtml}</span>
<span class="task-id status-${task.status}">${escapeHtml(task.taskId)}${showRepos ? repoBadgeHtml(tRepo, "repo-badge-task") : ""}</span>
<span><span class="status-badge status-${task.status}"><span class="status-dot ${task.status}"></span> ${task.status}</span></span>
<span class="task-duration">${dur}</span>
<span>${progressHtml}</span>
<span class="task-step">${stepHtml}${workerHtml}</span>
</div>`;
html += reviewerRowHtml;
}
html += `</div>`; // close lane-group
}
$lanesTasksBody.innerHTML = html;
}
// ─── Render: Merge Agents ───────────────────────────────────────────────────
/** Build full telemetry HTML for a merge agent (parity with worker stats).
* Shows: elapsed, tool count, context %, cost, current tool, retry/compaction badges.
* Returns empty string if no meaningful telemetry exists.
*/
function mergeTelemetryHtml(tel, alive) {
if (!tel) return '<span class="merge-no-data">—</span>';
const hasData = (tel.inputTokens || 0) > 0 || (tel.outputTokens || 0) > 0 ||
(tel.toolCalls || 0) > 0 || (tel.cost || 0) > 0;
if (!hasData) return '<span class="merge-no-data">—</span>';
let html = '<div class="merge-stats">';
// Elapsed time
if (tel.startedAt) {
const elapsed = Date.now() - tel.startedAt;
html += `<span class="worker-stat" title="Merge elapsed">⏱ ${formatDuration(elapsed)}</span>`;
}
// Tool calls
if (tel.toolCalls > 0) {
html += `<span class="worker-stat" title="Tool calls">🔧 ${tel.toolCalls}</span>`;
}
// Context %
if (tel.contextPct > 0) {
html += `<span class="worker-stat" title="Context window used">📊 ${Math.round(tel.contextPct)}%</span>`;
}
// Tokens + cost
const inp = (tel.inputTokens || 0) + (tel.cacheReadTokens || 0);
const out = tel.outputTokens || 0;
const cost = tel.cost || 0;
if (inp > 0 || out > 0) {
let tokenStr = `↑${formatTokens(inp)} ↓${formatTokens(out)}`;
if (cost > 0) tokenStr += ` ${formatCost(cost)}`;
html += `<span class="worker-stat" title="Tokens">🪙 ${tokenStr}</span>`;
}
// Current tool (if alive/active) or last tool (completed merges)
if (alive && tel.currentTool) {
html += `<span class="worker-stat worker-last-tool" title="Current tool">${escapeHtml(tel.currentTool)}</span>`;
} else if (!alive && tel.lastTool) {
html += `<span class="worker-stat worker-last-tool" title="Last tool">${escapeHtml(tel.lastTool)}</span>`;
}
// Retry/compaction badges (reuse shared helper)
html += telemetryBadgesHtml(tel);
html += '</div>';
return html;
}
function renderMergeAgents(batch, sessions) {
const mergeResults = batch?.mergeResults || [];
const sessionSet = new Set(sessions || []);
const showRepos = knownRepos.length >= 2;
const telemetry = currentData?.telemetry || {};
// Check for active merge sessions (convention: {prefix}-{opId}-merge-{N})
const mergeSessions = (sessions || []).filter(s => s.includes("-merge-"));
// Derive merge session name from lane session naming pattern.
// Lane sessions: "{prefix}-{opId}-lane-{N}", merge sessions: "{prefix}-{opId}-merge-{N}".
// Extract the prefix-opId part from the first lane and use it to construct merge names.
const lanes = batch?.lanes || [];
let mergePrefix = "orch-merge"; // fallback for legacy/unknown patterns
if (lanes.length > 0 && lanes[0].laneSessionId) {
const laneName = lanes[0].laneSessionId;
const laneMatch = laneName.match(/^(.+)-lane-\d+$/);
if (laneMatch) {
mergePrefix = laneMatch[1] + "-merge";
}
}
// Helper: get merge session name for a merge number
const getMergeSessionName = (mergeNum) => `${mergePrefix}-${mergeNum}`;
if (mergeResults.length === 0 && mergeSessions.length === 0) {
$mergeBody.innerHTML = '<div class="empty-state">No merge agents active</div>';
return;
}
let html = '<table class="merge-table"><thead><tr>';
html += '<th>Wave</th><th>Status</th><th>Session</th><th>Telemetry</th><th>Session ID</th><th>Details</th>';
html += '</tr></thead><tbody>';
// Track sessions shown in wave result rows so we don't duplicate them below