mindfork 0.11.0

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

use std::time::Duration;

use super::subagent::{Script, ScriptRecorder, load, text};
use super::*;
use crate::entities::attachment::{AttachMode, Attachment};
use crate::entities::chat_file::{ChatFile, FileOrigin};
use crate::entities::profile::ToolId;
use crate::features::file_command::{FileProgress, OpenedInstead};
use crate::features::tools::meta::ToolGroup;
use crate::features::tools::{ChatEffect, Tool, ToolContext, ToolImage, ToolOutcome};
use crate::shared::api::VisionSupport;
use crate::shared::api::contract::{ChatStream, FinishReason, ToolCallDelta};

const PNG: &[u8] = b"\x89PNG\r\n\x1a\nnot-really-pixels";

fn listing(name: &str) -> ChatFile {
    ChatFile::new(name, FileOrigin::Sandbox, PNG)
}

/// A bare orchestrator's one open chat; returns its id.
fn open_chat(orch: &mut Orchestrator) -> Uuid {
    let profile = Profile::new("P", "sys");
    let chat = Chat::from_profile(&profile, "t");
    let id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(id);
    id
}

fn files_of(orch: &Orchestrator, chat_id: Uuid) -> Vec<String> {
    orch.chats
        .iter()
        .find(|c| c.id == chat_id)
        .expect("the chat")
        .files
        .iter()
        .map(|f| f.name.clone())
        .collect()
}

/// What the bare orchestrator has emitted so far.
fn drain(rx: &mut UnboundedReceiver<AppEvent>) -> Vec<AppEvent> {
    std::iter::from_fn(|| rx.try_recv().ok()).collect()
}

fn saved_notes(events: &[AppEvent]) -> Vec<Vec<String>> {
    events
        .iter()
        .filter_map(|e| match e {
            AppEvent::FileProgress(FileProgress::Saved { names, .. }) => Some(names.clone()),
            _ => None,
        })
        .collect()
}

/// What the background half of `/file attach` hands the loop, prepared the way the command
/// prepares it: against the chat's folder and list as they are now.
fn prepared(
    orch: &Orchestrator,
    chat_id: Uuid,
    file: crate::app::orchestrator::attachments::ExtractedFile,
) -> crate::app::orchestrator::attachments::AttachResult {
    let (dir, listed) = orch.attach_snapshot(chat_id);
    crate::app::orchestrator::attachments::AttachResult::prepare(
        chat_id,
        Ok(file),
        &dir,
        &listed,
        orch.ui_locale(),
    )
}

fn failure(events: Vec<AppEvent>) -> Option<String> {
    events.into_iter().find_map(|e| match e {
        AppEvent::FileProgress(FileProgress::Failed(msg)) => Some(msg),
        _ => None,
    })
}

#[test]
fn a_stored_file_lands_once_and_one_note_names_it() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    orch.list_stored_files(chat_id, vec![listing("chart.png"), listing("totals.csv")]);
    // The same landing again — a repeated one — and a name that differs only in case.
    orch.list_stored_files(chat_id, vec![listing("chart.png"), listing("CHART.png")]);
    assert_eq!(files_of(&orch, chat_id), ["chart.png", "totals.csv"]);
    assert_eq!(
        saved_notes(&drain(&mut rx)),
        [vec!["chart.png".to_string(), "totals.csv".to_string()]]
    );
}

#[test]
fn a_landing_in_a_chat_that_is_not_open_lists_without_a_note() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    orch.active_id = None;
    orch.list_stored_files(chat_id, vec![listing("chart.png")]);
    assert_eq!(files_of(&orch, chat_id), ["chart.png"]);
    assert!(saved_notes(&drain(&mut rx)).is_empty());
}

/// The reply `/file list` sent, or nothing.
fn listed(events: Vec<AppEvent>) -> Option<(Vec<String>, Vec<String>, Vec<String>)> {
    events.into_iter().find_map(|e| match e {
        AppEvent::FileProgress(FileProgress::Listed {
            items,
            stored,
            images,
            ..
        }) => Some((
            items.iter().map(|a| a.name.clone()).collect(),
            stored.iter().map(|f| f.name.clone()).collect(),
            images.iter().map(|i| i.name.clone()).collect(),
        )),
        _ => None,
    })
}

/// One numbered list of the chat's three kinds (docs/history/sandbox-file-exchange.md §12 T2, T4):
/// attachments, then the stored files no attachment links, then the images its messages
/// carry — and a document that kept its original is **one** item, shown on its attachment's
/// line rather than twice (§12 T9).
#[test]
fn file_list_numbers_attachments_stored_files_and_images_as_one_list() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let original = ChatFile::new("report.pdf", FileOrigin::Attached, b"%PDF-1.7\n");
    let linked = Attachment::new(
        "report.pdf",
        "C:\\report.pdf",
        "the extracted text".into(),
        9,
        AttachMode::ByReference,
    )
    .with_file(original.id);
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    chat.attachments.push(linked);
    chat.files.push(original);
    chat.files.push(listing("chart.png"));
    let mut message = Message::user("look at this");
    message
        .images
        .push(crate::entities::message_image::MessageImage::new(
            "shot.png",
            "C:\\shot.png",
            "image/png",
            10,
            10,
            "AAAA".into(),
        ));
    chat.messages.push(message);

    orch.handle_file_list();
    let (items, stored, images) = listed(drain(&mut rx)).expect("a /file list reply");
    assert_eq!(items, ["report.pdf"]);
    // Not `report.pdf` again: the original is the attachment's own half.
    assert_eq!(stored, ["chart.png"]);
    assert_eq!(images, ["shot.png"]);
}

/// An image belongs to the message that carries it, so `/file remove` refuses it — and
/// names the command that *is* about images, rather than only saying no (lessons §4).
#[test]
fn removing_an_image_is_refused_with_the_way_out() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    let mut message = Message::user("look");
    message
        .images
        .push(crate::entities::message_image::MessageImage::new(
            "shot.png",
            "C:\\shot.png",
            "image/png",
            10,
            10,
            "AAAA".into(),
        ));
    chat.messages.push(message);

    orch.handle_file_remove("shot.png".into());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("shot.png"), "{msg}");
    assert!(msg.contains("/image remove"), "{msg}");
}

/// Fork F9 (§13 U3): a type the shell may run is never handed to a handler — the folder
/// opens instead, and the note says which happened. The plan is asserted rather than the
/// launch: nothing opens a window on the machine running the tests (§13 U10).
#[test]
fn a_document_opens_and_a_script_the_call_wrote_opens_its_folder() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("chart.png"), PNG).unwrap();
    std::fs::write(dir.join("run.bat"), b"echo hi").unwrap();
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    chat.files.push(listing("chart.png"));
    chat.files
        .push(ChatFile::new("run.bat", FileOrigin::Sandbox, b"echo hi"));

    let (path, note) = orch.plan_open("#1").expect("the chart opens");
    assert_eq!(path, dir.join("chart.png"));
    assert!(
        matches!(&note, FileProgress::Opened { name, .. } if name == "chart.png"),
        "{note:?}"
    );

    let (path, note) = orch.plan_open("run.bat").expect("the folder opens instead");
    assert_eq!(path, dir, "a script must not reach a handler");
    assert!(
        matches!(
            &note,
            FileProgress::OpenedFolder {
                instead_of: Some(OpenedInstead { name, by_a_call: true }),
                ..
            } if name == "run.bat"
        ),
        "{note:?}"
    );
    assert_eq!(failure(drain(&mut rx)), None, "neither is a refusal");
}

/// The folder stands in for a refused type whoever wrote the file — the allowlist is by
/// type — but the reason the note gives is true only of a file a call wrote. A `.py` the
/// user attached and a binary `/file attach` kept are the user's own; a call's script and
/// a leftover adopted from the folder are a call's (§13 U3).
#[test]
fn the_reason_a_folder_opens_instead_names_whose_file_it_is() {
    let (root, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    for name in ["setup.msi", "run.cmd", "old.sh"] {
        std::fs::write(dir.join(name), b"x").unwrap();
    }
    // The user's own script, attached from where it lives: plain text keeps no copy.
    let own = root.path().join("script.py");
    std::fs::write(&own, b"print(1)").unwrap();
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    chat.attachments.push(Attachment::new(
        "script.py",
        own.display().to_string(),
        "print(1)".into(),
        3,
        AttachMode::Inline,
    ));
    chat.files
        .push(ChatFile::new("setup.msi", FileOrigin::Attached, b"x"));
    chat.files
        .push(ChatFile::new("run.cmd", FileOrigin::Sandbox, b"x"));
    chat.files
        .push(ChatFile::new("old.sh", FileOrigin::Recovered, b"x"));

    let by_a_call = |target: &str| match orch.plan_open(target) {
        Some((
            _,
            FileProgress::OpenedFolder {
                instead_of: Some(instead),
                ..
            },
        )) => instead.by_a_call,
        other => panic!("{target}: expected its folder instead, got {other:?}"),
    };
    assert!(!by_a_call("script.py"), "the user attached it");
    assert!(
        !by_a_call("setup.msi"),
        "the user's binary, kept by /file attach"
    );
    assert!(by_a_call("run.cmd"), "a call wrote it");
    assert!(
        by_a_call("old.sh"),
        "adopted from the folder as a call's leftover"
    );
    assert_eq!(failure(drain(&mut rx)), None, "none of them is a refusal");
}

/// A stored name comes back from `chat.json` unvalidated. One that leaves the folder is
/// refused before anything is handed over — and the file it points at is **real**, so
/// the existence check alone would have let it through to a handler.
#[test]
fn a_stored_name_that_leaves_the_folder_is_refused_even_when_the_file_is_real() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    // Two levels above `files/<chat-id>/`: outside every chat's folder.
    std::fs::write(dir.join("..").join("..").join("escape.pdf"), b"%PDF").unwrap();
    // As `chat.json` would hand it back, not as `ChatFile::new` would build it.
    let mut file = ChatFile::new("escape.pdf", FileOrigin::Sandbox, b"%PDF");
    file.name = "../../escape.pdf".into();
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    chat.files.push(file);

    assert!(
        orch.plan_open("#1").is_none(),
        "nothing outside the folder is opened"
    );
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("escape.pdf"), "{msg}");
}

/// A launch runs off the loop and can outlast a switch of chats (§13 U5). Its success is
/// noted only in the chat it was asked in; its failure wherever the user is, because that
/// note is the only report of a command just given and a note is kept with no chat.
#[test]
fn a_launch_s_note_goes_to_its_chat_and_a_failure_is_never_lost() {
    use crate::app::orchestrator::attachments::OpenResult;
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let asked_in = open_chat(&mut orch);
    let opened = || FileProgress::Opened {
        name: "report.pdf".into(),
        path: "/data/files/a/report.pdf".into(),
    };
    let notes = |rx: &mut UnboundedReceiver<AppEvent>| {
        drain(rx)
            .iter()
            .filter(|e| matches!(e, AppEvent::FileProgress(_)))
            .count()
    };

    // Still in the chat: the note lands.
    orch.handle_open_result(OpenResult {
        chat_id: asked_in,
        progress: opened(),
    });
    assert_eq!(notes(&mut rx), 1);

    // The user moved on before the launch came back.
    let elsewhere = open_chat(&mut orch);
    assert_ne!(elsewhere, asked_in);
    orch.handle_open_result(OpenResult {
        chat_id: asked_in,
        progress: opened(),
    });
    assert_eq!(
        notes(&mut rx),
        0,
        "another chat's feed does not say this chat's file opened"
    );

    let why = "could not open /data/files/a/report.pdf";
    orch.handle_open_result(OpenResult {
        chat_id: asked_in,
        progress: FileProgress::Failed(why.into()),
    });
    assert_eq!(
        failure(drain(&mut rx)).as_deref(),
        Some(why),
        "a failure still reaches the user"
    );
}

/// The three shapes of "there is no file to open" — a pasted image, a handle nothing
/// answers to, and a listed copy the folder no longer holds — refuse before the shell is
/// reached, each naming what it looked for (§13 U2).
#[test]
fn opening_refuses_what_is_not_a_file_on_this_machine() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    // Listed, but its copy never reached the folder.
    chat.files.push(listing("chart.png"));
    let mut message = Message::user("look");
    message
        .images
        .push(crate::entities::message_image::MessageImage::new(
            "clipboard.png",
            "clipboard:9f2c",
            "image/png",
            10,
            10,
            "AAAA".into(),
        ));
    chat.messages.push(message);

    assert!(orch.plan_open("#2").is_none(), "a paste has no file");
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(
        msg.contains("clipboard.png") && msg.contains("clipboard:9f2c"),
        "{msg}"
    );

    assert!(orch.plan_open("#1").is_none(), "the copy is gone");
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("chart.png"), "{msg}");

    assert!(orch.plan_open("nothing.txt").is_none());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(
        msg.contains("nothing.txt") && msg.contains("/file list"),
        "a name nothing answers to points at the listing: {msg}"
    );
}

/// Observed live (2026-09-15, v0.9.9): `/file list` printed `#1 chart.png`, and
/// `/file open 1` and `/file remove 1` were each refused as "not attached" while the name
/// worked. A bare number is the `#N` the listing printed; a number no file carries is
/// answered with the numbers there are — what the same run needed again once a removal had
/// renumbered the list — and a chat with no files with the command that adds one.
#[test]
fn a_bare_number_reaches_the_listed_file_and_a_missing_one_names_the_numbers_there_are() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    for name in ["chart.png", "tool-image-1.png"] {
        std::fs::write(dir.join(name), PNG).unwrap();
        let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
        chat.files.push(listing(name));
    }

    let (path, _) = orch.plan_open("1").expect("`1` is `#1`");
    assert_eq!(path, dir.join("chart.png"));

    assert!(orch.plan_open("3").is_none());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(
        msg.contains("#3") && msg.contains("#1–#2") && msg.contains("/file list"),
        "{msg}"
    );

    orch.handle_file_remove("1".into());
    assert_eq!(files_of(&orch, chat_id), ["tool-image-1.png"]);
    drain(&mut rx);

    // The list renumbered: what was `#2` is `#1` now, and `#2` says what there is.
    assert!(orch.plan_open("#2").is_none());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(
        msg.contains("#2") && msg.contains("#1") && !msg.contains("#1–"),
        "{msg}"
    );

    orch.handle_file_remove("1".into());
    assert!(files_of(&orch, chat_id).is_empty());
    drain(&mut rx);
    assert!(orch.plan_open("1").is_none());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("/file attach"), "an empty chat: {msg}");
}

/// `/image remove` reads a bare number the way `/file` does, and a number nothing staged
/// carries is answered with the numbers there are.
#[test]
fn image_remove_takes_a_bare_number_and_answers_a_missing_one_with_the_range() {
    use crate::app::events::ImageProgress;
    use crate::entities::message_image::MessageImage;
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let staged = orch.staged_images.entry(chat_id).or_default();
    for (name, source) in [("a.png", "C:\\a.png"), ("b.png", "C:\\b.png")] {
        staged.push(MessageImage::new(
            name,
            source,
            "image/png",
            10,
            10,
            "AAAA".into(),
        ));
    }
    let refusal = |events: Vec<AppEvent>| {
        events.into_iter().find_map(|e| match e {
            AppEvent::ImageProgress(ImageProgress::Failed(msg)) => Some(msg),
            _ => None,
        })
    };

    orch.handle_image_remove("5".into());
    let msg = refusal(drain(&mut rx)).expect("a refusal");
    assert!(
        msg.contains("#5") && msg.contains("#1–#2") && msg.contains("/image list"),
        "{msg}"
    );

    orch.handle_image_remove("2".into());
    let names: Vec<&str> = orch.staged_images[&chat_id]
        .iter()
        .map(|i| i.name.as_str())
        .collect();
    assert_eq!(names, ["a.png"]);
}

/// A name two of the chat's files share opens nothing and lists each holder's `#N` and
/// source — the rule `/file remove` already had, now shared by both commands (§13 U1).
#[test]
fn opening_a_shared_name_is_refused_with_both_candidates() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    for source in ["C:\\a\\notes.md", "C:\\b\\notes.md"] {
        chat.attachments.push(Attachment::new(
            "notes.md",
            source,
            "text".into(),
            4,
            AttachMode::Inline,
        ));
    }

    assert!(orch.plan_open("notes.md").is_none());
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("#1") && msg.contains("#2"), "{msg}");
    assert!(
        msg.contains("C:\\a\\notes.md") && msg.contains("C:\\b\\notes.md"),
        "{msg}"
    );
}

/// `/file folder` on a chat that has saved nothing says so and prints the path — and
/// creates no empty directory on the way (§13 U7).
#[test]
fn the_folder_of_a_chat_that_saved_nothing_is_refused_with_its_path() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);

    orch.handle_file_folder();
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains(&dir.display().to_string()), "{msg}");
    assert!(
        !dir.exists(),
        "the command created the folder it reported on"
    );
}

/// Removing an attached document that kept its original takes both halves — the listing
/// and our copy of the file — and never the user's own (§12 T9).
#[test]
fn removing_a_pair_deletes_our_copy_and_both_listings() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("report.pdf"), b"%PDF-1.7\n").unwrap();
    let original = ChatFile::new("report.pdf", FileOrigin::Attached, b"%PDF-1.7\n");
    let linked = Attachment::new(
        "report.pdf",
        "C:\\report.pdf",
        "the extracted text".into(),
        9,
        AttachMode::ByReference,
    )
    .with_file(original.id);
    let chat = orch.chats.iter_mut().find(|c| c.id == chat_id).unwrap();
    chat.attachments.push(linked);
    chat.files.push(original);

    orch.handle_file_remove("report.pdf".into());
    let chat = orch.chats.iter().find(|c| c.id == chat_id).unwrap();
    assert!(chat.attachments.is_empty(), "the attachment stayed");
    assert!(chat.files.is_empty(), "the listing stayed");
    assert!(!dir.join("report.pdf").exists(), "our copy stayed on disk");
    let note = drain(&mut rx).into_iter().find_map(|e| match e {
        AppEvent::FileProgress(FileProgress::RemovedPair { name }) => Some(name),
        _ => None,
    });
    assert_eq!(note.as_deref(), Some("report.pdf"));
}

/// Fork F8a (§12 T9): `/file attach` on a binary keeps the file with the chat and makes no
/// attachment of it — there is no text to attach. The note says so, and `/file list`
/// numbers the file like any other stored one. This is the refusal D3 asked to lift.
#[test]
fn attaching_a_binary_keeps_the_file_and_makes_no_attachment() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    const WORKBOOK: &[u8] = b"PK\x03\x04not-really-a-workbook";
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let res = prepared(
        &orch,
        chat_id,
        ExtractedFile {
            name: "sales.xlsx".into(),
            source: "C:\\sales.xlsx".into(),
            text: String::new(),
            bytes: WORKBOOK.len(),
            encoding: None,
            original: Some(WORKBOOK.to_vec()),
        },
    );
    orch.handle_attach_result(res);
    assert_eq!(files_of(&orch, chat_id), ["sales.xlsx"]);
    let dir = orch.stored_files_dir(chat_id);
    assert_eq!(std::fs::read(dir.join("sales.xlsx")).unwrap(), WORKBOOK);
    assert!(
        orch.chats
            .iter()
            .find(|c| c.id == chat_id)
            .unwrap()
            .attachments
            .is_empty(),
        "a binary carries no text, so nothing is attached as text"
    );
    let note = drain(&mut rx).into_iter().find_map(|e| match e {
        AppEvent::FileProgress(FileProgress::StoredFile { name, .. }) => Some(name),
        _ => None,
    });
    assert_eq!(note.as_deref(), Some("sales.xlsx"));
}

/// The remedy the app itself prescribes has to work. A stored copy can go missing while
/// its listing stands — a pruned `data/files/`, a partial sync, a chat file restored
/// without its folder — `/file list` marks it, and `python_exec` refuses the file and tells
/// the model to *ask the user to attach it again*. Matching on the listing alone made that
/// a dead end: name and digest agreed, so re-attaching wrote nothing, the entry stayed
/// missing and the next call refused identically.
#[test]
fn reattaching_a_file_whose_copy_went_missing_puts_it_back() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    const WORKBOOK: &[u8] = b"PK\x03\x04not-really-a-workbook";
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let workbook = || ExtractedFile {
        name: "sales.xlsx".into(),
        source: "C:\\sales.xlsx".into(),
        text: String::new(),
        bytes: WORKBOOK.len(),
        encoding: None,
        original: Some(WORKBOOK.to_vec()),
    };

    let res = prepared(&orch, chat_id, workbook());
    orch.handle_attach_result(res);
    let dir = orch.stored_files_dir(chat_id);
    let copy = dir.join("sales.xlsx");
    assert_eq!(std::fs::read(&copy).unwrap(), WORKBOOK);
    let listed_before = files_of(&orch, chat_id);

    // The copy goes; the chat goes on listing it.
    std::fs::remove_file(&copy).unwrap();
    assert!(!crate::features::chat_files::exists(&dir, "sales.xlsx"));

    // Attaching the very same file again is what the refusal tells the user to do.
    let res = prepared(&orch, chat_id, workbook());
    orch.handle_attach_result(res);
    assert_eq!(
        std::fs::read(&copy).unwrap(),
        WORKBOOK,
        "the copy was not put back"
    );
    assert_eq!(
        files_of(&orch, chat_id),
        listed_before,
        "one listing, not a second one beside it"
    );
}

/// The store of the file's own bytes belongs to the background half
/// (`AttachResult::prepare`), and only the listing to the loop: up to 32 MB hashed, written
/// and synced used to run on the command loop while only the read was off it. Pinned by what
/// each half leaves behind — after the background half the bytes are on disk and the chat
/// lists nothing; after the landing, it lists them.
#[test]
fn the_original_is_written_off_the_loop_and_only_listed_on_it() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let res = prepared(
        &orch,
        chat_id,
        ExtractedFile {
            name: "report.pdf".into(),
            source: "C:\\report.pdf".into(),
            text: "the extracted text".into(),
            bytes: 9,
            encoding: None,
            original: Some(b"%PDF-1.7\n".to_vec()),
        },
    );
    let dir = orch.stored_files_dir(chat_id);
    assert_eq!(
        std::fs::read(dir.join("report.pdf")).unwrap(),
        b"%PDF-1.7\n",
        "written by the background half"
    );
    assert!(files_of(&orch, chat_id).is_empty(), "and not yet listed");

    orch.handle_attach_result(res);
    assert_eq!(files_of(&orch, chat_id), ["report.pdf"]);
}

/// The store answers from the list as the command found it, so the list can change before
/// that answer lands. A copy the store found unchanged, and that was then removed — listing
/// and bytes — must not be linked: the attachment would name a file the chat no longer
/// lists. Refused, saying so, with nothing attached.
#[test]
fn a_copy_removed_while_attaching_is_refused_rather_than_linked() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let report = || ExtractedFile {
        name: "report.pdf".into(),
        source: "C:\\report.pdf".into(),
        text: "the extracted text".into(),
        bytes: 9,
        encoding: None,
        original: Some(b"%PDF-1.7\n".to_vec()),
    };
    let first = prepared(&orch, chat_id, report());
    orch.handle_attach_result(first);
    drain(&mut rx);

    // Attached again: the store finds the same bytes listed and on disk — unchanged...
    let again = prepared(&orch, chat_id, report());
    // ...and before that answer lands, the pair is removed.
    orch.handle_file_remove("report.pdf".into());
    drain(&mut rx);

    orch.handle_attach_result(again);
    let chat = orch.chats.iter().find(|c| c.id == chat_id).unwrap();
    assert!(
        chat.attachments.is_empty(),
        "linked to a removed copy: {:?}",
        chat.attachments
    );
    let msg = failure(drain(&mut rx)).expect("a refusal");
    assert!(msg.contains("report.pdf"), "{msg}");
}

/// A document an extractor read becomes the attachment **and** keeps its original, the two
/// linked as one item (§12 T9) — which is what lets `python_exec` open the file itself
/// while the model reads the text.
#[test]
fn attaching_a_document_links_its_original_to_the_attachment() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let res = prepared(
        &orch,
        chat_id,
        ExtractedFile {
            name: "report.pdf".into(),
            source: "C:\\report.pdf".into(),
            text: "the extracted text".into(),
            bytes: 9,
            encoding: None,
            original: Some(b"%PDF-1.7\n".to_vec()),
        },
    );
    orch.handle_attach_result(res);
    let chat = orch.chats.iter().find(|c| c.id == chat_id).unwrap();
    assert_eq!(chat.attachments.len(), 1);
    let linked = chat.attachments[0].file_id.expect("the pair is linked");
    assert!(
        chat.files
            .iter()
            .any(|f| f.id == linked && f.name == "report.pdf"),
        "the original is listed: {:?}",
        chat.files
    );
}

#[test]
fn file_list_shows_stored_files_and_marks_one_missing_from_the_folder() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("chart.png"), PNG).unwrap();
    orch.list_stored_files(chat_id, vec![listing("chart.png"), listing("gone.png")]);
    drain(&mut rx);
    orch.handle_file_list();
    let (stored, shown) = drain(&mut rx)
        .into_iter()
        .find_map(|e| match e {
            AppEvent::FileProgress(FileProgress::Listed { stored, dir, .. }) => Some((stored, dir)),
            _ => None,
        })
        .expect("a listing");
    let seen: Vec<(&str, bool)> = stored
        .iter()
        .map(|f| (f.name.as_str(), f.missing))
        .collect();
    assert_eq!(seen, [("chart.png", false), ("gone.png", true)]);
    assert_eq!(shown, dir.display().to_string());
}

#[test]
fn removing_a_stored_file_deletes_our_copy_and_then_its_listing() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("chart.png"), PNG).unwrap();
    orch.list_stored_files(chat_id, vec![listing("chart.png")]);
    drain(&mut rx);
    orch.handle_file_remove("#1".into());
    assert!(!dir.join("chart.png").exists());
    assert!(files_of(&orch, chat_id).is_empty());
    assert!(drain(&mut rx).iter().any(|e| matches!(
        e,
        AppEvent::FileProgress(FileProgress::RemovedStored { name }) if name == "chart.png"
    )));
}

/// The order of the two writes (docs/lessons.md §8): a copy that cannot be deleted keeps
/// its listing, so the removal can be retried and nothing is lost. A directory where the
/// file should be is what makes the delete fail on every platform.
#[test]
fn a_stored_file_whose_copy_cannot_be_deleted_stays_listed() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(dir.join("chart.png")).unwrap();
    orch.list_stored_files(chat_id, vec![listing("chart.png")]);
    drain(&mut rx);
    orch.handle_file_remove("chart.png".into());
    assert_eq!(files_of(&orch, chat_id), ["chart.png"]);
    let msg = failure(drain(&mut rx)).expect("the refusal");
    assert!(msg.contains("chart.png"), "{msg}");
}

#[test]
fn a_name_an_attachment_and_a_stored_file_share_removes_neither() {
    let (_dir, mut orch, mut rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    orch.chats[0].attachments.push(Attachment::new(
        "chart.png",
        "/tmp/chart.png",
        "x".into(),
        1,
        AttachMode::Inline,
    ));
    orch.list_stored_files(chat_id, vec![listing("chart.png")]);
    drain(&mut rx);
    orch.handle_file_remove("chart.png".into());
    let msg = failure(drain(&mut rx)).expect("the refusal");
    assert!(msg.contains("#1") && msg.contains("#2"), "{msg}");
    assert_eq!(orch.chats[0].attachments.len(), 1);
    assert_eq!(files_of(&orch, chat_id), ["chart.png"]);
}

#[test]
fn adopting_lists_a_file_the_chat_does_not_and_deletes_nothing() {
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("orphan.csv"), b"a,b\n").unwrap();
    orch.adopt_unlisted_files();
    orch.adopt_unlisted_files();
    let chat = &orch.chats[0];
    assert_eq!(files_of(&orch, chat_id), ["orphan.csv"]);
    assert_eq!(chat.files[0].origin, FileOrigin::Recovered);
    assert!(dir.join("orphan.csv").exists());
}

/// Nothing says an adopted file is the user's, so it carries the mark a call's output does
/// (§13 U11).
#[cfg(windows)]
#[test]
fn an_adopted_file_is_marked_as_come_from_elsewhere() {
    use crate::shared::os_open::{FROM_ELSEWHERE, zone_of};
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let dir = orch.stored_files_dir(chat_id);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("orphan.csv"), b"=1+1\n").unwrap();
    orch.adopt_unlisted_files();
    assert_eq!(files_of(&orch, chat_id), ["orphan.csv"]);
    assert_eq!(
        zone_of(&dir.join("orphan.csv")).as_deref(),
        Some(FROM_ELSEWHERE)
    );
}

/// The chat's copy of an attached document carries the mark the user's file carries (§13
/// U11): a workbook downloaded from the web keeps its Protected View when it is opened from
/// the chat's folder, and one the user made gains no mark it did not have.
#[cfg(windows)]
#[test]
fn an_attached_copy_carries_the_mark_of_the_file_it_copies() {
    use crate::app::orchestrator::attachments::ExtractedFile;
    use crate::shared::os_open::{set_zone, zone_of};
    const WORKBOOK: &[u8] = b"PK\x03\x04not-really-a-workbook";
    const DOWNLOADED: &[u8] =
        b"[ZoneTransfer]\r\nZoneId=3\r\nHostUrl=https://example.com/sales.xlsx\r\n";
    let (_dir, mut orch, _rx) = bare_orch_rx();
    let chat_id = open_chat(&mut orch);
    let user = tempfile::tempdir().unwrap();
    let downloaded = user.path().join("sales.xlsx");
    let made = user.path().join("budget.xlsx");
    for path in [&downloaded, &made] {
        std::fs::write(path, WORKBOOK).unwrap();
    }
    set_zone(&downloaded, DOWNLOADED).unwrap();

    for path in [&downloaded, &made] {
        let file = ExtractedFile {
            name: path.file_name().unwrap().to_string_lossy().into_owned(),
            source: path.display().to_string(),
            text: String::new(),
            bytes: WORKBOOK.len(),
            encoding: None,
            original: Some(WORKBOOK.to_vec()),
        };
        let res = prepared(&orch, chat_id, file);
        orch.handle_attach_result(res);
    }
    let dir = orch.stored_files_dir(chat_id);
    assert_eq!(
        zone_of(&dir.join("sales.xlsx")).as_deref(),
        Some(DOWNLOADED),
        "the download's mark"
    );
    assert_eq!(
        zone_of(&dir.join("budget.xlsx")),
        None,
        "a mark the user's file did not have"
    );
}

/// The call site, not only the method: a chat saved without the listing of a file in its
/// folder has it listed — and saved — once the app has started (§11 S6).
#[tokio::test]
async fn the_bootstrap_adopts_unlisted_files_and_saves_the_listing() {
    let root = tempfile::tempdir().unwrap();
    let chat = {
        let storage = Storage::open(Paths::with_root(root.path())).unwrap();
        let profile = Profile::new("P", "sys");
        storage.json().upsert_profile(&profile).unwrap();
        let chat = Chat::from_profile(&profile, "t");
        storage.json().save_chat(&chat).unwrap();
        chat
    };
    let dir = root.path().join("files").join(chat.id.to_string());
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("chart.png"), PNG).unwrap();
    let (cmd_tx, mut evt_rx, handle) = spawn_orch_at(root.path(), None, no_auto_cfg());
    tokio::time::timeout(
        Duration::from_secs(5),
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. })),
    )
    .await
    .expect("the bootstrap activates a chat");
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
    let files = load(root.path(), chat.id).files;
    let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, ["chart.png"]);
    assert_eq!(files[0].origin, FileOrigin::Recovered);
}

#[test]
fn a_turns_next_round_sees_the_files_its_calls_stored() {
    let (_d, _s, mut ctx) = crate::features::tools::testkit::ctx_with_storage(Uuid::new_v4());
    let effects = vec![ChatEffect::AddChatFile(Box::new(listing("chart.png")))];
    super::super::generation::sync_files(&mut ctx, &effects);
    // The effects list is cumulative across rounds: mirroring it twice adds nothing.
    super::super::generation::sync_files(&mut ctx, &effects);
    let names: Vec<&str> = ctx.files.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, ["chart.png"]);
}

/// A decodable 4×4 PNG.
fn real_png() -> Vec<u8> {
    let mut out = std::io::Cursor::new(Vec::new());
    image::RgbImage::from_pixel(4, 4, image::Rgb([255, 255, 0]))
        .write_to(&mut out, image::ImageFormat::Png)
        .unwrap();
    out.into_inner()
}

/// A tool that stores a chart the way `python_exec` does: the bytes in the chat's folder,
/// a listing effect, and `image` for the model — offered on the result's `- chart.png` line,
/// which says nothing about whether it is shown: the loop ends it with that (spec §9.10).
struct Charting {
    image: Vec<u8>,
    /// Whether a line of the result names the image (`python_exec`'s shape) or none does
    /// (MCP's), which the loop can only count into a note.
    named: bool,
    /// Draw a different chart each round — a trailing byte per call. Off, every round
    /// stores the same bytes, which is the dedupe case; on, each round has an image of its
    /// own, which is what a tool called three times normally produces.
    vary: bool,
    calls: std::sync::atomic::AtomicUsize,
}

#[async_trait::async_trait]
impl Tool for Charting {
    fn id(&self) -> ToolId {
        "charting".into()
    }
    fn description(&self, _loc: &crate::shared::i18n::Locale) -> String {
        "draws a chart".into()
    }
    fn parameters(&self, _loc: &crate::shared::i18n::Locale) -> serde_json::Value {
        serde_json::json!({"type": "object", "properties": {}})
    }
    async fn invoke(
        &self,
        ctx: &ToolContext,
        _args: serde_json::Value,
    ) -> anyhow::Result<ToolOutcome> {
        use base64::Engine as _;
        let dir = ctx.files_dir.clone().expect("a turn has a files folder");
        let nth = self
            .calls
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut image = self.image.clone();
        if self.vary {
            image.push(nth as u8);
        }
        let stored = crate::features::chat_files::store(&dir, &ctx.files, "chart.png", &image)?;
        let file = match stored {
            crate::features::chat_files::Stored::New(file) => file,
            // Listed, but the copy had gone from the folder: the bytes are back and the
            // listing stands, so there is still nothing to add.
            crate::features::chat_files::Stored::Restored(_) => {
                return Ok(ToolOutcome::text("files:\n- chart.png — restored"));
            }
            // The same bytes under a name the turn already listed: nothing to add.
            crate::features::chat_files::Stored::Unchanged(_) => {
                return Ok(ToolOutcome::text("files:\n- chart.png — unchanged"));
            }
        };
        Ok(ToolOutcome::with_effects(
            "files:\n- chart.png",
            vec![ChatEffect::AddChatFile(Box::new(file))],
        )
        .with_images(vec![ToolImage {
            mime: "image/png".into(),
            data: base64::engine::general_purpose::STANDARD.encode(&image),
            entry: self.named.then(|| "- chart.png".to_string()),
        }]))
    }
    fn group(&self) -> ToolGroup {
        ToolGroup::Files
    }
    fn ui_label(&self) -> &'static str {
        "chart"
    }
}

/// A scripted engine that says what it can see, and counts being asked.
struct Sighted {
    inner: Arc<ScriptRecorder>,
    vision: VisionSupport,
    /// How many times the turn asked. The answer belongs to the server and the model, so
    /// it cannot change inside a turn — and asking is an HTTP round trip on the critical
    /// path, paid once per round that returned an image until it was memoized.
    asked: Arc<std::sync::atomic::AtomicUsize>,
}

#[async_trait::async_trait]
impl EngineBackend for Sighted {
    async fn chat_stream(
        &self,
        req: crate::shared::api::ChatRequest,
        cancel: tokio_util::sync::CancellationToken,
    ) -> anyhow::Result<ChatStream> {
        self.inner.chat_stream(req, cancel).await
    }
    async fn vision(&self) -> VisionSupport {
        self.asked
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.vision
    }
}

/// What a `charting` turn left: the data root (kept alive), the stored call's record (its
/// result and image count), the chat's stored files, and their folder.
struct ChartingTurn {
    _root: tempfile::TempDir,
    record: crate::entities::message::ToolCallRecord,
    files: Vec<ChatFile>,
    folder: std::path::PathBuf,
    /// How many times the turn asked the engine about images.
    asked: usize,
    /// The names of the images the chat's messages ended up carrying, in order.
    image_names: Vec<String>,
}

/// One turn in which the model calls `charting` once in each of `rounds` rounds.
async fn charting_turn(vision: VisionSupport, image: Vec<u8>, rounds: usize) -> ChartingTurn {
    charting_turn_drawing(vision, image, rounds, false).await
}

/// [`charting_turn`], with `vary` deciding whether each round draws a new chart.
async fn charting_turn_drawing(
    vision: VisionSupport,
    image: Vec<u8>,
    rounds: usize,
    vary: bool,
) -> ChartingTurn {
    charting_turn_with(vision, image, rounds, vary, true).await
}

/// [`charting_turn_drawing`], with `named` deciding whether a line of the result names the
/// image (see [`Charting::named`]).
async fn charting_turn_with(
    vision: VisionSupport,
    image: Vec<u8>,
    rounds: usize,
    vary: bool,
    named: bool,
) -> ChartingTurn {
    let mut scripts: Vec<Script> = (1..=rounds)
        .map(|round| Script {
            chunks: vec![
                ChatChunk::ToolCall(ToolCallDelta {
                    thought_signature: None,
                    index: 0,
                    id: Some(format!("c{round}")),
                    name: Some("charting".into()),
                    arguments: "{}".into(),
                }),
                ChatChunk::Finished(FinishReason::ToolCalls),
            ],
            hang: false,
        })
        .collect();
    scripts.push(text("done"));
    let recorder = ScriptRecorder::new(scripts);
    let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let backend: Arc<dyn EngineBackend> = Arc::new(Sighted {
        inner: recorder,
        vision,
        asked: Arc::clone(&asked),
    });
    let (dir, cmd_tx, mut evt_rx, handle) = spawn_orch_tools(
        Some(backend),
        no_auto_cfg(),
        vec![Arc::new(Charting {
            image,
            named,
            vary,
            calls: std::sync::atomic::AtomicUsize::new(0),
        })],
    );
    let (mut pid, mut chat_id) = (None, None);
    while pid.is_none() || chat_id.is_none() {
        match tokio::time::timeout(Duration::from_secs(5), evt_rx.recv())
            .await
            .expect("startup events")
        {
            Some(AppEvent::ProfileList(v)) if !v.is_empty() => pid = Some(v[0].id),
            Some(AppEvent::ChatActivated { id, .. }) => chat_id = Some(id),
            Some(_) => {}
            None => panic!("the orchestrator went away during startup"),
        }
    }
    cmd_tx
        .send(AppCommand::UpdateProfile {
            id: pid.unwrap(),
            edit: Box::new(ProfileEdit {
                enabled_tools: Some(vec!["charting".into()]),
                ..Default::default()
            }),
        })
        .unwrap();
    cmd_tx.send(AppCommand::SendMessage("draw".into())).unwrap();
    tokio::time::timeout(
        Duration::from_secs(20),
        wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. })),
    )
    .await
    .expect("the turn finishes");
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
    let chat_id = chat_id.unwrap();
    let chat = load(dir.path(), chat_id);
    let record = chat
        .messages
        .iter()
        .flat_map(|m| m.tool_calls.iter())
        .find(|r| r.name == "charting")
        .cloned()
        .expect("the call's record");
    let folder = dir.path().join("files").join(chat_id.to_string());
    let image_names = chat
        .messages
        .iter()
        .flat_map(|m| m.images.iter())
        .map(|i| i.name.clone())
        .collect();
    ChartingTurn {
        _root: dir,
        record,
        files: chat.files,
        folder,
        asked: asked.load(std::sync::atomic::Ordering::Relaxed),
        image_names,
    }
}

fn profile_note(key: &str, n: &str) -> String {
    crate::shared::i18n::locale(crate::shared::i18n::Lang::default()).tf(key, &[("n", n)])
}

/// Whether the engine takes images belongs to the server and the model behind it, so it
/// cannot change inside a turn — but asking is a real HTTP round trip on the turn's
/// critical path, and nothing memoized it: a turn whose every round returned an image paid
/// one probe per round, up to `max_tool_rounds` of them.
#[tokio::test]
async fn the_engine_is_asked_about_images_once_a_turn_however_many_rounds_return_one() {
    let ChartingTurn { asked, .. } =
        charting_turn_drawing(VisionSupport::Supported, real_png(), 3, true).await;
    assert_eq!(
        asked, 1,
        "three rounds, three images, and the answer cannot have changed between them"
    );
}

/// On an engine that takes no images the chart's own line says it was not shown, and why
/// — and nothing in the result still says it was. The tool used to end the line with
/// "shown to you below" before the loop knew, and the loop's note then contradicted it
/// (measured through OpenRouter on a text-only model; a llama.cpp without `--mmproj`
/// reads the same).
#[tokio::test]
async fn an_image_the_model_cannot_take_is_withheld_and_the_result_says_so() {
    let ChartingTurn {
        _root,
        record,
        files,
        folder,
        ..
    } = charting_turn(VisionSupport::Unsupported, real_png(), 1).await;
    let result = record.result.unwrap_or_default();
    assert_eq!(record.images, 0, "{result}");
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    assert_eq!(
        result,
        format!(
            "files:\n- chart.png{}",
            loc.t("loop.image_not_shown_no_vision")
        ),
    );
    assert!(!result.contains(loc.t("loop.image_shown")), "{result}");
    assert!(
        !result.contains(&profile_note("loop.images_no_vision", "1")),
        "said once, on its line: {result}"
    );
    // The file itself landed regardless: only the pixels are withheld.
    assert_eq!(files.len(), 1);
    assert!(folder.join("chart.png").exists());
}

/// The shown image's line is ended by the loop with the same words the tool used to write,
/// so what the model reads when the image does arrive is unchanged.
#[tokio::test]
async fn an_image_a_seeing_model_takes_is_sent_without_a_note() {
    let ChartingTurn {
        _root,
        record,
        files,
        ..
    } = charting_turn(VisionSupport::Supported, real_png(), 1).await;
    let result = record.result.unwrap_or_default();
    assert_eq!(record.images, 1, "{result}");
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    assert_eq!(
        result,
        format!("files:\n- chart.png{}", loc.t("loop.image_shown"))
    );
    assert_eq!(files.len(), 1);
}

/// `prepare_tool_images` drops what it cannot decode — silently, until the result had to
/// say so (§11 S8), for MCP's images as much as for a chart.
#[tokio::test]
async fn an_image_that_cannot_be_prepared_is_dropped_and_the_result_says_so() {
    let ChartingTurn { _root, record, .. } = charting_turn(
        VisionSupport::Unknown,
        b"\x89PNG\r\n\x1a\ntruncated".to_vec(),
        1,
    )
    .await;
    let result = record.result.unwrap_or_default();
    assert_eq!(record.images, 0, "{result}");
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    assert_eq!(
        result,
        format!(
            "files:\n- chart.png{}",
            loc.t("loop.image_not_shown_dropped")
        ),
    );
}

/// An image no line names — MCP's shape — has nowhere to be said but a note, one per
/// reason, as before; and a shown one needs none.
#[tokio::test]
async fn an_unnamed_image_s_fate_is_said_in_a_note() {
    let truncated = b"\x89PNG\r\n\x1a\ntruncated".to_vec();
    for (vision, image, note) in [
        (
            VisionSupport::Unsupported,
            real_png(),
            Some("loop.images_no_vision"),
        ),
        (
            VisionSupport::Unknown,
            truncated,
            Some("loop.images_dropped"),
        ),
        (VisionSupport::Supported, real_png(), None),
    ] {
        let ChartingTurn { _root, record, .. } =
            charting_turn_with(vision, image, 1, false, false).await;
        let result = record.result.unwrap_or_default();
        let expected = match note {
            Some(key) => format!("files:\n- chart.png\n\n{}", profile_note(key, "1")),
            None => "files:\n- chart.png".to_string(),
        };
        assert_eq!(result, expected, "{vision:?}");
    }
}

/// The line a fate is said on is the tool's **last** line of those words: `python_exec`
/// lists its files after the console, and code that printed the same words must not have
/// them claimed for its chart. A line the words only begin is not that line.
#[test]
fn a_fate_is_said_on_the_last_whole_line_that_names_the_image() {
    use super::super::generation::end_line;
    let mut text =
        "stdout:\n- chart.png\n- chart.png (2)\n\nfiles:\n- chart.png\n  | head".to_string();
    assert!(end_line(&mut text, "- chart.png", " — shown"));
    assert_eq!(
        text,
        "stdout:\n- chart.png\n- chart.png (2)\n\nfiles:\n- chart.png — shown\n  | head"
    );
    let mut none = "files:\n- chart.png (2)".to_string();
    assert!(!end_line(&mut none, "- chart.png", " — shown"));
    assert_eq!(none, "files:\n- chart.png (2)");
}

/// One call, three fates: each named image is said on its own line, and only the unnamed
/// one reaches a note.
#[test]
fn each_image_of_a_call_is_said_where_it_is_named() {
    use super::super::generation::{ImageFate, say_image_fates};
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::default());
    let mut result = "files:\n- a.png\n- b.png".to_string();
    say_image_fates(
        &mut result,
        loc,
        &[Some("- a.png".into()), Some("- b.png".into()), None],
        &[ImageFate::Shown, ImageFate::Dropped, ImageFate::Dropped],
    );
    assert_eq!(
        result,
        format!(
            "files:\n- a.png{}\n- b.png{}\n\n{}",
            loc.t("loop.image_shown"),
            loc.t("loop.image_not_shown_dropped"),
            profile_note("loop.images_dropped", "1"),
        )
    );
}

/// A tool image is named for the chat, not for the call. Numbered per call, every round
/// handed its first image `tool-image-1.png`, and two of those in one chat are a name two
/// items share — which `resolve` refuses (`Resolved::Shared`), so the model naming its own
/// chart in the next call's `files` bought a refusal with the round.
///
/// Two rounds, each drawing a chart of its own: the same bytes twice would be deduplicated
/// into one file and could not collide (the test below is that case).
#[tokio::test]
async fn each_round_s_chart_gets_a_name_of_its_own() {
    let ChartingTurn {
        _root, image_names, ..
    } = charting_turn_drawing(VisionSupport::Supported, real_png(), 2, true).await;
    assert_eq!(
        image_names,
        vec![
            "tool-image-1.png".to_string(),
            "tool-image-2.png".to_string()
        ],
        "the second round's chart takes the next free number"
    );
}

/// The mirror's call site (§11 S5): a turn's second round stores against the files its
/// first listed, so the same chart twice stays one file. Without `sync_files` the second
/// call finds the first on disk and saves `chart (2).png`.
#[tokio::test]
async fn a_second_round_storing_the_same_chart_keeps_one_file() {
    let ChartingTurn {
        _root,
        files,
        folder,
        ..
    } = charting_turn(VisionSupport::Supported, real_png(), 2).await;
    let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, ["chart.png"]);
    assert!(!folder.join("chart (2).png").exists());
}