codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
//! Active tool-card routing helpers for the TUI loop.

use std::path::PathBuf;
use std::time::Instant;

use crate::hooks::HookEvent;
use crate::tools::ReviewOutput;
use crate::tools::apply_patch::{NormalizedApplyPatchInput, normalize_apply_patch_input};
use crate::tools::canonical_action::canonical_action_alias;
use crate::tools::plan::PlanSnapshot;
use crate::tools::spec::{ToolError, ToolResult};
use crate::tui::active_cell::ActiveCell;
use crate::tui::app::{App, ToolDetailRecord, ToolEvidence};
use crate::tui::history::{
    ExecCell, ExecSource, ExploringEntry, GenericToolCell, HistoryCell, McpToolCell,
    PatchSummaryCell, PlanUpdateCell, ReviewCell, ToolCell, ToolStatus, ViewImageCell,
    WebSearchCell, output_looks_like_diff, summarize_mcp_output, summarize_tool_args,
    summarize_tool_output,
};
use crate::tui::workspace_context;

#[allow(clippy::too_many_lines)]
pub(super) fn handle_tool_call_started(
    app: &mut App,
    id: &str,
    name: &str,
    input: &serde_json::Value,
) {
    // #2511: ToolCallBefore gate moved to turn-loop planning loop
    // (Engine::handle_deepseek_turn). Removing observer-only firing
    // here to avoid double-firing hooks for each tool call.
    // Hooks that need observation can configure ToolCallBefore on
    // the turn-loop gate — it processes the denial (exit code 2).

    let id = id.to_string();
    let semantic_name = canonical_action_alias(name, input);

    // All in-flight tool work for the current turn lives in `app.active_cell`
    // until the turn completes. This mirrors Codex's contract: ONE active cell
    // mutates in place; finalized history isn't touched until flush. This
    // keeps the transcript stable while parallel completions arrive in any
    // order.
    if app.active_cell.is_none() {
        app.active_cell = Some(ActiveCell::new());
    }

    if is_exploring_tool(semantic_name) {
        let label = exploring_label(semantic_name, input);
        // ensure_exploring + append_to_exploring keeps all parallel exploring
        // starts in a single ExploringCell entry.
        let active = app.active_cell.as_mut().expect("active_cell just ensured");
        let entry_idx = active.ensure_exploring();
        app.active_tool_entry_completed_at.remove(&entry_idx);
        let inner = active
            .append_to_exploring(
                id.clone(),
                ExploringEntry {
                    label,
                    status: ToolStatus::Running,
                },
            )
            .map_or(0, |(_, inner)| inner);
        app.exploring_cell = Some(entry_idx);
        let virtual_index = app.history.len() + entry_idx;
        app.exploring_entries
            .insert(id.clone(), (virtual_index, inner));
        register_tool_cell(app, &id, name, input, virtual_index);
        app.mark_history_updated();
        return;
    }

    // Non-exploring tool: each is its own entry inside the active cell. We
    // intentionally do NOT clear `exploring_cell` here — the active cell can
    // hold both an exploring aggregate AND independent tool entries
    // simultaneously, which is exactly the case CX#7 fixes.

    if is_exec_tool(semantic_name) {
        let command = exec_target_from_input(input);
        let source = exec_source_from_input(input);
        let interaction = exec_interaction_summary(semantic_name, input);
        let mut is_wait = false;

        if let Some((summary, wait)) = interaction.as_ref() {
            is_wait = *wait;
            if is_wait
                && app
                    .last_exec_wait_command
                    .as_ref()
                    .is_some_and(|last| last == &command)
            {
                app.ignored_tool_calls.insert(id);
                return;
            }
            if is_wait {
                app.last_exec_wait_command = Some(command.clone());
            }

            push_active_tool_cell(
                app,
                &id,
                name,
                input,
                HistoryCell::Tool(ToolCell::Exec(ExecCell {
                    command,
                    status: ToolStatus::Running,
                    output: None,
                    live_output: None,
                    shell_task_id: None,
                    owner_agent_id: None,
                    owner_agent_name: None,
                    started_at: Some(Instant::now()),
                    duration_ms: None,
                    stale_elapsed_since_output_ms: None,
                    source,
                    interaction: Some(summary.clone()),
                    output_summary: None,
                })),
            );
            return;
        }

        if exec_is_background(input)
            && app
                .last_exec_wait_command
                .as_ref()
                .is_some_and(|last| last == &command)
        {
            app.ignored_tool_calls.insert(id);
            return;
        }
        if exec_is_background(input) && !is_wait {
            app.last_exec_wait_command = Some(command.clone());
        }

        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::Exec(ExecCell {
                command,
                status: ToolStatus::Running,
                output: None,
                live_output: None,
                shell_task_id: None,
                owner_agent_id: None,
                owner_agent_name: None,
                started_at: Some(Instant::now()),
                duration_ms: None,
                stale_elapsed_since_output_ms: None,
                source,
                interaction: None,
                output_summary: None,
            })),
        );
        return;
    }

    if semantic_name == "update_plan" {
        let snapshot = parse_plan_input(input);
        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::PlanUpdate(PlanUpdateCell {
                snapshot,
                status: ToolStatus::Running,
            })),
        );
        return;
    }

    if matches!(semantic_name, "write_file" | "edit_file" | "apply_patch") {
        let (path, summary) = parse_file_mutation_summary(semantic_name, input);
        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell {
                path,
                summary,
                status: ToolStatus::Running,
                error: None,
                receipt: None,
            })),
        );
        return;
    }

    if semantic_name == "review" {
        let target = review_target_label(input);
        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::Review(ReviewCell {
                target,
                status: ToolStatus::Running,
                output: None,
                error: None,
            })),
        );
        return;
    }

    if is_mcp_tool(semantic_name) {
        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::Mcp(McpToolCell {
                tool: name.to_string(),
                status: ToolStatus::Running,
                content: None,
                is_image: false,
            })),
        );
        return;
    }

    if is_view_image_tool(semantic_name) {
        if let Some(path) = input.get("path").and_then(|v| v.as_str()) {
            let raw_path = PathBuf::from(path);
            let display_path = raw_path
                .strip_prefix(&app.workspace)
                .unwrap_or(&raw_path)
                .to_path_buf();
            push_active_tool_cell(
                app,
                &id,
                name,
                input,
                HistoryCell::Tool(ToolCell::ViewImage(ViewImageCell { path: display_path })),
            );
        }
        return;
    }

    if is_web_search_tool(semantic_name) {
        let query = web_search_query(input);
        push_active_tool_cell(
            app,
            &id,
            name,
            input,
            HistoryCell::Tool(ToolCell::WebSearch(WebSearchCell {
                query,
                status: ToolStatus::Running,
                summary: None,
                source: None,
                degraded: None,
                ref_count: 0,
            })),
        );
        return;
    }

    let mut input_summary = summarize_tool_args(input);
    // Lead the `agent` args summary with the non-default action so renderers
    // can tell inspections (peek/status/wait) apart from spawns without a
    // schema change — a peek must not draw the same "delegate done" line as
    // a launch (#4112, dogfood A5).
    if name == "agent"
        && let Some(action) = input.get("action").and_then(serde_json::Value::as_str)
    {
        let action = action.trim().to_ascii_lowercase();
        let already_leads = input_summary
            .as_deref()
            .is_some_and(|summary| summary.starts_with("action:"));
        if !action.is_empty()
            && !already_leads
            && action != "start"
            && action != "spawn"
            && action != "run"
        {
            input_summary = Some(match input_summary {
                Some(rest) => format!("action: {action} {rest}"),
                None => format!("action: {action}"),
            });
        }
    }
    push_active_tool_cell(
        app,
        &id,
        name,
        input,
        HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
            name: semantic_name.to_string(),
            status: ToolStatus::Running,
            input_summary,
            output: None,
            prompts: None,
            spillover_path: None,
            output_summary: None,
            is_diff: false,
        })),
    );
}

/// Push a tool cell as a new entry in `active_cell`, register the tool id,
/// and write a stub detail record so the pager / Ctrl+O can find it.
fn push_active_tool_cell(
    app: &mut App,
    tool_id: &str,
    tool_name: &str,
    input: &serde_json::Value,
    cell: HistoryCell,
) {
    if app.active_cell.is_none() {
        app.active_cell = Some(ActiveCell::new());
    }
    let active = app.active_cell.as_mut().expect("active_cell just ensured");
    let entry_idx = active.push_tool(tool_id.to_string(), cell);
    app.active_tool_entry_completed_at.remove(&entry_idx);
    let virtual_index = app.history.len() + entry_idx;
    register_tool_cell(app, tool_id, tool_name, input, virtual_index);
    app.mark_history_updated();
}

fn register_tool_cell(
    app: &mut App,
    tool_id: &str,
    tool_name: &str,
    input: &serde_json::Value,
    cell_index: usize,
) {
    app.tool_cells.insert(tool_id.to_string(), cell_index);
    let record = ToolDetailRecord {
        tool_id: tool_id.to_string(),
        tool_name: tool_name.to_string(),
        input: input.clone(),
        output: None,
    };
    if cell_index < app.history.len() {
        app.tool_details_by_cell.insert(cell_index, record);
    } else {
        // Active-cell entry: keep the detail record in `active_tool_details`
        // until the active cell flushes. `flush_active_cell` migrates these
        // records into `tool_details_by_cell` keyed by the eventual real
        // cell index.
        app.active_tool_details.insert(tool_id.to_string(), record);
    }
}

fn store_tool_detail_output(
    app: &mut App,
    tool_id: &str,
    cell_index: usize,
    result: &Result<ToolResult, ToolError>,
) {
    let payload = Some(match result {
        Ok(tool_result) => tool_result.content.clone(),
        Err(err) => err.to_string(),
    });
    if cell_index < app.history.len()
        && let Some(detail) = app.tool_details_by_cell.get_mut(&cell_index)
    {
        detail.output = payload.clone();
    }
    // Also write to the active table while the entry might still live there;
    // some callsites pre-rewrite cell_index but the active_tool_details map is
    // the canonical source for in-flight outputs.
    if let Some(detail) = app.active_tool_details.get_mut(tool_id) {
        detail.output = payload;
    }
}

#[allow(clippy::too_many_lines)]
/// Inspect a tool's success metadata for the `child_*` token-usage
/// fields that tools spawning their own LLM calls populate (e.g.
/// `rlm`). Roll any reported child-token cost into the session's
/// running sub-agent cost counter so the footer total reflects all
/// tokens the user is actually billed for, not just the parent turn's
/// tokens.
///
/// Without this hook, an RLM-heavy session shows a fraction of the
/// real spend because the parent turn's `Usage` only counts the
/// orchestrator's tokens, not the dozens of `deepseek-v4-flash` child
/// rounds RLM fans out under the hood (#524).
fn accrue_child_token_cost_if_any(app: &mut App, result: &Result<ToolResult, ToolError>) {
    let Ok(tool_result) = result else { return };
    let Some(metadata) = tool_result.metadata.as_ref() else {
        return;
    };
    let Some(route) = crate::cost_status::child_route_envelope_from_metadata(metadata) else {
        return;
    };
    // Use the same parser as the runtime host. It deliberately returns a
    // zero-valued usage record when the producer emitted the canonical child
    // fields: a model-backed call is still an auditable/priced-zero call, and
    // replay/server-tool telemetry must not disappear in the TUI projection.
    let Some(usage) = crate::cost_status::child_usage_from_metadata(metadata) else {
        return;
    };
    // `route` is the child's own dispatch receipt, rehydrated from the
    // complete `child_*` metadata `attach_child_usage_metadata` emits at the
    // child's wire boundary (review/verify/rlm are the three producers). An
    // incomplete or legacy payload rehydrates as `RouteBillingMode::Unknown`,
    // so a child never inherits the live `app.billing_presentation` chip and a
    // `/provider` switch between dispatch and arrival cannot retro-bill it.
    //
    // Sub-agent spend lands in the same displayed total as parent turns, so it
    // has to feed the same completeness counters — otherwise `/cost` would call
    // a total complete while an unpriced child turn is missing from it.
    let audit = route.audit(&usage);
    app.record_turn_cost_audit(&audit);
    app.record_turn_cost_route_receipt(route.receipt(&audit));
    if let Some(cost) = audit.estimate {
        app.accrue_subagent_cost_estimate(cost);
    }
}

fn record_spillover_artifact_if_any(
    app: &mut App,
    id: &str,
    name: &str,
    result: &Result<ToolResult, ToolError>,
) {
    let Ok(tool_result) = result else { return };
    let Some(path) = tool_result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("spillover_path"))
        .and_then(serde_json::Value::as_str)
        .map(PathBuf::from)
    else {
        return;
    };
    let metadata = tool_result.metadata.as_ref();
    let session_id = metadata
        .and_then(|metadata| metadata.get("artifact_session_id"))
        .and_then(serde_json::Value::as_str)
        .or(app.current_session_id.as_deref())
        .unwrap_or("");
    let storage_path = metadata
        .and_then(|metadata| metadata.get("artifact_relative_path"))
        .and_then(serde_json::Value::as_str)
        .map(PathBuf::from)
        .unwrap_or_else(|| path.clone());
    let content_for_preview = metadata
        .and_then(|metadata| metadata.get("artifact_preview"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or(&tool_result.content);
    let byte_size = metadata
        .and_then(|metadata| metadata.get("artifact_byte_size"))
        .and_then(serde_json::Value::as_u64)
        .unwrap_or_else(|| {
            std::fs::metadata(&storage_path)
                .map(|metadata| metadata.len())
                .unwrap_or(tool_result.content.len() as u64)
        });
    if app
        .session_artifacts
        .iter()
        .any(|artifact| artifact.tool_call_id == id && artifact.storage_path == storage_path)
    {
        return;
    }
    app.session_artifacts
        .push(crate::artifacts::record_tool_output_artifact_with_size(
            session_id,
            id,
            name,
            storage_path,
            byte_size,
            content_for_preview,
        ));
}

pub(super) fn evidence_completion_should_be_ignored(
    app: &App,
    id: &str,
    result: &Result<ToolResult, ToolError>,
) -> bool {
    evidence_completion_identity_should_be_ignored(
        app.current_session_id.as_deref(),
        app.session_artifacts
            .iter()
            .map(|artifact| (artifact.id.as_str(), artifact.tool_call_id.as_str())),
        id,
        result,
    )
}

fn evidence_completion_identity_should_be_ignored<'a>(
    current_session: Option<&str>,
    known_artifacts: impl IntoIterator<Item = (&'a str, &'a str)>,
    id: &str,
    result: &Result<ToolResult, ToolError>,
) -> bool {
    let Some(metadata) = result
        .as_ref()
        .ok()
        .and_then(|result| result.metadata.as_ref())
    else {
        return false;
    };
    let origin = metadata
        .get("artifact_session_id")
        .and_then(serde_json::Value::as_str);
    if let (Some(origin), Some(current)) = (origin, current_session)
        && origin != current
    {
        return true;
    }
    metadata
        .get("artifact_id")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|artifact_id| {
            known_artifacts
                .into_iter()
                .any(|(known_id, known_call)| known_id == artifact_id && known_call == id)
        })
}

/// #3031: shell/tasks tools embed the literal `"(no output)"` into successful
/// `ToolResult` content (the model-facing transcript needs a non-empty tool
/// result). Treat it as no output on the TUI side so the compact-mode
/// suppression gate in `history.rs` actually fires; the raw content remains
/// available through the tool-detail store.
fn visible_tool_output(content: &str) -> Option<String> {
    if content.trim() == "(no output)" {
        None
    } else {
        Some(content.to_string())
    }
}

/// Read the process exit code a tool reported, when it reported one.
///
/// Only process-backed tools (`exec_shell`, task runners) carry one, and only
/// a real, integer-valued `exit_code` counts. Everything else stays `None` so
/// an `exit_code` condition never matches on a fabricated value.
/// Reported as `i64`, not `i32`: a Windows crash code such as `3221225477`
/// (`0xC0000005`) is a real value the shell tool records in its metadata, and
/// narrowing it dropped exactly those codes — the hook saw no exit code at all
/// for the crashes it most wanted to catch.
pub(crate) fn reported_tool_exit_code(result: &Result<ToolResult, ToolError>) -> Option<i64> {
    let metadata = result.as_ref().ok()?.metadata.as_ref()?;
    let code = metadata.get("exit_code")?;
    if code.is_null() {
        return None;
    }
    code.as_i64()
}

/// Fire `tool_call_after` for every settled tool call, plus `on_error` when
/// the call failed.
///
/// `on_error` is documented as covering tool failures, not just transport and
/// auth failures, so the tool path has to raise it too — the engine-error path
/// in `apply_engine_error_to_app` never sees a tool that returned
/// `success: false`.
///
/// Both are observer events: their stdout is ignored and neither can change
/// the result that goes back to the model. That is a statement about
/// Codewhale's control flow only — the commands themselves are arbitrary
/// shells and may have any external side effect.
fn fire_tool_completion_hooks(
    app: &mut App,
    id: &str,
    name: &str,
    result: &Result<ToolResult, ToolError>,
) {
    let wants_after = app.hooks.has_hooks_for_event(HookEvent::ToolCallAfter);
    let wants_error = app
        .hooks
        .has_hooks_for_event(crate::hooks::HookEvent::OnError);
    if !wants_after && !wants_error {
        // Fast path: skip the result clone and HookContext allocation when
        // the user has configured neither event.
        return;
    }

    let (result_text, success): (String, bool) = match result.as_ref() {
        Ok(tool_result) => (tool_result.content.clone(), tool_result.success),
        Err(err) => (err.to_string(), false),
    };
    let exit_code = reported_tool_exit_code(result);

    if wants_after {
        let context = app
            .base_hook_context()
            .with_tool_name(name)
            .with_tool_call_id(id)
            .with_tool_result(&result_text, success, exit_code);
        if let Err(error) = app.submit_hooks(HookEvent::ToolCallAfter, context) {
            app.surface_observer_hook_submission_failure(error);
        }
    }

    if wants_error && !success {
        let context = app
            .base_hook_context()
            .with_tool_name(name)
            .with_tool_call_id(id)
            .with_tool_result(&result_text, success, exit_code)
            .with_error(&format!("tool `{name}` failed: {result_text}"));
        if let Err(error) = app.submit_hooks(crate::hooks::HookEvent::OnError, context) {
            app.surface_observer_hook_submission_failure(error);
        }
    }
}

pub(super) fn handle_tool_call_complete(
    app: &mut App,
    id: &str,
    name: &str,
    result: &Result<ToolResult, ToolError>,
) {
    if app.ignored_tool_calls.remove(id) {
        // "Ignored" is a *presentation* decision: these are real settled
        // results — repeated `wait` polls, background-shell status reads —
        // that the transcript deliberately does not redraw. Observers still
        // have to see them, or `tool_call_after` silently skips a whole class
        // of completions while claiming to fire after each tool call. Fired
        // here and returned immediately, so each id emits exactly once.
        fire_tool_completion_hooks(app, id, name, result);
        return;
    }
    // Preserve the execution/audit name while recovering the action-qualified
    // semantic name from the registered call input. Active entries and
    // already-flushed history use separate detail stores.
    let semantic_name = app
        .active_tool_details
        .get(id)
        .or_else(|| {
            app.tool_cells
                .get(id)
                .and_then(|cell_index| app.tool_details_by_cell.get(cell_index))
        })
        .map_or(name, |detail| canonical_action_alias(name, &detail.input))
        .to_string();

    // Roll any child-LLM token usage the tool reports into the
    // session-cost counter. Runs unconditionally so future tools that
    // spawn their own LLM calls (RLM, summarizers, retrieval helpers)
    // get accrued without needing a per-tool hook (#524).
    accrue_child_token_cost_if_any(app, result);
    record_spillover_artifact_if_any(app, id, name, result);

    // #455: fire `tool_call_after` (and `on_error` for failures) here, before
    // any of the presentation early-returns below. Firing it further down meant
    // exploring-tool completions and orphaned completions never emitted the
    // event at all, so "fires after each tool call" was not true.
    fire_tool_completion_hooks(app, id, name, result);

    // Exploring entries land in the per-tool map regardless of whether they
    // live in the active cell or in finalized history; the path is the same.
    if let Some((cell_index, entry_index)) = app.exploring_entries.remove(id) {
        app.tool_cells.remove(id);
        store_tool_detail_output(app, id, cell_index, result);
        if let Some(HistoryCell::Tool(ToolCell::Exploring(cell))) =
            app.cell_at_virtual_index_mut(cell_index)
            && let Some(entry) = cell.entries.get_mut(entry_index)
        {
            entry.status = tool_status_from_result(result);
            app.mark_history_updated();
            // Mutating the in-flight exploring cell needs an active-cell
            // revision bump so the transcript cache invalidates the synthetic
            // tail row.
            if cell_index >= app.history.len() {
                app.active_cell_revision = app.active_cell_revision.wrapping_add(1);
                if let Some(active) = app.active_cell.as_mut() {
                    active.bump_revision();
                }
            }
        }
        refresh_active_tool_completion_timestamp(app, cell_index);
        return;
    }

    // Look up the cell by tool id. If the id isn't registered, that's an
    // orphan completion (race condition where the started event was lost or
    // a tool result arrived after the active cell was already flushed). Build
    // a finalized standalone cell from the result so the user can still see
    // the output, but DO NOT touch the active cell.
    let Some(cell_index) = app.tool_cells.remove(id) else {
        push_orphan_tool_completion(app, id, name, result);
        return;
    };

    store_tool_detail_output(app, id, cell_index, result);
    let in_active = cell_index >= app.history.len();

    let status = tool_status_from_result(result);
    let mutation_receipt = matches!(
        semantic_name.as_str(),
        "write_file" | "edit_file" | "apply_patch"
    )
    .then(|| {
        result.as_ref().ok().and_then(|tool_result| {
            crate::tui::history::FileMutationReceipt::from_success(&app.workspace, tool_result)
        })
    })
    .flatten();
    let mut workflow_panel_output: Option<String> = None;

    if let Some(cell) = app.cell_at_virtual_index_mut(cell_index) {
        match cell {
            HistoryCell::Tool(ToolCell::Exec(exec)) => {
                exec.status = status;
                if let Ok(tool_result) = result.as_ref() {
                    let shell_task_id = tool_result
                        .metadata
                        .as_ref()
                        .and_then(|m| m.get("task_id"))
                        .and_then(serde_json::Value::as_str)
                        .filter(|task_id| !task_id.trim().is_empty())
                        .map(str::to_string);
                    if shell_task_id.is_some() {
                        exec.shell_task_id = shell_task_id;
                    }
                    exec.owner_agent_id = tool_result
                        .metadata
                        .as_ref()
                        .and_then(|m| m.get("owner_agent_id"))
                        .and_then(serde_json::Value::as_str)
                        .filter(|agent_id| !agent_id.trim().is_empty())
                        .map(str::to_string);
                    exec.owner_agent_name = tool_result
                        .metadata
                        .as_ref()
                        .and_then(|m| m.get("owner_agent_name"))
                        .and_then(serde_json::Value::as_str)
                        .filter(|agent_name| !agent_name.trim().is_empty())
                        .map(str::to_string);
                    if let Some(meta_command) = tool_result
                        .metadata
                        .as_ref()
                        .and_then(|m| m.get("command"))
                        .and_then(serde_json::Value::as_str)
                        && !meta_command.trim().is_empty()
                        && (exec.command == "command" || exec.command.starts_with("command "))
                    {
                        exec.command = meta_command.to_string();
                        if exec.interaction.as_deref().is_some_and(|interaction| {
                            interaction.starts_with("Waiting for command")
                        }) {
                            let task_suffix = tool_result
                                .metadata
                                .as_ref()
                                .and_then(|m| m.get("task_id"))
                                .and_then(serde_json::Value::as_str)
                                .map(|task_id| format!(" ({task_id})"))
                                .unwrap_or_default();
                            exec.interaction =
                                Some(format!("Waiting for \"{meta_command}\"{task_suffix}"));
                        }
                    }
                    exec.duration_ms = tool_result
                        .metadata
                        .as_ref()
                        .and_then(|m| m.get("duration_ms"))
                        .and_then(serde_json::Value::as_u64);
                    if status != ToolStatus::Running && exec.interaction.is_none() {
                        exec.output = visible_tool_output(&tool_result.content);
                        exec.output_summary = exec
                            .output
                            .as_deref()
                            .map(super::history::summarize_tool_output);
                        exec.live_output = None;
                    } else if status == ToolStatus::Running
                        && exec.interaction.is_none()
                        && !tool_result.content.is_empty()
                    {
                        exec.live_output = Some(tool_result.content.clone());
                    }
                } else if let Err(err) = result.as_ref()
                    && exec.interaction.is_none()
                {
                    exec.output = Some(err.to_string());
                    exec.output_summary =
                        Some(super::history::summarize_tool_output(&err.to_string()));
                }
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::PlanUpdate(plan)) => {
                plan.status = status;
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::PatchSummary(patch)) => {
                patch.status = status;
                patch.receipt = mutation_receipt;
                match result.as_ref() {
                    Ok(tool_result) if tool_result.success => {
                        if let Ok(json) =
                            serde_json::from_str::<serde_json::Value>(&tool_result.content)
                            && let Some(message) = json.get("message").and_then(|v| v.as_str())
                        {
                            patch.summary = message.to_string();
                        }
                    }
                    Ok(tool_result) => {
                        patch.error = Some(tool_result.content.clone());
                    }
                    Err(err) => {
                        patch.error = Some(err.to_string());
                    }
                }
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::Review(review)) => {
                review.status = status;
                match result.as_ref() {
                    Ok(tool_result) => {
                        if tool_result.success {
                            review.output = Some(ReviewOutput::from_str(&tool_result.content));
                        } else {
                            review.error = Some(tool_result.content.clone());
                        }
                    }
                    Err(err) => {
                        review.error = Some(err.to_string());
                    }
                }
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::Mcp(mcp)) => {
                match result.as_ref() {
                    Ok(tool_result) => {
                        let summary = summarize_mcp_output(&tool_result.content);
                        if status == ToolStatus::Hydrated {
                            mcp.status = status;
                        } else if summary.is_error == Some(true) {
                            mcp.status = ToolStatus::Failed;
                        } else {
                            mcp.status = status;
                        }
                        mcp.is_image = summary.is_image;
                        mcp.content = summary.content;
                    }
                    Err(err) => {
                        mcp.status = status;
                        mcp.content = Some(err.to_string());
                    }
                }
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::WebSearch(search)) => {
                search.status = status;
                match result.as_ref() {
                    Ok(tool_result) => {
                        search.summary = Some(summarize_tool_output(&tool_result.content));
                        let presentation = web_search_presentation(&tool_result.content);
                        search.source = presentation.source;
                        search.degraded = presentation.degraded;
                        search.ref_count = presentation.ref_count;
                    }
                    Err(err) => {
                        search.summary = Some(err.to_string());
                    }
                }
                app.mark_history_updated();
            }
            HistoryCell::Tool(ToolCell::Generic(generic)) => {
                generic.status = status;
                match result.as_ref() {
                    Ok(tool_result) => {
                        generic.output = visible_tool_output(&tool_result.content);
                        generic.output_summary =
                            generic.output.as_deref().map(summarize_tool_output);
                        generic.is_diff = output_looks_like_diff(&tool_result.content);
                    }
                    Err(err) => {
                        generic.output = Some(err.to_string());
                        generic.output_summary = Some(summarize_tool_output(&err.to_string()));
                        generic.is_diff = false;
                    }
                }
                // #4121: capture workflow JSON before releasing the cell borrow
                // so we can hydrate the panel without overlapping borrows.
                if generic.name == "workflow" {
                    workflow_panel_output = generic.output.clone();
                }
                app.mark_history_updated();
            }
            _ => {}
        }
    }

    // #4121 / #4122: feed typed workflow events into the panel *and* keep the
    // history card snapshot in sync. Live streaming also arrives via
    // `Event::WorkflowUi`; this path covers tool-complete hydration.
    if let Some(output) = workflow_panel_output.as_deref() {
        apply_workflow_output_to_panel(app, output);
    }

    // If the mutated cell lived inside the active group, bump the active-cell
    // revision so the transcript cache re-renders the synthetic tail row.
    if in_active {
        app.active_cell_revision = app.active_cell_revision.wrapping_add(1);
        if let Some(active) = app.active_cell.as_mut() {
            active.bump_revision();
        }
        refresh_active_tool_completion_timestamp(app, cell_index);
    }

    if refreshes_workspace_context_on_completion(&semantic_name) && status != ToolStatus::Running {
        workspace_context::refresh_now(app, Instant::now());
    }

    // Collect evidence for the post-turn receipt.
    let evidence_summary = match result.as_ref() {
        Ok(tool_result) => {
            if tool_result.success {
                summarize_tool_output(&tool_result.content)
            } else {
                format!("failed: {}", summarize_tool_output(&tool_result.content))
            }
        }
        Err(err) => format!("error: {err}"),
    };
    app.tool_evidence.push(ToolEvidence {
        tool_name: name.to_string(),
        summary: evidence_summary,
    });
}

#[derive(Debug, Default, PartialEq, Eq)]
struct WebSearchPresentation {
    source: Option<String>,
    degraded: Option<String>,
    ref_count: usize,
}

fn web_search_presentation(content: &str) -> WebSearchPresentation {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(content) else {
        return WebSearchPresentation::default();
    };
    let surfaces = if value.get("receipt").is_some() {
        vec![&value]
    } else {
        value
            .get("search_query")
            .and_then(serde_json::Value::as_array)
            .map(|items| items.iter().collect())
            .unwrap_or_default()
    };
    let source = surfaces
        .iter()
        .filter_map(|surface| surface.get("source").and_then(serde_json::Value::as_str))
        .map(str::to_string)
        .next();
    let mut degraded = Vec::new();
    let mut ref_count = 0usize;
    for surface in surfaces {
        if let Some(results) = surface.get("results").and_then(serde_json::Value::as_array) {
            ref_count = ref_count.saturating_add(
                results
                    .iter()
                    .filter(|result| {
                        result
                            .get("ref_id")
                            .and_then(serde_json::Value::as_str)
                            .is_some_and(|ref_id| !ref_id.is_empty())
                    })
                    .count(),
            );
        }
        if let Some(reasons) = surface
            .pointer("/receipt/degraded")
            .and_then(serde_json::Value::as_array)
        {
            for reason in reasons {
                if let Some(label) = degraded_reason_label(reason)
                    && !degraded.contains(&label)
                {
                    degraded.push(label);
                }
            }
        }
    }
    WebSearchPresentation {
        source,
        degraded: (!degraded.is_empty()).then(|| degraded.join("; ")),
        ref_count,
    }
}

fn degraded_reason_label(reason: &serde_json::Value) -> Option<String> {
    let kind = reason.get("kind")?.as_str()?;
    let backend = |field: &str| {
        reason
            .get(field)
            .and_then(serde_json::Value::as_str)
            .unwrap_or("unknown")
    };
    Some(match kind {
        "backend_unavailable" => format!("{} unavailable", backend("backend")),
        "no_usable_results" => format!("{} returned no usable results", backend("backend")),
        "backend_fallback" => format!("{} -> {}", backend("from"), backend("to")),
        "challenge_detected" => format!("{} challenge", backend("backend")),
        "scrape_fallback" => format!("{} -> {} scrape", backend("from"), backend("to")),
        "knob_ignored" => format!(
            "{} ignored",
            reason
                .get("knob")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("filter")
        ),
        "post_filtered" => format!(
            "{} post-filtered",
            reason
                .get("knob")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("results")
        ),
        "synthesized_results" => "synthesized results".to_string(),
        other => other.replace('_', " "),
    })
}

/// Hydrate or advance the WorkflowPanel from a workflow tool JSON payload.
/// Accepts a single run record (with optional `events` array) or a status
/// list. Log-only events are filtered by the panel itself so the transcript
/// stays free of progress spam (#4121). Also keeps the matching history card
/// snapshot aligned (#4122).
fn apply_workflow_output_to_panel(app: &mut App, output: &str) {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(output) else {
        return;
    };

    // Prefer the typed event stream when present.
    if let Some(events) = value.get("events").and_then(|e| e.as_array()) {
        // Ensure a panel exists before applying — seed from run_id/goal if needed.
        if app.workflow_panel.is_none() {
            let run_id = value
                .get("run_id")
                .and_then(|v| v.as_str())
                .unwrap_or("workflow")
                .to_string();
            let label = value
                .get("workflow_goal")
                .and_then(|v| v.as_str())
                .or_else(|| value.get("workflow_id").and_then(|v| v.as_str()))
                .unwrap_or("workflow")
                .to_string();
            let at_ms = value
                .get("started_at_ms")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let mut panel =
                crate::tui::widgets::workflow_panel::WorkflowPanel::new(run_id, label, at_ms);
            panel.locale = app.ui_locale;
            app.workflow_panel = Some(panel);
        }
        if let Some(panel) = app.workflow_panel.as_mut() {
            let run_id = value
                .get("run_id")
                .and_then(|v| v.as_str())
                .unwrap_or(&panel.run_id)
                .to_string();
            let mut injected = Vec::with_capacity(events.len());
            for event in events {
                let mut event = event.clone();
                if let Some(obj) = event.as_object_mut() {
                    obj.entry("run_id".to_string())
                        .or_insert_with(|| serde_json::Value::String(run_id.clone()));
                }
                injected.push(event);
            }
            panel.apply_json_events(&injected);
            // Carry final result / source into panel for expanded history card.
            if let Some(summary) = value
                .get("result")
                .map(|v| v.to_string())
                .filter(|s| s != "null")
            {
                panel.result_summary = Some(summary);
            }
            if let Some(path) = value.get("source_path").and_then(|v| v.as_str()) {
                panel.source_path = Some(PathBuf::from(path));
            }
            app.needs_redraw = true;
        }
        sync_workflow_history_card_from_panel(app);
        return;
    }

    // Fallback: status list — show the most recent run as a shell panel.
    if value.get("action").and_then(|v| v.as_str()) == Some("status") {
        if let Some(runs) = value.get("runs").and_then(|r| r.as_array())
            && let Some(run) = runs.last()
        {
            apply_workflow_output_to_panel(app, &run.to_string());
        }
        return;
    }

    // Prefer full panel hydration from summary/phases snapshot when present.
    if let Some(mut panel) =
        crate::tui::widgets::workflow_panel::WorkflowPanel::from_run_json(&value)
    {
        panel.locale = app.ui_locale;
        app.workflow_panel = Some(panel);
        app.needs_redraw = true;
        sync_workflow_history_card_from_panel(app);
        return;
    }

    // Fallback: bare run record without events — at least surface header state.
    if let Some(run_id) = value.get("run_id").and_then(|v| v.as_str()) {
        use crate::tui::widgets::workflow_panel::{WorkflowPanelEvent, WorkflowPanelLifecycle};
        let label = value
            .get("workflow_goal")
            .and_then(|v| v.as_str())
            .or_else(|| value.get("workflow_id").and_then(|v| v.as_str()))
            .unwrap_or(run_id)
            .to_string();
        let at_ms = value
            .get("started_at_ms")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let status = value
            .get("status")
            .and_then(|v| v.as_str())
            .unwrap_or("running");
        app.apply_workflow_panel_event(WorkflowPanelEvent::RunStarted {
            run_id: run_id.to_string(),
            workflow_id: value
                .get("workflow_id")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            workflow_goal: Some(label),
            source_path: value
                .get("source_path")
                .and_then(|v| v.as_str())
                .map(PathBuf::from),
            token_budget: value.get("token_budget").and_then(|v| v.as_u64()),
            at_ms,
        });
        if status != "running" {
            let life = match status {
                "completed" | "succeeded" => WorkflowPanelLifecycle::Succeeded,
                "failed" => WorkflowPanelLifecycle::Failed,
                "cancelled" | "canceled" => WorkflowPanelLifecycle::Cancelled,
                _ => WorkflowPanelLifecycle::Running,
            };
            if life != WorkflowPanelLifecycle::Running {
                app.apply_workflow_panel_event(WorkflowPanelEvent::RunCompleted {
                    status: life,
                    error: value
                        .get("error")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    at_ms: value
                        .get("completed_at_ms")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(at_ms),
                });
            }
        }
        sync_workflow_history_card_from_panel(app);
    }
}

/// Apply one live `WorkflowUi` engine event to the panel and history card.
pub(super) fn apply_workflow_ui_event(app: &mut App, run_id: &str, event: &serde_json::Value) {
    use crate::tui::widgets::workflow_panel::WorkflowPanelEvent;

    let mut event = event.clone();
    if let Some(obj) = event.as_object_mut() {
        obj.entry("run_id".to_string())
            .or_insert_with(|| serde_json::Value::String(run_id.to_string()));
    }
    if let Some(panel_event) = WorkflowPanelEvent::from_json_value(&event) {
        app.apply_workflow_panel_event(panel_event);
    }
    sync_workflow_history_card_from_panel(app);
}

/// Mirror the live WorkflowPanel snapshot into the in-flight (or most recent)
/// workflow history tool cell so compact/expanded cards stay current.
fn sync_workflow_history_card_from_panel(app: &mut App) {
    let Some(panel) = app.workflow_panel.as_ref() else {
        return;
    };
    let run_id = panel.run_id.clone();
    let snapshot = panel.to_run_json().to_string();

    // Prefer an in-flight Generic(workflow) cell whose output already carries
    // this run_id, else the newest running workflow cell, else any workflow
    // cell (tool-complete path already wrote the final output).
    let mut target: Option<usize> = None;
    let history_len = app.history.len();
    let total = history_len
        + app
            .active_cell
            .as_ref()
            .map(|a| a.entries().len())
            .unwrap_or(0);

    for idx in (0..total).rev() {
        let Some(cell) = app.cell_at_virtual_index(idx) else {
            continue;
        };
        let HistoryCell::Tool(ToolCell::Generic(generic)) = cell else {
            continue;
        };
        if generic.name != "workflow" {
            continue;
        }
        let matches_run = generic
            .output
            .as_deref()
            .and_then(|out| serde_json::from_str::<serde_json::Value>(out).ok())
            .and_then(|v| {
                v.get("run_id")
                    .and_then(|id| id.as_str())
                    .map(|id| id == run_id)
            })
            .unwrap_or(false);
        let is_running = generic.status == ToolStatus::Running;
        if matches_run || (is_running && target.is_none()) {
            target = Some(idx);
            if matches_run {
                break;
            }
        }
    }

    let Some(idx) = target else {
        return;
    };
    if let Some(HistoryCell::Tool(ToolCell::Generic(generic))) = app.cell_at_virtual_index_mut(idx)
    {
        // Preserve a richer final output if the tool completion already wrote
        // a full run record with an events array longer than the snapshot.
        let replace = match generic.output.as_deref() {
            None => true,
            Some(existing) => {
                let Ok(value) = serde_json::from_str::<serde_json::Value>(existing) else {
                    return;
                };
                let existing_run = value.get("run_id").and_then(|v| v.as_str()).unwrap_or("");
                if !existing_run.is_empty() && existing_run != run_id {
                    return;
                }
                // Prefer full event-bearing records when the tool has completed.
                if generic.status == ToolStatus::Running {
                    true
                } else {
                    value
                        .get("events")
                        .and_then(|e| e.as_array())
                        .is_none_or(|e| e.is_empty())
                }
            }
        };
        if replace {
            generic.output = Some(snapshot);
            generic.output_summary = Some(format!("workflow {}", run_id));
            app.mark_history_updated();
        }
    }
}

fn refresh_active_tool_completion_timestamp(app: &mut App, cell_index: usize) {
    if cell_index < app.history.len() {
        return;
    }
    let entry_idx = cell_index - app.history.len();
    let Some(cell) = app.cell_at_virtual_index(cell_index) else {
        app.active_tool_entry_completed_at.remove(&entry_idx);
        return;
    };

    if history_cell_has_running_tool(cell) {
        app.active_tool_entry_completed_at.remove(&entry_idx);
    } else {
        app.active_tool_entry_completed_at
            .entry(entry_idx)
            .or_insert_with(Instant::now);
    }
}

fn history_cell_has_running_tool(cell: &HistoryCell) -> bool {
    let HistoryCell::Tool(tool) = cell else {
        return false;
    };
    match tool {
        ToolCell::Exec(exec) => exec.status == ToolStatus::Running,
        ToolCell::Exploring(explore) => explore
            .entries
            .iter()
            .any(|entry| entry.status == ToolStatus::Running),
        ToolCell::PlanUpdate(plan) => plan.status == ToolStatus::Running,
        ToolCell::PatchSummary(patch) => patch.status == ToolStatus::Running,
        ToolCell::Review(review) => review.status == ToolStatus::Running,
        ToolCell::Mcp(mcp) => mcp.status == ToolStatus::Running,
        ToolCell::ViewImage(_) => false,
        ToolCell::WebSearch(search) => search.status == ToolStatus::Running,
        ToolCell::Generic(generic) => generic.status == ToolStatus::Running,
    }
}

/// Build a finalized standalone history cell for a tool completion whose
/// start was never registered (orphan). This preserves the contract that
/// every tool result is visible somewhere; the alternative (silently
/// dropping it) hides errors and breaks debuggability.
///
/// Choice of cell type: success-only mutation metadata is sufficient to
/// reconstruct a structured File receipt; other orphans stay generic because
/// no input payload remains. The pager remains usable in both cases because
/// `tool_details_by_cell` is populated with the result text.
///
/// ## Index drift
///
/// If an active cell is in flight when the orphan arrives, pushing the
/// orphan into `app.history` shifts every active-cell virtual index forward
/// by 1. We must rewrite `tool_cells` / `exploring_entries` accordingly so
/// later completion lookups still find the right entries.
fn push_orphan_tool_completion(
    app: &mut App,
    tool_id: &str,
    name: &str,
    result: &Result<ToolResult, ToolError>,
) {
    let status = tool_status_from_result(result);
    let output = match result.as_ref() {
        Ok(tool_result) => Some(summarize_tool_output(&tool_result.content)),
        Err(err) => Some(err.to_string()),
    };
    let history_threshold_before_push = app.history.len();
    let active_in_flight = app.active_cell.is_some();
    let spillover_path = result
        .as_ref()
        .ok()
        .and_then(|r| r.metadata.as_ref())
        .and_then(|m| m.get("spillover_path"))
        .and_then(serde_json::Value::as_str)
        .map(std::path::PathBuf::from);
    let output_summary = output.as_deref().map(summarize_tool_output);
    let is_diff = output.as_deref().is_some_and(output_looks_like_diff);
    let mutation_receipt = result.as_ref().ok().and_then(|tool_result| {
        crate::tui::history::FileMutationReceipt::from_success(&app.workspace, tool_result)
    });
    let cell = if let Some(receipt) = mutation_receipt {
        let path = receipt
            .files
            .first()
            .map_or_else(|| "<file>".to_string(), |file| file.path.clone());
        let summary = receipt.semantic_summary();
        HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell {
            path,
            summary,
            status,
            error: None,
            receipt: Some(receipt),
        }))
    } else {
        HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
            name: name.to_string(),
            status,
            input_summary: None,
            output,
            prompts: None,
            spillover_path,
            output_summary,
            is_diff,
        }))
    };
    app.add_message(cell);
    let cell_index = app.history.len().saturating_sub(1);
    app.tool_details_by_cell.insert(
        cell_index,
        ToolDetailRecord {
            tool_id: tool_id.to_string(),
            tool_name: name.to_string(),
            input: serde_json::Value::Null,
            output: match result.as_ref() {
                Ok(tool_result) => Some(tool_result.content.clone()),
                Err(err) => Some(err.to_string()),
            },
        },
    );

    // Shift active-cell virtual indices forward by 1 to absorb the new
    // history cell. Without this, the next completion would address the
    // wrong entry.
    if active_in_flight {
        let threshold = history_threshold_before_push;
        for idx in app.tool_cells.values_mut() {
            if *idx >= threshold {
                *idx = idx.wrapping_add(1);
            }
        }
        for (cell_idx, _) in app.exploring_entries.values_mut() {
            if *cell_idx >= threshold {
                *cell_idx = cell_idx.wrapping_add(1);
            }
        }
        if let Some(idx) = app.exploring_cell.as_mut()
            && *idx >= threshold
        {
            *idx = idx.wrapping_add(1);
        }
    }
}

fn tool_status_from_result(result: &Result<ToolResult, ToolError>) -> ToolStatus {
    match result.as_ref() {
        Ok(tool_result) if is_deferred_schema_hydration(tool_result) => ToolStatus::Hydrated,
        Ok(tool_result) => match tool_result.metadata.as_ref() {
            Some(meta)
                if meta
                    .get("status")
                    .and_then(|v| v.as_str())
                    .is_some_and(|s| s == "Running") =>
            {
                ToolStatus::Running
            }
            _ => {
                if tool_result.success {
                    ToolStatus::Success
                } else {
                    ToolStatus::Failed
                }
            }
        },
        Err(_) => ToolStatus::Failed,
    }
}

fn is_deferred_schema_hydration(tool_result: &ToolResult) -> bool {
    if !tool_result.success {
        return false;
    }
    let Some(metadata) = tool_result.metadata.as_ref() else {
        return false;
    };
    metadata
        .get("event")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|event| event == "tool.schema_hydrated")
        && metadata
            .get("executed")
            .and_then(serde_json::Value::as_bool)
            .is_some_and(|executed| !executed)
}

fn is_exploring_tool(name: &str) -> bool {
    matches!(name, "read_file" | "list_dir" | "grep_files" | "list_files")
}

fn is_exec_tool(name: &str) -> bool {
    matches!(
        name,
        "exec_shell"
            | "exec_shell_wait"
            | "exec_shell_interact"
            | "exec_shell_cancel"
            | "exec_wait"
            | "exec_interact"
    )
}

pub(super) fn refreshes_workspace_context_on_completion(name: &str) -> bool {
    matches!(
        name,
        "exec_shell"
            | "exec_shell_wait"
            | "exec_shell_interact"
            | "exec_shell_cancel"
            | "exec_wait"
            | "exec_interact"
            | "task_shell_start"
            | "task_shell_wait"
            | "write_file"
            | "edit_file"
            | "apply_patch"
    )
}

pub(super) fn exploring_label(name: &str, input: &serde_json::Value) -> String {
    let fallback = format!("{name} tool");
    let obj = input.as_object();
    match name {
        "read_file" => obj
            .and_then(|o| o.get("path"))
            .and_then(|v| v.as_str())
            .map_or(fallback, |path| format!("Reading {path}")),
        "list_dir" => obj
            .and_then(|o| o.get("path"))
            .and_then(|v| v.as_str())
            .map_or("Listing directory".to_string(), |path| {
                format!("Listing {path}")
            }),
        "grep_files" => {
            let pattern = obj
                .and_then(|o| o.get("pattern"))
                .and_then(|v| v.as_str())
                .unwrap_or("pattern");
            format!("Searching for `{pattern}`")
        }
        "list_files" => "Listing files".to_string(),
        _ => fallback,
    }
}

fn is_mcp_tool(name: &str) -> bool {
    name.starts_with("mcp_")
}

fn is_view_image_tool(name: &str) -> bool {
    matches!(name, "view_image" | "view_image_file" | "view_image_tool")
}

fn is_web_search_tool(name: &str) -> bool {
    matches!(name, "web_search" | "search_web" | "search" | "web.run")
        || name.ends_with("_web_search")
}

fn web_search_query(input: &serde_json::Value) -> String {
    if let Some(searches) = input.get("search_query").and_then(|v| v.as_array())
        && let Some(first) = searches.first()
        && let Some(q) = first.get("q").and_then(|v| v.as_str())
    {
        return q.to_string();
    }

    input
        .get("query")
        .or_else(|| input.get("q"))
        .or_else(|| input.get("search"))
        .and_then(|v| v.as_str())
        .unwrap_or("Web search")
        .to_string()
}

fn review_target_label(input: &serde_json::Value) -> String {
    let target = input
        .get("target")
        .and_then(|v| v.as_str())
        .unwrap_or("review")
        .trim();
    let kind = input
        .get("kind")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    let staged = input
        .get("staged")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let target_lower = target.to_ascii_lowercase();

    if kind == "diff"
        || target_lower == "diff"
        || target_lower == "git diff"
        || target_lower == "staged"
        || target_lower == "cached"
    {
        if staged || target_lower == "staged" || target_lower == "cached" {
            return "git diff --cached".to_string();
        }
        return "git diff".to_string();
    }

    target.to_string()
}

fn parse_plan_input(input: &serde_json::Value) -> PlanSnapshot {
    PlanSnapshot::from_tool_input(input)
}

fn parse_file_mutation_summary(semantic_name: &str, input: &serde_json::Value) -> (String, String) {
    if semantic_name != "apply_patch" {
        let path = input
            .get("path")
            .and_then(serde_json::Value::as_str)
            .filter(|path| !path.trim().is_empty())
            .unwrap_or("<file>")
            .to_string();
        let summary = match semantic_name {
            "write_file" => "Writing file",
            "edit_file" => "Editing file",
            _ => "Changing file",
        }
        .to_string();
        return (path, summary);
    }
    let patch_text = match normalize_apply_patch_input(input) {
        Ok(NormalizedApplyPatchInput::Replacement {
            entries: changes, ..
        }) => {
            let count = changes.len();
            let path = changes
                .first()
                .and_then(|c| c.get("path"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| "<file>".to_string());
            let label = if count <= 1 {
                path
            } else {
                format!("{count} files")
            };
            let summary = format!("Changes: {count} file(s)");
            return (label, summary);
        }
        Ok(NormalizedApplyPatchInput::Patch(patch)) => patch,
        Err(_) => "",
    };
    let paths = extract_patch_paths(patch_text);
    let path = input
        .get("path")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .or_else(|| {
            if paths.len() == 1 {
                paths.first().cloned()
            } else if paths.is_empty() {
                None
            } else {
                Some(format!("{} files", paths.len()))
            }
        })
        .unwrap_or_else(|| "<file>".to_string());

    let (adds, removes) = count_patch_changes(patch_text);
    let summary = if adds == 0 && removes == 0 {
        "Patch applied".to_string()
    } else {
        format!("Changes: +{adds} / -{removes}")
    };
    (path, summary)
}

fn extract_patch_paths(patch: &str) -> Vec<String> {
    let mut paths = Vec::new();
    for line in patch.lines() {
        if let Some(rest) = line.strip_prefix("+++ ") {
            let raw = rest.trim();
            if raw == "/dev/null" || raw == "dev/null" {
                continue;
            }
            let raw = raw.strip_prefix("b/").unwrap_or(raw);
            if !paths.contains(&raw.to_string()) {
                paths.push(raw.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("diff --git ") {
            let parts: Vec<&str> = rest.split_whitespace().collect();
            if let Some(path) = parts.get(1).or_else(|| parts.first()) {
                let raw = path.trim();
                let raw = raw
                    .strip_prefix("b/")
                    .or_else(|| raw.strip_prefix("a/"))
                    .unwrap_or(raw);
                if !paths.contains(&raw.to_string()) {
                    paths.push(raw.to_string());
                }
            }
        }
    }
    paths
}

fn count_patch_changes(patch: &str) -> (usize, usize) {
    let mut adds = 0;
    let mut removes = 0;
    for line in patch.lines() {
        if line.starts_with("+++") || line.starts_with("---") {
            continue;
        }
        if line.starts_with('+') {
            adds += 1;
        } else if line.starts_with('-') {
            removes += 1;
        }
    }
    (adds, removes)
}

fn exec_command_from_input(input: &serde_json::Value) -> Option<String> {
    input
        .get("command")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string)
}

fn exec_target_from_input(input: &serde_json::Value) -> String {
    exec_command_from_input(input).unwrap_or_else(|| {
        input
            .get("task_id")
            .or_else(|| input.get("id"))
            .and_then(|v| v.as_str())
            .map(|task_id| format!("command {task_id}"))
            .unwrap_or_else(|| "command".to_string())
    })
}

fn exec_source_from_input(input: &serde_json::Value) -> ExecSource {
    match input.get("source").and_then(|v| v.as_str()) {
        Some(source) if source.eq_ignore_ascii_case("user") => ExecSource::User,
        _ => ExecSource::Assistant,
    }
}

fn exec_interaction_summary(name: &str, input: &serde_json::Value) -> Option<(String, bool)> {
    let command = exec_target_from_input(input);
    let command_display = format!("\"{command}\"");
    let interaction_input = input
        .get("input")
        .or_else(|| input.get("stdin"))
        .or_else(|| input.get("data"))
        .and_then(|v| v.as_str());

    let is_wait_tool = matches!(name, "exec_shell_wait" | "exec_wait");
    let is_interact_tool = matches!(name, "exec_shell_interact" | "exec_interact");
    let is_cancel_tool = name == "exec_shell_cancel";

    if is_cancel_tool {
        let summary = if input.get("all").and_then(serde_json::Value::as_bool) == Some(true) {
            "Cancelled all background commands".to_string()
        } else if let Some(task_id) = input
            .get("task_id")
            .or_else(|| input.get("id"))
            .and_then(serde_json::Value::as_str)
        {
            format!("Cancelled command {task_id}")
        } else {
            "Cancelled background command".to_string()
        };
        return Some((summary, false));
    }

    if is_interact_tool || interaction_input.is_some() {
        let preview = interaction_input.map(summarize_interaction_input);
        let summary = if let Some(preview) = preview {
            format!("Interacted with {command_display}, sent {preview}")
        } else {
            format!("Interacted with {command_display}")
        };
        return Some((summary, false));
    }

    if is_wait_tool || input.get("wait").and_then(serde_json::Value::as_bool) == Some(true) {
        if exec_command_from_input(input).is_none()
            && let Some(task_id) = input
                .get("task_id")
                .or_else(|| input.get("id"))
                .and_then(|v| v.as_str())
        {
            return Some((format!("Waiting for command {task_id}"), true));
        }
        return Some((format!("Waited for {command_display}"), true));
    }

    None
}

fn summarize_interaction_input(input: &str) -> String {
    let mut single_line = input.replace('\r', "");
    single_line = single_line.replace('\n', "\\n");
    single_line = single_line.replace('\"', "'");
    let max_len = 80;
    if single_line.chars().count() <= max_len {
        return format!("\"{single_line}\"");
    }
    let mut out = String::new();
    for ch in single_line.chars().take(max_len.saturating_sub(3)) {
        out.push(ch);
    }
    out.push_str("...");
    format!("\"{out}\"")
}

fn exec_is_background(input: &serde_json::Value) -> bool {
    input
        .get("background")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::plan::StepStatus;
    use serde_json::json;

    #[cfg(unix)]
    fn hook_log_lines_eventually(path: &std::path::Path, expected: usize) -> Vec<String> {
        for _ in 0..100 {
            let lines = std::fs::read_to_string(path)
                .unwrap_or_default()
                .lines()
                .map(str::to_string)
                .collect::<Vec<_>>();
            if lines.len() >= expected {
                return lines;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        std::fs::read_to_string(path)
            .unwrap_or_default()
            .lines()
            .map(str::to_string)
            .collect()
    }

    /// A UI-ignored completion is still a completion. `tool_call_after` and
    /// `on_error` must fire for it — exactly once — or the documented "fires
    /// after each tool call" silently excludes repeated `wait` and background
    /// results, which is the class of call an observer most wants to record.
    #[cfg(unix)]
    #[test]
    fn ignored_tool_calls_still_fire_after_and_error_hooks_once() {
        use crate::hooks::{Hook, HookEvent, HookExecutor, HooksConfig};

        let dir = tempfile::tempdir().expect("tempdir");
        let after_log = dir.path().join("after.log");
        let error_log = dir.path().join("error.log");
        let script = |path: &std::path::Path| {
            format!(
                "printf '%s\\n' \"$DEEPSEEK_TOOL_CALL_ID\" >> {}",
                path.display()
            )
        };

        let mut app = crate::test_support::test_app_with_options(
            crate::test_support::test_tui_options(dir.path()),
        );
        app.workspace = dir.path().to_path_buf();
        app.hooks = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![
                    Hook::new(HookEvent::ToolCallAfter, &script(&after_log)).with_name("after"),
                    Hook::new(HookEvent::OnError, &script(&error_log)).with_name("error"),
                ],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let id = "call_ignored_1";
        app.ignored_tool_calls.insert(id.to_string());
        let failed: Result<ToolResult, ToolError> = Ok(ToolResult::error("boom"));

        handle_tool_call_complete(&mut app, id, "exec_shell", &failed);

        // The presentation state still consumed the id...
        assert!(!app.ignored_tool_calls.contains(id));
        // ...and both observers saw the call, once each.
        let after = hook_log_lines_eventually(&after_log, 1);
        let errors = hook_log_lines_eventually(&error_log, 1);
        assert_eq!(after, vec![id]);
        assert_eq!(errors, vec![id]);

        // A successful ignored completion fires `tool_call_after` only.
        let second = "call_ignored_2";
        app.ignored_tool_calls.insert(second.to_string());
        handle_tool_call_complete(
            &mut app,
            second,
            "exec_shell",
            &Ok(ToolResult::success("ok")),
        );
        let after = hook_log_lines_eventually(&after_log, 2);
        let errors = hook_log_lines_eventually(&error_log, 1);
        assert_eq!(after, vec![id, second]);
        assert_eq!(errors, vec![id]);
    }

    #[test]
    fn adaptive_evidence_late_foreign_and_duplicate_completions_are_ignored() {
        let result = Ok(ToolResult::success("bounded").with_metadata(json!({
            "artifact_session_id": "session-a",
            "artifact_id": "art_call-a"
        })));
        assert!(evidence_completion_identity_should_be_ignored(
            Some("session-b"),
            std::iter::empty(),
            "call-a",
            &result,
        ));
        assert!(evidence_completion_identity_should_be_ignored(
            Some("session-a"),
            [("art_call-a", "call-a")],
            "call-a",
            &result,
        ));
        assert!(!evidence_completion_identity_should_be_ignored(
            Some("session-a"),
            std::iter::empty(),
            "call-a",
            &result,
        ));
    }

    #[test]
    fn web_search_presentation_reads_source_degradation_and_citation_count() {
        let presentation = web_search_presentation(
            &json!({
                "source": "provider-native/xai/grok-4.5",
                "results": [
                    {"ref_id": "web_a", "url": "https://example.com/a"},
                    {"ref_id": "web_b", "url": "https://example.com/b"}
                ],
                "receipt": {
                    "degraded": [
                        {"kind": "backend_unavailable", "backend": "provider_native"},
                        {"kind": "backend_fallback", "from": "provider_native", "to": "tavily"}
                    ]
                }
            })
            .to_string(),
        );

        assert_eq!(
            presentation.source.as_deref(),
            Some("provider-native/xai/grok-4.5")
        );
        assert_eq!(
            presentation.degraded.as_deref(),
            Some("provider_native unavailable; provider_native -> tavily")
        );
        assert_eq!(presentation.ref_count, 2);
    }

    #[test]
    fn web_run_presentation_reads_nested_search_receipts() {
        let presentation = web_search_presentation(
            &json!({
                "search_query": [{
                    "source": "duckduckgo",
                    "results": [{"ref_id": "web_a"}],
                    "receipt": {
                        "degraded": [{"kind": "knob_ignored", "knob": "recency"}]
                    }
                }]
            })
            .to_string(),
        );

        assert_eq!(presentation.source.as_deref(), Some("duckduckgo"));
        assert_eq!(presentation.degraded.as_deref(), Some("recency ignored"));
        assert_eq!(presentation.ref_count, 1);
    }

    #[test]
    fn parse_plan_input_accepts_legacy_payload() {
        let snapshot = parse_plan_input(&json!({
            "explanation": "Legacy explanation",
            "plan": [
                { "step": "inspect", "status": "completed" },
                { "step": "patch", "status": "in_progress" }
            ]
        }));

        assert_eq!(snapshot.explanation.as_deref(), Some("Legacy explanation"));
        assert_eq!(snapshot.items.len(), 2);
        assert_eq!(snapshot.items[0].status, StepStatus::Completed);
        assert_eq!(snapshot.items[1].status, StepStatus::InProgress);
    }

    #[test]
    fn parse_plan_input_extracts_rich_artifact_fields() {
        let snapshot = parse_plan_input(&json!({
            "title": " PlanArtifact ",
            "objective": "Make Plan mode reviewable",
            "context_summary": "Grounded in issue #2691",
            "sources_used": [" gh issue view 2691 ", ""],
            "critical_files": ["crates/tui/src/tools/plan.rs"],
            "constraints": ["No secrets"],
            "recommended_approach": "Enrich update_plan",
            "verification_plan": "Run focused tests",
            "risks_and_unknowns": "Replay may drift",
            "handoff_packet": "Continue with session replay",
            "plan": [
                { "step": " ", "status": "completed" },
                { "step": "render all fields", "status": "weird" }
            ]
        }));

        assert_eq!(snapshot.title.as_deref(), Some("PlanArtifact"));
        assert_eq!(snapshot.sources_used, vec!["gh issue view 2691"]);
        assert_eq!(
            snapshot.critical_files,
            vec!["crates/tui/src/tools/plan.rs"]
        );
        assert_eq!(snapshot.constraints, vec!["No secrets"]);
        assert_eq!(
            snapshot.verification_plan.as_deref(),
            Some("Run focused tests")
        );
        assert_eq!(snapshot.items.len(), 1);
        assert_eq!(snapshot.items[0].step, "render all fields");
        assert_eq!(snapshot.items[0].status, StepStatus::Pending);
    }

    #[test]
    fn parse_patch_summary_treats_replace_and_legacy_changes_equally() {
        let replacements = json!([{
            "path": "src/lib.rs",
            "content": "fn replacement() {}\n"
        }]);

        let canonical =
            parse_file_mutation_summary("apply_patch", &json!({"replace": replacements.clone()}));
        let legacy = parse_file_mutation_summary("apply_patch", &json!({"changes": replacements}));

        assert_eq!(canonical, legacy);
    }

    // ── #3031: "(no output)" placeholder must not defeat compact rendering ─

    #[test]
    fn visible_tool_output_maps_no_output_placeholder_to_none() {
        assert_eq!(visible_tool_output("(no output)"), None);
        assert_eq!(visible_tool_output("  (no output)\n"), None);
    }

    #[test]
    fn visible_tool_output_preserves_real_content() {
        assert_eq!(
            visible_tool_output("compiled 3 crates").as_deref(),
            Some("compiled 3 crates")
        );
        // Output that merely CONTAINS the placeholder is real output.
        assert_eq!(
            visible_tool_output("step 1: (no output) — continuing").as_deref(),
            Some("step 1: (no output) — continuing")
        );
        assert_eq!(visible_tool_output("").as_deref(), Some(""));
    }

    #[test]
    fn exec_cell_without_output_suppresses_placeholder_in_live_mode() {
        use crate::tui::history::{ExecCell, ExecSource, ToolCell, ToolStatus};

        let cell = ToolCell::Exec(ExecCell {
            command: "true".to_string(),
            status: ToolStatus::Success,
            output: None,
            live_output: None,
            shell_task_id: None,
            owner_agent_id: None,
            owner_agent_name: None,
            started_at: None,
            duration_ms: Some(120),
            stale_elapsed_since_output_ms: None,
            source: ExecSource::Assistant,
            interaction: None,
            output_summary: None,
        });

        let live: String = cell
            .lines(80)
            .iter()
            .flat_map(|line| line.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(
            !live.contains("(no output)"),
            "Live mode must suppress the placeholder: {live:?}"
        );

        let transcript: String = cell
            .transcript_lines(80)
            .iter()
            .flat_map(|line| line.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(
            transcript.contains("(no output)"),
            "Transcript mode still records the placeholder: {transcript:?}"
        );
    }

    /// #455 — `exit_code` conditions must only ever see a real, reported exit
    /// code. `tool_call_after` used to hard-code `None`, which made every
    /// `{ type = "exit_code" }` condition permanently unmatchable.
    #[test]
    fn reported_tool_exit_code_reads_only_real_metadata_codes() {
        let with_code = Ok(ToolResult {
            content: "boom".to_string(),
            success: false,
            metadata: Some(serde_json::json!({ "exit_code": 127 })),
        });
        assert_eq!(super::reported_tool_exit_code(&with_code), Some(127));

        // Zero is a real code, not a missing one.
        let zero = Ok(ToolResult {
            content: "ok".to_string(),
            success: true,
            metadata: Some(serde_json::json!({ "exit_code": 0 })),
        });
        assert_eq!(super::reported_tool_exit_code(&zero), Some(0));

        // Tools that report no exit code stay `None` — never synthesized from
        // the success flag.
        let no_metadata = Ok(ToolResult::error("failed"));
        assert_eq!(super::reported_tool_exit_code(&no_metadata), None);

        let null_code = Ok(ToolResult {
            content: String::new(),
            success: true,
            metadata: Some(serde_json::json!({ "exit_code": serde_json::Value::Null })),
        });
        assert_eq!(super::reported_tool_exit_code(&null_code), None);

        let wrong_type = Ok(ToolResult {
            content: String::new(),
            success: false,
            metadata: Some(serde_json::json!({ "exit_code": "127" })),
        });
        assert_eq!(super::reported_tool_exit_code(&wrong_type), None);

        // A Windows crash code does not fit in an `i32`, but it is a real code
        // and a hook scoped to it must be able to see it.
        let windows_crash = Ok(ToolResult {
            content: String::new(),
            success: false,
            metadata: Some(serde_json::json!({ "exit_code": 3_221_225_477_i64 })),
        });
        assert_eq!(
            super::reported_tool_exit_code(&windows_crash),
            Some(3_221_225_477)
        );

        // A transport-level tool error has no metadata at all.
        let errored: Result<ToolResult, ToolError> =
            Err(ToolError::execution_failed("no such tool"));
        assert_eq!(super::reported_tool_exit_code(&errored), None);
    }
}