mahbot 0.11.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
//! Pre-processing for media markers in chat content.
//!
//! A body is split into the two blocks a bubble draws — its attachments and its text — because
//! iced's markdown parser drains every accumulated inline span into an `Image` item's `alt`, so a
//! picture drawn *inside* a paragraph swallows the text beside it. Extracting at render time means
//! already-stored history and transcripts render correctly too; nothing about the stored content
//! changes, and the text that reaches `markdown::parse()` never carries a picture.
//!
//! What each marker draws: `[IMAGE:…]` and `![alt](url)` the picture (a `data:` URI or a local
//! file draws; a remote, undecodable, missing or oversized target shows its `🖼️` label instead —
//! never raw base64, never a blank), and inside code the source stays visible as written;
//! `[AUDIO:…]`/`[VIDEO:…]`/`[FILE:…]` an emoji plus the file name, whose click reveals the file in
//! the OS file manager; `[Audio transcription of …]`/`[Video transcription of …]` (legacy persisted
//! forms) an emoji plus the transcribed text; `[Saved image: …]` nothing (the image renders from its
//! data-URI marker); `[Saved video: …]`/`[Saved audio: …]` the clip's or recording's name, labelled
//! exactly as its own marker is (there is no separate video or audio renderer).
//!
//! # When a marker is an attachment
//!
//! One rule decides it, in every message and for every kind: a marker becomes an attachment if
//! and only if its target is a reference — a path, an address or an inline payload, as
//! [`media_target::resolve_marker_target`] (the authority Telegram delivery uses too) classifies
//! it. An address counts in any scheme casing: [`referenced_target`] canonicalises it first,
//! because the resolver reads a scheme as written. Prose that merely mentions the syntax — a bare
//! word, `<path in your workspace>` — stays text, and so do a malformed address and one of a
//! scheme the product cannot show. A reference stays one when its file is gone: the row draws and
//! a click behaves like any missing file (a bare word is a reference only while a workspace file
//! of that name is — the resolver's existence probe, not a display decision). A local reference
//! one clearly-misspelled directory away from an existing file shows that file, the repair
//! delivery applies too ([`media_target::repaired_local_target`]). Only a reference
//! that cannot be attached *as that kind* becomes a [`media_target::marker_refusal`] notice.
//!
//! # Canonical marker pattern
//!
//! `[KIND:path]` is defined by the `MediaMarkerKind` enum in `src/util/mod.rs`, from which
//! [`MEDIA_MARKER_RE`] is generated — **the single source of truth** for every marker kind, in
//! any casing. This module uses the shared regex and [`parse_media_marker`] so a new kind
//! propagates here and to `enrichment.rs`, `agent.rs` and `compatible.rs` without per-kind regexes.
//!
//! # Clickable file markers
//!
//! A file attachment is a label row, not a link: no colour, no underline, only a click reveals its
//! target. The click travels as a `mahbot-file:` URI ([`file_link_target`] takes it apart,
//! [`reveal_file_marker`] opens it), so both surfaces link a row the way they link a URL.

use iced::widget::{Column, image, markdown, text};
use iced::{ContentFit, Element, Length};
use std::borrow::{Borrow, Cow};
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::SystemTime;

use super::{selectable, theme, widgets};
use crate::gui::markdown_breaks;
use crate::util::media_target::{self, MarkerTarget};
use crate::util::{
    MEDIA_MARKER_RE, MediaMarkerKind, UnwrapPoison, file_name_or_path, parse_media_marker,
};

/// The `image` crate, aliased because `image` here is iced's widget module.
use ::image as image_crate;

/// One attachment a rendered body carries, in body order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MediaAttachment {
    /// The picture to draw (a `data:` URI, a local path — absolute once a
    /// workspace resolves it — or a remote address, which only ever shows its label); `None` for
    /// a named file (audio, video, document) and for a picture whose payload is gone.
    pub image: Option<String>,
    /// How a plain-text rendition names it — `🖼️ image`, `🎵 song.mp3`, `🎬 Video: clip.mp4`.
    pub label: String,
    pub reveal: Option<String>,
}

pub(crate) struct Preprocessed {
    pub text: String,
    pub attachments: Vec<MediaAttachment>,
}

impl Preprocessed {
    /// The body as plain text: one line per attachment (its label), then the text — the order it
    /// is drawn in. Used by the Sessions collapse measurement.
    #[must_use]
    pub fn display_text(&self) -> String {
        let mut out = self
            .attachments
            .iter()
            .map(|attachment| attachment.label.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        if !self.text.is_empty() {
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(&self.text);
        }
        out
    }
}

/// Pre-process a content string into the text to parse and the attachments the text no longer
/// carries. One ordered pass, so the attachments come out in body order, whichever source wrote
/// each one. `workspace` is the root relative marker targets name a file in; `None` leaves each
/// target to the module's rule as written.
pub(crate) fn preprocess(content: &str, workspace: Option<&Path>) -> Preprocessed {
    // Order matters: the transcription annotations contain the words "Audio" and "Video", which
    // overlap the raw `[AUDIO:...]`/`[VIDEO:...]` patterns. Handle them first.
    let s = replace_saved_annotations(&replace_transcription(content));
    if !MEDIA_MARKER_RE.is_match(&s) && !s.contains("![") {
        return Preprocessed {
            text: s,
            attachments: Vec::new(),
        };
    }
    let (code, mut edits) = scan(&s);
    edits.extend(marker_edits(&s, workspace, &code));
    edits.sort_by_key(|edit| edit.range.start);
    apply_edits(&s, edits)
}

/// Parse a chat body for display: extract its markers into attachments, escape the
/// HTML-classified regions so angle-bracket text renders literally, turn soft breaks into hard
/// ones, and parse what is left. Both chat surfaces run exactly this pipeline, and the order is
/// load-bearing: markers are extracted before the escape and the break pass.
pub(crate) fn parse_body(
    content: &str,
    workspace: Option<&Path>,
) -> (Vec<markdown::Item>, Vec<MediaAttachment>) {
    let rendered = preprocess(content, workspace);
    let escaped = markdown_breaks::escape_html_blocks(&rendered.text);
    let with_breaks = markdown_breaks::hard_breaks(&escaped);
    (
        markdown::parse(&with_breaks).collect(),
        rendered.attachments,
    )
}

/// `[Audio transcription of {filename}]: {text}` → 🔊, `[Video transcription of …]` → 🎬. Both are
/// legacy annotations: only rows persisted before media understanding reached the timeline carry
/// them, so the markers stay rendered rather than showing those old rows as raw text. Only the
/// annotation header is replaced.
fn replace_transcription(s: &str) -> String {
    static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
        regex::Regex::new(r"\[(Audio|Video) transcription of [^\]]+\]:\s*")
            .expect("transcription regex must compile")
    });
    RE.replace_all(s, |caps: &regex::Captures| {
        match caps.get(1).map(|m| m.as_str()) {
            Some("Audio") => "🔊 ",
            _ => "🎬 ",
        }
    })
    .to_string()
}

/// The display form of one marker under the module's one rule: the replacement it becomes, or
/// `None` when its target is prose and stays as written.
fn render_marker(kind: MediaMarkerKind, target: &str, roots: &[PathBuf]) -> Option<Replacement> {
    let target = referenced_target(target)?;
    match media_target::resolve_marker_target(&target, roots) {
        MarkerTarget::NotAReference => None,
        MarkerTarget::Inline => Some(match kind {
            MediaMarkerKind::Image => {
                Replacement::Attachment(delivered_marker(kind, &target, None))
            }
            MediaMarkerKind::Audio | MediaMarkerKind::Video | MediaMarkerKind::File => {
                Replacement::Text(media_target::inline_marker_refusal(kind))
            }
        }),
        MarkerTarget::Remote => Some(match media_target::remote_marker(kind, &target) {
            media_target::RemoteMarker::Refused(reason) => {
                Replacement::Text(media_target::marker_refusal_for(&target, reason))
            }
            media_target::RemoteMarker::Deliverable => {
                Replacement::Attachment(delivered_marker(kind, &target, None))
            }
        }),
        MarkerTarget::Local(path) => {
            // The one repair delivery applies too, so a repaired marker shows the file it meant
            // instead of a row pointing at a path that is not there.
            let path = media_target::repaired_local_target(&path).unwrap_or(path);
            Some(Replacement::Attachment(delivered_marker(
                kind,
                &target,
                Some(&path.to_string_lossy()),
            )))
        }
    }
}

/// The target as this layer classifies it, or `None` when it names no reference. The resolver
/// reads a scheme exactly as written, so the address reading is settled here: a scheme-written
/// target is the address it spells, never a path, while one that is not a well-formed http(s)
/// address names nothing — and an empty target names nothing either.
fn referenced_target(target: &str) -> Option<Cow<'_, str>> {
    let target = target.trim();
    if target.is_empty() {
        return None;
    }
    let Some(scheme) = scheme_of(target) else {
        return Some(Cow::Borrowed(target));
    };
    let canonical = if scheme.chars().any(|c| c.is_ascii_uppercase()) {
        let rest = &target[scheme.len() + 3..];
        Cow::Owned(format!("{}://{rest}", scheme.to_ascii_lowercase()))
    } else {
        Cow::Borrowed(target)
    };
    media_target::is_valid_remote_url(&canonical).then_some(canonical)
}

/// The scheme `target` is written with — `HTTPS://example.com/x.png` → `HTTPS`. A `://` further
/// into the target belongs to it, and only an RFC-valid scheme passes, so a `data:` payload
/// holding one is never read as an address.
fn scheme_of(target: &str) -> Option<&str> {
    let (scheme, _) = target.split_once("://")?;
    let mut chars = scheme.chars();
    (chars.next()?.is_ascii_alphabetic()
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
    .then_some(scheme)
}

/// The attachment a marker naming a reference becomes. `resolved` is what the thing is reached by
/// when that differs from the written target (a local target's absolute path).
fn delivered_marker(
    kind: MediaMarkerKind,
    target: &str,
    resolved: Option<&str>,
) -> MediaAttachment {
    let resolved = resolved.unwrap_or(target);
    match kind {
        MediaMarkerKind::Image => picture_attachment(resolved, Some(target)),
        MediaMarkerKind::File => MediaAttachment {
            image: None,
            label: format!("📄 {}", file_name_or_path(target)),
            reveal: Some(resolved.to_string()),
        },
        MediaMarkerKind::Audio | MediaMarkerKind::Video => MediaAttachment {
            image: None,
            label: media_label(kind, target),
            reveal: None,
        },
    }
}

/// The attachment a picture becomes: `image` is what the renderer draws, while the label names it
/// by file name — or generically, because an inline payload has no name.
fn picture_attachment(image: &str, label_target: Option<&str>) -> MediaAttachment {
    let stripped = image.starts_with(crate::util::DATA_URI_OMITTED_PREFIX);
    MediaAttachment {
        image: (!stripped).then(|| image.to_string()),
        label: if media_target::is_inline_payload(image) {
            "🖼️ image".to_string()
        } else {
            format!("🖼️ {}", file_name_or_path(label_target.unwrap_or(image)))
        },
        reveal: None,
    }
}

/// The label a delivered `AUDIO`/`VIDEO` marker shows: neither has an inline player, so the file
/// is named rather than played.
fn media_label(kind: MediaMarkerKind, target: &str) -> String {
    match kind {
        MediaMarkerKind::Audio => format!("🎵 {}", file_name_or_path(target)),
        _ => format!("🎬 Video: {}", file_name_or_path(target)),
    }
}

/// Handle the `[Saved <kind>: path]` upload annotations produced by the channel enrichment layer.
/// They are **not** `[KIND:path]` markers.
///
/// `[Saved image: path]` is stripped entirely: the image already renders from its `[IMAGE:data:…]`
/// marker. `[Saved video: path]` becomes `🎬 Video: filename` and `[Saved audio: path]`
/// `🎵 filename`, the same labels their own markers show: there is **no** separate video or audio
/// renderer, so stripping them would hide the file. A recording's line is model-facing only (the
/// owner's bubble carries the transcript), while a clip's reaches the bubble in the body.
fn replace_saved_annotations(s: &str) -> String {
    // `\n*` eats the blank-line separator enrichment inserts before the trailing image annotation
    // so no stray whitespace remains.
    static SAVED_IMAGE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
        regex::Regex::new(r"\n*\[Saved image: [^\]]*\]")
            .expect("saved image annotation regex must compile")
    });
    static SAVED_VIDEO_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
        regex::Regex::new(r"\[Saved video: ([^\]]*)\]")
            .expect("saved video annotation regex must compile")
    });
    static SAVED_AUDIO_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
        regex::Regex::new(r"\[Saved audio: ([^\]]*)\]")
            .expect("saved audio annotation regex must compile")
    });

    let s = SAVED_IMAGE_RE.replace_all(s, "").to_string();
    let s = SAVED_VIDEO_RE
        .replace_all(&s, |caps: &regex::Captures| {
            let path = caps.get(1).map_or("", |m| m.as_str());
            format!("🎬 Video: {}", file_name_or_path(path))
        })
        .to_string();
    SAVED_AUDIO_RE
        .replace_all(&s, |caps: &regex::Captures| {
            let path = caps.get(1).map_or("", |m| m.as_str());
            format!("🎵 {}", file_name_or_path(path))
        })
        .to_string()
}

struct Edit {
    range: Range<usize>,
    replacement: Replacement,
}

enum Replacement {
    Text(String),
    /// The attachment the range becomes: it leaves the text and is drawn in the body's
    /// attachment group instead.
    Attachment(MediaAttachment),
}

/// The desktop's share of the one [`crate::util::markdown::scan`] pass: its code regions, where
/// marker syntax is source, and the edits its markdown pictures become.
///
/// An agent writes `![alt](url)` directly, and the parser would draw it as an `Image` item that
/// swallows the text collected before it, so it leaves the text here too. A picture needs no code
/// check: this same scan is the render's.
fn scan(text: &str) -> (Vec<Range<usize>>, Vec<Edit>) {
    let markdown = crate::util::markdown::scan(text);
    let pictures = markdown
        .pictures
        .into_iter()
        .map(|(range, dest)| {
            let dest = dest.trim();
            // A picture with no destination can never draw and would still reach the parser as
            // an `Image` item, so its source goes without an attachment.
            let replacement = if dest.is_empty() {
                Replacement::Text(String::new())
            } else {
                Replacement::Attachment(picture_attachment(dest, None))
            };
            Edit { range, replacement }
        })
        .collect();
    (markdown.code, pictures)
}

/// The edits the body's `[KIND:…]` markers become, in body order, through the canonical
/// [`MEDIA_MARKER_RE`].
///
/// A reference becomes an attachment and contributes nothing to the text; a refusal notice and a
/// marker left as written keep their place. A marker inside code is source, so it stays too.
fn marker_edits(text: &str, workspace: Option<&Path>, code: &[Range<usize>]) -> Vec<Edit> {
    let roots: Vec<PathBuf> = workspace.map(Path::to_path_buf).into_iter().collect();
    let mut edits = Vec::new();
    for caps in MEDIA_MARKER_RE.captures_iter(text) {
        let whole = caps.get_match();
        if code.iter().any(|range| range.contains(&whole.start())) {
            continue;
        }
        let (kind, target) = parse_media_marker(&caps);
        let Some(replacement) = render_marker(kind, target, &roots) else {
            continue;
        };
        edits.push(Edit {
            range: whole.range(),
            replacement,
        });
    }
    edits
}

/// Apply the edits, sorted by where they begin, and collect the attachments in walk order — one
/// pass, so a body mixing marker kinds and markdown pictures keeps its order.
fn apply_edits(text: &str, edits: Vec<Edit>) -> Preprocessed {
    let mut out = String::with_capacity(text.len());
    let mut attachments = Vec::new();
    let mut cursor = 0usize;
    let mut edits = edits.into_iter().peekable();
    while let Some(edit) = edits.next() {
        if edit.range.start < cursor {
            continue;
        }
        match edit.replacement {
            Replacement::Text(replacement) => {
                out.push_str(&text[cursor..edit.range.start]);
                out.push_str(&replacement);
                cursor = edit.range.end;
            }
            Replacement::Attachment(attachment) => {
                let next_start = edits.peek().map(|next| next.range.start);
                let removal = removal_range(text, &edit.range, cursor, next_start);
                out.push_str(&text[cursor..removal.start]);
                cursor = join_after_removal(&mut out, text, removal.end);
                attachments.push(attachment);
            }
        }
    }
    out.push_str(&text[cursor..]);
    Preprocessed {
        text: out,
        attachments,
    }
}

/// The range an attachment's removal actually takes out: the picture itself, or — when the picture
/// is all its line holds, a bullet aside — the whole line including its newline. A lone picture's
/// two surrounding line breaks are one line break of the body, and a bullet left behind would
/// dangle. A line another edit already rewrote (`cursor`) or is about to (`next_start`) keeps its
/// own text.
fn removal_range(
    text: &str,
    range: &Range<usize>,
    cursor: usize,
    next_start: Option<usize>,
) -> Range<usize> {
    let line_start = text[..range.start]
        .rfind('\n')
        .map_or(0, |newline| newline + 1);
    let line_end = text[range.end..]
        .find('\n')
        .map_or(text.len(), |offset| range.end + offset);
    let line_shared = line_start < cursor || next_start.is_some_and(|start| start < line_end);
    let beside = format!(
        "{}{}",
        &text[line_start..range.start],
        &text[range.end..line_end]
    );
    let alone = !line_shared && (beside.trim().is_empty() || only_list_marker(&beside));
    if alone {
        line_start..(line_end + 1).min(text.len())
    } else {
        range.clone()
    }
}

/// Join the text around a removal: the whitespace run `out` ends with and the one the text
/// continues with are replaced by what they amount to — a blank line for a paragraph gap, one
/// newline for a line break, a single space inside a sentence, nothing at the end of the body.
/// Returns the cursor, past the run the text continues with.
fn join_after_removal(out: &mut String, text: &str, cursor: usize) -> usize {
    let mut newlines = 0;
    let mut opened = false;
    while let Some(&byte) = out.as_bytes().last() {
        if !matches!(byte, b' ' | b'\t' | b'\r' | b'\n') {
            break;
        }
        newlines += usize::from(byte == b'\n');
        opened = true;
        out.pop();
    }
    let after = &text[cursor..];
    let run = after.len() - after.trim_start_matches([' ', '\t', '\r', '\n']).len();
    newlines += after[..run].matches('\n').count();
    let rest = &after[run..];
    match newlines {
        0 => {
            if (opened || run > 0) && !out.is_empty() && !rest.is_empty() {
                out.push(' ');
            }
        }
        1 => out.push('\n'),
        _ => out.push_str("\n\n"),
    }
    cursor + run
}

/// Whether a line is only a list marker (`-`, `*`, `+`, `1.`, `1)`) and whitespace — the remains
/// of a bullet whose whole content was extracted.
fn only_list_marker(line: &str) -> bool {
    let trimmed = line.trim();
    if matches!(trimmed, "-" | "*" | "+") {
        return true;
    }
    trimmed.strip_suffix(['.', ')']).is_some_and(|digits| {
        !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
    })
}

/// Maximum longest side (px) of the rendered image the GUI keeps per image — a
/// `MAX_IMAGE_LONGEST_SIDE_PX² · 4` = 16 MiB RGBA tile. A larger but valid raster is decoded under
/// the shared generous budget and DOWNSCALED to this cap, so a tall chrome screenshot renders; only
/// a corrupt, missing, non-image or header-bomb target degrades to the placeholder.
const MAX_IMAGE_LONGEST_SIDE_PX: u32 = 2048;

fn downscale_raster(width: u32, height: u32, rgba: Vec<u8>) -> Option<(u32, u32, Vec<u8>)> {
    if width <= MAX_IMAGE_LONGEST_SIDE_PX && height <= MAX_IMAGE_LONGEST_SIDE_PX {
        return Some((width, height, rgba));
    }
    // `thumbnail` computes the aspect-preserving target dims internally and only shrinks when the
    // image exceeds the box.
    let img = image_crate::DynamicImage::ImageRgba8(image_crate::RgbaImage::from_raw(
        width, height, rgba,
    )?);
    let resized = img
        .thumbnail(MAX_IMAGE_LONGEST_SIDE_PX, MAX_IMAGE_LONGEST_SIDE_PX)
        .into_rgba8();
    Some((resized.width(), resized.height(), resized.into_raw()))
}

/// Decode `bytes` as a native raster and downscale it to the display cap, answering `(width,
/// height, RGBA8 pixels)` or `None` on any failure — every `None` renders as the placeholder.
///
/// The decode reuses the shared [`media_target::raster_decode_limits`] budget (generous dimension
/// and alloc caps, so a legitimate tall screenshot still decodes) and then shrinks the result to
/// the renderable cap, so the persistent handle stays small and the renderer upload happens once.
#[must_use]
fn render_raster(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
    let (width, height, rgba) =
        media_target::decode_raster_bytes(bytes, media_target::raster_decode_limits())?;
    downscale_raster(width, height, rgba)
}

/// Decode and validate the image in a `data:…` URI, answering `(width, height, RGBA8 pixels)` or
/// `None` on any failure. Vets the URI through the same declared-subtype==actual-bytes gate the
/// provider's image gate uses (a `data:image/png` holding JPEG bytes is rejected), then uses the
/// shared raster decode and downscale.
#[must_use]
fn decode_data_uri_image(uri: &str) -> Option<(u32, u32, Vec<u8>)> {
    let (width, height, rgba) =
        media_target::decode_native_data_uri(uri, media_target::raster_decode_limits())?;
    downscale_raster(width, height, rgba)
}

/// A bounded least-recently-used cache: `get` bumps recency, `insert` evicts the oldest once the
/// capacity is hit. Keys are looked up by [`Borrow`], so callers can use an unowned key.
pub(super) struct BoundedLruCache<K, V> {
    entries: HashMap<K, V>,
    /// LRU order of `entries` keys; back = most recently used.
    lru: VecDeque<K>,
    cap: usize,
}

impl<K, V> BoundedLruCache<K, V>
where
    K: Hash + Eq + Clone,
{
    pub(super) fn with_capacity(cap: usize) -> Self {
        Self {
            entries: HashMap::new(),
            lru: VecDeque::new(),
            cap,
        }
    }

    pub(super) fn get<Q>(&mut self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        let hit = self.entries.get(key);
        if hit.is_some() {
            if let Some(pos) = self.lru.iter().position(|k| k.borrow() == key) {
                let key = self.lru.remove(pos).expect("position found by iteration");
                self.lru.push_back(key);
            }
        }
        hit
    }

    pub(super) fn insert(&mut self, key: K, value: V) {
        // Remove any existing occurrence so a re-insert replaces the value and moves the key to
        // the most-recent position exactly once — a duplicate in `lru` would let eviction drop a
        // live entry.
        if let Some(pos) = self.lru.iter().position(|k| k == &key) {
            self.lru.remove(pos);
        }
        self.entries.insert(key.clone(), value);
        self.lru.push_back(key);
        while self.entries.len() > self.cap {
            let oldest = self
                .lru
                .pop_front()
                .expect("lru mirrors entries, so a front key always exists");
            self.entries.remove(&oldest);
        }
    }
}

/// Maximum decoded-image outcomes retained per process-lifetime cache. Each `Decoded` entry holds
/// up to 16 MiB of RGBA, so this caps worst-case retained pixels at ~512 MiB per cache.
const MAX_CACHED_IMAGES: usize = 32;

#[derive(Debug)]
pub(super) enum CachedImage {
    /// Successfully decoded; the stable handle is reused across frames, which keeps the wgpu
    /// texture Id stable too.
    Decoded(image::Handle),
    Failed,
}

impl CachedImage {
    fn from_raster(raster: Option<(u32, u32, Vec<u8>)>) -> Self {
        match raster {
            Some((width, height, rgba)) => {
                Self::Decoded(image::Handle::from_rgba(width, height, rgba))
            }
            None => Self::Failed,
        }
    }

    fn handle(&self) -> Option<image::Handle> {
        match self {
            Self::Decoded(handle) => Some(handle.clone()),
            Self::Failed => None,
        }
    }
}

/// Process-lifetime cache of data-URI decode outcomes, keyed by the full data-URI string.
static DATA_URI_IMAGE_CACHE: LazyLock<Mutex<BoundedLruCache<String, CachedImage>>> =
    LazyLock::new(|| Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES)));

/// Return the cached outcome for `key`, decoding and caching it on a miss.
///
/// The entry is inspected under the lock and returned through [`CachedImage::handle`] — a cached
/// [`CachedImage::Failed`] is a hit that yields `None`, never a miss (falling through would
/// re-decode a corrupt payload on every frame). The decode runs with the lock released.
#[must_use]
pub(super) fn cached_image<K, Q>(
    cache: &Mutex<BoundedLruCache<K, CachedImage>>,
    key: &Q,
    decode: impl FnOnce() -> Option<(u32, u32, Vec<u8>)>,
) -> Option<image::Handle>
where
    K: Hash + Eq + Clone + Borrow<Q>,
    Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
{
    if let Some(cached) = cache.lock().unwrap_poison().get(key) {
        return cached.handle();
    }
    let outcome = CachedImage::from_raster(decode());
    let handle = outcome.handle();
    cache.lock().unwrap_poison().insert(key.to_owned(), outcome);
    handle
}

/// A stable, cached iced handle for the image in a `data:…` URI, or `None` when the payload is
/// missing, over-cap or undecodable — the caller renders the placeholder. An over-cap payload is
/// refused from length alone BEFORE the cache is consulted, so it is never retained as a key.
#[must_use]
fn data_uri_image_handle(uri: &str) -> Option<image::Handle> {
    media_target::data_uri_base64_payload(uri)?;
    cached_image(&DATA_URI_IMAGE_CACHE, uri, || decode_data_uri_image(uri))
}

/// Process-lifetime cache of local-image decode outcomes, keyed by (canonical path, mtime) — a
/// modified file is a new entry. Evicts the least-recently-used entry past [`MAX_CACHED_IMAGES`].
static LOCAL_IMAGE_CACHE: LazyLock<Mutex<BoundedLruCache<(PathBuf, SystemTime), CachedImage>>> =
    LazyLock::new(|| Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES)));

/// A stable, cached iced handle for a local image file, or `None` when the file is missing,
/// relative, over-cap or undecodable — the caller renders the `🖼️ {filename}` placeholder. The
/// raster is decoded under the shared generous budget, downscaled to the display cap
/// ([`render_raster`]), then cached at most once per (canonical path, mtime).
#[must_use]
fn local_path_image_handle(path: &str) -> Option<image::Handle> {
    let p = Path::new(path);
    if !p.is_absolute() {
        return None;
    }
    let meta = std::fs::metadata(p).ok()?;
    // Shared 50 MiB cap: a huge file is refused from metadata alone (never opened), so the render
    // thread is not asked to read it.
    if !meta.is_file() || meta.len() > crate::util::INBOUND_IMAGE_MAX_INPUT_BYTES {
        return None;
    }
    let mtime = meta.modified().ok()?;
    let canonical = crate::util::canonical_or_self(p);
    cached_image(&LOCAL_IMAGE_CACHE, &(canonical.clone(), mtime), || {
        std::fs::read(&canonical)
            .ok()
            .and_then(|b| render_raster(&b))
    })
}

const FILE_LINK_PREFIX: &str = "mahbot-file:";

pub(crate) fn file_link_target(uri: &str) -> Option<&str> {
    uri.strip_prefix(FILE_LINK_PREFIX)
}

fn file_link_uri(target: &str) -> String {
    format!("{FILE_LINK_PREFIX}{target}")
}

/// Resolve a hand-over's target: an absolute one as it is, a relative one against the
/// conversation's workspace.
fn resolve_file_marker_target(target: &str, workspace: Option<&Path>) -> Result<PathBuf, String> {
    let raw = Path::new(target);
    if raw.is_absolute() {
        return Ok(raw.to_path_buf());
    }
    workspace
        .map(|root| root.join(raw))
        .ok_or_else(|| format!("Cannot open '{target}': the conversation's workspace is unknown."))
}

/// Reveal a marker's target in the platform file manager. Only an existing regular file is handed
/// over: the launchers report success and failure unreliably, so a target that is gone, is not a
/// file, or names no path is reported instead of opening something.
pub(crate) fn reveal_file_marker(target: &str, workspace: Option<&Path>) -> Result<(), String> {
    let path = resolve_file_marker_target(target, workspace)?;
    if !path.exists() {
        return Err(format!("File not found: {}", path.display()));
    }
    if !path.is_file() {
        return Err(format!("Not a file: {}", path.display()));
    }
    super::reveal_in_file_manager(&path)
}

/// The drawn body of one message: its attachment group above its whole text, in the stored order —
/// never interleaved, neither ever dropped. `fallback` draws what to show when the body carries
/// neither.
#[expect(
    clippy::large_types_passed_by_value,
    reason = "mirrors `markdown::view`, which hands the settings over by value"
)]
pub(crate) fn body<'a, Message: 'a>(
    attachments: &'a [MediaAttachment],
    items: &'a [markdown::Item],
    settings: markdown::Settings,
    on_link_click: impl Fn(String) -> Message + Clone + 'a,
    fallback: impl FnOnce() -> Element<'a, Message>,
) -> Element<'a, Message> {
    let text_size = f32::from(settings.text_size);
    let group = attachment_group(attachments, text_size, on_link_click.clone());
    let text =
        (!items.is_empty()).then(|| selectable::markdown::view(items, settings).map(on_link_click));
    match (group, text) {
        (Some(group), Some(text)) => Column::with_children(vec![group, text])
            .spacing(theme::SPACE_6)
            .into(),
        (Some(group), None) => group,
        (None, Some(text)) => text,
        (None, None) => fallback(),
    }
}

/// The attachment group of a rendered body: its pictures and named files, one block above the
/// text, in the order the content carried them. `None` when the body carries no attachment.
fn attachment_group<'a, Message: 'a>(
    attachments: &'a [MediaAttachment],
    text_size: f32,
    on_link_click: impl Fn(String) -> Message + Clone + 'a,
) -> Option<Element<'a, Message>> {
    if attachments.is_empty() {
        return None;
    }
    let rows: Vec<Element<'a, Message>> = attachments
        .iter()
        .map(|attachment| match &attachment.image {
            // A picture the content names: drawn from the cached bounded decode, or named by its
            // label when there is nothing to draw (missing, corrupt or over-cap file, undrawable
            // address, a payload the content no longer carries) — never a broken image.
            Some(url) => picture_row(url, &attachment.label, text_size),
            None => label_row(attachment, text_size, on_link_click.clone()),
        })
        .collect();
    Some(Column::with_children(rows).spacing(theme::SPACE_6).into())
}

fn picture_row<'a, Message: 'a>(
    url: &'a str,
    label: &'a str,
    text_size: f32,
) -> Element<'a, Message> {
    let handle = if url.starts_with("data:") {
        data_uri_image_handle(url)
    } else {
        local_path_image_handle(url)
    };
    match handle {
        Some(handle) => image::Image::new(handle)
            .width(Length::Fill)
            .content_fit(ContentFit::Contain)
            .into(),
        None => label_text(label, text_size),
    }
}

/// A named attachment's row. A revealable one is the same plain label as any other — no colour,
/// no underline, no button chrome: only a click reveals the file.
fn label_row<'a, Message: 'a>(
    attachment: &'a MediaAttachment,
    text_size: f32,
    on_link_click: impl Fn(String) -> Message + 'a,
) -> Element<'a, Message> {
    match &attachment.reveal {
        Some(target) => {
            let label = text::Span::new(attachment.label.as_str()).link(file_link_uri(target));
            selectable::rich_text([label])
                .size(text_size)
                .on_link_click(on_link_click)
                .into()
        }
        None => label_text(&attachment.label, text_size),
    }
}

fn label_text<'a, Message: 'a>(label: &'a str, text_size: f32) -> Element<'a, Message> {
    widgets::selectable_text(label, theme::TEXT_PRIMARY)
        .size(text_size)
        .into()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::DATA_URI_OMITTED_PREFIX;
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use iced::widget::markdown;
    use std::io::Cursor;

    fn picture(image: Option<&str>, label: &str) -> MediaAttachment {
        MediaAttachment {
            image: image.map(str::to_string),
            label: label.to_string(),
            reveal: None,
        }
    }

    /// An audio/video/document attachment, revealed at `reveal` on a click.
    fn named(label: &str, reveal: Option<&str>) -> MediaAttachment {
        MediaAttachment {
            image: None,
            label: label.to_string(),
            reveal: reveal.map(str::to_string),
        }
    }

    /// The picture row a resolved image path draws, named by its file name.
    fn img(path: &str) -> MediaAttachment {
        picture(Some(path), &format!("🖼️ {}", file_name_or_path(path)))
    }

    fn snd(path: &str) -> MediaAttachment {
        named(&format!("🎵 {}", file_name_or_path(path)), None)
    }

    fn clip(path: &str) -> MediaAttachment {
        named(&format!("🎬 Video: {}", file_name_or_path(path)), None)
    }

    fn doc(path: &str, reveal: &str) -> MediaAttachment {
        named(&format!("📄 {}", file_name_or_path(path)), Some(reveal))
    }

    fn paragraph_text(items: &[markdown::Item]) -> String {
        let style = crate::gui::theme::markdown_settings().style;
        items
            .iter()
            .filter_map(|item| match item {
                markdown::Item::Paragraph(text) => Some(text.spans(style)),
                _ => None,
            })
            .map(|spans| spans.iter().map(|s| s.text.to_string()).collect::<String>())
            .collect()
    }

    /// The text of the single bullet a parsed body renders the picture into.
    fn only_bullet(name: &str, items: &[markdown::Item]) -> String {
        let [markdown::Item::List { bullets, .. }] = items else {
            panic!("case {name}: expected the list to survive, got {items:?}");
        };
        let [markdown::Bullet::Point { items }] = bullets.as_slice() else {
            panic!("case {name}: expected one bullet, got {bullets:?}");
        };
        paragraph_text(items)
    }

    fn tiny_png(width: u32, height: u32) -> Vec<u8> {
        let img = ::image::RgbaImage::from_pixel(width, height, ::image::Rgba([255, 0, 0, 255]));
        let mut buf = Vec::new();
        img.write_to(&mut Cursor::new(&mut buf), ::image::ImageFormat::Png)
            .expect("test PNG must encode");
        buf
    }

    fn data_uri(png: &[u8]) -> String {
        format!("data:image/png;base64,{}", STANDARD.encode(png))
    }

    #[expect(clippy::too_many_lines)] // one table over every preprocessing case
    #[test]
    fn preprocess_table() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("photo.png"), tiny_png(2, 1)).unwrap();
        std::fs::write(root.join("my file.png"), tiny_png(2, 1)).unwrap();
        std::fs::write(root.join("recording.ogg"), b"ogg").unwrap();
        std::fs::create_dir_all(root.join("dir/subdir")).unwrap();
        std::fs::write(root.join("dir/subdir/rec.ogg"), b"ogg").unwrap();
        std::fs::write(root.join("video.mp4"), b"mp4").unwrap();
        std::fs::create_dir_all(root.join("generated")).unwrap();
        std::fs::write(root.join("generated/report.pdf"), b"pdf").unwrap();
        std::fs::write(root.join("README"), b"readme").unwrap();
        std::fs::write(root.join("notes.txt"), b"not an image").unwrap();
        let abs = |path: &str| root.join(path).to_string_lossy().into_owned();
        let (photo_str, spaced_str) = (abs("photo.png"), abs("my file.png"));
        let (report_str, readme_str) = (abs("generated/report.pdf"), abs("README"));
        let (gone_str, gone_file_str) = (abs("cleaned_up.png"), abs("generated/gone.pdf"));
        let not_an_image_str = abs("notes.txt");
        let valid_uri = data_uri(&tiny_png(2, 1));

        let cases: Vec<(&str, String, &str, Vec<MediaAttachment>)> = vec![
            (
                "resolves a workspace-relative image marker and takes an absolute one as it is",
                format!("Look [IMAGE:photo.png] and [IMAGE:{photo_str}] here"),
                "Look and here",
                vec![img(&photo_str), img(&photo_str)],
            ),
            (
                "delivers markers written in lowercase",
                "img [image:photo.png] hear [audio:recording.ogg]".into(),
                "img hear",
                vec![img(&photo_str), snd("recording.ogg")],
            ),
            (
                "draws markers whose file is gone like any missing file",
                format!("see [image:cleaned_up.png] and [IMAGE:{gone_str}] here"),
                "see and here",
                vec![img(&gone_str), img(&gone_str)],
            ),
            (
                "resolves a relative image marker with spaces in the path",
                "img [IMAGE:my file.png]".into(),
                "img",
                vec![img(&spaced_str)],
            ),
            (
                "draws a target that is not an image, letting the viewer show its placeholder",
                format!("[IMAGE:{not_an_image_str}]"),
                "",
                vec![img(&not_an_image_str)],
            ),
            (
                "keeps an address it cannot show as written",
                "see [IMAGE:https://exa mple.com/x.png], [FILE:https://exa mple.com/a.pdf] \
                 and [FILE:ftp://example.com/a.pdf] here"
                    .into(),
                "see [IMAGE:https://exa mple.com/x.png], [FILE:https://exa mple.com/a.pdf] \
                 and [FILE:ftp://example.com/a.pdf] here",
                Vec::new(),
            ),
            (
                "reads an address in a non-canonical scheme casing",
                "see [IMAGE:HTTPS://Example.com/x.png] here".into(),
                "see here",
                vec![img("https://Example.com/x.png")],
            ),
            (
                "names the stripped-data-URI placeholder generically and draws nothing",
                format!("Look [IMAGE:{DATA_URI_OMITTED_PREFIX} (35 bytes)>] here"),
                "Look here",
                vec![picture(None, "🖼️ image")],
            ),
            (
                "draws an inline image payload",
                format!("Look [IMAGE:{valid_uri}] here"),
                "Look here",
                vec![picture(Some(&valid_uri), "🖼️ image")],
            ),
            (
                "draws an inline payload whose body holds an address",
                r#"Look [IMAGE:data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>] here"#
                    .into(),
                "Look here",
                vec![picture(
                    Some(r#"data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>"#),
                    "🖼️ image",
                )],
            ),
            (
                "keeps prose marker examples as written, beside a reference that draws",
                "send with [IMAGE:path], [VIDEO:path] or [FILE:<path in your workspace>]; \
                 then [VIDEO:video.mp4]"
                    .into(),
                "send with [IMAGE:path], [VIDEO:path] or [FILE:<path in your workspace>]; then",
                vec![clip("video.mp4")],
            ),
            (
                "keeps an empty marker target as written",
                "an empty [FILE: ] names nothing".into(),
                "an empty [FILE: ] names nothing",
                Vec::new(),
            ),
            (
                "resolves a relative audio marker",
                "Listen [AUDIO:recording.ogg]".into(),
                "Listen",
                vec![snd("recording.ogg")],
            ),
            (
                "resolves a relative audio marker in a nested path",
                "hear [AUDIO:dir/subdir/rec.ogg]".into(),
                "hear",
                vec![snd("dir/subdir/rec.ogg")],
            ),
            (
                "draws a missing audio marker like any missing file",
                "Listen [AUDIO:gone.ogg]".into(),
                "Listen",
                vec![snd("gone.ogg")],
            ),
            (
                "resolves a relative video marker",
                "Watch [VIDEO:video.mp4]".into(),
                "Watch",
                vec![clip("video.mp4")],
            ),
            (
                "names a file marker's resolved target",
                "Get [FILE:generated/report.pdf]".into(),
                "Get",
                vec![doc("generated/report.pdf", &report_str)],
            ),
            (
                "delivers a workspace file whose name is a bare word",
                "Get [FILE:README]".into(),
                "Get",
                vec![doc("README", &readme_str)],
            ),
            (
                "draws a file marker whose file is gone, revealing where it was",
                "Get [FILE:generated/gone.pdf]".into(),
                "Get",
                vec![doc("generated/gone.pdf", &gone_file_str)],
            ),
            (
                "reports a file marker that names an address",
                "Get [FILE:https://example.com/a.pdf]".into(),
                "Get Could not send \"a.pdf\": an address is not a local file.",
                Vec::new(),
            ),
            (
                "refuses a file marker's inline payload, which cannot become a file row",
                "Get [FILE:data:text/plain;base64,aGVsbG8=]".into(),
                "Get Could not send \"file\": it carries an inline payload, not a file.",
                Vec::new(),
            ),
            (
                "replaces an audio transcription block",
                "[Audio transcription of recording.ogg]: Hello world".into(),
                "🔊 Hello world",
                Vec::new(),
            ),
            (
                "renders every line of a multiline audio transcription under 🔊",
                "[Audio transcription of voice.ogg]: Line one\nLine two".into(),
                "🔊 Line one\nLine two",
                Vec::new(),
            ),
            (
                "audio-transcription format contains Audio and is handled before the [AUDIO:...] pattern",
                "[Audio transcription of msg.ogg]: hi there [AUDIO:recording.ogg]".into(),
                "🔊 hi there",
                vec![snd("recording.ogg")],
            ),
            (
                "replaces a legacy video transcription block",
                "[Video transcription of clip.mp4]: A dog runs across the room.".into(),
                "🎬 A dog runs across the room.",
                Vec::new(),
            ),
            (
                "video-transcription format contains Video and is handled before the [VIDEO:...] pattern",
                "[Video transcription of clip.mp4]: a dog [VIDEO:other.mp4]".into(),
                "🎬 a dog",
                vec![clip("other.mp4")],
            ),
            (
                "separates mixed image/audio/video markers from the text around them",
                "![]() [IMAGE:photo.png] and [AUDIO:recording.ogg] end [VIDEO:video.mp4]".into(),
                "and end",
                vec![img(&photo_str), snd("recording.ogg"), clip("video.mp4")],
            ),
            (
                "drops a bullet whose only content was the picture",
                "- [IMAGE:photo.png]".into(),
                "",
                vec![img(&photo_str)],
            ),
            (
                "keeps the rest of a list whose first bullet was a picture",
                "1. [IMAGE:photo.png]\n2. the rest".into(),
                "2. the rest",
                vec![img(&photo_str)],
            ),
            (
                "leaves content without markers unchanged",
                "Hello world".into(),
                "Hello world",
                Vec::new(),
            ),
            (
                "returns the empty string unchanged",
                String::new(),
                "",
                Vec::new(),
            ),
            (
                "strips a saved image annotation and its blank-line separator",
                format!("[IMAGE:{valid_uri}]\n\n[Saved image: /uploads/img.png]"),
                "",
                vec![picture(Some(&valid_uri), "🖼️ image")],
            ),
            (
                "strips a saved image annotation at the start with no preceding separator",
                "[Saved image: /uploads/img.png]".into(),
                "",
                Vec::new(),
            ),
            (
                "turns a saved video annotation into a visible clip label",
                "Clip [Saved video: /uploads/clip.mp4] here".into(),
                "Clip 🎬 Video: clip.mp4 here",
                Vec::new(),
            ),
            (
                "turns a saved audio annotation into a visible recording label, the way its marker reads",
                "🔊✍️ hello\n[Saved audio: /uploads/upload_1.oga]".into(),
                "🔊✍️ hello\n🎵 upload_1.oga",
                Vec::new(),
            ),
        ];

        for (name, input, text, attachments) in &cases {
            let rendered = preprocess(input, Some(root));
            assert_eq!(rendered.text, *text, "case {name}: text");
            assert_eq!(rendered.attachments, *attachments, "case {name}: files");
        }
    }

    #[test]
    fn pictures_are_extracted_from_the_body() {
        let tmp = tempfile::tempdir().unwrap();
        let img = tmp.path().join("shot.png");
        std::fs::write(&img, b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR").unwrap();
        let img_str = img.to_string_lossy().into_owned();
        let uri = data_uri(&tiny_png(2, 1));
        let marker = picture(Some(&img_str), "🖼️ shot.png");
        let literal = picture(Some("second.png"), "🖼️ second.png");

        // (case, body, text, attachments, (parsed items, the single bullet's text))
        let cases = vec![
            (
                "literal markdown image is extracted",
                "Look ![shot](url) here".to_string(),
                "Look here".to_string(),
                vec![picture(Some("url"), "🖼️ url")],
                (1, None),
            ),
            (
                "picture on its own line keeps the paragraph",
                "before\n![shot](url)\nafter".to_string(),
                "before\nafter".to_string(),
                vec![picture(Some("url"), "🖼️ url")],
                (1, None),
            ),
            (
                "blank lines on either side stay a paragraph gap",
                "before\n\n![shot](url)\n\nafter".to_string(),
                "before\n\nafter".to_string(),
                vec![picture(Some("url"), "🖼️ url")],
                (2, None),
            ),
            (
                "text beside a picture survives the parse",
                format!("8. the body [IMAGE:{uri}]"),
                "8. the body".to_string(),
                vec![picture(Some(&uri), "🖼️ image")],
                (1, Some("the body")),
            ),
            (
                "fenced code keeps its marker and image source",
                format!("```\n[IMAGE:{img_str}]\n![x](y)\n```"),
                format!("```\n[IMAGE:{img_str}]\n![x](y)\n```"),
                Vec::new(),
                (1, None),
            ),
            (
                "indented code keeps its marker and image source",
                format!("    [IMAGE:{img_str}]\n    ![x](y)"),
                format!("    [IMAGE:{img_str}]\n    ![x](y)"),
                Vec::new(),
                (1, None),
            ),
            (
                "inline code span keeps its marker and image source",
                format!("use `[IMAGE:{img_str}]` and `![x](y)` here"),
                format!("use `[IMAGE:{img_str}]` and `![x](y)` here"),
                Vec::new(),
                (1, None),
            ),
            (
                "body order: marker before literal picture",
                format!("[IMAGE:{img_str}] and ![second](second.png)"),
                "and".to_string(),
                vec![marker.clone(), literal.clone()],
                (1, None),
            ),
            (
                "body order: literal picture before marker",
                format!("![second](second.png) and [IMAGE:{img_str}]"),
                "and".to_string(),
                vec![literal, marker],
                (1, None),
            ),
        ];

        for (name, body, text, attachments, (items_expected, bullet)) in cases {
            let rendered = preprocess(&body, Some(tmp.path()));
            assert_eq!(rendered.text, text, "case {name}: text");
            assert_eq!(rendered.attachments, attachments, "case {name}: files");
            if !attachments.is_empty() {
                let survived = rendered.text.contains("![") || rendered.text.contains("[IMAGE:");
                assert!(!survived, "case {name}: marker survived");
            }
            let items: Vec<_> = markdown::parse(&rendered.text).collect();
            assert_eq!(items.len(), items_expected, "case {name}: items {items:?}");
            if let Some(expected) = bullet {
                let bullet_text = only_bullet(name, &items);
                assert_eq!(bullet_text, expected, "case {name}: bullet text");
            }
        }
    }

    #[test]
    fn file_marker_targets_resolve_against_the_workspace() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();

        let relative = resolve_file_marker_target("generated/report.pdf", Some(root)).unwrap();
        let expected = root.join("generated/report.pdf");
        assert_eq!(
            relative, expected,
            "a relative target resolves against the workspace"
        );
        let absolute = root.join("elsewhere/report.pdf");
        let resolved = resolve_file_marker_target(&absolute.to_string_lossy(), Some(root));
        assert_eq!(
            resolved.unwrap(),
            absolute,
            "an absolute target is used as it is"
        );
        let error = resolve_file_marker_target("report.pdf", None).unwrap_err();
        let expected = "Cannot open 'report.pdf': the conversation's workspace is unknown.";
        assert_eq!(error, expected);
    }

    #[test]
    fn reveal_file_marker_refuses_a_target_that_is_not_a_file() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();

        let missing = root.join("generated/report.pdf");
        let error = reveal_file_marker("generated/report.pdf", Some(root)).unwrap_err();
        let expected = format!("File not found: {}", missing.display());
        assert_eq!(
            error, expected,
            "a relative target must resolve against the workspace"
        );

        std::fs::create_dir(root.join("folder")).unwrap();
        let error = reveal_file_marker("folder", Some(root)).unwrap_err();
        let expected = format!("Not a file: {}", root.join("folder").display());
        assert_eq!(error, expected);
    }

    #[test]
    fn decode_data_uri_image_table() {
        // URIs are built before the table: a success case needs a real encoded
        // PNG, and the two over-cap cases a payload/dimension past their cap.
        let valid_uri = data_uri(&tiny_png(2, 1));
        let invalid_base64 = "data:image/png;base64,%%%not-base64%%%".to_string();
        let non_image = format!("data:text/plain;base64,{}", STANDARD.encode(b"hello world"));
        let huge_payload = format!(
            "data:image/png;base64,{}",
            "A".repeat(media_target::MAX_DATA_URI_ENCODED_BYTES + 1)
        );
        let oversized = data_uri(&tiny_png(MAX_IMAGE_LONGEST_SIDE_PX + 1, 1));
        let missing_marker = "data:image/png,AAAA".to_string();
        let mut jbuf = Vec::new();
        ::image::RgbImage::from_pixel(1, 1, ::image::Rgb([255, 0, 0]))
            .write_to(&mut Cursor::new(&mut jbuf), ::image::ImageFormat::Jpeg)
            .expect("test JPEG must encode");
        let mismatched = format!("data:image/png;base64,{}", STANDARD.encode(&jbuf));

        // (case, uri) — every one of these is refused with no raster at all.
        let rejects: &[(&str, String)] = &[
            ("invalid base64", invalid_base64),
            ("non-image bytes", non_image),
            ("oversized payload length", huge_payload),
            ("missing base64 marker", missing_marker),
            ("subtype mismatches bytes", mismatched),
        ];
        for (name, uri) in rejects {
            assert_eq!(decode_data_uri_image(uri), None, "case {name}");
        }

        let png = decode_data_uri_image(&valid_uri);
        let red = vec![255, 0, 0, 255, 255, 0, 0, 255];
        assert_eq!(png, Some((2, 1, red)), "case decodes a solid-red 2×1 PNG");

        // A valid but over-display-cap raster is downscaled to the render cap.
        let downscaled = decode_data_uri_image(&oversized);
        let cap = [255, 0, 0, 255].repeat(MAX_IMAGE_LONGEST_SIDE_PX as usize);
        let expected = Some((MAX_IMAGE_LONGEST_SIDE_PX, 1, cap));
        assert_eq!(downscaled, expected, "case downscales to the cap");
    }

    #[test]
    fn data_uri_image_handle_caches_failures_and_skips_oversized() {
        let huge = "A".repeat(media_target::MAX_DATA_URI_ENCODED_BYTES + 1);
        // (case, uri, cached as a failure) — a decode failure is cached so a corrupt payload is
        // not re-decoded every frame, while an over-cap payload is refused before the cache.
        let cases: &[(&str, String, bool)] = &[
            (
                "decode failure cached",
                "data:image/png;base64,%%%not-base64%%%".to_string(),
                true,
            ),
            (
                "oversized payload not cached",
                format!("data:image/png;base64,{huge}"),
                false,
            ),
        ];
        for (name, uri, failure) in cases {
            assert_eq!(data_uri_image_handle(uri), None, "case {name}: handle");
            let (cached, failed) = {
                let cache = DATA_URI_IMAGE_CACHE.lock().unwrap_poison();
                let failed = matches!(cache.entries.get(uri), Some(CachedImage::Failed));
                (cache.entries.contains_key(uri), failed)
            };
            if *failure {
                assert!(failed, "case {name}: failed decode must be cached");
            } else {
                assert!(!cached, "case {name}: over-cap payload must not be cached");
            }
            assert_eq!(
                data_uri_image_handle(uri),
                None,
                "case {name}: answer is stable"
            );
        }
    }

    /// A cached failure is a hit (no re-decode) and a decode runs without the lock.
    #[test]
    fn cached_image_hits_cached_failures_and_decodes_outside_the_lock() {
        let cache = Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES));
        cache
            .lock()
            .unwrap_poison()
            .insert(String::from("bad"), CachedImage::Failed);
        let handle = cached_image(&cache, "bad", || {
            panic!("a cached failure must not be decoded again")
        });
        assert!(handle.is_none(), "a cached failure yields no handle");

        // `try_lock` fails rather than hanging if the decode still held the lock.
        let handle = cached_image(&cache, "raster", || {
            assert!(cache.try_lock().is_ok(), "decode must run unlocked");
            Some((1, 1, vec![0, 0, 0, 0]))
        });
        assert!(handle.is_some(), "the decoded handle is returned");
        let mut guard = cache.lock().unwrap_poison();
        assert!(matches!(guard.get("raster"), Some(CachedImage::Decoded(_))));
    }
}