mahbot 0.5.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
//! "Running Agents" dashboard page — a live view of every currently-running
//! agent and in-flight non-agent LLM work, grouped by WORKSPACE, then by
//! DIRECT PARENT INVOCATION (ticket / analyze round / research run / workspace
//! singleton / unattributable orchestrator calls).
//!
//! The view is read-only: at render time it reads the in-memory registries
//! (`AGENT_REGISTRY` and `NON_AGENT_CALLS`) plus the live transcript snapshots
//! (`TRANSCRIPT_REGISTRY`), so it reflects the live in-memory conversation
//! including the unpersisted tail. No database reads, no schema changes, no
//! history retained between ticks. Re-renders are driven by coalesced runtime
//! change events (agent/non-agent registries, live transcript content, voice
//! status) — the GUI refreshes as activity happens, not on a fixed cadence.
//!
//! Truthfulness rules:
//! - The card's first row is the role icon followed inline by the token/elapsed
//!   metrics (collapsed and expanded alike), with no fill spacers; the rest of
//!   the card content (thinking fallback, trace groups, tool blocks, activity
//!   line) starts on the second row at the card's left edge. Narration (the
//!   assistant's short reasoning text) is shown exactly once — as the current
//!   (latest) trace-group label, which shows a neutral "clanking" placeholder
//!   while its narration hasn't committed; a brand-new agent — or a current
//!   user turn with no tool rounds yet — shows a card-level "clanking"
//!   placeholder. The narration renders at 14px italic, never truncated — the
//!   full reasoning text stays a hover tooltip — while a silent round (empty
//!   narration) with a decoded Reasoning block promotes that reasoning into
//!   the label: capped, plain, no tooltip. The live activity phase label (a
//!   non-tool LLM call) renders as a separate line at the very bottom of the
//!   card in both the collapsed and expanded state.
//!   In-flight tool state is derived from the live transcript history: a tool
//!   call whose result has not been committed yet renders with a live
//!   in-flight marker. Only non-tool LLM phases remain invisible in the
//!   transcript and are still shown solely by the registry activity label.
//! - Trace groups (below the LIVE line) are a projection of the shared
//!   session ledger (the live transcript snapshot decoded via
//!   `session_view::build_ledger`): tool-call assistant rounds grouped by
//!   shared narration, bounded by real user turns. Content-only final answers
//!   are omitted.
//! - The trace groups shown on a card are scoped to the CURRENT user turn:
//!   groups from before the last real user message are never shown.
//! - Parallel tool execution is a history-derived over-approximation: a call
//!   shows as in-flight while its result is uncommitted (its tool-call round
//!   is already in the ledger) — finished-but-uncommitted calls in a parallel
//!   batch, unknown/pre-flight-cancelled calls before their round commits,
//!   and drain-suspended calls all appear in-flight. This is accepted for an
//!   observability view; tools that never produce a committed round simply
//!   never appear.
//! - The instrumentation is purely observational — it never affects
//!   shutdown/drain logic and gains no cancellation semantics.
//! - The live view shows tool arguments EXACTLY as the agent passed them —
//!   including any secrets. This is a deliberate, documented divergence from
//!   the durable logs (tool-call stats, failure feedback), which remain
//!   credential-scrubbed: the live view is transient and exists for full
//!   visibility of what the agent is doing.
//!
//! The page is DB-free by design: everything it shows is derived from the
//! live in-memory registries and the live transcript snapshots, plus the
//! dashboard's registered-workspace map (only for the "(external)" marker on
//! unregistered/ephemeral workspace sections). All header labels (ticket
//! titles, analyze/research questions) are captured observationally at spawn —
//! never read from the DB.

use std::collections::HashMap;
use std::collections::HashSet;

use crate::ChatRole;
use crate::agent::registry::{AgentHandle, NonAgentCallHandle, ParentKey};
use crate::gui::dialog;
use crate::gui::session_view::{
    MAX_TOOL_TOOLTIP_WIDTH, SessionEntry, ToolBlockView, ToolCallEntry, build_ledger,
    collapse_control_chars, promoted_reasoning, tool_block, truncate_at_boundary,
};
use crate::gui::theme;
use crate::gui::widgets;
use chrono::{DateTime, Utc};

use iced::widget::{
    Column, Row, Space, button, column, container, mouse_area, row, stack, text, tooltip,
};
use iced::{Alignment, Element, Length};

use iced_fonts::lucide;

use super::Message;

use crate::Workspace;

/// Maximum display length (Unicode chars) of an analyze/research group header
/// label (the question/task text). Truncated at a word/path-delimiter boundary
/// with "…" (see [`truncate_at_boundary`]).
const MAX_GROUP_LABEL_CHARS: usize = 104;

/// Maximum width (px) of a metric hover tooltip body. Much narrower than
/// [`MAX_TOOL_TOOLTIP_WIDTH`] (tuned for multi-arg tool calls) since a metric
/// tooltip holds one short line of explanatory text.
const MAX_METRIC_TOOLTIP_WIDTH: f32 = 360.0;

/// Messages emitted by the Running Agents page.
///
/// The page itself stays stateless — the pending research-cancel
/// confirmation lives on the [`Dashboard`](super::Dashboard) so the dialog
/// requires no per-run page state beyond the pending confirmation itself.
#[derive(Debug, Clone)]
pub(crate) enum RunningMessage {
    /// Cancel button pressed on a research-run group header. Carries the
    /// run's durable job id — NEVER rendered as text; the button action
    /// alone carries it.
    CancelRequest(String),
    /// The confirmation dialog's danger button — start the async cancel.
    CancelConfirmed,
    /// Keep/Dismiss (or Escape/backdrop) — close the dialog with no effect.
    CancelDismissed,
    /// The async cancel finished: the run stopped and the cleanup agent is
    /// removing its traces (cancel_research_run is infallible).
    CancelFinished,
    /// Toggle the expanded/collapsed state of a running-agent card. Keyed by
    /// (agent_id, generation) so a recycled agent_id never inherits a stale
    /// expansion.
    ToggleAgentExpanded { agent_id: String, generation: u64 },
}

/// Render the live running-agents page.
///
/// The page is observational — it reads the live in-memory registries and
/// renders directly into the dashboard's [`Message`] type; its only
/// self-emitted messages are the research-run manual-cancel flow
/// ([`RunningMessage`]) and the card expand/collapse toggle. `workspaces` is
/// the dashboard's registered-workspace map (name → info) — used only to mark
/// unregistered/ephemeral workspace sections with the "(external)" suffix.
/// Everything else comes from the live in-memory registries.
///
/// `expanded` is the dashboard's set of expanded agent cards, keyed by
/// (agent_id, generation). Stale keys are pruned by the dashboard's
/// `RuntimeChanged` handler against the freshly-listed agents; rendering here
/// only reads the set.
pub(crate) fn view(
    workspaces: &HashMap<String, Workspace>,
    pending_cancel: Option<&str>,
    expanded: &HashSet<(String, u64)>,
) -> Element<'static, Message> {
    let agents = crate::agent::registry::AGENT_REGISTRY.list();
    let calls = crate::agent::registry::NON_AGENT_CALLS.list();

    // Workspace-first sections: each section holds its groups, groups
    // sorted by kind (tickets → analyze rounds → research runs →
    // singletons → unattributed), sections alphabetically by name.
    let sections = build_sections(build_groups(&agents, &calls), workspaces);

    let body: Element<'_, RunningMessage> = if sections.is_empty() {
        // Shared empty-state pattern: large radar glyph (the page's nav
        // icon) + label, centered.
        widgets::empty_state_placeholder(
            lucide::radar::<iced::Theme, iced::Renderer>(),
            "Nothing is currently running.",
            theme::TEXT_MUTED,
        )
    } else {
        let mut content = Column::new().spacing(theme::SPACE_20);
        for section in &sections {
            content = content.push(render_section(section, expanded));
        }
        widgets::vscroll(content)
    };

    // Uniform page chrome with the rest of the dashboard: base Flexoki
    // fill + 24px padding, matching the other pages.
    let page: Element<'_, RunningMessage> = container(body)
        .width(Length::Fill)
        .height(Length::Fill)
        .padding(theme::PAGE_PADDING)
        .style(theme::base_container_style)
        .into();
    // Confirm-dialog overlay: the page content is stack child 0, the dialog
    // (or a type-stable placeholder) child 1 — the widget shapes never
    // change, so no page state is lost when the dialog opens/closes.
    let confirm_layer: Element<'_, RunningMessage> = if let Some(run_key) = pending_cancel {
        cancel_confirm_dialog(run_key)
    } else {
        stack([widgets::empty_stack_placeholder()]).into()
    };
    let stacked: Element<'_, RunningMessage> = stack([page, confirm_layer]).into();
    stacked.map(Message::RunningAgents)
}

// ── Display model ─────────────────────────────────────────────────────────

/// One running work item: either an agent card or a non-agent LLM call row.
/// The agent card is boxed — `AgentHandle` is large and the variant would
/// otherwise dominate the enum's size (clippy::large_enum_variant).
#[derive(Debug, Clone)]
enum DisplayItem {
    Agent(Box<AgentCard>),
    Call(CallRow),
}

#[derive(Debug, Clone)]
struct AgentCard {
    handle: AgentHandle,
}

#[derive(Debug, Clone)]
struct CallRow {
    handle: NonAgentCallHandle,
}

/// Ordered group kinds — the page's display order.
#[derive(Debug, Clone, PartialEq, Eq)]
enum GroupKind {
    Ticket,
    AnalyzeRound,
    Research,
    Singleton,
    Unattributed,
}

#[derive(Debug, Clone)]
struct DisplayGroup {
    kind: GroupKind,
    /// Group key (ticket id / round key / run key / workspace name).
    key: String,
    /// Workspace name for the group header.
    workspace: String,
    /// Human-readable header label for the group (ticket title / analyze
    /// question / research question), captured observationally from any
    /// member's `parent_label`. `None` for singletons/unattributed and for
    /// parent-keyed groups whose members carried no label (defensive fallback
    /// — the header then degrades to a generic label, never a raw key).
    label: Option<String>,
    items: Vec<DisplayItem>,
    /// True when this research group carries a run-lifetime orchestrator
    /// marker (rendered as a run-lifetime indicator, not a call row).
    run_lifetime: bool,
}

/// One workspace section on the page: the groups running in one workspace,
/// keyed by the raw workspace name and ordered by its resolved label.
#[derive(Debug, Clone)]
struct WorkspaceSection {
    /// Raw workspace name — the grouping key.
    workspace: String,
    /// Resolved display label: the bare name for registered workspaces, the
    /// "(external)"-suffixed form for unregistered/ephemeral ones, and
    /// "workspace" for an empty name.
    label: String,
    groups: Vec<DisplayGroup>,
}

impl DisplayGroup {
    /// (order, key) — groups sort by kind order first, then by key within
    /// the kind (stable, deterministic).
    fn sort_key(&self) -> (u8, String) {
        let order = match self.kind {
            GroupKind::Ticket => 0,
            GroupKind::AnalyzeRound => 1,
            GroupKind::Research => 2,
            GroupKind::Singleton => 3,
            GroupKind::Unattributed => 4,
        };
        (order, self.key.clone())
    }
}

/// Map a parent key to its display group kind — the DIRECT PARENT INVOCATION
/// the work item belongs to.
fn parent_group_kind(parent: &ParentKey) -> GroupKind {
    match parent {
        ParentKey::Ticket(_) => GroupKind::Ticket,
        ParentKey::AnalyzeRound(_) => GroupKind::AnalyzeRound,
        ParentKey::Research(_) => GroupKind::Research,
    }
}

/// The group key payload for a parent key (ticket id / round key / run key).
fn parent_group_key(parent: &ParentKey) -> &str {
    match parent {
        ParentKey::Ticket(id) => id,
        ParentKey::AnalyzeRound(key) | ParentKey::Research(key) => key,
    }
}

/// Group the running agents and non-agent calls by DIRECT PARENT INVOCATION.
///
/// - Tickets: agents with a [`ParentKey::Ticket`] plus calls with the same
///   ticket parent.
/// - Analyze rounds: agents + calls sharing an [`ParentKey::AnalyzeRound`] key.
/// - Research runs: agents + calls sharing a [`ParentKey::Research`] key.
/// - Workspace singletons: agents with no parent key (manager / maintainer /
///   discovery / direct chat).
/// - Unattributed: non-agent calls with no parent key (workspace-scoped).
///
/// Group identity is (kind, key) plus — for everything except research — the
/// workspace: ticket ids already embed the workspace name and analyze-round keys
/// are scoped to one workspace, so the extra component closes any
/// cross-workspace key collision (e.g. two concurrent sync analyze rounds in
/// different workspaces drawing the same short NanoID suffix). Research groups
/// are matched on (kind, key) alone because a run's coder round executes in an
/// EPHEMERAL per-run workspace whose name IS the run key (job_id) while its
/// analysts and orchestrator calls run in the real workspace — a workspace
/// component would split the group. The run key is a durable 10-char NanoID
/// (~60 bits entropy), so (kind, key) stays unique across workspaces; the
/// group's displayed workspace is resolved to the REAL workspace whenever a
/// non-ephemeral member is seen.
fn build_groups(agents: &[AgentHandle], calls: &[NonAgentCallHandle]) -> Vec<DisplayGroup> {
    let mut groups: Vec<DisplayGroup> = Vec::new();

    let find_group =
        |kind: GroupKind, key: &str, workspace: &str, groups: &mut Vec<DisplayGroup>| -> usize {
            let research = kind == GroupKind::Research;
            if let Some(idx) = groups.iter().position(|g| {
                g.kind == kind && g.key == key && (research || g.workspace == workspace)
            }) {
                if research && groups[idx].workspace == key && workspace != key {
                    // The group currently shows the ephemeral per-run
                    // workspace; adopt the joining member's real workspace.
                    groups[idx].workspace = workspace.to_string();
                }
                return idx;
            }
            groups.push(DisplayGroup {
                kind,
                key: key.to_string(),
                workspace: workspace.to_string(),
                label: None,
                items: Vec::new(),
                run_lifetime: false,
            });
            groups.len() - 1
        };

    // Adopt a member's parent label into the group (first non-None wins —
    // all members of one invocation carry the same label; the fallback keeps
    // a group whose only remaining member is label-less from degrading).
    let adopt_label = |label: &Option<String>, group: &mut DisplayGroup| {
        if group.label.is_none() && label.is_some() {
            group.label.clone_from(label);
        }
    };

    for agent in agents {
        let workspace = agent.workspace_name.clone();
        if let Some(parent) = &agent.parent_key {
            let idx = find_group(
                parent_group_kind(parent),
                parent_group_key(parent),
                &workspace,
                &mut groups,
            );
            adopt_label(&agent.parent_label, &mut groups[idx]);
            groups[idx]
                .items
                .push(DisplayItem::Agent(Box::new(AgentCard {
                    handle: agent.clone(),
                })));
        } else {
            // Workspace singleton. An empty workspace name groups under the
            // empty key; the section label resolver renders it as "workspace".
            let idx = find_group(GroupKind::Singleton, &workspace, &workspace, &mut groups);
            groups[idx]
                .items
                .push(DisplayItem::Agent(Box::new(AgentCard {
                    handle: agent.clone(),
                })));
        }
    }

    for call in calls {
        let workspace = call.workspace.clone();
        if let Some(parent) = &call.parent_key {
            let idx = find_group(
                parent_group_kind(parent),
                parent_group_key(parent),
                &workspace,
                &mut groups,
            );
            adopt_label(&call.parent_label, &mut groups[idx]);
            // Run-lifetime orchestrator markers render as a run-lifetime
            // indicator on the group, not as a transient call card.
            if call.run_lifetime {
                groups[idx].run_lifetime = true;
            } else {
                groups[idx].items.push(DisplayItem::Call(CallRow {
                    handle: call.clone(),
                }));
            }
        } else {
            let idx = find_group(GroupKind::Unattributed, &workspace, &workspace, &mut groups);
            groups[idx].items.push(DisplayItem::Call(CallRow {
                handle: call.clone(),
            }));
        }
    }

    groups
}

/// Group the display groups into WORKSPACE SECTIONS — the page is organized
/// by workspace, whose resolved label is used only for deterministic ordering
/// (the label no longer renders as a per-section heading).
///
/// Sections are ordered alphabetically by their resolved label (deterministic
/// — activity-based ordering would flicker as agents come and go); within a
/// section, groups keep the canonical kind order (tickets → analyze rounds →
/// research runs → singletons → unattributed) via [`DisplayGroup::sort_key`].
fn build_sections(
    groups: Vec<DisplayGroup>,
    workspaces: &std::collections::HashMap<String, Workspace>,
) -> Vec<WorkspaceSection> {
    let mut sections: Vec<WorkspaceSection> = Vec::new();
    for group in groups {
        let label = workspace_label_for(&group.workspace, workspaces);
        if let Some(section) = sections.iter_mut().find(|s| s.workspace == group.workspace) {
            section.groups.push(group);
        } else {
            sections.push(WorkspaceSection {
                workspace: group.workspace.clone(),
                label,
                groups: vec![group],
            });
        }
    }
    sections.sort_by(|a, b| a.label.cmp(&b.label));
    for section in &mut sections {
        section.groups.sort_by_key(DisplayGroup::sort_key);
    }
    sections
}

// ── Rendering ─────────────────────────────────────────────────────────────

/// Render one workspace section: just the section's groups. The workspace
/// name no longer gets a visual heading — `section.label` exists only for the
/// deterministic section ordering in [`build_sections`].
///
/// The returned element owns all rendered content (text widgets take owned
/// Strings), so its lifetime is independent of the `section` borrow.
fn render_section(
    section: &WorkspaceSection,
    expanded: &HashSet<(String, u64)>,
) -> Element<'static, RunningMessage> {
    let mut groups = Column::new().spacing(theme::SPACE_10);
    for group in &section.groups {
        groups = groups.push(render_group(group, expanded));
    }
    groups.into()
}

/// Resolve a group's header parts: the primary label plus an optional ticket
/// id. `render_group` composes a single flat header — for ticket groups
/// `[{id}] {title}`, otherwise just the label.
///
/// - Ticket groups: the ticket NAME plus the ticket ID. When no title was
///   captured (defensive — every live ticket group carries one via its agents
///   or the synthesis call), the key becomes the sole label.
/// - Analyze/research groups: the truncated question/task text; a generic
///   fallback when no label was captured. The raw NanoID key is NEVER shown.
/// - Singleton/unattributed groups: generic labels — their workspace name is
///   already the section grouping, so repeating it would be redundant.
fn group_title(group: &DisplayGroup) -> (String, Option<String>) {
    match &group.kind {
        GroupKind::Ticket => match &group.label {
            Some(title) => (title.clone(), Some(group.key.clone())),
            None => (group.key.clone(), None),
        },
        GroupKind::AnalyzeRound => (
            group.label.as_deref().map_or_else(
                || "Analyze round".to_string(),
                |l| truncate_at_boundary(l, MAX_GROUP_LABEL_CHARS),
            ),
            None,
        ),
        GroupKind::Research => (
            group.label.as_deref().map_or_else(
                || "Research run".to_string(),
                |l| truncate_at_boundary(l, MAX_GROUP_LABEL_CHARS),
            ),
            None,
        ),
        GroupKind::Singleton => ("Standalone".to_string(), None),
        GroupKind::Unattributed => ("Other LLM work".to_string(), None),
    }
}

/// Render one group: header (flat label + run-lifetime marker) then its
/// cards/rows directly on the page background — each agent card carries its
/// own card style; call rows are unadorned by design.
fn render_group(
    group: &DisplayGroup,
    expanded: &HashSet<(String, u64)>,
) -> Element<'static, RunningMessage> {
    let (title, id) = group_title(group);
    let mut header_parts: Vec<Element<'_, RunningMessage>> = Vec::new();
    // Ticket groups render a single flat `[{id}] {title}` header — the id is
    // composed into the text, never styled as a separate ACCENT element. When
    // no title was captured (defensive), the key is the sole label. All other
    // groups render their label as the same flat line.
    let header = if group.kind == GroupKind::Ticket {
        match id {
            Some(id) => format!("[{id}] {title}"),
            None => title.clone(),
        }
    } else {
        title.clone()
    };
    header_parts.push(
        text(header)
            .size(theme::TEXT_12)
            .color(theme::TEXT_SECONDARY)
            .into(),
    );
    if group.run_lifetime {
        header_parts.push(
            text("run active")
                .size(theme::TEXT_11)
                .color(theme::TEXT_SECONDARY)
                .into(),
        );
    }
    // Manual cancel: danger-styled button on RESEARCH-run group headers only.
    // The run key is carried by the message, never rendered as text.
    if group.kind == GroupKind::Research {
        header_parts.push(Space::new().width(Length::Fill).into());
        header_parts.push(
            button(text("Cancel run").size(theme::TEXT_11))
                .style(theme::button_danger)
                .on_press(RunningMessage::CancelRequest(group.key.clone()))
                .into(),
        );
    }

    let mut items = Column::new().spacing(theme::SPACE_6);
    for item in &group.items {
        match item {
            DisplayItem::Agent(card) => {
                let is_expanded =
                    expanded.contains(&(card.handle.agent_id.clone(), card.handle.generation));
                items = items.push(render_agent_card(card, is_expanded));
            }
            DisplayItem::Call(call) => {
                items = items.push(render_call_row(call));
            }
        }
    }

    column![
        Row::with_children(header_parts)
            .spacing(theme::SPACE_8)
            .align_y(Alignment::Center),
        items,
    ]
    .spacing(theme::SPACE_6)
    .into()
}

/// Build the research-run manual-cancel confirmation dialog, mirroring the
/// board's ticket-cancel pattern: consequences listed, danger confirm
/// button, Keep/Dismiss (and Escape/backdrop) to close with no effect.
/// `run_key` is the run's durable job id — never displayed as text.
fn cancel_confirm_dialog(run_key: &str) -> Element<'static, RunningMessage> {
    // Deliberately unused: the run key must never appear in the dialog's
    // rendered text — the button action alone carries it (see the enum docs).
    let _ = run_key;
    widgets::modal_backdrop(
        dialog::confirm_dialog(
            dialog::dialog_title("Cancel this research run?"),
            dialog::dialog_body([
                "Confirming will:",
                "• stop all agents of this run — an in-flight tool or LLM call \
                 may finish, but no further work happens;\n\
                 • stop the orchestrator — no more rounds, no report, and \
                 nothing is delivered to the Manager;\n\
                 • remove the run's temporary traces and its run folder — \
                 dispatching the cleanup agent while the orchestrator is still \
                 running, a direct sweep otherwise;\n\
                 • remove the run permanently — it can never resume.",
            ]),
            [
                dialog::DialogAction::secondary("Keep run", RunningMessage::CancelDismissed),
                dialog::DialogAction::danger("Cancel run", RunningMessage::CancelConfirmed),
            ],
        ),
        RunningMessage::CancelDismissed,
        0.5,
    )
}

/// Fallback label for workspaces outside the dashboard's registered set
/// (personal user spaces, ephemeral run-scoped workspaces).
fn fallback_workspace_label(workspace: &str) -> String {
    if workspace.is_empty() {
        "workspace".to_string()
    } else {
        format!("{workspace} (external)")
    }
}

/// Resolve a workspace's display label, used for deterministic section
/// ordering: the bare name for registered workspaces, the fallback label
/// (with the "(external)" marker) for unregistered/ephemeral ones, and
/// "workspace" for an empty name.
fn workspace_label_for(
    name: &str,
    workspaces: &std::collections::HashMap<String, Workspace>,
) -> String {
    if name.is_empty() {
        "workspace".to_string()
    } else if workspaces.contains_key(name) {
        name.to_string()
    } else {
        fallback_workspace_label(name)
    }
}

/// Render one running-agent card: the role icon and the token/elapsed metrics
/// inline in the first row, then the current user turn's trace groups. The
/// whole card is clickable to expand/collapse the trace groups.
///
/// Narration (the assistant's short reasoning text) lives solely in the
/// current trace-group label, which shows a "clanking" placeholder while its
/// narration hasn't committed; a brand-new agent — or a current user turn
/// with no tool rounds yet — shows a card-level "clanking" placeholder. The
/// live activity phase label (an
/// in-flight non-tool LLM call, e.g. extracting/summarizing/transcribing)
/// renders as a separate accent line at the very bottom of the card in both
/// the collapsed and expanded state. Trace groups come from the live
/// transcript snapshot (the unpersisted tail included): the current (latest)
/// group, plus up to 5 previous groups when expanded.
fn render_agent_card(card: &AgentCard, expanded: bool) -> Element<'static, RunningMessage> {
    let h = &card.handle;
    // Color resolution via the canonical string helper (handles derivative
    // names and falls back to muted grey for unknown roles); the icon still
    // needs a typed Role, so parse with the same Engineer fallback as before.
    let (fg, _bg) = theme::role_badge_color(&h.role);
    let role: crate::Role = h.role.parse().unwrap_or(crate::Role::Engineer);
    let icon = theme::role_icon(&role).size(theme::TEXT_24).color(fg);
    let elapsed = format_elapsed(h.started_at);

    // The live transcript snapshot feeds the trace groups below (and the
    // current group's narration label), scoped to the current user turn, so
    // fetch it once up front.
    let snapshot = crate::session::TRANSCRIPT_REGISTRY.snapshot(&h.agent_id);
    let groups = snapshot
        .as_ref()
        .map(|s| derive_trace_groups(current_turn_entries(&build_ledger(&s.history))))
        .unwrap_or_default();

    let token_count = snapshot.as_ref().and_then(|s| s.token_count);

    let mut content = Column::new()
        .spacing(theme::SPACE_6)
        .align_x(Alignment::Start)
        .width(Length::Fill);
    // The card's first row is the role icon followed inline by the token /
    // elapsed metrics, sitting at the left edge of the card (no fill spacers).
    let first_row = Row::new()
        .spacing(theme::SPACE_12)
        .align_y(Alignment::Center)
        .push(icon)
        .push(render_metrics(token_count, &elapsed));
    content = content.push(first_row);
    // A brand-new agent — or the current user turn with no tool rounds yet —
    // shows a card-level "clanking" placeholder. Once the current turn has any
    // group, the current group's own label handles narration / thinking, so
    // this fallback must not render at card level.
    if groups.is_empty() {
        content = content.push(clanking_placeholder());
    }
    // Trace groups from the live snapshot, scoped to the current user turn.
    // Content-only assistant messages (final answers) are deliberately
    // omitted — only tool-call assistant messages form groups.
    for group in render_visible_groups(&groups, expanded) {
        content = content.push(group);
    }
    // The live activity phase label (an in-flight non-tool LLM call) renders
    // as a separate accent line at the very bottom of the card, below the
    // trace groups, in both the collapsed and expanded view.
    if let Some(activity) = &h.activity {
        content = content.push(
            text(activity.to_owned())
                .size(theme::TEXT_13)
                .color(theme::ACCENT),
        );
    }

    let on_press = RunningMessage::ToggleAgentExpanded {
        agent_id: h.agent_id.clone(),
        generation: h.generation,
    };
    // The whole card is a click target (expand/collapse), but it stays a
    // `container` under a transparent `mouse_area` so the inner tool blocks
    // keep their hover tooltips (a `button` wrapper would swallow them).
    mouse_area(
        container(content)
            .width(Length::Fill)
            .padding(theme::PAD_8)
            .style(theme::surface_card_style),
    )
    .on_press(on_press)
    .into()
}

/// The narration typography of the trace-group labels: italic at
/// [`theme::NARRATION_TEXT_SIZE`] with wrapping within the row. A narration
/// label is never truncated and keeps the full reasoning as a hover tooltip;
/// a promoted reasoning label is pre-capped by
/// [`promoted_reasoning_label`] and carries no tooltip.
fn narration_text(narration: &str) -> iced::widget::Text<'static, iced::Theme, iced::Renderer> {
    text(narration.to_owned())
        .size(theme::NARRATION_TEXT_SIZE)
        .font(theme::FONT_ITALIC)
        .color(theme::TEXT_SECONDARY)
        .wrapping(iced::widget::text::Wrapping::WordOrGlyph)
}

/// Max display length (Unicode chars) of a promoted reasoning label. The
/// narration itself never truncates, but a promoted long CoT fallback is
/// capped so it cannot dominate the card.
const MAX_PROMOTED_LABEL_CHARS: usize = 200;

/// Single-line display form of a promoted reasoning label: control
/// characters collapsed to spaces ([`collapse_control_chars`]), then capped
/// at [`MAX_PROMOTED_LABEL_CHARS`] chars at a word/path-delimiter boundary
/// with "…" ([`truncate_at_boundary`]).
fn promoted_reasoning_label(reasoning: &str) -> String {
    truncate_at_boundary(
        &collapse_control_chars(reasoning, MAX_PROMOTED_LABEL_CHARS),
        MAX_PROMOTED_LABEL_CHARS,
    )
}

/// The neutral "clanking" placeholder shown while a narration has not
/// committed yet (a brand-new agent with no trace groups, or a current
/// group awaiting its first narration).
fn clanking_placeholder() -> iced::widget::Text<'static, iced::Theme, iced::Renderer> {
    text("clanking")
        .size(theme::TEXT_13)
        .color(theme::TEXT_SECONDARY)
}

/// Render the card's metrics: the live session-token count (when known) and
/// the elapsed run time, each as a compact labeled tooltip. Renders inline in
/// the card's first row, right after the role icon (see
/// [`render_agent_card`]).
fn render_metrics(token_count: Option<u64>, elapsed: &str) -> Element<'static, RunningMessage> {
    let mut metrics = Row::new()
        .spacing(theme::SPACE_12)
        .align_y(Alignment::Center);
    // The live token count comes from the published transcript snapshot (the
    // registry no longer carries a session_tokens mirror). It renders as a
    // compact count; hovering reveals the label and the exact unrounded value.
    if let Some(token_count) = token_count {
        metrics = metrics.push(
            tooltip(
                text(theme::format_compact_tokens(token_count))
                    .size(theme::TEXT_11)
                    .color(theme::TEXT_SECONDARY),
                render_metric_tooltip(format!("Session tokens: {token_count}")),
                tooltip::Position::Top,
            )
            .gap(theme::SPACE_4)
            .style(theme::tooltip_style),
        );
    }
    // Elapsed time since the agent started; hovering explains the meaning.
    metrics = metrics.push(
        tooltip(
            text(elapsed.to_owned())
                .size(theme::TEXT_11)
                .color(theme::TEXT_SECONDARY),
            render_metric_tooltip("Elapsed run time since the agent started".to_string()),
            tooltip::Position::Top,
        )
        .gap(theme::SPACE_4)
        .style(theme::tooltip_style),
    );
    metrics.into()
}

/// Render the visible trace groups for a card: the current (latest) group
/// always (last, chronologically, newest round expanded), plus up to 5
/// previous groups (collapsed) when the card is expanded. Every group renders
/// its narration label (see [`render_trace_group`]). Empty input renders
/// nothing.
fn render_visible_groups(
    groups: &[TraceGroup],
    expanded: bool,
) -> Vec<Element<'static, RunningMessage>> {
    let mut rendered = Vec::new();
    let Some((current, previous)) = groups.split_last() else {
        return rendered;
    };
    if expanded {
        // The 5 most-recent previous groups, oldest first, then current.
        for group in previous.iter().rev().take(5).rev() {
            rendered.push(render_trace_group(group, false));
        }
    }
    // Current group: newest round expanded, earlier rounds collapsed.
    rendered.push(render_trace_group(current, true));
    rendered
}

/// The text a trace group renders as its narration label: the group's
/// narration (wrapped in the reasoning hover tooltip), or — when the
/// narration is empty (whitespace-only counts as empty) — the group's
/// promoted reasoning as a capped label (no tooltip: the label already
/// shows the text), or the neutral "clanking" placeholder for a silent
/// group (no narration and no reasoning).
enum GroupLabelText<'a> {
    Narration(&'a str),
    Promoted(String),
    Placeholder,
}

fn group_label_text(group: &TraceGroup) -> GroupLabelText<'_> {
    if let Some(reasoning) = promoted_reasoning(Some(&group.narration), group.reasoning.as_deref())
    {
        GroupLabelText::Promoted(promoted_reasoning_label(reasoning))
    } else if !group.narration.trim().is_empty() {
        GroupLabelText::Narration(&group.narration)
    } else {
        GroupLabelText::Placeholder
    }
}

/// Render one trace group. `expand_current` renders the newest round's calls
/// expanded (current group); otherwise every call collapses to a name-only
/// line (previous groups). The group's narration label always renders (the
/// short reasoning text, its promoted capped reasoning, or the "clanking"
/// placeholder); hovering the narration label — not the promoted one, which
/// already shows the text — reveals the group's full decoded Reasoning when
/// it carried one.
fn render_trace_group(
    group: &TraceGroup,
    expand_current: bool,
) -> Element<'static, RunningMessage> {
    let mut column = Column::new()
        .spacing(theme::SPACE_4)
        .align_x(Alignment::Start);
    let label: Element<'static, RunningMessage> = match group_label_text(group) {
        GroupLabelText::Narration(narration) => {
            reasoning_tooltip(group.reasoning.as_deref(), narration_text(narration).into())
        }
        GroupLabelText::Promoted(promoted) => narration_text(&promoted).into(),
        GroupLabelText::Placeholder => clanking_placeholder().into(),
    };
    column = column.push(label);

    if expand_current {
        let (newest, earlier) = group
            .rounds
            .split_last()
            .expect("a trace group always carries at least one round");
        if !earlier.is_empty() {
            column = column.push(
                text(collapsed_calls_line(earlier))
                    .size(theme::TEXT_10)
                    .color(theme::TEXT_SECONDARY),
            );
        }
        for entry in newest {
            column = column.push(tool_row(entry));
        }
    } else {
        column = column.push(
            text(collapsed_calls_line(&group.rounds))
                .size(theme::TEXT_10)
                .color(theme::TEXT_SECONDARY),
        );
    }
    column.into()
}

/// A single expanded tool-call row in the current group. Settled calls render
/// exactly as [`tool_block`]; an in-flight call (result not yet committed)
/// gains a small accent `loader_circle` marker after the block.
fn tool_row(entry: &ToolCallEntry) -> Element<'static, RunningMessage> {
    let block = tool_block(&entry.tool, ToolBlockView::Compact);
    if entry.result.is_none() {
        Row::new()
            .spacing(theme::SPACE_6)
            .align_y(Alignment::Center)
            .push(block)
            .push(
                lucide::loader_circle::<iced::Theme, iced::Renderer>()
                    .size(theme::TEXT_14)
                    .color(theme::ACCENT),
            )
            .into()
    } else {
        block
    }
}

/// Wrap a narration label in a hover tooltip revealing the full decoded
/// Reasoning behind it (see [`TraceGroup::reasoning`]). When there is no
/// reasoning the label renders bare.
fn reasoning_tooltip<'a>(
    reasoning: Option<&str>,
    label: Element<'a, RunningMessage>,
) -> Element<'a, RunningMessage> {
    let Some(reasoning) = reasoning.filter(|r| !r.is_empty()) else {
        return label;
    };
    let tooltip_content: Element<'static, RunningMessage> = container(
        text(reasoning.to_string())
            .size(theme::TEXT_11)
            .color(theme::TEXT_SECONDARY)
            .wrapping(iced::widget::text::Wrapping::WordOrGlyph),
    )
    .max_width(MAX_TOOL_TOOLTIP_WIDTH)
    .into();
    tooltip(label, tooltip_content, tooltip::Position::Top)
        .gap(theme::SPACE_4)
        .style(theme::tooltip_style)
        .into()
}

/// Compose the collapsed name-only line for a set of tool-call rounds: tool
/// names with underscores replaced by spaces, in first-appearance order, each
/// unique name suffixed with `xN` when it appears more than once within the
/// collapsed set (e.g. `read file x2, list files`). An in-flight call
/// (result not yet committed) gets its display name suffixed with a running
/// marker (`…`) before the xN counting, so it never looks settled.
fn collapsed_calls_line(rounds: &[Vec<ToolCallEntry>]) -> String {
    let mut order: Vec<String> = Vec::new();
    let mut counts: HashMap<String, usize> = HashMap::new();
    for round in rounds {
        for call in round {
            let base = call.tool.name.replace('_', " ");
            let display = if call.result.is_none() {
                format!("{base} …")
            } else {
                base
            };
            if !counts.contains_key(&display) {
                order.push(display.clone());
            }
            *counts.entry(display).or_default() += 1;
        }
    }
    order
        .iter()
        .map(|name| {
            let c = counts[name];
            if c > 1 {
                format!("{name} x{c}")
            } else {
                name.clone()
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Prune stale expanded-state keys: an agent that finished (or was replaced by
/// a new generation of the same agent_id) must not keep a stale expansion.
pub(crate) fn prune_expanded(expanded: &mut HashSet<(String, u64)>, agents: &[AgentHandle]) {
    let live: HashSet<(String, u64)> = agents
        .iter()
        .map(|h| (h.agent_id.clone(), h.generation))
        .collect();
    expanded.retain(|key| live.contains(key));
}

/// One trace group in a running agent's live transcript: a maximal run of
/// consecutive tool-call assistant rounds sharing a single (possibly empty)
/// visible narration, bounded by a real user turn or a new narration.
///
/// Derived from the shared session ledger: the group's narration comes from
/// the decoded assistant `content` (the short visible reasoning text); its
/// `reasoning` is the long decoded `Reasoning` block of the group's rounds,
/// surfaced on hover or promoted into the label. A group always carries at
/// least one round.
struct TraceGroup {
    /// The assistant's short visible narration (empty → renders "clanking",
    /// or the promoted capped reasoning label when the group carries one).
    /// This is the decoded assistant `content`, NEVER the long `Reasoning`
    /// / `[thinking]` block.
    narration: String,
    /// The full decoded Reasoning of the group: the first non-empty reasoning
    /// among its rounds. Surfaced on hover behind a narration label, or
    /// promoted into the label itself when the narration is empty. `None` when
    /// the rounds carried none (a silent group then renders "clanking").
    reasoning: Option<String>,
    /// Tool-call rounds in first-appearance order; the LAST round is the newest
    /// (expanded in the current group), earlier rounds collapse. Each round
    /// carries the full ledger tool-call entries (name/args pairs plus the
    /// tool_call_id-matched result), so the display can distinguish an in-flight
    /// call (result not yet committed) from a settled one.
    rounds: Vec<Vec<ToolCallEntry>>,
}

/// A real user turn boundary in the ledger: a User message that is neither
/// an injected tool-result-image message (content starting with
/// [`crate::util::INJECTED_IMAGE_TAG`]) nor an empty resume signal (no/empty
/// content). Only such a message starts a new user turn.
fn is_user_turn_boundary(entry: &SessionEntry) -> bool {
    matches!(entry, SessionEntry::Message { role: ChatRole::User, content, .. }
    if content.as_deref().is_some_and(|c| {
        !c.trim().is_empty() && !c.starts_with(crate::util::INJECTED_IMAGE_TAG)
    }))
}

/// The slice of the ledger belonging to the CURRENT user turn: everything
/// after the last real user turn boundary ([`is_user_turn_boundary`]). The
/// running card shows only the current turn, so groups from previous turns
/// never leak onto it. When no boundary exists the whole ledger is current.
fn current_turn_entries(entries: &[SessionEntry]) -> &[SessionEntry] {
    let start = entries
        .iter()
        .rposition(is_user_turn_boundary)
        .map_or(0, |i| i + 1);
    &entries[start..]
}

/// Project the shared session ledger into a running agent's trace groups, in
/// chronological order.
///
/// Boundary rules:
/// - A new (non-empty) narration in a tool-call assistant round starts a new
///   group; that narration becomes the group's `narration`.
/// - Consecutive tool-call rounds with no narration accumulate into the current
///   group.
/// - A real user turn closes the current group; the next tool-call round then
///   starts a fresh one even with no narration (its `narration` slots to
///   "clanking"). An empty (whitespace) User message or a synthetic
///   tool-injected one (content starting with the
///   [`crate::util::INJECTED_IMAGE_TAG`] marker) is NOT a boundary.
fn derive_trace_groups(entries: &[SessionEntry]) -> Vec<TraceGroup> {
    let mut groups: Vec<TraceGroup> = Vec::new();
    let mut current: Option<TraceGroup> = None;
    for entry in entries {
        match entry {
            SessionEntry::ToolRound {
                narration,
                reasoning,
                calls,
            } => {
                let narration = narration.clone().unwrap_or_default();
                let new_group = !narration.is_empty() || current.is_none();
                if new_group {
                    if let Some(group) = current.take() {
                        groups.push(group);
                    }
                }
                let group = current.get_or_insert_with(|| TraceGroup {
                    narration,
                    reasoning: None,
                    rounds: Vec::new(),
                });
                if group.reasoning.is_none()
                    && let Some(reasoning) = reasoning
                    && !reasoning.is_empty()
                {
                    group.reasoning = Some(reasoning.clone());
                }
                group.rounds.push(calls.clone());
            }
            SessionEntry::Message { .. } => {
                if is_user_turn_boundary(entry)
                    && let Some(group) = current.take()
                {
                    groups.push(group);
                }
            }
        }
    }
    if let Some(group) = current.take() {
        groups.push(group);
    }
    groups
}

/// Render a one-line metric tooltip body in a narrow, styled container: the
/// explanatory text (metric label plus, where useful, the precise value). Kept
/// narrower than [`MAX_TOOL_TOOLTIP_WIDTH`] because a metric tooltip holds a
/// single short line, not multi-arg tool calls.
fn render_metric_tooltip(label: String) -> Element<'static, RunningMessage> {
    container(
        text(label)
            .size(theme::TEXT_11)
            .color(theme::TEXT_PRIMARY)
            .wrapping(iced::widget::text::Wrapping::WordOrGlyph),
    )
    .max_width(MAX_METRIC_TOOLTIP_WIDTH)
    .into()
}

/// Render a compact non-agent LLM call row: zap marker + purpose + elapsed.
/// No workspace name (the workspace grouping already names it); the elapsed
/// time uses the same brighter tone as agent cards. The purpose is the static
/// human-readable label — raw kind names never leak.
fn render_call_row(call: &CallRow) -> Element<'static, RunningMessage> {
    let h = &call.handle;
    let elapsed = format_elapsed(h.started_at);
    let purpose = crate::agent::registry::call_kind_label(h.kind);

    row![
        lucide::zap::<iced::Theme, iced::Renderer>()
            .size(theme::TEXT_16)
            .color(theme::ACCENT),
        text(purpose)
            .size(theme::TEXT_12)
            .color(theme::TEXT_SECONDARY),
        Space::new().width(Length::Fill),
        text(elapsed)
            .size(theme::TEXT_11)
            .color(theme::TEXT_SECONDARY),
    ]
    .spacing(theme::SPACE_6)
    .align_y(Alignment::Center)
    .into()
}

/// Format the elapsed time since `started_at` at render time.
fn format_elapsed(started_at: DateTime<Utc>) -> String {
    let now = Utc::now();
    let secs = now.signed_duration_since(started_at).num_seconds().max(0);
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {:02}s", secs / 60, secs % 60)
    } else {
        format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ChatMessage;
    use crate::agent::registry::{AgentHandle, RunningTool};
    use crate::gui::session_view::build_ledger;

    fn agent_handle(
        id: &str,
        role: &str,
        ticket_id: Option<String>,
        workspace: &str,
        parent: Option<ParentKey>,
    ) -> AgentHandle {
        AgentHandle {
            agent_id: id.to_string(),
            role: role.to_string(),
            ticket_id,
            workspace_path: format!("/ws/{workspace}"),
            workspace_name: workspace.to_string(),
            parent_key: parent,
            parent_label: None,
            started_at: Utc::now(),
            label: role.to_string(),
            generation: 0,
            activity: None,
        }
    }

    fn call_handle(
        kind: &'static str,
        workspace: &str,
        parent: Option<ParentKey>,
        run_lifetime: bool,
    ) -> NonAgentCallHandle {
        NonAgentCallHandle {
            kind,
            workspace: workspace.to_string(),
            started_at: Utc::now(),
            parent_key: parent,
            parent_label: None,
            run_lifetime,
        }
    }

    #[test]
    fn groups_ticket_agents_and_synthesis_together() {
        let agents = vec![
            agent_handle(
                "a1",
                "analyst",
                Some("T1".to_string()),
                "ws1",
                Some(ParentKey::Ticket("T1".to_string())),
            ),
            agent_handle("mgr", "manager", None, "ws1", None),
        ];
        let calls = vec![call_handle(
            "synthesis",
            "ws1",
            Some(ParentKey::Ticket("T1".to_string())),
            false,
        )];
        let groups = build_groups(&agents, &calls);
        assert_eq!(groups.len(), 2, "ticket group + singleton group");
        let ticket = &groups[0];
        assert_eq!(ticket.kind, GroupKind::Ticket);
        assert_eq!(ticket.key, "T1");
        assert_eq!(ticket.items.len(), 2, "analyst agent + synthesis call");
    }

    #[test]
    fn two_analyze_rounds_never_mix_members() {
        let agents = vec![
            agent_handle(
                "analyze_ws_AAA_0_analyst",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::AnalyzeRound("roundA".to_string())),
            ),
            agent_handle(
                "analyze_ws_AAA_1_analyst",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::AnalyzeRound("roundA".to_string())),
            ),
            agent_handle(
                "analyze_ws_BBB_0_analyst",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::AnalyzeRound("roundB".to_string())),
            ),
        ];
        let calls = vec![call_handle(
            "consolidate",
            "ws1",
            Some(ParentKey::AnalyzeRound("roundA".to_string())),
            false,
        )];
        let groups = build_groups(&agents, &calls);
        let analyze_groups: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::AnalyzeRound)
            .collect();
        assert_eq!(analyze_groups.len(), 2, "two distinct analyze round groups");
        let round_a = analyze_groups
            .iter()
            .find(|g| g.key == "roundA")
            .expect("round A exists");
        assert_eq!(round_a.items.len(), 3, "2 analysts + consolidation call");
        let round_b = analyze_groups
            .iter()
            .find(|g| g.key == "roundB")
            .expect("round B exists");
        assert_eq!(round_b.items.len(), 1, "only its own analyst");
    }

    #[test]
    fn research_run_members_share_one_key_across_phases() {
        // Two concurrent research runs in one workspace must never mix
        // members even though every spawn carries a unique agent-id suffix.
        let agents = vec![
            agent_handle(
                "research_ws_x1_decompose_0",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::Research("run1".to_string())),
            ),
            agent_handle(
                "research_ws_x2_r1_0",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::Research("run1".to_string())),
            ),
            agent_handle(
                "research_ws_y1_decompose_0",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::Research("run2".to_string())),
            ),
        ];
        let calls = vec![
            call_handle(
                "synthesize",
                "ws1",
                Some(ParentKey::Research("run1".to_string())),
                false,
            ),
            call_handle(
                "research_orchestrator",
                "ws1",
                Some(ParentKey::Research("run1".to_string())),
                true,
            ),
        ];
        let groups = build_groups(&agents, &calls);
        let research_groups: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::Research)
            .collect();
        assert_eq!(research_groups.len(), 2);
        let run1 = research_groups
            .iter()
            .find(|g| g.key == "run1")
            .expect("run 1 exists");
        assert_eq!(run1.items.len(), 3, "2 analysts + synthesize call");
        assert!(
            run1.run_lifetime,
            "run-lifetime orchestrator marker attached"
        );
        let run2 = research_groups
            .iter()
            .find(|g| g.key == "run2")
            .expect("run 2 exists");
        assert_eq!(run2.items.len(), 1, "only its own member");
        assert!(!run2.run_lifetime);
    }

    #[test]
    fn singletons_and_unattributed_calls_group_by_workspace() {
        let agents = vec![
            agent_handle("manager_ws1", "manager", None, "ws1", None),
            agent_handle("maintainer_ws2_abc", "maintainer", None, "ws2", None),
        ];
        let calls = vec![call_handle("some_orchestrator_call", "ws1", None, false)];
        let groups = build_groups(&agents, &calls);
        let singleton: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::Singleton)
            .collect();
        assert_eq!(singleton.len(), 2, "one per workspace");
        let unattributed: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::Unattributed)
            .collect();
        assert_eq!(unattributed.len(), 1);
        assert_eq!(unattributed[0].workspace, "ws1");
    }

    #[test]
    fn sort_key_orders_groups_by_kind() {
        let mut groups = [
            DisplayGroup {
                kind: GroupKind::Unattributed,
                key: "ws".to_string(),
                workspace: "ws".to_string(),
                label: None,
                items: Vec::new(),
                run_lifetime: false,
            },
            DisplayGroup {
                kind: GroupKind::Ticket,
                key: "T1".to_string(),
                workspace: "ws".to_string(),
                label: None,
                items: Vec::new(),
                run_lifetime: false,
            },
            DisplayGroup {
                kind: GroupKind::Research,
                key: "r".to_string(),
                workspace: "ws".to_string(),
                label: None,
                items: Vec::new(),
                run_lifetime: false,
            },
        ];
        groups.sort_by_key(DisplayGroup::sort_key);
        assert_eq!(groups[0].kind, GroupKind::Ticket);
        assert_eq!(groups[1].kind, GroupKind::Research);
        assert_eq!(groups[2].kind, GroupKind::Unattributed);
    }

    #[test]
    fn research_groups_resolve_workspace_across_ephemeral_coder_members() {
        // A run's coder round executes in an ephemeral per-run workspace whose
        // name IS the run key (job_id), while its analysts and orchestrator
        // calls run in the real workspace. The group must resolve to the REAL
        // workspace whether the coder registers before or after the run's
        // real-workspace members, and two concurrent runs must never mix.
        let agents = vec![
            // run1: ephemeral coder registers first, then a real-workspace
            // analyst.
            agent_handle(
                "research_ws1_run1_coder0",
                "coder",
                None,
                "run1",
                Some(ParentKey::Research("run1".to_string())),
            ),
            agent_handle(
                "research_ws1_run1_r1_0",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::Research("run1".to_string())),
            ),
            // run2: real-workspace analyst registers first, then the
            // ephemeral coder.
            agent_handle(
                "research_ws1_run2_r1_0",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::Research("run2".to_string())),
            ),
            agent_handle(
                "research_ws1_run2_coder0",
                "coder",
                None,
                "run2",
                Some(ParentKey::Research("run2".to_string())),
            ),
        ];
        let groups = build_groups(&agents, &[]);
        let runs: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::Research)
            .collect();
        assert_eq!(runs.len(), 2, "two concurrent runs never mix members");
        for run in runs {
            assert_eq!(
                run.workspace, "ws1",
                "the real workspace wins over the ephemeral per-run workspace"
            );
            assert_eq!(run.items.len(), 2, "coder + analyst in one group");
        }
    }

    #[test]
    fn cross_workspace_round_keys_never_merge_groups() {
        // Two concurrent sync analyze rounds in DIFFERENT workspaces could draw
        // the same short NanoID suffix — the workspace component of the group
        // identity must keep their groups separate.
        let agents = vec![
            agent_handle(
                "analyze_ws_AAA_0_analyst",
                "analyst",
                None,
                "ws1",
                Some(ParentKey::AnalyzeRound("abc123".to_string())),
            ),
            agent_handle(
                "analyze_ws_BBB_0_analyst",
                "analyst",
                None,
                "ws2",
                Some(ParentKey::AnalyzeRound("abc123".to_string())),
            ),
        ];
        let groups = build_groups(&agents, &[]);
        let analyze_groups: Vec<_> = groups
            .iter()
            .filter(|g| g.kind == GroupKind::AnalyzeRound)
            .collect();
        assert_eq!(
            analyze_groups.len(),
            2,
            "same round key in two workspaces stays separate"
        );
    }

    /// Build a handle with a parent label (the display-level label captured
    /// at spawn — ticket title / question text).
    fn agent_handle_labeled(
        id: &str,
        role: &str,
        workspace: &str,
        parent: Option<ParentKey>,
        parent_label: Option<&str>,
    ) -> AgentHandle {
        let mut h = agent_handle(id, role, None, workspace, parent);
        h.parent_label = parent_label.map(ToString::to_string);
        h
    }

    fn call_handle_labeled(
        kind: &'static str,
        workspace: &str,
        parent: Option<ParentKey>,
        parent_label: Option<&str>,
    ) -> NonAgentCallHandle {
        let mut h = call_handle(kind, workspace, parent, false);
        h.parent_label = parent_label.map(ToString::to_string);
        h
    }

    #[test]
    fn ticket_group_label_comes_from_members_not_the_key() {
        // Ticket title is captured observationally at spawn (agents via
        // Agent::new's ticket, the synthesis call via the joint-verdict
        // threading). A group must carry the title even when only the
        // synthesis call remains — never degrade to an ID-only header.
        let agents = vec![agent_handle_labeled(
            "a1",
            "analyst",
            "ws1",
            Some(ParentKey::Ticket("T1".to_string())),
            Some("Fix the login flow"),
        )];
        let calls = vec![call_handle_labeled(
            "synthesis",
            "ws1",
            Some(ParentKey::Ticket("T1".to_string())),
            Some("Fix the login flow"),
        )];
        let groups = build_groups(&agents, &calls);
        let ticket = groups
            .iter()
            .find(|g| g.kind == GroupKind::Ticket)
            .expect("ticket group exists");
        assert_eq!(
            ticket.label.as_deref(),
            Some("Fix the login flow"),
            "group label adopted from a member's parent label"
        );
        // group_title preserves (title, id); render_group composes `[id] title`.
        let (title, secondary) = group_title(ticket);
        assert_eq!(title, "Fix the login flow");
        assert_eq!(secondary.as_deref(), Some("T1"));
    }

    #[test]
    fn analyze_and_research_groups_render_question_not_raw_key() {
        // Analyze/research headers show the question text; the raw NanoID key
        // is never rendered. A missing label degrades to a generic label,
        // never the key.
        let agents = vec![agent_handle_labeled(
            "a1",
            "analyst",
            "ws1",
            Some(ParentKey::AnalyzeRound("job_abc".to_string())),
            Some("Why is CI flaky?"),
        )];
        let groups = build_groups(&agents, &[]);
        let analyze = groups
            .iter()
            .find(|g| g.kind == GroupKind::AnalyzeRound)
            .expect("analyze group exists");
        let (title, secondary) = group_title(analyze);
        assert_eq!(title, "Why is CI flaky?");
        assert!(secondary.is_none(), "no id secondary for analyze groups");
        assert!(!title.contains("job_abc"), "raw key never leaks");

        let mut no_label = analyze.clone();
        no_label.label = None;
        let (fallback, _) = group_title(&no_label);
        assert_eq!(fallback, "Analyze round");
        assert!(!fallback.contains("job_abc"), "generic fallback, no key");
    }

    #[test]
    fn sections_group_by_workspace_and_keep_kind_order() {
        // Workspace-first layout. Sections are alphabetical; within a section,
        // groups keep the canonical kind order. Singleton groups are keyed by
        // workspace, so they land in their own workspace's section.
        let mut ws_map = std::collections::HashMap::new();
        ws_map.insert(
            "ws2".to_string(),
            Workspace {
                path: "/ws/ws2".to_string(),
                paused: false,
                maintenance_enabled: false,
                ..Default::default()
            },
        );
        let agents = vec![
            agent_handle(
                "t_agent",
                "engineer",
                Some("T1".to_string()),
                "ws1",
                Some(ParentKey::Ticket("T1".to_string())),
            ),
            agent_handle("mgr_ws2", "manager", None, "ws2", None),
            agent_handle("mgr_ws1", "manager", None, "ws1", None),
        ];
        let groups = build_groups(&agents, &[]);
        let sections = build_sections(groups, &ws_map);
        assert_eq!(sections.len(), 2, "one section per workspace");
        assert_eq!(sections[0].workspace, "ws1");
        assert_eq!(sections[1].workspace, "ws2");
        // ws1: ticket group before singleton (kind order).
        assert_eq!(sections[0].groups[0].kind, GroupKind::Ticket);
        assert_eq!(sections[0].groups[1].kind, GroupKind::Singleton);
        // ws2 is registered → bare name; ws1 is unregistered → "(external)".
        assert_eq!(sections[1].label, "ws2");
        assert_eq!(sections[0].label, "ws1 (external)");
    }

    #[test]
    fn singleton_and_unattributed_headers_are_generic_not_workspace_titled() {
        // Inside a workspace section the singleton/unattributed group headers
        // must NOT repeat the workspace name — the workspace grouping already
        // names it.
        let agents = vec![agent_handle("mgr", "manager", None, "ws1", None)];
        let calls = vec![call_handle("some_orchestrator_call", "ws1", None, false)];
        let groups = build_groups(&agents, &calls);
        for group in &groups {
            let (title, _) = group_title(group);
            assert_ne!(title, "ws1", "group header must not duplicate the section");
            assert!(
                !title.contains("ws1"),
                "no workspace name in group headers: {title}"
            );
        }
    }

    // ── Trace-group derivation ──────────────────────────────────────

    fn assistant_tool_call(narration: &str, calls: &[(&str, serde_json::Value)]) -> ChatMessage {
        assistant_tool_call_reasoning(narration, calls, None)
    }

    /// Like [`assistant_tool_call`] but with an optional decoded `reasoning`
    /// field, so the ledger's `ToolRound.reasoning` is populated.
    fn assistant_tool_call_reasoning(
        narration: &str,
        calls: &[(&str, serde_json::Value)],
        reasoning: Option<&str>,
    ) -> ChatMessage {
        let calls_json: Vec<serde_json::Value> = calls
            .iter()
            .map(|(name, args)| {
                serde_json::json!({
                    "id": "call_1",
                    "name": name,
                    "arguments": serde_json::to_string(args).unwrap_or_default(),
                })
            })
            .collect();
        let content = if narration.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::Value::String(narration.to_string())
        };
        let mut body = serde_json::json!({ "content": content, "tool_calls": calls_json });
        if let Some(reasoning) = reasoning {
            body["reasoning"] = serde_json::json!(reasoning);
        }
        ChatMessage::assistant(body.to_string())
    }

    #[test]
    fn empty_and_non_tool_history_produce_no_groups() {
        assert!(derive_trace_groups(&[]).is_empty());
        // A content-only assistant message (final answer) is NOT a group.
        let history = vec![
            ChatMessage::user("hello\n\n<timestamp>2026-01-01 00:00:00 (UTC)</timestamp>"),
            ChatMessage::assistant("Final answer here."),
        ];
        assert!(derive_trace_groups(&build_ledger(&history)).is_empty());
    }

    #[test]
    fn narration_starts_and_boundary_groups() {
        let history = vec![
            assistant_tool_call(
                "Reading the file",
                &[("read", serde_json::json!({"path": "a.rs"}))],
            ),
            assistant_tool_call(
                "Editing it",
                &[("edit", serde_json::json!({"path": "b.rs"}))],
            ),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 2, "new narration starts a new group");
        assert_eq!(groups[0].narration, "Reading the file");
        assert_eq!(groups[1].narration, "Editing it");
    }

    #[test]
    fn consecutive_no_narration_rounds_accumulate() {
        let history = vec![
            assistant_tool_call("", &[("read", serde_json::json!({"path": "a.rs"}))]),
            assistant_tool_call("", &[("list", serde_json::json!({"path": "."}))]),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 1, "no narration → same group");
        assert_eq!(groups[0].rounds.len(), 2);
        assert!(groups[0].narration.is_empty());
    }

    #[test]
    fn real_user_turn_resets_group() {
        let history = vec![
            assistant_tool_call(
                "Narration",
                &[("read", serde_json::json!({"path": "a.rs"}))],
            ),
            ChatMessage::user("ok now fix it\n\n<timestamp>2026-01-01 00:00:00 (UTC)</timestamp>"),
            assistant_tool_call("", &[("edit", serde_json::json!({"path": "b.rs"}))]),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 2, "user turn closes the group");
        assert_eq!(groups[0].narration, "Narration");
        // The post-reset empty-narration round starts a fresh group.
        assert_eq!(groups[1].rounds.len(), 1);
    }

    #[test]
    fn injected_image_user_message_does_not_reset_group() {
        let history = vec![
            assistant_tool_call("", &[("read", serde_json::json!({"path": "a.rs"}))]),
            ChatMessage::user(crate::util::injected_image_user_message(
                "data:image/png;base64,xxx",
            )),
            assistant_tool_call("", &[("read", serde_json::json!({"path": "a.rs"}))]),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 1, "synthetic image stays in the same group");
        assert_eq!(groups[0].rounds.len(), 2);
    }

    #[test]
    fn empty_user_message_is_not_a_turn_boundary() {
        // An empty User message (resume signal) is NOT a real turn boundary:
        // tool rounds on both sides still form ONE group.
        let history = vec![
            assistant_tool_call("", &[("read", serde_json::json!({"path": "a.rs"}))]),
            ChatMessage::user(""),
            assistant_tool_call("", &[("edit", serde_json::json!({"path": "b.rs"}))]),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 1, "empty user message is not a boundary");
        assert_eq!(groups[0].rounds.len(), 2);
    }

    #[test]
    fn trace_group_reasoning_is_first_non_empty_round() {
        // Reasoning is captured from the first non-empty reasoning among the
        // group's rounds; rounds with no reasoning are skipped, and a group
        // with none at all carries None (the narration label renders bare).
        let history = vec![
            assistant_tool_call_reasoning(
                "",
                &[("read", serde_json::json!({"path": "a.rs"}))],
                None,
            ),
            assistant_tool_call_reasoning(
                "",
                &[("edit", serde_json::json!({"path": "b.rs"}))],
                Some("first"),
            ),
            assistant_tool_call_reasoning(
                "",
                &[("list", serde_json::json!({"path": "."}))],
                Some("second"),
            ),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 1, "no narration → same group");
        assert_eq!(groups[0].reasoning.as_deref(), Some("first"));
    }

    #[test]
    fn trace_group_without_reasoning_is_none() {
        let history = vec![assistant_tool_call_reasoning(
            "Narration",
            &[("read", serde_json::json!({"path": "a.rs"}))],
            None,
        )];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups[0].reasoning, None);
    }

    /// Build a ledger tool-call entry for the collapsed/in-flight projection
    /// tests: `result: None` marks the call in-flight.
    fn entry(name: &str, args: serde_json::Value, result: Option<&str>) -> ToolCallEntry {
        ToolCallEntry {
            tool_call_id: String::new(),
            tool: RunningTool::from_tool_call(&crate::ToolCall {
                id: String::new(),
                name: name.to_string(),
                arguments: args,
            }),
            result: result.map(ToString::to_string),
        }
    }

    #[test]
    fn collapsed_calls_line_counts_and_orders() {
        let rounds = vec![
            vec![
                entry("read_file", serde_json::json!({"path": "a.rs"}), Some("ok")),
                entry("list_files", serde_json::json!({"path": "."}), Some("ok")),
            ],
            vec![
                entry("read_file", serde_json::json!({"path": "b.rs"}), Some("ok")),
                entry("read_file", serde_json::json!({"path": "c.rs"}), None),
            ],
        ];
        assert_eq!(
            collapsed_calls_line(&rounds),
            "read file x2, list files, read file …",
            "underscores become spaces; settled names stay exact, an in-flight call gets a running suffix; `xN` counts collapsed repetitions; first-appearance order"
        );
    }

    #[test]
    fn card_shows_only_current_turn_groups() {
        // The card shows only the CURRENT user turn: the pre-turn group is gone.
        let history = vec![
            assistant_tool_call("First", &[("read", serde_json::json!({"path": "a.rs"}))]),
            ChatMessage::user("ok now do it\n\n<timestamp>2026-01-01 00:00:00 (UTC)</timestamp>"),
            assistant_tool_call("Second", &[("edit", serde_json::json!({"path": "b.rs"}))]),
        ];
        let ledger = build_ledger(&history);
        let groups = derive_trace_groups(current_turn_entries(&ledger));
        assert_eq!(groups.len(), 1, "only the post-turn group is shown");
        assert_eq!(groups[0].narration, "Second");
    }

    #[test]
    fn no_user_turn_shows_whole_history() {
        let history = vec![
            assistant_tool_call("A", &[("read", serde_json::json!({"path": "a.rs"}))]),
            assistant_tool_call("B", &[("edit", serde_json::json!({"path": "b.rs"}))]),
        ];
        let ledger = build_ledger(&history);
        let groups = derive_trace_groups(current_turn_entries(&ledger));
        assert_eq!(groups.len(), 2, "no boundary → whole ledger is current");
        assert_eq!(groups[0].narration, "A");
        assert_eq!(groups[1].narration, "B");
    }

    #[test]
    fn current_turn_without_tool_rounds_is_empty() {
        let history = vec![
            assistant_tool_call("A", &[("read", serde_json::json!({"path": "a.rs"}))]),
            ChatMessage::user("stop now\n\n<timestamp>2026-01-01 00:00:00 (UTC)</timestamp>"),
        ];
        let ledger = build_ledger(&history);
        let groups = derive_trace_groups(current_turn_entries(&ledger));
        assert!(
            groups.is_empty(),
            "no tool rounds after the last user turn → empty (clanking placeholder)"
        );
    }

    #[test]
    fn injected_image_and_empty_user_do_not_start_a_turn() {
        let history = vec![
            assistant_tool_call("", &[("read", serde_json::json!({"path": "a.rs"}))]),
            ChatMessage::user(crate::util::injected_image_user_message(
                "data:image/png;base64,xxx",
            )),
            ChatMessage::user(""),
            assistant_tool_call("", &[("edit", serde_json::json!({"path": "b.rs"}))]),
        ];
        let ledger = build_ledger(&history);
        let groups = derive_trace_groups(current_turn_entries(&ledger));
        assert_eq!(
            groups.len(),
            1,
            "injected + empty user messages are not boundaries"
        );
        assert_eq!(groups[0].rounds.len(), 2);
    }

    #[test]
    fn rounds_carry_results_for_in_flight_distinction() {
        // One assistant tool-call round with two calls; a tool result arrives
        // for only one of the two ids. After the ledger, one call is settled
        // and the other in-flight — both preserved in the group's round.
        let calls_json = serde_json::json!([
            {"id": "call_a", "name": "read", "arguments": "{\"path\": \"a.rs\"}"},
            {"id": "call_b", "name": "edit", "arguments": "{\"path\": \"b.rs\"}"},
        ]);
        let body = serde_json::json!({ "content": null, "tool_calls": calls_json });
        let history = vec![
            ChatMessage::assistant(body.to_string()),
            ChatMessage::tool_result("call_a", "contents of a.rs"),
        ];
        let ledger = build_ledger(&history);
        let groups = derive_trace_groups(&ledger);
        assert_eq!(groups.len(), 1);
        let round = &groups[0].rounds[0];
        assert_eq!(round.len(), 2, "both calls preserved in the round");
        let settled = round
            .iter()
            .find(|c| c.tool_call_id == "call_a")
            .expect("call_a present");
        assert_eq!(
            settled.result.as_deref(),
            Some("contents of a.rs"),
            "matched tool result attaches to call_a"
        );
        let in_flight = round
            .iter()
            .find(|c| c.tool_call_id == "call_b")
            .expect("call_b present");
        assert_eq!(
            in_flight.result, None,
            "call_b has no result yet → in-flight"
        );
    }

    #[test]
    fn promoted_reasoning_is_group_label() {
        // A silent round (empty narration) that carries a decoded Reasoning
        // block still forms exactly one group (boundary unchanged) and its
        // label is the promoted reasoning text — not a placeholder. A later
        // narrated round starts a second group (fragmentation did not grow).
        let history = vec![
            assistant_tool_call_reasoning(
                "",
                &[("read", serde_json::json!({"path": "a.rs"}))],
                Some("Checking the file first"),
            ),
            assistant_tool_call_reasoning(
                "Now editing",
                &[("edit", serde_json::json!({"path": "b.rs"}))],
                None,
            ),
        ];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 2, "new narration starts a second group");
        assert!(
            groups[0].narration.is_empty(),
            "silent round keeps empty narration"
        );
        assert!(
            matches!(
                group_label_text(&groups[0]),
                GroupLabelText::Promoted(s) if s == "Checking the file first"
            ),
            "silent round with reasoning labels as its promoted reasoning"
        );
        assert_eq!(groups[1].narration, "Now editing");
    }

    #[test]
    fn silent_round_without_reasoning_is_placeholder() {
        let history = vec![assistant_tool_call(
            "",
            &[("read", serde_json::json!({"path": "a.rs"}))],
        )];
        let groups = derive_trace_groups(&build_ledger(&history));
        assert_eq!(groups.len(), 1);
        assert!(
            matches!(group_label_text(&groups[0]), GroupLabelText::Placeholder),
            "no narration and no reasoning → neutral placeholder"
        );
    }

    #[test]
    fn promoted_label_caps_at_limit() {
        // A long multi-word reasoning is collapsed to one line and capped at
        // the word/path-delimiter boundary with "…" (the narration itself is
        // never truncated, but a promoted fallback must not dominate the card).
        let long = "word ".repeat(80); // 400 chars
        let capped = promoted_reasoning_label(&long);
        assert!(capped.ends_with('…'));
        assert!(
            capped.chars().count() <= MAX_PROMOTED_LABEL_CHARS + 1,
            "cap adds at most the trailing ellipsis"
        );
        // Short text passes through unchanged, with control chars collapsed.
        assert_eq!(promoted_reasoning_label("do it now"), "do it now");
        assert_eq!(promoted_reasoning_label("line1\nline2"), "line1 line2");
    }

    #[test]
    fn prune_expanded_drops_stale_keys() {
        let mut expanded: HashSet<(String, u64)> =
            HashSet::from([("a".to_string(), 0), ("b".to_string(), 2)]);
        let agents = vec![agent_handle("a", "analyst", None, "ws1", None)];
        prune_expanded(&mut expanded, &agents);
        assert_eq!(expanded.len(), 1);
        assert!(
            expanded.contains(&("a".to_string(), 0)),
            "live agent keeps its expanded key"
        );
    }
}