mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
//! Orchestrator tests — generation, the agentic loop, cancellation, readiness gates. Part of the [`super`]
//! module (fixtures in mod.rs). See docs/history/refactoring-god-objects.md, stage 3.

use super::*;

#[test]
fn effective_sampling_resolves_three_tiers() {
    let (_d, mut orch) = bare_orch();
    let mut profile = Profile::new("P", "sys");
    profile.default_sampling = Some(SamplingConfig {
        temperature: Some(0.5),
        ..Default::default()
    });
    let chat = Chat::from_profile(&profile, "c");
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);

    // override = None → the profile's default is used.
    assert_eq!(orch.effective_sampling(chat_id).temperature, Some(0.5));

    // override = Some → it's used (the chat takes priority).
    orch.chats[0].sampling_override = Some(SamplingConfig {
        temperature: Some(0.9),
        ..Default::default()
    });
    assert_eq!(orch.effective_sampling(chat_id).temperature, Some(0.9));

    // Neither an override nor a profile default → the global one.
    orch.chats[0].sampling_override = None;
    orch.profiles[0].default_sampling = None;
    assert_eq!(orch.effective_sampling(chat_id).temperature, Some(0.1));
}

#[tokio::test]
async fn send_streams_and_persists_assistant_message() {
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Thoughts("думаю".into()),
        ChatChunk::Text("Привет".into()),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();

    // Wait for activation and learn the active chat's id.
    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };

    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();

    // Finish and check that the chat was saved with two messages.
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened.json().load_chat(chat_id).unwrap().unwrap();
    assert_eq!(chat.messages.len(), 2);
    assert_eq!(chat.messages[0].role, MessageRole::User);
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].text, "Привет");
    assert_eq!(chat.messages[1].thoughts.as_deref(), Some("думаю"));
}

#[tokio::test]
async fn assistant_metadata_records_mode_model_and_filtered_sampling() {
    use crate::entities::sampling::SamplingConfig;
    use crate::shared::config::{CloudSettings, EngineSettings, ServerMode};

    // Cloud mode (OpenAI) + a model name; global sampling with top_k, which
    // the strict cloud dialect doesn't accept → it must not land in the metadata snapshot.
    let config = AppConfig {
        engine: EngineSettings {
            mode: ServerMode::OpenAi,
            openai: CloudSettings {
                model_name: Some("gpt-test".into()),
                ..Default::default()
            },
            ..Default::default()
        },
        default_sampling: SamplingConfig {
            temperature: Some(0.7),
            top_k: Some(40),
            max_tokens: Some(128),
            ..Default::default()
        },
        ..Default::default()
    };

    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("Привет".into()),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), config);
    let root = _d.path().to_path_buf();

    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };
    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened.json().load_chat(chat_id).unwrap().unwrap();
    let meta = chat.messages[1]
        .metadata
        .as_ref()
        .expect("expected a metadata snapshot");
    assert_eq!(meta.mode, ServerMode::OpenAi);
    assert_eq!(meta.model.as_deref(), Some("gpt-test"));
    // Fields available in the mode are kept; unavailable top_k and temperature (rejected
    // by GPT 5.5/5.6) are cleared.
    assert_eq!(meta.sampling.max_tokens, Some(128));
    assert_eq!(meta.sampling.top_k, None);
    assert_eq!(meta.sampling.temperature, None);
}

#[tokio::test]
async fn emits_token_counter_during_generation() {
    use crate::shared::api::contract::TokenUsage;
    // Two text deltas (the live count = 2), then exact usage from the server (= 5).
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("При".into()),
        ChatChunk::Text("вет".into()),
        ChatChunk::Usage(TokenUsage {
            prompt_tokens: 12,
            completion_tokens: 5,
            reasoning_tokens: 0,
            prefill: None,
        }),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));

    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();

    // Right after the start — an estimate of the conversation (prompt): context=Some, inexact,
    // no reply yet (completion=0).
    let est = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::TokenUsage { .. }))
        .await
        .unwrap();
    assert!(
        matches!(
            est,
            AppEvent::TokenUsage {
                completion: 0,
                context: Some(c),
                context_exact: false,
                ..
            } if c > 0
        ),
        "conversation estimate: {est:?}"
    );

    // Reply deltas → the reply counter grows, the conversation estimate is untouched (None).
    let first = wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::TokenUsage { context: None, .. })
    })
    .await
    .unwrap();
    assert!(
        matches!(
            first,
            AppEvent::TokenUsage {
                completion: 1,
                context: None,
                ..
            }
        ),
        "reply counter: {first:?}"
    );

    // The exact count from the server's usage arrives before completion: completion=5, context=12.
    let exact = wait_for(&mut evt_rx, |e| {
        matches!(
            e,
            AppEvent::TokenUsage {
                context_exact: true,
                ..
            }
        )
    })
    .await
    .unwrap();
    assert!(
        matches!(
            exact,
            AppEvent::TokenUsage {
                completion: 5,
                context: Some(12),
                context_exact: true,
                ..
            }
        ),
        "exact count from usage: {exact:?}"
    );

    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
}

#[tokio::test]
async fn regenerate_replaces_last_assistant_message() {
    // Two different replies in turn: the original turn gives the first, regeneration gives the second.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::Text("первый".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
        vec![
            ChatChunk::Text("второй".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();
    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };

    cmd_tx
        .send(AppCommand::SendMessage("вопрос".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    // ChatList after Finished — a sign that handle_done applied the reply (state Idle).
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatList(_)))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::RegenerateLast).unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatList(_)))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // The old reply is replaced by the new one; the user's message isn't duplicated.
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened.json().load_chat(chat_id).unwrap().unwrap();
    assert_eq!(chat.messages.len(), 2, "{:?}", chat.messages);
    assert_eq!(chat.messages[0].role, MessageRole::User);
    assert_eq!(chat.messages[0].text, "вопрос");
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].text, "второй");
}

#[tokio::test]
async fn delete_last_exchange_restores_user_text() {
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("ответ".into()),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();
    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };

    cmd_tx
        .send(AppCommand::SendMessage("забудь это".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatList(_)))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::DeleteLastExchange).unwrap();
    let restore = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::RestoreInput(_)))
        .await
        .unwrap();
    assert!(matches!(restore, AppEvent::RestoreInput(t) if t == "забудь это"));

    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // The exchange is deleted entirely (a default chat with no greeting → empty).
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened.json().load_chat(chat_id).unwrap().unwrap();
    assert!(chat.messages.is_empty(), "{:?}", chat.messages);
    // The deleted exchange is saved for manual recovery (the user's message +
    // the assistant's reply); the input draft was empty (spec §11.7).
    assert_eq!(chat.deleted.len(), 1);
    let removed = &chat.deleted[0];
    assert_eq!(removed.messages.len(), 2);
    assert_eq!(removed.messages[0].role, MessageRole::User);
    assert_eq!(removed.messages[0].text, "забудь это");
    assert_eq!(removed.messages[1].role, MessageRole::Assistant);
    assert_eq!(removed.draft, "");
}

#[tokio::test]
async fn regenerate_without_user_message_is_noop() {
    // A chat with an assistant greeting but no user message — there's nothing to
    // regenerate; the command must not start generation.
    let backend = Arc::new(MockBackend::scripted(vec![ChatChunk::Finished(
        FinishReason::Stop,
    )])) as Arc<dyn EngineBackend>;
    let (_d, mut orch) = bare_orch();
    orch.engines.backend = Some(backend);
    let mut profile = Profile::new("P", "sys");
    profile.greeting = Some("Привет!".into());
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::assistant("Привет!"));
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);

    orch.handle_regenerate();
    // State stayed Idle (generation wasn't started), history untouched.
    assert!(orch.gen_state.is_idle());
    assert_eq!(orch.chats[0].messages.len(), 1);
}

#[test]
fn regenerate_on_not_ready_server_keeps_reply() {
    // The server is still connecting (managed is loading the model) — regeneration must
    // neither wipe the previous reply nor go out as a request to a not-ready server (otherwise
    // a 503 "engine returned an error status" and the reply is lost). Regression test.
    let backend = Arc::new(MockBackend::scripted(vec![ChatChunk::Finished(
        FinishReason::Stop,
    )])) as Arc<dyn EngineBackend>;
    let (_d, mut orch) = bare_orch();
    orch.engines.backend = Some(backend);
    orch.engines.server_status = ServerStatus::Connecting; // not ready yet
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::user("вопрос"));
    chat.push_message(Message::assistant("старый ответ"));
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);

    orch.handle_regenerate();

    // The reply is preserved, generation didn't start (history wasn't truncated).
    assert!(orch.gen_state.is_idle());
    assert_eq!(
        orch.chats[0].messages.len(),
        2,
        "the previous reply must not be wiped on a not-ready server"
    );
    assert_eq!(orch.chats[0].messages[1].text, "старый ответ");
}

#[test]
fn send_on_not_ready_server_restores_input() {
    // The server is still connecting — the send is rejected, but the text is returned to the
    // input box (RestoreInput), and no message is added to the chat.
    let backend = Arc::new(MockBackend::scripted(vec![])) as Arc<dyn EngineBackend>;
    let (_d, mut orch, mut rx) = bare_orch_rx();
    orch.engines.backend = Some(backend);
    orch.engines.server_status = ServerStatus::Connecting;
    let profile = Profile::new("P", "sys");
    let chat = Chat::from_profile(&profile, "c");
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);

    orch.handle_send("привет".into());

    assert!(orch.gen_state.is_idle());
    assert!(
        orch.chats[0].messages.is_empty(),
        "no message should be added"
    );
    // Among the emitted events — an error and the text returning to the input box.
    let mut got_error = false;
    let mut restored = None;
    while let Ok(ev) = rx.try_recv() {
        match ev {
            AppEvent::Error(_) => got_error = true,
            AppEvent::RestoreInput(t) => restored = Some(t),
            _ => {}
        }
    }
    assert!(got_error, "an error about not-readiness should be emitted");
    assert_eq!(restored.as_deref(), Some("привет"));
}

#[test]
fn ready_backend_gates_by_status() {
    let (_d, mut orch) = bare_orch();
    orch.engines.backend = Some(Arc::new(MockBackend::scripted(vec![])) as Arc<dyn EngineBackend>);

    orch.engines.server_status = ServerStatus::Ready;
    assert!(orch.ready_backend().is_some());

    for status in [
        ServerStatus::Connecting,
        ServerStatus::NotConfigured,
        ServerStatus::Disconnected("боль".into()),
    ] {
        orch.engines.server_status = status;
        assert!(orch.ready_backend().is_none());
    }
}

#[tokio::test]
async fn cancel_stops_generation_and_saves_partial() {
    let backend = Arc::new(MockBackend::cancellable(vec![ChatChunk::Text(
        "часть".into(),
    )])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::SendMessage("hi".into())).unwrap();

    let mut sent_cancel = false;
    let mut cancelled = false;
    while let Some(ev) = evt_rx.recv().await {
        match ev {
            AppEvent::Chunk { .. } if !sent_cancel => {
                cmd_tx.send(AppCommand::Cancel).unwrap();
                sent_cancel = true;
            }
            AppEvent::Finished { reason, .. } => {
                assert_eq!(reason, FinishReason::Cancelled);
                cancelled = true;
                break;
            }
            _ => {}
        }
    }
    assert!(cancelled);

    drop(cmd_tx);
    handle.await.unwrap();
}

#[tokio::test]
async fn agentic_loop_executes_tool_then_finalizes() {
    use crate::shared::api::contract::ToolCallDelta;
    // Round 1: a call to note_save → round 2: the final text.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("note_save".into()),
                arguments: "{\"content\":\"любит чай\"}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ],
        vec![
            ChatChunk::Text("Запомнил.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;

    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();
    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };

    cmd_tx
        .send(AppCommand::SendMessage("запомни про чай".into()))
        .unwrap();

    // The tool-execution event reaches the UI.
    let tool_ev = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ToolCall { .. }))
        .await
        .unwrap();
    assert!(matches!(tool_ev, AppEvent::ToolCall { name, .. } if name == "note_save"));
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // History: user → assistant(tool_calls) → tool → assistant(final).
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened.json().load_chat(chat_id).unwrap().unwrap();
    assert_eq!(chat.messages.len(), 4, "{:?}", chat.messages);
    assert_eq!(chat.messages[0].role, MessageRole::User);
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].tool_calls.len(), 1);
    assert_eq!(chat.messages[1].tool_calls[0].name, "note_save");
    assert_eq!(chat.messages[2].role, MessageRole::Tool);
    assert_eq!(chat.messages[3].text, "Запомнил.");

    // The note is actually saved by the tool (isolation by profile).
    let notes = reopened
        .db()
        .note_list(chat.profile_id, None, &[], None)
        .unwrap();
    assert_eq!(notes.len(), 1);
    assert!(notes[0].content.contains("любит чай"));
}

#[tokio::test]
async fn disabled_tool_is_refused_by_loop() {
    use crate::shared::api::contract::ToolCallDelta;
    // python_exec is disabled globally (spawn_orch: python_enabled = false) —
    // even if the model calls it, the loop will refuse without executing it.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("python_exec".into()),
                arguments: "{\"code\":\"print(1)\"}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ],
        vec![
            ChatChunk::Text("ок".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;

    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("посчитай".into()))
        .unwrap();

    let tool_ev = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ToolCall { .. }))
        .await
        .unwrap();
    match tool_ev {
        AppEvent::ToolCall { name, result, .. } => {
            assert_eq!(name, "python_exec");
            assert!(result.contains("недоступен"), "got: {result}");
        }
        _ => unreachable!(),
    }
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    drop(cmd_tx);
    handle.await.unwrap();
}

#[tokio::test]
async fn tool_round_limit_is_respected() {
    use crate::shared::api::contract::ToolCallDelta;
    // The engine always requests a tool — the round limit should kick in.
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::ToolCall(ToolCallDelta {
            thought_signature: None,
            index: 0,
            id: Some("c1".into()),
            name: Some("get_sampling".into()),
            arguments: "{}".into(),
        }),
        ChatChunk::Finished(FinishReason::ToolCalls),
    ])) as Arc<dyn EngineBackend>;

    let config = AppConfig {
        max_tool_rounds: 2,
        ..Default::default()
    };
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), config);
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("зациклись".into()))
        .unwrap();

    // Reach Finished; the limit produces an error marker, but generation completes.
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    drop(cmd_tx);
    handle.await.unwrap();
}

#[tokio::test]
async fn round_limit_forces_final_synthesis_without_tools() {
    use crate::shared::api::contract::ToolCallDelta;
    // With the round limit, the model must not leave the user with no reply: after
    // exhausting the rounds a final round runs WITHOUT tools, where the model
    // sums up. Scripts: rounds 1 and 2 — tool calls, round 3 (forced synthesis) — text.
    let toolcall = || {
        vec![
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("get_sampling".into()),
                arguments: "{}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ]
    };
    let backend = Arc::new(MockBackend::sequence(vec![
        toolcall(),
        toolcall(),
        vec![
            ChatChunk::Text("Итог по собранному материалу.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;

    let config = AppConfig {
        max_tool_rounds: 1,
        ..Default::default()
    };
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), config);
    let root = _d.path().to_path_buf();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("собери и проанализируй".into()))
        .unwrap();

    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // The last message — the assistant's final summary text, not emptiness.
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened
        .json()
        .load_chats()
        .unwrap()
        .into_iter()
        .next()
        .unwrap();
    let last = chat.messages.last().unwrap();
    assert_eq!(last.role, MessageRole::Assistant);
    assert_eq!(last.text, "Итог по собранному материалу.");
}

#[tokio::test]
async fn followup_tool_makes_two_assistant_messages() {
    use crate::shared::api::contract::ToolCallDelta;
    // Round 1: text + a call to send_followup_message → round 2: the second message.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::Text("Первое сообщение.".into()),
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("send_followup_message".into()),
                arguments: "{}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ],
        vec![
            ChatChunk::Text("Второе сообщение.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;

    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();
    enable_all_tools(&cmd_tx, &mut evt_rx).await;
    cmd_tx
        .send(AppCommand::SendMessage("давай".into()))
        .unwrap();

    // The UI receives the signal to start a new bubble.
    wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::AssistantContinue { .. })
    })
    .await
    .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // History: user → assistant(followup tool_call) → tool → assistant(2nd, new_bubble).
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened
        .json()
        .load_chats()
        .unwrap()
        .into_iter()
        .next()
        .unwrap();
    assert_eq!(chat.messages.len(), 4, "{:?}", chat.messages);
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].text, "Первое сообщение.");
    assert_eq!(chat.messages[1].tool_calls[0].name, "send_followup_message");
    assert!(!chat.messages[1].new_bubble);
    assert_eq!(chat.messages[2].role, MessageRole::Tool);
    assert_eq!(chat.messages[3].text, "Второе сообщение.");
    assert!(
        chat.messages[3].new_bubble,
        "the second message should be a separate bubble"
    );
    // The control tool discards nothing.
    assert!(chat.deleted.is_empty());
}

#[tokio::test]
async fn rewrite_tool_discards_partial_and_saves_it() {
    use crate::shared::api::contract::ToolCallDelta;
    // Round 1: an incorrect text + a call to rewrite_current_message → round 2: the rewritten one.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::Text("Неправильный ответ".into()),
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("rewrite_current_message".into()),
                arguments: "{}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ],
        vec![
            ChatChunk::Text("Правильный ответ.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;

    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = _d.path().to_path_buf();
    enable_all_tools(&cmd_tx, &mut evt_rx).await;
    cmd_tx
        .send(AppCommand::SendMessage("вопрос".into()))
        .unwrap();

    // The UI receives the signal to discard the current bubble.
    wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::AssistantRewrite { .. })
    })
    .await
    .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // History: user → assistant(rewritten). The incorrect version is in the deleted archive.
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened
        .json()
        .load_chats()
        .unwrap()
        .into_iter()
        .next()
        .unwrap();
    assert_eq!(chat.messages.len(), 2, "{:?}", chat.messages);
    assert_eq!(chat.messages[0].role, MessageRole::User);
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].text, "Правильный ответ.");
    // The discarded (incorrect) reply + its tool message are saved for recovery.
    assert_eq!(chat.deleted.len(), 1);
    let discarded = &chat.deleted[0].messages;
    assert_eq!(discarded[0].role, MessageRole::Assistant);
    assert_eq!(discarded[0].text, "Неправильный ответ");
    assert_eq!(discarded[0].tool_calls[0].name, "rewrite_current_message");
}

/// A bounded [`wait_for`].
///
/// The shared helper blocks until the event channel *closes*, so a regression that
/// simply stops emitting an event makes a test hang rather than fail — and in CI a
/// hang reads as broken infrastructure instead of a broken promise. Measured while
/// mutation-testing the note below: with its `send` removed the test ran past ten
/// minutes; bounded, it fails in five seconds.
async fn wait_for_bounded<F: Fn(&AppEvent) -> bool>(
    rx: &mut UnboundedReceiver<AppEvent>,
    what: &str,
    pred: F,
) -> AppEvent {
    tokio::time::timeout(std::time::Duration::from_secs(5), wait_for(rx, pred))
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for {what}"))
        .unwrap_or_else(|| panic!("the event stream closed before {what}"))
}

/// The regression this whole change exists for: a provider that dies **after** the
/// stream opened used to end the turn silently — `Finished(Error)` pushes no note
/// (only `Cancelled` does), so a reply cut off mid-sentence was indistinguishable
/// from a finished one, and the only trace was a line in the file log.
#[tokio::test]
async fn a_mid_stream_error_reaches_the_feed_and_keeps_the_partial_reply() {
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("Половина отв".into()),
        ChatChunk::Error {
            message: "overloaded_error: Overloaded".into(),
            transient: true,
        },
        ChatChunk::Finished(FinishReason::Error),
    ])) as Arc<dyn EngineBackend>;
    let (dir, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    let root = dir.path().to_path_buf();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("вопрос".into()))
        .unwrap();

    // The note comes before Finished, and `wait_for` drains — so it must be
    // pulled first or the wait below eats it.
    let AppEvent::Error(note) = wait_for_bounded(&mut evt_rx, "the failure note", |e| {
        matches!(e, AppEvent::Error(_))
    })
    .await
    else {
        unreachable!("filtered on Error")
    };
    assert!(
        note.contains("overloaded_error"),
        "the note must carry what the provider said, got {note:?}"
    );
    wait_for_bounded(&mut evt_rx, "Finished", |e| {
        matches!(e, AppEvent::Finished { .. })
    })
    .await;
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    // What did arrive is still there — the note explains it, it does not replace it.
    let reopened = Storage::open(Paths::with_root(&root)).unwrap();
    let chat = reopened
        .json()
        .load_chats()
        .unwrap()
        .into_iter()
        .next()
        .unwrap();
    assert_eq!(chat.messages.len(), 2, "{:?}", chat.messages);
    assert_eq!(chat.messages[1].role, MessageRole::Assistant);
    assert_eq!(chat.messages[1].text, "Половина отв");
}

/// Which advice a failed turn gets. Asserted as the *decision* (the bundle key)
/// rather than the prose, so a translation edit cannot break it and a wrong branch
/// cannot pass.
#[test]
fn the_failure_note_is_chosen_by_condition() {
    use crate::app::orchestrator::generation::engine_error_key;

    let overflow =
        "engine returned status 400: {\"error\":{\"type\":\"exceed_context_size_error\"}}";
    let plain = "overloaded_error: Overloaded";

    // Overflow wins over everything: it is the one failure with a specific way
    // out, and which way out depends on whether compression is switched on.
    assert_eq!(
        engine_error_key(overflow, true, false, false),
        "ui.err.context_overflow"
    );
    assert_eq!(
        engine_error_key(overflow, false, false, false),
        "ui.err.context_overflow_off"
    );
    // ...including when text was already on screen — pointing at `/compact` beats
    // "press Ctrl+R", which would just overflow again — and regardless of
    // whether `/continue` could pick the fragment up: continuing would just
    // overflow again too, so `/compact` stays the named way out.
    assert_eq!(
        engine_error_key(overflow, true, true, true),
        "ui.err.context_overflow"
    );
    // Anything else: text already on screen means a fragment, so say so and name
    // the way to a whole reply — the resuming one when the mode can resume
    // (fork F9), the regenerating one when it cannot; nothing on screen is a
    // plain failure, whatever the mode.
    assert_eq!(
        engine_error_key(plain, true, true, true),
        "ui.err.generation_interrupted_continuable"
    );
    assert_eq!(
        engine_error_key(plain, true, true, false),
        "ui.err.generation_interrupted"
    );
    assert_eq!(
        engine_error_key(plain, true, false, true),
        "ui.err.generation_failed"
    );
    assert_eq!(
        engine_error_key(plain, true, false, false),
        "ui.err.generation_failed"
    );
}

#[tokio::test]
async fn send_without_backend_emits_error() {
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(None);
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::SendMessage("hi".into())).unwrap();

    let err = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Error(_)))
        .await
        .unwrap();
    assert!(matches!(err, AppEvent::Error(_)));

    drop(cmd_tx);
    handle.await.unwrap();
}

/// The code workspace is exempt from `max_tool_rounds` (spec §9.12), and the
/// exemption has to be **both** halves of a promise: a turn survives far past a
/// budget that would have cut it, and it still ends.
///
/// The engine here asks for `code_list` forever, with a budget of one round and
/// a project ceiling of three — without the exemption the turn would stop at the
/// first round, and without the ceiling it would never stop at all. The ceiling
/// is read from `workspace.max_rounds` rather than from a constant, which is
/// what the count below pins: three is a number only the setting can produce.
/// The wait is bounded, so a regression fails instead of hanging
/// (docs/lessons.md §2).
#[tokio::test]
async fn workspace_rounds_do_not_spend_the_budget_but_still_end() {
    use crate::shared::api::contract::ToolCallDelta;
    let backend = Arc::new(MockBackend::scripted(vec![
        ChatChunk::ToolCall(ToolCallDelta {
            thought_signature: None,
            index: 0,
            id: Some("c1".into()),
            name: Some(crate::features::tools::code::CODE_LIST_ID.into()),
            arguments: "{}".into(),
        }),
        ChatChunk::Finished(FinishReason::ToolCalls),
    ])) as Arc<dyn EngineBackend>;

    let project = tempfile::tempdir().unwrap();
    std::fs::write(project.path().join("a.rs"), "fn main() {}\n").unwrap();

    let config = AppConfig {
        // One round: enough that an unexempt tool would be cut off immediately.
        max_tool_rounds: 1,
        workspace: crate::shared::config::WorkspaceSettings {
            // Well below the default of 500, so the turn ends quickly *and* the
            // count proves the setting is what bounds it.
            max_rounds: 3,
            ..Default::default()
        },
        ..Default::default()
    };
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), config);
    let profile = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ProfileList(_)))
        .await
        .and_then(|e| match e {
            AppEvent::ProfileList(ps) => ps.first().map(|p| p.id),
            _ => None,
        })
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::UpdateProfile {
            id: profile,
            edit: Box::new(ProfileEdit {
                enabled_tools: Some(vec![crate::features::tools::code::CODE_LIST_ID.into()]),
                ..Default::default()
            }),
        })
        .unwrap();
    cmd_tx
        .send(AppCommand::ProjectAttach {
            path: project.path().to_string_lossy().into_owned(),
        })
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ProjectProgress(_)))
        .await
        .unwrap();

    cmd_tx
        .send(AppCommand::SendMessage("посмотри проект".into()))
        .unwrap();
    let mut calls = 0usize;
    let mut errors: Vec<String> = Vec::new();
    let finished = tokio::time::timeout(std::time::Duration::from_secs(60), async {
        while let Some(ev) = evt_rx.recv().await {
            match ev {
                AppEvent::ToolCall { .. } => calls += 1,
                AppEvent::Error(msg) => errors.push(msg),
                AppEvent::Finished { .. } => return true,
                _ => {}
            }
        }
        false
    })
    .await
    .expect("the turn must end rather than loop forever");
    assert!(finished, "the event stream closed before the turn finished");
    assert!(
        calls > 1,
        "a budget of one round must not stop an exempt tool: {calls} calls"
    );
    assert_eq!(
        calls, 3,
        "the ceiling must come from workspace.max_rounds: {calls} calls"
    );
    // And the note that ends such a turn must name the limit that fired. It
    // quoted `max_tool_rounds` for both until stage 3 — sending the user to
    // change a setting that was not the problem (docs/lessons.md §4).
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
    let expected = loc.tf("loop.workspace_round_limit_reached", &[("max_rounds", "3")]);
    assert!(
        errors.contains(&expected),
        "the project limit must name itself: {errors:?}"
    );
    drop(cmd_tx);
    handle.await.unwrap();
}

// ---------- /continue (spec §6.4, docs/research/continue-generation.md) ----------

/// The echo filter in isolation: an exact echo yields only the continuation, a
/// non-echoing stream loses nothing (including one that first coincides with
/// part of the seed), and a multi-byte character split across deltas keeps its
/// boundaries. Mutating the mismatch flush to drop the withheld bytes fails
/// the third case; mutating full-match detection fails the first.
#[test]
fn the_echo_filter_strips_an_echo_and_passes_real_content() {
    use super::super::generation::EchoFilter;

    let mut f = EchoFilter::new("Per the atlas".into());
    assert_eq!(f.push("Per the "), "");
    assert_eq!(f.push("atlas"), "");
    assert_eq!(f.push(" Paris."), " Paris.");

    let mut f = EchoFilter::new("Per the atlas".into());
    assert_eq!(f.push(" Paris."), " Paris.", "no echo: everything flows");

    let mut f = EchoFilter::new("Per the atlas".into());
    assert_eq!(f.push("Per"), "", "still ambiguous: withheld");
    assert_eq!(
        f.push(" it goes"),
        "Per it goes",
        "divergence flushes the withheld prefix"
    );

    let mut f = EchoFilter::new("По".into());
    assert_eq!(f.push("П"), "");
    assert_eq!(
        f.push("о!"),
        "!",
        "the split multi-byte echo is consumed whole"
    );
}

/// The in-place fold (fork F8) and the model-name rule (fork F7): the text
/// joins at the model's own seam, the id and timestamp stay the seed's, the
/// end state becomes the round's — and the model name stays the seed's unless
/// the continuation outgrew what it continued.
#[test]
fn merge_continuation_appends_in_place_and_keeps_the_model_name() {
    use super::super::generation::merge_continuation;
    use crate::entities::message::{Message, MessageFinish, MessageMetadata};

    let meta = |model: &str, finish: MessageFinish| MessageMetadata {
        sampling: Default::default(),
        mode: Default::default(),
        model: Some(model.into()),
        finish: Some(finish),
    };
    let mut seed = Message::assistant("Начало было длинным и обстоятельным");
    seed.metadata = Some(meta("gemma-4-31b", MessageFinish::Cancelled));
    let (id, stamp) = (seed.id, seed.timestamp);

    let mut round = Message::assistant(", конец.");
    round.metadata = Some(meta("qwen-3.6", MessageFinish::Stop));
    merge_continuation(&mut seed, round);

    assert_eq!(seed.text, "Начало было длинным и обстоятельным, конец.");
    assert_eq!(seed.id, id, "the same reply, finished later");
    assert_eq!(seed.timestamp, stamp);
    let md = seed.metadata.as_ref().unwrap();
    assert_eq!(
        md.finish,
        Some(MessageFinish::Stop),
        "the end state is the round's"
    );
    assert_eq!(
        md.model.as_deref(),
        Some("gemma-4-31b"),
        "a short continuation keeps the header on the model that wrote the bulk"
    );

    // The continuation outgrew the partial: the header follows the larger share.
    let mut seed = Message::assistant("Нач");
    seed.metadata = Some(meta("gemma-4-31b", MessageFinish::Error));
    let mut round = Message::assistant("ало, середина и весь длинный конец ответа.");
    round.metadata = Some(meta("qwen-3.6", MessageFinish::Stop));
    merge_continuation(&mut seed, round);
    assert_eq!(
        seed.metadata.unwrap().model.as_deref(),
        Some("qwen-3.6"),
        "an outgrown partial takes the continuing model's name"
    );
}

/// What [`interrupted_turn`] hands back: the harness, plus the first turn's
/// `Finished` event (some tests assert on what it announced).
type InterruptedOrch = (
    tempfile::TempDir,
    tokio::sync::mpsc::UnboundedSender<AppCommand>,
    tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
    AppEvent,
);

/// The shared road into a `/continue` scenario: one scripted turn that leaves
/// its interruption on disk, waited past the list re-emit — the proof the tail
/// has been applied before a test reads it (the result lands on its own
/// channel). Each test supplies only its script and its distinctive middle:
/// when the third test starts the same way as the first two, that opening is
/// a fixture (docs/lessons.md §2).
async fn interrupted_turn(script: Vec<Vec<ChatChunk>>) -> InterruptedOrch {
    let backend = Arc::new(MockBackend::sequence(script)) as Arc<dyn EngineBackend>;
    let (dir, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), no_auto_cfg());
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    cmd_tx
        .send(AppCommand::SendMessage("вопрос".into()))
        .unwrap();
    let finished = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatList(_)))
        .await
        .unwrap();
    (dir, cmd_tx, evt_rx, handle, finished)
}

/// The chat as the closed app left it on disk.
fn reload_chat(root: &std::path::Path) -> crate::entities::chat::Chat {
    Storage::open(Paths::with_root(root))
        .unwrap()
        .json()
        .load_chats()
        .unwrap()
        .into_iter()
        .next()
        .unwrap()
}

/// The whole route: a cancelled reply, then `/continue` — the turn announces
/// itself as a continuation (the feed re-opens the bubble on that flag), and
/// on disk there is still **one** assistant message, joined at the model's own
/// seam, with the end state re-recorded from `Cancelled` to `Stop`.
#[tokio::test]
async fn continue_appends_into_the_same_message() {
    use crate::entities::message::MessageFinish;

    let (dir, cmd_tx, mut evt_rx, handle, _) = interrupted_turn(vec![
        vec![
            ChatChunk::Text("Нача".into()),
            ChatChunk::Finished(FinishReason::Cancelled),
        ],
        vec![
            ChatChunk::Text("ло готово.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])
    .await;

    cmd_tx.send(AppCommand::ContinueLast).unwrap();
    let started = wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::GenerationStarted { .. })
    })
    .await
    .unwrap();
    assert!(
        matches!(
            started,
            AppEvent::GenerationStarted {
                continuation: true,
                ..
            }
        ),
        "the feed must be told to re-open the bubble instead of pushing one"
    );
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    let chat = reload_chat(dir.path());
    assert_eq!(chat.messages.len(), 2, "{:?}", chat.messages);
    assert_eq!(
        chat.messages[1].text, "Начало готово.",
        "joined at the seam, with no separator"
    );
    assert_eq!(
        chat.messages[1].metadata.as_ref().and_then(|m| m.finish),
        Some(MessageFinish::Stop),
        "the end state is the continuation's"
    );
}

/// llama.cpp returns prefill + continuation (research §7.1): the echoed prefix
/// must reach neither the screen nor the stored message. The second turn's
/// script echoes the partial verbatim; the feed sees only the new text, and
/// the disk holds it exactly once.
#[tokio::test]
async fn continue_strips_the_echoed_prefill() {
    let (dir, cmd_tx, mut evt_rx, handle, _) = interrupted_turn(vec![
        vec![
            ChatChunk::Text("Нача".into()),
            ChatChunk::Finished(FinishReason::Cancelled),
        ],
        vec![
            ChatChunk::Text("Нача".into()),
            ChatChunk::Text("ло готово.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])
    .await;

    cmd_tx.send(AppCommand::ContinueLast).unwrap();
    let mut chunks: Vec<String> = Vec::new();
    while let Some(ev) = evt_rx.recv().await {
        match ev {
            AppEvent::Chunk { text, .. } => chunks.push(text),
            AppEvent::Finished { .. } => break,
            _ => {}
        }
    }
    assert_eq!(
        chunks,
        vec!["ло готово.".to_string()],
        "the echoed prefix must not re-stream into the feed"
    );
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    assert_eq!(
        reload_chat(dir.path()).messages[1].text,
        "Начало готово.",
        "the echo must not double into the stored text"
    );
}

/// A length-cut reply records `Length` as its end state, and the turn's
/// `Finished` carries `continuable` so the feed's truncation note can name
/// `/continue` (fork F9). The mock supervisor runs as managed — the mode that
/// supports continuation.
#[tokio::test]
async fn a_length_cut_reply_is_recorded_and_announced_as_continuable() {
    use crate::entities::message::MessageFinish;

    let (dir, cmd_tx, _evt_rx, handle, finished) = interrupted_turn(vec![vec![
        ChatChunk::Text("Полов".into()),
        ChatChunk::Finished(FinishReason::Length),
    ]])
    .await;
    assert!(
        matches!(
            finished,
            AppEvent::Finished {
                reason: FinishReason::Length,
                continuable: true,
                ..
            }
        ),
        "a managed-mode length cut must announce the resume route: {finished:?}"
    );
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    assert_eq!(
        reload_chat(dir.path()).messages[1]
            .metadata
            .as_ref()
            .and_then(|m| m.finish),
        Some(MessageFinish::Length)
    );
}

/// A reply the provider's filter stopped keeps its fragment, is announced as
/// filtered and never as continuable — resuming meets the same filter — and is
/// stored as a stop, so `/continue` refuses it the way it refuses any finished
/// reply (docs/research/content-filter-finish.md, fork C2). The mock supervisor runs
/// as managed, where a length cut *would* be continuable.
#[tokio::test]
async fn a_filtered_reply_is_announced_and_stored_as_a_stop() {
    use crate::entities::message::MessageFinish;

    let (dir, cmd_tx, _evt_rx, handle, finished) = interrupted_turn(vec![vec![
        ChatChunk::Text("Half of it".into()),
        ChatChunk::Finished(FinishReason::Filtered),
    ]])
    .await;
    assert!(
        matches!(
            finished,
            AppEvent::Finished {
                reason: FinishReason::Filtered,
                continuable: false,
                ..
            }
        ),
        "a filtered reply must not offer /continue: {finished:?}"
    );
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    let chat = reload_chat(dir.path());
    assert_eq!(chat.messages[1].text, "Half of it");
    assert_eq!(
        chat.messages[1].metadata.as_ref().and_then(|m| m.finish),
        Some(MessageFinish::Stop)
    );
}

/// A turn interrupted between tool rounds leaves a tool-result tail;
/// `/continue` then resumes the agentic loop as an ordinary round — a **new**
/// assistant message, no prefill, no bubble re-opening.
#[tokio::test]
async fn continue_resumes_the_loop_on_a_tool_result_tail() {
    use crate::shared::api::contract::ToolCallDelta;

    let (dir, cmd_tx, mut evt_rx, handle, _) = interrupted_turn(vec![
        vec![
            ChatChunk::ToolCall(ToolCallDelta {
                thought_signature: None,
                index: 0,
                id: Some("c1".into()),
                name: Some("note_save".into()),
                arguments: "{\"content\":\"факт\"}".into(),
            }),
            ChatChunk::Finished(FinishReason::ToolCalls),
        ],
        // The round after the tool: nothing arrives — the turn ends as
        // cancelled, leaving the tool message as the chat's tail.
        vec![ChatChunk::Finished(FinishReason::Cancelled)],
        // The resumed round.
        vec![
            ChatChunk::Text("Записал.".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])
    .await;

    cmd_tx.send(AppCommand::ContinueLast).unwrap();
    let started = wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::GenerationStarted { .. })
    })
    .await
    .unwrap();
    assert!(
        matches!(
            started,
            AppEvent::GenerationStarted {
                continuation: false,
                ..
            }
        ),
        "a loop resume opens a bubble of its own: {started:?}"
    );
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();

    let chat = reload_chat(dir.path());
    let last = chat.messages.last().unwrap();
    assert_eq!(last.role, MessageRole::Assistant);
    assert_eq!(last.text, "Записал.", "{:?}", chat.messages);
}

/// Every refusal answers with the route that works (docs/lessons.md §4), and
/// each is chosen by the tail's actual state. Driven on a bare orchestrator:
/// the refusals need no turn, only the answer.
#[tokio::test]
async fn continue_refusals_answer_with_the_route_that_works() {
    use crate::entities::chat::Chat;
    use crate::entities::message::{Message, MessageFinish, MessageMetadata};
    use crate::entities::profile::Profile;
    use crate::shared::config::ServerMode;

    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    let (_d, mut orch, mut rx) = bare_orch_rx();
    orch.engines.backend = Some(Arc::new(MockBackend::scripted(vec![])) as Arc<dyn EngineBackend>);
    orch.engines.server_status = ServerStatus::Ready;
    let mut chat = Chat::from_profile(&Profile::new("P", "sys"), "Чат");
    let chat_id = chat.id;
    chat.push_message(Message::user("вопрос"));
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);

    let mut expect_note = |orch: &mut super::super::Orchestrator, key: &str| {
        orch.handle_continue();
        let mut note = None;
        while let Ok(ev) = rx.try_recv() {
            if let AppEvent::Error(text) = ev {
                note = Some(text);
            }
        }
        assert_eq!(note.as_deref(), Some(loc.t(key)), "expected {key}");
    };

    // A user tail: nothing to continue.
    expect_note(&mut orch, "ui.cmd.continue_nothing");

    // An assistant tail that finished on its own.
    let mut done = Message::assistant("Готовый ответ.");
    done.metadata = Some(MessageMetadata {
        sampling: Default::default(),
        mode: Default::default(),
        model: None,
        finish: Some(MessageFinish::Stop),
    });
    orch.chat_mut(chat_id).unwrap().push_message(done);
    expect_note(&mut orch, "ui.cmd.continue_complete");

    // Cut inside the reasoning, before any visible text (fork F4).
    {
        let chat = orch.chat_mut(chat_id).unwrap();
        let last = chat.messages.last_mut().unwrap();
        last.text = String::new();
        last.thoughts = Some("обрывок мысли".into());
    }
    expect_note(&mut orch, "ui.cmd.continue_thoughts");

    // A cloud mode: the capability gate answers before anything else.
    {
        let chat = orch.chat_mut(chat_id).unwrap();
        let last = chat.messages.last_mut().unwrap();
        last.text = "Оборванный отв".into();
        last.thoughts = None;
        if let Some(md) = last.metadata.as_mut() {
            md.finish = Some(MessageFinish::Cancelled);
        }
    }
    orch.config.engine.mode = ServerMode::OpenAi;
    expect_note(&mut orch, "ui.cmd.continue_unsupported");

    // Anthropic is per-model (stage 2): a 4.6+ id refuses — the wider matrix
    // is pinned in `shared::config`'s own capability test.
    orch.config.engine.mode = ServerMode::Claude;
    orch.config.engine.claude.model_name = Some("claude-opus-4-8".into());
    expect_note(&mut orch, "ui.cmd.continue_unsupported");

    // Back on a supporting mode with a continuable tail — and a message stored
    // before the bookkeeping existed (`finish: None`) is continuable too
    // (fork F1): the turn actually starts.
    orch.config.engine.mode = ServerMode::Managed;
    if let Some(md) = orch
        .chat_mut(chat_id)
        .unwrap()
        .messages
        .last_mut()
        .unwrap()
        .metadata
        .as_mut()
    {
        md.finish = None;
    }
    orch.handle_continue();
    let mut started = None;
    while let Ok(ev) = rx.try_recv() {
        if let AppEvent::GenerationStarted { continuation, .. } = ev {
            started = Some(continuation);
        }
    }
    assert_eq!(
        started,
        Some(true),
        "a legacy partial without the end-state field must still continue"
    );
}

/// Through a gateway `/continue` follows the route table measured in
/// docs/history/gateway-images-and-continue.md §1.3 (fork H2): a refusing slug answers with
/// the gateway's own note — not the generic one, which says external engines
/// continue — while the same slug on an endpoint that published no catalogue keeps
/// the behaviour that shipped, and a family the table allows starts the turn.
#[tokio::test]
async fn continue_through_a_gateway_follows_the_route_table() {
    use crate::app::orchestrator::compaction::EngineFacts;
    use crate::entities::chat::Chat;
    use crate::entities::message::{Message, MessageFinish, MessageMetadata};
    use crate::entities::profile::Profile;
    use crate::shared::api::contract::ModelCapabilities;
    use crate::shared::config::ServerMode;

    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    let (_d, mut orch, mut rx) = bare_orch_rx();
    orch.engines.backend = Some(Arc::new(MockBackend::scripted(vec![])) as Arc<dyn EngineBackend>);
    orch.engines.server_status = ServerStatus::Ready;
    orch.config.engine.mode = ServerMode::External;
    orch.config.engine.external.model_name = Some("google/gemma-4-31b-it".into());
    let mut chat = Chat::from_profile(&Profile::new("P", "sys"), "Чат");
    let chat_id = chat.id;
    chat.push_message(Message::user("вопрос"));
    let mut partial = Message::assistant("Оборванный отв");
    partial.metadata = Some(MessageMetadata {
        sampling: Default::default(),
        mode: Default::default(),
        model: None,
        finish: Some(MessageFinish::Cancelled),
    });
    chat.push_message(partial);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);
    let land_catalogue = |orch: &mut super::super::Orchestrator| {
        let epoch = orch.context.epoch();
        orch.handle_budget_result(
            epoch,
            EngineFacts {
                budget: None,
                caps: Some(ModelCapabilities {
                    context_length: Some(262_144),
                    sampling_fields: None,
                }),
            },
        );
    };
    let drain = |rx: &mut UnboundedReceiver<AppEvent>| {
        let (mut note, mut started) = (None, None);
        while let Ok(ev) = rx.try_recv() {
            match ev {
                AppEvent::Error(text) => note = Some(text),
                AppEvent::GenerationStarted { continuation, .. } => started = Some(continuation),
                _ => {}
            }
        }
        (note, started)
    };

    // A gateway (the catalogue answered) and a slug that restarts on every route.
    land_catalogue(&mut orch);
    orch.handle_continue();
    assert_eq!(
        drain(&mut rx),
        (
            Some(loc.t("ui.cmd.continue_unsupported_gateway").to_string()),
            None
        ),
        "a restarting family is refused through a gateway, with the gateway's note"
    );

    // The same slug on an endpoint that published nothing: silence is not a claim.
    orch.context.invalidate();
    assert!(
        orch.continuation_supported(),
        "without a catalogue external answers as it always did"
    );

    // A family the table allows continues through the same gateway.
    land_catalogue(&mut orch);
    orch.config.engine.external.model_name = Some("anthropic/claude-haiku-4.5".into());
    orch.handle_continue();
    assert_eq!(
        drain(&mut rx),
        (None, Some(true)),
        "Claude up to 4.5 continues through a gateway"
    );
}

/// A backend that publishes a catalogue entry for its model, the way a gateway does.
struct CataloguedBackend {
    inner: MockBackend,
}

#[async_trait::async_trait]
impl EngineBackend for CataloguedBackend {
    async fn chat_stream(
        &self,
        req: crate::shared::api::ChatRequest,
        cancel: tokio_util::sync::CancellationToken,
    ) -> anyhow::Result<crate::shared::api::contract::ChatStream> {
        self.inner.chat_stream(req, cancel).await
    }

    async fn model_capabilities(&self) -> Option<crate::shared::api::contract::ModelCapabilities> {
        Some(crate::shared::api::contract::ModelCapabilities {
            context_length: Some(262_144),
            sampling_fields: Some(vec!["temperature".to_string()].into()),
        })
    }
}

/// The whole route on a running orchestrator: the gateway's catalogue lands
/// **before any turn** — `/continue` as the first command after a restart is the
/// command's main case, and it must not meet an unanswered question — and then
/// it governs all three readers: a length-cut reply is announced as *not*
/// continuable, and the command refuses with the gateway's note
/// (docs/history/gateway-images-and-continue.md §4, H2).
#[tokio::test]
async fn a_gateways_catalogue_lands_before_the_first_turn_and_governs_continue() {
    use crate::shared::config::ServerMode;
    use std::time::Duration;

    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    let backend = Arc::new(CataloguedBackend {
        inner: MockBackend::sequence(vec![vec![
            ChatChunk::Text("Нача".into()),
            ChatChunk::Finished(FinishReason::Length),
        ]]),
    }) as Arc<dyn EngineBackend>;
    let mut cfg = no_auto_cfg();
    cfg.engine.mode = ServerMode::External;
    cfg.engine.external.model_name = Some("google/gemma-4-31b-it".into());
    let (_dir, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), cfg);

    let landed = tokio::time::timeout(
        Duration::from_secs(5),
        wait_for(&mut evt_rx, |e| {
            matches!(e, AppEvent::EngineSamplingFields(Some(_)))
        }),
    )
    .await;
    assert!(
        matches!(landed, Ok(Some(_))),
        "the catalogue must be asked when the engine is applied, not at the first turn"
    );

    cmd_tx
        .send(AppCommand::SendMessage("вопрос".into()))
        .unwrap();
    let finished = tokio::time::timeout(
        Duration::from_secs(5),
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. })),
    )
    .await
    .expect("the turn finishes")
    .unwrap();
    assert!(
        matches!(
            finished,
            AppEvent::Finished {
                reason: FinishReason::Length,
                continuable: false,
                ..
            }
        ),
        "a gateway's restarting family must not be announced as continuable: {finished:?}"
    );

    cmd_tx.send(AppCommand::ContinueLast).unwrap();
    let note = tokio::time::timeout(
        Duration::from_secs(5),
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Error(_))),
    )
    .await
    .expect("the command answers");
    assert!(
        matches!(&note, Some(AppEvent::Error(text)) if text == loc.t("ui.cmd.continue_unsupported_gateway")),
        "{note:?}"
    );
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
}

// ---------- the slow-prefill note (docs/research/slow-prefill-detection.md) ----------

mod slow_prefill {
    use super::*;
    use crate::shared::api::contract::{Prefill, TokenUsage};
    use crate::shared::config::ServerMode;
    use crate::shared::server::ServerStatus;

    /// The CPU build at the default batch: ~90 tok/s over a real prompt.
    const SLOW: Prefill = Prefill {
        tokens: 1800,
        ms: 20_000,
    };

    fn notices(rx: &mut UnboundedReceiver<AppEvent>) -> Vec<String> {
        let mut out = Vec::new();
        while let Ok(e) = rx.try_recv() {
            if let AppEvent::Notice(text) = e {
                out.push(text);
            }
        }
        out
    }

    /// A managed server at the default batch: one note per server session,
    /// naming the field, the hold and the batch; the next turn says nothing;
    /// a server that reaches `Ready` again — a relaunch — may be told once
    /// more (§3.3).
    #[test]
    fn a_managed_server_is_told_once_per_session() {
        let (_d, mut orch, mut rx) = bare_orch_rx();
        orch.config.engine.mode = ServerMode::Managed;
        orch.config.engine.managed.gpu_layers = 99;
        orch.config.engine.managed.batch_size = None;

        orch.note_slow_prefill(Some(SLOW));
        let notes = notices(&mut rx);
        assert_eq!(notes.len(), 1, "{notes:?}");
        assert!(
            notes[0].contains("Batch (-b)") && notes[0].contains("23") && notes[0].contains("2048"),
            "{}",
            notes[0]
        );

        orch.note_slow_prefill(Some(SLOW));
        assert!(notices(&mut rx).is_empty(), "once per session");

        orch.engines.set_chat_status(ServerStatus::Ready);
        orch.note_slow_prefill(Some(SLOW));
        assert_eq!(notices(&mut rx).len(), 1, "a new session, told again");
    }

    /// Nothing to say: the batch already at the knee (typed, or the CPU auto),
    /// a fast prefill, a cloud, no sample.
    #[test]
    fn nothing_is_said_where_the_rule_does_not_hold() {
        let (_d, mut orch, mut rx) = bare_orch_rx();
        orch.config.engine.mode = ServerMode::Managed;
        orch.config.engine.managed.gpu_layers = 99;
        orch.config.engine.managed.batch_size = Some(256);
        orch.note_slow_prefill(Some(SLOW));
        assert!(notices(&mut rx).is_empty(), "typed 256: the change is made");

        orch.config.engine.managed.batch_size = None;
        orch.config.engine.managed.gpu_layers = 0;
        orch.note_slow_prefill(Some(SLOW));
        assert!(notices(&mut rx).is_empty(), "the CPU auto: 256 already");

        orch.config.engine.managed.gpu_layers = 99;
        orch.note_slow_prefill(Some(Prefill {
            tokens: 1800,
            ms: 900,
        }));
        assert!(notices(&mut rx).is_empty(), "a GPU's second");

        orch.config.engine.mode = ServerMode::OpenAi;
        orch.note_slow_prefill(Some(SLOW));
        assert!(notices(&mut rx).is_empty(), "a cloud has no batch");

        orch.config.engine.mode = ServerMode::Managed;
        orch.note_slow_prefill(None);
        assert!(notices(&mut rx).is_empty(), "no sample");
    }

    /// An external server: the launch line's wording, at the default batch the
    /// app assumes (fork F3).
    #[test]
    fn an_external_server_is_told_the_launch_line() {
        let (_d, mut orch, mut rx) = bare_orch_rx();
        orch.config.engine.mode = ServerMode::External;
        orch.note_slow_prefill(Some(SLOW));
        let notes = notices(&mut rx);
        assert_eq!(notes.len(), 1, "{notes:?}");
        assert!(
            notes[0].contains("-b 256 -ub 256") && notes[0].contains("2048"),
            "{}",
            notes[0]
        );
    }

    /// A tool's own request is a stream of the turn (spec §9.3.1): the
    /// timing it reports on its outcome folds into the turn's largest sample
    /// and reaches the note like a round's — the page summary's path without
    /// the page (docs/research/page-summary-usage.md §3.2). The engine's own
    /// rounds carry a warm sample under the floor; the tool's is the cold one.
    #[tokio::test]
    async fn a_tools_own_request_is_the_turns_sample_too() {
        use crate::app::orchestrator::tests::subagent::{Script, ScriptRecorder};
        let warm = ChatChunk::Usage(TokenUsage {
            prompt_tokens: 40,
            completion_tokens: 1,
            reasoning_tokens: 0,
            prefill: Some(Prefill { tokens: 40, ms: 20 }),
        });
        let call = Script {
            chunks: vec![
                ChatChunk::ToolCall(crate::shared::api::contract::ToolCallDelta {
                    thought_signature: None,
                    index: 0,
                    id: Some("s1".into()),
                    name: Some("sampled".into()),
                    arguments: "{}".into(),
                }),
                warm.clone(),
                ChatChunk::Finished(FinishReason::ToolCalls),
            ],
            hang: false,
        };
        let reply = Script {
            chunks: vec![
                ChatChunk::Text("done".into()),
                warm,
                ChatChunk::Finished(FinishReason::Stop),
            ],
            hang: false,
        };
        let backend = ScriptRecorder::new(vec![call, reply]);
        let mut config = no_auto_cfg();
        config.engine.mode = ServerMode::External;
        let tool = Arc::new(crate::app::orchestrator::tests::SampledTool {
            id: "sampled",
            sample: Some(SLOW),
        });
        let (_d, cmd_tx, mut evt_rx, handle) =
            spawn_orch_tools(Some(backend as Arc<dyn EngineBackend>), config, vec![tool]);
        // The startup emits the profile list and the active chat in whichever
        // order; both are needed before the tool can be enabled and the
        // message sent.
        let (mut pid, mut chat) = (None, None);
        while pid.is_none() || chat.is_none() {
            match tokio::time::timeout(std::time::Duration::from_secs(5), evt_rx.recv())
                .await
                .expect("startup events")
            {
                Some(AppEvent::ProfileList(v)) if !v.is_empty() => pid = Some(v[0].id),
                Some(AppEvent::ChatActivated { id, .. }) => chat = Some(id),
                Some(_) => {}
                None => panic!("the orchestrator went away during startup"),
            }
        }
        cmd_tx
            .send(AppCommand::UpdateProfile {
                id: pid.unwrap(),
                edit: Box::new(ProfileEdit {
                    enabled_tools: Some(vec!["sampled".into()]),
                    ..Default::default()
                }),
            })
            .unwrap();
        cmd_tx.send(AppCommand::SendMessage("go".into())).unwrap();
        let note = wait_for(
            &mut evt_rx,
            |e| matches!(e, AppEvent::Notice(t) if t.contains("-b 256 -ub 256")),
        )
        .await;
        assert!(note.is_some(), "the tool's cold sample reached the note");
        cmd_tx.send(AppCommand::Quit).unwrap();
        handle.await.unwrap();
    }

    /// The whole path: the engine's `timings` on the stream's usage chunk
    /// travel through the round, the turn and the landing to the note
    /// (§3.1) — and the second turn on the same server says nothing.
    #[tokio::test]
    async fn a_turn_carries_the_engines_figure_to_the_note() {
        let backend = Arc::new(MockBackend::scripted(vec![
            ChatChunk::Text("hi".into()),
            ChatChunk::Usage(TokenUsage {
                prompt_tokens: 1850,
                completion_tokens: 1,
                reasoning_tokens: 0,
                prefill: Some(SLOW),
            }),
            ChatChunk::Finished(FinishReason::Stop),
        ])) as Arc<dyn EngineBackend>;
        let mut config = AppConfig::default();
        config.engine.mode = ServerMode::External;
        let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), config);
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
            .await
            .unwrap();

        cmd_tx.send(AppCommand::SendMessage("one".into())).unwrap();
        let note = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Notice(_)))
            .await
            .unwrap();
        let AppEvent::Notice(text) = note else {
            unreachable!()
        };
        assert!(text.contains("-b 256 -ub 256"), "{text}");

        cmd_tx.send(AppCommand::SendMessage("two".into())).unwrap();
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
            .await
            .unwrap();
        // The landing's note, had there been one, follows `Finished` at once;
        // a quit flushes the channel in order.
        cmd_tx.send(AppCommand::Quit).unwrap();
        handle.await.unwrap();
        let mut second = Vec::new();
        while let Ok(e) = evt_rx.try_recv() {
            if let AppEvent::Notice(t) = e {
                second.push(t);
            }
        }
        assert!(second.is_empty(), "the same server, told once: {second:?}");
    }
}

/// The estimate counts the tool schemas as the wire sends them
/// (docs/research/roll-usage-calibration.md §3.1): one part at the text's
/// bytes-per-token, plus the per-message overhead once for the block; a
/// request without tools estimates as before.
#[test]
fn the_estimate_counts_the_tool_schemas() {
    use crate::shared::api::contract::ToolSchema;
    let bare = crate::shared::api::ChatRequest {
        continue_final: false,
        system: Some("sys".into()),
        messages: vec![crate::shared::api::ApiMessage::user("hi")],
        sampling: Default::default(),
        tools: Vec::new(),
    };
    let schema = ToolSchema {
        name: "note_save".into(),
        description: "Saves a note.".into(),
        parameters: serde_json::json!({
            "type": "object",
            "properties": { "text": { "type": "string" } }
        }),
    };
    let with = crate::shared::api::ChatRequest {
        tools: vec![schema],
        ..bare.clone()
    };
    let json = crate::shared::api::openai::tools_json(&with.tools);
    assert!(
        json.starts_with(r#"[{"type":"function","function":{"name":"note_save""#),
        "the wire's own wrapper: {json}"
    );
    let bare_estimate = super::super::generation::estimate_prompt_tokens(&bare);
    let with_estimate = super::super::generation::estimate_prompt_tokens(&with);
    assert_eq!(
        with_estimate - bare_estimate,
        (json.len() as u64).div_ceil(4) + 4,
        "the block's bytes over four, plus one message overhead"
    );
}