eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! Sight end to end: a real config, a real `Agent`, and real local servers (`#346`).
//!
//! Every claim here is asserted on the request bodies the servers actually received, not on what
//! the harness intended to send: "the turn model never saw the bytes" is a fact about a body, and a
//! note on stderr cannot establish it.

use eclipse_core::config::Config;
use eclipse_core::message::ImagePart;
use eclipse_core::tools::AllowAll;
use eclipse_core::Agent;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

const REPLY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"answered"}}]}"#;
const PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==";

/// A server that appends each request body it is sent and answers with `REPLY`, unless the
/// responder says otherwise.
async fn spawn(
    answer: impl Fn(usize, &str) -> Option<(u16, String)> + Send + Sync + 'static,
) -> (String, Arc<Mutex<Vec<String>>>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let bodies = Arc::new(Mutex::new(Vec::new()));
    let seen = Arc::clone(&bodies);
    let answer = Arc::new(answer);
    let count = Arc::new(AtomicUsize::new(0));
    tokio::spawn(async move {
        loop {
            let Ok((mut socket, _)) = listener.accept().await else {
                break;
            };
            let seen = Arc::clone(&seen);
            let answer = Arc::clone(&answer);
            let n = count.fetch_add(1, Ordering::SeqCst);
            tokio::spawn(async move {
                let mut buf = Vec::new();
                let request = loop {
                    let mut chunk = [0u8; 4096];
                    let read = socket.read(&mut chunk).await.unwrap_or(0);
                    buf.extend_from_slice(&chunk[..read]);
                    let text = String::from_utf8_lossy(&buf).to_string();
                    let Some(idx) = text.find("\r\n\r\n") else {
                        if read == 0 {
                            return;
                        }
                        continue;
                    };
                    let len = text[..idx]
                        .to_lowercase()
                        .lines()
                        .find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
                        .unwrap_or(0usize);
                    if buf.len() >= idx + 4 + len {
                        break text[idx + 4..].to_string();
                    }
                };
                seen.lock().unwrap().push(request.clone());
                let (status, body) = match answer(n, &request) {
                    Some((status, body)) => (status, body),
                    None => (200, REPLY.to_string()),
                };
                let response = format!(
                    "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                let _ = socket.write_all(response.as_bytes()).await;
                let _ = socket.shutdown().await;
            });
        }
    });
    (base, bodies)
}

fn config(base: &str, extra: &str) -> Config {
    Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{base}"
model = "stub-stream"
api_key = "none"
[sessions]
autotitle = false
[context]
judge = false
{extra}
"#
    ))
    .unwrap()
}

/// A manifest that claims vision, for a route that describes pictures. Without one the planner
/// refuses to send a picture to it — which is decision 1 of `#346`: declared, never probed.
fn seeing_plugin(dir: &std::path::Path) {
    let manifest = dir.join(".eclipse/plugins/seeing");
    std::fs::create_dir_all(&manifest).unwrap();
    std::fs::write(
        manifest.join("plugin.toml"),
        "name = \"seeing\"\nversion = \"0.1.0\"\n\n[[provider_profile]]\nname = \"seeing\"\nvision = true\n",
    )
    .unwrap();
}

/// `[[provider.route]]` for the describing model, as text for a config.
fn sight_route(base: &str) -> String {
    format!(
        "[[provider.route]]\nname = \"sight\"\nbase_url = \"{base}\"\nmodel = \"sight-model\"\n\
         api_key = \"none\"\nprofile = \"seeing\"\n"
    )
}

fn temp_home() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
    dir
}

/// The picture the runtime tests attach: one tiny PNG, named so a refusal or a description can be
/// read back.
fn picture() -> ImagePart {
    ImagePart::new("shot.png", "image/png", PNG)
}

fn env_of(dir: &std::path::Path) -> impl Fn(&str) -> Option<String> {
    let home = dir.display().to_string();
    move |k: &str| (k == "HOME").then(|| home.clone())
}

/// One run over a history whose last user message carries a picture: the attach and the question
/// are one message, so the turn is resumed on it rather than asking again.
async fn run_with_photo(cfg: &Config, home: &std::path::Path, question: &str) -> (Agent, String) {
    let env = env_of(home);
    let agent = Agent::from_config_with_env(cfg, &env).unwrap();
    let id = agent.store().new_id();
    let message = eclipse_core::message::Message::user(question).with_image(ImagePart::new(
        "shot.png",
        "image/png",
        PNG,
    ));
    agent.store().append(&id, &message).unwrap();
    let result = agent
        .run_with(
            Some(&id),
            "",
            &AllowAll,
            &|_| {},
            &eclipse_core::runtime::RunOptions {
                resume: true,
                ..Default::default()
            },
        )
        .await;
    let text = match result {
        Ok(run) => run.reply,
        Err(e) => format!("error: {e}"),
    };
    (agent, text)
}

/// `native` with a model whose manifest says it cannot see: the turn is refused before anything is
/// sent, and the sentence names the model.
#[tokio::test]
async fn native_refuses_before_the_turn_when_the_model_cannot_see() {
    let (base, bodies) = spawn(|_, _| None).await;
    let cfg = config(&base, "[vision]\nmode = \"native\"\n");
    let home = temp_home();
    let (_agent, text) = run_with_photo(&cfg, home.path(), "what is this?").await;
    assert!(text.contains("cannot see images"), "{text}");
    assert!(text.contains("stub-stream"), "names the model: {text}");
    assert!(
        bodies.lock().unwrap().is_empty(),
        "nothing was sent: {:?}",
        bodies.lock().unwrap()
    );
}

/// `text`: the describe route receives the picture, the turn's model receives a description and
/// never the bytes. Two servers, two bodies.
#[tokio::test]
async fn text_sends_the_picture_to_the_describe_route_and_words_to_the_turn() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square with the word STOP"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            sight_route(&sight_base)
        ),
    );
    let (_agent, text) = run_with_photo(&cfg, home.path(), "what does the sign say?").await;
    assert!(!text.contains("error:"), "{text}");

    let sight = sight_bodies.lock().unwrap();
    assert_eq!(sight.len(), 1, "the describe route was asked once");
    assert!(sight[0].contains("image_url"), "it got the picture");
    assert!(
        sight[0].contains("what does the sign say?"),
        "and the question"
    );

    let turn = turn_bodies.lock().unwrap();
    assert_eq!(turn.len(), 1, "one turn request");
    let body = &turn[0];
    assert!(
        !body.contains("image_url"),
        "the turn model never saw it: {body}"
    );
    assert!(!body.contains("iVBORw0KGgo"), "not even the bytes");
    assert!(
        body.contains("a red square with the word STOP"),
        "the description arrived: {body}"
    );
    assert!(
        body.contains("described by `sight`") && body.contains("cannot see"),
        "and says where it came from: {body}"
    );
}

/// The description is written beside the picture, so the second turn does not pay for it again.
#[tokio::test]
async fn a_stored_description_is_not_asked_for_twice() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, _turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            sight_route(&sight_base)
        ),
    );
    let env = env_of(home.path());
    let agent = Agent::from_config_with_env(&cfg, &env).unwrap();
    let id = agent.store().new_id();
    let message = eclipse_core::message::Message::user("what is this?").with_image(ImagePart::new(
        "shot.png",
        "image/png",
        PNG,
    ));
    agent.store().append(&id, &message).unwrap();
    for turn in 0..2 {
        let _ = agent
            .run_with(
                Some(&id),
                "and now?",
                &AllowAll,
                &|_| {},
                &eclipse_core::runtime::RunOptions {
                    resume: turn == 0,
                    ..Default::default()
                },
            )
            .await;
    }
    assert_eq!(
        sight_bodies.lock().unwrap().len(),
        1,
        "the picture was described once, not once per turn"
    );
}

/// `auto` with a model that declares vision: no describe call at all.
#[tokio::test]
async fn auto_does_not_call_the_describe_route_when_the_turn_model_can_see() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"unused"}}]}"#.to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    // The turn's own route is described by a manifest that claims vision.
    let dir = temp_home();
    seeing_plugin(dir.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
[[provider.route]]
name = "sight"
base_url = "{sight_base}"
model = "sight-model"
api_key = "none"
[vision]
mode = "auto"
route = "sight"
"#
    ))
    .unwrap();
    let (_agent, text) = run_with_photo(&cfg, dir.path(), "what is this?").await;
    assert!(!text.contains("error:"), "{text}");
    assert!(
        sight_bodies.lock().unwrap().is_empty(),
        "the describe route was never asked"
    );
    let turn = turn_bodies.lock().unwrap();
    assert_eq!(turn.len(), 1);
    assert!(
        turn[0].contains("image_url"),
        "the turn's own model got the picture: {}",
        turn[0]
    );
}

/// `auto` with a model that declares vision and a backend that then refuses the part: exactly one
/// second attempt, with the picture described.
#[tokio::test]
async fn a_backend_that_refuses_the_part_gets_one_described_retry() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square"}}]}"#
                .to_string(),
        ))
    })
    .await;
    // The turn's server refuses the first body that carries an image, and answers afterwards.
    let (turn_base, turn_bodies) = spawn(|_, body| {
        if body.contains("image_url") {
            Some((
                400,
                r#"{"error":{"message":"this model does not support image_url content"}}"#
                    .to_string(),
            ))
        } else {
            None
        }
    })
    .await;
    let dir = temp_home();
    seeing_plugin(dir.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
max_retries = 0
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
[[provider.route]]
name = "sight"
base_url = "{sight_base}"
model = "sight-model"
api_key = "none"
profile = "seeing"
[vision]
mode = "auto"
route = "sight"
"#
    ))
    .unwrap();
    let (_agent, text) = run_with_photo(&cfg, dir.path(), "what is this?").await;
    assert!(
        !text.contains("error:"),
        "one answer, not a failure: {text}"
    );
    let turn = turn_bodies.lock().unwrap();
    assert_eq!(
        turn.len(),
        2,
        "two attempts, the second read as a description"
    );
    assert!(
        turn[0].contains("image_url"),
        "the first carried the picture"
    );
    assert!(!turn[1].contains("image_url"), "the second did not");
    assert_eq!(
        sight_bodies.lock().unwrap().len(),
        1,
        "and the picture was described once"
    );
}

/// One run over a **fresh** turn: the picture arrives with this turn's prompt, which is the path
/// every ordinary attach takes. `#359` lived exactly here — `resume: true` (appending the message
/// first, as the 0.12.0 tests did) is the one shape where the seq is already known.
async fn fresh_turn(agent: &Agent, id: &str, question: &str, image: Option<ImagePart>) -> String {
    let images: Vec<ImagePart> = image.into_iter().collect();
    let result = agent
        .run_with(
            Some(id),
            question,
            &AllowAll,
            &|_| {},
            &eclipse_core::runtime::RunOptions {
                resume: false,
                images,
                ..Default::default()
            },
        )
        .await;
    match result {
        Ok(run) => run.reply,
        Err(e) => format!("error: {e}"),
    }
}

/// `#359`: the description is written beside the picture on the turn that carried it. `append`
/// threw the seq away, so the in-memory message had none and `sight` could not persist what it
/// learned — every fresh attach paid for two describe calls, and could read two wordings.
#[tokio::test]
async fn a_fresh_attach_stores_its_description_and_pays_for_it_once() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, _turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            sight_route(&sight_base)
        ),
    );
    let agent = Agent::from_config_with_env(&cfg, &env_of(home.path())).unwrap();
    let id = agent.store().new_id();

    let text = fresh_turn(&agent, &id, "what is this?", Some(picture())).await;
    assert!(!text.contains("error:"), "{text}");
    let stored = agent.store().load(&id).unwrap();
    let seen = stored
        .iter()
        .flat_map(|m| m.images.iter())
        .next()
        .expect("the picture is stored")
        .seen
        .clone();
    assert_eq!(seen.as_deref(), Some("a red square"), "beside the picture");

    let _ = fresh_turn(&agent, &id, "and now?", None).await;
    assert_eq!(
        sight_bodies.lock().unwrap().len(),
        1,
        "one describe call across two turns"
    );
}

/// `#360`: a refusal leaves no half-session. The picture used to be appended before the plan was
/// consulted, so every later turn on that session found it and refused again — for a question that
/// had nothing to do with it.
#[tokio::test]
async fn a_refused_attach_is_not_stored_and_the_session_still_works() {
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let cfg = config(&turn_base, "[vision]\nmode = \"native\"\n");
    let home = temp_home();
    let agent = Agent::from_config_with_env(&cfg, &env_of(home.path())).unwrap();
    let id = agent.store().new_id();

    let text = fresh_turn(&agent, &id, "what is this?", Some(picture())).await;
    assert!(text.contains("cannot see images"), "{text}");
    assert!(!agent.store().exists(&id), "nothing was written");
    assert!(
        turn_bodies.lock().unwrap().is_empty(),
        "and nothing was sent"
    );

    // The id is still usable for the follow-up the attach was meant to open.
    let text = fresh_turn(&agent, &id, "never mind — what is in this directory?", None).await;
    assert!(!text.contains("error:"), "{text}");
}

/// `#361`: the capability belongs to the provider that answers, not to the agent's default route.
/// The default declares vision, the run is pinned to a route that does not, and the picture must not
/// be sent there — and the refusal must name the model actually in use.
#[tokio::test]
async fn the_route_in_use_decides_whether_the_picture_is_sent() {
    let (default_base, default_bodies) = spawn(|_, _| None).await;
    let (blind_base, blind_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{default_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
fallback = ["default", "sighted", "blind"]
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
[[provider.route]]
name = "sighted"
base_url = "{default_base}"
model = "sighted-model"
api_key = "none"
profile = "seeing"
[[provider.route]]
name = "blind"
base_url = "{blind_base}"
model = "blind-model"
api_key = "none"
[vision]
mode = "native"
"#
    ))
    .unwrap();
    let agent = Agent::from_config_with_env(&cfg, &env_of(home.path())).unwrap();
    // The chain starts on a route that declares vision; the run is pinned to one that does not.
    agent.set_route(Some("blind")).unwrap();
    let id = agent.store().new_id();

    let text = fresh_turn(&agent, &id, "what is this?", Some(picture())).await;
    assert!(
        text.contains("blind-model cannot see images"),
        "the refusal names the model in use: {text}"
    );
    assert!(
        default_bodies.lock().unwrap().is_empty(),
        "the default route was not the one running"
    );
    assert!(
        blind_bodies.lock().unwrap().is_empty(),
        "and the blind one was never sent the bytes"
    );
}

/// `#363` (first half): a text-only turn is not retried. The matcher reads the error body, and a
/// provider echoing the user's own words back answers a 400 naming `image` — the fallback then
/// re-sent the identical request, because there was no picture to describe.
#[tokio::test]
async fn a_text_only_turn_is_not_retried_because_its_error_mentions_images() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"unused"}}]}"#.to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, _| {
        Some((
            400,
            r#"{"error":{"message":"unknown field `image_uploads`: does this tool support image uploads?"}}"#
                .to_string(),
        ))
    })
    .await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
max_retries = 0
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
{}
[vision]
mode = "auto"
route = "sight"
"#,
        sight_route(&sight_base)
    ))
    .unwrap();
    let agent = Agent::from_config_with_env(&cfg, &env_of(home.path())).unwrap();
    let id = agent.store().new_id();

    let text = fresh_turn(&agent, &id, "does this tool support image uploads?", None).await;
    assert!(
        text.contains("error:"),
        "the real error reaches the caller: {text}"
    );
    assert_eq!(
        turn_bodies.lock().unwrap().len(),
        1,
        "one request, and no retry of the same one"
    );
    assert!(
        sight_bodies.lock().unwrap().is_empty(),
        "and the describe route was not asked about a picture that is not there"
    );
}

/// `#363` (second half): once a backend has refused an image part, the refusal is remembered. The
/// next picture goes to the describe route directly instead of paying for the same 400 again — this
/// is the difference between one bad turn and a permanent 2× request tax.
#[tokio::test]
async fn a_remembered_refusal_skips_the_native_attempt_next_turn() {
    let (sight_base, _sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, body| {
        if body.contains("image_url") {
            Some((
                400,
                r#"{"error":{"message":"this model does not support image_url content"}}"#
                    .to_string(),
            ))
        } else {
            None
        }
    })
    .await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
max_retries = 0
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
{}
[vision]
mode = "auto"
route = "sight"
"#,
        sight_route(&sight_base)
    ))
    .unwrap();
    let agent = Agent::from_config_with_env(&cfg, &env_of(home.path())).unwrap();
    let id = agent.store().new_id();

    let first = fresh_turn(&agent, &id, "what is this?", Some(picture())).await;
    assert!(!first.contains("error:"), "{first}");
    let second = fresh_turn(&agent, &id, "and this one?", Some(picture())).await;
    assert!(!second.contains("error:"), "{second}");

    let native = turn_bodies
        .lock()
        .unwrap()
        .iter()
        .filter(|body| body.contains("image_url"))
        .count();
    assert_eq!(
        native,
        1,
        "only the first turn tried the native path: {:?}",
        turn_bodies.lock().unwrap().len()
    );
}

/// `text` with a describe route off this machine, and the default `allow_cloud = false`: the turn
/// is refused before anything is sent. This goes through `Agent::from_config_with_env` — the
/// constructor the runtime uses — because a hand-built `Describe` proves nothing about whether the
/// call site remembers to ask where the route is (`#356`).
#[tokio::test]
async fn a_describe_route_off_this_machine_is_refused_before_the_turn() {
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            // A public host name that never resolves: this test must fail on the privacy gate,
            // never because a request went out and timed out.
            sight_route("http://api.openai.invalid/v1")
        ),
    );
    let (_agent, text) = run_with_photo(&cfg, home.path(), "what is this?").await;
    assert!(text.contains("error:"), "the turn was refused: {text}");
    assert!(
        text.contains("allow_cloud = true") && text.contains("\"sight\""),
        "the privacy gate, naming the route: {text}"
    );
    assert!(
        !text.contains("cannot see images"),
        "the route declares vision, so the model is not the objection: {text}"
    );
    assert!(
        turn_bodies.lock().unwrap().is_empty(),
        "nothing left the machine: {:?}",
        turn_bodies.lock().unwrap()
    );
}

/// `auto`, a model whose manifest declares vision and a backend that then refuses the part, with the
/// describe route off this machine: the retry plans again instead of building a `Describe` by hand,
/// so the locality check applies to the fallback exactly as it does to a route chosen up front
/// (`#356`).
#[tokio::test]
async fn the_auto_fallback_does_not_route_a_refused_picture_to_a_remote_route() {
    let (turn_base, turn_bodies) = spawn(|_, body| {
        if body.contains("image_url") {
            Some((
                400,
                r#"{"error":{"message":"this model does not support image_url content"}}"#
                    .to_string(),
            ))
        } else {
            None
        }
    })
    .await;
    let dir = temp_home();
    seeing_plugin(dir.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "stub-stream"
api_key = "none"
profile = "seeing"
max_retries = 0
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
{}
[vision]
mode = "auto"
route = "sight"
"#,
        sight_route("http://api.openai.invalid/v1")
    ))
    .unwrap();
    let (_agent, text) = run_with_photo(&cfg, dir.path(), "what is this?").await;
    assert!(
        text.contains("allow_cloud = true") && text.contains("\"sight\""),
        "the fallback is gated too: {text}"
    );
    let turn = turn_bodies.lock().unwrap();
    assert_eq!(
        turn.len(),
        1,
        "one attempt, the one that carried the picture: {turn:?}"
    );
    assert!(turn[0].contains("image_url"), "and it did carry it");
}

/// `#383`: a picture-only turn's content *is* the marker the composer added, so the describe route
/// was asked "--- attached picture: shot.png (image/png) ---" and the default question was
/// unreachable from the dashboard.
#[tokio::test]
async fn a_picture_only_turn_asks_the_default_question() {
    let (sight_base, sight_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a red square"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            sight_route(&sight_base)
        ),
    );
    let marker = "--- attached picture: shot.png (image/png) ---";
    let (_agent, text) = run_with_photo(&cfg, home.path(), marker).await;
    assert!(!text.contains("error:"), "{text}");

    let sight = sight_bodies.lock().unwrap();
    assert_eq!(sight.len(), 1, "the describe route was asked once");
    assert!(
        sight[0].contains("Describe this picture in enough detail"),
        "the marker is structure, not a question: {}",
        sight[0]
    );
    assert!(
        !sight[0].contains("attached picture:"),
        "the marker was not sent as the question: {}",
        sight[0]
    );
    // And the turn's model is not told the person asked the marker either.
    let turn = turn_bodies.lock().unwrap();
    assert!(!turn[0].contains("attached picture:"), "{}", turn[0]);
}

/// A route that takes the request and never answers — the only honest way to prove a call is
/// cancellable rather than merely quick.
async fn spawn_silent() -> String {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    tokio::spawn(async move {
        loop {
            let Ok((mut socket, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                let mut chunk = [0u8; 4096];
                while socket.read(&mut chunk).await.unwrap_or(0) > 0 {}
                // Held open and silent until the test ends.
                std::future::pending::<()>().await;
            });
        }
    });
    base
}

/// `#386`: the describe call is cancellable. Without a `select!` on the run's flag, pressing Stop
/// during a description waits for that route to answer or time out.
#[tokio::test]
async fn a_cancelled_run_does_not_wait_for_the_describe_route() {
    let sight_base = spawn_silent().await;
    let (turn_base, _turn) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = config(
        &turn_base,
        &format!(
            "{}\n[plugins]\nenabled = [\"seeing\"]\n[vision]\nmode = \"text\"\nroute = \"sight\"\n",
            sight_route(&sight_base)
        ),
    );
    let env = env_of(home.path());
    let agent = Agent::from_config_with_env(&cfg, &env).unwrap();
    let id = agent.store().new_id();
    let message = eclipse_core::message::Message::user("look").with_image(ImagePart::new(
        "shot.png",
        "image/png",
        PNG,
    ));
    agent.store().append(&id, &message).unwrap();

    let cancel = eclipse_core::cancel::Cancel::new();
    let flag = cancel.clone();
    let start = std::time::Instant::now();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        flag.cancel();
    });
    let result = agent
        .run_cancellable_with(
            Some(&id),
            "",
            &AllowAll,
            &|_| {},
            &cancel,
            &eclipse_core::runtime::RunOptions {
                resume: true,
                ..Default::default()
            },
        )
        .await;
    let elapsed = start.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(5),
        "the run waited for the describe route to answer: {elapsed:?}"
    );
    match result {
        Err(e) => assert!(
            matches!(e, eclipse_core::Error::Cancelled),
            "it stopped because it was cancelled, not for another reason: {e}"
        ),
        Ok(run) => panic!("a cancelled run has no reply: {:?}", run.reply),
    }
}

/// `#491` AC 1: with `vision = true` on a `[[provider.route]]`, `route = "aux"` and `mode = "auto"`,
/// attaching a picture describes it through `aux` while the blind `llamacpp` main route only sees words.
#[tokio::test]
async fn route_vision_true_allows_local_llamacpp_aux_route_to_describe() {
    let (aux_base, aux_bodies) = spawn(|_, _| {
        Some((
            200,
            r#"{"choices":[{"message":{"role":"assistant","content":"a blue lighthouse"}}]}"#
                .to_string(),
        ))
    })
    .await;
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "inkling-2-mini"
api_key = "none"
profile = "llamacpp"
[sessions]
autotitle = false
[context]
judge = false
[[provider.route]]
name = "aux"
base_url = "{aux_base}"
model = "gemma-4-12b"
api_key = "none"
profile = "llamacpp"
vision = true
[vision]
mode = "auto"
route = "aux"
"#
    ))
    .unwrap();

    let (_agent, text) = run_with_photo(&cfg, home.path(), "what is on this picture?").await;
    assert!(!text.contains("error:"), "{text}");

    let aux = aux_bodies.lock().unwrap();
    assert_eq!(aux.len(), 1, "aux described the picture once");
    assert!(aux[0].contains("image_url"), "aux received the picture");

    let turn = turn_bodies.lock().unwrap();
    assert_eq!(turn.len(), 1, "main route ran once");
    assert!(!turn[0].contains("image_url"), "main route got words only");
    assert!(turn[0].contains("a blue lighthouse"), "{}", turn[0]);
}

/// `#491` AC 4: explicit `vision = false` on a route overrides a profile that declares `vision = true`.
#[tokio::test]
async fn route_vision_false_overrides_a_seeing_profile() {
    let (turn_base, turn_bodies) = spawn(|_, _| None).await;
    let home = temp_home();
    seeing_plugin(home.path());
    let cfg = Config::from_toml_str(&format!(
        r#"
[provider]
base_url = "{turn_base}"
model = "blind-model"
api_key = "none"
profile = "seeing"
vision = false
[sessions]
autotitle = false
[context]
judge = false
[plugins]
enabled = ["seeing"]
[vision]
mode = "native"
"#
    ))
    .unwrap();

    let (_agent, text) = run_with_photo(&cfg, home.path(), "what is this?").await;
    assert!(text.contains("blind-model cannot see images"), "{text}");
    assert!(
        turn_bodies.lock().unwrap().is_empty(),
        "no request was sent to a route forced blind"
    );
}