vtcode-ui 0.140.0

Unified UI crate for VT Code: design system, theme registry, and TUI framework
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
#![allow(missing_docs)]
pub use super::super::Session;
use super::super::TranscriptLine;
pub use crate::tui::config::constants::ui;
pub use crate::tui::core_tui::app::session::AppSession;
pub use crate::tui::core_tui::app::types as app_types;
pub use crate::tui::core_tui::session::terminal_capabilities;
pub use crate::tui::core_tui::types::{InlineCommand, InlineEvent};
pub use crate::tui::core_tui::types::{
    InlineHeaderBadge, InlineHeaderStatusBadge, InlineHeaderStatusTone, InlineLinkTarget, InlineListItem,
    InlineListSearchConfig, InlineListSelection, InlineSegment, InlineTextStyle, InlineTheme, ListOverlayRequest,
    LocalAgentEntry, OverlayEvent, OverlayHotkey, OverlayHotkeyAction, OverlayHotkeyKey, OverlayRequest,
    OverlaySubmission, WizardModalMode, WizardOverlayRequest, WizardStep,
};
pub use crate::tui::core_tui::widgets::TranscriptWidget;
pub use crate::tui::ui::tui::session::message::RenderedTranscriptLink;
pub use anstyle::Color as AnsiColorEnum;
pub use anstyle::RgbColor;
pub use ratatui::crossterm::event::{
    Event as CrosstermEvent, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
#[cfg(target_os = "macos")]
pub use ratatui::crossterm::event::{KeyEventKind, ModifierKeyCode};
pub use ratatui::text::Text;
pub use ratatui::{
    Terminal,
    backend::TestBackend,
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier},
    text::Line,
    widgets::Widget,
};
pub use std::fs;
pub use std::path::PathBuf;
pub use std::sync::Arc;
pub use std::sync::{
    LazyLock, Mutex,
    atomic::{AtomicUsize, Ordering},
};
pub use std::time::Duration;
pub use tokio::sync::mpsc;
pub use tokio::sync::mpsc::UnboundedSender;
pub use vtcode_commons::ui_protocol::InlineMessageKind;

pub(crate) const VIEW_ROWS: u16 = 14;
pub(crate) const VIEW_WIDTH: u16 = 100;
pub(crate) const LINE_COUNT: usize = 10;
pub(crate) const LABEL_PREFIX: &str = "line";
pub(crate) const EXTRA_SEGMENT: &str = "\nextra-line";
static TRANSCRIPT_TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0);
pub(crate) static CLIPBOARD_TEST_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
static TERMINAL_ENV_TEST_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

pub(crate) fn with_terminal_env<R>(tmux: Option<&str>, term: Option<&str>, f: impl FnOnce() -> R) -> R {
    let _guard = TERMINAL_ENV_TEST_LOCK.lock().expect("terminal env test lock");
    let original_tmux = std::env::var("TMUX").ok();
    let original_term = std::env::var("TERM").ok();

    terminal_capabilities::set_test_env_override("TMUX", tmux);
    terminal_capabilities::set_test_env_override("TERM", term);

    let result = f();

    match original_tmux {
        Some(value) => terminal_capabilities::set_test_env_override("TMUX", Some(&value)),
        None => terminal_capabilities::clear_test_env_override("TMUX"),
    }
    match original_term {
        Some(value) => terminal_capabilities::set_test_env_override("TERM", Some(&value)),
        None => terminal_capabilities::clear_test_env_override("TERM"),
    }

    result
}

pub(crate) fn make_segment(text: &str) -> InlineSegment {
    InlineSegment {
        text: text.to_string(),
        style: Arc::new(InlineTextStyle::default()),
    }
}

pub(crate) fn themed_inline_colors() -> InlineTheme {
    InlineTheme {
        foreground: Some(AnsiColorEnum::Rgb(RgbColor(0xEE, 0xEE, 0xEE))),
        tool_accent: Some(AnsiColorEnum::Rgb(RgbColor(0xBF, 0x45, 0x45))),
        tool_body: Some(AnsiColorEnum::Rgb(RgbColor(0xAA, 0x88, 0x88))),
        primary: Some(AnsiColorEnum::Rgb(RgbColor(0x88, 0x88, 0x88))),
        secondary: Some(AnsiColorEnum::Rgb(RgbColor(0x77, 0x99, 0xAA))),
        ..Default::default()
    }
}

pub(crate) fn session_with_input(input: &str, cursor: usize) -> Session {
    let mut session = Session::new(InlineTheme::default(), None, VIEW_ROWS * 2);
    session.set_input(input.to_string());
    session.set_cursor(cursor);
    session
}

pub(crate) fn app_session_with_input(input: &str, cursor: usize) -> AppSession {
    let mut session = AppSession::new(InlineTheme::default(), None, VIEW_ROWS);
    session.core.set_input(input.to_string());
    session.core.set_cursor(cursor);
    session
}

pub(crate) fn left_click_session(
    session: &mut Session,
    events: &UnboundedSender<InlineEvent>,
    column: u16,
    row: u16,
    modifiers: KeyModifiers,
) {
    session.handle_event(
        CrosstermEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column,
            row,
            modifiers,
        }),
        events,
        None,
    );
    session.handle_event(
        CrosstermEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column,
            row,
            modifiers,
        }),
        events,
        None,
    );
}

pub(crate) fn left_click_app_session(
    session: &mut AppSession,
    events: &UnboundedSender<app_types::InlineEvent>,
    column: u16,
    row: u16,
    modifiers: KeyModifiers,
) {
    session.handle_event(
        CrosstermEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column,
            row,
            modifiers,
        }),
        events,
        None,
    );
    session.handle_event(
        CrosstermEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column,
            row,
            modifiers,
        }),
        events,
        None,
    );
}

pub(crate) fn sample_local_agent_entry(kind: app_types::LocalAgentKind) -> LocalAgentEntry {
    sample_local_agent_entry_with_id("agent-1", "rust-engineer", kind)
}

pub(crate) fn sample_local_agent_entry_with_id(
    id: &str,
    display_label: &str,
    kind: app_types::LocalAgentKind,
) -> LocalAgentEntry {
    LocalAgentEntry {
        id: id.to_string(),
        display_label: display_label.to_string(),
        agent_name: display_label.to_string(),
        color: Some("cyan".to_string()),
        kind,
        status: "running".to_string(),
        summary: Some("Reviewing the workspace".to_string()),
        preview: "assistant: reviewing the workspace".to_string(),
        transcript_path: None,
    }
}

pub(crate) fn load_app_file_palette(session: &mut AppSession, files: Vec<String>, workspace: PathBuf) {
    use crate::tui::core_tui::app::session::file_palette::DirLister;
    use std::path::Path;

    // Synthesize a directory lister from the flat file list so navigation works
    // in tests (the paths do not exist on disk). A child is a directory when some
    // other entry is nested beneath it.
    let dir_lister = DirLister::new({
        let files = files.clone();
        move |dir: &Path| {
            let dir_str = dir.display().to_string();
            let mut out: Vec<(PathBuf, bool)> = Vec::new();
            for f in &files {
                let p = Path::new(f);
                let Some(parent) = p.parent() else {
                    continue;
                };
                if parent.display().to_string() != dir_str {
                    continue;
                }
                let is_dir = files.iter().any(|other| other != f && other.starts_with(&format!("{f}/")));
                out.push((PathBuf::from(f), is_dir));
            }
            out.sort_by(|a, b| {
                b.1.cmp(&a.1)
                    .then_with(|| a.0.to_string_lossy().to_lowercase().cmp(&b.0.to_string_lossy().to_lowercase()))
            });
            out
        }
    });

    session.handle_command(app_types::InlineCommand::ShowTransient {
        request: Box::new(app_types::TransientRequest::FilePalette(app_types::FilePaletteTransientRequest {
            dir_lister,
            workspace,
            visible: None,
        })),
    });
    // Mirror the runtime: the recursive index is delivered after configuration.
    session.handle_command(app_types::InlineCommand::UpdateFilePaletteSearch { files });
}

pub(crate) fn session_with_slash_palette_commands() -> AppSession {
    AppSession::new_with_logs(
        InlineTheme::default(),
        None,
        VIEW_ROWS,
        true,
        None,
        vec![
            app_types::SlashCommandItem::new("new", "Start a new session"),
            app_types::SlashCommandItem::new("review", "Review current diff"),
            app_types::SlashCommandItem::new("checkup", "Run diagnostics"),
            app_types::SlashCommandItem::new("command", "Run a terminal command"),
            app_types::SlashCommandItem::new("files", "Browse files"),
        ],
        "Agent TUI".to_string(),
    )
}

pub(crate) fn enable_vim_normal_mode(session: &mut Session) {
    session.vim_state.set_enabled(true);
    assert!(session.handle_vim_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)));
}

pub(crate) fn enable_vim_normal_mode_app(session: &mut AppSession) {
    session.core.vim_state.set_enabled(true);
    assert!(session.core.handle_vim_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)));
}

pub(crate) fn show_basic_list_overlay(session: &mut Session) {
    session.handle_command(InlineCommand::ShowOverlay {
        request: Box::new(OverlayRequest::List(ListOverlayRequest {
            title: "Pick one".to_string(),
            lines: vec!["Choose an option".to_string()],
            footer_hint: None,
            items: vec![
                InlineListItem {
                    title: "Option A".to_string(),
                    subtitle: None,
                    badge: None,
                    indent: 0,
                    selection: Some(InlineListSelection::SlashCommand("a".to_string())),
                    search_value: None,
                },
                InlineListItem {
                    title: "Option B".to_string(),
                    subtitle: None,
                    badge: None,
                    indent: 0,
                    selection: Some(InlineListSelection::SlashCommand("b".to_string())),
                    search_value: None,
                },
            ],
            selected: Some(InlineListSelection::SlashCommand("a".to_string())),
            search: None,
            hotkeys: Vec::new(),
        })),
    });
}

pub(crate) fn show_diff_overlay(session: &mut AppSession, mode: app_types::DiffPreviewMode) {
    session.show_diff_overlay(app_types::DiffOverlayRequest {
        file_path: "src/main.rs".to_string(),
        before: "fn old() {}\n".to_string(),
        after: "fn new() {}\n".to_string(),
        hunks: vec![app_types::DiffHunk {
            old_start: 0,
            new_start: 0,
            old_lines: 1,
            new_lines: 1,
            display: "@@ -1 +1 @@".to_string(),
        }],
        current_hunk: 0,
        mode,
    });
}

pub(crate) fn visible_transcript(session: &mut Session) -> Vec<String> {
    let backend = TestBackend::new(VIEW_WIDTH, VIEW_ROWS);
    let mut terminal = Terminal::new(backend).expect("failed to create test terminal");
    terminal
        .draw(|frame| session.render(frame))
        .expect("failed to render test session");

    current_visible_transcript(session)
}

fn current_visible_transcript(session: &mut Session) -> Vec<String> {
    let width = session.transcript_width;
    let viewport = session.viewport_height();
    let offset = session.transcript_view_top;
    let lines = session.reflow_transcript_lines(width);

    let start = offset.min(lines.len());
    let mut visible: Vec<TranscriptLine> = lines
        .into_iter()
        .skip(start)
        .take(viewport)
        .map(|line| TranscriptLine { line, explicit_links: Vec::new() })
        .collect();
    let filler = viewport.saturating_sub(visible.len());
    if filler > 0 {
        visible.extend((0..filler).map(|_| TranscriptLine::default()));
    }
    if !session.queued_inputs.is_empty() {
        session.overlay_queue_lines(&mut visible, width);
    }
    visible
        .into_iter()
        .map(|line| {
            line.line
                .spans
                .into_iter()
                .map(|span| span.content.into_owned())
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect()
}

pub(crate) fn rendered_session_lines(session: &mut Session, rows: u16) -> Vec<String> {
    session.apply_view_rows(rows);
    let backend = TestBackend::new(VIEW_WIDTH, rows);
    let mut terminal = Terminal::new(backend).expect("failed to create test terminal");
    let completed = terminal.draw(|frame| session.render(frame)).expect("failed to render session");

    let buffer = completed.buffer;
    (0..buffer.area.height)
        .map(|y| {
            (0..buffer.area.width)
                .filter_map(|x| buffer.cell((x, y)).map(|cell| cell.symbol().to_string()))
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect()
}

pub(crate) fn rendered_transcript_widget_lines(session: &mut Session, width: u16, height: u16) -> Vec<String> {
    let area = Rect::new(0, 0, width, height);
    let mut buf = Buffer::empty(area);
    TranscriptWidget::new(session).render(area, &mut buf);

    (0..area.height)
        .map(|y| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol())
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect()
}

pub(crate) fn rendered_transcript_lines(session: &mut Session, rows: u16) -> (Rect, Vec<String>) {
    session.apply_view_rows(rows);
    let backend = TestBackend::new(VIEW_WIDTH, rows);
    let mut terminal = Terminal::new(backend).expect("failed to create test terminal");
    let _ = terminal.draw(|frame| session.render(frame)).expect("failed to render session");

    let area = session.transcript_area().expect("expected transcript area");
    (area, current_visible_transcript(session))
}

pub(crate) fn rendered_app_session_lines(session: &mut AppSession, rows: u16) -> Vec<String> {
    session.core.apply_view_rows(rows);
    let backend = TestBackend::new(VIEW_WIDTH, rows);
    let mut terminal = Terminal::new(backend).expect("failed to create test terminal");
    let completed = terminal.draw(|frame| session.render(frame)).expect("failed to render session");

    let buffer = completed.buffer;
    (0..buffer.area.height)
        .map(|y| {
            (0..buffer.area.width)
                .filter_map(|x| buffer.cell((x, y)).map(|cell| cell.symbol().to_string()))
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect()
}

pub(crate) fn is_horizontal_rule(line: &str) -> bool {
    let glyph = ui::INLINE_BLOCK_HORIZONTAL.chars().next().expect("horizontal rule glyph");
    !line.is_empty() && line.chars().all(|ch| ch == glyph)
}

pub(crate) fn line_text(line: &Line<'_>) -> String {
    line.spans.iter().map(|span| span.content.clone().into_owned()).collect()
}

pub(crate) fn transcript_line(text: impl Into<String>) -> TranscriptLine {
    TranscriptLine {
        line: Line::from(text.into()),
        explicit_links: Vec::new(),
    }
}

pub(crate) fn text_content(text: &Text<'static>) -> String {
    text.lines.iter().map(line_text).collect::<Vec<_>>().join("\n")
}

pub(crate) fn vtcode_tui_workspace_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

pub(crate) fn transcript_file_fixture_relative_path() -> &'static str {
    "src/tui/core_tui/session.rs"
}

pub(crate) fn transcript_file_fixture_absolute_path() -> String {
    vtcode_tui_workspace_root()
        .join(transcript_file_fixture_relative_path())
        .display()
        .to_string()
}

pub(crate) fn quoted_transcript_temp_file_path() -> PathBuf {
    let unique = TRANSCRIPT_TEST_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir().join(format!("vtcode transcript quoted path {} {unique}.txt", std::process::id()))
}

#[cfg(target_os = "macos")]
pub(crate) fn open_file_click_modifiers() -> KeyModifiers {
    KeyModifiers::SUPER
}

#[cfg(not(target_os = "macos"))]
pub fn open_file_click_modifiers() -> KeyModifiers {
    KeyModifiers::CONTROL
}

#[cfg(target_os = "macos")]
pub(crate) fn command_modifier_press_event() -> KeyEvent {
    KeyEvent::new_with_kind(KeyCode::Modifier(ModifierKeyCode::LeftSuper), KeyModifiers::SUPER, KeyEventKind::Press)
}

#[cfg(target_os = "macos")]
pub(crate) fn command_modifier_release_event() -> KeyEvent {
    KeyEvent::new_with_kind(KeyCode::Modifier(ModifierKeyCode::LeftSuper), KeyModifiers::SUPER, KeyEventKind::Release)
}

#[cfg(target_os = "macos")]
pub(crate) fn meta_modifier_press_event() -> KeyEvent {
    KeyEvent::new_with_kind(KeyCode::Modifier(ModifierKeyCode::LeftMeta), KeyModifiers::META, KeyEventKind::Press)
}

pub(crate) fn request_user_input_step(question_id: &str, label: &str) -> WizardStep {
    WizardStep {
        title: format!("Question {question_id}"),
        question: format!("Select {question_id}"),
        items: vec![InlineListItem {
            title: label.to_string(),
            subtitle: Some("Option".to_string()),
            badge: None,
            indent: 0,
            selection: Some(InlineListSelection::RequestUserInputAnswer {
                question_id: question_id.to_string(),
                selected: vec![label.to_string()],
                other: None,
            }),
            search_value: Some(label.to_string()),
        }],
        completed: false,
        answer: None,
        allow_freeform: true,
        freeform_label: None,
        freeform_placeholder: None,
        freeform_default: None,
    }
}

pub(crate) fn request_user_input_custom_step(question_id: &str, label: &str, default: &str) -> WizardStep {
    WizardStep {
        title: format!("Question {question_id}"),
        question: format!("Enter {question_id}"),
        items: vec![InlineListItem {
            title: label.to_string(),
            subtitle: Some("Input".to_string()),
            badge: None,
            indent: 0,
            selection: Some(InlineListSelection::RequestUserInputAnswer {
                question_id: question_id.to_string(),
                selected: vec![],
                other: Some(String::new()),
            }),
            search_value: Some(label.to_string()),
        }],
        completed: false,
        answer: None,
        allow_freeform: true,
        freeform_label: Some(label.to_string()),
        freeform_placeholder: Some(default.to_string()),
        freeform_default: Some(default.to_string()),
    }
}

pub(crate) fn show_plan_confirmation_overlay(session: &mut Session, plan: app_types::PlanContent) {
    let mut lines: Vec<String> = plan.raw_content.lines().map(|line| line.to_string()).collect();
    if lines.is_empty() && !plan.summary.is_empty() {
        lines.push(plan.summary.clone());
    }
    lines.insert(0, "A plan is ready to execute. Would you like to proceed?".to_string());

    session.handle_command(InlineCommand::ShowOverlay {
        request: Box::new(OverlayRequest::List(ListOverlayRequest {
            title: "Ready to code?".to_string(),
            lines,
            footer_hint: plan
                .file_path
                .as_ref()
                .map(|path| format!("ctrl-g to edit in VS Code · {path}")),
            items: vec![
                InlineListItem {
                    title: "Yes, auto-accept edits".to_string(),
                    subtitle: Some("Execute with auto-approval.".to_string()),
                    badge: Some("Recommended".to_string()),
                    indent: 0,
                    selection: Some(InlineListSelection::PlanApprovalAutoAccept),
                    search_value: None,
                },
                InlineListItem {
                    title: "Yes, manually approve edits".to_string(),
                    subtitle: Some("Keep context and confirm each edit before applying.".to_string()),
                    badge: None,
                    indent: 0,
                    selection: Some(InlineListSelection::PlanApprovalExecute),
                    search_value: None,
                },
                InlineListItem {
                    title: "Type feedback to revise the plan".to_string(),
                    subtitle: Some("Return to planning workflow and refine the plan.".to_string()),
                    badge: None,
                    indent: 0,
                    selection: Some(InlineListSelection::PlanApprovalEditPlan),
                    search_value: None,
                },
            ],
            selected: Some(InlineListSelection::PlanApprovalAutoAccept),
            search: None,
            hotkeys: vec![OverlayHotkey {
                key: OverlayHotkeyKey::CtrlChar('g'),
                action: OverlayHotkeyAction::LaunchEditor,
            }],
        })),
    });
}

// Helper structs and functions for transcript_links tests

pub(crate) struct SessionWithFileLink {
    pub(crate) session: Session,
    pub(crate) path: String,
}

impl SessionWithFileLink {
    pub(crate) fn new() -> Self {
        let path = transcript_file_fixture_absolute_path();
        let mut session = Session::new(InlineTheme::default(), None, VIEW_ROWS);
        session.push_line(InlineMessageKind::Agent, vec![make_segment(&format!("Open {path}"))]);
        let _ = visible_transcript(&mut session);
        Self { session, path }
    }

    pub(crate) fn target_area(&self) -> Rect {
        self.session
            .transcript_file_link_targets
            .first()
            .expect("expected transcript file target")
            .area
    }
}

pub(crate) struct AppSessionWithFileLink {
    pub(crate) session: AppSession,
    pub(crate) path: String,
}

impl AppSessionWithFileLink {
    pub(crate) fn new() -> Self {
        let path = transcript_file_fixture_absolute_path();
        let mut session = AppSession::new(InlineTheme::default(), None, VIEW_ROWS);
        session.push_line(InlineMessageKind::Agent, vec![make_segment(&format!("Open {path}"))]);
        let _ = rendered_app_session_lines(&mut session, VIEW_ROWS);
        Self { session, path }
    }

    pub(crate) fn target_area(&self) -> Rect {
        self.session
            .core
            .transcript_file_link_targets
            .first()
            .expect("expected transcript file target")
            .area
    }
}

pub(crate) fn wizard_auth_transient(url: &str) -> app_types::TransientRequest {
    app_types::TransientRequest::Wizard(app_types::WizardOverlayRequest {
        title: "OpenAI manual callback".to_string(),
        steps: vec![WizardStep {
            title: "Callback".to_string(),
            question: format!("Open this URL in your browser:\n\n{url}"),
            items: vec![InlineListItem {
                title: "Submit".to_string(),
                subtitle: Some("Press Enter to continue.".to_string()),
                badge: None,
                indent: 0,
                selection: Some(InlineListSelection::ConfigAction("submit".to_string())),
                search_value: None,
            }],
            completed: false,
            answer: None,
            allow_freeform: false,
            freeform_label: None,
            freeform_placeholder: None,
            freeform_default: None,
        }],
        current_step: 0,
        search: None,
        mode: WizardModalMode::MultiStep,
    })
}

pub(crate) fn list_auth_overlay(url: &str) -> OverlayRequest {
    OverlayRequest::List(ListOverlayRequest {
        title: format!("Authorize with {url}"),
        lines: vec![format!("Open this URL in your browser:\n{url}")],
        footer_hint: None,
        items: vec![InlineListItem {
            title: "Continue".to_string(),
            subtitle: None,
            badge: None,
            indent: 0,
            selection: Some(InlineListSelection::SlashCommand("continue".to_string())),
            search_value: None,
        }],
        selected: Some(InlineListSelection::SlashCommand("continue".to_string())),
        search: None,
        hotkeys: Vec::new(),
    })
}

// Helpers for queue_inputs tests

pub(crate) fn set_busy_status(session: &mut Session) {
    session.handle_command(InlineCommand::SetInputStatus {
        left: Some("Running tool: code_search".to_string()),
        right: None,
    });
}

pub(crate) fn set_app_session_busy_status(session: &mut AppSession) {
    session.handle_command(app_types::InlineCommand::SetInputStatus {
        left: Some("Running tool: code_search".to_string()),
        right: None,
    });
}

pub(crate) fn set_queued_inputs(session: &mut Session, entries: Vec<String>) {
    session.handle_command(InlineCommand::SetQueuedInputs { entries });
}

pub(crate) fn set_app_session_queued_inputs(session: &mut AppSession, entries: Vec<String>) {
    session.handle_command(app_types::InlineCommand::SetQueuedInputs { entries });
}

pub(crate) fn assert_footer_contains(session: &mut Session, take_from_bottom: u16, needle: &str) {
    let view = visible_transcript(session);
    let footer: Vec<String> = view.iter().rev().take(take_from_bottom as usize).cloned().collect();
    assert!(footer.iter().any(|line| line.contains(needle)), "expected footer to contain: {needle}");
}