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
// Entrypoint for the Yolop coding agent example.
// Decision: support both interactive TUI and a `--print` one-shot mode so the
// example is testable in CI and easy to demo against a real codebase.

mod acp;
mod app;
mod capabilities;
mod config_schema;
mod config_service;
mod hooks_config;
mod host_ui;
mod into;
mod mcp_config;
mod runtime;
mod session_log;
mod settings;
#[cfg(test)]
mod test_env;
mod tools;
mod version;

#[cfg(test)]
mod streaming_tests;

#[cfg(test)]
mod mcp_e2e_tests;

#[cfg(test)]
mod agent_scenarios;

use anyhow::Result;
use app::{App, COMPOSER_VIEWPORT_HEIGHT};
use clap::{Args, Parser, Subcommand};
use crossterm::event::{
    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use crossterm::{execute, queue};
use everruns_core::message::MessageRole;
use ratatui::backend::CrosstermBackend;
use ratatui::{Terminal, TerminalOptions, Viewport};
use runtime::{BuiltRuntime, ProviderChoice};
use settings::SettingsStore;
use std::io::{self, IsTerminal, Write};
use std::path::PathBuf;
use std::sync::Arc;

#[derive(Parser, Debug)]
#[command(
    name = "yolop",
    version = version::VERSION_DETAILS,
    about = "Yolop coding agent — embedded terminal agent built on everruns-runtime"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Workspace root the agent operates inside (default: current dir)
    #[arg(short = 'C', long = "cwd")]
    cwd: Option<PathBuf>,

    /// Force a provider (auto-detected from env vars otherwise)
    #[arg(long, value_enum)]
    provider: Option<ProviderArg>,

    /// Override the model id
    #[arg(short, long)]
    model: Option<String>,

    /// Reasoning effort for OpenAI and OpenRouter model calls
    #[arg(long)]
    reasoning_effort: Option<String>,

    /// Run a single prompt non-interactively and print the result. Useful for CI smoke tests.
    #[arg(short = 'p', long)]
    print: Option<String>,

    /// Speak the Agent Client Protocol (ACP) over stdio instead of launching
    /// the TUI. Editors such as Zed spawn `yolop --acp` and drive it as an
    /// external agent. Builds one runtime per ACP session (cwd comes from the
    /// client); the `-C/--cwd`, `--print`, and `--session` flags are
    /// ignored in this mode. See `specs/acp.md`.
    #[arg(long, conflicts_with = "print")]
    acp: bool,

    /// Resume an existing session. Reads the JSONL log for this id and
    /// seeds the message history; the new run continues appending to the
    /// same file. If no log exists, a new session starts with this id.
    /// Without `--session`, a fresh id is generated each run.
    #[arg(long)]
    session: Option<String>,

    /// Directory where per-session folders are stored. Default: the
    /// platform-native user data directory (`$XDG_DATA_HOME/yolop/sessions/`
    /// on Linux, `~/Library/Application Support/yolop/sessions/` on macOS,
    /// `%APPDATA%\yolop\sessions\` on Windows).
    #[arg(long)]
    session_dir: Option<PathBuf>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Print version information.
    Version,
    /// Add yolop into supported editors.
    Into(IntoCommand),
}

#[derive(Args, Debug)]
struct IntoCommand {
    #[command(subcommand)]
    target: IntoTarget,
}

#[derive(Subcommand, Debug)]
enum IntoTarget {
    /// Configure Zed to launch yolop as a custom ACP agent.
    Zed(ZedIntoArgs),
}

#[derive(Args, Debug)]
struct ZedIntoArgs {
    /// Zed settings file to update (default: ~/.config/zed/settings.json).
    #[arg(long = "settings")]
    settings_path: Option<PathBuf>,

    /// Agent server name to write under `agent_servers`.
    #[arg(long, default_value = "yolop")]
    name: String,

    /// Command path Zed should spawn (default: this yolop executable).
    #[arg(long)]
    command: Option<PathBuf>,

    /// Replace an existing `agent_servers.<name>` entry instead of preserving its env/extra fields.
    #[arg(long)]
    force: bool,
}

#[derive(clap::ValueEnum, Debug, Clone, Copy)]
enum ProviderArg {
    Anthropic,
    Openai,
    Google,
    Openrouter,
    Ollama,
    /// Generic OpenAI-compatible endpoint (CUSTOM_BASE_URL / saved base URL).
    Custom,
    #[value(name = "llmsim", alias = "sim")]
    Sim,
}

fn provider_name_for_arg(arg: ProviderArg) -> &'static str {
    match arg {
        ProviderArg::Anthropic => "anthropic",
        ProviderArg::Openai => "openai",
        ProviderArg::Google => "google",
        ProviderArg::Openrouter => "openrouter",
        ProviderArg::Ollama => "ollama",
        ProviderArg::Custom => "custom",
        ProviderArg::Sim => "llmsim",
    }
}

/// Resolution order: explicit `--provider` flag > persisted settings >
/// env-var auto-detection. Model and reasoning-effort flags layer on top
/// of whichever base was chosen.
fn pick_provider(cli: &Cli, settings: &SettingsStore) -> ProviderChoice {
    let snapshot = settings.snapshot();
    let cli_reasoning_effort = runtime::normalize_reasoning_effort(cli.reasoning_effort.clone());
    let base = if let Some(arg) = cli.provider {
        ProviderChoice::default_for_provider_name(provider_name_for_arg(arg))
            .expect("ProviderArg names are always valid")
    } else if let Some(saved) = snapshot.provider.as_deref() {
        match ProviderChoice::default_for_provider_name(saved) {
            Ok(choice) => choice,
            Err(err) => {
                eprintln!("yolop: ignoring saved provider `{saved}`: {err}");
                ProviderChoice::from_env_or_settings(&snapshot)
            }
        }
    } else {
        ProviderChoice::from_env_or_settings(&snapshot)
    };
    // A model persisted by `/setup model` for the chosen provider wins over
    // the provider default; CLI flags still override it below.
    let base = base.with_saved_model(&snapshot);
    let selected = match (base, cli.model.clone()) {
        (ProviderChoice::Anthropic { .. }, Some(m)) => ProviderChoice::Anthropic { model: m },
        (
            ProviderChoice::OpenAi {
                reasoning_effort, ..
            },
            Some(m),
        ) => ProviderChoice::OpenAi {
            model: m,
            reasoning_effort: cli_reasoning_effort.clone().or(reasoning_effort),
        },
        (ProviderChoice::Google { base_url, .. }, Some(m)) => {
            ProviderChoice::Google { model: m, base_url }
        }
        (
            ProviderChoice::OpenRouter {
                base_url,
                reasoning_effort,
                ..
            },
            Some(m),
        ) => ProviderChoice::OpenRouter {
            model: m,
            base_url,
            reasoning_effort: cli_reasoning_effort.clone().or(reasoning_effort),
        },
        (ProviderChoice::Ollama { base_url, .. }, Some(m)) => {
            ProviderChoice::Ollama { model: m, base_url }
        }
        (
            ProviderChoice::Custom {
                reasoning_effort, ..
            },
            Some(m),
        ) => ProviderChoice::Custom {
            model: m,
            reasoning_effort: cli_reasoning_effort.clone().or(reasoning_effort),
        },
        (other, _) => other,
    };
    match (selected, cli_reasoning_effort) {
        (
            ProviderChoice::OpenAi {
                model,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::OpenAi {
            model,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (
            ProviderChoice::OpenRouter {
                model,
                base_url,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::OpenRouter {
            model,
            base_url,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (
            ProviderChoice::Custom {
                model,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::Custom {
            model,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (other, _) => other,
    }
}

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("error")),
        )
        .with_writer(io::stderr)
        .init();

    let cli = Cli::parse();
    if let Some(command) = cli.command {
        return run_command(command);
    }

    let cwd = cli
        .cwd
        .clone()
        .unwrap_or_else(|| std::env::current_dir().expect("cwd"));
    // Fall back to an unwritable scratch path when no platform config dir
    // is resolvable (minimal containers, CI without HOME). `SettingsStore`
    // loads to defaults when the file does not exist, and writes will
    // error visibly via `/setup` rather than killing
    // startup — keeps `--print` usable in stripped-down environments.
    let settings_path = settings::default_settings_path().unwrap_or_else(|| {
        eprintln!(
            "yolop: no platform config dir resolvable — settings will not persist across runs"
        );
        std::path::PathBuf::from("/dev/null/yolop/settings.toml")
    });
    let settings = Arc::new(SettingsStore::open(settings_path));
    let provider = pick_provider(&cli, &settings);

    let resume_session_id = match cli.session.as_deref() {
        Some(raw) => Some(
            raw.parse()
                .map_err(|e| anyhow::anyhow!("invalid --session id `{raw}`: {e}"))?,
        ),
        None => None,
    };
    let sessions_dir = match cli.session_dir.clone() {
        Some(p) => p,
        None => session_log::default_sessions_dir()?,
    };

    // ACP mode builds runtimes per session (cwd arrives via `session/new`), so
    // it bypasses the up-front runtime build and the TUI.
    if cli.acp {
        return acp::run_stdio(provider, settings, sessions_dir).await;
    }

    // Only the interactive TUI can apply terminal-side commands (overlays,
    // transcript clear, quit), so only it enables `ClientCommandsCapability`.
    // `--print` is one-shot and never dispatches them.
    let interactive = cli.print.is_none();
    let runtime = runtime::build_with_options(
        cwd,
        provider,
        resume_session_id,
        sessions_dir,
        settings,
        runtime::BuildOptions {
            client_commands: interactive,
            ..Default::default()
        },
    )
    .await?;

    if let Some(prompt) = cli.print {
        return run_print_mode(runtime, prompt).await;
    }
    run_tui(runtime).await
}

fn run_command(command: Commands) -> Result<()> {
    match command {
        Commands::Version => {
            println!("{}", version::VERSION_LINE);
            Ok(())
        }
        Commands::Into(into) => match into.target {
            IntoTarget::Zed(args) => {
                let command = match args.command {
                    Some(path) => path,
                    None => std::env::current_exe().unwrap_or_else(|_| PathBuf::from("yolop")),
                };
                let result = into::into_zed(into::ZedIntoOptions {
                    settings_path: args.settings_path,
                    agent_name: args.name,
                    command,
                    force: args.force,
                })?;
                match result.status {
                    into::IntoStatus::Unchanged => {
                        println!(
                            "yolop: Zed already has `{}` configured at {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                    into::IntoStatus::Created => {
                        println!(
                            "yolop: added `{}` ACP agent to {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                    into::IntoStatus::Updated => {
                        println!(
                            "yolop: updated `{}` ACP agent in {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                }
                println!("yolop: Zed command: {} --acp", result.command);
                Ok(())
            }
        },
    }
}

async fn run_tui(runtime: BuiltRuntime) -> Result<()> {
    let mut raw_mode = RawModeGuard::new()?;
    let mut keyboard_enhancements = KeyboardEnhancementGuard::new();
    let stdout = io::stdout();
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::with_options(
        backend,
        TerminalOptions {
            viewport: Viewport::Inline(COMPOSER_VIEWPORT_HEIGHT),
        },
    )?;
    // Anchoring is cosmetic. Since ratatui 0.30.1 `insert_before` snapshots
    // the cursor (via `Terminal::clear`) with a blocking `CSI 6n` query that
    // slow emulators (ttyd / xterm.js) may not answer before crossterm's ~2s
    // timeout. Start unanchored rather than dying.
    if let Err(err) = anchor_inline_viewport_at_bottom(&mut terminal) {
        tracing::warn!("inline viewport anchoring failed, starting unanchored: {err:#}");
    }

    let mut app = App::new(runtime);
    let result = app.run(&mut terminal).await;
    let show_resume_hint = app.should_show_resume_hint();
    let session_id = app.session_id();

    // Cosmetic cleanup must not turn a successful session into an error
    // exit: since ratatui 0.30.1 `Terminal::clear` issues the same blocking
    // cursor query as anchoring above. The two steps are independent —
    // restoring the cursor is a plain escape write that should still happen
    // when the clear's query times out. Raw-mode restore below still fails
    // hard — leaving the terminal unusable is worth a nonzero exit.
    if let Err(err) = terminal.clear() {
        tracing::warn!("terminal clear failed: {err:#}");
    }
    if let Err(err) = terminal.show_cursor() {
        tracing::warn!("cursor restore failed: {err:#}");
    }
    drop(terminal);
    keyboard_enhancements.disable();
    raw_mode.disable()?;

    if show_resume_hint {
        println!();
        print_resume_divider();
        println!("Resume with yolop --session {session_id}");
        println!();
        print_centered_ukraine_banner();
    }
    result
}

fn anchor_inline_viewport_at_bottom<B>(terminal: &mut Terminal<B>) -> Result<()>
where
    B: ratatui::backend::Backend,
    B::Error: std::error::Error + Send + Sync + 'static,
{
    let terminal_height = terminal.size()?.height;
    let viewport_area = terminal.get_frame().area();
    let blank_lines =
        blank_lines_after_inline_viewport(viewport_area.y, viewport_area.height, terminal_height);
    if blank_lines == 0 {
        return Ok(());
    }
    terminal.insert_before(blank_lines, |_| {})?;
    Ok(())
}

fn blank_lines_after_inline_viewport(
    viewport_top: u16,
    viewport_height: u16,
    terminal_height: u16,
) -> u16 {
    terminal_height.saturating_sub(viewport_top.saturating_add(viewport_height))
}

struct RawModeGuard {
    active: bool,
}

impl RawModeGuard {
    fn new() -> Result<Self> {
        enable_raw_mode()?;
        Ok(Self { active: true })
    }

    fn disable(&mut self) -> Result<()> {
        if self.active {
            disable_raw_mode()?;
            self.active = false;
        }
        Ok(())
    }
}

impl Drop for RawModeGuard {
    fn drop(&mut self) {
        if self.active {
            let _ = disable_raw_mode();
            self.active = false;
        }
    }
}

struct KeyboardEnhancementGuard {
    active: bool,
}

impl KeyboardEnhancementGuard {
    fn new() -> Self {
        let flags = KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
            | KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES;
        let mut stdout = io::stdout();
        let active = execute!(stdout, PushKeyboardEnhancementFlags(flags)).is_ok();
        Self { active }
    }

    fn disable(&mut self) {
        if self.active {
            let mut stdout = io::stdout();
            let _ = queue!(stdout, PopKeyboardEnhancementFlags);
            let _ = stdout.flush();
            self.active = false;
        }
    }
}

impl Drop for KeyboardEnhancementGuard {
    fn drop(&mut self) {
        self.disable();
    }
}

fn print_resume_divider() {
    let width = crossterm::terminal::size()
        .map(|(width, _)| width as usize)
        .unwrap_or(80)
        .max(1);
    println!("\x1b[38;2;45;91;158m{}\x1b[0m", "".repeat(width));
}

fn print_centered_ukraine_banner() {
    let text = ">> Зроблено в Україні <<";
    let width = crossterm::terminal::size()
        .map(|(width, _)| width as usize)
        .unwrap_or(0);
    let pad = width.saturating_sub(text.chars().count()) / 2;
    println!(
        "{}\x1b[38;2;45;91;158m>> Зроблено в \x1b[38;2;126;94;19mУкраїні <<\x1b[0m",
        " ".repeat(pad)
    );
}

async fn run_print_mode(runtime: BuiltRuntime, prompt: String) -> Result<()> {
    let BuiltRuntime {
        handles,
        startup,
        model,
        ..
    } = runtime;
    let color = io::stdout().is_terminal();
    println!("{}", paint(color, "90", &format!("{prompt}")));
    println!();
    println!(
        "{} {}",
        paint(color, "90", "workspace"),
        startup.workspace_root.display()
    );
    println!(
        "{}  {}",
        paint(color, "90", "provider"),
        paint(color, "96", &model.provider_label())
    );
    println!(
        "{}     {}",
        paint(color, "90", "tools"),
        startup.tool_names.join(", ")
    );
    println!(
        "{}   {} (folder: {}; log: {}; {} prior event(s))",
        paint(color, "90", "session"),
        handles.session_id,
        startup.session_dir.display(),
        startup.session_log_path.display(),
        startup.replayed_events,
    );
    if !startup.capability_commands.is_empty() {
        let names: Vec<String> = startup
            .capability_commands
            .iter()
            .map(|c| format!("/{}", c.name))
            .collect();
        println!("{} {}", paint(color, "90", "commands"), names.join(", "));
    }
    if startup.hook_configured {
        println!(
            "{}     {}",
            paint(color, "90", "hooks"),
            startup.hook_summary()
        );
    }
    println!();

    let before_events = handles.runtime.events().await.map(|e| e.len()).unwrap_or(0);
    let before_msgs = handles
        .runtime
        .messages(handles.session_id)
        .await
        .map(|m| m.len())
        .unwrap_or(0);

    let input = model.input_message(prompt);
    let result = handles.runtime.run_turn(handles.session_id, input).await?;
    let events = handles.runtime.events().await.unwrap_or_default();
    let messages = handles
        .runtime
        .messages(handles.session_id)
        .await
        .unwrap_or_default();

    for event in events.iter().skip(before_events) {
        if let Some(status) = app::status_for_event(event) {
            print_status_line(&status.text, color);
        }
        for line in app::lines_for_event(event) {
            print_transcript_line(&line, color);
        }
    }
    for msg in messages.iter().skip(before_msgs) {
        if msg.role == MessageRole::Agent
            && !msg.has_tool_calls()
            && let Some(text) = msg.text()
        {
            let t = text.trim();
            if !t.is_empty() {
                println!();
                print_transcript_line(
                    &app::ChatLine {
                        author: app::Author::Assistant,
                        text: t.to_string(),
                    },
                    color,
                );
            }
        }
    }
    println!(
        "\n{} success={} iterations={} tool_calls={}",
        paint(color, if result.success { "92" } else { "91" }, "done"),
        result.success,
        result.iterations,
        result.tool_calls_count
    );
    if !result.success
        && let Some(err) = result.error
    {
        eprintln!("turn error: {err}");
        std::process::exit(1);
    }
    Ok(())
}

fn print_transcript_line(line: &app::ChatLine, color: bool) {
    match line.author {
        app::Author::Assistant => {
            println!("{} {}", paint(color, "90", ""), line.text);
        }
        app::Author::Narration => {
            println!(
                "{} {} {}",
                paint(color, "90", ""),
                paint(color, "90", line.author.label()),
                paint(color, "90", &line.text)
            );
        }
        app::Author::Tool => {
            println!(
                "{} {} {}",
                paint(color, "92", ""),
                paint(color, "93", line.author.label()),
                line.text
            );
        }
        app::Author::ToolDetail => {
            println!("           {}", line.text);
        }
        app::Author::Diff => {
            println!("  {}", paint(color, "95", &line.text));
        }
        app::Author::System | app::Author::User => {
            println!(
                "{} {} {}",
                paint(color, "90", ""),
                paint(color, "90", line.author.label()),
                line.text
            );
        }
    }
}

fn print_status_line(text: &str, color: bool) {
    println!("{} {}", paint(color, "94", ""), text);
}

fn paint(enabled: bool, code: &str, text: &str) -> String {
    if enabled {
        format!("\x1b[{code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cli_with_reasoning_effort(reasoning_effort: Option<&str>) -> Cli {
        Cli {
            command: None,
            cwd: None,
            provider: Some(ProviderArg::Openrouter),
            model: Some("nvidia/nemotron-3-super-120b-a12b".to_string()),
            reasoning_effort: reasoning_effort.map(str::to_string),
            print: None,
            acp: false,
            session: None,
            session_dir: None,
        }
    }

    #[test]
    fn pick_provider_normalizes_cli_reasoning_effort() {
        let tmp = tempfile::tempdir().expect("settings tempdir");
        let settings = SettingsStore::open(tmp.path().join("settings.toml"));

        let provider = pick_provider(&cli_with_reasoning_effort(Some(" HIGH ")), &settings);

        assert_eq!(
            provider.label(),
            "openrouter/nvidia/nemotron-3-super-120b-a12b high"
        );
    }

    #[test]
    fn pick_provider_ignores_blank_cli_reasoning_effort() {
        let tmp = tempfile::tempdir().expect("settings tempdir");
        let settings = SettingsStore::open(tmp.path().join("settings.toml"));

        let provider = pick_provider(&cli_with_reasoning_effort(Some("  ")), &settings);

        assert_eq!(
            provider.label(),
            "openrouter/nvidia/nemotron-3-super-120b-a12b"
        );
    }

    #[test]
    fn pick_provider_applies_saved_model_for_saved_provider() {
        let _guard = crate::test_env::lock();
        unsafe {
            std::env::remove_var("EVERRUNS_CLI_MODEL");
        }
        let tmp = tempfile::tempdir().expect("settings tempdir");
        let path = tmp.path().join("settings.toml");
        std::fs::write(
            &path,
            "provider = \"openai\"\n\n[models]\nopenai = \"gpt-5.4 high\"\n",
        )
        .expect("write settings");
        let settings = SettingsStore::open(path);
        let cli = Cli {
            command: None,
            cwd: None,
            provider: None,
            model: None,
            reasoning_effort: None,
            print: None,
            acp: false,
            session: None,
            session_dir: None,
        };

        let provider = pick_provider(&cli, &settings);

        assert_eq!(provider.label(), "openai/gpt-5.4 high");
    }

    #[test]
    fn inline_viewport_anchor_fills_space_above_bottom_target() {
        assert_eq!(blank_lines_after_inline_viewport(4, 18, 60), 38);
    }

    #[test]
    fn inline_viewport_anchor_does_not_scroll_when_already_low_enough() {
        assert_eq!(blank_lines_after_inline_viewport(42, 18, 60), 0);
        assert_eq!(blank_lines_after_inline_viewport(50, 18, 60), 0);
    }

    #[test]
    fn inline_viewport_anchor_handles_small_terminals() {
        assert_eq!(blank_lines_after_inline_viewport(0, 18, 10), 0);
    }
}