kodact-cli 0.1.0

The kodact binary: interactive and print modes, the stream-json host protocol, subcommands.
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
//! The interactive terminal UI (M8). The design is in docs/TUI.md.
//!
//! By default the UI takes the whole window (the terminal's alternate
//! screen): a centred front screen until the first message, then the
//! transcript above the live region (the answer being written, the spinner,
//! a dialog, the input box, the status line). On exit the transcript is
//! printed into the terminal's scrollback. With `KODACT_TUI=inline`, an inline
//! viewport at the bottom shows what is live and finished output goes into
//! the terminal's own scrollback as it happens.
//!
//! - `editor`: the prompt's text editor;
//! - `text`: theme, one-line markdown, wrapping;
//! - `app`: the UI state machine (keys and session events);
//! - `render`: the live region, drawn from the app;
//! - `session`: the task that owns the driver;
//! - this module: the terminal, the event loop and prompt history.

pub mod app;
pub mod brand;
pub mod editor;
pub mod front;
pub mod keys;
pub mod look;
pub mod palette;
pub mod render;
pub mod session;
pub mod text;

use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use crossterm::event::{
    DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture, Event, EventStream, KeyCode,
    KeyEventKind, KeyModifiers, KeyboardEnhancementFlags, MouseEventKind, PopKeyboardEnhancementFlags,
    PushKeyboardEnhancementFlags,
};
use futures::StreamExt;
use ratatui::backend::{Backend, CrosstermBackend};
use ratatui::layout::Position;
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, Widget};
use ratatui::{Terminal, TerminalOptions, Viewport};
use tokio::sync::mpsc;

use app::{Action, App, UiEvent};
use render::LiveView;
use session::ToSession;

use crate::args::Opts;
use crate::exit::Fail;

/// Rows written into scrollback per `insert_before` call.
const COMMIT_CHUNK: usize = 100;
/// The fastest the live region is redrawn.
const FRAME: Duration = Duration::from_millis(16);
/// Prompts kept from history for this directory.
const HISTORY_ENTRIES: usize = 500;

/// A backend that remembers where the cursor is instead of asking the terminal.
///
/// ratatui asks for the cursor position whenever an inline viewport is made or
/// resized. Asking means writing a query and reading the reply from stdin, but
/// once the UI runs, crossterm's event reader owns stdin, so the reply never
/// arrives and the query fails after two seconds ("The cursor position could
/// not be read"), which ended the session (seen with `/model`). Only the first
/// viewport asks the terminal; after that every move goes through this
/// backend, so it knows.
pub struct Tracked<B: Backend> {
    inner: B,
    pos: std::rc::Rc<std::cell::Cell<Option<Position>>>,
}

impl<B: Backend> Backend for Tracked<B> {
    fn draw<'a, I>(&mut self, content: I) -> std::io::Result<()>
    where
        I: Iterator<Item = (u16, u16, &'a ratatui::buffer::Cell)>,
    {
        let mut last = None;
        let cells: Vec<_> = content.inspect(|(x, y, _)| last = Some(Position { x: *x, y: *y })).collect();
        self.inner.draw(cells.into_iter())?;
        if let Some(p) = last {
            self.pos.set(Some(Position { x: p.x.saturating_add(1), y: p.y }));
        }
        Ok(())
    }

    fn append_lines(&mut self, n: u16) -> std::io::Result<()> {
        self.inner.append_lines(n)?;
        if let Some(p) = self.pos.get() {
            let rows = self.inner.size().map(|s| s.height).unwrap_or(u16::MAX);
            self.pos.set(Some(Position { x: p.x, y: p.y.saturating_add(n).min(rows.saturating_sub(1)) }));
        }
        Ok(())
    }

    fn hide_cursor(&mut self) -> std::io::Result<()> {
        self.inner.hide_cursor()
    }

    fn show_cursor(&mut self) -> std::io::Result<()> {
        self.inner.show_cursor()
    }

    fn get_cursor_position(&mut self) -> std::io::Result<Position> {
        match self.pos.get() {
            Some(p) => Ok(p),
            None => {
                let p = self.inner.get_cursor_position()?;
                self.pos.set(Some(p));
                Ok(p)
            }
        }
    }

    fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> std::io::Result<()> {
        let p = position.into();
        self.inner.set_cursor_position(p)?;
        self.pos.set(Some(p));
        Ok(())
    }

    fn clear(&mut self) -> std::io::Result<()> {
        self.inner.clear()
    }

    fn clear_region(&mut self, clear_type: ratatui::backend::ClearType) -> std::io::Result<()> {
        self.inner.clear_region(clear_type)
    }

    fn size(&self) -> std::io::Result<ratatui::layout::Size> {
        self.inner.size()
    }

    fn window_size(&mut self) -> std::io::Result<ratatui::backend::WindowSize> {
        self.inner.window_size()
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

/// The live viewport and the scrollback above it.
pub struct Screen<B: Backend> {
    terminal: Terminal<Tracked<B>>,
    /// Makes a fresh backend when the viewport changes height.
    make: Box<dyn FnMut() -> B>,
    height: u16,
    pos: std::rc::Rc<std::cell::Cell<Option<Position>>>,
}

impl<B: Backend> Screen<B> {
    pub fn new(mut make: Box<dyn FnMut() -> B>, height: u16) -> std::io::Result<Self> {
        let pos = std::rc::Rc::new(std::cell::Cell::new(None));
        let backend = Tracked { inner: make(), pos: pos.clone() };
        let terminal = Terminal::with_options(backend, TerminalOptions { viewport: Viewport::Inline(height) })?;
        Ok(Screen { terminal, make, height, pos })
    }

    pub fn height(&self) -> u16 {
        self.height
    }

    pub fn width(&self) -> u16 {
        self.terminal.size().map(|s| s.width).unwrap_or(80)
    }

    pub fn rows(&self) -> u16 {
        self.terminal.size().map(|s| s.height).unwrap_or(24)
    }

    /// Change the viewport's height. ratatui can't resize an inline viewport
    /// in place: clear it (the cursor goes to its top) and make a new one there.
    pub fn set_height(&mut self, h: u16) -> std::io::Result<()> {
        let h = h.max(1);
        if h == self.height {
            return Ok(());
        }
        self.terminal.clear()?;
        let backend = Tracked { inner: (self.make)(), pos: self.pos.clone() };
        self.terminal = Terminal::with_options(backend, TerminalOptions { viewport: Viewport::Inline(h) })?;
        self.height = h;
        Ok(())
    }

    /// Write finished lines into scrollback, above the viewport.
    pub fn commit(&mut self, lines: Vec<Line<'static>>) -> std::io::Result<()> {
        let rows = text::wrap(lines, self.width());
        for chunk in rows.chunks(COMMIT_CHUNK) {
            let chunk = chunk.to_vec();
            self.terminal.insert_before(chunk.len() as u16, |buf| Paragraph::new(chunk).render(buf.area, buf))?;
        }
        Ok(())
    }

    /// Draw the live region. A view shorter than the viewport sits at its bottom.
    pub fn draw(&mut self, view: &LiveView) -> std::io::Result<()> {
        let pad = (self.height as usize).saturating_sub(view.lines.len());
        let mut lines = vec![Line::default(); pad];
        lines.extend(view.lines.iter().cloned());
        self.terminal.draw(|f| {
            let area = f.area();
            f.render_widget(Paragraph::new(lines), area);
            if let Some((x, y)) = view.cursor {
                let y = y + pad as u16;
                if x < area.width && y < area.height {
                    f.set_cursor_position((area.x + x, area.y + y));
                }
            }
        })?;
        Ok(())
    }

    /// Clear the live region (Ctrl+L redraws after this).
    pub fn clear(&mut self) -> std::io::Result<()> {
        self.terminal.clear()
    }

    #[cfg(test)]
    pub fn backend(&self) -> &B {
        &self.terminal.backend().inner
    }
}

/// The full-screen UI: the whole window, and the transcript it keeps itself
/// (wrapped once per width, as lines arrive).
pub struct Full<B: Backend> {
    terminal: Terminal<B>,
    /// Finished lines, as committed.
    transcript: Vec<Line<'static>>,
    /// The transcript wrapped to `wrapped_w`.
    wrapped: Vec<Line<'static>>,
    wrapped_w: u16,
    /// Rows up from the transcript's end.
    pub scroll: usize,
    max_scroll: usize,
    /// What the front page shows about the session.
    info: front::FrontInfo,
}

impl<B: Backend> Full<B> {
    pub fn new(backend: B, info: front::FrontInfo) -> std::io::Result<Self> {
        let terminal = Terminal::with_options(backend, TerminalOptions { viewport: Viewport::Fullscreen })?;
        Ok(Full { terminal, transcript: vec![], wrapped: vec![], wrapped_w: 0, scroll: 0, max_scroll: 0, info })
    }

    pub fn width(&self) -> u16 {
        self.terminal.size().map(|s| s.width).unwrap_or(80)
    }

    pub fn rows(&self) -> u16 {
        self.terminal.size().map(|s| s.height).unwrap_or(24)
    }

    /// Finished lines join the transcript. A view scrolled up stays where it is.
    pub fn commit(&mut self, lines: Vec<Line<'static>>) {
        let w = self.width();
        let rows = text::wrap(lines.clone(), w);
        if self.scroll > 0 {
            self.scroll += rows.len();
        }
        if w == self.wrapped_w {
            self.wrapped.extend(rows);
        }
        self.transcript.extend(lines);
    }

    /// Scroll by `rows` (up when positive), within the transcript.
    pub fn scroll_by(&mut self, rows: isize) {
        self.scroll = (self.scroll as isize + rows).clamp(0, self.max_scroll as isize) as usize;
    }

    pub fn draw(&mut self, app: &App) -> std::io::Result<()> {
        let size = self.terminal.size()?;
        if size.width != self.wrapped_w {
            self.wrapped = text::wrap(self.transcript.clone(), size.width);
            self.wrapped_w = size.width;
        }
        let page = front::front_page(&app.theme, app.look, &self.info, size.width as usize);
        let (view, max) = render::full_view(app, size.width, size.height, &self.wrapped, &page, self.scroll);
        self.max_scroll = max;
        self.scroll = self.scroll.min(max);
        self.terminal.draw(|f| {
            let area = f.area();
            f.render_widget(Paragraph::new(view.lines.clone()), area);
            if let Some((x, y)) = view.cursor {
                if x < area.width && y < area.height {
                    f.set_cursor_position((area.x + x, area.y + y));
                }
            }
        })?;
        Ok(())
    }

    pub fn clear(&mut self) -> std::io::Result<()> {
        self.terminal.clear()
    }

    /// The transcript as text with ANSI styles, wrapped to `cols`, for the
    /// terminal's scrollback once the full screen has closed.
    pub fn transcript_text(&self, cols: u16) -> Vec<String> {
        text::wrap(self.transcript.clone(), cols).iter().map(brand::ansi).collect()
    }
}

/// Where the UI draws: the whole window, or an inline viewport.
enum Display {
    Full(Box<Full<CrosstermBackend<std::io::Stdout>>>),
    Inline(Screen<CrosstermBackend<std::io::Stdout>>),
}

impl Display {
    fn clear(&mut self) -> std::io::Result<()> {
        match self {
            Display::Full(f) => f.clear(),
            Display::Inline(s) => s.clear(),
        }
    }
}

/// The full-screen UI, unless `KODACT_TUI=inline` asks for the inline one.
fn full_screen() -> bool {
    std::env::var("KODACT_TUI").map(|v| !v.trim().eq_ignore_ascii_case("inline")).unwrap_or(true)
}

// ---- the terminal's modes ----

static ENHANCED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The UI is on the alternate screen, with the mouse captured (for the wheel).
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// The terminal turned on the keyboard protocol (Shift+Enter is its own key).
pub fn keyboard_protocol() -> bool {
    ENHANCED.load(std::sync::atomic::Ordering::SeqCst)
}

/// Put `text` on the clipboard through the terminal (OSC 52).
fn osc52(text: &str) -> String {
    use base64::Engine as _;
    format!("\x1b]52;c;{}\x07", base64::engine::general_purpose::STANDARD.encode(text))
}

/// Put the terminal back as it was: keyboard flags, paste, raw mode, cursor.
fn restore() {
    let mut out = std::io::stdout();
    if ENHANCED.swap(false, std::sync::atomic::Ordering::SeqCst) {
        let _ = crossterm::execute!(out, PopKeyboardEnhancementFlags);
    }
    if FULL.swap(false, std::sync::atomic::Ordering::SeqCst) {
        let _ = crossterm::execute!(out, DisableMouseCapture, crossterm::terminal::LeaveAlternateScreen);
    }
    let _ = crossterm::execute!(out, DisableBracketedPaste, crossterm::cursor::Show);
    let _ = crossterm::terminal::disable_raw_mode();
    let _ = out.flush();
}

/// Restores the terminal when dropped, on every exit path.
struct Guard;

impl Drop for Guard {
    fn drop(&mut self) {
        restore();
    }
}

fn setup(full: bool) -> std::io::Result<Guard> {
    crossterm::terminal::enable_raw_mode()?;
    let guard = Guard;
    let mut out = std::io::stdout();
    crossterm::execute!(out, EnableBracketedPaste)?;
    if full {
        crossterm::execute!(out, crossterm::terminal::EnterAlternateScreen, EnableMouseCapture)?;
        FULL.store(true, std::sync::atomic::Ordering::SeqCst);
    }
    if crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false) {
        // Shift+Enter becomes a key of its own.
        crossterm::execute!(out, PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES))?;
        ENHANCED.store(true, std::sync::atomic::Ordering::SeqCst);
    }
    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore();
        prev(info);
    }));
    Ok(guard)
}

// ---- prompt history ----

pub fn history_path() -> PathBuf {
    kodact_config::state_dir().join("history.jsonl")
}

/// The last prompts typed in `cwd`, oldest first.
pub fn load_history(path: &Path, cwd: &str) -> Vec<String> {
    let Ok(text) = std::fs::read_to_string(path) else { return vec![] };
    let mut out: Vec<String> = text
        .lines()
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter(|v| v["cwd"] == cwd)
        .filter_map(|v| v["text"].as_str().map(str::to_string))
        .collect();
    if out.len() > HISTORY_ENTRIES {
        out.drain(..out.len() - HISTORY_ENTRIES);
    }
    out
}

/// Add a prompt to the history file (created with mode 0600).
pub fn append_history(path: &Path, cwd: &str, text: &str) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let mut o = std::fs::OpenOptions::new();
    o.create(true).append(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        o.mode(0o600);
    }
    let mut f = o.open(path)?;
    writeln!(f, "{}", serde_json::json!({"text": text, "cwd": cwd}))
}

// ---- `@` completion ----

/// Most paths offered for `@` completion.
const MAX_FILES: usize = 20_000;

/// The project's files and directories (relative, `/`-separated; directories end in `/`),
/// skipping what `.gitignore` and hidden-file rules skip.
pub fn project_files(root: &Path) -> Vec<String> {
    let mut out = vec![];
    for e in ignore::WalkBuilder::new(root).build().flatten() {
        let Ok(rel) = e.path().strip_prefix(root) else { continue };
        if rel.as_os_str().is_empty() {
            continue;
        }
        let mut p = rel.to_string_lossy().replace('\\', "/");
        if e.file_type().is_some_and(|t| t.is_dir()) {
            p.push('/');
        }
        out.push(p);
        if out.len() >= MAX_FILES {
            break;
        }
    }
    out
}

fn walk_files(root: String, ui: mpsc::UnboundedSender<UiEvent>) {
    tokio::task::spawn_blocking(move || {
        let _ = ui.send(UiEvent::Files(project_files(Path::new(&root))));
    });
}

// ---- the loop ----

/// The interactive UI: until `/exit`, Ctrl-D or Ctrl-C twice.
pub async fn run(prompt: Option<String>, o: Opts) -> Result<i32, Fail> {
    let (ui_tx, mut ui_rx) = mpsc::unbounded_channel::<UiEvent>();
    let theme = text::Theme::named("auto", crate::term::get().color, palette::Depth::detect());
    let cols = crossterm::terminal::size().map(|(c, _)| c as usize).unwrap_or(80);
    let (driver, warnings) = match session::build(&o, ui_tx.clone()).await {
        Ok(built) => built,
        // Nothing to talk to yet: the first-run card says how to set one up.
        Err(f) if f.first_run => {
            for l in brand::first_run(&theme, kodact_core::VERSION, &f.message, cols) {
                println!("{}", brand::ansi(&l));
            }
            return Ok(f.code);
        }
        Err(f) => return Err(f),
    };
    let live = driver.live();
    let cwd = driver.info.cwd.display().to_string();
    let persist = !o.no_session_persistence;
    let hist_path = history_path();
    // The `theme` setting arrives from the session first thing.
    let mut app = App::new(theme, load_history(&hist_path, &cwd));
    // Bad entries in keybindings.json are warnings, never a failure.
    let (keymap, key_warnings) = keys::Keymap::load();
    app.keymap = keymap;
    let warnings: Vec<String> = warnings.into_iter().chain(key_warnings).collect();
    let provider = driver.engine.provider();
    let endpoint = endpoint_label(provider.base_url().as_deref(), provider.origin().map(|o| o.backend));
    let recent = kodact_core::commands::recent_sessions(&driver, 3);
    let full = full_screen();
    let branch = kodact_git::current_branch(&driver.info.cwd);
    let info = front::FrontInfo {
        version: kodact_core::VERSION.to_string(),
        model: driver.handle().model(),
        endpoint: endpoint.clone(),
        folder: short_path(&cwd),
        branch: branch.clone(),
        mcp: driver.info.init.mcp_servers.iter().map(|s| (s.name.clone(), s.status.clone())).collect(),
        tools: driver.info.init.tools.len(),
        recent: recent.clone(),
    };
    app.front = true;
    app.endpoint = endpoint;
    app.branch = branch.unwrap_or_default();
    if !full {
        let rows = crossterm::terminal::size().map(|(_, r)| r as usize).unwrap_or(24);
        app.pending.extend(brand::welcome(
            &theme,
            &brand::Welcome { recent: &recent[..recent.len().min(1)] },
            cols,
            rows,
        ));
    }
    for w in warnings {
        app.on_event(UiEvent::Engine(kodact_engine::EngineEvent::Notice {
            level: kodact_engine::NoticeLevel::Warning,
            text: w,
        }));
    }

    let (to_session, rx) = mpsc::unbounded_channel::<ToSession>();
    walk_files(cwd.clone(), ui_tx.clone());
    // Re-walked when the session moves (/cd). A weak sender, so the channel still
    // closes when the session task ends.
    let files_tx = ui_tx.downgrade();
    let mut files_root = cwd.clone();
    // The session task holds the other senders (here and in its sink and prompter): when it
    // ends, the UI sees the channel close.
    let task = tokio::spawn(session::run(driver, rx, ui_tx));
    let guard = setup(full).map_err(|e| Fail::config(format!("cannot set up the terminal: {e}")))?;
    let draw_fail = |e: std::io::Error| Fail::config(format!("cannot draw on the terminal: {e}"));
    let mut screen = if full {
        Display::Full(Box::new(Full::new(CrosstermBackend::new(std::io::stdout()), info).map_err(draw_fail)?))
    } else {
        Display::Inline(Screen::new(Box::new(|| CrosstermBackend::new(std::io::stdout())), 1).map_err(draw_fail)?)
    };

    let send = |text: String, to: &mpsc::UnboundedSender<ToSession>| {
        let _ = append_history(&hist_path, &cwd, &text);
        let _ = to.send(ToSession::Input(text));
    };
    if let Some(p) = prompt.filter(|p| !p.trim().is_empty()) {
        for a in app.submit(p) {
            if let Action::Send(t) = a {
                send(t, &to_session);
            }
        }
    }

    let mut events = EventStream::new();
    let mut tick = tokio::time::interval(render::SPINNER_STEP);
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    let mut last_draw = Instant::now() - FRAME;
    let mut had_dialog = false;
    let mut exiting = false;
    loop {
        if !app.pending.is_empty() {
            match &mut screen {
                Display::Inline(s) => s.commit(app.take_pending()).map_err(io_fail)?,
                Display::Full(f) => f.commit(app.take_pending()),
            }
            app.dirty = true;
        }
        if let Some(text) = app.clipboard.take() {
            let mut out = std::io::stdout();
            let _ = out.write_all(osc52(&text).as_bytes());
            let _ = out.flush();
        }
        if app.exit {
            break;
        }
        while let Some(t) = app.next_queued() {
            send(t, &to_session);
        }
        if !app.status.cwd.is_empty() && app.status.cwd != files_root {
            files_root = app.status.cwd.clone();
            if let Some(tx) = files_tx.upgrade() {
                walk_files(files_root.clone(), tx);
            }
        }
        let now = Instant::now();
        if app.dirty && now.duration_since(last_draw) >= FRAME {
            match &mut screen {
                Display::Inline(screen) => {
                    let max = screen.rows().saturating_sub(1).max(1);
                    let view = render::live_view(&app, screen.width(), max);
                    let want = (view.lines.len() as u16).min(max);
                    let dialog_closed = had_dialog && app.dialog.is_none();
                    if want > screen.height() || (want < screen.height() && (!app.busy || dialog_closed)) {
                        screen.set_height(want).map_err(io_fail)?;
                    }
                    screen.draw(&view).map_err(io_fail)?;
                }
                Display::Full(f) => f.draw(&app).map_err(io_fail)?,
            }
            had_dialog = app.dialog.is_some();
            app.dirty = false;
            last_draw = now;
        }
        let hint = app.hint.as_ref().is_some_and(|(_, at)| at.elapsed() < render::HINT_FOR + render::SPINNER_STEP);
        let frame_wait = (last_draw + FRAME).saturating_duration_since(Instant::now());
        tokio::select! {
            ev = events.next() => match ev {
                Some(Ok(Event::Key(k))) if k.kind != KeyEventKind::Release
                    && app.keymap.translate(k).is_some_and(|k| {
                        k.code == KeyCode::Char('l') && k.modifiers.contains(KeyModifiers::CONTROL)
                    }) => {
                    screen.clear().map_err(io_fail)?;
                    app.dirty = true;
                }
                // The full screen scrolls its transcript: the wheel, and PgUp / PgDn with no dialog open.
                Some(Ok(Event::Mouse(m))) if matches!(screen, Display::Full(_)) => {
                    if let Display::Full(f) = &mut screen {
                        match m.kind {
                            MouseEventKind::ScrollUp => f.scroll_by(3),
                            MouseEventKind::ScrollDown => f.scroll_by(-3),
                            _ => {}
                        }
                    }
                    app.dirty = true;
                }
                Some(Ok(Event::Key(k))) if k.kind != KeyEventKind::Release
                    && app.dialog.is_none()
                    && matches!(k.code, KeyCode::PageUp | KeyCode::PageDown)
                    && matches!(screen, Display::Full(_)) => {
                    if let Display::Full(f) = &mut screen {
                        let page = (f.rows() as isize / 2).max(1);
                        f.scroll_by(if k.code == KeyCode::PageUp { page } else { -page });
                    }
                    app.dirty = true;
                }
                Some(Ok(Event::Resize(..))) => app.dirty = true,
                Some(Ok(ev)) => {
                    for a in app.on_term_event(ev) {
                        match a {
                            Action::Send(t) => {
                                // Sending goes back to the newest lines.
                                if let Display::Full(f) = &mut screen {
                                    f.scroll = 0;
                                }
                                send(t, &to_session)
                            }
                            Action::Picker(t) => {
                                let _ = to_session.send(ToSession::Picker(t));
                            }
                            Action::Interrupt => {
                                live.handle().interrupt();
                                app.close_dialog_if_stale();
                            }
                            Action::SetMode(m) => live.handle().set_permission_mode(m),
                            Action::Exit => {
                                let _ = to_session.send(ToSession::Exit);
                                exiting = true;
                            }
                        }
                    }
                    if exiting {
                        break;
                    }
                }
                // The terminal is gone.
                Some(Err(_)) | None => break,
            },
            ev = ui_rx.recv() => match ev {
                Some(ev) => {
                    app.on_event(ev);
                    // Take what else is ready, so a burst of deltas is one frame.
                    while let Ok(ev) = ui_rx.try_recv() {
                        app.on_event(ev);
                    }
                }
                None => break,
            },
            _ = tick.tick(), if app.busy || hint => app.dirty = true,
            _ = tokio::time::sleep(frame_wait), if app.dirty && !frame_wait.is_zero() => {}
        }
    }
    // Whatever is left goes to scrollback, then the live region is cleared. The full
    // screen closes, and its transcript goes into the terminal's scrollback.
    let transcript = match &mut screen {
        Display::Inline(s) => {
            let _ = s.commit(app.take_pending());
            let _ = s.set_height(1);
            let _ = s.clear();
            vec![]
        }
        Display::Full(f) => {
            f.commit(app.take_pending());
            let cols = f.width();
            f.transcript_text(cols)
        }
    };
    drop(screen);
    drop(guard);
    if !transcript.is_empty() {
        let mut out = std::io::stdout();
        for l in transcript {
            let _ = writeln!(out, "{l}");
        }
        let _ = out.flush();
    }
    let _ = to_session.send(ToSession::Exit);
    drop(to_session);
    // The session ends its own way (hooks, MCP); don't wait for it forever.
    let _ = tokio::time::timeout(Duration::from_secs(5), task).await;
    if persist {
        eprintln!("Resume this conversation with: kodact --resume {}", live.session_id());
    }
    Ok(crate::exit::OK)
}

/// Where requests go, for the welcome banner: the endpoint's host, or its kind.
fn endpoint_label(url: Option<&str>, backend: Option<kodact_api::auth::Backend>) -> String {
    if let Some(u) = url {
        let rest = u.split_once("://").map(|(_, r)| r).unwrap_or(u);
        let host = rest.split(['/', '?', '#']).next().unwrap_or(rest);
        // No user name or password in a banner.
        let host = host.rsplit('@').next().unwrap_or(host);
        if !host.is_empty() {
            return host.to_string();
        }
    }
    match backend {
        Some(kodact_api::auth::Backend::OpenAi) => "an OpenAI-compatible endpoint".into(),
        Some(kodact_api::auth::Backend::Gemini) => "the Gemini API".into(),
        _ => "the Messages API".into(),
    }
}

/// A directory as people write it: `~/proj` under the home directory.
pub fn short_path(p: &str) -> String {
    kodact_config::short_path(std::path::Path::new(p))
}

fn io_fail(e: std::io::Error) -> Fail {
    Fail::config(format!("terminal error: {e}"))
}

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

    #[test]
    fn the_banner_names_the_endpoint_host_without_credentials() {
        use kodact_api::auth::Backend;
        assert_eq!(endpoint_label(Some("http://127.0.0.1:11434/v1"), Some(Backend::OpenAi)), "127.0.0.1:11434");
        assert_eq!(endpoint_label(Some("https://u:p@gw.example.com/v1?k=x"), None), "gw.example.com");
        assert_eq!(endpoint_label(None, Some(Backend::Messages)), "the Messages API");
        assert_eq!(endpoint_label(None, Some(Backend::OpenAi)), "an OpenAI-compatible endpoint");
    }
    use ratatui::backend::TestBackend;

    /// A terminal that answers the cursor-position query only once, like a
    /// real one whose stdin the event reader has taken over.
    struct AsksOnce {
        inner: TestBackend,
        asked: std::rc::Rc<std::cell::Cell<u32>>,
    }

    impl Backend for AsksOnce {
        fn draw<'a, I: Iterator<Item = (u16, u16, &'a ratatui::buffer::Cell)>>(&mut self, c: I) -> std::io::Result<()> {
            self.inner.draw(c)
        }
        fn append_lines(&mut self, n: u16) -> std::io::Result<()> {
            self.inner.append_lines(n)
        }
        fn hide_cursor(&mut self) -> std::io::Result<()> {
            self.inner.hide_cursor()
        }
        fn show_cursor(&mut self) -> std::io::Result<()> {
            self.inner.show_cursor()
        }
        fn get_cursor_position(&mut self) -> std::io::Result<Position> {
            self.asked.set(self.asked.get() + 1);
            if self.asked.get() > 1 {
                return Err(std::io::Error::other("The cursor position could not be read within a normal duration"));
            }
            self.inner.get_cursor_position()
        }
        fn set_cursor_position<P: Into<Position>>(&mut self, p: P) -> std::io::Result<()> {
            self.inner.set_cursor_position(p)
        }
        fn clear(&mut self) -> std::io::Result<()> {
            self.inner.clear()
        }
        fn clear_region(&mut self, t: ratatui::backend::ClearType) -> std::io::Result<()> {
            self.inner.clear_region(t)
        }
        fn size(&self) -> std::io::Result<ratatui::layout::Size> {
            self.inner.size()
        }
        fn window_size(&mut self) -> std::io::Result<ratatui::backend::WindowSize> {
            self.inner.window_size()
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.inner.flush()
        }
    }

    /// `/model` ended the session: opening its picker resized the viewport, which asked the
    /// terminal for the cursor position after the event reader owned stdin. Only the first
    /// viewport may ask.
    #[test]
    fn resizing_the_viewport_never_asks_the_terminal_again() {
        let asked = std::rc::Rc::new(std::cell::Cell::new(0));
        let a = asked.clone();
        let mut s =
            Screen::new(Box::new(move || AsksOnce { inner: TestBackend::new(40, 12), asked: a.clone() }), 2).unwrap();
        s.draw(&LiveView { lines: vec![Line::from("> ")], cursor: Some((2, 0)) }).unwrap();
        s.set_height(9).expect("growing for a picker works");
        s.draw(&LiveView { lines: vec![Line::from("picker"); 9], cursor: None }).unwrap();
        s.set_height(3).expect("and shrinking back");
        s.commit(vec![Line::from("answer")]).unwrap();
        assert_eq!(asked.get(), 1, "only the first viewport asked");
    }

    fn rows(b: &TestBackend) -> Vec<String> {
        let buf = b.buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>().trim_end().into()
            })
            .collect()
    }

    #[test]
    fn commit_wraps_into_scrollback_above_the_viewport() {
        let mut s = Screen::new(Box::new(|| TestBackend::new(10, 6)), 2).unwrap();
        let view = LiveView { lines: vec![Line::from("> input")], cursor: Some((2, 0)) };
        s.draw(&view).unwrap();
        s.commit(vec![Line::from("the quick brown fox"), Line::from("end")]).unwrap();
        // The loop redraws the live region after each commit.
        s.draw(&view).unwrap();
        let r = rows(s.backend());
        // Committed rows are wrapped to the width and sit above the live region.
        let at = r.iter().position(|l| l == "the quick").expect("committed");
        assert_eq!(r[at + 1], "brown fox");
        assert_eq!(r[at + 2], "end");
        assert!(r[at + 3..].iter().any(|l| l == "> input"), "{r:?}");
    }

    #[test]
    fn commit_writes_long_output_in_chunks() {
        let mut s = Screen::new(Box::new(|| TestBackend::new(20, 8)), 1).unwrap();
        let lines: Vec<Line<'static>> = (0..250).map(|i| Line::from(format!("row {i}"))).collect();
        s.commit(lines).unwrap();
        let r = rows(s.backend());
        // The screen keeps the newest rows just above the viewport.
        assert!(r.iter().any(|l| l == "row 249"), "{r:?}");
        assert!(!r.iter().any(|l| l == "row 0"));
    }

    #[test]
    fn history_is_per_directory_and_private() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("state/history.jsonl");
        append_history(&p, "/a", "first").unwrap();
        append_history(&p, "/b", "elsewhere").unwrap();
        append_history(&p, "/a", "multi\nline").unwrap();
        assert_eq!(load_history(&p, "/a"), ["first", "multi\nline"]);
        assert!(load_history(&d.path().join("none"), "/a").is_empty());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
        }
    }

    #[test]
    fn project_files_follow_ignore_rules() {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(d.path().join("src")).unwrap();
        std::fs::create_dir_all(d.path().join("target")).unwrap();
        std::fs::write(d.path().join("src/main.rs"), "").unwrap();
        std::fs::write(d.path().join("target/out"), "").unwrap();
        std::fs::write(d.path().join(".gitignore"), "target/\n").unwrap();
        std::process::Command::new("git").arg("init").arg("-q").current_dir(d.path()).status().ok();
        let mut files = project_files(d.path());
        files.sort();
        assert_eq!(files, ["src/", "src/main.rs"]);
    }

    #[test]
    fn osc52_carries_base64() {
        assert_eq!(osc52("hi"), "\x1b]52;c;aGk=\x07");
    }
}