yolop 0.7.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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
// 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 atif;
mod background_wake;
mod capabilities;
mod capability_settings;
mod clipboard_paste;
mod codex_auth;
mod codex_driver;
mod config_schema;
mod config_service;
mod connectors;
mod extensions;
mod goal;
mod hooks_config;
mod host_ui;
mod image_input;
mod into;
mod mcp_config;
mod mcp_oauth;
mod oauth_flow;
mod paste_attachment;
mod presentation;
mod runtime;
mod session;
mod session_log;
mod session_tasks_view;
mod settings;
#[cfg(test)]
mod test_env;
mod tools;
mod transcript;
mod user_ask;
mod version;
mod workspace_host;
mod worktree;

#[cfg(test)]
mod streaming_tests;

#[cfg(test)]
mod mcp_e2e_tests;

#[cfg(test)]
mod agent_scenarios;

use crate::capabilities::ClientUiContext;
use anyhow::{Context, Result};

// Force-link integration crates whose inventory registrations must survive
// LTO/dead-code elimination when we register capabilities explicitly.
extern crate everruns_integrations_daytona;
extern crate everruns_integrations_parallel;
use app::{App, COMPOSER_VIEWPORT_HEIGHT, maybe_reanchor_inline_viewport};
use clap::{Args, Parser, Subcommand};
use crossterm::event::{
    DisableBracketedPaste, EnableBracketedPaste, KeyboardEnhancementFlags,
    PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use crossterm::{execute, queue};
use everruns_core::command::ExecuteCommandRequest;
use everruns_core::message::{ContentPart, MessageRole};
use everruns_core::typed_id::SessionId;
use mcp_config::{McpConfigScope, McpConfigStore};
use ratatui::backend::CrosstermBackend;
use ratatui::{Terminal, TerminalOptions, Viewport};
use runtime::{BuiltRuntime, ProviderChoice, ResolvedProviderChoice, resolve_for_settings};
use settings::SettingsStore;
use std::io::{self, IsTerminal, Write};
use std::path::{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 model calls (validated against the model's
    /// supported values, e.g. minimal/low/medium/high). Applies to any
    /// provider whose selected model exposes a reasoning-effort setting.
    #[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>,

    /// Attach one or more image files to the prompt. Separate multiple paths
    /// with commas or repeat the flag. Supported formats: png, jpeg, gif, webp.
    #[arg(
        long = "image",
        short = 'i',
        value_name = "FILE",
        value_delimiter = ',',
        num_args = 1..
    )]
    images: Vec<PathBuf>,

    /// 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>,

    /// Write the full session as an ATIF v1.7 trajectory JSON file to this
    /// path at end of run. Works interactively and with `-p/--print`; see
    /// `specs/trajectory.md`.
    #[arg(long, value_name = "PATH")]
    trajectory_out: Option<PathBuf>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Print version information.
    Version,
    /// Add yolop into supported editors.
    Into(IntoCommand),
    /// Git worktree maintenance.
    Worktree(WorktreeArgs),
    /// Manage MCP servers in global settings or workspace `.mcp.json`.
    Mcp(McpArgs),
}

#[derive(Args, Debug)]
struct McpArgs {
    #[command(subcommand)]
    command: McpCommand,
}

#[derive(Subcommand, Debug)]
enum McpCommand {
    /// List configured MCP servers.
    List {
        /// Scope to inspect (`global`, `workspace`, or `effective`).
        #[arg(long, default_value = "effective")]
        scope: McpScopeArg,
        /// Workspace root for workspace/effective config.
        #[arg(short = 'C', long = "cwd")]
        cwd: Option<PathBuf>,
    },
    /// Add or replace an MCP server.
    Add {
        /// Scope to write (`global` or `workspace`).
        #[arg(long, default_value = "global")]
        scope: McpScopeArg,
        /// Server name.
        name: String,
        /// Transport type (`stdio`, `http`, or `sse`).
        #[arg(long = "type")]
        transport_type: String,
        /// Command for stdio servers.
        #[arg(long)]
        command: Option<String>,
        /// Command arguments for stdio servers. Repeat or comma-separate.
        #[arg(long, value_delimiter = ',', num_args = 0..)]
        args: Vec<String>,
        /// URL for http/sse servers.
        #[arg(long)]
        url: Option<String>,
        /// Header as KEY=VALUE. Repeat for multiple headers.
        #[arg(long = "header", value_parser = parse_key_value)]
        headers: Vec<(String, String)>,
        /// Auth mode (`bearer`, `oauth`, or `none`).
        #[arg(long)]
        auth_mode: Option<String>,
        /// OAuth provider id for auth-mode=oauth.
        #[arg(long)]
        oauth_provider_id: Option<String>,
        /// Disable the server immediately after adding it.
        #[arg(long, default_value_t = false)]
        disabled: bool,
        /// Workspace root when writing workspace config.
        #[arg(short = 'C', long = "cwd")]
        cwd: Option<PathBuf>,
    },
    /// Remove an MCP server.
    Remove {
        /// Scope to write (`global` or `workspace`).
        #[arg(long, default_value = "global")]
        scope: McpScopeArg,
        /// Server name.
        name: String,
        /// Workspace root when writing workspace config.
        #[arg(short = 'C', long = "cwd")]
        cwd: Option<PathBuf>,
    },
    /// Enable or disable an MCP server without deleting it.
    Enable {
        /// Scope to write (`global` or `workspace`).
        #[arg(long, default_value = "global")]
        scope: McpScopeArg,
        /// Server name.
        name: String,
        /// Disable instead of enable.
        #[arg(long, default_value_t = false)]
        disable: bool,
        /// Workspace root when writing workspace config.
        #[arg(short = 'C', long = "cwd")]
        cwd: Option<PathBuf>,
    },
}

#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
enum McpScopeArg {
    Global,
    Workspace,
    Effective,
}

fn parse_key_value(value: &str) -> Result<(String, String), String> {
    let (key, val) = value
        .split_once('=')
        .ok_or_else(|| "expected KEY=VALUE".to_string())?;
    if key.trim().is_empty() {
        return Err("header key cannot be empty".to_string());
    }
    Ok((key.trim().to_string(), val.to_string()))
}

#[derive(Args, Debug)]
struct WorktreeArgs {
    #[command(subcommand)]
    command: WorktreeCommand,
}

#[derive(Subcommand, Debug)]
enum WorktreeCommand {
    /// List session worktree directories on disk.
    List,
    /// Remove worktrees not referenced by any saved session.
    Prune {
        /// Print what would be removed without deleting anything.
        #[arg(long)]
        dry_run: bool,
        /// Session storage parent directory (default: platform data dir).
        #[arg(long)]
        session_dir: Option<PathBuf>,
    },
}

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

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

#[derive(Args, Debug)]
struct PaseoIntoArgs {
    /// Replace an existing `agents.providers.yolop` entry instead of preserving its env/extra fields.
    #[arg(long)]
    force: bool,
}

#[derive(Args, Debug)]
struct ZedIntoArgs {
    /// Replace an existing `agent_servers.yolop` entry instead of preserving its env/extra fields.
    #[arg(long)]
    force: bool,
}

#[derive(clap::ValueEnum, Debug, Clone, Copy)]
enum ProviderArg {
    Anthropic,
    Codex,
    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::Codex => "codex",
        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, Vec<String>) {
    let snapshot = settings.snapshot();
    let cli_reasoning_effort = runtime::normalize_reasoning_effort(cli.reasoning_effort.clone());
    let mut notes = Vec::new();

    let resolved = if let Some(arg) = cli.provider {
        resolve_for_settings(provider_name_for_arg(arg), &snapshot)
            .expect("ProviderArg names are always valid")
    } else if let Some(saved) = snapshot.default_provider.as_deref() {
        match resolve_for_settings(saved, &snapshot) {
            Ok(resolved) => resolved,
            Err(err) => {
                eprintln!("yolop: ignoring saved provider `{saved}`: {err}");
                let auto = ProviderChoice::from_env_or_settings(&snapshot);
                resolve_for_settings(auto.provider_name(), &snapshot).unwrap_or(
                    ResolvedProviderChoice {
                        choice: auto,
                        source: runtime::ModelResolutionSource::ProviderDefault,
                        notes: vec![],
                    },
                )
            }
        }
    } else {
        let auto = ProviderChoice::from_env_or_settings(&snapshot);
        resolve_for_settings(auto.provider_name(), &snapshot).unwrap_or(ResolvedProviderChoice {
            choice: auto,
            source: runtime::ModelResolutionSource::ProviderDefault,
            notes: vec![],
        })
    };

    notes.extend(resolved.notes);
    let base = resolved.choice;
    let selected = if let Some(model) = cli.model.clone() {
        let spec = match cli_reasoning_effort.clone() {
            Some(effort) => format!("{model} {effort}"),
            None => model,
        };
        match base.resolve_model_spec(&spec) {
            Ok(selected) => selected,
            Err(err) => {
                notes.push(format!("model override ignored: {err}"));
                base
            }
        }
    } else {
        base
    };
    let selected = match (selected, cli_reasoning_effort) {
        (
            ProviderChoice::Anthropic {
                model,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::Anthropic {
            model,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (
            ProviderChoice::OpenAi {
                model,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::OpenAi {
            model,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (
            ProviderChoice::Codex {
                model,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::Codex {
            model,
            reasoning_effort: effort.or(reasoning_effort),
        },
        (
            ProviderChoice::Google {
                model,
                base_url,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::Google {
            model,
            base_url,
            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::Ollama {
                model,
                base_url,
                reasoning_effort,
            },
            effort,
        ) => ProviderChoice::Ollama {
            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,
    };
    (selected, notes)
}

#[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);
    }

    // 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 (mut provider, mut notes) = pick_provider(&cli, &settings);
    let snapshot = settings.snapshot();
    let (reconciled, catalog_notes) =
        capabilities::model_discovery::reconcile_provider_with_catalog(provider, &snapshot).await;
    provider = reconciled;
    notes.extend(catalog_notes);
    for note in notes {
        eprintln!("yolop: {note}");
    }

    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()?,
    };
    let cwd = resolve_workspace_root(cli.cwd.clone(), resume_session_id, &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 {
        if cli.trajectory_out.is_some() {
            eprintln!("yolop: --trajectory-out is ignored in --acp mode");
        }
        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,
            client_ui: if interactive {
                ClientUiContext::Tui
            } else {
                ClientUiContext::Print
            },
            session_kind: if interactive {
                session_log::SessionKind::Interactive
            } else {
                session_log::SessionKind::Print
            },
            initial_prompt: cli.print.clone(),
            ..Default::default()
        },
    )
    .await?;

    if let Some(prompt) = cli.print {
        let image_parts = image_input::load_image_parts(&cli.images)?;
        return run_print_mode(runtime, prompt, image_parts, cli.trajectory_out).await;
    }
    let pending_images = image_input::load_image_parts(&cli.images)?;
    run_tui(runtime, pending_images, cli.trajectory_out).await
}

fn resolve_workspace_root(
    cli_cwd: Option<PathBuf>,
    resume_session_id: Option<SessionId>,
    sessions_dir: &Path,
) -> Result<PathBuf> {
    if let Some(cwd) = cli_cwd {
        return Ok(cwd);
    }
    if let Some(session_id) = resume_session_id {
        let session_dir = session_log::session_dir_path(sessions_dir, session_id);
        if let Some(saved) = session_log::read_session_workspace(&session_dir)? {
            return Ok(saved);
        }
    }
    std::env::current_dir().context("resolve current workspace directory")
}

fn run_mcp_command(command: McpCommand) -> Result<()> {
    use crate::mcp_config::{McpServerEntry, McpServerSummary};
    use everruns_core::{McpServerTransportType, ScopedMcpServer};
    use std::collections::HashMap;

    fn store(cwd: Option<PathBuf>) -> Result<McpConfigStore> {
        let workspace_root = match cwd {
            Some(path) => path,
            None => std::env::current_dir().context("resolve current workspace directory")?,
        };
        Ok(McpConfigStore::default_for_workspace(&workspace_root))
    }

    fn write_scope(scope: McpScopeArg) -> Result<McpConfigScope> {
        match scope {
            McpScopeArg::Global => Ok(McpConfigScope::Global),
            McpScopeArg::Workspace => Ok(McpConfigScope::Workspace),
            McpScopeArg::Effective => anyhow::bail!(
                "effective scope is read-only; use --scope global or --scope workspace"
            ),
        }
    }

    match command {
        McpCommand::List { scope, cwd } => {
            let store = store(cwd)?;
            let servers: Vec<McpServerSummary> = match scope {
                McpScopeArg::Global => store
                    .effective()
                    .map_err(anyhow::Error::msg)?
                    .servers
                    .into_iter()
                    .filter(|server| server.scope == McpConfigScope::Global)
                    .collect(),
                McpScopeArg::Workspace => store
                    .effective()
                    .map_err(anyhow::Error::msg)?
                    .servers
                    .into_iter()
                    .filter(|server| server.scope == McpConfigScope::Workspace)
                    .collect(),
                McpScopeArg::Effective => store
                    .effective()
                    .map_err(anyhow::Error::msg)?
                    .servers
                    .into_iter()
                    .filter(|server| server.effective)
                    .collect(),
            };
            if servers.is_empty() {
                println!("no MCP servers configured");
            } else {
                for server in servers {
                    let enabled = if server.enabled {
                        "enabled"
                    } else {
                        "disabled"
                    };
                    println!(
                        "{}	{}	{}",
                        server.name,
                        mcp_scope_label(server.scope),
                        enabled
                    );
                }
            }
            Ok(())
        }
        McpCommand::Add {
            scope,
            name,
            transport_type,
            command,
            args,
            url,
            headers,
            auth_mode,
            oauth_provider_id,
            disabled,
            cwd,
        } => {
            let transport = transport_type.to_ascii_lowercase();
            let server = match transport.as_str() {
                "stdio" => ScopedMcpServer {
                    transport_type: McpServerTransportType::Stdio,
                    command: Some(command.context("--command is required for stdio MCP servers")?),
                    args,
                    env: HashMap::new(),
                    ..ScopedMcpServer::default()
                },
                "http" | "sse" => ScopedMcpServer {
                    transport_type: McpServerTransportType::Http,
                    url: url.context("--url is required for remote MCP servers")?,
                    headers: headers.into_iter().collect(),
                    auth_mode: auth_mode
                        .as_deref()
                        .map(parse_mcp_auth_mode)
                        .transpose()?
                        .unwrap_or_default(),
                    oauth_provider_id,
                    ..ScopedMcpServer::default()
                },
                other => anyhow::bail!(
                    "unsupported MCP transport `{other}`; expected stdio, http, or sse"
                ),
            };
            let store = store(cwd)?;
            let _summary = store
                .upsert(
                    write_scope(scope)?,
                    &name,
                    McpServerEntry {
                        enabled: !disabled,
                        server,
                    },
                )
                .map_err(anyhow::Error::msg)?;
            let action = "saved";
            println!(
                "{action} MCP server `{name}` in {} scope",
                mcp_scope_label(write_scope(scope)?)
            );
            println!(
                "restart or start a new yolop session for MCP connection changes to take effect"
            );
            Ok(())
        }
        McpCommand::Remove { scope, name, cwd } => {
            let store = store(cwd)?;
            let removed = store
                .remove(write_scope(scope)?, &name)
                .map_err(anyhow::Error::msg)?;
            if removed {
                println!(
                    "removed MCP server `{name}` from {} scope",
                    mcp_scope_label(write_scope(scope)?)
                );
                println!(
                    "restart or start a new yolop session for MCP connection changes to take effect"
                );
            } else {
                println!(
                    "MCP server `{name}` was not configured in {} scope",
                    mcp_scope_label(write_scope(scope)?)
                );
            }
            Ok(())
        }
        McpCommand::Enable {
            scope,
            name,
            disable,
            cwd,
        } => {
            let store = store(cwd)?;
            store
                .set_enabled(write_scope(scope)?, &name, !disable)
                .map_err(anyhow::Error::msg)?;
            println!(
                "{} MCP server `{name}` in {} scope",
                if disable { "disabled" } else { "enabled" },
                mcp_scope_label(write_scope(scope)?)
            );
            println!(
                "restart or start a new yolop session for MCP connection changes to take effect"
            );
            Ok(())
        }
    }
}

fn mcp_scope_label(scope: McpConfigScope) -> &'static str {
    match scope {
        McpConfigScope::Global => "global",
        McpConfigScope::Workspace => "workspace",
    }
}

fn parse_mcp_auth_mode(value: &str) -> Result<everruns_core::McpServerAuthMode> {
    match value.to_ascii_lowercase().as_str() {
        "none" => Ok(everruns_core::McpServerAuthMode::None),
        "bearer" | "api_key" | "api-key" => Ok(everruns_core::McpServerAuthMode::ApiKey),
        "oauth" | "o_auth" => Ok(everruns_core::McpServerAuthMode::OAuth),
        other => anyhow::bail!(
            "unsupported auth mode `{other}`; expected none, bearer/api_key, or oauth"
        ),
    }
}

fn run_worktree_command(command: WorktreeCommand) -> Result<()> {
    match command {
        WorktreeCommand::List => {
            let paths = worktree::list_worktree_paths_on_disk()?;
            if paths.is_empty() {
                println!("no yolop worktrees found on disk");
            } else {
                for path in paths {
                    println!("{}", path.display());
                }
            }
            Ok(())
        }
        WorktreeCommand::Prune {
            dry_run,
            session_dir,
        } => {
            let sessions_dir = match session_dir {
                Some(path) => path,
                None => session_log::default_sessions_dir()?,
            };
            let report = worktree::prune_orphan_worktrees(&sessions_dir, dry_run)?;
            let action = if dry_run { "would remove" } else { "removed" };
            for path in &report.removed {
                println!("{action}: {}", path.display());
            }
            println!(
                "kept {} referenced worktree(s); {} orphan(s) {action}",
                report.kept,
                report.removed.len()
            );
            for err in &report.errors {
                eprintln!("error: {err}");
            }
            if report.errors.is_empty() {
                Ok(())
            } else {
                std::process::exit(1);
            }
        }
    }
}

fn run_command(command: Commands) -> Result<()> {
    match command {
        Commands::Version => {
            println!("{}", version::VERSION_LINE);
            Ok(())
        }
        Commands::Worktree(args) => run_worktree_command(args.command),
        Commands::Mcp(args) => run_mcp_command(args.command),
        Commands::Into(into) => match into.target {
            IntoTarget::Paseo(args) => {
                let command = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("yolop"));
                let result = into::into_paseo(into::PaseoIntoOptions {
                    settings_path: None,
                    agent_name: "yolop".to_string(),
                    command,
                    force: args.force,
                })?;
                match result.status {
                    into::IntoStatus::Unchanged => {
                        println!(
                            "yolop: Paseo already has `{}` ACP provider configured at {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                    into::IntoStatus::Created => {
                        println!(
                            "yolop: added `{}` ACP provider to {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                    into::IntoStatus::Updated => {
                        println!(
                            "yolop: updated `{}` ACP provider in {}",
                            result.agent_name,
                            result.settings_path.display()
                        );
                    }
                }
                println!("yolop: Paseo command: {} --acp", result.command);
                println!("yolop: restart the Paseo daemon to reload this configuration");
                Ok(())
            }
            IntoTarget::Zed(args) => {
                let command = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("yolop"));
                let result = into::into_zed(into::ZedIntoOptions {
                    settings_path: None,
                    agent_name: "yolop".to_string(),
                    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,
    pending_images: Vec<ContentPart>,
    trajectory_out: Option<PathBuf>,
) -> Result<()> {
    // Cheap Arc clones taken before `App` consumes the runtime, so the
    // trajectory can be exported after the TUI loop ends.
    let trajectory_handles = runtime.handles.clone();
    let trajectory_model = runtime.model.clone();
    let mut raw_mode = RawModeGuard::new()?;
    let mut keyboard_enhancements = KeyboardEnhancementGuard::new();
    let mut bracketed_paste = BracketedPasteGuard::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) = maybe_reanchor_inline_viewport(&mut terminal) {
        tracing::warn!("inline viewport anchoring failed, starting unanchored: {err:#}");
    }

    let mut app = App::new(runtime, pending_images);
    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);
    bracketed_paste.disable();
    keyboard_enhancements.disable();
    raw_mode.disable()?;

    write_trajectory_if_requested(
        &trajectory_handles,
        &trajectory_model,
        trajectory_out.as_deref(),
    )
    .await;

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

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();
    }
}

struct BracketedPasteGuard {
    active: bool,
}

impl BracketedPasteGuard {
    fn new() -> Self {
        let mut stdout = io::stdout();
        let active = execute!(stdout, EnableBracketedPaste).is_ok();
        Self { active }
    }

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

impl Drop for BracketedPasteGuard {
    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)
    );
}

/// Export the session as an ATIF trajectory when `--trajectory-out` was
/// given. Best-effort: export problems are reported on stderr and never turn
/// a finished run into a failure.
async fn write_trajectory_if_requested(
    handles: &runtime::RuntimeHandles,
    model: &runtime::ModelState,
    path: Option<&Path>,
) {
    let Some(path) = path else { return };
    let events = match handles.runtime.events().await {
        Ok(events) => events,
        Err(err) => {
            eprintln!("yolop: trajectory export failed to read session events: {err}");
            return;
        }
    };
    let trajectory = atif::trajectory_from_events(
        atif::AgentInfo {
            name: "yolop".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            model_name: Some(model.model_id()),
        },
        handles.session_id,
        &events,
    );
    if let Err(err) = atif::write_trajectory_file(path, &trajectory) {
        eprintln!(
            "yolop: failed to write trajectory to {}: {err}",
            path.display()
        );
    }
}

async fn run_print_mode(
    runtime: BuiltRuntime,
    prompt: String,
    images: Vec<ContentPart>,
    trajectory_out: Option<PathBuf>,
) -> Result<()> {
    let BuiltRuntime {
        handles,
        startup,
        model,
        goal_store,
        user_ask_store,
        user_ask_enabled,
        worktree,
        ..
    } = runtime;
    let color = io::stdout().is_terminal();
    if let Err(err) = worktree.ensure_before_turn(prompt.trim()) {
        eprintln!("worktree: {err}");
    }
    let _ = (&startup.session_dir, &startup.session_log_path);

    let trimmed = prompt.trim();
    if let Some(goal_args) = trimmed.strip_prefix("/goal") {
        // `run_print_goal` reports failure as a flag (not `process::exit`)
        // so the trajectory export still runs on failed goal runs.
        let success = run_print_goal(
            &handles,
            &worktree,
            &model,
            &goal_store,
            goal_args.trim(),
            color,
        )
        .await?;
        write_trajectory_if_requested(&handles, &model, trajectory_out.as_deref()).await;
        if !success {
            std::process::exit(1);
        }
        return Ok(());
    }

    if user_ask_enabled
        && let Err(err) = user_ask_store.record_user_prompt(handles.session_id, trimmed)
    {
        eprintln!("user ask: {err}");
    }

    let turn = collect_print_turn(&handles, &worktree, &model, trimmed, images).await?;
    print_final_output(&turn.output);
    if !turn.result.success {
        write_trajectory_if_requested(&handles, &model, trajectory_out.as_deref()).await;
        std::process::exit(1);
    }
    if user_ask_enabled && user_ask_store.is_active(handles.session_id) {
        let evaluation = handles
            .runtime
            .execute_command(
                handles.session_id,
                ExecuteCommandRequest {
                    name: "ask".to_string(),
                    arguments: Some(user_ask::USER_ASK_EVALUATE_ARG.to_string()),
                    controls: None,
                },
            )
            .await?;
        if evaluation.success {
            let _ = user_ask::parse_evaluation_response(&evaluation.message);
        } else {
            eprintln!("user ask evaluation failed: {}", evaluation.message);
        }
    }
    write_trajectory_if_requested(&handles, &model, trajectory_out.as_deref()).await;
    Ok(())
}

/// Returns `Ok(false)` on goal/turn failure instead of exiting so the caller
/// can finish end-of-run work (trajectory export) before setting the exit code.
async fn run_print_goal(
    handles: &runtime::RuntimeHandles,
    worktree: &crate::worktree::WorktreeManager,
    model: &runtime::ModelState,
    goal_store: &goal::GoalStore,
    arguments: &str,
    color: bool,
) -> Result<bool> {
    let session_id = handles.session_id;
    let request = ExecuteCommandRequest {
        name: "goal".to_string(),
        arguments: if arguments.is_empty() {
            None
        } else {
            Some(arguments.to_string())
        },
        controls: None,
    };
    let result = handles.runtime.execute_command(session_id, request).await?;
    if !result.success {
        eprintln!("goal command failed: {}", result.message);
        return Ok(false);
    }

    if !goal_store.take_pending_turn(session_id) {
        if !result.message.is_empty() {
            println!("{}", paint(color, "90", &result.message));
        }
        return Ok(true);
    }

    let Some(mut turn_prompt) = goal_store.active_condition(session_id) else {
        return Ok(true);
    };

    loop {
        let turn = collect_print_turn(handles, worktree, model, &turn_prompt, vec![]).await?;
        if !turn.result.success {
            print_final_output(&turn.output);
            return Ok(false);
        }
        if !goal_store.is_active(session_id) {
            print_final_output(&turn.output);
            return Ok(true);
        }

        let evaluation = handles
            .runtime
            .execute_command(
                session_id,
                ExecuteCommandRequest {
                    name: "goal".to_string(),
                    arguments: Some(goal::GOAL_EVALUATE_ARG.to_string()),
                    controls: None,
                },
            )
            .await?;
        if !evaluation.success {
            eprintln!("goal evaluation failed: {}", evaluation.message);
            return Ok(false);
        }
        let parsed = goal::parse_evaluation_response(&evaluation.message)?;
        if parsed.met {
            print_final_output(&turn.output);
            return Ok(true);
        }
        turn_prompt = goal_store
            .continuation_prompt(session_id)
            .unwrap_or_else(|| turn_prompt.clone());
    }
}

struct PrintTurn {
    result: everruns_runtime::TurnResult,
    output: Vec<String>,
}

async fn collect_print_turn(
    handles: &runtime::RuntimeHandles,
    worktree: &crate::worktree::WorktreeManager,
    model: &runtime::ModelState,
    prompt: &str,
    images: Vec<ContentPart>,
) -> Result<PrintTurn> {
    if let Err(err) = worktree.ensure_before_turn(prompt) {
        eprintln!("worktree: {err}");
    }
    let before_msgs = handles
        .runtime
        .messages(handles.session_id)
        .await
        .map(|m| m.len())
        .unwrap_or(0);

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

    let mut output = Vec::new();
    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() {
                output.push(t.to_string());
            }
        }
    }
    if !result.success
        && let Some(err) = &result.error
    {
        eprintln!("turn error: {err}");
    }
    Ok(PrintTurn { result, output })
}

fn print_final_output(output: &[String]) {
    for (index, text) in output.iter().enumerate() {
        if index > 0 {
            println!();
        }
        println!("{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,
            images: vec![],
            acp: false,
            session: None,
            session_dir: None,
            trajectory_out: 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, _notes) =
            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, _notes) = 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,
            images: vec![],
            acp: false,
            session: None,
            session_dir: None,
            trajectory_out: None,
        };

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

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

    #[test]
    fn resolve_workspace_root_uses_saved_session_workspace() {
        let sessions = tempfile::tempdir().expect("sessions tempdir");
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        let session_id = SessionId::from_seed(42);
        let session_dir = session_log::session_dir_path(sessions.path(), session_id);
        session_log::write_session_workspace(
            &session_dir,
            &session_log::SessionWorkspaceMetadata::new(workspace.path().to_path_buf(), None),
        )
        .expect("write workspace metadata");

        let resolved =
            resolve_workspace_root(None, Some(session_id), sessions.path()).expect("resolve");

        assert_eq!(resolved, workspace.path());
    }

    #[test]
    fn resolve_workspace_root_prefers_explicit_cwd() {
        let sessions = tempfile::tempdir().expect("sessions tempdir");
        let saved = tempfile::tempdir().expect("saved workspace tempdir");
        let explicit = tempfile::tempdir().expect("explicit workspace tempdir");
        let session_id = SessionId::from_seed(43);
        let session_dir = session_log::session_dir_path(sessions.path(), session_id);
        session_log::write_session_workspace(
            &session_dir,
            &session_log::SessionWorkspaceMetadata::new(saved.path().to_path_buf(), None),
        )
        .expect("write workspace metadata");

        let resolved = resolve_workspace_root(
            Some(explicit.path().to_path_buf()),
            Some(session_id),
            sessions.path(),
        )
        .expect("resolve");

        assert_eq!(resolved, explicit.path());
    }

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

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

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