mahbot 0.4.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! Channel message enrichment: media marker processing, link enrichment, file
//! operations, and multimodal annotation strategies.
//!
//! This module transforms [`ChannelMessage`] content before it reaches the
//! agent pipeline. It handles:
//! - **Media markers** (`[IMAGE: ...]`, `[AUDIO: ...]`, `[VIDEO: ...]`)
//!   → transcription for audio and video, data URI conversion for images
//!   (multimodal strategy) or strippping with annotation (non-multimodal
//!   strategy)
//! - **Link enrichment** → prepends webpage summaries for URLs in the message
//! - **File operations** → downloading/saving images to workspace, cleaning
//!   up temporary files
//!
//! **Containment invariant**: all local file reads, copies, and deletes are
//! scoped to the daemon's Telegram temp dir. Marker paths outside it
//! (user-typed `[IMAGE:...]`, `[AUDIO:...]`, `[VIDEO:...]` annotations) degrade
//! to plain-text annotations and are never read, transcribed, copied into
//! workspace uploads, or deleted.
//!
//! The public entry points are [`enrich_message`] and [`enrich_links`],
//! re-exported from [`crate::channels`]. The two [`EnrichmentStrategy`]
//! variants control how image media markers are handled: `Multimodal`
//! preserves them as data URIs for vision-capable models, while
//! `NonMultimodal` strips them and adds a textual annotation.

use crate::ChannelMessage;
use crate::tools::browser::BrowserTool;
use crate::util::{MEDIA_MARKER_RE, 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;

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

/// The audio-transcription icon combo (sound written into text). Used both as
/// the transcription-failure fallback and as the annotation for out-of-scope
/// `[AUDIO:...]` markers that must never be read or deleted.
const AUDIO_ICON: &str = "🔊✍️";

/// Transcribe an audio file referenced by a `[AUDIO:...]` marker and return
/// the content to embed in the message: the audio-transcription icon combo
/// (`🔊✍️` — sound written into text) followed by the transcription text.
///
/// The audio file is a pure intermediate artifact — the caller deletes it
/// regardless of outcome (scoped to the Telegram temp dir), so the returned
/// string never contains the file name or path. On failure just the icon
/// combo is returned (no text).
async fn transcribe_audio_marker(path: &str) -> String {
    let path_buf = std::path::PathBuf::from(path);

    // ── Step 1: Try local Qwen3-ASR transcription ────────────────────
    // Default to enabled; only explicitly "false" disables local transcription.
    let use_local = crate::config::CONFIG
        .snapshot()
        .audio_transcription_use_local
        .as_deref()
        != Some("false");

    if use_local {
        match crate::audio::local_transcriber::transcribe_file_async(
            &path_buf,
            // 10-minute timeout for enrichment path — attached audio can be
            // arbitrarily long (voice memos, meeting recordings, etc.).
            crate::audio::local_transcriber::INFERENCE_TIMEOUT,
        )
        .await
        {
            Ok(text) => {
                tracing::debug!("Local audio transcription succeeded");
                let text = text.trim();
                return if text.is_empty() {
                    AUDIO_ICON.to_string()
                } else {
                    format!("{AUDIO_ICON} {text}")
                };
            }
            Err(e) => {
                tracing::warn!(error = %e, "Local audio transcription failed");
            }
        }
    }

    // ── Step 2: Icon-only fallback (no text, no filename) ────────────
    tracing::warn!("Audio transcription unavailable");
    AUDIO_ICON.to_string()
}

/// 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) into the workspace `uploads/` directory so
/// the agent can reference it via tool calls. Returns `None` when no uploads
/// dir is available or the copy fails.
async fn save_media_to_workspace(
    media_path: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    label: &str,
    fallback_ext: &str,
) -> Option<SavedMedia> {
    let dir = uploads_dir?;
    tokio::fs::create_dir_all(dir).await.ok()?;
    let ext = media_path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or(fallback_ext);
    let timestamp = crate::util::unix_millis();
    let dest_name = format!("upload_{timestamp}.{ext}");
    let dest_path = dir.join(&dest_name);
    tokio::fs::copy(media_path, &dest_path).await.ok()?;
    Some(SavedMedia {
        annotation: format!("[Saved {label}: {}]", dest_path.display()),
        dest: dest_path,
    })
}

/// Strategy for message enrichment, determining how each media marker kind
/// (IMAGE, AUDIO, VIDEO) is handled.
///
/// Local media reads, copies, transcriptions, and deletes are scoped to the
/// daemon's Telegram temp dir (see module docs); out-of-scope marker paths
/// degrade to plain-text annotations.
#[derive(Debug, Clone)]
pub enum EnrichmentStrategy {
    /// Multimodal mode:
    /// - IMAGE markers are converted to base64 data URIs (for vision model)
    /// - AUDIO markers are transcribed to text
    /// - VIDEO markers are copied to workspace `uploads/`, replaced with a
    ///   plain-text `[Saved video: path]` annotation, and transcribed to a
    ///   text description (media transcriber) so the Artist can understand the
    ///   clip and feed it into the video-edit flow
    ///
    /// When `workspace_path` is provided, copies of media files are saved to
    /// `uploads/` for agent tool references. Reads, copies, and cleanup are
    /// scoped to the daemon's Telegram temp dir.
    Multimodal {
        workspace_path: Option<std::path::PathBuf>,
    },
    /// Non-multimodal mode: all media markers are transcribed/extracted to
    /// text annotations and the raw markers are stripped from the content.
    /// Transcription (a read) and cleanup only happen for files in the
    /// daemon's Telegram temp dir; out-of-scope markers become plain
    /// attachment annotations.
    NonMultimodal,
}

/// Outcome of processing an IMAGE marker in multimodal mode.
enum MultimodalImageAction {
    /// 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 the daemon's Telegram temp
    /// dir (copied/read) — out-of-scope and missing files are never deleted.
    Replace {
        replacement: String,
        upload_annotation: Option<String>,
        delete_temp: bool,
    },
}

/// Handle an IMAGE marker in multimodal mode — convert to data URI, invalid
/// reference, or (for out-of-scope paths) a plain-text annotation. Saves a
/// workspace copy if `uploads_dir` is available. The returned action's
/// `delete_temp` tells the caller whether the source temp file was consumed
/// from the Telegram temp dir and may be cleaned up.
async fn handle_multimodal_image(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
) -> MultimodalImageAction {
    // HTTP/HTTPS URLs can be sent as-is.
    if is_http_url(path) {
        return MultimodalImageAction::Keep;
    }

    let invalid_ref = format!("[Invalid image reference: {path}]");
    if !path_obj.exists() || !path_obj.is_file() {
        tracing::warn!(%path, "Image file not found for multimodal enrichment");
        return MultimodalImageAction::Replace {
            replacement: invalid_ref,
            upload_annotation: None,
            delete_temp: false,
        };
    }

    // Containment: only Telegram-temp-dir files may be read, copied, or deleted.
    if !is_under_telegram_files(path_obj).await {
        tracing::warn!(%path, "Image path outside telegram temp dir — annotating without copy");
        return MultimodalImageAction::Replace {
            replacement: format!("[Image: {} attached]", file_name_or_path(path)),
            upload_annotation: None,
            delete_temp: false,
        };
    }

    // Save a copy to workspace uploads so the agent can reference it
    let saved = save_media_to_workspace(path_obj, uploads_dir, "image", "png")
        .await
        .map(|saved| saved.annotation);

    // Convert to data URI for the API request
    let replacement = match crate::util::local_image_to_data_uri(path_obj).await {
        Ok(data_uri) => format!("[IMAGE:{data_uri}]"),
        Err(e) => {
            tracing::warn!(%path, error = %e, "Failed to convert image to data URI");
            invalid_ref
        }
    };

    MultimodalImageAction::Replace {
        replacement,
        upload_annotation: saved,
        delete_temp: true,
    }
}

/// Whether a local media path resolves inside the daemon's Telegram
/// attachment temp dir — the only legitimate source of inbound media
/// (video clips and voice messages). Arbitrary marker paths must never
/// reach workspace uploads or be deleted.
async fn is_under_telegram_files(path: &std::path::Path) -> bool {
    let Ok(canonical) = tokio::fs::canonicalize(path).await else {
        return false;
    };
    let root = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
    let Ok(canonical_root) = tokio::fs::canonicalize(&root).await else {
        return false;
    };
    crate::tools::path::is_path_under_roots(&canonical, &[canonical_root])
}

/// Outcome of processing a VIDEO marker in multimodal mode: the replacement
/// text, whether the source temp file was copied into the workspace uploads
/// (so the Artist can feed the clip to the video-edit flow) and can be cleaned
/// up, and the optional "[Video transcription of <name>]: <text>" annotation
/// (prepended as an annotation block by the caller). HTTP(S) URLs become
/// plain-text references; missing files, out-of-scope paths, and copy failures
/// degrade to annotations while preserving the source file.
struct MultimodalVideoAction {
    replacement: String,
    delete_temp: bool,
    transcription: Option<String>,
}

impl MultimodalVideoAction {
    /// Plain annotation: no workspace copy, no transcription.
    fn annotation(replacement: String) -> Self {
        Self {
            replacement,
            delete_temp: false,
            transcription: None,
        }
    }
}

async fn handle_multimodal_video(
    path: &str,
    path_obj: &std::path::Path,
    uploads_dir: Option<&std::path::Path>,
    workspace: &str,
) -> MultimodalVideoAction {
    if is_http_url(path) {
        return MultimodalVideoAction::annotation(format!("[Video: {path}]"));
    }
    if !path_obj.exists() || !path_obj.is_file() {
        tracing::warn!(%path, "Video file not found for multimodal enrichment");
        return MultimodalVideoAction::annotation(format!("[Invalid video reference: {path}]"));
    }
    if !is_under_telegram_files(path_obj).await {
        tracing::warn!(%path, "Video path outside telegram temp dir — annotating without copy");
        return MultimodalVideoAction::annotation(format!(
            "[Video: {} attached]",
            file_name_or_path(path)
        ));
    }
    if let Some(saved) = save_media_to_workspace(path_obj, uploads_dir, "video", "mp4").await {
        // Transcribe the persistent workspace copy — never the temp file
        // (deleted after a successful copy). The annotation keeps the original
        // Telegram filename; fail-open: any failure degrades to the plain
        // [Saved video: ...] annotation.
        let transcription =
            transcribe_saved_video(&saved.dest, file_name_or_path(path), workspace).await;
        return MultimodalVideoAction {
            replacement: saved.annotation,
            delete_temp: true,
            transcription,
        };
    }
    // Copy failed — annotate and preserve the temp file.
    MultimodalVideoAction::annotation(format!("[Video: {} attached]", file_name_or_path(path)))
}

/// Transcribe a saved workspace video copy for the Artist, returning the
/// "[Video transcription of <name>]: <text>" annotation (using the original
/// source `file_name`). Fail-open: returns `None` (plain annotation) when the
/// transcription fails (unavailable transcriber, unsupported format, upload
/// or model error, timeout, empty output) — the overall timeout lives inside
/// [`transcribe_video_file`](crate::providers::transcribe_video_file),
/// bounding both callers. `workspace` names the workspace for telemetry and
/// the live non-agent call row (the inbound path has no agent card).
async fn transcribe_saved_video(
    path: &std::path::Path,
    file_name: &str,
    workspace: &str,
) -> Option<String> {
    let text = crate::providers::transcribe_video_file(path, Some(workspace)).await?;
    Some(format!("[Video transcription of {file_name}]: {text}"))
}

/// Handle an IMAGE marker in non-multimodal mode — transcribe to text
/// description or fall back to a generic attachment annotation.
async fn handle_non_multimodal_image(
    path_obj: &std::path::Path,
    file_name: &str,
    workspace: &str,
) -> String {
    if let Some(ref transcriber) = crate::providers::media_transcriber() {
        match transcribe_image_file(path_obj, transcriber, workspace).await {
            Ok(description) => format!("[Image: {description}]"),
            Err(e) => {
                tracing::warn!(path = %path_obj.display(), error = %e, "Image transcription failed");
                format!("[Image: {file_name} attached]")
            }
        }
    } else {
        format!("[Image: {file_name} attached]")
    }
}

/// Process all media markers (`[IMAGE:...]`, `[AUDIO:...]`, `[VIDEO:...]`)
/// in a single pass. Each marker kind is handled according to the strategy:
///
/// | Kind | Multimodal | NonMultimodal |
/// |------|-----------|---------------|
/// | IMAGE | data URI conversion, workspace copy | text transcription |
/// | AUDIO | transcription | transcription |
/// | VIDEO | workspace copy + `[Saved video: path]` + transcription | text annotation |
///
/// After processing, markers that were handled are stripped from the content
/// and annotations are prepended. Temp files are cleaned up after processing,
/// scoped to the daemon's Telegram temp dir — out-of-scope marker paths are
/// never read, copied, or deleted and degrade to plain-text annotations.
// Marker dispatch hub (3 kinds × 2 strategies); per-kind handling is extracted
// into the handler functions above, keeping this loop flat on purpose.
#[expect(clippy::too_many_lines)]
pub async fn enrich_message(msg: &mut ChannelMessage, strategy: &EnrichmentStrategy) {
    let mut annotations: Vec<String> = Vec::new();
    let mut result = msg.content.clone();
    // Accumulates upload path annotations across the for-loop below.
    // Only ever populated in Multimodal/IMAGE branch — always empty otherwise.
    let mut upload_annotations: Vec<String> = Vec::new();

    // Temp files to remove after the loop — only ever queued for files under
    // the daemon's Telegram temp dir, so user-typed markers can never delete
    // arbitrary local files.
    let mut files_to_delete: Vec<std::path::PathBuf> = Vec::new();

    let uploads_dir = match strategy {
        EnrichmentStrategy::Multimodal { workspace_path } => {
            workspace_path.as_ref().map(|p| p.join("uploads"))
        }
        EnrichmentStrategy::NonMultimodal => None,
    };

    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 {
            "IMAGE" => match strategy {
                EnrichmentStrategy::Multimodal { .. } => {
                    match handle_multimodal_image(path, path_obj, uploads_dir.as_deref()).await {
                        MultimodalImageAction::Keep => {
                            // HTTP/HTTPS URL — no local file to clean up.
                        }
                        MultimodalImageAction::Replace {
                            replacement,
                            upload_annotation,
                            delete_temp,
                        } => {
                            result = result.replacen(whole.as_str(), &replacement, 1);
                            if let Some(ann) = upload_annotation {
                                upload_annotations.push(ann);
                            }
                            // Local IMAGE temp files are cleaned up only when
                            // consumed from the daemon's Telegram temp dir (delete_temp).
                            if delete_temp {
                                files_to_delete.push(path_obj.to_path_buf());
                            }
                        }
                    }
                }
                EnrichmentStrategy::NonMultimodal => {
                    let file_name = file_name_or_path(path);
                    // Containment: only Telegram-temp-dir files are transcribed or deleted.
                    let in_scope = is_under_telegram_files(path_obj).await;
                    let annotation = if in_scope {
                        handle_non_multimodal_image(path_obj, file_name, &msg.workspace).await
                    } else {
                        tracing::warn!(%path, "Image path outside telegram temp dir — annotating without transcription");
                        format!("[Image: {file_name} attached]")
                    };
                    annotations.push(annotation);
                    if in_scope {
                        files_to_delete.push(path_obj.to_path_buf());
                    }
                }
            },
            "AUDIO" => {
                // Containment: only Telegram-temp-dir files are transcribed or
                // deleted; out-of-scope markers degrade to the icon only.
                if is_under_telegram_files(path_obj).await {
                    annotations.push(transcribe_audio_marker(path).await);
                    files_to_delete.push(path_obj.to_path_buf());
                } else {
                    tracing::warn!(%path, "Audio path outside telegram temp dir — annotating without transcription");
                    annotations.push(AUDIO_ICON.to_string());
                }
            }
            "VIDEO" => match strategy {
                EnrichmentStrategy::Multimodal { .. } => {
                    let MultimodalVideoAction {
                        replacement,
                        delete_temp,
                        transcription,
                    } = handle_multimodal_video(
                        path,
                        path_obj,
                        uploads_dir.as_deref(),
                        &msg.workspace,
                    )
                    .await;
                    result = result.replacen(whole.as_str(), &replacement, 1);
                    if let Some(annotation) = transcription {
                        annotations.push(annotation);
                    }
                    if delete_temp {
                        files_to_delete.push(path_obj.to_path_buf());
                    }
                }
                EnrichmentStrategy::NonMultimodal => {
                    annotations.push(format!("[Video: {} attached]", file_name_or_path(path)));
                    // Containment: only Telegram-temp-dir files are deleted.
                    if is_under_telegram_files(path_obj).await {
                        files_to_delete.push(path_obj.to_path_buf());
                    }
                }
            },
            // NOTE: If a new marker kind is added to MEDIA_MARKER_RE in
            // util/mod.rs, a corresponding arm MUST be added here for enrichment
            // behavior (transcription, annotation, etc.). The unified stripping
            // at the end of this function handles marker removal: in multimodal mode,
            // only IMAGE markers are preserved (all others are stripped); in
            // non-multimodal mode, all markers are stripped. The `_ =>` arm is
            // unreachable for well-formed markers (the regex only matches
            // IMAGE|AUDIO|VIDEO), but exists as a defensive guard during development.
            _ => {
                tracing::warn!(kind, %path, "Unknown media marker kind");
            }
        }
    }

    // ── File cleanup ────────────────────────────────────────────────
    // Delete queued temp files (only Telegram-temp-dir paths are ever queued).
    // Deletion errors are logged (not silently discarded).
    for file_path in &files_to_delete {
        if let Err(e) = tokio::fs::remove_file(file_path).await {
            tracing::warn!(
                path = %file_path.display(),
                error = %e,
                "Failed to delete temp file after enrichment"
            );
        }
    }

    // ── Multimodal-specific post-processing ──
    // Append upload path annotations so the model can reference saved files.
    // `upload_annotations` accumulates across the for-loop; it is only ever
    // populated in Multimodal mode when a local IMAGE file was successfully
    // copied to the workspace uploads directory.
    if !upload_annotations.is_empty() {
        let annotation_block = upload_annotations.join("\n");
        let _ = write!(result, "\n\n{annotation_block}");
    }

    // ── Marker stripping and annotation prepending ──
    // Strip media markers from the enriched content. In multimodal mode,
    // IMAGE markers are preserved (needed for vision API integration via
    // to_message_content); all other markers are stripped. In non-multimodal
    // mode, all markers are stripped. The MEDIA_MARKER_PATTERN constant in
    // util/mod.rs is the single canonical source of truth for the marker
    // pattern; both MEDIA_MARKER_RE (case-sensitive) and TELEGRAM_MEDIA_MARKER_RE
    // (case-insensitive) are built from it to stay in sync.
    //
    // Note: using matches!() with a boolean guard means a future
    // EnrichmentStrategy variant would silently default to marker-stripping
    // (conservative behavior) rather than producing a compile error. This is
    // intentional — stripping unknown markers is the safe default.
    let keep_image = matches!(strategy, EnrichmentStrategy::Multimodal { .. });
    let cleaned = MEDIA_MARKER_RE
        .replace_all(&result, |caps: &regex::Captures| {
            if keep_image && parse_media_marker(caps).0 == "IMAGE" {
                caps.get_match().as_str().to_string()
            } else {
                String::new()
            }
        })
        .to_string();
    let cleaned = cleaned.trim().to_string();

    // ── Prepend text annotations (if any) ──
    // These are accumulated text descriptions for non-multimodal image files,
    // transcribed AUDIO content, and VIDEO annotations.
    msg.content = if annotations.is_empty() {
        cleaned
    } else {
        let prefix = annotations.join("\n");
        if cleaned.is_empty() {
            prefix
        } else {
            format!("{prefix}\n\n{cleaned}")
        }
    };
}

/// Whether `content` carries `[AUDIO:...]` markers and no other media markers.
///
/// Used by the caller to decide when enriched content (icon + transcription)
/// can be persisted to chat history instead of the raw original: audio-only
/// messages never leak temp file paths (raw audio markers) or embed image
/// data URIs (multimodal IMAGE markers). Mixed audio+image/audio+video
/// messages fall back to the raw persist — the raw `[AUDIO:path]` marker
/// still reaches chat history for those (data-URI avoidance takes precedence).
/// Purely syntactic: a hand-typed `[AUDIO:<URL>]` marker qualifies too, so its
/// icon-only enriched content is persisted and the URL is dropped.
#[must_use]
pub fn has_only_audio_markers(content: &str) -> bool {
    let mut has_audio = false;
    for caps in MEDIA_MARKER_RE.captures_iter(content) {
        if parse_media_marker(&caps).0 == "AUDIO" {
            has_audio = true;
        } else {
            return false;
        }
    }
    has_audio
}

/// Transcribe a local image file into a text description.
async fn transcribe_image_file(
    path: &std::path::Path,
    transcriber: &crate::providers::transcribe::MediaTranscriber,
    workspace: &str,
) -> anyhow::Result<String> {
    if !path.exists() || !path.is_file() {
        anyhow::bail!("image file not found: {}", path.display());
    }

    let data_uri = crate::util::local_image_to_data_uri(path).await?;
    transcriber.transcribe(&data_uri, Some(workspace)).await
}

/// Extract all unique URLs from message text.
///
/// Strips common trailing punctuation (commas, periods, closing brackets,
/// colons, semicolons, exclamation/question marks) that naturally appears
/// around URLs in prose.
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();
        // Strip trailing punctuation that isn't part of the actual URL
        while url.ends_with(&[',', '.', ')', ']', '}', ':', ';', '!', '?'][..]) {
            url.pop();
        }
        if seen.insert(url.clone()) {
            result.push(url);
        }
    }
    result
}

/// Enrich a message by prepending link summaries for any URLs found in the text.
///
/// If no URLs are found, the original message is returned unchanged.
/// Links are fetched concurrently using the shared `BrowserTool` — each URL
/// gets its own isolated session tab that is closed after text extraction.
pub async fn enrich_links(content: &str) -> Cow<'_, str> {
    // Truncate very long snippets to keep messages manageable.
    const MAX_TEXT_LEN: 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 cheap
    // in-memory check short-circuits the `--version` spawn below while the
    // daemon is confirmed down. A stale/unknown state passes optimistically
    // and the concurrent fetch tasks re-discover liveness (bounded by the
    // probe timeout) without failing the message.
    if !(crate::tools::browser_daemon::is_advertised()
        && matches!(
            crate::tools::browser_daemon::cli_probe().await,
            crate::tools::browser_daemon::CliStatus::Available
        ))
    {
        tracing::debug!("chrome-use not available, skipping link enrichment");
        return Cow::Borrowed(content);
    }

    // Fetch all URLs concurrently.
    let browser = std::sync::Arc::new(BrowserTool::default());
    let mut tasks = Vec::with_capacity(urls.len());
    for (i, url) in urls.iter().enumerate() {
        let url = url.clone();
        let tab = format!("link-enricher-{i}");
        let browser = std::sync::Arc::clone(&browser);
        tasks.push(tokio::spawn(async move {
            let result = browser.fetch_page_text(&url, &tab).await;
            // Close the tab (best-effort) regardless of fetch outcome.
            browser.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() {
                    // Blank/empty page — don't insert an empty snippet.
                    tracing::debug!(url, "Link enricher: page text is empty, skipping snippet");
                    continue;
                }
                let snippet = if body_text.len() > MAX_TEXT_LEN {
                    format!("{}", crate::util::truncate_bytes(&body_text, MAX_TEXT_LEN))
                } else {
                    body_text
                };
                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::*;

    #[test]
    fn extract_urls_finds_http_and_https() {
        let urls = extract_urls("Check https://example.com and http://test.org/page for info");
        assert_eq!(urls, vec!["https://example.com", "http://test.org/page"]);
    }

    #[test]
    fn extract_urls_deduplicates() {
        let urls = extract_urls("Visit https://example.com and https://example.com again");
        assert_eq!(urls.len(), 1);
    }

    #[test]
    fn extract_urls_strips_trailing_punctuation() {
        let urls = extract_urls("See https://example.com, and https://test.org.");
        assert_eq!(urls, vec!["https://example.com", "https://test.org"]);
    }

    #[test]
    fn extract_urls_handles_urls_in_parens() {
        let urls = extract_urls("(https://example.com) and [https://test.org]");
        assert_eq!(urls, vec!["https://example.com", "https://test.org"]);
    }

    #[tokio::test]
    async fn enrich_links_returns_borrowed_when_no_urls() {
        let content = "Hello, this is a plain message without any URLs.";
        let result = enrich_links(content).await;
        // No URLs → should borrow the input, not allocate a new String.
        assert!(matches!(result, Cow::Borrowed(_)));
        assert_eq!(result.as_ref(), content);
    }

    // ── Enrichment strategy tests ─────────────────────────────────────

    /// Helper: quick ChannelMessage for enrichment tests.
    fn test_msg(content: &str) -> ChannelMessage {
        ChannelMessage {
            user_name: "test".into(),
            reply_target: "test".into(),
            content: content.to_string(),
            channel: "test".into(),
            workspace: "test".into(),
            optimistic_id: None,
            callback_query_id: None,
        }
    }

    /// 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() {
        let tg_dir = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
        tokio::fs::create_dir_all(&tg_dir).await.unwrap();
    }

    /// Set up an out-of-scope fixture: a unique scratch dir under the system
    /// temp dir (outside the Telegram temp dir) containing a fake workspace
    /// (`ws_path`) and a single 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 = std::env::temp_dir().join(format!("{prefix}_{}", std::process::id()));
        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)
    }

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

    #[tokio::test]
    async fn enrich_multimodal_image_file_not_found() {
        let mut msg = test_msg("Here is [IMAGE:/tmp/nonexistent_xyz_img.png] an image");
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: None,
        };
        enrich_message(&mut msg, &strategy).await;
        assert!(
            msg.content
                .contains("[Invalid image reference: /tmp/nonexistent_xyz_img.png]")
        );
    }

    #[tokio::test]
    async fn enrich_multimodal_audio_annotation_and_strip() {
        let mut msg = test_msg("Listen [AUDIO:/tmp/audio_xyz.mp3] to this");
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: None,
        };
        enrich_message(&mut msg, &strategy).await;
        // AUDIO marker stripped; annotation prepended (icon-only fallback since
        // no audio transcriber is configured in the test environment)
        assert!(
            msg.content.contains("🔊✍️"),
            "Audio annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[AUDIO:"),
            "AUDIO marker must be stripped"
        );
        // No file name may survive in any form
        assert!(
            !msg.content.contains("audio_xyz"),
            "Audio temp file name must not appear, got: {}",
            msg.content
        );
        // The original text is preserved
        assert!(msg.content.contains("Listen"), "Original text preserved");
        assert!(msg.content.contains("to this"), "Original text preserved");
    }

    #[tokio::test]
    async fn enrich_multimodal_image_valid_file_converts_to_data_uri_and_deletes_temp() {
        // The fixture must live under the daemon's Telegram temp dir to be in
        // scope for reading (data URI) and cleanup.
        let tg_dir = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
        tokio::fs::create_dir_all(&tg_dir).await.unwrap();
        let tmp = tg_dir.join(format!("test_enrich_img_{}.png", std::process::id()));
        let png_header: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0x60, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE7, 0x21, 0x33, 0x7C,
            0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        tokio::fs::write(&tmp, png_header).await.unwrap();
        let path_str = tmp.to_string_lossy().to_string();

        let mut msg = test_msg(&format!("Image: [IMAGE:{path_str}]"));
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: None,
        };
        enrich_message(&mut msg, &strategy).await;

        // Marker replaced with data URI
        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"
        );
        // Temp file deleted
        assert!(
            !tmp.exists(),
            "Temp image file must be deleted after enrichment"
        );
    }

    #[tokio::test]
    async fn enrich_multimodal_image_with_workspace_creates_upload_annotation() {
        let tmp_root = std::env::temp_dir().join(format!("test_enrich_ws_{}", std::process::id()));
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        // The fixture must live under the daemon's Telegram temp dir to be in
        // scope for reading (data URI) and cleanup.
        let tg_dir = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
        tokio::fs::create_dir_all(&tg_dir).await.unwrap();
        let tmp_img = tg_dir.join(format!("test_enrich_ws_img_{}.png", std::process::id()));
        let png_header: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0x60, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE7, 0x21, 0x33, 0x7C,
            0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        tokio::fs::write(&tmp_img, png_header).await.unwrap();
        let img_path_str = tmp_img.to_string_lossy().to_string();

        let mut msg = test_msg(&format!("Image: [IMAGE:{img_path_str}]"));
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: Some(ws_path.clone()),
        };
        enrich_message(&mut msg, &strategy).await;

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

    #[tokio::test]
    async fn enrich_non_multimodal_image_annotation() {
        let mut msg = test_msg("Here is [IMAGE:/tmp/photo_xyz.jpg] from the camera");
        enrich_message(&mut msg, &EnrichmentStrategy::NonMultimodal).await;
        // IMAGE marker stripped, annotation prepended — the path is outside
        // the daemon's Telegram temp dir, so it gets the plain attachment
        // annotation without a transcription attempt.
        assert!(
            msg.content.contains("[Image:"),
            "Image annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[IMAGE:"),
            "IMAGE marker must be stripped"
        );
        assert!(msg.content.contains("from the camera"));
    }

    #[tokio::test]
    async fn enrich_non_multimodal_http_image_url_passthrough() {
        let mut msg = test_msg("Check [IMAGE:https://example.com/photo.png] online");
        enrich_message(&mut msg, &EnrichmentStrategy::NonMultimodal).await;
        // HTTP image URL treated as attachment, annotation prepended
        assert!(
            msg.content.contains("[Image:"),
            "Image annotation must be present despite HTTP URL"
        );
        assert!(
            !msg.content.contains("[IMAGE:"),
            "IMAGE marker must be stripped"
        );
    }

    #[tokio::test]
    async fn enrich_non_multimodal_video_annotation() {
        let mut msg = test_msg("Watch [VIDEO:/tmp/clip_xyz.mp4] this video");
        enrich_message(&mut msg, &EnrichmentStrategy::NonMultimodal).await;
        // VIDEO marker stripped, generic annotation prepended
        assert!(
            msg.content.contains("[Video: clip_xyz.mp4 attached]"),
            "Video annotation must be present, got: {}",
            msg.content
        );
        assert!(
            !msg.content.contains("[VIDEO:"),
            "VIDEO marker must be stripped"
        );
    }

    #[tokio::test]
    async fn enrich_multimodal_video_with_workspace_copies_and_annotates() {
        let tmp_root =
            std::env::temp_dir().join(format!("test_enrich_video_ws_{}", std::process::id()));
        let ws_path = tmp_root.join("myworkspace");
        tokio::fs::create_dir_all(&ws_path).await.unwrap();

        // Only clips in the daemon's Telegram temp dir are eligible for copy.
        let tg_dir = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
        tokio::fs::create_dir_all(&tg_dir).await.unwrap();
        let tmp_video = tg_dir.join(format!("test_enrich_video_{}.mp4", std::process::id()));
        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,
        ];
        tokio::fs::write(&tmp_video, mp4_header).await.unwrap();
        let video_path_str = tmp_video.to_string_lossy().to_string();

        let mut msg = test_msg(&format!("Edit this clip: [VIDEO:{video_path_str}]"));
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: Some(ws_path.clone()),
        };
        enrich_message(&mut msg, &strategy).await;

        // Marker replaced with a [Saved video: ...] annotation pointing at the
        // workspace uploads copy so the Artist can feed it to video_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"
        );
        // Temp file deleted after the workspace copy
        assert!(
            !tmp_video.exists(),
            "Temp video file must be deleted after enrichment"
        );
        // Cleanup
        let _ = tokio::fs::remove_file(&tmp_video).await;
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_multimodal_video_outside_telegram_files_annotates_without_copy() {
        // An injected marker pointing at an arbitrary readable file must not
        // be copied into uploads (exfiltration vector) or deleted.
        let (tmp_root, ws_path, arbitrary) =
            out_of_scope_fixture("test_enrich_video_outside", "secret.txt", b"top secret").await;
        let marker = format!("Edit [VIDEO:{}]", arbitrary.display());

        let mut msg = test_msg(&marker);
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: Some(ws_path.clone()),
        };
        enrich_message(&mut msg, &strategy).await;

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

    #[tokio::test]
    async fn enrich_multimodal_image_outside_telegram_files_annotates_without_read_or_copy() {
        // An injected marker pointing at an arbitrary readable file must not
        // be read into model context (data URI), 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);
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: Some(ws_path.clone()),
        };
        enrich_message(&mut msg, &strategy).await;

        assert!(
            msg.content.contains("[Image: secret.png attached]"),
            "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"
        );
        // Cleanup
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_non_multimodal_image_outside_telegram_files_annotates_without_read_or_delete() {
        // An injected marker pointing at an arbitrary readable file must not
        // be transcribed (read) or deleted — the key regression: the old code
        // deleted it.
        let (tmp_root, _ws_path, arbitrary) = out_of_scope_fixture(
            "test_enrich_img_nonmm",
            "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, &EnrichmentStrategy::NonMultimodal).await;

        assert!(
            msg.content.contains("[Image: secret.png attached]"),
            "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("[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"
        );
        // Cleanup
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_non_multimodal_video_outside_telegram_files_annotates_without_delete() {
        // An injected marker pointing at an arbitrary readable file must not
        // be deleted by the non-multimodal cleanup pass.
        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, &EnrichmentStrategy::NonMultimodal).await;

        assert!(
            msg.content.contains("[Video: secret.mp4 attached]"),
            "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"
        );
        // Cleanup
        let _ = tokio::fs::remove_dir_all(&tmp_root).await;
    }

    #[tokio::test]
    async fn enrich_multimodal_video_http_url_kept_as_plain_text() {
        let mut msg = test_msg("Edit [VIDEO:https://example.com/clip.mp4] this");
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: None,
        };
        enrich_message(&mut msg, &strategy).await;
        // HTTP URL video reference is preserved as plain text (no marker strip)
        assert!(
            msg.content
                .contains("[Video: https://example.com/clip.mp4]"),
            "HTTP video URL must be kept as plain-text reference, got: {}",
            msg.content
        );
        assert!(!msg.content.contains("[VIDEO:"));
    }

    #[tokio::test]
    async fn enrich_non_multimodal_all_markers_stripped_and_annotated() {
        // The `_xyz`-suffixed paths are outside the daemon's Telegram temp dir,
        // so IMAGE/AUDIO never attempt transcription (a read) and no cleanup is
        // queued — all three degrade to their plain-text annotations.
        let mut msg = test_msg(
            "Check [IMAGE:/tmp/img_xyz.png] and listen [AUDIO:/tmp/audio_xyz.mp3] and watch [VIDEO:/tmp/vid_xyz.mp4]",
        );
        enrich_message(&mut msg, &EnrichmentStrategy::NonMultimodal).await;
        // All markers stripped
        assert!(!msg.content.contains("[IMAGE:"));
        assert!(!msg.content.contains("[AUDIO:"));
        assert!(!msg.content.contains("[VIDEO:"));
        // Annotations for all three
        assert!(msg.content.contains("[Image:"), "Image annotation missing");
        assert!(msg.content.contains("🔊✍️"), "Audio annotation missing");
        assert!(msg.content.contains("[Video:"), "Video annotation missing");
        // Original text preserved
        assert!(msg.content.contains("Check"));
        assert!(msg.content.contains("listen"));
        assert!(msg.content.contains("watch"));
    }

    #[tokio::test]
    async fn enrich_audio_file_deleted_on_failure() {
        // Only files in the daemon's Telegram temp dir are eligible for
        // cleanup (user-typed markers must never delete arbitrary files).
        let tg_dir = std::env::temp_dir().join(crate::util::TELEGRAM_FILES_DIR);
        tokio::fs::create_dir_all(&tg_dir).await.unwrap();
        let tmp = tg_dir.join(format!("test_enrich_audio_{}.mp3", std::process::id()));
        tokio::fs::write(&tmp, b"fake audio content").await.unwrap();
        let path_str = tmp.to_string_lossy().to_string();

        let mut msg = test_msg(&format!("Audio: [AUDIO:{path_str}]"));
        enrich_message(&mut msg, &EnrichmentStrategy::NonMultimodal).await;

        // Temp file must be deleted even when transcription fails — the audio
        // file is a pure intermediate artifact (no transcriber in tests).
        assert!(
            !tmp.exists(),
            "Audio temp file must be deleted on transcription failure"
        );
        // Defensive cleanup in case the assertion above fails.
        let _ = tokio::fs::remove_file(&tmp).await;
    }

    #[tokio::test]
    async fn enrich_multimodal_combined_image_preserved_audio_annotated() {
        let msg_content = "Here [IMAGE:https://example.com/img.png] and [AUDIO:/tmp/sound_xyz.mp3]";
        let mut msg = test_msg(msg_content);
        let strategy = EnrichmentStrategy::Multimodal {
            workspace_path: None,
        };
        enrich_message(&mut msg, &strategy).await;

        // IMAGE http URL kept
        assert!(
            msg.content.contains("[IMAGE:https://example.com/img.png]"),
            "IMAGE with http URL must be preserved in multimodal mode, got: {}",
            msg.content
        );
        // AUDIO marker stripped, annotation present
        assert!(
            msg.content.contains("🔊✍️"),
            "Audio annotation must be present"
        );
        assert!(
            !msg.content.contains("[AUDIO:"),
            "AUDIO marker must be stripped"
        );
    }

    async fn assert_no_markers_unchanged(strategy: EnrichmentStrategy, content: &str) {
        let mut msg = test_msg(content);
        let original = msg.content.clone();
        enrich_message(&mut msg, &strategy).await;
        assert_eq!(msg.content, original, "No markers = no changes");
    }

    #[tokio::test]
    async fn enrich_multimodal_no_annotations_when_no_markers() {
        assert_no_markers_unchanged(
            EnrichmentStrategy::Multimodal {
                workspace_path: None,
            },
            "Just a plain message with no markers",
        )
        .await;
    }

    #[tokio::test]
    async fn enrich_non_multimodal_no_annotations_when_no_markers() {
        assert_no_markers_unchanged(
            EnrichmentStrategy::NonMultimodal,
            "Plain text, no markers here",
        )
        .await;
    }
}