yolop 0.3.0

Yolop — a terminal coding agent built on everruns-runtime
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
// Integration tests for the yolop binary.
//
// The unignored tests exercise the offline `llmsim` provider so CI can prove
// the binary still launches and the agent loop wires up correctly without any
// API key.
//
// The live tests reach real provider endpoints (OpenAI and OpenRouter). They
// skip themselves when the relevant API key is absent, so a plain `cargo test`
// stays offline — no `#[ignore]` needed. CI's live-smoke job runs them under
// Doppler with `YOLOP_REQUIRE_LIVE_TESTS=1`, which upgrades a missing key from
// "skip" to a hard failure so a misconfigured secret can't report a false
// green:
//
//     YOLOP_REQUIRE_LIVE_TESTS=1 doppler run -- cargo test --test integration
//
// The OpenRouter tests default to a Nemotron 3 model and guard the OpenRouter
// driver's tool-calling and turn-chaining path (everruns EVE-522 / EVE-523).

mod support;

use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::{Duration, Instant};

use support::mock_openai::MockOpenAiServer;
use support::strip_ansi;
use support::tui_harness::{
    TuiSpawnOptions, assert_cursor_near_bottom, spawn_tui_llmsim, spawn_tui_llmsim_with,
    spawn_tui_llmsim_with_settings, wait_for_exit,
};

fn yolop_binary() -> PathBuf {
    // CARGO_BIN_EXE_<name> is set by Cargo for integration tests.
    PathBuf::from(env!("CARGO_BIN_EXE_yolop"))
}

#[test]
fn help_flag_succeeds() {
    let output = Command::new(yolop_binary())
        .arg("--help")
        .output()
        .expect("spawn yolop --help");
    assert!(
        output.status.success(),
        "yolop --help failed: stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("yolop"), "help output missing binary name");
    assert!(
        stdout.contains("--provider"),
        "help output missing --provider"
    );
    assert!(stdout.contains("--print"), "help output missing --print");
}

#[test]
fn version_flag_succeeds() {
    let output = Command::new(yolop_binary())
        .arg("--version")
        .output()
        .expect("spawn yolop --version");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_version_output(&stdout);
}

#[test]
fn version_command_succeeds() {
    let output = Command::new(yolop_binary())
        .arg("version")
        .output()
        .expect("spawn yolop version");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_version_output(&stdout);
}

fn assert_version_output(stdout: &str) {
    assert!(
        stdout.contains("yolop"),
        "version output missing binary name: {stdout}"
    );
    assert!(
        stdout.contains(env!("CARGO_PKG_VERSION")),
        "version output missing package version: {stdout}"
    );
    assert!(
        stdout.contains("commit "),
        "version output missing commit SHA: {stdout}"
    );
    assert!(
        stdout.contains("everruns-runtime "),
        "version output missing runtime version: {stdout}"
    );
}

#[test]
fn into_zed_command_writes_acp_settings() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let settings = tmp.path().join("zed/settings.json");

    let output = Command::new(yolop_binary())
        .args([
            "into",
            "zed",
            "--settings",
            settings.to_str().unwrap(),
            "--command",
            "/tmp/yolop",
        ])
        .output()
        .expect("spawn yolop into zed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "into zed failed: stdout={stdout} stderr={stderr}"
    );
    assert!(
        stdout.contains("added `yolop` ACP agent"),
        "unexpected into stdout: {stdout}"
    );
    let value: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(settings).expect("settings")).unwrap();
    assert_eq!(value["agent_servers"]["yolop"]["type"], "custom");
    assert_eq!(value["agent_servers"]["yolop"]["command"], "/tmp/yolop");
    assert_eq!(
        value["agent_servers"]["yolop"]["args"],
        serde_json::json!(["--acp"])
    );
}

#[test]
fn llmsim_print_smoke() {
    // The llmsim provider needs no API key and returns deterministic output.
    // We point --session-dir at a temp dir so the test never touches the
    // user's real ~/.local/share/yolop.
    let tmp = tempfile::tempdir().expect("tempdir");
    let output = Command::new(yolop_binary())
        .args([
            "--provider",
            "llmsim",
            "--session-dir",
            tmp.path().to_str().unwrap(),
            "-p",
            "hi",
        ])
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OLLAMA_BASE_URL")
        .env_remove("OLLAMA_API_KEY")
        .output()
        .expect("spawn yolop --provider llmsim -p hi");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "yolop llmsim run failed: stdout={stdout} stderr={stderr}"
    );
    // The print driver always emits a `done success=...` summary line.
    assert!(
        stdout.contains("done") && stdout.contains("success="),
        "missing done summary line: {stdout}"
    );
    // Session line should mention the llmsim model so we know the provider
    // wiring picked the offline driver.
    assert!(
        stdout.contains("llmsim"),
        "expected llmsim in stdout: {stdout}"
    );
}

#[test]
fn llmsim_resume_replays_prior_events() {
    // Two-shot test: the first invocation starts a fresh session and writes a
    // JSONL log; the second invocation resumes that session via `--session <id>`
    // and must replay the prior events (startup line reports "N prior event(s)"
    // with N > 0). Proves the session_dir + session id wiring round-trips.
    let tmp = tempfile::tempdir().expect("tempdir");
    let session_dir = tmp.path().to_str().unwrap();

    let first = Command::new(yolop_binary())
        .args([
            "--provider",
            "llmsim",
            "--session-dir",
            session_dir,
            "-p",
            "hi",
        ])
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OLLAMA_BASE_URL")
        .env_remove("OLLAMA_API_KEY")
        .output()
        .expect("spawn first yolop run");
    let first_stdout = String::from_utf8_lossy(&first.stdout).to_string();
    let first_stderr = String::from_utf8_lossy(&first.stderr).to_string();
    assert!(
        first.status.success(),
        "first run failed: stdout={first_stdout} stderr={first_stderr}"
    );
    let session_id = extract_session_id(&first_stdout)
        .unwrap_or_else(|| panic!("could not find session id in stdout: {first_stdout}"));
    assert!(
        first_stdout.contains("0 prior event(s)"),
        "first run should start with no replayed events: {first_stdout}"
    );

    let second = Command::new(yolop_binary())
        .args([
            "--provider",
            "llmsim",
            "--session-dir",
            session_dir,
            "--session",
            &session_id,
            "-p",
            "second turn",
        ])
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OLLAMA_BASE_URL")
        .env_remove("OLLAMA_API_KEY")
        .output()
        .expect("spawn resume yolop run");
    let second_stdout = String::from_utf8_lossy(&second.stdout).to_string();
    let second_stderr = String::from_utf8_lossy(&second.stderr).to_string();
    assert!(
        second.status.success(),
        "resume run failed: stdout={second_stdout} stderr={second_stderr}"
    );
    // Resume should reuse the same session id and report a non-zero replay count.
    assert!(
        second_stdout.contains(&session_id),
        "resume stdout should mention reused session id {session_id}: {second_stdout}"
    );
    let prior = parse_prior_events(&second_stdout)
        .unwrap_or_else(|| panic!("could not find prior event count in stdout: {second_stdout}"));
    assert!(
        prior > 0,
        "resume run must replay >0 events, got {prior}: {second_stdout}"
    );
}

#[test]
fn llmsim_unknown_session_id_is_invalid() {
    // A malformed `--session` value should fail at parse time with a clear
    // error, not crash later in the runtime layer.
    let tmp = tempfile::tempdir().expect("tempdir");
    let output = Command::new(yolop_binary())
        .args([
            "--provider",
            "llmsim",
            "--session-dir",
            tmp.path().to_str().unwrap(),
            "--session",
            "not-a-valid-id",
            "-p",
            "hi",
        ])
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OLLAMA_BASE_URL")
        .env_remove("OLLAMA_API_KEY")
        .output()
        .expect("spawn yolop with bad session id");
    assert!(
        !output.status.success(),
        "expected non-zero exit for malformed --session"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("invalid --session") || stderr.contains("session"),
        "expected diagnostic mentioning session id: {stderr}"
    );
}

#[test]
fn tui_escape_does_not_exit_and_ctrl_c_exits() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"\x1b");
    assert!(
        wait_for_exit(&mut *tui.child, Duration::from_millis(700)).is_none(),
        "Esc should not exit the TUI: {}",
        tui.output_text()
    );

    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(3));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly, got {status:?}: {}",
        tui.output_text()
    );
    assert!(
        tui.output_text().contains("Resume with yolop --session"),
        "Ctrl-C cleanup should print resume hint: {}",
        tui.output_text()
    );
}

#[test]
fn tui_alt_enter_sequence_submits_like_enter() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"one\x1b\r");
    assert!(
        tui.wait_for_output("one", Duration::from_secs(3)),
        "Alt-Enter should submit like Enter: {}",
        tui.output_text()
    );
    assert!(
        tui.wait_for_output("offline mode", Duration::from_secs(3)),
        "first turn did not complete before second input: {}",
        tui.output_text()
    );

    tui.write_input(b"two\r");
    assert!(
        tui.wait_for_output("two", Duration::from_secs(3)),
        "plain Enter did not submit second input: {}",
        tui.output_text()
    );
    let after_submit = strip_ansi(&tui.output_text());
    assert!(
        after_submit.contains("one") && after_submit.contains("two"),
        "submitted text should render both turns: {after_submit}"
    );

    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(3));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly, got {status:?}: {}",
        tui.output_text()
    );
}

#[test]
fn tui_survives_slow_cursor_position_reply_after_resize() {
    // Regression test for the TUI dying right around turn completion under
    // xterm.js-backed terminals (ttyd / vhs recordings). Those emulators
    // resize the PTY mid-session (fit-addon re-measuring once the scrollbar
    // appears or fonts settle) and can be slow to answer the `CSI 6n`
    // cursor-position query ratatui issues to re-anchor the inline viewport
    // after a resize — crossterm gives up on that query after 2 seconds.
    // That transient failure must not exit the TUI.
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"hi\r");
    assert!(
        tui.wait_for_output("offline mode", Duration::from_secs(5)),
        "turn did not complete: {}",
        tui.output_text()
    );

    // Shrink the PTY by one column, like xterm.js does when its scrollbar
    // appears as the transcript first overflows. The harness deliberately
    // does NOT answer the cursor-position query this triggers, emulating a
    // busy emulator. crossterm's 2s query timeout fires at least once.
    tui.set_answer_cursor_queries(false);
    tui.resize(79, 24);
    assert!(
        wait_for_exit(&mut *tui.child, Duration::from_secs(5)).is_none(),
        "TUI exited after an unanswered cursor-position query: {}",
        tui.output_text()
    );

    // The emulator catches up: answer the (retried) query by hand, resume
    // answering future queries, then Ctrl-C. The manual reply must come
    // first — the event loop is blocked inside the cursor query until it
    // arrives, and the harness responder only answers queries it sees after
    // being re-enabled.
    tui.write_input(b"\x1b[1;1R");
    tui.set_answer_cursor_queries(true);
    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(10));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly after recovery, got {status:?}: {}",
        tui.output_text()
    );
}

// ratatui 0.30.1 `Terminal::clear` snapshots the cursor with a blocking
// `CSI 6n` query, and the inline viewport calls `clear` inside
// `insert_before` — so viewport anchoring, every transcript flush, and exit
// cleanup all issue cursor-position queries beyond the one
// `Terminal::with_options` always made. A slow emulator (ttyd / xterm.js,
// see the resize test above) may answer the first query and then go silent.
// These paths are cosmetic: crossterm's ~2s per-query timeout must degrade
// the session, not kill it. The two tests below pin that down for startup
// and for exit.

#[test]
fn tui_starts_when_emulator_answers_only_the_first_cursor_query() {
    let mut tui = spawn_tui_llmsim_with(
        &yolop_binary(),
        TuiSpawnOptions {
            cursor_reply_budget: 1,
            ..TuiSpawnOptions::default()
        },
    );
    // Every unanswered query eats a ~2s crossterm timeout before yolop moves
    // on, so the banner can take several stalls to appear. The point is that
    // it appears at all instead of the process dying at anchor time.
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(20)),
        "TUI did not render startup banner despite anchoring query going unanswered: {}",
        tui.output_text()
    );
    assert!(
        wait_for_exit(&mut *tui.child, Duration::from_millis(200)).is_none(),
        "TUI exited after unanswered cursor-position queries: {}",
        tui.output_text()
    );
}

#[test]
fn tui_exits_cleanly_when_emulator_stops_answering_cursor_queries() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    // The emulator goes silent after startup; Ctrl-C's terminal cleanup
    // (`Terminal::clear`) gets no answer to its cursor query. The session
    // was successful, so the exit must still be clean.
    tui.set_answer_cursor_queries(false);
    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(10));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly despite cleanup query going unanswered, got {status:?}: {}",
        tui.output_text()
    );
    assert!(
        tui.output_text().contains("Resume with yolop --session"),
        "cleanup should still print resume hint: {}",
        tui.output_text()
    );
}

#[test]
fn tui_startup_anchors_composer_from_top_in_tall_terminal() {
    let mut tui = spawn_tui_llmsim_with(
        &yolop_binary(),
        TuiSpawnOptions {
            rows: 40,
            cols: 100,
            cursor_row: 1,
            ..TuiSpawnOptions::default()
        },
    );
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    assert_cursor_near_bottom(&mut tui, 40);
}

#[test]
fn tui_startup_anchors_composer_when_prompt_is_already_near_bottom() {
    let mut tui = spawn_tui_llmsim_with(
        &yolop_binary(),
        TuiSpawnOptions {
            rows: 24,
            cols: 80,
            cursor_row: 23,
            ..TuiSpawnOptions::default()
        },
    );
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    assert_cursor_near_bottom(&mut tui, 24);
}

#[test]
fn tui_startup_anchors_composer_in_short_terminal() {
    let mut tui = spawn_tui_llmsim_with(
        &yolop_binary(),
        TuiSpawnOptions {
            rows: 8,
            cols: 80,
            cursor_row: 1,
            ..TuiSpawnOptions::default()
        },
    );
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    assert_cursor_near_bottom(&mut tui, 8);
}

#[test]
fn tui_setup_overlay_renders_in_real_pty() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"/setup\r");
    assert!(
        tui.wait_for_output("Set Up Yolop", Duration::from_secs(3)),
        "/setup should render setup overlay: {}",
        tui.output_text()
    );
    assert!(
        tui.wait_for_output("Esc cancel", Duration::from_secs(3)),
        "/setup footer should render without clipping: {}",
        tui.output_text()
    );
}

/// Drive the real TUI binary through the whole model-selection flow:
/// `/setup` → quick-select a provider that is already connected (saved key)
/// → the wizard jumps straight to the model picker → quick-select a preset
/// model → the switch is announced and persisted to settings.toml.
#[test]
fn tui_setup_selects_model_for_connected_provider_in_real_pty() {
    let mut tui = spawn_tui_llmsim_with_settings(
        &yolop_binary(),
        TuiSpawnOptions::default(),
        "provider = \"llmsim\"\n\n[tokens]\nopenai = \"sk-test\"\n",
    );
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"/setup\r");
    assert!(
        tui.wait_for_output("Set Up Yolop", Duration::from_secs(3)),
        "/setup should render the provider picker: {}",
        tui.output_text()
    );
    assert!(
        tui.wait_for_output("saved key", Duration::from_secs(3)),
        "OpenAI should show as connected via the saved key: {}",
        tui.output_text()
    );

    // Quick-select OpenAI (row 1). It is connected, so the wizard must skip
    // the credential step and open the model picker directly. Render diffs
    // are unreliable to wait on (ratatui repaints only changed cells and the
    // async "fetching models" hint shifts rows), so wait on the side effect
    // that the fast path produces just before the picker opens: the provider
    // switch is persisted to settings.toml.
    tui.write_input(b"1");
    let deadline = Instant::now() + Duration::from_secs(3);
    while Instant::now() < deadline
        && !std::fs::read_to_string(tui.settings_path())
            .unwrap_or_default()
            .contains("provider = \"openai\"")
    {
        thread::sleep(Duration::from_millis(20));
    }
    let before_pick = strip_ansi(&tui.output_text());
    assert!(
        !before_pick.contains("API Key for OpenAI"),
        "credential step should be skipped for a connected provider: {before_pick}"
    );

    // Quick-select the second preset (gpt-5.4).
    tui.write_input(b"2");
    assert!(
        tui.wait_for_output(
            "setup complete: openai/gpt-5.4 medium",
            Duration::from_secs(3)
        ),
        "model selection should complete with the picked model: {}",
        tui.output_text()
    );

    let settings =
        std::fs::read_to_string(tui.settings_path()).expect("read settings written by the TUI");
    assert!(
        settings.contains("provider = \"openai\""),
        "provider switch should persist: {settings}"
    );
    assert!(
        settings.contains("openai = \"gpt-5.4 medium\""),
        "picked model should persist under [models]: {settings}"
    );

    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(3));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly, got {status:?}: {}",
        tui.output_text()
    );
}

/// A model picked via `/setup model` must be restored on the next run and
/// actually sent to the provider. Seeds settings the way the wizard writes
/// them (custom provider, saved base URL + model), runs one `--print` turn
/// against a mock OpenAI-compatible server, and asserts the request body
/// carries the saved model id.
#[test]
fn print_mode_sends_saved_model_selection_to_endpoint() {
    let mock = MockOpenAiServer::spawn("hello from custom endpoint");
    let home = tempfile::tempdir().expect("home tempdir");
    let sessions = tempfile::tempdir().expect("sessions tempdir");
    let settings_toml = format!(
        "provider = \"custom\"\n\n[base_urls]\ncustom = \"{}\"\n\n[models]\ncustom = \"picked-model-x\"\n",
        mock.base_url
    );
    for settings_dir in [
        home.path().join(".config/yolop"),
        home.path().join("Library/Application Support/yolop"),
    ] {
        std::fs::create_dir_all(&settings_dir).expect("create settings dir");
        std::fs::write(settings_dir.join("settings.toml"), &settings_toml).expect("write settings");
    }

    let output = Command::new(yolop_binary())
        .args([
            "--session-dir",
            sessions.path().to_str().unwrap(),
            "-p",
            "hi",
        ])
        .env("HOME", home.path())
        .env("XDG_CONFIG_HOME", home.path().join(".config"))
        .env("XDG_DATA_HOME", home.path().join(".local/share"))
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("GEMINI_API_KEY")
        .env_remove("GOOGLE_API_KEY")
        .env_remove("OLLAMA_BASE_URL")
        .env_remove("OLLAMA_API_KEY")
        .env_remove("CUSTOM_BASE_URL")
        .env_remove("CUSTOM_API_KEY")
        .env_remove("EVERRUNS_CLI_MODEL")
        .env_remove("EVERRUNS_CLI_REASONING_EFFORT")
        .output()
        .expect("spawn yolop against mock endpoint");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "saved-model run failed: stdout={stdout} stderr={stderr}"
    );
    assert!(
        stdout.contains("custom/picked-model-x"),
        "startup banner should show the restored model: {stdout}"
    );
    assert!(
        stdout.contains("hello from custom endpoint"),
        "mock reply should reach the transcript: {stdout}"
    );

    let request = mock.next_request(Duration::from_secs(5));
    assert_eq!(
        request["model"], "picked-model-x",
        "request must carry the saved model id: {request}"
    );
}

#[test]
fn tui_submit_turn_renders_assistant_in_scrollback() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"scrollback smoke\r");
    assert!(
        tui.wait_for_output("scrollback smoke", Duration::from_secs(3)),
        "submitted prompt should appear in scrollback: {}",
        tui.output_text()
    );
    assert!(
        tui.wait_for_output("offline mode", Duration::from_secs(5)),
        "assistant reply should land in scrollback after turn completion: {}",
        tui.output_text()
    );

    let transcript = strip_ansi(&tui.output_text());
    assert!(
        transcript.contains("scrollback smoke") && transcript.contains("offline mode"),
        "scrollback should retain both user prompt and assistant reply: {transcript}"
    );

    tui.write_input(b"\x03");
    let status = tui.wait_or_kill(Duration::from_secs(3));
    assert!(
        status.success(),
        "Ctrl-C should exit cleanly, got {status:?}: {}",
        tui.output_text()
    );
}

#[test]
fn tui_double_ctrl_c_exits() {
    let mut tui = spawn_tui_llmsim(&yolop_binary());
    assert!(
        tui.wait_for_output("type /help", Duration::from_secs(3)),
        "TUI did not render startup banner: {}",
        tui.output_text()
    );

    tui.write_input(b"\x03\x03");
    let status = tui.wait_or_kill(Duration::from_secs(3));
    assert!(
        status.success(),
        "double Ctrl-C should exit cleanly, got {status:?}: {}",
        tui.output_text()
    );
}

/// Parse the session id printed on the `session …` line of `--print` stdout.
/// The line shape is:
/// `session   <id> (folder: ...; log: ...; N prior event(s))`
fn extract_session_id(stdout: &str) -> Option<String> {
    for line in stdout.lines() {
        // The line begins with a possibly-coloured "session" token and a run
        // of whitespace before the id. Strip ANSI escapes defensively.
        let stripped = strip_ansi(line);
        let trimmed = stripped.trim_start();
        if let Some(rest) = trimmed.strip_prefix("session") {
            let rest = rest.trim_start();
            // First whitespace-delimited token is the id.
            let id = rest.split_whitespace().next()?;
            if !id.is_empty() {
                return Some(id.to_string());
            }
        }
    }
    None
}

/// Parse the `N prior event(s)` count from the same session line.
fn parse_prior_events(stdout: &str) -> Option<u64> {
    for line in stdout.lines() {
        let stripped = strip_ansi(line);
        if let Some(idx) = stripped.find(" prior event(s)") {
            let head = &stripped[..idx];
            let count = head.rsplit(|c: char| !c.is_ascii_digit()).next()?;
            if !count.is_empty() {
                return count.parse().ok();
            }
        }
    }
    None
}

/// Result of one scripted ACP handshake against the real binary.
struct AcpHandshake {
    init: serde_json::Value,
    session_id: String,
    prompt: serde_json::Value,
    /// All `agent_message_chunk` text streamed during the prompt, concatenated.
    assistant_text: String,
    /// True if the process exited cleanly after stdin was closed.
    exited_cleanly: bool,
}

/// Spawn `yolop --acp <provider>` over real OS stdin/stdout pipes and drive the
/// full JSON-RPC handshake: initialize → session/new → session/prompt, closing
/// stdin to let the agent exit. Returns the responses and streamed text so
/// callers can assert per-provider behaviour. Exercises the binary's actual
/// ACP wiring, not just the in-process `serve` tests.
fn run_acp_handshake(provider: &str, prompt_text: &str) -> AcpHandshake {
    use std::io::BufRead;
    use std::process::{Command as StdCommand, Stdio};

    let session_dir = tempfile::tempdir().expect("session tempdir");
    let workspace = tempfile::tempdir().expect("workspace tempdir");

    let mut child = StdCommand::new(yolop_binary())
        .args([
            "--acp",
            "--provider",
            provider,
            "--session-dir",
            session_dir.path().to_str().unwrap(),
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn yolop --acp");

    let mut stdin = child.stdin.take().expect("acp stdin");
    let (line_tx, line_rx) = mpsc::channel::<String>();
    let stdout = child.stdout.take().expect("acp stdout");
    let reader = thread::spawn(move || {
        let mut buf = std::io::BufReader::new(stdout);
        loop {
            let mut line = String::new();
            match buf.read_line(&mut line) {
                Ok(0) => break,
                Ok(_) => {
                    if line_tx.send(line).is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
    });

    let send = |stdin: &mut std::process::ChildStdin, value: serde_json::Value| {
        let line = format!("{value}\n");
        stdin.write_all(line.as_bytes()).expect("write acp request");
        stdin.flush().expect("flush acp request");
    };

    // Collect lines until one parses to a JSON object with the given response
    // id (carrying result or error). `agent_message_chunk` notifications seen
    // along the way are accumulated into `assistant_text`.
    let assistant_text = std::cell::RefCell::new(String::new());
    let await_response = |rx: &Receiver<String>, id: i64| -> serde_json::Value {
        let deadline = Instant::now() + Duration::from_secs(60);
        while Instant::now() < deadline {
            match rx.recv_timeout(Duration::from_millis(500)) {
                Ok(line) => {
                    let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
                        continue;
                    };
                    if value["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                        && let Some(text) = value["params"]["update"]["content"]["text"].as_str()
                    {
                        assistant_text.borrow_mut().push_str(text);
                    }
                    if value.get("id").and_then(serde_json::Value::as_i64) == Some(id)
                        && (value.get("result").is_some() || value.get("error").is_some())
                    {
                        return value;
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => continue,
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
        panic!("timed out awaiting acp response id={id}");
    };

    send(
        &mut stdin,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 0,
            "method": "initialize",
            "params": {
                "protocolVersion": 1,
                "clientCapabilities": { "fs": { "readTextFile": true, "writeTextFile": true } }
            }
        }),
    );
    let init = await_response(&line_rx, 0);

    send(
        &mut stdin,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "session/new",
            "params": { "cwd": workspace.path().to_str().unwrap(), "mcpServers": [] }
        }),
    );
    let new_session = await_response(&line_rx, 1);
    let session_id = new_session["result"]["sessionId"]
        .as_str()
        .unwrap_or_else(|| panic!("sessionId in response: {new_session}"))
        .to_string();

    send(
        &mut stdin,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "session/prompt",
            "params": {
                "sessionId": session_id,
                "prompt": [{ "type": "text", "text": prompt_text }]
            }
        }),
    );
    let prompt = await_response(&line_rx, 2);

    // Closing stdin makes the agent's read loop hit EOF and exit cleanly.
    drop(stdin);
    let status = wait_for_process_exit(&mut child, Duration::from_secs(10));
    let _ = reader.join();

    AcpHandshake {
        init,
        session_id,
        prompt,
        assistant_text: assistant_text.into_inner(),
        exited_cleanly: status.map(|s| s.success()).unwrap_or(false),
    }
}

#[test]
fn acp_stdio_handshake_smoke() {
    // env_remove on the parent process is unnecessary: --provider llmsim wins,
    // and the offline driver needs no key.
    let result = run_acp_handshake("llmsim", "hi");
    assert_eq!(
        result.init["result"]["protocolVersion"], 1,
        "initialize response: {}",
        result.init
    );
    assert!(
        result.session_id.starts_with("session_"),
        "unexpected session id: {}",
        result.session_id
    );
    assert_eq!(
        result.prompt["result"]["stopReason"], "end_turn",
        "prompt response: {}",
        result.prompt
    );
    assert!(
        !result.assistant_text.is_empty(),
        "expected a streamed agent_message_chunk"
    );
    assert!(
        result.exited_cleanly,
        "yolop --acp should exit cleanly after stdin close"
    );
}

/// Resolve a provider API key for a live test.
///
/// Returns `None` (the test should then `return` early) when the key is absent,
/// so a plain `cargo test` run stays offline without any `#[ignore]`. CI's
/// live-smoke job sets `YOLOP_REQUIRE_LIVE_TESTS=1`, which turns a missing key
/// into a hard failure — a misconfigured secret must not let the live check
/// report a false green.
///
/// This is a presence check only: it never reads the key value into memory, so
/// the secret is not materialized here and a non-UTF-8 value still counts as
/// present.
fn live_key_or_skip(var: &str) -> Option<()> {
    if std::env::var_os(var).is_some_and(|value| !value.is_empty()) {
        return Some(());
    }
    assert!(
        std::env::var_os("YOLOP_REQUIRE_LIVE_TESTS").is_none(),
        "{var} is required when YOLOP_REQUIRE_LIVE_TESTS is set"
    );
    eprintln!("skipping live test: {var} not set");
    None
}

#[test]
fn acp_openai_handshake_smoke() {
    let Some(_) = live_key_or_skip("OPENAI_API_KEY") else {
        return;
    };
    let result = run_acp_handshake("openai", "Reply with exactly the single word: pong");
    assert_eq!(
        result.prompt["result"]["stopReason"], "end_turn",
        "prompt response: {}",
        result.prompt
    );
    assert!(
        result.assistant_text.to_lowercase().contains("pong"),
        "expected `pong` in streamed assistant text, got: {:?}",
        result.assistant_text
    );
    assert!(result.exited_cleanly, "agent should exit cleanly");
}

#[test]
#[ignore = "requires ANTHROPIC_API_KEY; run under doppler with --ignored"]
fn acp_anthropic_handshake_smoke() {
    let Ok(_) = std::env::var("ANTHROPIC_API_KEY") else {
        panic!("ANTHROPIC_API_KEY required for live ACP smoke test");
    };
    let result = run_acp_handshake("anthropic", "Reply with exactly the single word: pong");
    assert_eq!(
        result.prompt["result"]["stopReason"], "end_turn",
        "prompt response: {}",
        result.prompt
    );
    assert!(
        result.assistant_text.to_lowercase().contains("pong"),
        "expected `pong` in streamed assistant text, got: {:?}",
        result.assistant_text
    );
    assert!(result.exited_cleanly, "agent should exit cleanly");
}

fn wait_for_process_exit(
    child: &mut std::process::Child,
    timeout: Duration,
) -> Option<std::process::ExitStatus> {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        match child.try_wait().expect("poll acp child") {
            Some(status) => return Some(status),
            None => thread::sleep(Duration::from_millis(20)),
        }
    }
    let _ = child.kill();
    child.try_wait().expect("poll acp child after kill")
}

#[test]
fn openai_print_smoke() {
    let Some(_) = live_key_or_skip("OPENAI_API_KEY") else {
        return;
    };
    let tmp = tempfile::tempdir().expect("tempdir");
    let output = Command::new(yolop_binary())
        .args([
            "--provider",
            "openai",
            "--session-dir",
            tmp.path().to_str().unwrap(),
            "-p",
            "Reply with exactly the single word: pong",
        ])
        .output()
        .expect("spawn yolop --provider openai");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "yolop openai smoke failed: stdout={stdout} stderr={stderr}"
    );
    assert!(
        stdout.to_lowercase().contains("pong"),
        "expected `pong` in stdout: {stdout}"
    );
    assert!(
        stdout.contains("success=true"),
        "expected success=true: {stdout}"
    );
}

/// Model used by the live OpenRouter smoke tests. Defaults to a Nemotron 3
/// variant (the path these tests exist to protect); override with
/// `YOLOP_LIVE_OPENROUTER_MODEL` to pin a cheaper or less rate-limited model in
/// CI without touching code.
fn live_openrouter_model() -> String {
    std::env::var("YOLOP_LIVE_OPENROUTER_MODEL")
        .unwrap_or_else(|_| "nvidia/nemotron-3-ultra-550b-a55b".to_string())
}

/// True when a live run failed only because the upstream provider rate-limited
/// us (HTTP 429). That is infrastructure, not a yolop regression, so the live
/// OpenRouter tests skip on it rather than fail — the shared Nemotron endpoints
/// 429 often enough to make a required CI check flaky otherwise. A real
/// regression in the tool-calling path produces a missing sentinel or
/// `success=false`, not a 429, so it is still caught.
fn looks_rate_limited(combined: &str) -> bool {
    let lower = combined.to_lowercase();
    combined.contains("429")
        && (lower.contains("rate-limit") || lower.contains("too many requests"))
}

#[test]
fn openrouter_print_smoke() {
    let Some(_) = live_key_or_skip("OPENROUTER_API_KEY") else {
        return;
    };
    let tmp = tempfile::tempdir().expect("tempdir");
    let model = live_openrouter_model();
    let output = Command::new(yolop_binary())
        .args([
            "--provider",
            "openrouter",
            "--model",
            &model,
            "--session-dir",
            tmp.path().to_str().unwrap(),
            "-p",
            "Reply with exactly the single word: pong",
        ])
        .output()
        .expect("spawn yolop --provider openrouter");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() && looks_rate_limited(&format!("{stdout}{stderr}")) {
        eprintln!("skipping live test: upstream provider rate-limited (429)");
        return;
    }
    assert!(
        output.status.success(),
        "yolop openrouter smoke failed: stdout={stdout} stderr={stderr}"
    );
    assert!(
        stdout.to_lowercase().contains("pong"),
        "expected `pong` in stdout: {stdout}"
    );
    assert!(
        stdout.contains("success=true"),
        "expected success=true: {stdout}"
    );
}

/// Live regression test for the OpenRouter tool-calling path (everruns EVE-522
/// and EVE-523).
///
/// OpenRouter's `/responses` endpoint is stateless (it ignores
/// `previous_response_id`). Yolop routes OpenRouter through the first-class
/// OpenRouter Responses driver (everruns 0.10+), which replays the full
/// transcript each turn instead of chaining by response id. History loss on
/// this path is silent: the agent emits a tool call, the result never reaches
/// the next turn, and the model loops without making progress.
///
/// This test seeds a unique sentinel in a workspace file and asks the model to
/// read it back. The sentinel is *not* in the prompt, so it can only appear in
/// the answer if `read_file` actually executed and its result flowed back into
/// the next turn. A regression on tool-call streaming or turn chaining makes
/// this fail.
#[test]
fn openrouter_tool_call_executes_end_to_end() {
    let Some(_) = live_key_or_skip("OPENROUTER_API_KEY") else {
        return;
    };
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    let sessions = tempfile::tempdir().expect("sessions tempdir");
    // Unique per run so a stale cache or a model that pattern-matches a known
    // token can't fake a pass — the value only exists in the file we just wrote.
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("system clock after epoch")
        .as_nanos();
    let sentinel = format!("MARMOT-{}-{nanos}", std::process::id());
    std::fs::write(
        workspace.path().join("secret.txt"),
        format!("The access token is {sentinel}.\n"),
    )
    .expect("write secret.txt");

    let model = live_openrouter_model();
    let output = Command::new(yolop_binary())
        .args([
            "--provider",
            "openrouter",
            "--model",
            &model,
            "-C",
            workspace.path().to_str().unwrap(),
            "--session-dir",
            sessions.path().to_str().unwrap(),
            "-p",
            "Read the file secret.txt in the workspace and reply with ONLY the \
             access token it contains, and nothing else.",
        ])
        .output()
        .expect("spawn yolop --provider openrouter");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() && looks_rate_limited(&format!("{stdout}{stderr}")) {
        eprintln!("skipping live test: upstream provider rate-limited (429)");
        return;
    }
    assert!(
        output.status.success(),
        "yolop openrouter tool-call smoke failed: stdout={stdout} stderr={stderr}"
    );
    assert!(
        stdout.contains(&sentinel),
        "expected sentinel {sentinel} in stdout (proves read_file executed and \
         its result reached the model): {stdout}"
    );
    assert!(
        stdout.contains("success=true"),
        "expected success=true: {stdout}"
    );
}