mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
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
//! Channel message enrichment: media markers, link enrichment, file operations and media
//! handling — what transforms a [`ChannelMessage`]'s content before it reaches the agent pipeline.
//!
//! Media markers (`[IMAGE: ...]`, `[AUDIO: ...]`, `[VIDEO: ...]`, `[FILE: ...]`): an inbound
//! local image becomes a native data-URI part carrying the original bytes, re-encoded to a
//! bounded JPEG only when it would exceed the encoded-payload cap; audio is a workspace copy
//! plus its transcript; video is a workspace copy plus its timeline; an inbound document is copied
//! into the workspace and converted to text and its first
//! [`crate::document::MAX_READ_PICTURES`] pictures. Link enrichment prepends webpage
//! summaries for URLs in the message.
//!
//! **Containment invariant**: every local read, copy and delete is scoped to the message's
//! own staging directories ([`ChannelMessage::attachment_dirs`], built by
//! `util::telegram_staging_dir_name`) — one for a single message, several for a merged
//! album. A marker is in scope only when it names a file inside one of those; everything
//! else (another chat's or message's attachment, a hand-typed marker, a message owning no
//! directory) is inert text: IMAGE/AUDIO/VIDEO degrade to a plain annotation and
//! `[FILE:...]` stays verbatim, so nothing is read, transcribed, copied or deleted. The
//! desktop composer stages attachments the same way (`gui::attachment`), so a GUI message is
//! enriched exactly like a Telegram one.
//!
//! Entry points are [`enrich_message`] and [`enrich_links`]; [`has_inbound_temp_marker`] is
//! called by `channels::persist_content` to decide what is persisted to chat history.
//! [`enrich_message`] takes the workspace whose `uploads/` receives saved full-resolution
//! copies (`None` disables copies) — the path that makes a clip's timeline possible, and the one
//! place every kept copy lives, aged out by `research_cleanup::sweep_media`'s mention rule.

use crate::ChannelMessage;
use crate::document::{DocOutcome, INLINE_TEXT_MAX_CHARS, convert_document_file};
use crate::tools::chrome::ChromeTool;
use crate::util::media_target::{self, MediaTarget};
use crate::util::{
    MEDIA_MARKER_RE, MediaMarkerKind, file_name_or_path, is_http_url, parse_media_marker,
};
use regex::Regex;
use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt::Write;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};

/// Matches http:// and https:// URLs, stopping at whitespace, angle brackets or quotes.
static URL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"https?://[^\s<>"']+"#).expect("URL regex must compile"));

/// Process-global sequence for link-enricher session names: the `link-enricher-` prefix is
/// load-bearing (`is_mahbot_session_name` sweeps only sessions starting with it) and unique
/// suffixes keep concurrent [`enrich_links`] runs from sharing a chrome session.
static LINK_ENRICHER_SEQ: AtomicU64 = AtomicU64::new(0);

/// What a recording reads as when it could not be transcribed: the icon combo alone, which is also
/// the annotation for out-of-scope `[AUDIO:...]` markers that must never be read or deleted.
const AUDIO_ICON: &str = "🔊✍️";

/// A transcribed message as presented: the icon combo, one space, then the text. The one
/// definition of that form — an inbound audio attachment and a voice recording both go
/// through it, so a spoken message reads the same however it arrived.
#[must_use]
pub(crate) fn marked_transcript(text: &str) -> String {
    format!("{AUDIO_ICON} {text}")
}

/// One recording into words: the transcript, or `None` when transcription is switched off, fails,
/// or reads nothing. Saving the file is the caller's business — the recording outlives the words
/// either way, so this never deletes or renames it.
async fn transcribe_audio_marker(path: &std::path::Path) -> Option<String> {
    if !crate::audio::voice::is_transcription_disabled() {
        // The 10-minute engine bound: attached audio can be arbitrarily long (voice memos,
        // meeting recordings, etc.).
        match crate::speech::transcribe_file_async(path, crate::speech::INFERENCE_TIMEOUT).await {
            Ok(text) => {
                tracing::debug!("Local audio transcription succeeded");
                let text = text.trim();
                if !text.is_empty() {
                    return Some(marked_transcript(text));
                }
            }
            Err(e) => {
                tracing::warn!(error = %e, "Local audio transcription failed");
            }
        }
    }

    tracing::warn!("Audio transcription unavailable");
    None
}

/// Whether `path` is above the size automatic processing stops at.
///
/// `bound` is the transport's own limit, and only the Telegram receive path has one: a file above
/// it could only have arrived through the local Bot API server, and receiving such a file means
/// saving it. The bound stays on the conversions that read the whole file into memory — a document,
/// or a recording, whose sound the recogniser reads whole: from the file itself, or from what the
/// media toolchain converted it to. A video is not one of them: its timeline is decoded from the
/// file on disk, a piece at a time, so every inbound video gets one.
async fn too_large_to_process(path: &std::path::Path, bound: u64) -> bool {
    tokio::fs::metadata(path)
        .await
        .is_ok_and(|meta| meta.len() > bound)
}

/// A media file copied into the workspace `uploads/` directory: the
/// `[Saved {label}: path]` annotation for the message and the destination
/// path for agent tool references.
struct SavedMedia {
    annotation: String,
    dest: std::path::PathBuf,
}

/// Copy a media file (image/video/audio) into the workspace `uploads/` directory
/// under a fresh `upload_<millis>.<ext>` name, so the agent can reference it
/// via tool calls. Returns `None` when no uploads dir is available or the copy fails.
///
/// The source's own extension is kept, so the copy is the container it really is. `fallback_ext`
/// names one only where the source has none and its kind guarantees it; a recording passes `None`,
/// because an unknown container must not be renamed to one it is not — the copy is then named
/// `upload_<millis>` with no extension at all.
async fn save_media_to_workspace(
    media_path: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    label: &str,
    fallback_ext: Option<&str>,
) -> Option<SavedMedia> {
    let dir = uploads_dir?;
    let millis = crate::util::unix_millis();
    let name = match media_path
        .extension()
        .and_then(|e| e.to_str())
        .or(fallback_ext)
    {
        Some(ext) => format!("upload_{millis}.{ext}"),
        None => format!("upload_{millis}"),
    };
    let dest = copy_to_uploads(media_path, dir, &name).await?;
    Some(SavedMedia {
        annotation: format!("[Saved {label}: {}]", dest.display()),
        dest,
    })
}

/// Copy `src` into the workspace uploads dir `dir` as `name`, creating the dir
/// and disambiguating the name when a file of that name is already there.
///
/// Fail-open: `None` when the dir cannot be created or the copy fails — the
/// caller then annotates the message without a workspace handle (a document's
/// conversion still runs).
async fn copy_to_uploads(
    src: &std::path::Path,
    dir: &std::path::Path,
    name: &str,
) -> Option<std::path::PathBuf> {
    if let Err(e) = tokio::fs::create_dir_all(dir).await {
        tracing::warn!(
            dir = %dir.display(),
            error = %e,
            "Failed to create the workspace uploads dir"
        );
        return None;
    }
    // The created file *is* the collision check, so a failure after this point
    // would leave an empty or truncated file in the uploads dir with nothing
    // referencing it.
    let (mut dest, path) = match crate::util::create_unique_file(dir, name).await {
        Ok(handle) => handle,
        Err(e) => {
            tracing::warn!(
                dir = %dir.display(),
                error = %e,
                "Failed to create a file in the workspace uploads dir"
            );
            return None;
        }
    };
    let copied = async {
        let mut source = tokio::fs::File::open(src).await?;
        tokio::io::copy(&mut source, &mut dest).await?;
        Ok::<_, std::io::Error>(())
    }
    .await;
    if let Err(e) = copied {
        tracing::warn!(
            path = %src.display(),
            error = %e,
            "Failed to copy a file into the workspace uploads dir"
        );
        let _ = tokio::fs::remove_file(&path).await;
        return None;
    }
    Some(path)
}

enum ImageAction {
    /// Keep the marker unchanged (e.g. HTTP/HTTPS URL).
    Keep,
    /// Replace the marker with the given text, optionally including an
    /// upload-path annotation for agent tool references. `delete_temp` is set
    /// only when the source file was consumed from this message's inbound
    /// attachments (copied/read) — out-of-scope and missing files are never deleted.
    Replace {
        replacement: String,
        upload_annotation: Option<String>,
        delete_temp: bool,
    },
    /// The target is not a decodable local raster. Each caller phrases its own
    /// note: a user-typed marker reads as an invalid image reference, while an
    /// image a document pass extracted reads as a converter note about the
    /// page (its path is a temp artifact the same pass deletes, so it must
    /// never reach model-visible content). `delete_temp` is set when the file
    /// was in scope (this message's inbound attachments).
    Invalid { delete_temp: bool },
}

impl ImageAction {
    /// Whether the source temp file was consumed from this message's inbound
    /// attachments and may be deleted. `false` for [`Self::Keep`] (an
    /// HTTP/HTTPS URL: no local file) and for a missing or out-of-scope path.
    fn delete_temp(&self) -> bool {
        match self {
            Self::Keep => false,
            Self::Replace { delete_temp, .. } | Self::Invalid { delete_temp } => *delete_temp,
        }
    }
}

/// Produce a data-URI for a confirmed-decodable local raster that is guaranteed
/// under the shared encoded-payload cap the provider accepts, so an image is
/// never silently dropped downstream. The primary encode passes the original
/// bytes through; any over-cap result is re-encoded to a bounded JPEG, and a
/// degenerate over-cap result even after that re-encode fails closed.
async fn bounded_image_data_uri(path: &std::path::Path) -> anyhow::Result<String> {
    match crate::util::local_image_to_data_uri(path).await {
        Ok(uri) if uri.len() <= media_target::MAX_DATA_URI_ENCODED_BYTES => Ok(uri),
        Ok(_) => {
            // Over-cap: fall back to a bounded JPEG re-encode; still over cap means failing
            // closed rather than forwarding an over-cap payload.
            tracing::warn!(path = %path.display(), "image data-URI exceeds the encoded-payload cap — re-encoding to a bounded JPEG");
            let reencoded = crate::util::local_image_to_compressed_data_uri_with_meta(path)
                .await?
                .data_uri;
            if reencoded.len() <= media_target::MAX_DATA_URI_ENCODED_BYTES {
                Ok(reencoded)
            } else {
                Err(anyhow::Error::msg(
                    "image exceeds the compressed data-URI cap",
                ))
            }
        }
        Err(e) => Err(e),
    }
}

/// Handle an IMAGE marker — a data URI, an [`ImageAction::Invalid`] target, or (out of scope)
/// a plain-text annotation; a workspace copy is saved when `uploads_dir` is available. The
/// reported `delete_temp` tells the caller whether the source temp file was consumed from this
/// message's inbound attachments and may be cleaned up.
async fn handle_image(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    staging_dirs: &[String],
) -> ImageAction {
    // Only a well-formed http(s) URL is sent as-is; a malformed one falls through to the
    // classifier and stays inert text, matching the provider's final image gate.
    if media_target::is_valid_remote_url(path) {
        return ImageAction::Keep;
    }

    if !path_obj.exists() || !path_obj.is_file() {
        tracing::warn!(%path, "Image file not found for enrichment");
        return ImageAction::Invalid { delete_temp: false };
    }

    // Containment: only this message's own inbound attachment may be read, copied or deleted.
    if !is_inbound_attachment(path_obj, staging_dirs).await {
        tracing::warn!(%path, "Image path outside this message's inbound attachments — annotating without copy");
        return ImageAction::Replace {
            replacement: format!("[Image attached: {}]", file_name_or_path(path)),
            upload_annotation: None,
            delete_temp: false,
        };
    }

    // Only a real raster converts. The file is in scope, so it is a pure temp artifact and
    // is cleaned up even though it is never consumed as an image. The classifier needs a real
    // decode (authoritative, not a magic sniff), so it runs off the async worker.
    if !matches!(
        crate::util::with_block_in_place(|| media_target::classify_media_image_target(path)),
        MediaTarget::LocalImage
    ) {
        return ImageAction::Invalid { delete_temp: true };
    }

    // The classifier established a decodable native raster, so the only failure left is an
    // image too large even after the bounded re-encode — never a junk data-URI.
    let data_uri = bounded_image_data_uri(path_obj).await;

    // The workspace copy waits until the image converts, so a dead file leaves no junk upload
    // plus a "[Saved image: ...]" annotation beside the invalid ref.
    let saved = match &data_uri {
        Ok(_) => save_media_to_workspace(path_obj, uploads_dir, "image", Some("png"))
            .await
            .map(|saved| saved.annotation),
        Err(_) => None,
    };
    let data_uri = match data_uri {
        Ok(data_uri) => data_uri,
        Err(e) => {
            tracing::warn!(%path, error = %e, "Failed to convert image to data URI");
            return ImageAction::Invalid { delete_temp: true };
        }
    };

    ImageAction::Replace {
        replacement: format!("[IMAGE:{data_uri}]"),
        upload_annotation: saved,
        delete_temp: true,
    }
}

/// Canonical path of the daemon's Telegram attachment temp root; `None` when the directory
/// does not exist (then nothing can be in scope).
async fn canonical_telegram_files_root() -> Option<std::path::PathBuf> {
    tokio::fs::canonicalize(crate::util::telegram_files_root())
        .await
        .ok()
}

/// A file inside one of the message's own staging directories under the Telegram temp root
/// (see `util::telegram_staging_dir_name`).
///
/// This is the only legitimate source of inbound media, and the narrower of the two inbound
/// containment predicates: [`has_inbound_temp_marker`] only widens which text is replaced in
/// chat history, while this authorizes reading, copying and deleting, so it demands the exact
/// owning directory. Anything else — another chat's or message's attachment, a hand-typed
/// `[FILE:/etc/passwd]` — is inert text and is never read, copied or deleted.
async fn is_inbound_attachment(path: &std::path::Path, staging_dirs: &[String]) -> bool {
    if staging_dirs.is_empty() {
        return false;
    }
    let Some(root) = canonical_telegram_files_root().await else {
        return false;
    };
    // A path that exists must canonicalize inside the root on its own; the parent fallback
    // applies ONLY to a path that is not there at all (an attachment deleted before
    // enrichment, in the per-message directory the download created for it). A symlink
    // planted in a per-message directory but pointing outside the root exists, so the
    // fallback never rescues it and the marker is left inert.
    let candidate = match tokio::fs::canonicalize(path).await {
        Ok(canonical) => canonical,
        Err(_) => match path.parent() {
            Some(parent) => match tokio::fs::canonicalize(parent).await {
                Ok(canonical) => canonical,
                Err(_) => return false,
            },
            None => return false,
        },
    };
    let Ok(relative) = candidate.strip_prefix(&root) else {
        return false;
    };
    // Exact match: a prefix comparison would also accept a sibling directory of the same chat.
    relative
        .components()
        .next()
        .and_then(|component| component.as_os_str().to_str())
        .is_some_and(|dir| staging_dirs.iter().any(|staging_dir| staging_dir == dir))
}

/// The only shape the receive path generates for a staging directory.
/// [`ChannelMessage::attachment_dirs`] is a public field, and an empty or relative name would
/// make the removal below target the shared Telegram root instead of a directory inside it.
fn is_staging_dir_name(name: &str) -> bool {
    !name.is_empty() && name != "." && name != ".." && !name.contains(std::path::is_separator)
}

/// The replacement text, whether the source temp file was copied into the workspace uploads
/// (so the agent can feed the clip to the video tool as the one to edit) and can be cleaned up, and the
/// optional timeline annotation. HTTP(S) URLs, missing files and out-of-scope paths degrade to
/// plain annotations; in-scope inbound attachments are always cleaned up.
struct VideoAction {
    replacement: String,
    delete_temp: bool,
    /// The clip's timeline in both forms: the model's carries its pictures as ordinary
    /// `[IMAGE:]` markers, the owner's bubble shows the timeline text alone.
    timeline: Option<Annotation>,
}

impl VideoAction {
    /// No workspace copy, no timeline.
    fn annotation(replacement: String) -> Self {
        Self {
            replacement,
            delete_temp: false,
            timeline: None,
        }
    }
}

async fn handle_video(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    staging_dirs: &[String],
) -> VideoAction {
    if is_http_url(path) {
        return VideoAction::annotation(format!("[Video link: {path}]"));
    }
    if !path_obj.exists() || !path_obj.is_file() {
        tracing::warn!(%path, "Video file not found for enrichment");
        return VideoAction::annotation(format!("[Invalid video reference: {path}]"));
    }
    if !is_inbound_attachment(path_obj, staging_dirs).await {
        tracing::warn!(%path, "Video path outside this message's inbound attachments — annotating without copy");
        return VideoAction::annotation(format!("[Video attached: {}]", file_name_or_path(path)));
    }
    if let Some(saved) = save_media_to_workspace(path_obj, uploads_dir, "video", Some("mp4")).await
    {
        // Read the persistent workspace copy, never the temp file. A failure becomes the
        // timeline's own sentence, carried beside the `[Saved video: ...]` annotation. Every
        // inbound video gets one, whatever its size: the timeline decodes from the file on disk
        // rather than holding it in memory, and a read has no bound of its own.
        return VideoAction {
            replacement: saved.annotation,
            delete_temp: true,
            timeline: Some(video_timeline(&saved.dest).await),
        };
    }
    // Copy failed (or no uploads dir): annotate without a timeline, but the in-scope temp file is
    // still a pure intermediate and is cleaned up. A recording is the opposite case — it is the
    // artifact the user wants, so it is deleted only once its workspace copy exists.
    VideoAction {
        replacement: format!("[Video attached: {}]", file_name_or_path(path)),
        delete_temp: true,
        timeline: None,
    }
}

/// The clip's timeline as the message carries it: what the model reads — the timeline text, the
/// line naming the frames each picture holds, then its pictures as ordinary `[IMAGE:]` markers —
/// and what the owner's own bubble shows, which is the same timeline without the pictures. A
/// failure says what happened — a decode failure, a missing sound track and a failed recognition
/// are different sentences.
async fn video_timeline(path: &std::path::Path) -> Annotation {
    match crate::media::read(path, crate::media::Window::Overview).await {
        Ok(reading) => {
            let (model, attached) = crate::media::inline(&reading).await;
            // The bubble attaches no pictures, so it shows the timeline as it stands — and only
            // a reading that really inlined one needs that second form.
            Annotation {
                display: attached.then_some(reading.text),
                model,
            }
        }
        Err(error) => Annotation {
            model: error.unreadable(),
            display: None,
        },
    }
}

/// Handle an AUDIO marker, answering the annotation to add and whether the source temp file may be
/// deleted.
///
/// A recording that is this message's own inbound attachment is copied into the workspace before
/// anything reads it, and lives there by the same rule as every other saved media. Saving does not
/// depend on the transcript: a format the recogniser cannot read, a failed or empty transcription
/// and transcription switched off all leave the file saved. A recording above the
/// automatic-processing bound is saved and never read (only the local Bot API server could have
/// delivered it, and receiving it means keeping it). A marker naming anything else — one
/// typed by the user, another message's attachment — is annotated without a transcript, never
/// copied, and its file is never deleted.
async fn handle_audio(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    staging_dirs: &[String],
    processing_bound: Option<u64>,
) -> (Annotation, bool) {
    if !path_obj.is_file() || !is_inbound_attachment(path_obj, staging_dirs).await {
        tracing::warn!(
            %path,
            "Audio marker is not an inbound attachment file — annotating without transcription"
        );
        return (Annotation::shared(AUDIO_ICON.to_string()), false);
    }

    // Above the bound the recording is kept but not read: the recogniser reads the whole file into
    // memory, whichever decoder reads it.
    let too_large = match processing_bound {
        Some(bound) => too_large_to_process(path_obj, bound).await,
        None => false,
    };

    // Save first: the recording outlives the words, so a transcription that fails, reads nothing
    // or is switched off must not take the file with it.
    let saved = save_media_to_workspace(path_obj, uploads_dir, "audio", None).await;
    let transcript = if too_large {
        None
    } else {
        // The persistent workspace copy, never the temp file.
        let source = saved
            .as_ref()
            .map_or(path_obj, |saved| saved.dest.as_path());
        transcribe_audio_marker(source).await
    };
    // Without a workspace copy the temp file stays for the OS sweep rather than being deleted:
    // losing it is the outcome this path exists to prevent.
    (
        audio_annotation(saved.as_ref(), transcript, too_large),
        saved.is_some(),
    )
}

/// What a recording reads as. The model gets the transcript with the saved location on the line
/// under it; the owner's bubble keeps the transcript alone, because the location is a filesystem
/// path the user's own message never shows. A recording that produced no words reads as the icon
/// combo. Above the processing bound it was never read at all, so both forms are the saved
/// location, as they have always been for a recording kept this way.
fn audio_annotation(
    saved: Option<&SavedMedia>,
    transcript: Option<String>,
    above_bound: bool,
) -> Annotation {
    let display = transcript.unwrap_or_else(|| AUDIO_ICON.to_string());
    let Some(saved) = saved else {
        return Annotation::shared(display);
    };
    if above_bound {
        return Annotation::shared(saved.annotation.clone());
    }
    Annotation {
        model: format!("{display}\n{}", saved.annotation),
        display: Some(display),
    }
}

/// An inbound attachment the receive path saved under the daemon's Telegram temp dir. Returns
/// the marker's replacement text, or `None` out of scope: a user-typed `[FILE:...]` is the
/// user's own text, and another chat's or message's attachment is never read, copied or
/// deleted. An in-scope attachment is copied into the workspace uploads dir under the sender's
/// name and converted into text and images, accumulating the copy, the text and the converter's
/// notes into `batch`; a missing attachment, an unrouted message and a failed copy each degrade
/// to a plain annotation. A file above the automatic-processing bound is saved, not read.
async fn handle_file(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    staging_dirs: &[String],
    processing_bound: Option<u64>,
    batch: &mut EnrichmentBatch,
) -> Option<String> {
    // Containment: only this message's own inbound attachment may be read, copied or deleted.
    if !is_inbound_attachment(path_obj, staging_dirs).await {
        // Also the vanished-staging-directory shape: the parent fallback needs that directory
        // to exist, so the path reads as hand-typed and its marker stays verbatim.
        tracing::warn!(%path, "File path outside this message's inbound attachment — leaving the marker untouched");
        return None;
    }
    let name = file_name_or_path(path);
    // A pure intermediate: the workspace copy (or the extracted text) outlives this call, so a
    // real file is queued for deletion; a marker naming the staging directory is never removed.
    if path_obj.is_file() {
        batch.files_to_delete.push(path_obj.to_path_buf());
    } else if path_obj.exists() {
        return Some(format!(
            "[File {name}: the attachment is not a regular file]"
        ));
    } else {
        tracing::warn!(%path, "Inbound attachment missing for enrichment");
        return Some(format!(
            "[File {name}: could not be retrieved — the downloaded attachment is missing]"
        ));
    }
    let Some(uploads_dir) = uploads_dir else {
        // No workspace path: nowhere to copy the file into and no agent to convert it for.
        return Some(format!(
            "[File {name}: received, not saved to the workspace]"
        ));
    };

    // Copy first: the workspace handle is what the agent reads, and the conversion then runs
    // off a file that outlives the temp cleanup.
    let copy = copy_to_uploads(path_obj, uploads_dir, name).await;
    let copied_to_workspace = copy.is_some();
    let replacement = match &copy {
        Some(dest) => format!("[FILE:{}]", dest.display()),
        None => format!("[File {name}: received, not saved to the workspace]"),
    };

    // Above the bound the file could only have come through the local Bot API server, and
    // receiving it means keeping it: converting would read the whole file into memory.
    if let Some(bound) = processing_bound
        && too_large_to_process(path_obj, bound).await
    {
        let saved = if copied_to_workspace {
            " — open the saved file directly"
        } else {
            ""
        };
        batch.annotate(format!(
            "[File {name}: received but not converted (larger than the {} MB the bot reads \
             automatically){saved}]",
            bound.div_ceil(1024 * 1024)
        ));
        return Some(replacement);
    }

    // Extracted images go into the attachment's own per-message directory, which is what the
    // inbound IMAGE containment accepts. A file always has a parent directory.
    let out_dir = path_obj.parent().unwrap_or(path_obj);
    match convert_document_file(path_obj, name, out_dir).await {
        DocOutcome::Text {
            text,
            images,
            notes,
            unshown,
            all_page_text_lost,
            page_text,
        } => {
            // The IMAGE pipeline runs before the annotations are composed, because whether an
            // image was delivered decides how the no-text sentence reads.
            let delivered =
                deliver_document_images(name, &images, uploads_dir, staging_dirs, batch).await;
            // "The content was provided as images" is only true when every picture the reading
            // produced was delivered.
            let images_complete = delivered.kept > 0 && delivered.left_out == 0;
            // The reader failed on every page, so the pages carry no text: the notes below name
            // them and the "no text could be extracted" sentence — which would report a reader
            // failure as an absence — is left out. Anything else the conversion read (a comment,
            // a filled field value) is content and is delivered regardless.
            if !all_page_text_lost || !text.trim().is_empty() {
                batch.annotate(
                    extracted_text_annotation(uploads_dir, name, &text, images_complete).await,
                );
            }
            // The report of what the reading did not show leads the notes, as in the read tool's
            // answer: a kind and its count ahead of the detail of each loss.
            for line in unshown.lines() {
                batch.annotate(format!("[File {name}: {line}]"));
            }
            for note in notes {
                batch.annotate(format!("[File {name}: {note}]"));
            }
            // A description, annotation or form list can carry the text while no page produced
            // any: the reading still says so, naming an image only when one was delivered.
            if !page_text && !all_page_text_lost && !text.trim().is_empty() {
                let note = crate::document::no_text_note(images_complete);
                batch.annotate(format!("[File {name}: {note}]"));
            }
        }
        DocOutcome::Unreadable { reason } => {
            batch.annotate(format!("[File {name}: {reason}]"));
        }
        DocOutcome::Unsupported => {
            // The copy is what the agent would open, so claim it is openable only when it landed
            // in the workspace.
            let saved = if copied_to_workspace {
                " — open the saved file directly"
            } else {
                ""
            };
            batch.annotate(format!(
                "[File {name}: received but not converted (unsupported format){saved}]"
            ));
        }
    }
    Some(replacement)
}

/// Delivered through the ordinary IMAGE pipeline: a native data-URI part plus a workspace copy,
/// so the model sees them and the agent can reopen them. Only the pictures the shared limit
/// allows are delivered; the ones it left out and the ones the pipeline rejected are each
/// counted into one note, like the converter's skipped-media note. The batch effects are
/// applied here.
struct DeliveredImages {
    /// How many images the model actually received.
    kept: usize,
    /// How many pictures the document held beyond the limit.
    left_out: usize,
}

async fn deliver_document_images(
    name: &str,
    images: &[std::path::PathBuf],
    uploads_dir: &std::path::Path,
    staging_dirs: &[String],
    batch: &mut EnrichmentBatch,
) -> DeliveredImages {
    let (pictures, left_out) = crate::document::attachable_pictures(images);
    let mut delivered = DeliveredImages { kept: 0, left_out };
    let mut unreadable = 0usize;
    for image in pictures {
        let image_path = image.to_string_lossy().to_string();
        match handle_image(&image_path, image, Some(uploads_dir), staging_dirs).await {
            ImageAction::Keep => delivered.kept += 1,
            ImageAction::Invalid { delete_temp } => {
                // A temp artifact written by this pass, so the note must not name it — the file
                // is deleted right below.
                unreadable += 1;
                if delete_temp {
                    batch.files_to_delete.push(image.clone());
                }
            }
            ImageAction::Replace {
                replacement,
                upload_annotation,
                delete_temp,
            } => {
                delivered.kept += 1;
                batch.appended_markers.push(replacement);
                if let Some(annotation) = upload_annotation {
                    batch.upload_annotations.push(annotation);
                }
                if delete_temp {
                    batch.files_to_delete.push(image.clone());
                }
            }
        }
    }
    if left_out > 0 {
        // Never delivered, so their only copy is this pass's own temp artifact: consumed here
        // rather than left for the OS temp sweep.
        batch
            .files_to_delete
            .extend(images[pictures.len()..].iter().cloned());
        batch.annotate(format!(
            "[File {name}: {}]",
            crate::document::left_out_pictures_note(images.len(), left_out)
        ));
    }
    if unreadable > 0 {
        batch.annotate(format!(
            "[File {name}: {unreadable} extracted image(s) could not be read]"
        ));
    }
    delivered
}

/// Short text is inlined; longer text is spilled to `<uploads>/<stem>.extracted.txt` and the
/// annotation points at that file, so a book-sized document cannot blow up the message. Empty
/// text (a scanned, image-only document) names the delivered images instead — only when the
/// read delivered all of them, never when the picture limit left some out.
async fn extracted_text_annotation(
    uploads_dir: &std::path::Path,
    name: &str,
    text: &str,
    images_complete: bool,
) -> String {
    let text = text.trim();
    if text.is_empty() {
        return format!(
            "[File {name}: {}]",
            crate::document::no_text_note(images_complete)
        );
    }
    let char_count = text.chars().count();
    if char_count <= INLINE_TEXT_MAX_CHARS {
        return format!("[File {name}: extracted text follows]\n\n{text}");
    }
    let spill_name = format!("{}.extracted.txt", crate::util::name_stem(name));
    let spilled = crate::util::write_unique_file(uploads_dir, &spill_name, text.as_bytes()).await;
    let spill = match spilled {
        Ok(path) => path,
        Err(e) => {
            tracing::warn!(
                dir = %uploads_dir.display(),
                error = %e,
                "Failed to save the extracted document text"
            );
            return format!(
                "[File {name}: the extracted text could not be saved to the workspace]"
            );
        }
    };
    format!(
        "[File {name}: {}]",
        crate::document::spilled_text_note(char_count, &spill)
    )
}

/// One line the enriched message carries ahead of its body.
struct Annotation {
    /// What the model reads: a clip's timeline carries its pictures as ordinary `[IMAGE:]`
    /// markers, and a recording's transcript carries the path it was saved at.
    model: String,
    /// What the owner's own bubble shows instead, when it differs — the same line without the
    /// pictures, or without the saved path. Usually it does not, and then nothing is kept for it.
    display: Option<String>,
}

impl Annotation {
    /// One line both forms read the same.
    fn shared(text: String) -> Self {
        Self {
            model: text,
            display: None,
        }
    }

    fn model(&self) -> &str {
        &self.model
    }

    fn display(&self) -> &str {
        self.display.as_deref().unwrap_or(&self.model)
    }
}

/// Accumulators shared by the per-kind marker handlers in [`enrich_message`]: what the finished
/// message gets prepended/appended, and which temp artifacts the pass consumed.
#[derive(Default)]
struct EnrichmentBatch {
    /// Annotation blocks prepended to the finished message.
    annotations: Vec<Annotation>,
    /// `[Saved ...]` upload annotations appended to the body.
    upload_annotations: Vec<String>,
    /// `[IMAGE:data:...]` parts a FILE ingestion extracted, appended after the marker loop
    /// (`captures_iter` already snapshotted the source, so the loop never visits them).
    appended_markers: Vec<String>,
    /// Only ever queued for this message's own inbound attachments, so user-typed markers can
    /// never delete arbitrary local files. The staging directories go afterwards.
    files_to_delete: Vec<std::path::PathBuf>,
}

impl EnrichmentBatch {
    /// One line both forms share.
    fn annotate(&mut self, text: String) {
        self.annotations.push(Annotation::shared(text));
    }

    /// Delete the queued artifacts and the message's staging directories, then assemble the
    /// enriched content: append the native parts, strip the handled markers, prepend the
    /// annotations. Both forms are returned — the model's, then the owner's bubble's when an
    /// annotation differs between them.
    async fn finish(self, mut body: String, staging_dirs: &[String]) -> (String, Option<String>) {
        // Deletion errors are logged; a file already gone is not an error.
        for file_path in &self.files_to_delete {
            if let Err(e) = tokio::fs::remove_file(file_path).await
                && e.kind() != std::io::ErrorKind::NotFound
            {
                tracing::warn!(
                    path = %file_path.display(),
                    error = %e,
                    "Failed to delete temp file after enrichment"
                );
            }
        }

        // `remove_dir` removes only an empty directory, so a staging directory still holding an
        // unconsumed artifact is left to the OS temp sweep; an already-gone directory is not an
        // error.
        let root = crate::util::telegram_files_root();
        for staging_dir in staging_dirs {
            if !is_staging_dir_name(staging_dir) {
                continue;
            }
            let _ = tokio::fs::remove_dir(root.join(staging_dir)).await;
        }

        // Upload path annotations, preceded by the `[IMAGE:data:...]` parts a document produced.
        if !self.appended_markers.is_empty() {
            let _ = write!(body, "\n\n{}", self.appended_markers.join("\n"));
        }
        if !self.upload_annotations.is_empty() {
            let annotation_block = self.upload_annotations.join("\n");
            let _ = write!(body, "\n\n{annotation_block}");
        }

        // Strip only the kinds this pass consumed (AUDIO, VIDEO): IMAGE carries the native parts
        // the model consumes, FILE the workspace handle the agent opens itself.
        let cleaned = MEDIA_MARKER_RE
            .replace_all(&body, |caps: &regex::Captures| {
                if matches!(
                    parse_media_marker(caps).0,
                    MediaMarkerKind::Audio | MediaMarkerKind::Video
                ) {
                    String::new()
                } else {
                    caps.get_match().as_str().to_string()
                }
            })
            .to_string();
        let cleaned = cleaned.trim().to_string();

        // Prepend the accumulated text descriptions: an AUDIO transcript and saved location, VIDEO
        // annotations and a FILE's extracted text. Prepending rather than inlining at the marker
        // keeps marker-shaped text inside a document away from the strip pass above. The owner's
        // form is built only when an annotation differs from it — for a clip's timeline pictures,
        // or a recording's saved location.
        let content = composed(&self.annotations, &cleaned, Annotation::model);
        let display = self
            .annotations
            .iter()
            .any(|annotation| annotation.display.is_some())
            .then(|| composed(&self.annotations, &cleaned, Annotation::display));
        (content, display)
    }
}

/// The message as one form reads it: the annotations, then the body.
fn composed(annotations: &[Annotation], body: &str, pick: fn(&Annotation) -> &str) -> String {
    let prefix = annotations.iter().map(pick).collect::<Vec<_>>().join("\n");
    match (prefix.is_empty(), body.is_empty()) {
        (true, _) => body.to_string(),
        (false, true) => prefix,
        (false, false) => format!("{prefix}\n\n{body}"),
    }
}

/// Process every media marker (`[IMAGE:...]`, `[AUDIO:...]`, `[VIDEO:...]`, `[FILE:...]`) in a
/// single pass:
///
/// | Kind | Behavior |
/// |------|----------|
/// | IMAGE | data URI (original bytes, bounded-JPEG re-encode over the cap only) + in-scope copy |
/// | AUDIO | workspace copy + `[Saved audio: path]` beside the transcript, or alone |
/// | VIDEO | workspace copy + `[Saved video: path]` + the clip's timeline |
/// | FILE | workspace copy + extracted text and images; verbatim when out of scope |
///
/// The kinds this pass consumed (AUDIO, VIDEO) are then stripped and the annotations prepended;
/// IMAGE (native parts) and FILE (workspace handle) are preserved. Temp files are cleaned up
/// within this message's own directories. `workspace_path` is the workspace whose `uploads/`
/// receives saved media copies; `None` disables copies.
// Marker dispatch hub: per-kind handling lives in the handlers above, keeping this loop flat.
pub async fn enrich_message(msg: &mut ChannelMessage, workspace_path: Option<&std::path::Path>) {
    let mut batch = EnrichmentBatch::default();
    let mut result = msg.content.clone();
    let uploads_dir = workspace_path.map(|p| p.join("uploads"));
    // The staging directories this message's producer created: the Telegram receive path or the
    // desktop composer. Empty when it has no attachment.
    let staging_dirs = msg.attachment_dirs.clone();
    // Automatic processing stops at the carrying transport's bound for the conversions that read
    // the whole file into memory — a document, or a recording, whatever its codec.
    // Only the Telegram side has one: a file above the cloud's download limit can only have come
    // through the local Bot API server, and receiving it means keeping it.
    let processing_bound = (msg.channel == "telegram")
        .then_some(crate::channels::telegram::TELEGRAM_MAX_FILE_DOWNLOAD_BYTES);

    for caps in MEDIA_MARKER_RE.captures_iter(&msg.content) {
        let whole = caps.get_match();
        let (kind, path) = parse_media_marker(&caps);
        let path_obj = std::path::Path::new(path);

        match kind {
            MediaMarkerKind::File => {
                // `None` = an out-of-scope user-typed marker, left verbatim.
                if let Some(replacement) = handle_file(
                    path,
                    path_obj,
                    uploads_dir.as_deref(),
                    &staging_dirs,
                    processing_bound,
                    &mut batch,
                )
                .await
                {
                    result = result.replacen(whole.as_str(), &replacement, 1);
                }
            }
            MediaMarkerKind::Image => {
                let action =
                    handle_image(path, path_obj, uploads_dir.as_deref(), &staging_dirs).await;
                let delete_temp = action.delete_temp();
                match action {
                    ImageAction::Keep => {
                        // HTTP/HTTPS URL — no local file to clean up.
                    }
                    ImageAction::Invalid { .. } => {
                        // Not a decodable raster: name the failed reference.
                        let replacement = format!("[Invalid image reference: {path}]");
                        result = result.replacen(whole.as_str(), &replacement, 1);
                    }
                    ImageAction::Replace {
                        replacement,
                        upload_annotation,
                        ..
                    } => {
                        result = result.replacen(whole.as_str(), &replacement, 1);
                        if let Some(ann) = upload_annotation {
                            batch.upload_annotations.push(ann);
                        }
                    }
                }
                // Local IMAGE temp files are cleaned up only when consumed from this message's
                // inbound attachments (`delete_temp`).
                if delete_temp {
                    batch.files_to_delete.push(path_obj.to_path_buf());
                }
            }
            MediaMarkerKind::Audio => {
                // Containment applies: only this message's own inbound attachment is saved,
                // transcribed or deleted; an out-of-scope marker degrades to the icon only.
                let (annotation, delete_temp) = handle_audio(
                    path,
                    path_obj,
                    uploads_dir.as_deref(),
                    &staging_dirs,
                    processing_bound,
                )
                .await;
                batch.annotations.push(annotation);
                if delete_temp {
                    batch.files_to_delete.push(path_obj.to_path_buf());
                }
            }
            MediaMarkerKind::Video => {
                let VideoAction {
                    replacement,
                    delete_temp,
                    timeline,
                } = handle_video(path, path_obj, uploads_dir.as_deref(), &staging_dirs).await;
                result = result.replacen(whole.as_str(), &replacement, 1);
                if let Some(timeline) = timeline {
                    batch.annotations.push(timeline);
                }
                if delete_temp {
                    batch.files_to_delete.push(path_obj.to_path_buf());
                }
            }
        }
    }

    let (content, display) = batch.finish(result, &staging_dirs).await;
    msg.display_content = display;
    msg.content = content;
}

/// A marker naming a path under the daemon's Telegram temp root.
///
/// [`crate::channels::persist_content`] uses it to decide what reaches chat history: those
/// markers name the staging files a message arrived in — paths that are never what the enriched
/// form refers to (a kept copy is named by its own `[Saved …]` line) — so the enriched content is
/// persisted instead. Purely syntactic, and deliberately looser than
/// [`is_inbound_attachment`]: a hand-typed marker naming that root also qualifies, which is
/// safe because this only decides which text is replaced — it never reads, copies or deletes.
#[must_use]
pub(crate) fn has_inbound_temp_marker(content: &str) -> bool {
    let root = crate::util::telegram_files_root();
    MEDIA_MARKER_RE.captures_iter(content).any(|caps| {
        let (_, path) = parse_media_marker(&caps);
        std::path::Path::new(path).starts_with(&root)
    })
}

fn extract_urls(text: &str) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut result = Vec::new();
    for m in URL_RE.find_iter(text) {
        let mut url = m.as_str().to_string();
        while url.ends_with(&[',', '.', ')', ']', '}', ':', ';', '!', '?'][..]) {
            url.pop();
        }
        if seen.insert(url.clone()) {
            result.push(url);
        }
    }
    result
}

/// Prepends link summaries for any URLs found in the text; with none, the message is returned
/// unchanged. Links are fetched concurrently through the shared `ChromeTool` — each URL gets
/// its own isolated session tab, closed after text extraction.
pub async fn enrich_links(content: &str) -> Cow<'_, str> {
    // The cap is in bytes: it is the only bound on page text reaching the model, so it must not
    // grow with a page's character count.
    const MAX_TEXT_BYTES: usize = 5000;
    let urls = extract_urls(content);
    if urls.is_empty() {
        return Cow::Borrowed(content);
    }

    // Gate on the cached (non-probing) daemon advertisement first — the in-memory check
    // short-circuits the `--version` spawn while the daemon is confirmed down. A stale state
    // passes optimistically and the fetch tasks re-discover liveness under the probe timeout.
    if !(crate::tools::chrome_daemon::is_advertised()
        && matches!(
            crate::tools::chrome_daemon::cli_probe().await,
            crate::tools::chrome_daemon::CliStatus::Available
        ))
    {
        tracing::debug!("chrome-use not available, skipping link enrichment");
        return Cow::Borrowed(content);
    }

    let chrome = std::sync::Arc::new(ChromeTool::default());
    let mut tasks = Vec::with_capacity(urls.len());
    for url in &urls {
        let url = url.clone();
        let tab = format!(
            "link-enricher-{}",
            LINK_ENRICHER_SEQ.fetch_add(1, Ordering::Relaxed)
        );
        let chrome = std::sync::Arc::clone(&chrome);
        tasks.push(tokio::spawn(async move {
            let result = chrome.fetch_page_text(&url, &tab).await;
            // Close the tab (best-effort) whatever the fetch outcome.
            chrome.close_session(&tab).await;
            (url, result)
        }));
    }

    let mut enrichments: Vec<String> = Vec::new();
    for task in tasks {
        match task.await {
            Ok((url, Ok(body_text))) => {
                if body_text.trim().is_empty() {
                    // A blank page inserts no empty snippet.
                    tracing::debug!(url, "Link enricher: page text is empty, skipping snippet");
                    continue;
                }
                let snippet = crate::util::cut_bytes(&body_text, MAX_TEXT_BYTES);
                enrichments.push(format!("📄 [{url}]\n{snippet}"));
            }
            Ok((url, Err(e))) => {
                tracing::debug!(url, error = %e, "Link enricher: failed to fetch page text");
            }
            Err(e) => {
                tracing::debug!("Link enricher task panicked: {e}");
            }
        }
    }

    if enrichments.is_empty() {
        return Cow::Borrowed(content);
    }

    let prefix = enrichments.join("\n\n");
    Cow::Owned(format!("{prefix}\n\n{content}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine as _;
    use base64::engine::general_purpose::STANDARD;

    /// Both schemes count, a repeat is one URL, and the punctuation or brackets around an
    /// address are not part of it.
    #[test]
    fn extract_urls_applies_its_rules() {
        let cases: &[(&str, &[&str])] = &[
            (
                "Check https://example.com and http://test.org/page for info",
                &["https://example.com", "http://test.org/page"],
            ),
            (
                "Visit https://example.com and https://example.com again",
                &["https://example.com"],
            ),
            (
                "See https://example.com, and https://test.org.",
                &["https://example.com", "https://test.org"],
            ),
            (
                "(https://example.com) and [https://test.org]",
                &["https://example.com", "https://test.org"],
            ),
        ];
        for (input, expected) in cases {
            assert_eq!(extract_urls(input), *expected, "input: {input}");
        }
    }

    /// The chat id every inbound fixture belongs to: the test messages carry it and the fixture
    /// directories are named after it.
    const TEST_CHAT_ID: &str = "1";

    /// Carries [`TEST_CHAT_ID`] but no message id, so it owns no inbound attachment — containment
    /// is per message, and any inbound fixture is out of scope for it.
    fn test_msg(content: &str) -> ChannelMessage {
        ChannelMessage {
            user_name: "test".into(),
            reply_target: "test".into(),
            content: content.to_string(),
            display_content: None,
            channel: "test".into(),
            workspace: "test".into(),
            optimistic_id: None,
            callback_query_id: None,
            reply_reference: None,
            chat_id: Some(TEST_CHAT_ID.into()),
            message_id: None,
            attachment_dirs: Vec::new(),
            parts: Vec::new(),
            update_date: None,
            forwarded: false,
            update_ids: Vec::new(),
            dictated: false,
            urgent: false,
        }
    }

    /// Owning the staging directories of `message_ids` — one for a single message, several for
    /// the album shape. `message_id` stays the first, as an album merge keeps the first.
    fn inbound_album_msg(message_ids: &[i64], content: &str) -> ChannelMessage {
        ChannelMessage {
            message_id: message_ids.first().copied(),
            attachment_dirs: message_ids
                .iter()
                .map(|id| crate::util::telegram_staging_dir_name(TEST_CHAT_ID, *id))
                .collect(),
            ..test_msg(content)
        }
    }

    fn inbound_msg(message_id: i64, content: &str) -> ChannelMessage {
        inbound_album_msg(&[message_id], content)
    }

    fn telegram_root() -> std::path::PathBuf {
        crate::util::telegram_files_root()
    }

    /// Create the daemon's Telegram temp dir. The containment root must exist before path
    /// canonicalization — a missing root makes every path look out of scope.
    async fn ensure_telegram_files_dir() {
        tokio::fs::create_dir_all(telegram_root()).await.unwrap();
    }

    /// A unique scratch dir under the system temp dir (outside the Telegram temp dir) with a fake
    /// workspace and one arbitrary media file. Returns `(tmp_root, ws_path, arbitrary_file)`.
    async fn out_of_scope_fixture(
        prefix: &str,
        file_name: &str,
        contents: &[u8],
    ) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
        ensure_telegram_files_dir().await;
        let tmp_root = crate::util::test::test_root().join(prefix);
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();
        let arbitrary = tmp_root.join(file_name);
        tokio::fs::write(&arbitrary, contents).await.unwrap();
        (tmp_root, ws_path, arbitrary)
    }

    /// Exactly as the receive path delivers one: the file inside its own staging subdirectory of
    /// the Telegram temp root. Each test uses its own message id, which is what the per-message
    /// containment compares against. Returns `(msg_dir, attachment)`.
    async fn telegram_attachment_fixture(
        chat_id: &str,
        message_id: i64,
        file_name: &str,
        bytes: &[u8],
    ) -> (std::path::PathBuf, std::path::PathBuf) {
        ensure_telegram_files_dir().await;
        let msg_dir =
            telegram_root().join(crate::util::telegram_staging_dir_name(chat_id, message_id));
        tokio::fs::create_dir_all(&msg_dir).await.unwrap();
        let attachment = msg_dir.join(file_name);
        tokio::fs::write(&attachment, bytes).await.unwrap();
        (msg_dir, attachment)
    }

    /// An inbound attachment of [`TEST_CHAT_ID`]: in scope for [`inbound_msg`] with the same
    /// message id.
    async fn inbound_attachment_fixture(
        message_id: i64,
        file_name: &str,
        bytes: &[u8],
    ) -> (std::path::PathBuf, std::path::PathBuf) {
        telegram_attachment_fixture(TEST_CHAT_ID, message_id, file_name, bytes).await
    }

    /// Set up an inbound attachment of [`TEST_CHAT_ID`] plus a workspace to ingest it into. Returns
    /// `(tmp_root, ws_path, msg_dir, attachment)`.
    async fn inbound_ingest_fixture(
        prefix: &str,
        message_id: i64,
        file_name: &str,
        bytes: &[u8],
    ) -> (
        std::path::PathBuf,
        std::path::PathBuf,
        std::path::PathBuf,
        std::path::PathBuf,
    ) {
        let tmp_root = crate::util::test::test_root().join(prefix);
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();
        let (msg_dir, attachment) = inbound_attachment_fixture(message_id, file_name, bytes).await;
        (tmp_root, ws_path, msg_dir, attachment)
    }

    /// Generate a real decodable PNG of the given dimensions (solid gradient).
    fn real_png(w: u32, h: u32) -> Vec<u8> {
        let img = image::RgbImage::from_fn(w, h, |x, y| {
            image::Rgb([
                u8::try_from(x % 256).expect("x % 256 fits in u8"),
                u8::try_from(y % 256).expect("y % 256 fits in u8"),
                128,
            ])
        });
        let mut bytes = Vec::new();
        image::DynamicImage::ImageRgb8(img)
            .write_to(
                &mut std::io::Cursor::new(&mut bytes),
                image::ImageFormat::Png,
            )
            .expect("fixture PNG must encode");
        bytes
    }

    #[tokio::test]
    async fn enrich_image_http_url_passthrough() {
        let mut msg = test_msg("Check this [IMAGE:https://example.com/img.png] out");
        enrich_message(&mut msg, None).await;
        assert_eq!(
            msg.content,
            "Check this [IMAGE:https://example.com/img.png] out"
        );
    }

    /// A user-typed marker is out of scope, so it degrades to the icon combo (no engine in tests).
    #[tokio::test]
    async fn enrich_audio_annotation_and_strip() {
        let mut msg = test_msg("Listen [AUDIO:/tmp/audio_xyz.mp3] to this");
        enrich_message(&mut msg, None).await;
        assert!(
            msg.content.contains(AUDIO_ICON),
            "Audio annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[AUDIO:"),
            "AUDIO marker must be stripped"
        );
        assert!(
            !msg.content.contains("audio_xyz"),
            "Audio temp file name must not appear, got: {}",
            msg.content
        );
        assert!(msg.content.contains("Listen"), "Original text preserved");
        assert!(msg.content.contains("to this"), "Original text preserved");
    }

    /// Read into a data URI of the source bytes exactly, with the temp file and its per-message
    /// directory going with the read.
    #[tokio::test]
    async fn enrich_image_valid_file_converts_to_data_uri_and_deletes_temp() {
        // The fixture must be one of this message's inbound attachments to be in scope.
        let source_bytes = real_png(2, 1);
        let (msg_dir, tmp) = inbound_attachment_fixture(7001, "photo.png", &source_bytes).await;
        let path_str = tmp.to_string_lossy().to_string();

        let mut msg = inbound_msg(7001, &format!("Image: [IMAGE:{path_str}]"));
        enrich_message(&mut msg, None).await;

        assert!(
            msg.content.contains("[IMAGE:data:image/png;base64,"),
            "Expected data URI, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains(&path_str),
            "Raw file path must not remain in content"
        );
        assert!(
            !tmp.exists(),
            "Temp image file must be deleted after enrichment"
        );
        assert!(!msg_dir.exists(), "Per-message directory must be deleted");

        // The data URI carries the source bytes untouched, at any size.
        let source_bytes = real_png(64, 48);
        let (_msg_dir, tmp) = inbound_attachment_fixture(7006, "art.png", &source_bytes).await;
        let path_str = tmp.to_string_lossy().to_string();
        let mut msg = inbound_msg(7006, &format!("Art: [IMAGE:{path_str}]"));
        enrich_message(&mut msg, None).await;
        let expected = format!(
            "[IMAGE:data:image/png;base64,{}]",
            STANDARD.encode(&source_bytes)
        );
        assert!(
            msg.content.contains(&expected),
            "Image data URI must be byte-identical to the source, got: {}",
            msg.content
        );
        assert!(
            !tmp.exists(),
            "Temp image file must be deleted after enrichment"
        );
    }

    #[tokio::test]
    async fn enrich_image_with_workspace_creates_upload_annotation() {
        let tmp_root = crate::util::test::test_root().join("test_enrich_ws");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        let source_bytes = real_png(2, 1);
        let (_msg_dir, tmp_img) =
            inbound_attachment_fixture(7002, "photo.png", &source_bytes).await;
        let img_path_str = tmp_img.to_string_lossy().to_string();

        let mut msg = inbound_msg(7002, &format!("Image: [IMAGE:{img_path_str}]"));
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(msg.content.contains("[IMAGE:data:image/png;base64,"));
        assert!(
            msg.content.contains("[Saved image:"),
            "Upload annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !tmp_img.exists(),
            "Temp file must be deleted after enrichment"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    // The read reaches the process-global ffmpeg install (root and the failed-attempt latch), which
    // the install tests own: this one takes their key so the two cannot interleave.
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn enrich_video_with_workspace_copies_and_annotates() {
        let tmp_root = crate::util::test::test_root().join("test_enrich_video_ws");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        // Only this message's own inbound attachments are eligible for the copy.
        let mp4_header: &[u8] = &[
            0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6F, 0x6D, 0x00, 0x00,
            0x00, 0x00, 0x69, 0x73, 0x6F, 0x6D, 0x69, 0x73, 0x6F, 0x32,
        ];
        let (_msg_dir, tmp_video) = inbound_attachment_fixture(7003, "clip.mp4", mp4_header).await;
        let video_path_str = tmp_video.to_string_lossy().to_string();

        let mut msg = inbound_msg(7003, &format!("Edit this clip: [VIDEO:{video_path_str}]"));
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        // The annotation points at the workspace uploads copy, so the agent can feed it to the
        // video tool as the clip to edit.
        assert!(
            msg.content.contains("[Saved video:"),
            "Video upload annotation must be present, got: {}",
            msg.content
        );
        assert!(
            msg.content
                .contains(&ws_path.join("uploads").display().to_string()),
            "Annotation must point into workspace uploads, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[VIDEO:"),
            "VIDEO marker must be stripped"
        );
        // The fixture's bytes are a bare header, so the read cannot produce a timeline: it is the
        // distinguishable failure sentence instead. Which one depends on the machine — a managed
        // ffmpeg that is present reports the decode, one that is not reports itself — so only the
        // envelope is asserted.
        assert!(
            msg.content.contains("The clip could not be read: "),
            "Timeline failure must be annotated, got: {}",
            msg.content
        );
        // A failed timeline has no pictures, so the two forms are the same.
        assert!(msg.display_content.is_none());
        assert!(
            !tmp_video.exists(),
            "Temp video file must be deleted after enrichment"
        );
        let _ = tokio::fs::remove_file(&tmp_video).await;
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_image_outside_inbound_attachments_annotates_without_read_or_copy() {
        // An injected marker naming an arbitrary readable file must not be read into model
        // context, copied into uploads, or deleted.
        let (tmp_root, ws_path, arbitrary) = out_of_scope_fixture(
            "test_enrich_img_outside",
            "secret.png",
            b"top secret image bytes",
        )
        .await;
        let marker = format!("Look at [IMAGE:{}]", arbitrary.display());

        let mut msg = test_msg(&marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content.contains("[Image attached: secret.png]"),
            "Out-of-scope path must degrade to a plain-text annotation, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("data:image"),
            "No data URI may be produced for out-of-scope paths (would read the file)"
        );
        assert!(!msg.content.contains("[Saved image:"));
        assert!(!msg.content.contains("[IMAGE:"));
        assert!(
            arbitrary.exists(),
            "Source file outside the telegram temp dir must not be deleted"
        );
        assert_eq!(
            tokio::fs::read(&arbitrary).await.unwrap(),
            b"top secret image bytes",
            "Source file contents must be unchanged"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "No uploads copy may be created for out-of-scope paths"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_video_http_url_kept_as_plain_text() {
        let mut msg = test_msg("Edit [VIDEO:https://example.com/clip.mp4] this");
        enrich_message(&mut msg, None).await;
        assert!(
            msg.content
                .contains("[Video link: https://example.com/clip.mp4]"),
            "HTTP video URL must be kept as plain-text reference, got: {}",
            msg.content
        );
        assert!(!msg.content.contains("[VIDEO:"));
        assert!(
            !crate::util::MEDIA_MARKER_RE.is_match(&msg.content),
            "the product's own note must not read as a media marker: {}",
            msg.content
        );
    }

    #[tokio::test]
    async fn enrich_video_outside_inbound_attachments_annotates_without_copy_or_delete() {
        // An injected marker naming an arbitrary readable file must not be copied into uploads
        // (an exfiltration vector) or deleted.
        let (tmp_root, ws_path, arbitrary) = out_of_scope_fixture(
            "test_enrich_video_nonmm",
            "secret.mp4",
            b"top secret video bytes",
        )
        .await;
        let marker = format!("Watch [VIDEO:{}]", arbitrary.display());

        let mut msg = test_msg(&marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content.contains("[Video attached: secret.mp4]"),
            "Out-of-scope path must degrade to a plain-text annotation, got: {}",
            msg.content
        );
        assert!(!msg.content.contains("[VIDEO:"));
        assert!(
            arbitrary.exists(),
            "Source file outside the telegram temp dir must not be deleted"
        );
        assert_eq!(
            tokio::fs::read(&arbitrary).await.unwrap(),
            b"top secret video bytes",
            "Source file contents must be unchanged"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "No uploads copy may be created for out-of-scope paths"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// A file in this message's own inbound directory that is not a decodable raster must never
    /// fail open to a junk data URI: the classifier rejects a non-image with an image extension,
    /// and the primary encode refuses a PNG whose payload is truncated. Both degrade to an
    /// `[Invalid image reference: …]` note, and the in-scope temp file is cleaned up.
    #[tokio::test]
    async fn enrich_image_that_is_not_a_decodable_raster_never_fails_open_to_a_junk_data_uri() {
        let (_msg_dir, tmp) = inbound_attachment_fixture(7007, "photo.png", b"not an image").await;
        let path_str = tmp.to_string_lossy().to_string();
        let mut msg = inbound_msg(7007, &format!("Photo: [IMAGE:{path_str}]"));
        enrich_message(&mut msg, None).await;
        assert!(
            msg.content
                .contains(&format!("[Invalid image reference: {path_str}]")),
            "Non-raster in-scope file must degrade to an invalid reference, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[IMAGE:data:"),
            "No junk data URI may be produced for a non-raster file, got: {}",
            msg.content
        );
        assert!(
            !tmp.exists(),
            "In-scope non-raster temp file must be cleaned up"
        );

        // A truncated PNG: valid magic and IHDR, no decodable payload.
        let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
        let mut buf = Vec::new();
        img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();
        let truncated = &buf[..buf.len().min(24)];
        let (_msg_dir, tmp) = inbound_attachment_fixture(7008, "photo.png", truncated).await;
        let path_str = tmp.to_string_lossy().to_string();
        let mut msg = inbound_msg(7008, &format!("Photo: [IMAGE:{path_str}]"));
        enrich_message(&mut msg, None).await;
        assert!(
            msg.content
                .contains(&format!("[Invalid image reference: {path_str}]")),
            "Corrupt-but-magic-valid in-scope file must degrade to an invalid reference, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[IMAGE:data:"),
            "No junk data URI may be produced for a corrupt file, got: {}",
            msg.content
        );
        // Defensive cleanup in case an assertion above fails.
        let _ = tokio::fs::remove_file(&tmp).await;
    }

    /// A recording is kept in the workspace whatever the transcript does: here the bytes are not a
    /// container the recogniser reads, so there is no transcript at all and the file is still saved
    /// — the outcome the whole path exists for.
    #[tokio::test]
    async fn enrich_audio_saved_to_workspace_when_transcription_fails() {
        let tmp_root = crate::util::test::test_root().join("test_enrich_audio_ws");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        let bytes: &[u8] = b"fake audio content";
        let (msg_dir, tmp) = inbound_attachment_fixture(7010, "voice.oga", bytes).await;
        let path_str = tmp.to_string_lossy().to_string();

        let mut msg = inbound_msg(7010, &format!("Audio: [AUDIO:{path_str}]"));
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        // The copy keeps the recording's real container and its bytes, and is the only file left.
        let uploads = ws_path.join("uploads");
        let saved: Vec<_> = std::fs::read_dir(&uploads)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .collect();
        assert_eq!(saved.len(), 1, "exactly one saved recording: {saved:?}");
        assert_eq!(
            saved[0].extension().and_then(|e| e.to_str()),
            Some("oga"),
            "the saved file keeps its real container: {saved:?}"
        );
        assert_eq!(tokio::fs::read(&saved[0]).await.unwrap(), bytes);
        assert!(!tmp.exists(), "Temp file is deleted once the copy exists");
        assert!(!msg_dir.exists(), "Per-message directory must be deleted");

        // The model reads the icon (no transcript) with the saved location under it, and the temp
        // path the marker carried is gone; the owner's bubble shows the icon alone.
        assert_eq!(
            msg.content,
            format!(
                "{AUDIO_ICON}\n[Saved audio: {}]\n\nAudio:",
                saved[0].display()
            )
        );
        assert_eq!(msg.display_content, Some(format!("{AUDIO_ICON}\n\nAudio:")));

        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// With no workspace to save into, the temp file is NOT deleted: losing the recording is the one
    /// outcome this path must not produce.
    #[tokio::test]
    async fn enrich_audio_without_workspace_keeps_temp() {
        let (msg_dir, tmp) =
            inbound_attachment_fixture(7024, "voice.oga", b"fake audio content").await;
        let path_str = tmp.to_string_lossy().to_string();

        let mut msg = inbound_msg(7024, &format!("Audio: [AUDIO:{path_str}]"));
        enrich_message(&mut msg, None).await;

        assert!(
            tmp.exists(),
            "A recording is never deleted without a workspace copy"
        );
        assert_eq!(
            msg.content,
            format!("{AUDIO_ICON}\n\nAudio:"),
            "Nothing was saved, so nothing is named"
        );
        let _ = tokio::fs::remove_file(&tmp).await;
        let _ = tokio::fs::remove_dir_all(&msg_dir).await;
    }

    /// Another message's attachment is inert: not read, not copied, not deleted.
    #[tokio::test]
    async fn enrich_audio_other_message_attachment_left_inert() {
        let tmp_root = crate::util::test::test_root().join("test_enrich_audio_inert");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        // The fixture belongs to message 7025; the message carrying the marker is 7026.
        let (msg_dir, foreign) =
            inbound_attachment_fixture(7025, "voice.oga", b"someone else's recording").await;
        let mut msg = inbound_msg(7026, &format!("Audio: [AUDIO:{}]", foreign.display()));
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content.contains(AUDIO_ICON),
            "Out-of-scope audio degrades to the icon, got: {}",
            msg.content
        );
        assert!(!msg.content.contains("[Saved audio:"), "{}", msg.content);
        assert!(
            !ws_path.join("uploads").exists(),
            "Nothing may be copied into the workspace"
        );
        assert!(foreign.exists(), "Another message's file is never deleted");
        let _ = tokio::fs::remove_file(&foreign).await;
        let _ = tokio::fs::remove_dir_all(&msg_dir).await;
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// Above the automatic-processing bound the recording is saved and never read.
    #[tokio::test]
    async fn enrich_audio_above_processing_bound_is_saved_not_transcribed() {
        let tmp_root = crate::util::test::test_root().join("test_enrich_audio_large");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        // A sparse file: the size is what the bound reads, and no page is materialized by writing it.
        let (msg_dir, tmp) = inbound_attachment_fixture(7027, "song.mp3", b"").await;
        let oversized = crate::channels::telegram::TELEGRAM_MAX_FILE_DOWNLOAD_BYTES + 1;
        std::fs::OpenOptions::new()
            .write(true)
            .open(&tmp)
            .unwrap()
            .set_len(oversized)
            .unwrap();

        // The bound only exists on the Telegram receive path.
        let mut msg = inbound_msg(7027, &format!("Song: [AUDIO:{}]", tmp.display()));
        msg.channel = "telegram".into();
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        let uploads = ws_path.join("uploads");
        let saved: Vec<_> = std::fs::read_dir(&uploads)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .collect();
        assert_eq!(saved.len(), 1, "exactly one saved recording: {saved:?}");
        assert_eq!(
            std::fs::metadata(&saved[0]).unwrap().len(),
            oversized,
            "the whole file is kept"
        );
        assert!(!tmp.exists(), "Temp file is deleted once the copy exists");
        assert!(!msg_dir.exists(), "Per-message directory must be deleted");
        // Both forms are the saved location, as they always were for a recording kept this way —
        // the GUI labels it as a file row, so the bubble never shows the raw path.
        assert_eq!(
            msg.content,
            format!("[Saved audio: {}]\n\nSong:", saved[0].display())
        );
        assert_eq!(msg.display_content, None);

        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// The two forms of a saved recording, and of one that was never decoded at all.
    #[test]
    fn audio_annotation_keeps_the_location_for_the_model_alone() {
        let saved = SavedMedia {
            annotation: "[Saved audio: /ws/uploads/upload_1.oga]".to_string(),
            dest: std::path::PathBuf::from("/ws/uploads/upload_1.oga"),
        };
        let transcript = Some(marked_transcript("hello there"));

        // The words, then the location for the model; the bubble keeps the words alone.
        let annotation = audio_annotation(Some(&saved), transcript.clone(), false);
        assert_eq!(
            annotation.model(),
            "🔊✍️ hello there\n[Saved audio: /ws/uploads/upload_1.oga]"
        );
        assert_eq!(annotation.display(), "🔊✍️ hello there");

        // Saved with no transcript: the icon still opens the model's form, as it always has, and
        // the bubble shows the icon rather than a path.
        let annotation = audio_annotation(Some(&saved), None, false);
        assert_eq!(
            annotation.model(),
            "🔊✍️\n[Saved audio: /ws/uploads/upload_1.oga]"
        );
        assert_eq!(annotation.display(), AUDIO_ICON);

        // Above the bound the recording was never read, so both forms are the saved location — what
        // the message carried before the recording was kept at all.
        let annotation = audio_annotation(Some(&saved), None, true);
        assert_eq!(
            annotation.model(),
            "[Saved audio: /ws/uploads/upload_1.oga]"
        );
        assert_eq!(
            annotation.display(),
            "[Saved audio: /ws/uploads/upload_1.oga]"
        );

        // No copy: one line both forms read the same, the transcript or the icon.
        let annotation = audio_annotation(None, transcript, false);
        assert_eq!(annotation.model(), "🔊✍️ hello there");
        assert_eq!(annotation.display(), "🔊✍️ hello there");
        let annotation = audio_annotation(None, None, false);
        assert_eq!(annotation.display(), AUDIO_ICON);
    }

    #[tokio::test]
    async fn enrich_file_inlines_text_and_copies_to_uploads() {
        let document = "# Title\n\nHello from a document";
        let (tmp_root, ws_path, msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_file_md", 7011, "notes.md", document.as_bytes())
                .await;
        let marker = format!("Read [FILE:{}] please", attachment.display());

        let mut msg = inbound_msg(7011, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        let copy = ws_path.join("uploads").join("notes.md");
        assert!(
            msg.content.contains(&format!("[FILE:{}]", copy.display())),
            "Marker must point at the workspace copy, got: {}",
            msg.content
        );
        assert!(
            msg.content.contains("Hello from a document"),
            "Extracted document text must be inline, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains(&attachment.display().to_string()),
            "The temp path must not survive anywhere, got: {}",
            msg.content
        );
        assert_eq!(
            tokio::fs::read(&copy).await.unwrap(),
            document.as_bytes(),
            "Workspace copy must be byte-identical to the inbound file"
        );
        assert!(!attachment.exists(), "Inbound temp file must be deleted");
        assert!(
            !msg_dir.exists(),
            "Inbound per-message directory must be deleted"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// A document the reader failed on for every page it could read, yet which
    /// still produced text: the attachment path must deliver that text. Dropping
    /// it because the reader failed is exactly the loss this covers.
    #[tokio::test]
    async fn enrich_file_keeps_text_of_pages_that_fail_after_producing_it() {
        let (tmp_root, ws_path, _msg_dir, attachment) = inbound_ingest_fixture(
            "test_enrich_file_partial_pdf",
            7015,
            "report.pdf",
            &crate::document::test_fixtures::pdf_with_all_pages_failing_midway(),
        )
        .await;
        let marker = format!("Read [FILE:{}] please", attachment.display());

        let mut msg = inbound_msg(7015, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert_eq!(
            msg.content.matches("Kept page text long enough").count(),
            2,
            "every page's text must be inline, got: {}",
            msg.content
        );
        assert!(
            msg.content.contains(
                "[File report.pdf: the text of pages 1, 2 could not be read in full (2 of 2 pages)]"
            ),
            "the pages must be named in a delimited note, got: {}",
            msg.content
        );
        assert_eq!(
            msg.content
                .matches("[IMAGE:data:image/jpeg;base64,")
                .count(),
            2,
            "each page that could not be read in full comes back as an image, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains(crate::document::NO_TEXT_NOTE),
            "delivered text must never be reported as a document without one, got: {}",
            msg.content
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// A document the reading found things in but did not show: the attachment
    /// path names the kinds in the same words the read tool's answer does, so an
    /// agent knows what it is working without whichever way the file arrived.
    #[tokio::test]
    async fn enrich_file_names_what_the_reading_did_not_show() {
        use crate::ooxml::test_fixtures::{DOCX_BODY, zip_fixture};
        let package = zip_fixture(&[
            ("word/document.xml", DOCX_BODY),
            ("word/media/clip.mp4", b"not a picture at all"),
        ]);
        let (tmp_root, ws_path, _msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_document_report", 7040, "clip.docx", &package)
                .await;
        let marker = format!("Read [FILE:{}] please", attachment.display());

        let mut msg = inbound_msg(7040, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content
                .contains("[File clip.docx: 1 embedded video(s) not shown]"),
            "the report must reach the inbound answer too, got: {}",
            msg.content
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// A document holding more pictures than one read may attach: the attachment
    /// path delivers the first six and says how many the document holds and how
    /// many the limit left out — the same count the read tool's answer carries —
    /// and never claims a partial delivery was its whole content provided as
    /// images.
    #[tokio::test]
    async fn enrich_file_delivers_at_most_six_document_pictures() {
        use crate::ooxml::test_fixtures::zip_fixture;
        const EMPTY_BODY: &[u8] = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body></w:body></w:document>"#;
        let png = crate::util::test::noisy_png(16, 16);
        let names: Vec<String> = (1..=7)
            .map(|page| format!("word/media/page_{page}.png"))
            .collect();
        let mut entries: Vec<(&str, &[u8])> = vec![("word/document.xml", EMPTY_BODY)];
        entries.extend(names.iter().map(|name| (name.as_str(), png.as_slice())));
        let package = zip_fixture(&entries);
        let (tmp_root, ws_path, msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_document_pictures", 7041, "scan.docx", &package)
                .await;
        let marker = format!("Read [FILE:{}] please", attachment.display());

        let mut msg = inbound_msg(7041, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert_eq!(
            msg.content.matches("[IMAGE:data:image/png;base64,").count(),
            6,
            "one read attaches at most six pictures, got: {}",
            msg.content
        );
        assert!(
            msg.content.contains(
                "[File scan.docx: 7 pictures in the document; 1 left out by the 6-picture \
                 limit]"
            ),
            "the answer must count what it left out, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains(crate::document::NO_TEXT_LAYER_NOTE),
            "a partial delivery is not its whole content provided as images, got: {}",
            msg.content
        );
        // The pictures left out are this pass's own artifacts: consumed, so nothing lingers
        // beside the (deleted) attachment.
        assert!(
            !msg_dir.exists(),
            "the per-message directory must be emptied and deleted"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// A one-page PDF whose page has no `/MediaBox` — the shape the text reader
    /// panics on, so every page's text is lost — but which carries a highlight
    /// with a Russian comment and author, and one filled form field whose widget
    /// is on that page.
    fn pdf_marks_with_every_page_text_lost() -> Vec<u8> {
        use crate::document::test_fixtures::{PdfFixture, one_page_pdf, pdf_text_string};
        const CONTENT: &[u8] = b"0.1 0.5 0.9 rg 0 0 612 792 re f";
        let mut fixture = PdfFixture::new();
        let highlight = fixture.push(format!(
            "<< /Subtype /Highlight /T {} /Contents {} >>",
            pdf_text_string("Иван Петров"),
            pdf_text_string("проверьте третью фигуру")
        ));
        let field = fixture.push(format!(
            "<< /Subtype /Widget /FT /Tx /T (Name) /V {} /Rect [0 0 0 0] >>",
            pdf_text_string("Иван Петров")
        ));
        let acroform = fixture.push(format!("<< /Fields [{field}] >>"));
        // No `/MediaBox` in the page dictionary: the reader panics on this page.
        one_page_pdf(
            fixture,
            CONTENT,
            &format!("/Annots [{highlight} {field}]"),
            &format!(" /AcroForm {acroform}"),
        )
    }

    /// Every page's text lost, yet the document carries marks: the marks are
    /// content, so the attachment path must deliver them — dropping the only
    /// text the document has is exactly the loss this covers — while the page
    /// itself still comes back as an image.
    #[tokio::test]
    async fn enrich_file_delivers_marks_when_every_page_text_was_lost() {
        let (tmp_root, ws_path, _msg_dir, attachment) = inbound_ingest_fixture(
            "test_enrich_file_marks_only_pdf",
            7023,
            "marked.pdf",
            &pdf_marks_with_every_page_text_lost(),
        )
        .await;
        let marker = format!("Read [FILE:{}] please", attachment.display());

        let mut msg = inbound_msg(7023, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content
                .contains("highlight (Иван Петров) on page 1:\n  проверьте третью фигуру"),
            "the annotation must survive the lost page text, got: {}",
            msg.content
        );
        assert!(
            msg.content.contains("Name (text) on page 1: Иван Петров"),
            "the filled field must survive the lost page text, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains(crate::document::NO_TEXT_NOTE),
            "delivered marks are text, not a document without one, got: {}",
            msg.content
        );
        assert_eq!(
            msg.content
                .matches("[IMAGE:data:image/jpeg;base64,")
                .count(),
            1,
            "the page whose text was lost still comes back as an image, got: {}",
            msg.content
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_long_text_spills_to_extracted_sidecar() {
        let text = "Lorem ipsum dolor sit amet. ".repeat(300);
        assert!(text.chars().count() > INLINE_TEXT_MAX_CHARS);
        let (tmp_root, ws_path, _msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_file_long", 7012, "long.txt", text.as_bytes())
                .await;
        let marker = format!("Read [FILE:{}]", attachment.display());

        let mut msg = inbound_msg(7012, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        // No inline body — the text goes to a sidecar the message names.
        assert!(
            !msg.content.contains(&text[..200]),
            "Long text must not be inlined, got: {}",
            msg.content
        );
        let uploads_dir = ws_path.join("uploads");
        let mut entries = tokio::fs::read_dir(&uploads_dir).await.unwrap();
        let mut spill = None;
        while let Some(entry) = entries.next_entry().await.unwrap() {
            if entry
                .file_name()
                .to_string_lossy()
                .ends_with(".extracted.txt")
            {
                spill = Some(entry.path());
            }
        }
        let spill = spill.expect("an .extracted.txt sidecar must be written");
        // The note is asserted in full, closing bracket included, so a note
        // left undelimited cannot pass unnoticed.
        assert!(
            msg.content.contains(&format!(
                "[File long.txt: the extracted text is too long to inline ({} characters); \
                 the full text was saved to {} — read that file.]",
                text.trim().chars().count(),
                spill.display()
            )),
            "Annotation must be a delimited note naming the sidecar, got: {}",
            msg.content
        );
        assert_eq!(
            tokio::fs::read_to_string(&spill).await.unwrap(),
            text.trim(),
            "Sidecar must carry the full extracted text"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_out_of_scope_marker_left_verbatim() {
        // A `[FILE:...]` marker is also user-typed text: reading, copying, or
        // deleting anything it names would be an exfiltration vector.
        let (tmp_root, ws_path, arbitrary) =
            out_of_scope_fixture("test_enrich_file_outside", "secret.md", b"# top secret").await;
        let marker = format!("Look at [FILE:{}]", arbitrary.display());

        let mut msg = test_msg(&marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert_eq!(
            msg.content, marker,
            "Out-of-scope marker must stay verbatim"
        );
        assert_eq!(
            tokio::fs::read(&arbitrary).await.unwrap(),
            b"# top secret",
            "Source file contents must be unchanged"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "No uploads copy may be created for out-of-scope paths"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_other_chat_attachment_left_inert() {
        // Inbound containment is per message: only the directory of the message
        // owning the marker is read, copied and deleted. Another chat's
        // directory (chat `12` is also the off-by-prefix trap for chat `1`) and
        // another message of the same chat are both inert.
        let tmp_root = crate::util::test::test_root().join("test_enrich_file_other_chat");
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();
        let (other_msg_dir, other_attachment) =
            telegram_attachment_fixture("2", 7014, "secret.md", b"# other chat").await;
        let (longer_id_dir, longer_id_attachment) =
            telegram_attachment_fixture("12", 7015, "secret.md", b"# chat 12").await;
        let (sibling_msg_dir, sibling_attachment) =
            telegram_attachment_fixture(TEST_CHAT_ID, 7016, "secret.md", b"# sibling").await;
        for attachment in [
            &other_attachment,
            &longer_id_attachment,
            &sibling_attachment,
        ] {
            let marker = format!("Look at [FILE:{}]", attachment.display());
            let mut msg = inbound_msg(7014, &marker);
            enrich_message(&mut msg, Some(ws_path.as_path())).await;
            assert_eq!(msg.content, marker, "Another message's attachment is inert");
        }

        assert_eq!(
            tokio::fs::read(&other_attachment).await.unwrap(),
            b"# other chat",
            "Another chat's attachment must not be read or deleted"
        );
        assert_eq!(
            tokio::fs::read(&longer_id_attachment).await.unwrap(),
            b"# chat 12",
            "A longer chat id's attachment must not be read or deleted"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "No uploads copy may be created for another message's attachment"
        );
        let _ = tokio::fs::remove_dir_all(&other_msg_dir).await;
        let _ = tokio::fs::remove_dir_all(&longer_id_dir).await;
        let _ = tokio::fs::remove_dir_all(&sibling_msg_dir).await;
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_album_members_all_ingested() {
        // An album is merged into one message keeping only the first member's
        // message id, so every member's directory must be carried over or all
        // but the first attachment would be rejected by containment.
        let (tmp_root, ws_path, first_dir, first) =
            inbound_ingest_fixture("test_enrich_file_album", 7017, "first.md", b"# first").await;
        let (second_dir, second) =
            telegram_attachment_fixture(TEST_CHAT_ID, 7018, "second.md", b"# second").await;
        let marker = format!(
            "Album [FILE:{}] and [FILE:{}]",
            first.display(),
            second.display()
        );

        let mut msg = inbound_album_msg(&[7017, 7018], &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        let uploads_dir = ws_path.join("uploads");
        for (name, bytes) in [
            ("first.md", &b"# first"[..]),
            ("second.md", &b"# second"[..]),
        ] {
            let copy = uploads_dir.join(name);
            assert!(
                msg.content.contains(&format!("[FILE:{}]", copy.display())),
                "Marker for {name} must point at the workspace copy, got: {}",
                msg.content
            );
            assert_eq!(
                tokio::fs::read(&copy).await.unwrap(),
                bytes,
                "Workspace copy of {name} must be byte-identical to the inbound file"
            );
        }
        for temp in [&first, &second] {
            assert!(
                !msg.content.contains(&temp.display().to_string()),
                "No raw temp path may survive, got: {}",
                msg.content
            );
        }
        assert!(
            !first_dir.exists() && !second_dir.exists(),
            "Both per-message directories must be deleted"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_vanished_attachment_annotated_and_dir_removed() {
        // The download wrote the file into its staging directory and the file is
        // gone by enrichment: the parent-directory fallback still recognizes the
        // directory as ours, so the marker is annotated and the now-empty
        // directory is cleaned up.
        let (tmp_root, ws_path, msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_file_vanished", 7020, "gone.md", b"# gone").await;
        tokio::fs::remove_file(&attachment).await.unwrap();
        let marker = format!("Read [FILE:{}]", attachment.display());

        let mut msg = inbound_msg(7020, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content.contains(
                "[File gone.md: could not be retrieved — the downloaded attachment is missing]"
            ),
            "A vanished attachment must be annotated, got: {}",
            msg.content
        );
        assert!(
            !msg_dir.exists(),
            "The now-empty staging directory must be deleted"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "A vanished attachment must not be copied into the workspace"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    /// The staging-directory cleanup is per message, not per marker kind: an
    /// image attachment that is gone by enrichment still leaves no directory behind.
    #[tokio::test]
    async fn enrich_vanished_image_attachment_leaves_no_staging_dir() {
        let (tmp_root, ws_path, msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_image_vanished", 7022, "gone.png", b"png").await;
        tokio::fs::remove_file(&attachment).await.unwrap();
        let marker = format!("Look at [IMAGE:{}]", attachment.display());

        let mut msg = inbound_msg(7022, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert!(
            msg.content.contains("[Invalid image reference:"),
            "A vanished image must be annotated, got: {}",
            msg.content
        );
        assert!(
            !msg_dir.exists(),
            "The empty staging directory must be removed"
        );
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_marker_naming_staging_dir_itself_is_not_removed_and_dir_cleaned_up() {
        // A marker naming the staging directory itself passes containment (it is
        // inside the root) but is not a regular file: it must never be
        // `remove_file`d, and the empty directory must still be cleaned up
        // without a spurious deletion failure.
        let (msg_dir, attachment) =
            inbound_attachment_fixture(7021, "placeholder.md", b"# x").await;
        tokio::fs::remove_file(&attachment).await.unwrap();
        let marker = format!("Look at [FILE:{}]", msg_dir.display());

        let mut msg = inbound_msg(7021, &marker);
        enrich_message(&mut msg, None).await;

        assert!(
            msg.content
                .contains(": the attachment is not a regular file]"),
            "A directory marker must be annotated as a non-file, got: {}",
            msg.content
        );
        assert!(
            !msg_dir.exists(),
            "The empty staging directory must be removed"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn enrich_file_symlink_in_inbound_dir_marker_left_verbatim() {
        // A symlink planted in this message's own per-message directory but
        // pointing outside the temp root exists, so the parent-directory
        // fallback must not rescue it: reading or copying it would exfiltrate
        // the target, and deleting it would remove a path the user placed
        // inside the containment root.
        let (tmp_root, ws_path, outside) =
            out_of_scope_fixture("test_enrich_file_symlink", "secret.md", b"# top secret").await;
        let (msg_dir, _) =
            telegram_attachment_fixture(TEST_CHAT_ID, 7019, "placeholder.bin", b"x").await;
        let link = msg_dir.join("link.md");
        std::os::unix::fs::symlink(&outside, &link).expect("plant the symlink");
        let marker = format!("Look at [FILE:{}]", link.display());

        let mut msg = inbound_msg(7019, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        assert_eq!(msg.content, marker, "A symlinked marker must stay verbatim");
        assert_eq!(
            tokio::fs::read(&outside).await.unwrap(),
            b"# top secret",
            "The symlink target must never be read or deleted"
        );
        assert!(
            tokio::fs::symlink_metadata(&link).await.is_ok(),
            "The symlink itself must not be deleted"
        );
        assert!(
            msg_dir.exists(),
            "The per-message directory holding the symlink must not be deleted"
        );
        assert!(
            !ws_path.join("uploads").exists(),
            "No uploads copy may be created through a symlink"
        );
        let _ = tokio::fs::remove_file(&link).await;
        let _ = tokio::fs::remove_dir_all(&msg_dir).await;
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_file_unsupported_blob_annotates_and_keeps_workspace_copy() {
        // Non-UTF-8 bytes with an unknown extension: no converter applies, but
        // the agent still gets the workspace copy to open itself.
        let bytes: &[u8] = &[0x00, 0x01, 0x02, 0xFF, 0xFE, b'x'];
        let (tmp_root, ws_path, msg_dir, attachment) =
            inbound_ingest_fixture("test_enrich_file_blob", 7013, "blob.bin", bytes).await;
        let marker = format!("Attached [FILE:{}]", attachment.display());

        let mut msg = inbound_msg(7013, &marker);
        enrich_message(&mut msg, Some(ws_path.as_path())).await;

        let copy = ws_path.join("uploads").join("blob.bin");
        assert!(
            msg.content.contains(&format!("[FILE:{}]", copy.display())),
            "Marker must point at the workspace copy, got: {}",
            msg.content
        );
        assert!(
            msg.content.contains(
                "[File blob.bin: received but not converted (unsupported format) — open the saved file directly]"
            ),
            "Unsupported format must be annotated, got: {}",
            msg.content
        );
        assert_eq!(
            tokio::fs::read(&copy).await.unwrap(),
            bytes,
            "Workspace copy must be byte-identical to the inbound file"
        );
        assert!(!attachment.exists() && !msg_dir.exists());
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_video_without_workspace_deletes_in_scope_temp() {
        // No workspace path: the video gets a plain annotation and no timeline, but the in-scope
        // inbound attachment is still a pure intermediate artifact and must be cleaned up.
        let (_msg_dir, tmp_video) = inbound_attachment_fixture(7004, "clip.mp4", b"fake mp4").await;
        let video_path_str = tmp_video.to_string_lossy().to_string();

        let mut msg = inbound_msg(7004, &format!("Watch [VIDEO:{video_path_str}] this clip"));
        enrich_message(&mut msg, None).await;

        assert!(
            msg.content.contains(&format!(
                "[Video attached: {}]",
                tmp_video.file_name().unwrap().to_string_lossy()
            )),
            "Plain video annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[Saved video:"),
            "No workspace copy may be made without an uploads dir, got: {}",
            msg.content
        );
        assert!(!msg.content.contains("[VIDEO:"));
        assert!(
            !tmp_video.exists(),
            "In-scope temp video must be deleted even without a workspace copy"
        );
    }
}