aidaemon-channels 0.29.0

Chat channel contract and the runner that connects channels to aidaemon agents
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
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
//! A session's turns, the same on every chat platform.
//!
//! A platform hands the runner an authorized [`Turn`] and a [`TurnSurface`]
//! (where the turn's output goes). The runner owns everything that follows:
//! session registration, cancel words, queueing and deduplication, task
//! tracking, the inactivity watchdog and wall-clock limit, the working
//! indicator and status updates, reply delivery and its receipts, and
//! draining the session's queue in order. Platforms differ only in how the
//! surface shows things.

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};

use aidaemon_core::ChannelVisibility;
use aidaemon_events::ResponseDeliveryState;
use aidaemon_events::conversation::MessageAttachment;
use aidaemon_tools::semantics::UserRole;
use aidaemon_tools::status::StatusUpdate;

use crate::context::ChannelContext;
use crate::hub::{SessionChannelStore, SessionMap};
use crate::owner_wait::OwnerWaitClock;
use crate::ports::{
    AgentResponseEnvelope, ChannelAgentRuntime, InboundMessageRequest, InboundMessageTiming,
    MidRunIntent, MidRunReading, RunningWork,
};
use crate::stop::StopRequest;
use crate::tasks::{QueueOutcome, QueuedMessage, TaskRegistry};

/// Least time between two ordinary status messages.
const STATUS_INTERVAL: Duration = Duration::from_secs(3);
/// Most time a finished turn waits for its status display to catch up
/// before the reply is sent.
const STATUS_DRAIN: Duration = Duration::from_secs(3);
const CANCELLED: &str = "Task cancelled";

/// How a turn that produced no reply ended, as the runner itself observed
/// it: never read back from an error's text.
enum TurnStop {
    /// The owner (or a new message) cancelled the turn.
    Cancelled,
    /// The stale watchdog stopped a turn that made no progress.
    Inactive { minutes: u64 },
    /// The agent returned an error.
    Agent(anyhow::Error),
}

impl std::fmt::Display for TurnStop {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cancelled => f.write_str(CANCELLED),
            Self::Inactive { minutes } => write!(
                f,
                "Task auto-cancelled due to inactivity ({minutes} minute{} without progress).",
                if *minutes == 1 { "" } else { "s" }
            ),
            Self::Agent(error) => write!(f, "{error}"),
        }
    }
}

/// One authorized message, ready to run.
pub struct Turn {
    pub session_id: String,
    pub text: String,
    pub attachments: Vec<MessageAttachment>,
    pub user_role: UserRole,
    pub channel_ctx: ChannelContext,
    /// The platform's message id. A redelivery of the same message is
    /// dropped; the same text typed again is not.
    pub dedup_key: Option<String>,
    pub ingress_timing: Option<InboundMessageTiming>,
}

/// Where the owner put a message sent while its session works.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MidRunPlacement {
    /// Into the running work.
    Steer,
    /// After it, as a turn of its own.
    Queue,
}

/// What delivering a reply achieved.
pub struct Delivered {
    pub state: ResponseDeliveryState,
    pub message_ids: Vec<String>,
    pub error: Option<String>,
}

impl Delivered {
    fn from_send(result: anyhow::Result<Vec<String>>, platform: &str) -> Self {
        match result {
            Ok(message_ids) => Self {
                state: ResponseDeliveryState::PlatformAcknowledged,
                message_ids,
                error: None,
            },
            Err(error) => {
                warn!(platform, %error, "Failed to send a reply");
                Self {
                    state: ResponseDeliveryState::Failed,
                    message_ids: Vec::new(),
                    error: Some(format!("{platform}_send_failed")),
                }
            }
        }
    }
}

/// How a turn ended, for [`TurnSurface::turn_ended`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnEnd {
    Delivered,
    /// The agent had nothing to say.
    Empty,
    Failed,
    Cancelled,
}

/// Where one conversation's turns are shown.
#[async_trait]
pub trait TurnSurface: Send + Sync + 'static {
    /// The platform recorded on delivery receipts (`telegram`, `slack`...).
    fn platform(&self) -> &'static str;

    /// Send Markdown `text`, split to fit. Returns the ids of the messages
    /// sent, or an error if any part failed.
    async fn say(&self, text: &str) -> anyhow::Result<Vec<String>>;

    /// Replace the text of message `message_id` that [`Self::say`] sent.
    /// `Ok(false)` when the platform cannot edit it; the default suits
    /// surfaces that never can.
    async fn edit(&self, _message_id: &str, _text: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Show that work is in progress until `stop` is cancelled. When the
    /// heartbeat has been quiet for `stale_secs` (0 = never), stop showing it.
    fn show_working(&self, stop: CancellationToken, heartbeat: Arc<AtomicU64>, stale_secs: u64);

    /// Where this surface keeps a turn's one status card, when it keeps
    /// one (a message it can create, edit and delete). The runner then owns
    /// the card: what it shows and how it ends with the turn, by the one
    /// rule ([`aidaemon_core::card::CardEnd`]). `None` (the default): the
    /// turn's status goes to [`Self::show_status`].
    fn card_sink(&self) -> Option<Arc<dyn crate::live_status::SurfaceSink>> {
        None
    }

    /// The turn kept its card: message `message_id` stays as the record of
    /// the work, for what outlives the turn (a helper ending) to settle.
    async fn card_kept(&self, _message_id: &str) {}

    /// Show one turn's status updates. Handing them back (the default)
    /// uses throttled status messages, sent only in private conversations.
    /// Not called for a surface with a [`Self::card_sink`].
    fn show_status(
        &self,
        updates: mpsc::Receiver<StatusUpdate>,
        _private: bool,
    ) -> Result<JoinHandle<()>, mpsc::Receiver<StatusUpdate>> {
        Err(updates)
    }

    /// Whether this surface's status is one card that the reply settles
    /// (its closing state decides whether the card stays). Such a surface
    /// gets a finished turn's last updates before the reply; plain status
    /// messages do not, since a late one would only repeat the reply.
    fn status_settles_before_reply(&self) -> bool {
        false
    }

    /// Deliver the agent's reply (already prepared for chat).
    async fn deliver(&self, _envelope: &AgentResponseEnvelope, reply: &str) -> Delivered {
        Delivered::from_send(self.say(reply).await, self.platform())
    }

    /// A turn is over: its reply was delivered, or it had none, or it
    /// failed or was cancelled (after any error message was shown).
    async fn turn_ended(&self, _ended: TurnEnd) {}

    /// Re-check a queued message just before it runs; its authority may
    /// have narrowed while it waited.
    async fn before_queued(&self, queued: QueuedMessage) -> QueuedMessage {
        queued
    }
}

tokio::task_local! {
    static TURN_OVER: TurnOver;
}

/// Marks the end of the turn running this task: everything it shows is out
/// (its reply and the card it kept). Work the turn started that outlives it
/// (a background helper) waits on this before it touches the chat, so the
/// turn's reply always comes before the work's own end.
#[derive(Clone)]
pub struct TurnOver {
    over: CancellationToken,
    /// When the owner's request reached the runner: what a time "since your
    /// request" is measured from.
    requested_at: chrono::DateTime<chrono::Utc>,
}

impl Default for TurnOver {
    fn default() -> Self {
        Self {
            over: CancellationToken::new(),
            requested_at: chrono::Utc::now(),
        }
    }
}

impl TurnOver {
    /// When the owner's request that started this turn reached the runner.
    pub fn requested_at(&self) -> chrono::DateTime<chrono::Utc> {
        self.requested_at
    }

    /// The turn is over: everything it shows is out.
    pub fn end(&self) {
        self.over.cancel();
    }

    /// The turn running this task, if any (scheduled work has none).
    pub fn current() -> Option<Self> {
        TURN_OVER.try_with(Clone::clone).ok()
    }

    /// Wait until that turn is over.
    pub async fn wait(&self) {
        self.over.cancelled().await;
    }

    /// Whether that turn is over.
    pub fn is_over(&self) -> bool {
        self.over.is_cancelled()
    }

    /// Run `future` as part of the turn this marks.
    pub async fn within<F: std::future::Future>(&self, future: F) -> F::Output {
        TURN_OVER.scope(self.clone(), future).await
    }
}

/// A turn's card on a surface that keeps one: its state and where it is
/// drawn. The runner owns it for the turn.
#[derive(Clone)]
struct TurnCard {
    live: Arc<tokio::sync::Mutex<crate::live_status::LiveStatus>>,
    sink: Arc<dyn crate::live_status::SurfaceSink>,
}

impl TurnCard {
    fn new(sink: Arc<dyn crate::live_status::SurfaceSink>) -> Self {
        Self {
            live: Arc::default(),
            sink,
        }
    }

    /// Deliver the reply, always on its own: the card is the state, and it
    /// ends after the reply ([`Self::close`]).
    async fn deliver(
        &self,
        surface: &dyn TurnSurface,
        envelope: &AgentResponseEnvelope,
        reply: &str,
    ) -> Delivered {
        surface.deliver(envelope, reply).await
    }

    /// End the card with the turn, once, by the one rule: kept and
    /// settled (handed to the surface for what outlives the turn), or
    /// removed.
    async fn close(&self, surface: &dyn TurnSurface) {
        let mut live = self.live.lock().await;
        live.close(self.sink.as_ref()).await;
        if let Some(id) = live.kept_card_message_id() {
            surface.card_kept(&id).await;
        }
    }
}

/// A turn as it starts, for a [`TurnObserver`].
pub struct TurnStart<'a> {
    pub session_id: &'a str,
    /// The task registry's id for the turn.
    pub turn: u64,
    /// The surface's platform (`telegram`, `app`...).
    pub platform: &'static str,
    /// What the sender said.
    pub text: &'a str,
    pub attachments: &'a [MessageAttachment],
    pub user_role: UserRole,
    /// How the running-work list names it.
    pub description: &'a str,
    /// The conversation as its channel saw it on this turn (visibility,
    /// sender, workspace grant): what a later turn into the same
    /// conversation from another surface must run under.
    pub channel_ctx: &'a crate::context::ChannelContext,
}

/// A turn as it ends, for a [`TurnObserver`].
pub struct TurnFinish<'a> {
    pub session_id: &'a str,
    pub turn: u64,
    pub platform: &'static str,
    pub end: TurnEnd,
    /// The reply as delivered (Markdown); empty when there was none.
    pub reply: &'a str,
    /// The work goes on in the background; its report comes later.
    pub handed_off: bool,
    /// Why it failed or was cancelled.
    pub error: Option<&'a str>,
    /// The model that wrote the reply, when the runtime recorded one.
    pub model: Option<&'a str>,
}

/// Sees every turn a runner runs, whatever its platform, so one place can
/// show all the work (the Client Gateway). Called inline: return quickly.
pub trait TurnObserver: Send + Sync {
    fn turn_started(&self, turn: &TurnStart<'_>);
    /// A turn the daemon starts on its own in a conversation (the
    /// follow-up to background work it handed off): nobody sent anything,
    /// so there is no message to show, only the work. Its updates and end
    /// come as any turn's.
    fn followup_started(&self, _session_id: &str, _turn: u64, _description: &str) {}
    /// One of the turn's status updates, as the surface gets it.
    fn turn_status(&self, session_id: &str, turn: u64, update: &StatusUpdate);
    fn turn_finished(&self, turn: &TurnFinish<'_>);
    /// A helper run (sub-agent, launched coding agent, background command)
    /// started, took a step or ended, from the runtime's record of it. Its
    /// updates go on after the turn that started it is over.
    fn run_changed(&self, _change: &RunChange) {}
    /// A team of coding agents (a lead and the peers it delegated to)
    /// changed: a member joined, started, ended or was stopped. The whole
    /// roster as it stands.
    fn team_changed(&self, _team: &TeamChange) {}
    /// A post reached a team's board.
    fn board_posted(&self, _post: &BoardPostChange) {}
    /// The daemon kept a message in a conversation's history outside a
    /// turn's reply: another conversation's message, or a change of lead.
    fn history_marked(&self, _mark: &HistoryMark) {}
    /// Conversation `session_id` was erased (`/wipe`, or deleted from a
    /// client): whoever keeps a copy of what it said drops it.
    fn session_erased(&self, _session_id: &str) {}
}

/// A message kept in a conversation's history outside a turn's reply
/// ([`TurnObserver::history_marked`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryMark {
    pub session_id: String,
    pub id: String,
    /// What a client shows: the other conversation's words, or the change
    /// of lead in words.
    pub text: String,
    pub at_ms: u64,
    pub kind: HistoryMarkKind,
}

/// What a [`HistoryMark`] is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HistoryMarkKind {
    /// Another conversation's lead sent it.
    FromConversation {
        conversation: String,
        label: String,
        message: String,
        in_reply_to: Option<String>,
    },
    /// This conversation's lead sent it to another conversation.
    ToConversation {
        conversation: String,
        label: String,
        message: String,
        in_reply_to: Option<String>,
    },
    /// The owner made `to` the lead in place of `from` (names).
    LeadChange { from: String, to: String },
}

/// A helper run as its record stands after a change, for a
/// [`TurnObserver`].
#[derive(Debug, Clone)]
pub struct RunChange {
    /// The conversation it reports to.
    pub session_id: String,
    /// The run's id: the key every surface finds it by.
    pub id: String,
    pub view: aidaemon_core::card::HelperView,
    /// What a coding agent it launched last said it was doing, in plain
    /// words ("Editing state.rs"); `None` for any other run.
    pub activity: Option<String>,
    /// What kind of step [`Self::activity`] is (a wait while it waits):
    /// what a client draws the run's mark by.
    pub activity_kind: Option<aidaemon_core::card::AgentStepKind>,
    /// The coding agent it is ("Claude Code"), when it launched one.
    pub agent: Option<String>,
    /// That agent's mark (its maker's provider id, or its own), when it
    /// has one: what a client draws its logo by.
    pub agent_mark: Option<String>,
    /// The chat turn (its task id) that started it: runs one request
    /// started share it.
    pub group: Option<String>,
    /// The files the coding agent it launched changed.
    pub edited: Vec<String>,
    /// The earlier run it continues: the same coding agent's session,
    /// resumed with the owner's follow-up.
    pub continues: Option<String>,
    /// The first run of its thread: the agent session it is part of (one
    /// participant of the conversation). `None`: it starts its own.
    pub thread: Option<String>,
    /// Its coding agent keeps its session where a follow-up can continue it.
    pub keeps_session: bool,
    /// While running, its live host accepts mid-run notes directly.
    pub accepts_mid_run: bool,
    /// Running but not started yet: it waits its turn behind another run,
    /// for its folder or for a free slot.
    pub queued: bool,
    /// What its coding agent ended with, once it ended ([`crate::turns::RunResult`]).
    pub result: Option<crate::turns::RunResult>,
    /// What it was asked, and by whom.
    pub asked: Option<crate::turns::RunAsk>,
    pub started_at: chrono::DateTime<chrono::Utc>,
    pub ended_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Only its current step changed: it started or ended earlier.
    pub step_only: bool,
    /// The team of coding agents it is a member of: its tree and its id
    /// there.
    pub team: Option<RunTeam>,
    /// The builds and tests it ran, as seen.
    pub seen_checks: Vec<SeenCheck>,
    /// Tokens its coding agent used so far, as the agent counted them.
    pub tokens: Option<u64>,
    /// The files it wrote: its own edits, and the changed files its
    /// repository tracks.
    pub wrote: Vec<String>,
    /// How its coding agent's work stands beyond its latest step.
    pub pulse: RunPulse,
}

/// How a running coding agent's work stands beyond its latest step, from
/// its typed events and its output, the same for every agent: whether
/// that step is still open and since when, what the agent last told the
/// owner, the work it left running, and when it last printed anything.
/// What an agent cannot report stays empty; a client still tells a quiet
/// agent apart by [`Self::output_at`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunPulse {
    /// When its latest step began.
    pub step_since: Option<chrono::DateTime<chrono::Utc>>,
    /// Its latest step is still running (no end seen yet).
    pub step_open: bool,
    /// What it last told the owner as it works (its progress line), as it
    /// wrote it.
    pub said: Option<String>,
    /// When it said [`Self::said`].
    pub said_at: Option<chrono::DateTime<chrono::Utc>>,
    /// The work it left running while it waits for it, as it last listed
    /// it.
    pub background: Vec<RunBackground>,
    /// When it last printed anything (any output line, typed or not).
    pub output_at: Option<chrono::DateTime<chrono::Utc>>,
    /// When it last took a message written to its input (its task, the
    /// owner's note), for an agent that says so; `None`: it never said.
    pub input_taken_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl RunPulse {
    /// What it said in answer to a message written to its input at
    /// `delivered`: words said after it took that message, for an agent
    /// that says when it takes one ([`Self::input_taken_at`]), else after
    /// the message reached it. `None` until it said something then.
    pub fn answer_after(&self, delivered: chrono::DateTime<chrono::Utc>) -> Option<&str> {
        let from = match self.input_taken_at {
            Some(taken) if taken > delivered => taken,
            // It says when it takes a message, and has not taken this one.
            Some(_) => return None,
            None => delivered,
        };
        self.said
            .as_deref()
            .filter(|_| self.said_at.is_some_and(|at| at >= from))
    }

    /// It waits for the work it left running: its latest step ended and
    /// some of that work is open.
    pub fn waiting_on_background(&self) -> bool {
        !self.step_open && !self.background.is_empty()
    }

    /// Since when the run's shown step (of kind `kind`) holds: its oldest
    /// open background work's start while it waits for that work, else its
    /// latest step's start; `None` for any other wait (the daemon's own,
    /// which keeps its own clock).
    pub fn shown_since(
        &self,
        kind: Option<aidaemon_core::card::AgentStepKind>,
    ) -> Option<chrono::DateTime<chrono::Utc>> {
        if self.waiting_on_background() {
            return self.background.iter().filter_map(|work| work.since).min();
        }
        match kind {
            None | Some(aidaemon_core::card::AgentStepKind::Wait) => None,
            Some(_) => self.step_since,
        }
    }

    /// Its latest step (of kind `kind`) ended and nothing else is open: it
    /// is thinking, or quiet.
    pub fn between_steps(&self, kind: Option<aidaemon_core::card::AgentStepKind>) -> bool {
        !self.step_open
            && self.background.is_empty()
            && !matches!(kind, None | Some(aidaemon_core::card::AgentStepKind::Wait))
    }
}

/// One piece of work a coding agent left running while it waits for it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunBackground {
    /// What it is, as the agent described it.
    pub what: Option<String>,
    /// When it started, when the agent says.
    pub since: Option<chrono::DateTime<chrono::Utc>>,
}

impl RunBackground {
    pub fn new(what: Option<String>, since: Option<chrono::DateTime<chrono::Utc>>) -> Self {
        Self { what, since }
    }
}

/// A build or test a run ran (a command that runs the project's own code),
/// as the daemon saw it: its latest outcome and how often it failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeenCheck {
    /// The program it ran ("cargo", "pytest", "python3").
    pub program: String,
    /// Its subcommand or module ("test" for `cargo test`, "pytest" for
    /// `python3 -m pytest`), when it named one.
    pub subcommand: Option<String>,
    /// Its latest run passed; `None` while that run goes on.
    pub passed: Option<bool>,
    /// How many of its runs failed.
    pub failures: u32,
}

/// A run's place in a team of coding agents ([`TeamChange`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunTeam {
    pub tree: String,
    pub peer: String,
    /// The lead's run when this run joined: the exchange it belongs to
    /// (for the lead, itself).
    pub lead_run: Option<String>,
}

/// A team of coding agents as it stands after a change, for a
/// [`TurnObserver`]: the lead run of a conversation and every peer it (or
/// one of its peers) delegated to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamChange {
    pub session_id: String,
    /// The team's coordination tree: stable across the conversation's
    /// exchanges with the same lead.
    pub tree: String,
    /// The lead's coding agent (its tool name).
    pub lead_agent: String,
    /// The lead first, then each peer in the order it joined.
    pub members: Vec<TeamMember>,
    /// How many posts its board holds.
    pub posts: u64,
    /// Members writing the same files, as the daemon saw it.
    pub overlaps: Vec<TeamOverlap>,
    /// Questions members asked the owner.
    pub questions: Vec<TeamQuestion>,
}

/// A question a member asked the owner ([`TeamChange`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamQuestion {
    /// Its post on the board.
    pub seq: u64,
    /// The member that asked, by id.
    pub from: String,
    pub question: String,
    /// The answers it offered.
    pub options: Vec<String>,
    /// The lead's run it was asked during.
    pub lead_run: Option<String>,
    /// The owner wrote to the team since.
    pub answered: bool,
}

/// Members of one exchange writing the same files ([`TeamChange`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamOverlap {
    /// The files, each relative to its writer's folder.
    pub files: Vec<String>,
    /// The members that wrote them, by id.
    pub peers: Vec<String>,
    /// The lead's run of the exchange.
    pub lead_run: Option<String>,
}

/// What a [`TeamMember`] waits on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TeamWait {
    /// Another member, by id.
    Member(String),
    /// New posts on the board.
    Board,
    /// Another conversation's lead to answer, by its name.
    Conversation(String),
}

/// How a [`TeamMember`] works on the files.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TeamWorkspace {
    ReadOnly,
    /// A copy of its own.
    Isolated,
    /// Only the paths it was given.
    Scoped,
}

/// One member of a [`TeamChange`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamMember {
    /// Its id in the team (`peer-root` for the lead).
    pub peer: String,
    /// The member that delegated to it; `None` for the lead.
    pub parent: Option<String>,
    /// Its coding agent (tool name).
    pub agent: String,
    /// What it was given to do, in its delegator's words.
    pub title: String,
    pub state: TeamMemberState,
    /// Its current run, once one began.
    pub run: Option<String>,
    pub workspace: TeamWorkspace,
    pub branch: Option<String>,
    pub started_at_ms: Option<u64>,
    pub ended_at_ms: Option<u64>,
    /// What it is blocked waiting on.
    pub waiting_on: Option<TeamWait>,
}

/// Where a [`TeamMember`] stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TeamMemberState {
    Queued,
    Running,
    Completed,
    Failed,
    Cancelled,
}

/// One post on a team's board, for a [`TurnObserver`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoardPostChange {
    pub session_id: String,
    pub tree: String,
    /// Its place on the board, from 1.
    pub seq: u64,
    /// The member that posted it, or `owner`.
    pub from: String,
    /// The member it was addressed to; `None`: to everyone.
    pub to: Option<String>,
    pub topic: String,
    pub body: String,
    /// Written by an agent whose words are untrusted (any but the lead).
    pub untrusted: bool,
    pub at_ms: Option<u64>,
    /// The lead's run it was posted during: which exchange it belongs to.
    pub lead_run: Option<String>,
}

/// What a run was asked: the task as given (without the daemon's rules),
/// and whether the owner sent it to the agent directly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunAsk {
    pub text: String,
    pub by_owner: bool,
}

/// What a run's coding agent ended with: its reply, its typed claims, and
/// where those claims disagree with what it was seen doing.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunResult {
    /// Its final message, whole (bounded only against a runaway agent); its
    /// report's summary when it reported in fields.
    pub text: String,
    /// Its report, when its protocol held it to the report schema.
    pub claims: Option<RunClaims>,
    /// Where its claims disagree with its recorded actions.
    pub mismatches: Vec<RunMismatch>,
}

/// A coding agent's typed report: its claims.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunClaims {
    pub summary: String,
    pub changed_files: Vec<String>,
    /// Each check it says it ran, and whether it says it passed.
    pub checks: Vec<(String, bool)>,
    pub open_questions: Vec<String>,
    pub needs_owner: bool,
}

/// A claim its recorded actions don't bear out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunMismatch {
    /// It says it changed the file; no change to it was recorded.
    ChangeNotSeen { path: String },
    /// A change to the file was recorded; it doesn't say so.
    ChangeNotClaimed { path: String },
    /// It says it ran the check; no run of that program was recorded.
    CheckNotRun { command: String },
    /// It says the check passed; the recorded run failed.
    CheckFailed { command: String },
}

/// Where a runner reports its turns: empty until an observer is set, which
/// may happen after the runners are built. Clones share the slot.
#[derive(Clone, Default)]
pub struct TurnWatch(Arc<std::sync::RwLock<Option<Arc<dyn TurnObserver>>>>);

impl TurnWatch {
    /// Report turns to `observer` from now on.
    pub fn set(&self, observer: Arc<dyn TurnObserver>) {
        *self.0.write().unwrap_or_else(|p| p.into_inner()) = Some(observer);
    }

    /// The observer, if one is set.
    pub fn observer(&self) -> Option<Arc<dyn TurnObserver>> {
        self.0.read().unwrap_or_else(|p| p.into_inner()).clone()
    }
}

/// What a [`TurnRunner`] runs turns with.
#[derive(Clone)]
pub struct TurnDeps {
    pub agent: Arc<dyn ChannelAgentRuntime>,
    /// Which bot each session belongs to, for outbound routing.
    pub session_map: SessionMap,
    /// Where that mapping is persisted.
    pub sessions: Arc<dyn SessionChannelStore>,
    pub task_registry: Arc<TaskRegistry>,
    /// Heartbeat silence (seconds) after which a turn is cancelled as hung;
    /// 0 never cancels. The engine stamps the heartbeat on a timer while the
    /// turn loop runs, so silence means the loop is wedged, not slow work.
    pub watchdog_stale_threshold_secs: u64,
    /// Who sees every turn (empty by default).
    pub watch: TurnWatch,
}

/// Per session: each queued message's text and its notice's message id.
type QueuedNotices = std::collections::HashMap<String, Vec<(String, String)>>;

/// Runs turns for one channel (bot).
#[derive(Clone)]
pub struct TurnRunner {
    pub(crate) deps: TurnDeps,
    /// Per session, the "got it" notice sent for each queued message (its
    /// text and the notice's message id), so the notice can be edited when
    /// that message's turn starts instead of a second bubble being sent.
    queued_notices: Arc<std::sync::Mutex<QueuedNotices>>,
    /// Each session's running work as its status updates show it, for
    /// answering a question about it mid-run.
    live: crate::mid_run::LiveWork,
}

/// Longest the owner waits for a mid-run message to be read before it
/// joins the running work unread, as before.
const MID_RUN_READ_LIMIT: Duration = Duration::from_secs(15);

impl TurnRunner {
    pub fn new(deps: TurnDeps) -> Self {
        Self {
            deps,
            queued_notices: Arc::default(),
            live: crate::mid_run::LiveWork::default(),
        }
    }

    fn remember_queued_notice(&self, session_id: &str, text: &str, message_id: String) {
        if let Ok(mut notices) = self.queued_notices.lock() {
            notices
                .entry(session_id.to_string())
                .or_default()
                .push((text.to_string(), message_id));
        }
    }

    /// The notice sent for the queued `text`, taken out of the map.
    fn take_queued_notice(&self, session_id: &str, text: &str) -> Option<String> {
        let mut notices = self.queued_notices.lock().ok()?;
        let session = notices.get_mut(session_id)?;
        let at = session.iter().position(|(queued, _)| queued == text)?;
        let (_, message_id) = session.remove(at);
        if session.is_empty() {
            notices.remove(session_id);
        }
        Some(message_id)
    }

    fn forget_queued_notices(&self, session_id: &str) {
        if let Ok(mut notices) = self.queued_notices.lock() {
            notices.remove(session_id);
        }
    }

    /// Remember that `session_id` belongs to `channel_name`, so outbound
    /// messages (approvals, media, notifications) route back to it.
    /// [`Self::register_session`] for a message that arrived in a chat:
    /// also records whether other people are in it, which places a
    /// direct-message chat in its bot's project the first time.
    pub async fn register_chat(
        &self,
        session_id: &str,
        channel_name: &str,
        context: &crate::context::ChannelContext,
    ) {
        self.register_session(session_id, channel_name).await;
        let shared = !matches!(
            context.visibility,
            aidaemon_core::ChannelVisibility::Private | aidaemon_core::ChannelVisibility::Internal
        );
        let _ = self
            .deps
            .sessions
            .chat_seen(session_id, channel_name, shared)
            .await;
    }

    pub async fn register_session(&self, session_id: &str, channel_name: &str) {
        self.deps
            .session_map
            .write()
            .await
            .insert(session_id.to_string(), channel_name.to_string());
        let _ = self
            .deps
            .sessions
            .save_session_channel(session_id, channel_name)
            .await;
    }

    /// Handle an authorized message: a cancel word, a message queued behind
    /// a running turn, or a new turn (and then every turn queued behind it).
    pub async fn submit(&self, surface: Arc<dyn TurnSurface>, turn: Turn) {
        self.submit_placed(surface, turn, None).await;
    }

    /// [`Self::submit`], with the owner's own choice of where a message
    /// sent while the session works goes. With a choice the agent does not
    /// read the message first: it joins the running work (`Steer`) or waits
    /// for its own turn (`Queue`).
    pub async fn submit_placed(
        &self,
        surface: Arc<dyn TurnSurface>,
        turn: Turn,
        placement: Option<MidRunPlacement>,
    ) {
        if is_cancel_word(&turn.text) {
            let reply = self
                .cancel(&turn.session_id, turn.user_role, StopRequest::Bare)
                .await;
            let _ = surface.say(&reply).await;
            self.record_exchange(&turn, &reply).await;
            return;
        }

        let registry = &self.deps.task_registry;
        let session_id = turn.session_id.clone();
        let dedup_key = turn.dedup_key.as_deref();
        // No model connected and the conversation needs one: one fixed line,
        // no turn and no model call.
        if self.deps.agent.needs_missing_model(&session_id).await {
            if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
                let _ = surface.say(crate::ports::NO_MODEL_LINE).await;
                self.record_exchange(&turn, crate::ports::NO_MODEL_LINE)
                    .await;
            }
            return;
        }
        if !registry.has_running_task(&session_id).await
            && turn.channel_ctx.in_run.is_none()
            && !turn.channel_ctx.fresh_agent_session
        {
            match self.read_between_runs(&turn).await {
                Some(BetweenRuns::Stop { request, also_asks }) => {
                    if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
                        return;
                    }
                    let reply = self.cancel(&session_id, turn.user_role, request).await;
                    if !also_asks {
                        let _ = surface.say(&reply).await;
                        self.record_exchange(&turn, &reply).await;
                        return;
                    }
                    // The turn below answers the whole message, the stop
                    // included: a stop line said now would land above the
                    // owner's message, which the turn shows (live
                    // 2026-11-21), and be gone after a reload.
                    // "Stop it and delete it": the work is stopped, and the
                    // rest of the message runs as a turn of its own (which
                    // records it), never dropped with the stop.
                    registry
                        .unmark_seen(&session_id, &turn.text, dedup_key)
                        .await;
                }
                // A question about the helpers and commands running for
                // the chat: answered from their typed state, the same reply
                // as mid-run, never a turn of its own that would time
                // itself (live 2026-11-13: "Still working on \"how's it
                // going?\" (1s so far)").
                Some(BetweenRuns::Status) => {
                    if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
                        let answer = crate::mid_run::running_work_reply(
                            &self.running_work(&session_id).await,
                        );
                        let reply = crate::presentation::prepare_chat_message(&answer);
                        let _ = surface.say(&reply).await;
                        self.record_exchange(&turn, &reply).await;
                    }
                    return;
                }
                None => {}
            }
        }
        if registry.has_running_task(&session_id).await {
            // A message explicitly addressed to a coding-agent session or
            // starting a fresh agent session must never be steered into
            // AIDaemon's own running turn: queue it for its own turn instead.
            let directed_to_agent =
                turn.channel_ctx.in_run.is_some() || turn.channel_ctx.fresh_agent_session;
            let mut steerable = !directed_to_agent;
            // The agent was asked to read it but gave no reading (its model
            // call failed): the owner still sees where the work stands.
            let mut unread = false;
            let reading = if directed_to_agent {
                None
            } else {
                match placement {
                    Some(MidRunPlacement::Steer) => None,
                    Some(MidRunPlacement::Queue) => {
                        steerable = false;
                        None
                    }
                    None => {
                        let reading = self.read_mid_run(&turn).await;
                        if reading.is_none() {
                            unread = Self::mid_run_readable(&turn);
                        }
                        reading
                    }
                }
            };
            match reading {
                Some(
                    reading @ MidRunReading {
                        intent: MidRunIntent::StopsWork,
                        ..
                    },
                ) => {
                    if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
                        return;
                    }
                    let reply = self
                        .cancel(&session_id, turn.user_role, stop_request(&reading))
                        .await;
                    if !reading.also_asks {
                        let _ = surface.say(&reply).await;
                        self.record_exchange(&turn, &reply).await;
                        return;
                    }
                    registry
                        .unmark_seen(&session_id, &turn.text, dedup_key)
                        .await;
                    // The rest of the message waits for the stopped run to
                    // end, then runs as its own turn.
                    steerable = false;
                }
                Some(MidRunReading {
                    intent: MidRunIntent::AboutRunningWork,
                    ..
                }) => {
                    // Answered now from the typed state, read afresh with
                    // the clock `/tasks` uses; the run goes on undisturbed.
                    if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
                        let answer = crate::mid_run::running_work_reply(
                            &self.running_work(&session_id).await,
                        );
                        let reply = crate::presentation::prepare_chat_message(&answer);
                        let _ = surface.say(&reply).await;
                        self.record_exchange(&turn, &reply).await;
                    }
                    return;
                }
                Some(MidRunReading {
                    intent: MidRunIntent::Unrelated,
                    ..
                }) => steerable = false,
                Some(MidRunReading {
                    intent: MidRunIntent::ChangesWork,
                    ..
                })
                | None => {}
            }
            let mut queued = QueuedMessage::new(
                &turn.text,
                turn.user_role,
                turn.channel_ctx.clone(),
                turn.attachments.clone(),
            );
            if matches!(placement, Some(MidRunPlacement::Queue)) {
                queued = queued.placed_for_later();
            } else if !steerable {
                queued = queued.not_steerable();
            }
            if placement.is_some() {
                queued = queued.listed_by_client();
            }
            if let Some(timing) = turn.ingress_timing.clone() {
                queued = queued.with_ingress_timing(timing);
            }
            // Atomic check-and-queue: if the running turn finished since the
            // check above, run this one directly instead of stranding it.
            match registry
                .queue_message_if_running(&session_id, queued, dedup_key)
                .await
            {
                QueueOutcome::Queued(position) => {
                    // Notify for the first few only: a long message pasted
                    // in parts can arrive as many.
                    if position <= 3 {
                        let notice = if steerable && crate::owner_wait::approval_open(&session_id) {
                            Some(crate::presentation::after_approval_notice())
                        } else if unread {
                            Some(crate::mid_run::unread_message_notice(
                                &self.running_work(&session_id).await,
                            ))
                        } else if placement.is_some() {
                            // The owner placed it themselves (an app's Now or
                            // After), and the app lists it under "Waiting to
                            // send": a "Got it" line would only sit in the
                            // chat above the message it answers (live
                            // 2026-11-21).
                            None
                        } else {
                            Some(crate::presentation::queued_message_notice(
                                !turn.attachments.is_empty() || !steerable,
                            ))
                        };
                        if let Some(notice) = notice
                            && let Ok(ids) = surface.say(&notice).await
                            && let [message_id] = ids.as_slice()
                        {
                            self.remember_queued_notice(
                                &session_id,
                                &turn.text,
                                message_id.clone(),
                            );
                        }
                    }
                    return;
                }
                QueueOutcome::Duplicate => {
                    debug!(session_id, "Dropped duplicate queued message");
                    return;
                }
                QueueOutcome::NoRunningTask => {
                    info!(
                        session_id,
                        "Task finished during queue attempt — processing message directly"
                    );
                }
            }
        }

        // Mark the message seen so concurrent deliveries of it don't all run.
        if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
            debug!(
                session_id,
                "Dropped duplicate message (direct processing race)"
            );
            return;
        }

        let runner = self.clone();
        tokio::spawn(async move { runner.run(surface, turn).await });
    }

    /// The session's running work as its typed state shows it: the running
    /// list `/tasks` reads and the turn's live progress, timed at one
    /// instant.
    async fn running_work(&self, session_id: &str) -> RunningWork {
        let listed = crate::stop::running_work(
            &self.deps.task_registry,
            self.deps.agent.as_ref(),
            session_id,
        )
        .await;
        let now = chrono::Utc::now();
        let mut work = self.running_turn(session_id, now).await;
        work.running = listed.items(now);
        work
    }

    /// The session's running turn as its live state shows it at `now`.
    async fn running_turn(
        &self,
        session_id: &str,
        now: chrono::DateTime<chrono::Utc>,
    ) -> RunningWork {
        let running = self
            .deps
            .task_registry
            .list_for_session(session_id)
            .await
            .into_iter()
            .find(|entry| matches!(entry.status, crate::tasks::TaskStatus::Running));
        let (request, elapsed) = running.map_or_else(
            || (String::new(), Duration::ZERO),
            |entry| {
                let elapsed = (now - entry.started_at).to_std().unwrap_or_default();
                (entry.description, elapsed)
            },
        );
        let runs = self.deps.agent.chat_runs(session_id).await;
        self.live.snapshot(session_id, &request, elapsed, runs)
    }

    /// Whether the agent reads `turn` sent mid-run: the owner's own text,
    /// without files.
    fn mid_run_readable(turn: &Turn) -> bool {
        turn.user_role == UserRole::Owner
            && turn.attachments.is_empty()
            && !turn.text.trim().is_empty()
    }

    /// Have the agent read a message the owner sent while a turn runs:
    /// only the owner's own text is read (another sender's message or one
    /// with files joins the queue as before), within a time limit.
    async fn read_mid_run(&self, turn: &Turn) -> Option<MidRunReading> {
        if !Self::mid_run_readable(turn) {
            return None;
        }
        let work = self.running_work(&turn.session_id).await;
        let reading = tokio::time::timeout(
            MID_RUN_READ_LIMIT,
            self.deps
                .agent
                .read_mid_run_message(&turn.session_id, &turn.text, &work),
        )
        .await
        .ok()
        .flatten();
        info!(
            session_id = %turn.session_id,
            intent = ?reading.as_ref().map(|r| r.intent),
            "Read a message sent mid-run"
        );
        reading
    }

    /// The reply to a cancel word, or to a message read as a stop request:
    /// the same stop as `/cancel`, read back before it is reported.
    async fn cancel(&self, session_id: &str, role: UserRole, request: StopRequest) -> String {
        if role != UserRole::Owner {
            return "Only the owner can cancel running work in this session.".to_string();
        }
        crate::stop::stop(
            &self.deps.task_registry,
            self.deps.agent.as_ref(),
            session_id,
            request,
        )
        .await
    }

    /// Keep a message the channel answered itself, and its reply, in the
    /// conversation.
    async fn record_exchange(&self, turn: &Turn, reply: &str) {
        self.deps
            .agent
            .record_control_exchange(
                &turn.session_id,
                &turn.text,
                turn.user_role,
                &turn.channel_ctx,
                reply,
            )
            .await;
    }

    /// Read a message sent while the chat has sub-agents or background
    /// commands running but no turn: a stop request stops them (the same
    /// stop as `/cancel`), a question about them is answered from their
    /// typed state; anything else runs as a turn. `None` when it is neither
    /// or nothing runs.
    async fn read_between_runs(&self, turn: &Turn) -> Option<BetweenRuns> {
        if turn.user_role != UserRole::Owner
            || !turn.attachments.is_empty()
            || turn.text.trim().is_empty()
        {
            return None;
        }
        let list = crate::stop::running_work(
            &self.deps.task_registry,
            self.deps.agent.as_ref(),
            &turn.session_id,
        )
        .await;
        if list.entries.is_empty() {
            return None;
        }
        let work = RunningWork {
            running: list.items(chrono::Utc::now()),
            ..RunningWork::default()
        };
        let reading = tokio::time::timeout(
            MID_RUN_READ_LIMIT,
            self.deps
                .agent
                .read_mid_run_message(&turn.session_id, &turn.text, &work),
        )
        .await
        .ok()
        .flatten()?;
        info!(
            session_id = %turn.session_id,
            intent = ?reading.intent,
            "Read a message sent while background work runs"
        );
        match reading.intent {
            MidRunIntent::StopsWork => Some(BetweenRuns::Stop {
                request: stop_request(&reading),
                also_asks: reading.also_asks,
            }),
            MidRunIntent::AboutRunningWork => Some(BetweenRuns::Status),
            MidRunIntent::ChangesWork | MidRunIntent::Unrelated => None,
        }
    }

    /// Run `turn` and then each turn queued behind it.
    /// Run `first`, then every turn queued behind it, in order.
    pub async fn run(self, surface: Arc<dyn TurnSurface>, first: Turn) {
        let registry = Arc::clone(&self.deps.task_registry);
        let agent = Arc::clone(&self.deps.agent);
        let stale_secs = self.deps.watchdog_stale_threshold_secs;
        let session_id = first.session_id;
        let mut text = first.text;
        let mut attachments = first.attachments;
        let mut role = first.user_role;
        let mut channel_ctx = first.channel_ctx;
        let mut timing = first.ingress_timing;
        // Stops the working indicator even if this task panics.
        let indicator = Arc::new(std::sync::Mutex::new(CancellationToken::new()));
        let _indicator_guard = CancelOnDrop(indicator.clone());

        loop {
            // Each turn gets the whole limit; a message queued behind a long
            // turn does not inherit what that turn used.
            let owner_wait = OwnerWaitClock::default();
            // Shown in "current task (…)" notices and cancel replies.
            let description = crate::presentation::word_preview(&text, 80);
            let (task_id, cancel) = registry.register(&session_id, &description).await;
            let observer = self.deps.watch.observer();
            if let Some(observer) = observer.as_ref() {
                observer.turn_started(&TurnStart {
                    session_id: &session_id,
                    turn: task_id,
                    platform: surface.platform(),
                    text: &text,
                    attachments: &attachments,
                    user_role: role,
                    description: &description,
                    channel_ctx: &channel_ctx,
                });
            }
            self.live.begin(&session_id, task_id);
            let heartbeat = Arc::new(AtomicU64::new(now_secs()));
            registry.set_heartbeat(task_id, heartbeat.clone()).await;
            let working = CancellationToken::new();
            if let Ok(mut slot) = indicator.lock() {
                *slot = working.clone();
            }
            surface.show_working(working.clone(), heartbeat.clone(), stale_secs);
            registry.set_typing_cancel(task_id, working.clone()).await;
            let (status_tx, mut run_updates) = mpsc::channel::<StatusUpdate>(16);
            let (shown_tx, status_rx) = mpsc::channel::<StatusUpdate>(16);
            // Each update is noted as the work's live state, then shown.
            {
                let live = self.live.clone();
                let session_id = session_id.clone();
                let observer = observer.clone();
                tokio::spawn(async move {
                    while let Some(update) = run_updates.recv().await {
                        // Reply text and messages taken mid-run are for app
                        // clients: no chat surface, card or live state shows
                        // them.
                        if matches!(
                            update,
                            StatusUpdate::ReplyText(_) | StatusUpdate::MessageTaken { .. }
                        ) {
                            if let Some(observer) = observer.as_ref() {
                                observer.turn_status(&session_id, task_id, &update);
                            }
                            continue;
                        }
                        live.record(&session_id, task_id, &update);
                        if let Some(observer) = observer.as_ref() {
                            observer.turn_status(&session_id, task_id, &update);
                        }
                        let _ = shown_tx.send(update).await;
                    }
                });
            }
            let private = channel_ctx.visibility == ChannelVisibility::Private;
            // A surface that keeps a card gets it from the runner, which
            // owns how it ends; any other shows the updates its own way.
            let card = surface.card_sink().map(TurnCard::new);
            let settle = CancellationToken::new();
            let status_task = match &card {
                Some(card) => tokio::spawn(show_on_card(
                    surface.clone(),
                    card.clone(),
                    status_rx,
                    private,
                    settle.clone(),
                )),
                None => surface
                    .show_status(status_rx, private)
                    .unwrap_or_else(|updates| throttled_status(surface.clone(), updates, private)),
            };
            // Marked once everything the turn shows is out, however this
            // iteration ends.
            let turn_over = TurnOver::default();
            let over_when_dropped = turn_over.over.clone().drop_guard();
            if let Some(timing) = timing.as_mut() {
                timing.mark_dispatched_now();
            }

            let result = tokio::select! {
                result = turn_over.within(OwnerWaitClock::within(
                    Some(owner_wait.clone()),
                    agent.handle_inbound_message(InboundMessageRequest {
                        session_id: session_id.clone(),
                        user_text: text.clone(),
                        attachments: attachments.clone(),
                        status_tx: Some(status_tx),
                        user_role: role,
                        channel_ctx: channel_ctx.clone(),
                        heartbeat: Some(heartbeat.clone()),
                        ingress_timing: timing.clone(),
                    }),
                )) => result.map_err(TurnStop::Agent),
                _ = cancel.cancelled() => Err(TurnStop::Cancelled),
                stale_mins = wait_for_stale_heartbeat(heartbeat.clone(), stale_secs, 4), if stale_secs > 0 => {
                    Err(TurnStop::Inactive { minutes: stale_mins })
                },
            };
            working.cancel();
            self.live.end(&session_id, task_id);
            // The run is over: what it sent must reach the card before the
            // reply, or the card stays on "Working" above a reply (and a
            // helper it started is missing when the card's end is decided).
            // The card shows what is queued and stops, whatever still holds
            // a sender. Another surface finishes showing what it sent; a
            // background job may still hold a sender, so that wait is
            // bounded and a handoff, whose job keeps running, skips it.
            let mut status_task = status_task;
            let run_finished = matches!(
                &result,
                Ok(envelope) if envelope.disposition
                    != aidaemon_events::AssistantResponseDisposition::BackgroundHandoff
            );
            if card.is_some() {
                settle.cancel();
                let _ = tokio::time::timeout(STATUS_DRAIN, &mut status_task).await;
            } else if run_finished && surface.status_settles_before_reply() {
                let _ = tokio::time::timeout(STATUS_DRAIN, &mut status_task).await;
            }
            status_task.abort();

            // The task stays running while the reply is sent, so a message
            // arriving meanwhile queues instead of starting a second turn.
            let error = match result {
                Ok(envelope) => {
                    let platform = surface.platform();
                    let _ = agent
                        .record_response_delivery(
                            &session_id,
                            envelope.delivery(
                                platform,
                                ResponseDeliveryState::Queued,
                                Vec::new(),
                                None,
                            ),
                        )
                        .await;
                    let reply = crate::presentation::prepare_chat_message(&envelope.text);
                    let tasks: Vec<(u64, String)> = registry
                        .list_for_session(&session_id)
                        .await
                        .into_iter()
                        .map(|entry| (entry.id, entry.description))
                        .collect();
                    let reply = crate::presentation::render_task_numbers(&reply, &tasks);
                    let empty = reply.trim().is_empty();
                    let delivered = if empty {
                        Delivered {
                            state: ResponseDeliveryState::PlatformAcknowledged,
                            message_ids: Vec::new(),
                            error: None,
                        }
                    } else {
                        match &card {
                            Some(card) => card.deliver(surface.as_ref(), &envelope, &reply).await,
                            None => surface.deliver(&envelope, &reply).await,
                        }
                    };
                    let _ = agent
                        .record_response_delivery(
                            &session_id,
                            envelope.delivery(
                                platform,
                                delivered.state,
                                delivered.message_ids,
                                delivered.error,
                            ),
                        )
                        .await;
                    let end = if empty {
                        TurnEnd::Empty
                    } else {
                        TurnEnd::Delivered
                    };
                    if let Some(observer) = observer.as_ref() {
                        observer.turn_finished(&TurnFinish {
                            session_id: &session_id,
                            turn: task_id,
                            platform,
                            end,
                            reply: if empty { "" } else { &reply },
                            handed_off: envelope.disposition
                                == aidaemon_events::AssistantResponseDisposition::BackgroundHandoff,
                            error: None,
                            model: envelope.model.as_deref(),
                        });
                    }
                    if let Some(card) = &card {
                        card.close(surface.as_ref()).await;
                    }
                    surface.turn_ended(end).await;
                    None
                }
                Err(stop) => {
                    let message = stop.to_string();
                    let cancelled = matches!(stop, TurnStop::Cancelled);
                    match &stop {
                        TurnStop::Cancelled => info!("Task #{} cancelled", task_id),
                        TurnStop::Inactive { .. } => {
                            info!("Task #{} auto-cancelled by stale watchdog", task_id);
                            let _ = surface.say(&format!("⚠️ {message}")).await;
                        }
                        TurnStop::Agent(error) => {
                            warn!("Agent error: {}", error);
                            let _ = surface.say(&format!("Error: {message}")).await;
                        }
                    }
                    if let Some(card) = &card {
                        card.close(surface.as_ref()).await;
                    }
                    surface
                        .turn_ended(if cancelled {
                            TurnEnd::Cancelled
                        } else {
                            TurnEnd::Failed
                        })
                        .await;
                    if let Some(observer) = observer.as_ref() {
                        observer.turn_finished(&TurnFinish {
                            session_id: &session_id,
                            turn: task_id,
                            platform: surface.platform(),
                            end: if cancelled {
                                TurnEnd::Cancelled
                            } else {
                                TurnEnd::Failed
                            },
                            reply: "",
                            handed_off: false,
                            error: Some(&message),
                            model: None,
                        });
                    }
                    Some((message, cancelled))
                }
            };

            drop(over_when_dropped);

            if let Some((error, cancelled)) = error.as_ref() {
                let status = if *cancelled {
                    aidaemon_events::TaskStatus::Cancelled
                } else {
                    aidaemon_events::TaskStatus::Failed
                };
                if let Err(terminalize_error) = agent
                    .terminalize_supervised_task(&session_id, status, error.clone())
                    .await
                {
                    warn!(%terminalize_error, "Failed to persist supervised task termination");
                }
            }

            // Finalize and drain together, so a message arriving meanwhile is
            // either drained here or runs directly, never stranded.
            let Some(queued) = registry
                .finalize_and_drain(
                    task_id,
                    &session_id,
                    error.as_ref().map(|(message, _)| message.as_str()),
                )
                .await
            else {
                self.forget_queued_notices(&session_id);
                break;
            };
            // Let the finished turn's messages commit first.
            tokio::time::sleep(Duration::from_millis(100)).await;
            let notice = self.take_queued_notice(&session_id, &queued.text);
            let queued = surface.before_queued(queued).await;
            let preview = crate::presentation::word_preview(&queued.text, 50);
            info!(session_id, "Processing queued message: {}", preview);
            let starting = crate::presentation::queued_message_starting(&queued.text);
            let edited = match notice {
                Some(message_id) => matches!(surface.edit(&message_id, &starting).await, Ok(true)),
                None => false,
            };
            // An app shows the message itself as its turn starts: a "Now
            // on" line would sit just above it (live 2026-11-21).
            if !edited && !queued.listed_by_client {
                let _ = surface.say(&starting).await;
            }
            text = queued.text;
            role = queued.user_role;
            channel_ctx = queued.channel_ctx;
            attachments = queued.attachments;
            timing = queued.ingress_timing;
        }
    }
}

/// Cancels the current token when dropped.
struct CancelOnDrop(Arc<std::sync::Mutex<CancellationToken>>);

impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        if let Ok(token) = self.0.lock() {
            token.cancel();
        }
    }
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// `cancel`, `stop` or `abort`, said on its own.
pub fn is_cancel_word(text: &str) -> bool {
    matches!(
        text.trim().to_lowercase().as_str(),
        "cancel" | "stop" | "abort"
    )
}

/// What a message sent while only background work runs asks for.
enum BetweenRuns {
    /// Stop that work; `also_asks` when the message asks for more than
    /// the stop, which then runs as a turn.
    Stop {
        request: StopRequest,
        also_asks: bool,
    },
    /// Where that work stands.
    Status,
}

/// The stop a reading names: its items, or what bare `/cancel` stops.
fn stop_request(reading: &MidRunReading) -> StopRequest {
    if reading.stop.is_empty() {
        StopRequest::Bare
    } else {
        StopRequest::Numbers(reading.stop.clone())
    }
}

/// Status messages, at most one per [`STATUS_INTERVAL`] unless the update
/// must be seen at once. Outside private conversations only updates that
/// must be seen are sent; the working indicator says the rest.
fn throttled_status(
    surface: Arc<dyn TurnSurface>,
    mut updates: mpsc::Receiver<StatusUpdate>,
    private: bool,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let mut last_sent: Option<tokio::time::Instant> = None;
        while let Some(update) = updates.recv().await {
            let immediate = update.requires_immediate_delivery();
            if !private && !immediate {
                continue;
            }
            let now = tokio::time::Instant::now();
            if !immediate && last_sent.is_some_and(|at| now.duration_since(at) < STATUS_INTERVAL) {
                continue;
            }
            let Some(line) = status_line(&update) else {
                continue;
            };
            let _ = surface.say(&line).await;
            last_sent = Some(tokio::time::Instant::now());
        }
    })
}

/// A turn's status updates on its card. Every update notes the card's
/// state ([`crate::live_status::LiveStatus::note`]); the card is sent at
/// most once per [`STATUS_INTERVAL`], and an update that arrives inside the
/// interval is shown when it ends instead of being dropped (live
/// 2026-11-12: a throttled step left the card stale through six minutes of
/// helpers working). A long step's line says how long it has run, refreshed
/// on a tick. Updates that must be seen at once are their own messages.
/// Outside private conversations only those are shown. When `settle` fires
/// (the turn's run is over), whatever is queued is noted and shown, then
/// this ends: the card is settled before the reply, without waiting on
/// work (a background helper) that still holds a sender.
async fn show_on_card(
    surface: Arc<dyn TurnSurface>,
    card: TurnCard,
    mut updates: mpsc::Receiver<StatusUpdate>,
    private: bool,
    settle: CancellationToken,
) {
    let mut last_sent: Option<tokio::time::Instant> = None;
    let mut tick = tokio::time::interval(Duration::from_secs(5));
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    loop {
        let mut last = false;
        let backlog = tokio::select! {
            biased;
            _ = settle.cancelled() => {
                last = true;
                let mut backlog = Vec::new();
                while let Ok(next) = updates.try_recv() {
                    backlog.push(next);
                }
                backlog
            }
            first = updates.recv() => {
                let Some(first) = first else { break };
                // Whatever piled up while the last edit was on its way is
                // applied in order and shown in one edit.
                let mut backlog = vec![first];
                while let Ok(next) = updates.try_recv() {
                    backlog.push(next);
                }
                backlog
            }
            // Nothing new: show what an interval held back, or a long
            // step's new elapsed time.
            _ = tick.tick() => Vec::new(),
        };
        let mut show_now = last;
        for update in backlog {
            if update.requires_immediate_delivery() {
                if let Some(line) = status_line(&update) {
                    let _ = surface.say(&line).await;
                }
                continue;
            }
            if private {
                show_now |= card.live.lock().await.note(&update);
            }
        }
        let due = last_sent.is_none_or(|at| at.elapsed() >= STATUS_INTERVAL);
        if private && (show_now || due) {
            let sent = card
                .live
                .lock()
                .await
                .flush_if_changed(card.sink.as_ref())
                .await;
            if sent {
                last_sent = Some(tokio::time::Instant::now());
            }
        }
        if last {
            break;
        }
    }
}

/// The status line for one update, as Markdown, when it has one: progress
/// in italics, a plan card or a needed action as they are.
pub fn status_line(update: &StatusUpdate) -> Option<String> {
    let text = status_text(update)?;
    Some(match update {
        StatusUpdate::UserActionRequired { .. } | StatusUpdate::Checklist(_) => text,
        _ => format!("_{text}_"),
    })
}

/// The plain status text for one update, when it has one. A step reads as
/// its typed kind in plain words; a tool ending is not a step.
pub fn status_text(update: &StatusUpdate) -> Option<String> {
    use aidaemon_core::card::Step;
    let progress = |text: String| text;
    Some(match update {
        // The working indicator says it; no line of its own.
        StatusUpdate::Thinking(_)
        | StatusUpdate::ReplyText(_)
        | StatusUpdate::MessageTaken { .. } => return None,
        // A generic kind of work ("Checking things") says nothing.
        StatusUpdate::ToolStart { kind, .. } if !kind.says_what() => return None,
        StatusUpdate::ToolStart { kind, .. } => progress(format!("{}…", kind.words())),
        StatusUpdate::ToolProgress { chunk, .. } => {
            let preview: String = chunk.chars().take(100).collect();
            let more = if chunk.chars().count() > 100 {
                "…"
            } else {
                ""
            };
            progress(format!("📤 {preview}{more}"))
        }
        StatusUpdate::UserActionRequired { message } => message.clone(),
        StatusUpdate::ToolComplete { .. } => return None,
        // Bookkeeping for `/stop`: no line of its own.
        StatusUpdate::ToolCancellable { .. } => return None,
        StatusUpdate::ProgressSummary {
            elapsed_mins,
            summary,
        } => progress(format!("📊 Progress ({elapsed_mins} min): {summary}")),
        StatusUpdate::IterationWarning { current, threshold } => progress(format!(
            "⚠️ Approaching soft limit: {current} of {threshold} iterations"
        )),
        StatusUpdate::PlanCreated {
            description,
            total_steps,
            ..
        } => progress(format!(
            "📋 Plan created: {description} ({total_steps} steps)"
        )),
        StatusUpdate::PlanStepStart {
            step_index,
            total_steps,
            description,
            ..
        } => progress(format!(
            "▶️ Step {}/{total_steps}: {description}",
            step_index + 1
        )),
        StatusUpdate::PlanStepComplete {
            step_index,
            total_steps,
            description,
            summary,
            ..
        } => {
            let base = format!(
                "✅ Step {}/{total_steps} done: {description}",
                step_index + 1
            );
            match summary {
                Some(summary) => progress(format!("{base} - {summary}")),
                None => progress(base),
            }
        }
        StatusUpdate::PlanStepFailed {
            step_index,
            description,
            error,
            ..
        } => progress(format!(
            "❌ Step {} failed: {description} - {error}",
            step_index + 1
        )),
        StatusUpdate::PlanComplete {
            description,
            total_steps,
            duration_secs,
            ..
        } => progress(format!(
            "🎉 Plan complete: {description} ({total_steps} steps in {}m {}s)",
            duration_secs / 60,
            duration_secs % 60
        )),
        StatusUpdate::PlanAbandoned { description, .. } => {
            progress(format!("🚫 Plan abandoned: {description}"))
        }
        StatusUpdate::PlanRevised {
            description,
            reason,
            new_total_steps,
            ..
        } => progress(format!(
            "🔄 Plan revised: {description} ({new_total_steps} steps) - {reason}"
        )),
        StatusUpdate::Checklist(plan) => plan.text.clone(),
        StatusUpdate::Helper(helper) => progress(crate::live_status::render_card(
            &crate::live_status::CardView {
                helpers: vec![(helper.clone(), None)],
                ..Default::default()
            },
        )?),
        StatusUpdate::StepHandedOff { kind, .. } => progress(Step::HandedOff(*kind).words()),
        StatusUpdate::CommandOutput { lines, .. } => {
            progress(Step::Output { lines: *lines }.words())
        }
        StatusUpdate::Finished { by_me, total } => progress(crate::live_status::finished_block(
            by_me.as_deref(),
            total.as_deref(),
        )?),
    })
}

/// Repeat `send` every `every` until `stop` is cancelled, the heartbeat has
/// been quiet for `stale_secs` (0 = never), or 30 minutes pass.
pub fn repeat_while_working<F, Fut>(
    every: Duration,
    stop: CancellationToken,
    heartbeat: Arc<AtomicU64>,
    stale_secs: u64,
    mut send: F,
) where
    F: FnMut() -> Fut + Send + 'static,
    Fut: std::future::Future<Output = ()> + Send,
{
    tokio::spawn(async move {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(30 * 60);
        loop {
            send().await;
            tokio::select! {
                _ = tokio::time::sleep(every) => {
                    if stale_secs > 0
                        && now_secs().saturating_sub(heartbeat.load(Ordering::Relaxed)) > stale_secs
                    {
                        break;
                    }
                    if tokio::time::Instant::now() >= deadline {
                        warn!("Working indicator reached its 30-minute limit");
                        break;
                    }
                }
                _ = stop.cancelled() => break,
            }
        }
    });
}

/// Wait until the heartbeat becomes stale and return stale minutes.
///
/// `stale_threshold_secs` must be > 0.
pub async fn wait_for_stale_heartbeat(
    heartbeat: Arc<AtomicU64>,
    stale_threshold_secs: u64,
    check_interval_secs: u64,
) -> u64 {
    debug_assert!(stale_threshold_secs > 0);

    loop {
        tokio::time::sleep(Duration::from_secs(check_interval_secs.max(1))).await;
        let last_hb = heartbeat.load(Ordering::Relaxed);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        if now.saturating_sub(last_hb) > stale_threshold_secs {
            return now.saturating_sub(last_hb) / 60;
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn how_a_turn_stopped_is_typed_not_read_from_its_text() {
        // An agent error that reads like a cancel is still an agent error.
        let stop = super::TurnStop::Agent(anyhow::anyhow!(super::CANCELLED));
        assert!(!matches!(stop, super::TurnStop::Cancelled));
        assert_eq!(
            super::TurnStop::Inactive { minutes: 1 }.to_string(),
            "Task auto-cancelled due to inactivity (1 minute without progress)."
        );
    }

    use super::*;

    #[tokio::test]
    async fn stale_heartbeat_returns_minutes() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let heartbeat = Arc::new(AtomicU64::new(now.saturating_sub(125)));

        let mins = tokio::time::timeout(
            Duration::from_secs(3),
            wait_for_stale_heartbeat(heartbeat, 60, 1),
        )
        .await
        .expect("stale heartbeat should resolve quickly");

        assert!(mins >= 2);
    }

    /// An agent whose turn runs until released and whose reading of a
    /// mid-run message is scripted.
    struct ScriptedAgent {
        release: tokio::sync::Notify,
        reading: std::sync::Mutex<Option<MidRunReading>>,
        /// The chat's sub-agents and background commands; a stop removes one.
        work: std::sync::Mutex<Vec<crate::ports::ChatWork>>,
        /// Exchanges kept in history without a turn: (owner text, reply).
        recorded: std::sync::Mutex<Vec<(String, String)>>,
        /// The text of each turn started.
        turns: std::sync::Mutex<Vec<String>>,
    }

    #[async_trait]
    impl crate::ports::AgentIngress for ScriptedAgent {
        async fn handle_inbound_message(
            &self,
            request: InboundMessageRequest,
        ) -> anyhow::Result<AgentResponseEnvelope> {
            self.turns.lock().unwrap().push(request.user_text.clone());
            if let Some(status) = request.status_tx.as_ref() {
                let _ = status
                    .send(StatusUpdate::tool_start(
                        "terminal",
                        "installing the blog",
                        aidaemon_core::card::ActivityKind::Run,
                    ))
                    .await;
            }
            self.release.notified().await;
            Ok(AgentResponseEnvelope {
                response_id: "r".into(),
                task_id: "t".into(),
                turn_id: None,
                text: "Done.".into(),
                referenced_receipts: Vec::new(),
                disposition: Default::default(),
                model: None,
            })
        }
    }

    #[async_trait]
    impl ChannelAgentRuntime for ScriptedAgent {
        async fn read_mid_run_message(
            &self,
            _session_id: &str,
            _text: &str,
            _work: &RunningWork,
        ) -> Option<MidRunReading> {
            self.reading.lock().unwrap().clone()
        }
        async fn record_control_exchange(
            &self,
            _session_id: &str,
            owner_text: &str,
            _user_role: UserRole,
            _channel_ctx: &crate::context::ChannelContext,
            reply: &str,
        ) {
            self.recorded
                .lock()
                .unwrap()
                .push((owner_text.to_string(), reply.to_string()));
        }
        async fn chat_work(&self, _session_id: &str) -> crate::ports::ChatWorkView {
            crate::ports::ChatWorkView {
                current_request: None,
                items: self.work.lock().unwrap().clone(),
            }
        }
        /// Each sub-agent with a run record, running a command.
        async fn chat_runs(&self, _session_id: &str) -> crate::ports::ChatRuns {
            let runs = self
                .work
                .lock()
                .unwrap()
                .iter()
                .filter_map(|item| {
                    Some(crate::ports::ChatRun {
                        id: item.run.clone()?,
                        view: aidaemon_core::card::HelperView::running(
                            item.title.trim_start_matches("Sub-agent: "),
                            true,
                            Some(aidaemon_core::card::Step::Doing(
                                aidaemon_core::card::ActivityKind::Run,
                            )),
                        ),
                        running_for: Duration::from_secs(60),
                        started_at: chrono::Utc::now(),
                        ended_at: None,
                        activity: None,
                        activity_kind: None,
                        agent: None,
                        agent_mark: None,
                        group: None,
                        edited: Vec::new(),
                        continues: None,
                        thread: None,
                        keeps_session: false,
                        accepts_mid_run: false,
                        queued: false,
                        result: None,
                        asked: None,
                        this_request: false,
                        team: None,
                        seen_checks: Vec::new(),
                        tokens: None,
                        wrote: Vec::new(),
                        pulse: Default::default(),
                    })
                })
                .collect();
            crate::ports::ChatRuns { runs, plan: None }
        }
        async fn stop_chat_work(&self, _session_id: &str, key: &str) -> bool {
            let mut work = self.work.lock().unwrap();
            work.retain(|item| item.key != key);
            true
        }
        async fn terminalize_supervised_task(
            &self,
            _: &str,
            _: aidaemon_events::TaskStatus,
            _: String,
        ) -> anyhow::Result<Option<String>> {
            Ok(None)
        }
        async fn cancel_active_finite_work_for_session(&self, _: &str) -> Vec<String> {
            Vec::new()
        }
        async fn current_model(&self) -> String {
            String::new()
        }
        async fn context_debug_settings(
            &self,
            _: &str,
            _: &str,
        ) -> (bool, usize, usize, usize, Option<i64>) {
            (false, 0, 0, 0, None)
        }
        async fn set_model(&self, _: String) {}
        async fn list_models(&self) -> anyhow::Result<Vec<String>> {
            Ok(Vec::new())
        }
        async fn clear_model_override(&self) {}
        async fn clear_session_context(&self, _: &str) -> anyhow::Result<()> {
            Ok(())
        }
        async fn clear_session(&self, _: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    struct NoSessions;
    impl SessionChannelStore for NoSessions {}

    #[derive(Default)]
    struct Said(std::sync::Mutex<Vec<String>>);

    #[async_trait]
    impl TurnSurface for Said {
        fn platform(&self) -> &'static str {
            "test"
        }
        async fn say(&self, text: &str) -> anyhow::Result<Vec<String>> {
            self.0.lock().unwrap().push(text.to_string());
            Ok(Vec::new())
        }
        fn show_working(&self, _: CancellationToken, _: Arc<AtomicU64>, _: u64) {}
    }

    fn owner_turn(text: &str, key: &str) -> Turn {
        Turn {
            session_id: "test:mid-run".into(),
            text: text.into(),
            attachments: Vec::new(),
            user_role: UserRole::Owner,
            channel_ctx: ChannelContext::private("test"),
            dedup_key: Some(key.into()),
            ingress_timing: None,
        }
    }

    /// Messages a restart left waiting come back on the queue with nothing
    /// running to drain them: each runs as its own turn, in order, with
    /// the role it was sent with.
    #[tokio::test]
    async fn messages_a_restart_left_waiting_run_in_order() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(Vec::new()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = Arc::new(TaskRegistry::new(10));
        let runner = TurnRunner::new(TurnDeps {
            agent: agent.clone(),
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: registry.clone(),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let session = "test:restored";
        let waiting = |text: &str| {
            crate::tasks::QueuedMessage::new(
                text,
                UserRole::Owner,
                ChannelContext::private("test"),
                Vec::new(),
            )
            .placed_for_later()
        };
        let snapshot: crate::tasks::QueueSnapshot = [(
            session.to_string(),
            vec![waiting("first"), waiting("second")],
        )]
        .into();
        assert_eq!(registry.restore_queues(snapshot).await, vec![session]);

        let surface = Arc::new(Said::default());
        let run = tokio::spawn(runner.clone().run_restored(surface, session));
        for expected in 1..=2 {
            for _ in 0..400 {
                if agent.turns.lock().unwrap().len() == expected {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            agent.release.notify_one();
        }
        run.await.unwrap();
        assert_eq!(agent.turns.lock().unwrap().as_slice(), ["first", "second"]);
        assert_eq!(registry.queue_len(session).await, 0);
    }

    /// A question about the running work is answered at once from its live
    /// state and never reaches the run; a change joins the run; anything
    /// else waits for its own turn.
    #[tokio::test]
    async fn a_mid_run_message_is_answered_joined_or_kept_by_its_reading() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(Vec::new()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = Arc::new(TaskRegistry::new(10));
        let runner = TurnRunner::new(TurnDeps {
            agent: agent.clone(),
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: registry.clone(),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let surface = Arc::new(Said::default());
        let session = "test:mid-run";
        runner
            .submit(surface.clone(), owner_turn("Set up two demo sites", "m1"))
            .await;
        for _ in 0..200 {
            if registry.has_running_task(session).await
                && runner.running_work(session).await.last_step.is_some()
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        let set = |reading: Option<MidRunReading>| *agent.reading.lock().unwrap() = reading;
        let last = |surface: &Said| {
            surface
                .0
                .lock()
                .unwrap()
                .last()
                .cloned()
                .unwrap_or_default()
        };

        // A question: the typed state itself is the reply.
        set(Some(MidRunReading {
            intent: MidRunIntent::AboutRunningWork,
            stop: Vec::new(),
            also_asks: false,
        }));
        runner
            .submit(surface.clone(), owner_turn("How is it going so far?", "m2"))
            .await;
        let reply = last(&surface);
        assert!(
            reply.starts_with("Still working on \"Set up two demo sites\""),
            "{reply}"
        );
        assert!(reply.contains("Latest step: Running a command"), "{reply}");
        // Worded differently, it gets the same typed state.
        runner
            .submit(
                surface.clone(),
                owner_turn("Send me the screenshots now.", "m3"),
            )
            .await;
        let reply = last(&surface);
        assert!(
            reply.starts_with("Still working on \"Set up two demo sites\""),
            "{reply}"
        );
        assert_eq!(registry.queue_len(session).await, 0);

        // Something else: queued for its own turn, not taken into the run.
        set(Some(MidRunReading {
            intent: MidRunIntent::Unrelated,
            stop: Vec::new(),
            also_asks: false,
        }));
        runner
            .submit(
                surface.clone(),
                owner_turn("What is the capital of Peru?", "m4"),
            )
            .await;
        assert_eq!(
            last(&surface),
            crate::presentation::queued_message_notice(true)
        );
        let ctx = ChannelContext::private("test");
        assert!(
            registry
                .take_steering_messages(session, UserRole::Owner, &ctx)
                .await
                .is_empty()
        );
        registry.clear_queue(session).await;

        // A change to the work (or no reading at all): it joins the run.
        // With no reading (the model call failed) the owner also sees where
        // the work stands, so a question is answered either way.
        for (reading, key) in [
            (
                Some(MidRunReading {
                    intent: MidRunIntent::ChangesWork,
                    stop: Vec::new(),
                    also_asks: false,
                }),
                "m5",
            ),
            (None, "m6"),
        ] {
            let unread = reading.is_none();
            set(reading);
            runner
                .submit(surface.clone(), owner_turn("how's it going?", key))
                .await;
            let notice = last(&surface);
            assert!(
                notice.starts_with(&crate::presentation::queued_message_notice(false)),
                "{notice}"
            );
            assert_eq!(
                notice.contains("Still working on \"Set up two demo sites\""),
                unread,
                "{notice}"
            );
            assert_eq!(
                notice.contains("Latest step: Running a command"),
                unread,
                "{notice}"
            );
            let taken = registry
                .take_steering_messages(session, UserRole::Owner, &ctx)
                .await;
            assert_eq!(taken.len(), 1);
        }

        // The owner's own placement wins over any reading: even a message
        // read as a question goes where the owner put it.
        // The app lists a placed message under "Waiting to send": no "Got
        // it" line is said for it.
        set(Some(MidRunReading {
            intent: MidRunIntent::AboutRunningWork,
            stop: Vec::new(),
            also_asks: false,
        }));
        let said_before = surface.0.lock().unwrap().len();
        runner
            .submit_placed(
                surface.clone(),
                owner_turn("How is it going so far?", "m7"),
                Some(MidRunPlacement::Queue),
            )
            .await;
        assert_eq!(surface.0.lock().unwrap().len(), said_before);
        assert!(
            registry
                .take_steering_messages(session, UserRole::Owner, &ctx)
                .await
                .is_empty()
        );
        assert_eq!(registry.queue_len(session).await, 1);
        registry.clear_queue(session).await;
        runner
            .submit_placed(
                surface.clone(),
                owner_turn("Use the staging server instead", "m8"),
                Some(MidRunPlacement::Steer),
            )
            .await;
        assert_eq!(surface.0.lock().unwrap().len(), said_before);
        let taken = registry
            .take_steering_messages(session, UserRole::Owner, &ctx)
            .await;
        assert_eq!(taken.len(), 1);

        // A placed message runs as its own turn once the work ends with no
        // "Now on" line: the app shows the message itself.
        runner
            .submit_placed(
                surface.clone(),
                owner_turn("Then list the files", "m9"),
                Some(MidRunPlacement::Queue),
            )
            .await;
        agent.release.notify_one();
        for _ in 0..200 {
            if agent
                .turns
                .lock()
                .unwrap()
                .iter()
                .any(|t| t == "Then list the files")
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        assert!(
            agent
                .turns
                .lock()
                .unwrap()
                .iter()
                .any(|t| t == "Then list the files"),
            "the placed message ran as a turn"
        );
        assert!(
            !surface
                .0
                .lock()
                .unwrap()
                .iter()
                .any(|said| said.starts_with("▶️ Now on")),
            "{:?}",
            surface.0.lock().unwrap()
        );
        agent.release.notify_one();
    }

    /// A turn that reports `updates`, starts work that outlives it (it
    /// waits on [`TurnOver`], then notes its end in the chat's log) and
    /// replies `reply`.
    struct CardAgent {
        updates: Vec<StatusUpdate>,
        reply: &'static str,
        disposition: aidaemon_events::AssistantResponseDisposition,
        log: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[async_trait]
    impl crate::ports::AgentIngress for CardAgent {
        async fn handle_inbound_message(
            &self,
            request: InboundMessageRequest,
        ) -> anyhow::Result<AgentResponseEnvelope> {
            if let Some(turn) = TurnOver::current() {
                let log = self.log.clone();
                tokio::spawn(async move {
                    turn.wait().await;
                    log.lock().unwrap().push("background work ended".into());
                });
            }
            if let Some(status) = request.status_tx.as_ref() {
                for update in &self.updates {
                    let _ = status.send(update.clone()).await;
                }
            }
            Ok(AgentResponseEnvelope {
                response_id: "r".into(),
                task_id: "t".into(),
                turn_id: None,
                text: self.reply.into(),
                referenced_receipts: Vec::new(),
                disposition: self.disposition,
                model: None,
            })
        }
    }

    #[async_trait]
    impl ChannelAgentRuntime for CardAgent {
        async fn terminalize_supervised_task(
            &self,
            _: &str,
            _: aidaemon_events::TaskStatus,
            _: String,
        ) -> anyhow::Result<Option<String>> {
            Ok(None)
        }
        async fn cancel_active_finite_work_for_session(&self, _: &str) -> Vec<String> {
            Vec::new()
        }
        async fn current_model(&self) -> String {
            String::new()
        }
        async fn context_debug_settings(
            &self,
            _: &str,
            _: &str,
        ) -> (bool, usize, usize, usize, Option<i64>) {
            (false, 0, 0, 0, None)
        }
        async fn set_model(&self, _: String) {}
        async fn list_models(&self) -> anyhow::Result<Vec<String>> {
            Ok(Vec::new())
        }
        async fn clear_model_override(&self) {}
        async fn clear_session_context(&self, _: &str) -> anyhow::Result<()> {
            Ok(())
        }
        async fn clear_session(&self, _: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    /// A chat that keeps a card (as Telegram does): every message, card
    /// change and hand-off lands in one log, in order.
    struct CardChat {
        log: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[async_trait]
    impl crate::live_status::SurfaceSink for CardChat {
        async fn create(&self, text: &str) -> anyhow::Result<Option<String>> {
            self.log.lock().unwrap().push(format!("card:{text}"));
            Ok(Some("card-1".into()))
        }
        async fn edit(&self, _: &str, text: &str) -> anyhow::Result<bool> {
            self.log.lock().unwrap().push(format!("card:{text}"));
            Ok(true)
        }
        async fn delete(&self, _: &str) -> anyhow::Result<bool> {
            self.log.lock().unwrap().push("card deleted".into());
            Ok(true)
        }
    }

    struct CardSurface(Arc<CardChat>);

    #[async_trait]
    impl TurnSurface for CardSurface {
        fn platform(&self) -> &'static str {
            "test"
        }
        async fn say(&self, text: &str) -> anyhow::Result<Vec<String>> {
            self.0.log.lock().unwrap().push(format!("say:{text}"));
            Ok(vec!["reply-1".into()])
        }
        fn show_working(&self, _: CancellationToken, _: Arc<AtomicU64>, _: u64) {}
        fn card_sink(&self) -> Option<Arc<dyn crate::live_status::SurfaceSink>> {
            Some(self.0.clone())
        }
        async fn card_kept(&self, id: &str) {
            self.0.log.lock().unwrap().push(format!("card kept {id}"));
        }
    }

    /// Run one turn of `agent` on a chat that keeps a card; the chat's log.
    async fn run_card_turn(
        updates: Vec<StatusUpdate>,
        reply: &'static str,
        disposition: aidaemon_events::AssistantResponseDisposition,
    ) -> Vec<String> {
        let log = Arc::new(std::sync::Mutex::new(Vec::new()));
        let agent = Arc::new(CardAgent {
            updates,
            reply,
            disposition,
            log: log.clone(),
        });
        let runner = TurnRunner::new(TurnDeps {
            agent,
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: Arc::new(TaskRegistry::new(10)),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let surface = Arc::new(CardSurface(Arc::new(CardChat { log: log.clone() })));
        runner
            .run(surface, owner_turn("Count both files", "m1"))
            .await;
        for _ in 0..200 {
            if log
                .lock()
                .unwrap()
                .iter()
                .any(|e| e == "background work ended")
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        log.lock().unwrap().clone()
    }

    fn helper(label: &str, phase: aidaemon_core::card::RunPhase) -> StatusUpdate {
        StatusUpdate::Helper(aidaemon_core::card::HelperView {
            run: None,
            phase,
            ..aidaemon_core::card::HelperView::running(label, false, None)
        })
    }

    /// The runner's path: the same card state ends the same way as the
    /// card's own rule says. Two helpers ran side by side, so the card is
    /// kept and settled after the reply (live 2026-11-13: deleted at turn
    /// end with no final header); a single step collapses.
    #[tokio::test]
    async fn the_runner_ends_each_card_by_its_typed_state() {
        use aidaemon_core::card::{ActivityKind, RunPhase};
        let log = run_card_turn(
            vec![
                StatusUpdate::tool_start("spawn", "", ActivityKind::Delegate),
                helper("Count lines", RunPhase::Running),
                helper("Count words", RunPhase::Running),
                helper("Count lines", RunPhase::Succeeded),
                helper("Count words", RunPhase::Succeeded),
            ],
            "Lines: 12. Words: 80.",
            Default::default(),
        )
        .await;
        // The card already reads settled once both helpers ended (the turn
        // waiting on them is no step of its own), and it is kept after the
        // reply, never deleted.
        let reply = log.iter().position(|e| e == "say:Lines: 12. Words: 80.");
        let settled = log.iter().rposition(|e| {
            e == "card:✅ A helper finished: Count lines\n\n✅ A helper finished: Count words"
        });
        let kept = log.iter().position(|e| e == "card kept card-1");
        assert!(
            settled.is_some() && reply.is_some() && kept > reply,
            "{log:#?}"
        );
        assert!(!log.contains(&"card deleted".to_string()), "{log:#?}");

        let log = run_card_turn(
            vec![StatusUpdate::tool_start("read", "", ActivityKind::Read)],
            "It says hello.",
            Default::default(),
        )
        .await;
        let reply = log.iter().position(|e| e == "say:It says hello.");
        let deleted = log.iter().position(|e| e == "card deleted");
        assert!(reply.is_some() && deleted > reply, "{log:#?}");
        assert!(!log.iter().any(|e| e.starts_with("card kept")), "{log:#?}");
    }

    /// A background handoff with a run on its card keeps the card: the ack
    /// goes out as its own message, before anything the background work does
    /// when it ends. One with nothing kept is removed after the ack: the
    /// card never becomes a message of its own.
    #[tokio::test]
    async fn a_handoffs_ack_comes_before_the_work_ends() {
        use aidaemon_core::card::HelperView;
        use aidaemon_events::AssistantResponseDisposition::BackgroundHandoff;
        let log = run_card_turn(
            vec![StatusUpdate::Helper(HelperView::running(
                "Slow count",
                true,
                None,
            ))],
            "Started in the background: Slow count.",
            BackgroundHandoff,
        )
        .await;
        let ack = log
            .iter()
            .position(|e| e == "say:Started in the background: Slow count.");
        let kept = log.iter().position(|e| e == "card kept card-1");
        let ended = log.iter().position(|e| e == "background work ended");
        assert!(ack.is_some() && kept > ack && ended > kept, "{log:#?}");
        assert!(
            !log.iter().any(|e| e.starts_with("card became")),
            "{log:#?}"
        );

        let log = run_card_turn(
            vec![StatusUpdate::step_handed_off(
                "running the installer",
                aidaemon_core::card::ActivityKind::Run,
            )],
            "Started the install in the background.",
            BackgroundHandoff,
        )
        .await;
        let ack = log
            .iter()
            .position(|e| e == "say:Started the install in the background.");
        let deleted = log.iter().position(|e| e == "card deleted");
        let ended = log.iter().position(|e| e == "background work ended");
        assert!(
            ack.is_some() && deleted > ack && ended > deleted,
            "{log:#?}"
        );
        assert!(
            !log.contains(&"card:Started the install in the background.".to_string()),
            "{log:#?}"
        );
    }

    #[test]
    fn cancel_words_are_whole_messages() {
        assert!(is_cancel_word("Stop"));
        assert!(is_cancel_word(" cancel "));
        assert!(!is_cancel_word("stop the server"));
        assert!(!is_cancel_word("don't stop"));
    }

    /// Two background commands started by one request: a bare stop word
    /// stops both and names each, read back as gone; with nothing left it
    /// says so. A stop request read in plain words between runs takes the
    /// same path.
    #[tokio::test]
    async fn a_bare_stop_stops_every_job_of_one_request_and_names_them() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(two_counting_jobs()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = Arc::new(TaskRegistry::new(10));
        let runner = TurnRunner::new(TurnDeps {
            agent: agent.clone(),
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: registry.clone(),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let surface = Arc::new(Said::default());
        runner
            .submit(surface.clone(), owner_turn("stop", "s1"))
            .await;
        let reply = surface.0.lock().unwrap().last().cloned().unwrap();
        assert_eq!(
            reply,
            "⏹️ Stopped:\n• Sub-agent: Counting agent A\n• Background command: count to 300"
        );
        assert!(agent.work.lock().unwrap().is_empty());
        runner
            .submit(surface.clone(), owner_turn("stop", "s2"))
            .await;
        assert_eq!(
            surface.0.lock().unwrap().last().cloned().unwrap(),
            "Nothing is running in this chat right now."
        );

        // "Stop both counting agents now", read as a stop request: no turn
        // starts, and the same read-back stop runs.
        *agent.work.lock().unwrap() = two_counting_jobs();
        *agent.reading.lock().unwrap() = Some(MidRunReading {
            intent: MidRunIntent::StopsWork,
            stop: Vec::new(),
            also_asks: false,
        });
        runner
            .submit(
                surface.clone(),
                owner_turn("Stop both counting agents now.", "s3"),
            )
            .await;
        assert!(!registry.has_running_task("test:mid-run").await);
        let reply = surface.0.lock().unwrap().last().cloned().unwrap();
        assert!(reply.contains("• Sub-agent: Counting agent A"), "{reply}");
        assert!(
            reply.contains("• Background command: count to 300"),
            "{reply}"
        );
        assert!(agent.work.lock().unwrap().is_empty());
    }

    /// Live 2026-11-21: "stop it and delete it, I don't need it" sent while
    /// a background job ran stopped the job, but the message never reached
    /// the chat's history and the delete was dropped. A plain stop is kept
    /// as an exchange; a stop that asks for more stops the work and runs
    /// the message as a turn.
    #[tokio::test]
    async fn a_stop_is_kept_in_history_and_what_else_it_asks_runs_as_a_turn() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(Some(MidRunReading {
                intent: MidRunIntent::StopsWork,
                stop: Vec::new(),
                also_asks: false,
            })),
            work: std::sync::Mutex::new(two_counting_jobs()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let runner = TurnRunner::new(TurnDeps {
            agent: agent.clone(),
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: Arc::new(TaskRegistry::new(10)),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let surface = Arc::new(Said::default());
        runner
            .submit(surface.clone(), owner_turn("Stop the counting jobs.", "k1"))
            .await;
        let recorded = agent.recorded.lock().unwrap().clone();
        assert_eq!(recorded.len(), 1, "{recorded:?}");
        assert_eq!(recorded[0].0, "Stop the counting jobs.");
        assert!(recorded[0].1.starts_with("⏹️ Stopped:"), "{recorded:?}");
        assert!(agent.turns.lock().unwrap().is_empty());

        *agent.work.lock().unwrap() = two_counting_jobs();
        *agent.reading.lock().unwrap() = Some(MidRunReading {
            intent: MidRunIntent::StopsWork,
            stop: Vec::new(),
            also_asks: true,
        });
        agent.release.notify_one();
        runner
            .submit(
                surface.clone(),
                owner_turn("Stop it and delete what it made.", "k2"),
            )
            .await;
        assert!(agent.work.lock().unwrap().is_empty());
        assert_eq!(agent.recorded.lock().unwrap().len(), 1);
        // The turn runs on its own task.
        for _ in 0..200 {
            if !agent.turns.lock().unwrap().is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        assert_eq!(
            agent.turns.lock().unwrap().as_slice(),
            ["Stop it and delete what it made."]
        );
    }

    /// Only helpers and background commands run, no turn (live 2026-11-13:
    /// "how's it going?" became a turn that said "Still working on
    /// \"how's it going?\" (1s so far)"). A question about them is answered
    /// from their typed state, each helper with the step it last reported
    /// (a step from after the turn that started it ended) and the time
    /// `/tasks` shows; no turn starts. Anything else still runs as a turn.
    #[tokio::test]
    async fn a_status_question_between_runs_gets_the_typed_status() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(Some(MidRunReading {
                intent: MidRunIntent::AboutRunningWork,
                stop: Vec::new(),
                also_asks: false,
            })),
            work: std::sync::Mutex::new(two_counting_jobs()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = Arc::new(TaskRegistry::new(10));
        let runner = TurnRunner::new(TurnDeps {
            agent: agent.clone(),
            session_map: Arc::default(),
            sessions: Arc::new(NoSessions),
            task_registry: registry.clone(),
            watchdog_stale_threshold_secs: 0,
            watch: TurnWatch::default(),
        });
        let session = "test:mid-run";
        // The turn that started the helper has ended; the helper runs on,
        // its record says how.
        let surface = Arc::new(Said::default());
        runner
            .submit(surface.clone(), owner_turn("how's it going?", "b1"))
            .await;
        assert!(!registry.has_running_task(session).await);
        let reply = surface.0.lock().unwrap().last().cloned().unwrap();
        assert!(reply.starts_with("Working in the background:"), "{reply}");
        assert!(
            reply.contains("\n• Counting agent A: Running a command (1m so far)"),
            "{reply}"
        );
        assert!(
            reply.contains("\n• Background command: count to 300 (50s so far)"),
            "{reply}"
        );
        assert!(!reply.contains("how's it going"), "{reply}");

        // A new request is not a status question: it runs as a turn.
        *agent.reading.lock().unwrap() = Some(MidRunReading {
            intent: MidRunIntent::Unrelated,
            stop: Vec::new(),
            also_asks: false,
        });
        runner
            .submit(
                surface.clone(),
                owner_turn("What is the capital of Peru?", "b2"),
            )
            .await;
        for _ in 0..200 {
            if registry.has_running_task(session).await {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        assert!(registry.has_running_task(session).await);
        agent.release.notify_one();
    }

    /// Work from two requests: a bare stop lists it to pick from and stops
    /// nothing; a number stops just that one.
    #[tokio::test]
    async fn a_bare_stop_over_two_requests_asks_which() {
        let mut work = two_counting_jobs();
        work[1].request = Some("req-2".into());
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(work),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = TaskRegistry::new(10);
        let reply =
            crate::stop::stop(&registry, agent.as_ref(), "test:mid-run", StopRequest::Bare).await;
        assert!(
            reply.starts_with("Work from more than one request is running:"),
            "{reply}"
        );
        assert!(reply.contains("/cancel all"), "{reply}");
        assert_eq!(agent.work.lock().unwrap().len(), 2);
        let list = crate::stop::running_work(&registry, agent.as_ref(), "test:mid-run").await;
        let job = list.entries[1].number;
        let reply = crate::stop::stop(
            &registry,
            agent.as_ref(),
            "test:mid-run",
            StopRequest::Numbers(vec![job]),
        )
        .await;
        assert_eq!(reply, "⏹️ Stopped:\n• Background command: count to 300");
        assert_eq!(agent.work.lock().unwrap().len(), 1);
    }

    /// `/clear` and `/wipe` stop the chat's sub-agents and background
    /// commands through the same read-back stop.
    #[tokio::test]
    async fn clearing_stops_every_sub_agent_and_command() {
        let agent = Arc::new(ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(two_counting_jobs()),
            recorded: Default::default(),
            turns: Default::default(),
        });
        let registry = TaskRegistry::new(10);
        let stopped =
            crate::stop::stop_background_work(&registry, agent.as_ref(), "test:mid-run").await;
        assert_eq!(stopped.len(), 2);
        // `/clear` names what stopped, as `/cancel` does.
        let named = crate::stop::stopped_list(&stopped);
        assert!(named.starts_with("⏹️ Stopped:\n• "), "{named}");
        for title in &stopped {
            assert!(named.contains(title.as_str()), "{named}");
        }
        assert!(agent.work.lock().unwrap().is_empty());
    }

    /// `/tasks` gives each helper's latest step beside its title, as the
    /// status reply does (live 2026-11-13: "#2 Sub-agent: WordPress Install
    /// (29s so far)" with nothing about what it was doing).
    #[tokio::test]
    async fn tasks_lists_a_helpers_latest_step() {
        let mut work = two_counting_jobs();
        work[0].step = Some(aidaemon_core::card::Step::Output { lines: 14 });
        let agent = ScriptedAgent {
            release: tokio::sync::Notify::new(),
            reading: std::sync::Mutex::new(None),
            work: std::sync::Mutex::new(work),
            recorded: Default::default(),
            turns: Default::default(),
        };
        let registry = TaskRegistry::new(10);
        let running = crate::stop::running_work(&registry, &agent, "s1").await;
        let tasks = crate::slash::render_tasks(&running, &[], chrono::Utc::now(), None);
        assert!(
            tasks.contains(
                "Sub-agent: Counting agent A – Running a command · 14 lines of output so far ("
            ),
            "{tasks}"
        );
        assert!(
            tasks.contains("Background command: count to 300 ("),
            "{tasks}"
        );
    }

    fn two_counting_jobs() -> Vec<crate::ports::ChatWork> {
        let now = chrono::Utc::now();
        vec![
            crate::ports::ChatWork {
                key: "agent:1".into(),
                kind: crate::ports::ChatWorkKind::SubAgent,
                title: "Sub-agent: Counting agent A".into(),
                started_at: now - chrono::Duration::seconds(60),
                request: Some("req-1".into()),
                step: None,
                run: Some("helper:a".into()),
            },
            crate::ports::ChatWork {
                key: "job:0:4242".into(),
                kind: crate::ports::ChatWorkKind::BackgroundJob,
                title: "Background command: count to 300".into(),
                started_at: now - chrono::Duration::seconds(50),
                request: Some("req-1".into()),
                step: None,
                run: None,
            },
        ]
    }
}

#[cfg(test)]
mod command_output_card_tests {
    use super::status_text;
    use aidaemon_tools::status::StatusUpdate;

    /// A chat's card never carries what a command printed: only the owner's
    /// own app reads the tail (it can hold a credential the redaction
    /// missed, and a card can be in a group).
    #[test]
    fn a_card_never_shows_a_commands_output() {
        let update = StatusUpdate::CommandOutput {
            name: "terminal".into(),
            lines: 3,
            tail: Some("SYNTHETIC-OUTPUT-LINE".into()),
        };
        let shown = status_text(&update).unwrap_or_default();
        assert!(!shown.contains("SYNTHETIC-OUTPUT-LINE"), "{shown}");
    }
}